lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
88c0d7c34aab807f04668df87d0f560913d6e9d3
0
permazen/permazen,tempbottle/jsimpledb,tempbottle/jsimpledb,tempbottle/jsimpledb,permazen/permazen,archiecobbs/jsimpledb,permazen/permazen,archiecobbs/jsimpledb,archiecobbs/jsimpledb
/* * Copyright (C) 2011 Archie L. Cobbs. All rights reserved. * * $Id$ */ /** * Classes supporting automated database schema management. * * <p> * Features include: * <ul> * <li>Automatic initialization of the database schema when the application runs for the first time</li> * <li>Automatic application of database schema updates as needed during each application startup cycle</li> * <li>Automated tracking and constraint-based ordering of schema updates supporting multiple code branches</li> * <li>Integration with <a href="http://www.springframework.org/">Spring</a> allowing simple XML declaration of updates</li> * <li>An <a href="http://ant.apache.org/">ant</a> task that verifies schema update correctness</li> * </ul> * </p> * * <p> * See {@link org.dellroad.stuff.schema.SpringSchemaUpdater} for an example of how to declare your * {@link javax.sql.DataSource DataSource} and associated schema updates in a Spring application context. * </p> * * <p> * Updates may have ordering constraints, and these should be declared explicitly. Once you have done so, then * you may safely "cherry pick" individual schema updates for merging into different code branches without worrying * whether the schema will get messed up, because any ordering constraint violations will be detected automatically. * This verification step is required to detect inconsistencies between the updates and the current code. * </p> * * <p> * See DellRoad Stuff's <a href="/svn/trunk/src/build/macros.xml">ant macros</a> for the {@code schemacheck} * ant macro that can be used to verify that your delcared schema updates, when applied to the original schema, * yield the expected result (which is typically generated automatically by your schema generation tool from * your current code). It is also a good idea to compare your generated shema matches to an expected result * during each build to detect schema changes caused by e.g., inadvertent changes to model classes. * </p> * * <p> * The central classes are {@link org.dellroad.stuff.schema.SchemaUpdater} and * {@link org.dellroad.stuff.schema.SpringSchemaUpdater}. * </p> */ package org.dellroad.stuff.schema;
src/java/org/dellroad/stuff/schema/package-info.java
/* * Copyright (C) 2011 Archie L. Cobbs. All rights reserved. * * $Id$ */ /** * Classes supporting automated database schema management. * * <p> * The central classes are {@link org.dellroad.stuff.schema.SchemaUpdater} and * {@link org.dellroad.stuff.schema.SpringSchemaUpdater}. */ package org.dellroad.stuff.schema;
Add some Javadoc describing how schema updates work.
src/java/org/dellroad/stuff/schema/package-info.java
Add some Javadoc describing how schema updates work.
<ide><path>rc/java/org/dellroad/stuff/schema/package-info.java <ide> * Classes supporting automated database schema management. <ide> * <ide> * <p> <add> * Features include: <add> * <ul> <add> * <li>Automatic initialization of the database schema when the application runs for the first time</li> <add> * <li>Automatic application of database schema updates as needed during each application startup cycle</li> <add> * <li>Automated tracking and constraint-based ordering of schema updates supporting multiple code branches</li> <add> * <li>Integration with <a href="http://www.springframework.org/">Spring</a> allowing simple XML declaration of updates</li> <add> * <li>An <a href="http://ant.apache.org/">ant</a> task that verifies schema update correctness</li> <add> * </ul> <add> * </p> <add> * <add> * <p> <add> * See {@link org.dellroad.stuff.schema.SpringSchemaUpdater} for an example of how to declare your <add> * {@link javax.sql.DataSource DataSource} and associated schema updates in a Spring application context. <add> * </p> <add> * <add> * <p> <add> * Updates may have ordering constraints, and these should be declared explicitly. Once you have done so, then <add> * you may safely "cherry pick" individual schema updates for merging into different code branches without worrying <add> * whether the schema will get messed up, because any ordering constraint violations will be detected automatically. <add> * This verification step is required to detect inconsistencies between the updates and the current code. <add> * </p> <add> * <add> * <p> <add> * See DellRoad Stuff's <a href="/svn/trunk/src/build/macros.xml">ant macros</a> for the {@code schemacheck} <add> * ant macro that can be used to verify that your delcared schema updates, when applied to the original schema, <add> * yield the expected result (which is typically generated automatically by your schema generation tool from <add> * your current code). It is also a good idea to compare your generated shema matches to an expected result <add> * during each build to detect schema changes caused by e.g., inadvertent changes to model classes. <add> * </p> <add> * <add> * <p> <ide> * The central classes are {@link org.dellroad.stuff.schema.SchemaUpdater} and <ide> * {@link org.dellroad.stuff.schema.SpringSchemaUpdater}. <add> * </p> <ide> */ <ide> package org.dellroad.stuff.schema;
Java
apache-2.0
1cb27c9cbca4340d7159abda9934ccdf4eca455f
0
tmaffia/newsapi
package com.thomasmaffia.newsapi.request; import com.thomasmaffia.newsapi.objects.Language; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by tmaffia on 1/9/17. */ public class NewsAPIRequest { private static final Logger logger = LoggerFactory.getLogger(NewsAPIRequest.class); private static final String ARTICLES_URL = "https://newsapi.org/v1/articles"; private static final String SOURCES_URL = "https://newsapi.org/v1/sources"; private static final String USER_AGENT = "Mozilla/5.0"; private HttpURLConnection connection = null; private final String apiKey; public NewsAPIRequest(String apiKey) { this.apiKey = apiKey; } public String getArticles(final String source) { String finalUrl = ARTICLES_URL + "?source=" + source; return execute(finalUrl); } public String getSources(final Language language) { String finalUrl = SOURCES_URL + "?language=" + language.getLanguageCode(); return execute(finalUrl); } private String execute(final String urlString) { try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setRequestProperty("X-Api-Key", apiKey); int responseCode = connection.getResponseCode(); logger.debug("Request at URL: " + urlString); logger.debug("Reponse Code: " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (MalformedURLException e) { logger.error("Malformed URL: " + urlString); logger.error(e.toString()); } catch (IOException e) { logger.error("IOException while opening URL Connection"); logger.error(e.toString()); } return null; } }
src/main/java/com/thomasmaffia/newsapi/request/NewsAPIRequest.java
package com.thomasmaffia.newsapi.request; import com.thomasmaffia.newsapi.objects.Language; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by tmaffia on 1/9/17. */ public class NewsAPIRequest { private static final Logger logger = LoggerFactory.getLogger(NewsAPIRequest.class); private static final String ARTICLES_URL = "https://newsapi.org/v1/articles"; private static final String SOURCES_URL = "https://newsapi.org/v1/sources"; private static final String USER_AGENT = "Mozilla/5.0"; private HttpURLConnection connection = null; private final String apiKey; public NewsAPIRequest(String apiKey) { this.apiKey = apiKey; } public String getArticles(final String source) { String finalUrl = ARTICLES_URL + "?source=" + source + "&apiKey=" + apiKey; return execute(finalUrl); } public String getSources(final Language language) { String finalUrl = SOURCES_URL + "?language=" + language.getLanguageCode() + "&apiKey=" + apiKey; return execute(finalUrl); } private String execute(final String urlString) { try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", USER_AGENT); int responseCode = connection.getResponseCode(); logger.debug("Request at URL: " + urlString); logger.debug("Reponse Code: " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (MalformedURLException e) { logger.error("Malformed URL: " + urlString); logger.error(e.toString()); } catch (IOException e) { logger.error("IOException while opening URL Connection"); logger.error(e.toString()); } return null; } }
modify request to use api key in header property rather than query param
src/main/java/com/thomasmaffia/newsapi/request/NewsAPIRequest.java
modify request to use api key in header property rather than query param
<ide><path>rc/main/java/com/thomasmaffia/newsapi/request/NewsAPIRequest.java <ide> } <ide> <ide> public String getArticles(final String source) { <del> String finalUrl = ARTICLES_URL <del> + "?source=" + source <del> + "&apiKey=" + apiKey; <add> String finalUrl = ARTICLES_URL + "?source=" + source; <ide> return execute(finalUrl); <ide> } <ide> <ide> public String getSources(final Language language) { <del> String finalUrl = SOURCES_URL <del> + "?language=" + language.getLanguageCode() <del> + "&apiKey=" + apiKey; <add> String finalUrl = SOURCES_URL + "?language=" + language.getLanguageCode(); <ide> return execute(finalUrl); <ide> } <ide> <ide> connection = (HttpURLConnection) url.openConnection(); <ide> connection.setRequestMethod("GET"); <ide> connection.setRequestProperty("User-Agent", USER_AGENT); <add> connection.setRequestProperty("X-Api-Key", apiKey); <ide> int responseCode = connection.getResponseCode(); <ide> <ide> logger.debug("Request at URL: " + urlString);
Java
apache-2.0
fd27e3a10407147291670f7ff09e10eb9e5f2c37
0
pumpadump/sweble-wikitext,pumpadump/sweble-wikitext,pumpadump/sweble-wikitext
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sweble.wikitext.engine.utils; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.collections.map.MultiValueMap; import org.sweble.wikitext.engine.config.I18nAliasImpl; import org.sweble.wikitext.engine.config.InterwikiImpl; import org.sweble.wikitext.engine.config.NamespaceImpl; import org.sweble.wikitext.engine.config.WikiConfig; import org.sweble.wikitext.engine.config.WikiConfigImpl; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * @author Samy Ateia, [email protected] * */ public class LanguageConfigGenerator { public static WikiConfig generateWikiConfig(String siteName, String siteURL, String languagePrefix) throws IOException, ParserConfigurationException, SAXException { WikiConfigImpl wikiConfig = new WikiConfigImpl(); wikiConfig.setSiteName(siteName); wikiConfig.setWikiUrl(siteURL); wikiConfig.setContentLang(languagePrefix); wikiConfig.setIwPrefix(languagePrefix); DefaultConfigEnWp config = new DefaultConfigEnWp(); config.configureEngine(wikiConfig); addNamespaces(wikiConfig, wikiConfig.getInterwikiPrefix()); addInterwikis(wikiConfig, wikiConfig.getInterwikiPrefix()); addi18NAliases(wikiConfig, wikiConfig.getInterwikiPrefix()); config.addParserFunctions(wikiConfig); config.addTagExtensions(wikiConfig); return wikiConfig; } public static void addi18NAliases(WikiConfigImpl wikiConfig, String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=magicwords&format=xml"; Document document = getXMLFromUlr(urlString); NodeList apiI18NAliases = document.getElementsByTagName("magicword"); for(int i=0; i< apiI18NAliases.getLength(); i++) { Node apii18NAlias = apiI18NAliases.item(i); NamedNodeMap attributes = apii18NAlias.getAttributes(); String name = attributes.getNamedItem("name").getNodeValue(); boolean iscaseSensitive = false; Node caseSensitive = attributes.getNamedItem("case-sensitive"); if(caseSensitive != null) { iscaseSensitive = true; } Node aliasesNode = apii18NAlias.getFirstChild(); NodeList aliasesList = aliasesNode.getChildNodes(); ArrayList<String> aliases = new ArrayList<String>(); for(int j = 0; j< aliasesList.getLength(); j++) { Node aliasNode = aliasesList.item(j); String aliasString = aliasNode.getTextContent(); aliases.add(aliasString); } I18nAliasImpl I18Alias = new I18nAliasImpl(name, iscaseSensitive, aliases); try{ wikiConfig.addI18nAlias(I18Alias); }catch(Exception e) { //TODO resolve conflicts problem e.printStackTrace(); } } } public static void addInterwikis(WikiConfigImpl wikiConfig, String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=interwikimap&format=xml"; Document document = getXMLFromUlr(urlString); NodeList apiInterwikis = document.getElementsByTagName("iw"); for(int i=0; i< apiInterwikis.getLength(); i++) { Node apiInterWiki = apiInterwikis.item(i); NamedNodeMap attributes = apiInterWiki.getAttributes(); String prefixString = attributes.getNamedItem("prefix").getNodeValue(); //same as prefix in api boolean isLocal = false; //if present set true else false Node localNode = attributes.getNamedItem("local"); if(localNode != null) { isLocal = true; } boolean isTrans = false; //TODO always false? String urlStringApi = attributes.getNamedItem("url").getNodeValue();//same as url in api InterwikiImpl interwiki = new InterwikiImpl(prefixString,urlStringApi,isLocal,isTrans); wikiConfig.addInterwiki(interwiki); } } public static void addNamespaces(WikiConfigImpl wikiConfig, String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespaces&format=xml"; Document document = getXMLFromUlr(urlString); NodeList apiNamespaces = document.getElementsByTagName("ns"); MultiValueMap namespaceAliases = getNamespaceAliases(iwPrefix); for (int i = 0; i < apiNamespaces.getLength(); i++) { Node apiNamespace = apiNamespaces.item(i); String name = apiNamespace.getTextContent(); NamedNodeMap attributes = apiNamespace.getAttributes(); Integer id = new Integer(attributes.getNamedItem("id").getNodeValue()); String canonical = ""; if (attributes.getNamedItem("canonical") != null) { canonical = attributes.getNamedItem("canonical").getNodeValue(); } boolean fileNs = false; if (canonical.equals("File")) { fileNs = true; } Node subpages = attributes.getNamedItem("subpages"); boolean canHaveSubpages = false; if (subpages != null) { canHaveSubpages = true; } Collection<String> aliases = new ArrayList<String>(); if(namespaceAliases.containsKey(id)) { aliases = (Collection<String>) namespaceAliases.getCollection(id); } NamespaceImpl namespace = new NamespaceImpl(id.intValue(), name, canonical, canHaveSubpages, fileNs, aliases); wikiConfig.addNamespace(namespace); if (canonical.equals("Template")) { wikiConfig.setTemplateNamespace(namespace); }else if(id.intValue() == 0) { wikiConfig.setDefaultNamespace(namespace); } } } public static MultiValueMap getNamespaceAliases(String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespacealiases&format=xml"; Document document = getXMLFromUlr(urlString); NodeList namespaceAliasess = document.getElementsByTagName("ns"); MultiValueMap namespaces = new MultiValueMap(); for(int i = 0; i< namespaceAliasess.getLength(); i++) { Node aliasNode = namespaceAliasess.item(i); NamedNodeMap attributes = aliasNode.getAttributes(); Integer id = new Integer(attributes.getNamedItem("id").getNodeValue()); String aliasString = aliasNode.getTextContent(); namespaces.put(id, aliasString); } return namespaces; } public static Document getXMLFromUlr(String urlString) throws IOException, ParserConfigurationException, SAXException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = documentBuilderFactory .newDocumentBuilder(); Document document = docBuilder.parse(connection.getInputStream()); return document; } }
swc-engine/src/main/java/org/sweble/wikitext/engine/utils/LanguageConfigGenerator.java
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sweble.wikitext.engine.utils; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.collections.map.MultiValueMap; import org.sweble.wikitext.engine.config.I18nAliasImpl; import org.sweble.wikitext.engine.config.InterwikiImpl; import org.sweble.wikitext.engine.config.NamespaceImpl; import org.sweble.wikitext.engine.config.WikiConfig; import org.sweble.wikitext.engine.config.WikiConfigImpl; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * @author Samy Ateia, [email protected] * */ public class LanguageConfigGenerator { public static WikiConfig generateWikiConfig(String siteName, String siteURL, String languagePrefix) throws IOException, ParserConfigurationException, SAXException { WikiConfigImpl wikiConfig = new WikiConfigImpl(); wikiConfig.setSiteName(siteName); wikiConfig.setWikiUrl(siteURL); wikiConfig.setContentLang(languagePrefix); wikiConfig.setIwPrefix(languagePrefix); DefaultConfigEnWp config = new DefaultConfigEnWp(); config.configureEngine(wikiConfig); addNamespaces(wikiConfig, wikiConfig.getInterwikiPrefix()); addInterwikis(wikiConfig, wikiConfig.getInterwikiPrefix()); addi18NAliases(wikiConfig, wikiConfig.getInterwikiPrefix()); config.addParserFunctions(wikiConfig); config.addTagExtensions(wikiConfig); return wikiConfig; } public static void addi18NAliases(WikiConfigImpl wikiConfig, String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=magicwords&format=xml"; Document document = getXMLFromUlr(urlString); NodeList apiI18NAliases = document.getElementsByTagName("magicword"); for(int i=0; i< apiI18NAliases.getLength(); i++) { Node apii18NAlias = apiI18NAliases.item(i); NamedNodeMap attributes = apii18NAlias.getAttributes(); String name = attributes.getNamedItem("name").getNodeValue(); boolean iscaseSensitive = false; Node caseSensitive = attributes.getNamedItem("case-sensitive"); if(caseSensitive != null) { iscaseSensitive = true; } Node aliasesNode = apii18NAlias.getFirstChild(); NodeList aliasesList = aliasesNode.getChildNodes(); ArrayList<String> aliases = new ArrayList<String>(); for(int j = 0; j< aliasesList.getLength(); j++) { Node aliasNode = aliasesList.item(j); String aliasString = aliasNode.getTextContent(); aliases.add(aliasString); } I18nAliasImpl I18Alias = new I18nAliasImpl(name, iscaseSensitive, aliases); try{ wikiConfig.addI18nAlias(I18Alias); }catch(Exception e) { //TODO resolve conflicts problem e.printStackTrace(); } } } public static void addInterwikis(WikiConfigImpl wikiConfig, String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=interwikimap&format=xml"; Document document = getXMLFromUlr(urlString); NodeList apiInterwikis = document.getElementsByTagName("iw"); for(int i=0; i< apiInterwikis.getLength(); i++) { Node apiInterWiki = apiInterwikis.item(i); NamedNodeMap attributes = apiInterWiki.getAttributes(); String prefixString = attributes.getNamedItem("prefix").getNodeValue(); //same as prefix in api boolean isLocal = false; //if present set true else false Node localNode = attributes.getNamedItem("local"); if(localNode != null) { isLocal = true; } boolean isTrans = false; //TODO always false? String urlStringApi = attributes.getNamedItem("url").getNodeValue();//same as url in api InterwikiImpl interwiki = new InterwikiImpl(prefixString,urlStringApi,isLocal,isTrans); wikiConfig.addInterwiki(interwiki); } } public static void addNamespaces(WikiConfigImpl wikiConfig, String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespaces&format=xml"; Document document = getXMLFromUlr(urlString); NodeList apiNamespaces = document.getElementsByTagName("ns"); MultiValueMap namespaceAliases = getNamespaceAliases(iwPrefix); for (int i = 0; i < apiNamespaces.getLength(); i++) { Node apiNamespace = apiNamespaces.item(i); String name = apiNamespace.getTextContent(); NamedNodeMap attributes = apiNamespace.getAttributes(); Integer id = new Integer(attributes.getNamedItem("id").getNodeValue()); String canonical = ""; if (attributes.getNamedItem("canonical") != null) { canonical = attributes.getNamedItem("canonical").getNodeValue(); } boolean fileNs = false; if (canonical.equals("File")) { fileNs = true; } Node subpages = attributes.getNamedItem("subpages"); boolean canHaveSubpages = false; if (subpages != null) { canHaveSubpages = true; } Collection<String> aliases = new ArrayList<String>(); if(namespaceAliases.containsKey(id)) { aliases = (Collection<String>) namespaceAliases.getCollection(id); } NamespaceImpl namespace = new NamespaceImpl(id.intValue(), name, canonical, canHaveSubpages, fileNs, aliases); wikiConfig.addNamespace(namespace); if (canonical.equals("Template")) { wikiConfig.setTemplateNamespace(namespace); }else if(id.intValue() == 0) { wikiConfig.setDefaultNamespace(namespace); } } } public static MultiValueMap getNamespaceAliases(String iwPrefix) throws IOException, ParserConfigurationException, SAXException { String urlString = "http://" + iwPrefix + ".wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespacealiases&format=xml"; Document document = getXMLFromUlr(urlString); NodeList namespaceAliasess = document.getElementsByTagName("ns"); MultiValueMap namespaces = new MultiValueMap(); for(int i = 0; i< namespaceAliasess.getLength(); i++) { Node aliasNode = namespaceAliasess.item(i); NamedNodeMap attributes = aliasNode.getAttributes(); Integer id = new Integer(attributes.getNamedItem("id").getNodeValue()); String aliasString = aliasNode.getTextContent(); namespaces.put(id, aliasString); } return namespaces; } public static Document getXMLFromUlr(String urlString) throws IOException, ParserConfigurationException, SAXException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = documentBuilderFactory .newDocumentBuilder(); Document document = docBuilder.parse(connection.getInputStream()); return document; } }
Removed wrong copyright notice from license header.
swc-engine/src/main/java/org/sweble/wikitext/engine/utils/LanguageConfigGenerator.java
Removed wrong copyright notice from license header.
<ide><path>wc-engine/src/main/java/org/sweble/wikitext/engine/utils/LanguageConfigGenerator.java <ide> /** <del> * Copyright 2011 The Open Source Research Group, <del> * University of Erlangen-Nürnberg <del> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at
JavaScript
mit
947e25adde1111a21e7942ec988a04b87c9aea75
0
JohnnyBeGood34/JQuery-AnimateSlider,JohnnyBeGood34/JQuery-AnimateSlider
$(function(){ var screenHeight = $(window).height(); //Height of slider $("#home-slider").css("height",screenHeight); //Height of img group $("#home-slider .image-right").css("height",$("#home-slider").height()); //Height of navigations buttons var heightOfNavButtons = $("#home-slider .nav-arrows").height(), marginNavButtons = screenHeight - (heightOfNavButtons * 3.5); $("#home-slider .nav-arrows").css("margin-top",marginNavButtons); });
exemple/JS/main.js
$(function(){ });
Update main.js
exemple/JS/main.js
Update main.js
<ide><path>xemple/JS/main.js <ide> $(function(){ <del> <add> var screenHeight = $(window).height(); <add> //Height of slider <add> $("#home-slider").css("height",screenHeight); <add> //Height of img group <add> $("#home-slider .image-right").css("height",$("#home-slider").height()); <add> <add> //Height of navigations buttons <add> var heightOfNavButtons = $("#home-slider .nav-arrows").height(), <add> marginNavButtons = screenHeight - (heightOfNavButtons * 3.5); <add> <add> $("#home-slider .nav-arrows").css("margin-top",marginNavButtons); <add> <ide> });
Java
bsd-2-clause
9bbcf30430a64645750e28bcd4a2a8f804ff7b47
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
/* * Copyright (c) 2003-2006 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jmex.hud; import java.net.*; import com.jme.image.*; import com.jme.math.*; import com.jme.scene.shape.*; import com.jme.scene.state.*; import com.jme.system.*; import com.jme.util.*; /** * Gauge180 represents a HUD gauge that can be displayed and display a circular texture on up to * 180 degrees of the screen. * * @author Matthew D. Hicks (original concept by shingoki) */ public class Gauge180 extends Quad { private static final long serialVersionUID = 1L; private Quaternion quat; private Vector3f dir; private int maxValue; private float maxRotation; private boolean allowPositive; private boolean allowNegative; private Texture texture; private Texture clip; public Gauge180(String name, URL textureURL, URL clipURL, int maxValue, float maxRotation, boolean allowPositive, boolean allowNegative) { super(name + "Quad", 400, 400); this.maxValue = maxValue; this.maxRotation = maxRotation; this.allowPositive = allowPositive; this.allowNegative = allowNegative; texture = TextureManager.loadTexture( textureURL, Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1f, true); texture.setWrap(Texture.WM_ECLAMP_S_ECLAMP_T); texture.setEnvironmentalMapMode(Texture.EM_NONE); texture.setApply(Texture.AM_COMBINE); texture.setCombineFuncRGB(Texture.ACF_MODULATE); texture.setCombineFuncAlpha(Texture.ACF_REPLACE); texture.setCombineOp0RGB(Texture.ACO_ONE_MINUS_SRC_ALPHA); texture.setCombineSrc0RGB(Texture.ACS_PREVIOUS); texture.setCombineOp0Alpha(Texture.ACO_SRC_ALPHA); texture.setCombineSrc0Alpha(Texture.ACS_TEXTURE); texture.setCombineOp1Alpha(Texture.ACO_SRC_COLOR); texture.setCombineSrc1Alpha(Texture.ACS_TEXTURE); texture.setCombineOp2RGB(Texture.ACO_SRC_COLOR); texture.setCombineSrc2RGB(Texture.ACS_CONSTANT); texture.setCombineOp2Alpha(Texture.ACO_SRC_COLOR); texture.setCombineSrc2Alpha(Texture.ACS_TEXTURE); clip = TextureManager.loadTexture( clipURL, Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, com.jme.image.Image.GUESS_FORMAT_NO_S3TC, 1f, true); clip.setWrap(Texture.WM_ECLAMP_S_ECLAMP_T); clip.setEnvironmentalMapMode(Texture.EM_NONE); clip.setApply(Texture.AM_MODULATE); TextureState textureState = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); textureState.setCorrection(TextureState.CM_AFFINE); textureState.setEnabled(true); textureState.setTexture(clip, 0); textureState.setTexture(texture, 1); setRenderState(textureState); quat = new Quaternion(); dir = new Vector3f(0.0f, 0.0f, 1.0f); } public void setValue(int value) { if ((value > 0) && (!allowPositive)) value = 0; if ((value < 0) && (!allowNegative)) value = 0; float actual = ((float)value / (float)maxValue) * maxRotation; quat.fromAngleAxis(-actual * FastMath.PI, dir); clip.setRotation(quat); updateRenderState(); } }
src/com/jmex/hud/Gauge180.java
/* * Copyright (c) 2003-2006 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jmex.hud; import com.jme.image.*; import com.jme.math.*; import com.jme.scene.*; import com.jme.scene.shape.*; import com.jme.scene.state.*; import com.jme.system.*; /** * Gauge180 represents a HUD gauge that can be displayed and display a circular texture on up to * 180 degrees of the screen. * * @author Matthew D. Hicks (original concept by shingoki) */ public class Gauge180 extends Node { private static final long serialVersionUID = 1L; private Quad quad; private Quad clipping; private Quaternion quat; private Vector3f dir; private int maxValue; private float maxRotation; private boolean allowPositive; private boolean allowNegative; public Gauge180(String name, Texture texture, Texture clipTexture, int maxValue, float maxRotation, boolean allowPositive, boolean allowNegative) { super(name); quad = new Quad(name + "Quad", 400, 400); this.maxValue = maxValue; this.maxRotation = maxRotation; this.allowPositive = allowPositive; this.allowNegative = allowNegative; TextureState textureState = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); textureState.setEnabled(true); textureState.setTexture(texture); quad.setRenderState(textureState); attachChild(quad); clipping = new Quad(name + "Clipping", 400, 400); TextureState textureStateClip = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); textureStateClip.setEnabled(true); textureStateClip.setTexture(clipTexture); clipping.setRenderState(textureStateClip); attachChild(clipping); quat = new Quaternion(); dir = new Vector3f(0.0f, 0.0f, 1.0f); } public void setValue(int value) { if ((value > 0) && (!allowPositive)) value = 0; if ((value < 0) && (!allowNegative)) value = 0; float actual = ((float)value / (float)maxValue) * maxRotation; quat.fromAngleAxis(-actual * FastMath.PI, dir); clipping.getLocalRotation().set(quat); } }
* Updates to Gauge180 git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@3439 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/com/jmex/hud/Gauge180.java
* Updates to Gauge180
<ide><path>rc/com/jmex/hud/Gauge180.java <ide> */ <ide> package com.jmex.hud; <ide> <add>import java.net.*; <add> <ide> import com.jme.image.*; <ide> import com.jme.math.*; <del>import com.jme.scene.*; <ide> import com.jme.scene.shape.*; <ide> import com.jme.scene.state.*; <ide> import com.jme.system.*; <add>import com.jme.util.*; <ide> <ide> /** <ide> * Gauge180 represents a HUD gauge that can be displayed and display a circular texture on up to <ide> * <ide> * @author Matthew D. Hicks (original concept by shingoki) <ide> */ <del>public class Gauge180 extends Node { <add>public class Gauge180 extends Quad { <ide> private static final long serialVersionUID = 1L; <del> <del> private Quad quad; <del> private Quad clipping; <ide> <ide> private Quaternion quat; <ide> private Vector3f dir; <ide> private float maxRotation; <ide> private boolean allowPositive; <ide> private boolean allowNegative; <add> <add> private Texture texture; <add> private Texture clip; <ide> <del> public Gauge180(String name, Texture texture, Texture clipTexture, int maxValue, float maxRotation, boolean allowPositive, boolean allowNegative) { <del> super(name); <del> quad = new Quad(name + "Quad", 400, 400); <add> public Gauge180(String name, URL textureURL, URL clipURL, int maxValue, float maxRotation, boolean allowPositive, boolean allowNegative) { <add> super(name + "Quad", 400, 400); <ide> this.maxValue = maxValue; <ide> this.maxRotation = maxRotation; <ide> this.allowPositive = allowPositive; <ide> this.allowNegative = allowNegative; <add> <add> texture = TextureManager.loadTexture( <add> textureURL, <add> Texture.MM_LINEAR_LINEAR, <add> Texture.FM_LINEAR, <add> com.jme.image.Image.GUESS_FORMAT_NO_S3TC, <add> 1f, <add> true); <add> texture.setWrap(Texture.WM_ECLAMP_S_ECLAMP_T); <add> texture.setEnvironmentalMapMode(Texture.EM_NONE); <add> texture.setApply(Texture.AM_COMBINE); <add> texture.setCombineFuncRGB(Texture.ACF_MODULATE); <add> texture.setCombineFuncAlpha(Texture.ACF_REPLACE); <add> texture.setCombineOp0RGB(Texture.ACO_ONE_MINUS_SRC_ALPHA); <add> texture.setCombineSrc0RGB(Texture.ACS_PREVIOUS); <add> texture.setCombineOp0Alpha(Texture.ACO_SRC_ALPHA); <add> texture.setCombineSrc0Alpha(Texture.ACS_TEXTURE); <add> texture.setCombineOp1Alpha(Texture.ACO_SRC_COLOR); <add> texture.setCombineSrc1Alpha(Texture.ACS_TEXTURE); <add> texture.setCombineOp2RGB(Texture.ACO_SRC_COLOR); <add> texture.setCombineSrc2RGB(Texture.ACS_CONSTANT); <add> texture.setCombineOp2Alpha(Texture.ACO_SRC_COLOR); <add> texture.setCombineSrc2Alpha(Texture.ACS_TEXTURE); <add> <add> clip = TextureManager.loadTexture( <add> clipURL, <add> Texture.MM_LINEAR_LINEAR, <add> Texture.FM_LINEAR, <add> com.jme.image.Image.GUESS_FORMAT_NO_S3TC, <add> 1f, <add> true); <add> clip.setWrap(Texture.WM_ECLAMP_S_ECLAMP_T); <add> clip.setEnvironmentalMapMode(Texture.EM_NONE); <add> clip.setApply(Texture.AM_MODULATE); <add> <ide> TextureState textureState = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); <add> textureState.setCorrection(TextureState.CM_AFFINE); <ide> textureState.setEnabled(true); <del> textureState.setTexture(texture); <del> quad.setRenderState(textureState); <del> attachChild(quad); <del> <del> clipping = new Quad(name + "Clipping", 400, 400); <del> TextureState textureStateClip = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); <del> textureStateClip.setEnabled(true); <del> textureStateClip.setTexture(clipTexture); <del> clipping.setRenderState(textureStateClip); <del> attachChild(clipping); <add> textureState.setTexture(clip, 0); <add> textureState.setTexture(texture, 1); <add> setRenderState(textureState); <ide> <ide> quat = new Quaternion(); <ide> dir = new Vector3f(0.0f, 0.0f, 1.0f); <ide> if ((value < 0) && (!allowNegative)) value = 0; <ide> float actual = ((float)value / (float)maxValue) * maxRotation; <ide> quat.fromAngleAxis(-actual * FastMath.PI, dir); <del> clipping.getLocalRotation().set(quat); <add> clip.setRotation(quat); <add> updateRenderState(); <ide> } <ide> }
Java
bsd-3-clause
1bb73c3d128bf270be4d69362b97702f95dfb382
0
msf-oca-his/dhis-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis-core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,dhis2/dhis2-core,vietnguyen/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,vietnguyen/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,msf-oca-his/dhis2-core,vietnguyen/dhis2-core,msf-oca-his/dhis-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,vietnguyen/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,msf-oca-his/dhis-core,vietnguyen/dhis2-core,msf-oca-his/dhis-core,hispindia/dhis2-Core
package org.hisp.dhis.webapi.controller.event; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.google.common.collect.Lists; import org.hisp.dhis.common.DhisApiVersion; import org.hisp.dhis.common.OrganisationUnitSelectionMode; import org.hisp.dhis.common.PagerUtils; import org.hisp.dhis.commons.util.StreamUtils; import org.hisp.dhis.commons.util.TextUtils; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.dxf2.events.enrollment.Enrollment; import org.hisp.dhis.dxf2.events.enrollment.EnrollmentService; import org.hisp.dhis.dxf2.events.enrollment.Enrollments; import org.hisp.dhis.dxf2.importsummary.ImportStatus; import org.hisp.dhis.dxf2.importsummary.ImportSummaries; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.hisp.dhis.dxf2.webmessage.WebMessage; import org.hisp.dhis.dxf2.webmessage.WebMessageException; import org.hisp.dhis.dxf2.webmessage.WebMessageUtils; import org.hisp.dhis.fieldfilter.FieldFilterParams; import org.hisp.dhis.fieldfilter.FieldFilterService; import org.hisp.dhis.importexport.ImportStrategy; import org.hisp.dhis.node.NodeUtils; import org.hisp.dhis.node.types.RootNode; import org.hisp.dhis.program.ProgramInstanceQueryParams; import org.hisp.dhis.program.ProgramInstanceService; import org.hisp.dhis.program.ProgramStatus; import org.hisp.dhis.webapi.controller.exception.NotFoundException; import org.hisp.dhis.webapi.mvc.annotation.ApiVersion; import org.hisp.dhis.webapi.service.ContextService; import org.hisp.dhis.webapi.service.WebMessageService; import org.hisp.dhis.webapi.utils.ContextUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author Morten Olav Hansen <[email protected]> */ @Controller @RequestMapping( value = EnrollmentController.RESOURCE_PATH ) @ApiVersion( { DhisApiVersion.DEFAULT, DhisApiVersion.ALL } ) public class EnrollmentController { public static final String RESOURCE_PATH = "/enrollments"; @Autowired private EnrollmentService enrollmentService; @Autowired private ProgramInstanceService programInstanceService; @Autowired protected FieldFilterService fieldFilterService; @Autowired protected ContextService contextService; @Autowired private WebMessageService webMessageService; // ------------------------------------------------------------------------- // READ // ------------------------------------------------------------------------- @RequestMapping( value = "", method = RequestMethod.GET ) public @ResponseBody RootNode getEnrollments( @RequestParam( required = false ) String ou, @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode, @RequestParam( required = false ) String program, @RequestParam( required = false ) ProgramStatus programStatus, @RequestParam( required = false ) Boolean followUp, @RequestParam( required = false ) Date lastUpdated, @RequestParam( required = false ) Date programStartDate, @RequestParam( required = false ) Date programEndDate, @RequestParam( required = false ) String trackedEntityType, @RequestParam( required = false ) String trackedEntityInstance, @RequestParam( required = false ) String enrollment, @RequestParam( required = false ) Integer page, @RequestParam( required = false ) Integer pageSize, @RequestParam( required = false ) boolean totalPages, @RequestParam( required = false ) Boolean skipPaging, @RequestParam( required = false ) Boolean paging ) { List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) ); if ( fields.isEmpty() ) { fields.add( "enrollment,created,lastUpdated,trackedEntityType,trackedEntityInstance,program,status,orgUnit,orgUnitName,enrollmentDate,incidentDate,followup" ); } Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON ); skipPaging = PagerUtils.isSkipPaging( skipPaging, paging ); RootNode rootNode = NodeUtils.createMetadata(); List<Enrollment> listEnrollments; if ( enrollment == null ) { ProgramInstanceQueryParams params = programInstanceService.getFromUrl( orgUnits, ouMode, lastUpdated, program, programStatus, programStartDate, programEndDate, trackedEntityType, trackedEntityInstance, followUp, page, pageSize, totalPages, skipPaging ); Enrollments enrollments = enrollmentService.getEnrollments( params ); if ( enrollments.getPager() != null ) { rootNode.addChild( NodeUtils.createPager( enrollments.getPager() ) ); } listEnrollments = enrollments.getEnrollments(); } else { Set<String> enrollmentIds = TextUtils.splitToArray( enrollment, TextUtils.SEMICOLON ); listEnrollments = enrollmentIds != null ? enrollmentIds.stream().map( enrollmentId -> enrollmentService.getEnrollment( enrollmentId ) ).collect( Collectors.toList() ) : null; } rootNode.addChild( fieldFilterService.toCollectionNode( Enrollment.class, new FieldFilterParams( listEnrollments, fields ) ) ); return rootNode; } @RequestMapping( value = "/{id}", method = RequestMethod.GET ) public @ResponseBody Enrollment getEnrollment( @PathVariable String id, @RequestParam Map<String, String> parameters, Model model ) throws NotFoundException { return getEnrollment( id ); } // ------------------------------------------------------------------------- // CREATE // ------------------------------------------------------------------------- @RequestMapping( value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public void postEnrollmentJson( @RequestParam( defaultValue = "CREATE" ) ImportStrategy strategy, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { importOptions.setStrategy( strategy ); InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummaries importSummaries = enrollmentService.addEnrollmentsJson( inputStream, importOptions ); importSummaries.setImportOptions( importOptions ); response.setContentType( MediaType.APPLICATION_JSON_VALUE ); importSummaries.getImportSummaries().stream() .filter( importSummary -> !importOptions.isDryRun() && !importSummary.getStatus().equals( ImportStatus.ERROR ) && !importOptions.getImportStrategy().isDelete() ) .forEach( importSummary -> importSummary.setHref( ContextUtils.getRootPath( request ) + RESOURCE_PATH + "/" + importSummary.getReference() ) ); if ( importSummaries.getImportSummaries().size() == 1 ) { ImportSummary importSummary = importSummaries.getImportSummaries().get( 0 ); importSummary.setImportOptions( importOptions ); if ( !importSummary.getStatus().equals( ImportStatus.ERROR ) ) { response.setHeader( "Location", getResourcePath( request, importSummary ) ); } } response.setStatus( HttpServletResponse.SC_CREATED ); webMessageService.send( WebMessageUtils.importSummaries( importSummaries ), response, request ); } @RequestMapping( value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE ) public void postEnrollmentXml( @RequestParam( defaultValue = "CREATE" ) ImportStrategy strategy, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { importOptions.setStrategy( strategy ); InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummaries importSummaries = enrollmentService.addEnrollmentsXml( inputStream, importOptions ); importSummaries.setImportOptions( importOptions ); response.setContentType( MediaType.APPLICATION_XML_VALUE ); if ( importSummaries.getImportSummaries().size() == 1 ) { ImportSummary importSummary = importSummaries.getImportSummaries().get( 0 ); importSummary.setImportOptions( importOptions ); if ( !importSummary.getStatus().equals( ImportStatus.ERROR ) ) { response.setHeader( "Location", getResourcePath( request, importSummary ) ); } } response.setStatus( HttpServletResponse.SC_CREATED ); webMessageService.send( WebMessageUtils.importSummaries( importSummaries ), response, request ); } // ------------------------------------------------------------------------- // UPDATE // ------------------------------------------------------------------------- @RequestMapping( value = "/{id}/note", method = RequestMethod.POST, consumes = "application/json" ) public void updateEnrollmentForNoteJson( @PathVariable String id, HttpServletRequest request, HttpServletResponse response ) throws IOException { InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummary importSummary = enrollmentService.updateEnrollmentForNoteJson( id, inputStream ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } @RequestMapping( value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE ) public void updateEnrollmentXml( @PathVariable String id, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummary importSummary = enrollmentService.updateEnrollmentXml( id, inputStream, importOptions ); importSummary.setImportOptions( importOptions ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } @RequestMapping( value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public void updateEnrollmentJson( @PathVariable String id, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummary importSummary = enrollmentService.updateEnrollmentJson( id, inputStream, importOptions ); importSummary.setImportOptions( importOptions ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } @RequestMapping( value = "/{id}/cancelled", method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void cancelEnrollment( @PathVariable String id ) throws NotFoundException, WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.cancelEnrollment( id ); } @RequestMapping( value = "/{id}/completed", method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void completeEnrollment( @PathVariable String id ) throws NotFoundException, WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.completeEnrollment( id ); } @RequestMapping( value = "/{id}/incompleted", method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void incompleteEnrollment( @PathVariable String id ) throws NotFoundException, WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.incompleteEnrollment( id ); } // ------------------------------------------------------------------------- // DELETE // ------------------------------------------------------------------------- @RequestMapping( value = "/{id}", method = RequestMethod.DELETE ) public void deleteEnrollment( @PathVariable String id, HttpServletRequest request, HttpServletResponse response ) throws WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } ImportSummary importSummary = enrollmentService.deleteEnrollment( id ); if ( importSummary.getStatus() == ImportStatus.SUCCESS ) { response.setStatus( HttpServletResponse.SC_OK ); WebMessage webMsg = WebMessageUtils.ok( "Object was deleted successfully" ); webMessageService.send( webMsg, response, request ); } else if ( importSummary.getStatus() == ImportStatus.ERROR ) { response.setStatus( HttpServletResponse.SC_NOT_FOUND ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } } // ------------------------------------------------------------------------- // HELPERS // ------------------------------------------------------------------------- private Enrollment getEnrollment( String id ) throws NotFoundException { Enrollment enrollment = enrollmentService.getEnrollment( id ); if ( enrollment == null ) { throw new NotFoundException( "Enrollment", id ); } return enrollment; } private String getResourcePath( HttpServletRequest request, ImportSummary importSummary ) { return ContextUtils.getContextPath( request ) + "/api/" + "enrollments" + "/" + importSummary.getReference(); } }
dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/event/EnrollmentController.java
package org.hisp.dhis.webapi.controller.event; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.google.common.collect.Lists; import org.hisp.dhis.common.DhisApiVersion; import org.hisp.dhis.common.OrganisationUnitSelectionMode; import org.hisp.dhis.common.PagerUtils; import org.hisp.dhis.commons.util.StreamUtils; import org.hisp.dhis.commons.util.TextUtils; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.dxf2.events.enrollment.Enrollment; import org.hisp.dhis.dxf2.events.enrollment.EnrollmentService; import org.hisp.dhis.dxf2.events.enrollment.Enrollments; import org.hisp.dhis.dxf2.importsummary.ImportStatus; import org.hisp.dhis.dxf2.importsummary.ImportSummaries; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.hisp.dhis.dxf2.webmessage.WebMessage; import org.hisp.dhis.dxf2.webmessage.WebMessageException; import org.hisp.dhis.dxf2.webmessage.WebMessageUtils; import org.hisp.dhis.fieldfilter.FieldFilterParams; import org.hisp.dhis.fieldfilter.FieldFilterService; import org.hisp.dhis.importexport.ImportStrategy; import org.hisp.dhis.node.NodeUtils; import org.hisp.dhis.node.types.RootNode; import org.hisp.dhis.program.ProgramInstanceQueryParams; import org.hisp.dhis.program.ProgramInstanceService; import org.hisp.dhis.program.ProgramStatus; import org.hisp.dhis.webapi.controller.exception.NotFoundException; import org.hisp.dhis.webapi.mvc.annotation.ApiVersion; import org.hisp.dhis.webapi.service.ContextService; import org.hisp.dhis.webapi.service.WebMessageService; import org.hisp.dhis.webapi.utils.ContextUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author Morten Olav Hansen <[email protected]> */ @Controller @RequestMapping( value = EnrollmentController.RESOURCE_PATH ) @ApiVersion( { DhisApiVersion.DEFAULT, DhisApiVersion.ALL } ) public class EnrollmentController { public static final String RESOURCE_PATH = "/enrollments"; @Autowired private EnrollmentService enrollmentService; @Autowired private ProgramInstanceService programInstanceService; @Autowired protected FieldFilterService fieldFilterService; @Autowired protected ContextService contextService; @Autowired private WebMessageService webMessageService; // ------------------------------------------------------------------------- // READ // ------------------------------------------------------------------------- @RequestMapping( value = "", method = RequestMethod.GET ) public @ResponseBody RootNode getEnrollments( @RequestParam( required = false ) String ou, @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode, @RequestParam( required = false ) String program, @RequestParam( required = false ) ProgramStatus programStatus, @RequestParam( required = false ) Boolean followUp, @RequestParam( required = false ) Date lastUpdated, @RequestParam( required = false ) Date programStartDate, @RequestParam( required = false ) Date programEndDate, @RequestParam( required = false ) String trackedEntityType, @RequestParam( required = false ) String trackedEntityInstance, @RequestParam( required = false ) String enrollment, @RequestParam( required = false ) Integer page, @RequestParam( required = false ) Integer pageSize, @RequestParam( required = false ) boolean totalPages, @RequestParam( required = false ) Boolean skipPaging, @RequestParam( required = false ) Boolean paging ) { List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) ); if ( fields.isEmpty() ) { fields.add( "enrollment,created,lastUpdated,trackedEntityType,trackedEntityInstance,program,status,orgUnit,orgUnitName,enrollmentDate,incidentDate,followup" ); } Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON ); skipPaging = PagerUtils.isSkipPaging( skipPaging, paging ); RootNode rootNode = NodeUtils.createMetadata(); List<Enrollment> listEnrollments; if ( enrollment == null ) { ProgramInstanceQueryParams params = programInstanceService.getFromUrl( orgUnits, ouMode, lastUpdated, program, programStatus, programStartDate, programEndDate, trackedEntityType, trackedEntityInstance, followUp, page, pageSize, totalPages, skipPaging ); Enrollments enrollments = enrollmentService.getEnrollments( params ); if ( enrollments.getPager() != null ) { rootNode.addChild( NodeUtils.createPager( enrollments.getPager() ) ); } listEnrollments = enrollments.getEnrollments(); } else { Set<String> enrollmentIds = TextUtils.splitToArray( enrollment, TextUtils.SEMICOLON ); listEnrollments = enrollmentIds != null ? enrollmentIds.stream().map( enrollmentId -> enrollmentService.getEnrollment( enrollmentId ) ).collect( Collectors.toList() ) : null; } rootNode.addChild( fieldFilterService.toCollectionNode( Enrollment.class, new FieldFilterParams( listEnrollments, fields ) ) ); return rootNode; } @RequestMapping( value = "/{id}", method = RequestMethod.GET ) public @ResponseBody Enrollment getEnrollment( @PathVariable String id, @RequestParam Map<String, String> parameters, Model model ) throws NotFoundException { return getEnrollment( id ); } // ------------------------------------------------------------------------- // CREATE // ------------------------------------------------------------------------- @RequestMapping( value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public void postEnrollmentJson( @RequestParam( defaultValue = "CREATE" ) ImportStrategy strategy, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { importOptions.setStrategy( strategy ); InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummaries importSummaries = enrollmentService.addEnrollmentsJson( inputStream, importOptions ); importSummaries.setImportOptions( importOptions ); response.setContentType( MediaType.APPLICATION_JSON_VALUE ); importSummaries.getImportSummaries().stream() .filter( importSummary -> !importOptions.isDryRun() && !importSummary.getStatus().equals( ImportStatus.ERROR ) && !importOptions.getImportStrategy().isDelete() ) .forEach( importSummary -> importSummary.setHref( ContextUtils.getRootPath( request ) + RESOURCE_PATH + "/" + importSummary.getReference() ) ); if ( importSummaries.getImportSummaries().size() == 1 ) { ImportSummary importSummary = importSummaries.getImportSummaries().get( 0 ); importSummary.setImportOptions( importOptions ); if ( !importSummary.getStatus().equals( ImportStatus.ERROR ) ) { response.setHeader( "Location", getResourcePath( request, importSummary ) ); } } response.setStatus( HttpServletResponse.SC_CREATED ); webMessageService.send( WebMessageUtils.importSummaries( importSummaries ), response, request ); } @RequestMapping( value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE ) public void postEnrollmentXml( @RequestParam( defaultValue = "CREATE" ) ImportStrategy strategy, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { importOptions.setStrategy( strategy ); InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummaries importSummaries = enrollmentService.addEnrollmentsXml( inputStream, importOptions ); importSummaries.setImportOptions( importOptions ); response.setContentType( MediaType.APPLICATION_XML_VALUE ); if ( importSummaries.getImportSummaries().size() == 1 ) { ImportSummary importSummary = importSummaries.getImportSummaries().get( 0 ); importSummary.setImportOptions( importOptions ); if ( !importSummary.getStatus().equals( ImportStatus.ERROR ) ) { response.setHeader( "Location", getResourcePath( request, importSummary ) ); } } response.setStatus( HttpServletResponse.SC_CREATED ); webMessageService.send( WebMessageUtils.importSummaries( importSummaries ), response, request ); } // ------------------------------------------------------------------------- // UPDATE // ------------------------------------------------------------------------- @RequestMapping( value = "/{id}/note", method = RequestMethod.POST, consumes = "application/json" ) public void updateEnrollmentForNoteJson( @PathVariable String id, HttpServletRequest request, HttpServletResponse response ) throws IOException { InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummary importSummary = enrollmentService.updateEnrollmentForNoteJson( id, inputStream ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } @RequestMapping( value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE ) public void updateEnrollmentXml( @PathVariable String id, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummary importSummary = enrollmentService.updateEnrollmentXml( id, inputStream, importOptions ); importSummary.setImportOptions( importOptions ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } @RequestMapping( value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public void updateEnrollmentJson( @PathVariable String id, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException { InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() ); ImportSummary importSummary = enrollmentService.updateEnrollmentJson( id, inputStream, importOptions ); importSummary.setImportOptions( importOptions ); webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); } @RequestMapping( value = "/{id}/cancelled", method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void cancelEnrollment( @PathVariable String id ) throws NotFoundException, WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.cancelEnrollment( id ); } @RequestMapping( value = "/{id}/completed", method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void completeEnrollment( @PathVariable String id ) throws NotFoundException, WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.completeEnrollment( id ); } @RequestMapping( value = "/{id}/incompleted", method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void incompleteEnrollment( @PathVariable String id ) throws NotFoundException, WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.incompleteEnrollment( id ); } // ------------------------------------------------------------------------- // DELETE // ------------------------------------------------------------------------- @RequestMapping( value = "/{id}", method = RequestMethod.DELETE ) public void deleteEnrollment( @PathVariable String id, HttpServletRequest request, HttpServletResponse response ) throws WebMessageException { if ( !programInstanceService.programInstanceExists( id ) ) { throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); } enrollmentService.deleteEnrollment( id ); response.setStatus( HttpServletResponse.SC_OK ); WebMessage webMsg = WebMessageUtils.ok( "Object was deleted successfully" ); webMessageService.send( webMsg, response, request ); } // ------------------------------------------------------------------------- // HELPERS // ------------------------------------------------------------------------- private Enrollment getEnrollment( String id ) throws NotFoundException { Enrollment enrollment = enrollmentService.getEnrollment( id ); if ( enrollment == null ) { throw new NotFoundException( "Enrollment", id ); } return enrollment; } private String getResourcePath( HttpServletRequest request, ImportSummary importSummary ) { return ContextUtils.getContextPath( request ) + "/api/" + "enrollments" + "/" + importSummary.getReference(); } }
Fixes delete method to return 404 when there is a fail. - RP229-35 (#1670)
dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/event/EnrollmentController.java
Fixes delete method to return 404 when there is a fail. - RP229-35 (#1670)
<ide><path>his-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/event/EnrollmentController.java <ide> throw new WebMessageException( WebMessageUtils.notFound( "Enrollment not found for ID " + id ) ); <ide> } <ide> <del> enrollmentService.deleteEnrollment( id ); <del> <del> response.setStatus( HttpServletResponse.SC_OK ); <del> WebMessage webMsg = WebMessageUtils.ok( "Object was deleted successfully" ); <del> webMessageService.send( webMsg, response, request ); <add> ImportSummary importSummary = enrollmentService.deleteEnrollment( id ); <add> <add> if ( importSummary.getStatus() == ImportStatus.SUCCESS ) <add> { <add> response.setStatus( HttpServletResponse.SC_OK ); <add> WebMessage webMsg = WebMessageUtils.ok( "Object was deleted successfully" ); <add> webMessageService.send( webMsg, response, request ); <add> } <add> else if ( importSummary.getStatus() == ImportStatus.ERROR ) <add> { <add> response.setStatus( HttpServletResponse.SC_NOT_FOUND ); <add> webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request ); <add> } <ide> } <ide> <ide> // -------------------------------------------------------------------------
JavaScript
mit
262807b5b36ad1e3a54151e0a65d32a46ccf2ace
0
dcfemtech/hackforgood-waba-map,dcfemtech/hackforgood-waba-map
L.mapbox.accessToken = 'pk.eyJ1IjoiYWx1bHNoIiwiYSI6ImY0NDBjYTQ1NjU4OGJmMDFiMWQ1Y2RmYjRlMGI1ZjIzIn0.pngboKEPsfuC4j54XDT3VA'; var map = L.mapbox.map('map', 'mapbox.light', { zoomControl: false }) .setView([38.898, -77.043], 12); new L.Control.Zoom({ position: 'bottomright' }).addTo(map); var dcBufferLayer = L.mapbox.featureLayer().addTo(map); var dcTrailsBufferLayer = L.mapbox.featureLayer().addTo(map); var mocoBufferLayer = L.mapbox.featureLayer().addTo(map); var fairfaxBufferLayer = L.mapbox.featureLayer().addTo(map); var alexBufferLayer = L.mapbox.featureLayer().addTo(map); var arlingtonBufferLayer = L.mapbox.featureLayer().addTo(map); var dcBikeLanes = L.mapbox.featureLayer().addTo(map); var dcBikeTrails = L.mapbox.featureLayer().addTo(map); var mocoBikeLanes = L.mapbox.featureLayer().addTo(map); var alexBikeTrails = L.mapbox.featureLayer().addTo(map); var arlingtonBikeTrails = L.mapbox.featureLayer().addTo(map); var fairfaxBikeLanes = L.mapbox.featureLayer().addTo(map); var geocoder = L.mapbox.geocoderControl('mapbox.places') geocoder.setPosition('topright') map.addControl(geocoder); var search_marker geocoder.on('select', function(e){ // close the address selection dropdown and add a marker if(search_marker){ map.removeLayer(search_marker) } this._closeIfOpen() search_marker = L.marker(e.feature.center.reverse()); search_marker.bindPopup(e.feature.place_name); search_marker.addTo(map); }) dcBikeLanes.loadURL('./data/DC_Bike_Lanes.geojson') .on('ready', done); dcBikeTrails.loadURL('./data/DC_Bike_Trails.geojson') .on('ready', done); mocoBikeLanes.loadURL('./data/MD_MontgomeryCounty_Bike.geojson') .on('ready', done); fairfaxBikeLanes.loadURL('./data/VA_FairfaxCounty_Bike.geojson') .on('ready', done); alexBikeTrails.loadURL('./data/VA_Alexandria_Bike.geojson') .on('ready', done); arlingtonBikeTrails.loadURL('./data/VA_Arlington_Bike.geojson') .on('ready', done); // styles and color paletter for map var bikeLaneStyle = { color: 'green', weight: 2 }; var bufferStyle = { "fill": "#56B6DB", "stroke": "#1A3742", "stroke-width": 2 }; // Each buffer feature object needs to have the properties set individually function setProperties (buffer) { for (var i = 0; i < buffer.features.length; i++) { buffer.features[i].properties = bufferStyle; } } function done(e) { var BikeLanes = e.target; BikeLanes.setStyle(bikeLaneStyle); function run() { var radius = parseInt(document.getElementById('radius').value); if (isNaN(radius)) radius = 500; var buffer = turf.buffer(BikeLanes.getGeoJSON(), radius / 5280, 'miles'); // Each buffer feature object needs to have the properties set individually setProperties(buffer); BikeLanes.setGeoJSON(buffer); } run(); document.getElementById('radius').onchange = run; }
site.js
L.mapbox.accessToken = 'pk.eyJ1IjoiYWx1bHNoIiwiYSI6ImY0NDBjYTQ1NjU4OGJmMDFiMWQ1Y2RmYjRlMGI1ZjIzIn0.pngboKEPsfuC4j54XDT3VA'; var map = L.mapbox.map('map', 'mapbox.light', { zoomControl: false }) .setView([38.898, -77.043], 12); new L.Control.Zoom({ position: 'bottomright' }).addTo(map); var dcBufferLayer = L.mapbox.featureLayer().addTo(map); var dcTrailsBufferLayer = L.mapbox.featureLayer().addTo(map); var mocoBufferLayer = L.mapbox.featureLayer().addTo(map); var fairfaxBufferLayer = L.mapbox.featureLayer().addTo(map); var alexBufferLayer = L.mapbox.featureLayer().addTo(map); var arlingtonBufferLayer = L.mapbox.featureLayer().addTo(map); var dcBikeLanes = L.mapbox.featureLayer().addTo(map); var dcBikeTrails = L.mapbox.featureLayer().addTo(map); var mocoBikeLanes = L.mapbox.featureLayer().addTo(map); var alexBikeTrails = L.mapbox.featureLayer().addTo(map); var arlingtonBikeTrails = L.mapbox.featureLayer().addTo(map); var fairfaxBikeLanes = L.mapbox.featureLayer().addTo(map); var geocoder = L.mapbox.geocoderControl('mapbox.places') geocoder.setPosition('topright') map.addControl(geocoder); geocoder.on('select', function(e){ // close the address selection dropdown and add a marker this._closeIfOpen() marker = L.marker(e.feature.center.reverse()); marker.bindPopup(e.feature.place_name); marker.addTo(map); }) dcBikeLanes.loadURL('./data/DC_Bike_Lanes.geojson') .on('ready', done); dcBikeTrails.loadURL('./data/DC_Bike_Trails.geojson') .on('ready', done); mocoBikeLanes.loadURL('./data/MD_MontgomeryCounty_Bike.geojson') .on('ready', done); fairfaxBikeLanes.loadURL('./data/VA_FairfaxCounty_Bike.geojson') .on('ready', done); alexBikeTrails.loadURL('./data/VA_Alexandria_Bike.geojson') .on('ready', done); arlingtonBikeTrails.loadURL('./data/VA_Arlington_Bike.geojson') .on('ready', done); // styles and color paletter for map var bikeLaneStyle = { color: 'green', weight: 2 }; var bufferStyle = { "fill": "#56B6DB", "stroke": "#1A3742", "stroke-width": 2 }; // Each buffer feature object needs to have the properties set individually function setProperties (buffer) { for (var i = 0; i < buffer.features.length; i++) { buffer.features[i].properties = bufferStyle; } } function done(e) { var BikeLanes = e.target; BikeLanes.setStyle(bikeLaneStyle); function run() { var radius = parseInt(document.getElementById('radius').value); if (isNaN(radius)) radius = 500; var buffer = turf.buffer(BikeLanes.getGeoJSON(), radius / 5280, 'miles'); // Each buffer feature object needs to have the properties set individually setProperties(buffer); BikeLanes.setGeoJSON(buffer); } run(); document.getElementById('radius').onchange = run; }
Fixes #25: delete old seatch marker when doing adding the new search marker
site.js
Fixes #25: delete old seatch marker when doing adding the new search marker
<ide><path>ite.js <ide> geocoder.setPosition('topright') <ide> map.addControl(geocoder); <ide> <add>var search_marker <ide> geocoder.on('select', function(e){ <ide> // close the address selection dropdown and add a marker <add> if(search_marker){ <add> map.removeLayer(search_marker) <add> } <ide> this._closeIfOpen() <del> marker = L.marker(e.feature.center.reverse()); <del> marker.bindPopup(e.feature.place_name); <del> marker.addTo(map); <add> search_marker = L.marker(e.feature.center.reverse()); <add> search_marker.bindPopup(e.feature.place_name); <add> search_marker.addTo(map); <ide> }) <ide> <ide> dcBikeLanes.loadURL('./data/DC_Bike_Lanes.geojson')
Java
apache-2.0
ed59fd7fddc244d05ff31c3a0bbe96e45d66635e
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.android.view; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Hashtable; import java.util.Vector; import org.commcare.android.models.AsyncEntity; import org.commcare.android.models.Entity; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.graph.GraphData; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.odk.collect.android.views.media.AudioButton; import org.odk.collect.android.views.media.AudioController; import org.odk.collect.android.views.media.ViewId; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.speech.tts.TextToSpeech; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.BackgroundColorSpan; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * @author ctsims * */ public class EntityView extends LinearLayout { private View[] views; private String[] forms; private TextToSpeech tts; private String[] searchTerms; private Context context; private AudioController controller; private Hashtable<Integer, Hashtable<Integer, View>> renderedGraphsCache; // index => { orientation => GraphView } private long rowId; public static final String FORM_AUDIO = "audio"; public static final String FORM_IMAGE = "image"; public static final String FORM_GRAPH = "graph"; private boolean mFuzzySearchEnabled = true; private boolean mIsAsynchronous = false; /* * Constructor for row/column contents */ public EntityView(Context context, Detail d, Entity e, TextToSpeech tts, String[] searchTerms, AudioController controller, long rowId, boolean mFuzzySearchEnabled) { super(context); this.context = context; //this is bad :( mIsAsynchronous = e instanceof AsyncEntity; this.searchTerms = searchTerms; this.tts = tts; this.setWeightSum(1); this.controller = controller; this.renderedGraphsCache = new Hashtable<Integer, Hashtable<Integer, View>>(); this.rowId = rowId; views = new View[e.getNumFields()]; forms = d.getTemplateForms(); float[] weights = calculateDetailWeights(d.getTemplateSizeHints()); for (int i = 0; i < views.length; ++i) { if (weights[i] != 0) { Object uniqueId = new ViewId(rowId, i, false); views[i] = initView(e.getField(i), forms[i], uniqueId, e.getSortField(i)); views[i].setId(i); } } refreshViewsForNewEntity(e, false, rowId); for (int i = 0; i < views.length; i++) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, weights[i]); if (views[i] != null) { addView(views[i], l); } } this.mFuzzySearchEnabled = mFuzzySearchEnabled; } /* * Constructor for row/column headers */ public EntityView(Context context, Detail d, String[] headerText) { super(context); this.context = context; this.setWeightSum(1); views = new View[headerText.length]; float[] lengths = calculateDetailWeights(d.getHeaderSizeHints()); String[] headerForms = d.getHeaderForms(); for (int i = 0 ; i < views.length ; ++i) { if (lengths[i] != 0) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, lengths[i]); ViewId uniqueId = new ViewId(rowId, i, false); views[i] = initView(headerText[i], headerForms[i], uniqueId, null); views[i].setId(i); addView(views[i], l); } } } /* * Creates up a new view in the view with ID uniqueid, based upon * the entity's text and form */ private View initView(Object data, String form, Object uniqueId, String sortField) { View retVal; if (FORM_IMAGE.equals(form)) { ImageView iv = (ImageView)View.inflate(context, R.layout.entity_item_image, null); retVal = iv; } else if (FORM_AUDIO.equals(form)) { String text = (String) data; AudioButton b; if (text != null & text.length() > 0) { b = new AudioButton(context, text, uniqueId, controller, true); } else { b = new AudioButton(context, text, uniqueId, controller, false); } retVal = b; } else if (FORM_GRAPH.equals(form) && data instanceof GraphData) { View layout = View.inflate(context, R.layout.entity_item_graph, null); retVal = layout; } else { View layout = View.inflate(context, R.layout.component_audio_text, null); setupTextAndTTSLayout(layout, (String) data, sortField); retVal = layout; } return retVal; } public void setSearchTerms(String[] terms) { this.searchTerms = terms; } public void refreshViewsForNewEntity(Entity e, boolean currentlySelected, long rowId) { for (int i = 0; i < e.getNumFields() ; ++i) { Object field = e.getField(i); View view = views[i]; String form = forms[i]; if (view == null) { continue; } if (FORM_AUDIO.equals(form)) { ViewId uniqueId = new ViewId(rowId, i, false); setupAudioLayout(view, (String) field, uniqueId); } else if(FORM_IMAGE.equals(form)) { setupImageLayout(view, (String) field); } else if (FORM_GRAPH.equals(form) && field instanceof GraphData) { int orientation = getResources().getConfiguration().orientation; GraphView g = new GraphView(context, ""); View rendered = null; if (renderedGraphsCache.get(i) != null) { rendered = renderedGraphsCache.get(i).get(orientation); } else { renderedGraphsCache.put(i, new Hashtable<Integer, View>()); } if (rendered == null) { rendered = g.getView((GraphData) field); renderedGraphsCache.get(i).put(orientation, rendered); } ((LinearLayout) view).removeAllViews(); ((LinearLayout) view).addView(rendered, g.getLayoutParams()); view.setVisibility(VISIBLE); } else { //text to speech setupTextAndTTSLayout(view, (String) field, e.getSortField(i)); } } if (currentlySelected) { this.setBackgroundResource(R.drawable.grey_bordered_box); } else { this.setBackgroundDrawable(null); } } /* * Updates the AudioButton layout that is passed in, based on the * new id and source */ private void setupAudioLayout(View layout, String source, ViewId uniqueId) { AudioButton b = (AudioButton)layout; if (source != null && source.length() > 0) { b.modifyButtonForNewView(uniqueId, source, true); } else { b.modifyButtonForNewView(uniqueId, source, false); } } /* * Updates the text layout that is passed in, based on the new text */ private void setupTextAndTTSLayout(View layout, final String text, String searchField) { TextView tv = (TextView)layout.findViewById(R.id.component_audio_text_txt); tv.setVisibility(View.VISIBLE); tv.setText(highlightSearches(this.getContext(), searchTerms, new SpannableString(text == null ? "" : text), searchField, mFuzzySearchEnabled, mIsAsynchronous)); ImageButton btn = (ImageButton)layout.findViewById(R.id.component_audio_text_btn_audio); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener(){ /* * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { String textToRead = text; tts.speak(textToRead, TextToSpeech.QUEUE_FLUSH, null); } }); if (tts == null || text == null || text.equals("")) { btn.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = 0; btn.setLayoutParams(params); } else { btn.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = LayoutParams.WRAP_CONTENT; btn.setLayoutParams(params); } } /* * Updates the ImageView layout that is passed in, based on the * new id and source */ public void setupImageLayout(View layout, final String source) { ImageView iv = (ImageView) layout; Bitmap b; if (!source.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(source).getStream()); if (b == null) { //Input stream could not be used to derive bitmap, so showing error-indicating image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException ex) { ex.printStackTrace(); //Error loading image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } catch (InvalidReferenceException ex) { ex.printStackTrace(); //No image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { iv.setImageDrawable(getResources().getDrawable(R.color.white)); } } //TODO: This method now really does two different things and should possibly be different //methods. /** * Based on the search terms provided, highlight the aspects of the spannable provided which * match. A background string can be provided which provides the exact data that is being * matched. * * @param context * @param searchTerms * @param raw * @param backgroundString * @param fuzzySearchEnabled * @param strictMode * @return */ public static Spannable highlightSearches(Context context, String[] searchTerms, Spannable raw, String backgroundString, boolean fuzzySearchEnabled, boolean strictMode) { if (searchTerms == null) { return raw; } try { //TOOD: Only do this if we're in strict mode if(strictMode) { if(backgroundString == null) { return raw; } //make sure that we have the same consistency for our background match backgroundString = StringUtils.normalize(backgroundString).trim(); } else { //Otherwise we basically want to treat the "Search" string and the display string //the same way. backgroundString = StringUtils.normalize(raw.toString()); } String normalizedDisplayString = StringUtils.normalize(raw.toString()); removeSpans(raw); Vector<int[]> matches = new Vector<int[]>(); //Highlight direct substring matches for (String searchText : searchTerms) { if ("".equals(searchText)) { continue; } //TODO: Assuming here that our background string exists and //isn't null due to the background string check above //check to see where we should start displaying this chunk int offset = TextUtils.indexOf(normalizedDisplayString, backgroundString); if (offset == -1) { //We can't safely highlight any of this, due to this field not actually //containing the same string we're searching by. continue; } int index = backgroundString.indexOf(searchText); //int index = TextUtils.indexOf(normalizedDisplayString, searchText); while (index >= 0) { //grab the display offset for actually displaying things int displayIndex = index + offset; raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.yellow)), displayIndex, displayIndex + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); matches.add(new int[]{index, index + searchText.length()}); //index=TextUtils.indexOf(raw, searchText, index + searchText.length()); index = backgroundString.indexOf(searchText, index + searchText.length()); //we have a non-fuzzy match, so make sure we don't fuck with it } } //now insert the spans for any fuzzy matches (if enabled) if (fuzzySearchEnabled && backgroundString != null) { backgroundString += " "; for (String searchText : searchTerms) { if ("".equals(searchText)) { continue; } int curStart = 0; int curEnd = backgroundString.indexOf(" ", curStart); while (curEnd != -1) { boolean skip = matches.size() != 0; //See whether the fuzzy match overlaps at all with the concrete matches for (int[] textMatch : matches) { if (curStart < textMatch[0] && curEnd <= textMatch[0]) { skip = false; } else if (curStart >= textMatch[1] && curEnd > textMatch[1]) { skip = false; } else { //We're definitely inside of this span, so //don't do any fuzzy matching! skip = true; break; } } if (!skip) { //Walk the string to find words that are fuzzy matched String currentSpan = backgroundString.substring(curStart, curEnd); //First, figure out where we should be matching (if we don't //have anywhere to match, that means there's nothing to display //anyway) int indexInDisplay = normalizedDisplayString.indexOf(currentSpan); int length = (curEnd - curStart); if (indexInDisplay != -1 && StringUtils.fuzzyMatch(currentSpan, searchText).first) { raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.green)), indexInDisplay, indexInDisplay + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } curStart = curEnd + 1; curEnd = backgroundString.indexOf(" ", curStart); } } } } catch (Exception excp){ removeSpans(raw); StringWriter sw = new StringWriter(); excp.printStackTrace(new PrintWriter(sw)); Logger.log("search-hl", excp.toString() + " " + sw.toString()); } return raw; } /** * Removes all background color spans from the Spannable * @param raw Spannable to remove background colors from */ private static void removeSpans(Spannable raw) { //Zero out the existing spans BackgroundColorSpan[] spans=raw.getSpans(0,raw.length(), BackgroundColorSpan.class); for (BackgroundColorSpan span : spans) { raw.removeSpan(span); } } private float[] calculateDetailWeights(int[] hints) { float[] weights = new float[hints.length]; int fullSize = 100; int sharedBetween = 0; for(int hint : hints) { if(hint != -1) { fullSize -= hint; } else { sharedBetween ++; } } double average = ((double)fullSize) / (double)sharedBetween; for(int i = 0; i < hints.length; ++i) { int hint = hints[i]; weights[i] = hint == -1? (float)(average/100.0) : (float)(((double)hint)/100.0); } return weights; } }
app/src/org/commcare/android/view/EntityView.java
package org.commcare.android.view; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import org.commcare.android.models.AsyncEntity; import org.commcare.android.models.Entity; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.graph.GraphData; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.odk.collect.android.views.media.AudioButton; import org.odk.collect.android.views.media.AudioController; import org.odk.collect.android.views.media.ViewId; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.speech.tts.TextToSpeech; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.BackgroundColorSpan; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * @author ctsims * */ public class EntityView extends LinearLayout { private View[] views; private String[] forms; private TextToSpeech tts; private String[] searchTerms; private Context context; private AudioController controller; private Hashtable<Integer, Hashtable<Integer, View>> renderedGraphsCache; // index => { orientation => GraphView } private long rowId; public static final String FORM_AUDIO = "audio"; public static final String FORM_IMAGE = "image"; public static final String FORM_GRAPH = "graph"; private boolean mFuzzySearchEnabled = true; private boolean mIsAsynchronous = false; /* * Constructor for row/column contents */ public EntityView(Context context, Detail d, Entity e, TextToSpeech tts, String[] searchTerms, AudioController controller, long rowId, boolean mFuzzySearchEnabled) { super(context); this.context = context; //this is bad :( mIsAsynchronous = e instanceof AsyncEntity; this.searchTerms = searchTerms; this.tts = tts; this.setWeightSum(1); this.controller = controller; this.renderedGraphsCache = new Hashtable<Integer, Hashtable<Integer, View>>(); this.rowId = rowId; views = new View[e.getNumFields()]; forms = d.getTemplateForms(); float[] weights = calculateDetailWeights(d.getTemplateSizeHints()); for (int i = 0; i < views.length; ++i) { if (weights[i] != 0) { Object uniqueId = new ViewId(rowId, i, false); views[i] = initView(e.getField(i), forms[i], uniqueId, e.getSortField(i)); views[i].setId(i); } } refreshViewsForNewEntity(e, false, rowId); for (int i = 0; i < views.length; i++) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, weights[i]); if (views[i] != null) { addView(views[i], l); } } this.mFuzzySearchEnabled = mFuzzySearchEnabled; } /* * Constructor for row/column headers */ public EntityView(Context context, Detail d, String[] headerText) { super(context); this.context = context; this.setWeightSum(1); views = new View[headerText.length]; float[] lengths = calculateDetailWeights(d.getHeaderSizeHints()); String[] headerForms = d.getHeaderForms(); for (int i = 0 ; i < views.length ; ++i) { if (lengths[i] != 0) { LayoutParams l = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, lengths[i]); ViewId uniqueId = new ViewId(rowId, i, false); views[i] = initView(headerText[i], headerForms[i], uniqueId, null); views[i].setId(i); addView(views[i], l); } } } /* * Creates up a new view in the view with ID uniqueid, based upon * the entity's text and form */ private View initView(Object data, String form, Object uniqueId, String sortField) { View retVal; if (FORM_IMAGE.equals(form)) { ImageView iv = (ImageView)View.inflate(context, R.layout.entity_item_image, null); retVal = iv; } else if (FORM_AUDIO.equals(form)) { String text = (String) data; AudioButton b; if (text != null & text.length() > 0) { b = new AudioButton(context, text, uniqueId, controller, true); } else { b = new AudioButton(context, text, uniqueId, controller, false); } retVal = b; } else if (FORM_GRAPH.equals(form) && data instanceof GraphData) { View layout = View.inflate(context, R.layout.entity_item_graph, null); retVal = layout; } else { View layout = View.inflate(context, R.layout.component_audio_text, null); setupTextAndTTSLayout(layout, (String) data, sortField); retVal = layout; } return retVal; } public void setSearchTerms(String[] terms) { this.searchTerms = terms; } public void refreshViewsForNewEntity(Entity e, boolean currentlySelected, long rowId) { for (int i = 0; i < e.getNumFields() ; ++i) { Object field = e.getField(i); View view = views[i]; String form = forms[i]; if (view == null) { continue; } if (FORM_AUDIO.equals(form)) { ViewId uniqueId = new ViewId(rowId, i, false); setupAudioLayout(view, (String) field, uniqueId); } else if(FORM_IMAGE.equals(form)) { setupImageLayout(view, (String) field); } else if (FORM_GRAPH.equals(form) && field instanceof GraphData) { int orientation = getResources().getConfiguration().orientation; GraphView g = new GraphView(context, ""); View rendered = null; if (renderedGraphsCache.get(i) != null) { rendered = renderedGraphsCache.get(i).get(orientation); } else { renderedGraphsCache.put(i, new Hashtable<Integer, View>()); } if (rendered == null) { rendered = g.getView((GraphData) field); renderedGraphsCache.get(i).put(orientation, rendered); } ((LinearLayout) view).removeAllViews(); ((LinearLayout) view).addView(rendered, g.getLayoutParams()); view.setVisibility(VISIBLE); } else { //text to speech setupTextAndTTSLayout(view, (String) field, e.getSortField(i)); } } if (currentlySelected) { this.setBackgroundResource(R.drawable.grey_bordered_box); } else { this.setBackgroundDrawable(null); } } /* * Updates the AudioButton layout that is passed in, based on the * new id and source */ private void setupAudioLayout(View layout, String source, ViewId uniqueId) { AudioButton b = (AudioButton)layout; if (source != null && source.length() > 0) { b.modifyButtonForNewView(uniqueId, source, true); } else { b.modifyButtonForNewView(uniqueId, source, false); } } /* * Updates the text layout that is passed in, based on the new text */ private void setupTextAndTTSLayout(View layout, final String text, String searchField) { TextView tv = (TextView)layout.findViewById(R.id.component_audio_text_txt); tv.setVisibility(View.VISIBLE); tv.setText(highlightSearches(this.getContext(), searchTerms, new SpannableString(text == null ? "" : text), searchField, mFuzzySearchEnabled, mIsAsynchronous)); ImageButton btn = (ImageButton)layout.findViewById(R.id.component_audio_text_btn_audio); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener(){ /* * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { String textToRead = text; tts.speak(textToRead, TextToSpeech.QUEUE_FLUSH, null); } }); if (tts == null || text == null || text.equals("")) { btn.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = 0; btn.setLayoutParams(params); } else { btn.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = LayoutParams.WRAP_CONTENT; btn.setLayoutParams(params); } } /* * Updates the ImageView layout that is passed in, based on the * new id and source */ public void setupImageLayout(View layout, final String source) { ImageView iv = (ImageView) layout; Bitmap b; if (!source.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(source).getStream()); if (b == null) { //Input stream could not be used to derive bitmap, so showing error-indicating image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException ex) { ex.printStackTrace(); //Error loading image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } catch (InvalidReferenceException ex) { ex.printStackTrace(); //No image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { iv.setImageDrawable(getResources().getDrawable(R.color.white)); } } //TODO: This method now really does two different things and should possibly be different //methods. /** * Based on the search terms provided, highlight the aspects of the spannable provided which * match. A background string can be provided which provides the exact data that is being * matched. * * @param context * @param searchTerms * @param raw * @param backgroundString * @param fuzzySearchEnabled * @param strictMode * @return */ public static Spannable highlightSearches(Context context, String[] searchTerms, Spannable raw, String backgroundString, boolean fuzzySearchEnabled, boolean strictMode) { if (searchTerms == null) { return raw; } //TOOD: Only do this if we're in strict mode if(strictMode) { if(backgroundString == null) { return raw; } //make sure that we have the same consistency for our background match backgroundString = StringUtils.normalize(backgroundString).trim(); } else { //Otherwise we basically want to treat the "Search" string and the display string //the same way. backgroundString = StringUtils.normalize(raw.toString()); } String normalizedDisplayString = StringUtils.normalize(raw.toString()); //Zero out the existing spans BackgroundColorSpan[] spans=raw.getSpans(0,raw.length(), BackgroundColorSpan.class); for (BackgroundColorSpan span : spans) { raw.removeSpan(span); } Vector<int[]> matches = new Vector<int[]>(); //Highlight direct substring matches for (String searchText : searchTerms) { if ("".equals(searchText)) { continue;} //TODO: Assuming here that our background string exists and //isn't null due to the background string check above //check to see where we should start displaying this chunk int offset = TextUtils.indexOf(normalizedDisplayString, backgroundString); if(offset == -1) { //We can't safely highlight any of this, due to this field not actually //containing the same string we're searching by. continue; } int index = backgroundString.indexOf(searchText); //int index = TextUtils.indexOf(normalizedDisplayString, searchText); while (index >= 0) { //grab the display offset for actually displaying things int displayIndex = index + offset; raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.yellow)), displayIndex, displayIndex + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); matches.add(new int[] {index, index + searchText.length() } ); //index=TextUtils.indexOf(raw, searchText, index + searchText.length()); index = backgroundString.indexOf(searchText, index + searchText.length()); //we have a non-fuzzy match, so make sure we don't fuck with it } } //now insert the spans for any fuzzy matches (if enabled) if(fuzzySearchEnabled && backgroundString != null) { backgroundString += " "; for (String searchText : searchTerms) { if ("".equals(searchText)) { continue;} int curStart = 0; int curEnd = backgroundString.indexOf(" ", curStart); while(curEnd != -1) { boolean skip = matches.size() != 0; //See whether the fuzzy match overlaps at all with the concrete matches for(int[] textMatch : matches) { if(curStart < textMatch[0] && curEnd <= textMatch[0]) { skip = false; } else if(curStart >= textMatch[1] && curEnd > textMatch[1]) { skip = false; } else { //We're definitely inside of this span, so //don't do any fuzzy matching! skip = true; break; } } if(!skip) { //Walk the string to find words that are fuzzy matched String currentSpan = backgroundString.substring(curStart, curEnd); //First, figure out where we should be matching (if we don't //have anywhere to match, that means there's nothing to display //anyway) int indexInDisplay = normalizedDisplayString.indexOf(currentSpan); int length = (curEnd - curStart); if(indexInDisplay != -1 && StringUtils.fuzzyMatch(currentSpan, searchText).first) { raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.green)), indexInDisplay, indexInDisplay + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } curStart = curEnd + 1; curEnd = backgroundString.indexOf(" ", curStart); } } } return raw; } private float[] calculateDetailWeights(int[] hints) { float[] weights = new float[hints.length]; int fullSize = 100; int sharedBetween = 0; for(int hint : hints) { if(hint != -1) { fullSize -= hint; } else { sharedBetween ++; } } double average = ((double)fullSize) / (double)sharedBetween; for(int i = 0; i < hints.length; ++i) { int hint = hints[i]; weights[i] = hint == -1? (float)(average/100.0) : (float)(((double)hint)/100.0); } return weights; } }
Ensuring a crash in search highlight code will not break the app.
app/src/org/commcare/android/view/EntityView.java
Ensuring a crash in search highlight code will not break the app.
<ide><path>pp/src/org/commcare/android/view/EntityView.java <ide> package org.commcare.android.view; <ide> <ide> import java.io.IOException; <add>import java.io.PrintWriter; <add>import java.io.StringWriter; <ide> import java.util.Hashtable; <ide> import java.util.Vector; <ide> <ide> import org.commcare.suite.model.graph.GraphData; <ide> import org.javarosa.core.reference.InvalidReferenceException; <ide> import org.javarosa.core.reference.ReferenceManager; <add>import org.javarosa.core.services.Logger; <ide> import org.odk.collect.android.views.media.AudioButton; <ide> import org.odk.collect.android.views.media.AudioController; <ide> import org.odk.collect.android.views.media.ViewId; <ide> if (searchTerms == null) { <ide> return raw; <ide> } <del> <del> //TOOD: Only do this if we're in strict mode <del> if(strictMode) { <del> if(backgroundString == null) { <del> return raw; <del> } <del> <del> //make sure that we have the same consistency for our background match <del> backgroundString = StringUtils.normalize(backgroundString).trim(); <del> } else { <del> //Otherwise we basically want to treat the "Search" string and the display string <del> //the same way. <del> backgroundString = StringUtils.normalize(raw.toString()); <del> } <del> <del> String normalizedDisplayString = StringUtils.normalize(raw.toString()); <del> <add> <add> try { <add> //TOOD: Only do this if we're in strict mode <add> if(strictMode) { <add> if(backgroundString == null) { <add> return raw; <add> } <add> <add> //make sure that we have the same consistency for our background match <add> backgroundString = StringUtils.normalize(backgroundString).trim(); <add> } else { <add> //Otherwise we basically want to treat the "Search" string and the display string <add> //the same way. <add> backgroundString = StringUtils.normalize(raw.toString()); <add> } <add> <add> String normalizedDisplayString = StringUtils.normalize(raw.toString()); <add> <add> removeSpans(raw); <add> <add> Vector<int[]> matches = new Vector<int[]>(); <add> <add> //Highlight direct substring matches <add> for (String searchText : searchTerms) { <add> if ("".equals(searchText)) { <add> continue; <add> } <add> <add> //TODO: Assuming here that our background string exists and <add> //isn't null due to the background string check above <add> <add> //check to see where we should start displaying this chunk <add> int offset = TextUtils.indexOf(normalizedDisplayString, backgroundString); <add> if (offset == -1) { <add> //We can't safely highlight any of this, due to this field not actually <add> //containing the same string we're searching by. <add> continue; <add> } <add> <add> int index = backgroundString.indexOf(searchText); <add> //int index = TextUtils.indexOf(normalizedDisplayString, searchText); <add> <add> while (index >= 0) { <add> <add> //grab the display offset for actually displaying things <add> int displayIndex = index + offset; <add> <add> raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.yellow)), displayIndex, displayIndex <add> + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); <add> <add> matches.add(new int[]{index, index + searchText.length()}); <add> <add> //index=TextUtils.indexOf(raw, searchText, index + searchText.length()); <add> index = backgroundString.indexOf(searchText, index + searchText.length()); <add> <add> //we have a non-fuzzy match, so make sure we don't fuck with it <add> } <add> } <add> <add> //now insert the spans for any fuzzy matches (if enabled) <add> if (fuzzySearchEnabled && backgroundString != null) { <add> backgroundString += " "; <add> <add> for (String searchText : searchTerms) { <add> <add> if ("".equals(searchText)) { <add> continue; <add> } <add> <add> <add> int curStart = 0; <add> int curEnd = backgroundString.indexOf(" ", curStart); <add> <add> while (curEnd != -1) { <add> <add> boolean skip = matches.size() != 0; <add> <add> //See whether the fuzzy match overlaps at all with the concrete matches <add> for (int[] textMatch : matches) { <add> if (curStart < textMatch[0] && curEnd <= textMatch[0]) { <add> skip = false; <add> } else if (curStart >= textMatch[1] && curEnd > textMatch[1]) { <add> skip = false; <add> } else { <add> //We're definitely inside of this span, so <add> //don't do any fuzzy matching! <add> skip = true; <add> break; <add> } <add> } <add> <add> if (!skip) { <add> //Walk the string to find words that are fuzzy matched <add> String currentSpan = backgroundString.substring(curStart, curEnd); <add> <add> //First, figure out where we should be matching (if we don't <add> //have anywhere to match, that means there's nothing to display <add> //anyway) <add> int indexInDisplay = normalizedDisplayString.indexOf(currentSpan); <add> int length = (curEnd - curStart); <add> <add> if (indexInDisplay != -1 && StringUtils.fuzzyMatch(currentSpan, searchText).first) { <add> raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.green)), indexInDisplay, <add> indexInDisplay + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); <add> } <add> } <add> curStart = curEnd + 1; <add> curEnd = backgroundString.indexOf(" ", curStart); <add> } <add> } <add> } <add> } catch (Exception excp){ <add> removeSpans(raw); <add> StringWriter sw = new StringWriter(); <add> excp.printStackTrace(new PrintWriter(sw)); <add> Logger.log("search-hl", excp.toString() + " " + sw.toString()); <add> } <add> <add> return raw; <add> } <add> <add> /** <add> * Removes all background color spans from the Spannable <add> * @param raw Spannable to remove background colors from <add> */ <add> private static void removeSpans(Spannable raw) { <ide> //Zero out the existing spans <ide> BackgroundColorSpan[] spans=raw.getSpans(0,raw.length(), BackgroundColorSpan.class); <ide> for (BackgroundColorSpan span : spans) { <ide> raw.removeSpan(span); <ide> } <del> <del> Vector<int[]> matches = new Vector<int[]>(); <del> <del> <del> //Highlight direct substring matches <del> for (String searchText : searchTerms) { <del> if ("".equals(searchText)) { continue;} <del> <del> //TODO: Assuming here that our background string exists and <del> //isn't null due to the background string check above <del> <del> //check to see where we should start displaying this chunk <del> int offset = TextUtils.indexOf(normalizedDisplayString, backgroundString); <del> if(offset == -1) { <del> //We can't safely highlight any of this, due to this field not actually <del> //containing the same string we're searching by. <del> continue; <del> } <del> <del> int index = backgroundString.indexOf(searchText); <del> //int index = TextUtils.indexOf(normalizedDisplayString, searchText); <del> <del> while (index >= 0) { <del> <del> //grab the display offset for actually displaying things <del> int displayIndex = index + offset; <del> <del> raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.yellow)), displayIndex, displayIndex <del> + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); <del> <del> matches.add(new int[] {index, index + searchText.length() } ); <del> <del> //index=TextUtils.indexOf(raw, searchText, index + searchText.length()); <del> index = backgroundString.indexOf(searchText, index + searchText.length()); <del> <del> //we have a non-fuzzy match, so make sure we don't fuck with it <del> } <del> } <del> <del> //now insert the spans for any fuzzy matches (if enabled) <del> if(fuzzySearchEnabled && backgroundString != null) { <del> backgroundString += " "; <del> <del> for (String searchText : searchTerms) { <del> <del> if ("".equals(searchText)) { continue;} <del> <del> <del> int curStart = 0; <del> int curEnd = backgroundString.indexOf(" ", curStart); <del> <del> while(curEnd != -1) { <del> <del> boolean skip = matches.size() != 0; <del> <del> //See whether the fuzzy match overlaps at all with the concrete matches <del> for(int[] textMatch : matches) { <del> if(curStart < textMatch[0] && curEnd <= textMatch[0]) { <del> skip = false; <del> } else if(curStart >= textMatch[1] && curEnd > textMatch[1]) { <del> skip = false; <del> } else { <del> //We're definitely inside of this span, so <del> //don't do any fuzzy matching! <del> skip = true; <del> break; <del> } <del> } <del> <del> if(!skip) { <del> //Walk the string to find words that are fuzzy matched <del> String currentSpan = backgroundString.substring(curStart, curEnd); <del> <del> //First, figure out where we should be matching (if we don't <del> //have anywhere to match, that means there's nothing to display <del> //anyway) <del> int indexInDisplay = normalizedDisplayString.indexOf(currentSpan); <del> int length = (curEnd - curStart); <del> <del> if(indexInDisplay != -1 && StringUtils.fuzzyMatch(currentSpan, searchText).first) { <del> raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.green)), indexInDisplay, <del> indexInDisplay + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); <del> } <del> } <del> curStart = curEnd + 1; <del> curEnd = backgroundString.indexOf(" ", curStart); <del> } <del> } <del> } <del> <del> return raw; <del> } <del> <add> } <add> <ide> private float[] calculateDetailWeights(int[] hints) { <ide> float[] weights = new float[hints.length]; <ide> int fullSize = 100;
Java
apache-2.0
81c26968c87e908eaffe5efc20e04646da8b75b3
0
ivanr/qlue
/* * Qlue Web Application Framework * Copyright 2009-2012 Ivan Ristic <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webkreator.qlue; import com.webkreator.qlue.editors.*; import com.webkreator.qlue.exceptions.*; import com.webkreator.qlue.router.QlueRouteManager; import com.webkreator.qlue.router.RouteFactory; import com.webkreator.qlue.util.*; import com.webkreator.qlue.view.*; import com.webkreator.qlue.view.velocity.ClasspathVelocityViewFactory; import com.webkreator.qlue.view.velocity.DefaultVelocityTool; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * This class represents one Qlue application. Very simple applications might * use it directly, but most will need to subclass in order to support complex * configuration (page resolver, view resolver, etc). */ public class QlueApplication { public static final String PROPERTIES_FILENAME = "qlue.properties"; public static final String ROUTES_FILENAME = "routes.conf"; public static final String REQUEST_ACTUAL_PAGE_KEY = "QLUE_ACTUAL_PAGE"; public static final String PROPERTY_CONF_PATH = "qlue.confPath"; public static final int FRONTEND_ENCRYPTION_NO = 0; public static final int FRONTEND_ENCRYPTION_CONTAINER = 1; public static final int FRONTEND_ENCRYPTION_FORCE_YES = 2; public static final int FRONTEND_ENCRYPTION_TRUSTED_HEADER = 3; private static final String PROPERTY_CHARACTER_ENCODING = "qlue.characterEncoding"; private static final String PROPERTY_DEVMODE_ENABLED = "qlue.devmode.active"; private static final String PROPERTY_DEVMODE_RANGES = "qlue.devmode.subnets"; private static final String PROPERTY_DEVMODE_PASSWORD = "qlue.devmode.password"; private static final String PROPERTY_TRUSTED_PROXIES = "qlue.trustedProxies"; private static final String PROPERTY_FRONTEND_ENCRYPTION = "qlue.frontendEncryption"; private static final String PROPERTY_ADMIN_EMAIL = "qlue.adminEmail"; private static final String PROPERTY_URGENT_EMAIL = "qlue.urgentEmail"; private String messagesFilename = "com/webkreator/qlue/messages"; private Properties properties = new Properties(); private String appPrefix = "QlueApp"; private HttpServlet servlet; private Logger log = LoggerFactory.getLogger(QlueApplication.class); private QlueRouteManager routeManager = new QlueRouteManager(this); private ViewResolver viewResolver = new ViewResolver(); private ViewFactory viewFactory = new ClasspathVelocityViewFactory(); private HashMap<Class, PropertyEditor> editors = new HashMap<>(); private String characterEncoding = "UTF-8"; private int developmentMode = QlueConstants.DEVMODE_DISABLED; private String developmentModePassword = null; private List<CIDRUtils> developmentSubnets = null; private List<CIDRUtils> trustedProxies = null; private String adminEmail; private String urgentEmail; private int urgentCounter = -1; private SmtpEmailSender smtpEmailSender; private SmtpEmailSender asyncSmtpEmailSender; private HashMap<Locale, MessageSource> messageSources = new HashMap<>(); private String confPath; private int frontendEncryptionCheck = FRONTEND_ENCRYPTION_CONTAINER; private Timer timer; private String priorityTemplatePath; /** * This is the default constructor. The idea is that a subclass will * override it and supplement with its own configuration. */ protected QlueApplication() { initPropertyEditors(); } /** * This constructor is intended for use by very simple web applications that * consist of only one package. */ public QlueApplication(String pagesHome) { initPropertyEditors(); // These are the default routes for a simple application; we use them // to avoid having to provide routing configuration. routeManager.add(RouteFactory.create(routeManager, "/_qlue/{} package:com.webkreator.qlue.pages")); routeManager.add(RouteFactory.create(routeManager, "/{} package:" + pagesHome)); } protected void determineConfigPath() { // First, try a system property. confPath = System.getProperty(PROPERTY_CONF_PATH); if (confPath != null) { return; } // Assume the configuration is in the WEB-INF folder. confPath = servlet.getServletContext().getRealPath("/WEB-INF/"); } /** * Initialize QlueApp instance. Qlue applications are designed to be used by * servlets to delegate both initialization and request processing. */ public void init(HttpServlet servlet) throws Exception { this.servlet = servlet; determineConfigPath(); loadProperties(); initRouteManagers(); if (viewResolver == null) { throw new Exception("View resolver not configured"); } if (viewFactory == null) { throw new Exception("View factory not configured"); } viewFactory.init(this); Calendar nextHour = Calendar.getInstance(); nextHour.set(Calendar.HOUR_OF_DAY, nextHour.get(Calendar.HOUR_OF_DAY) + 1); nextHour.set(Calendar.MINUTE, 0); nextHour.set(Calendar.SECOND, 0); scheduleTask(new SendUrgentRemindersTask(), nextHour.getTime(), 60 * 60 * 1000); } protected void initRouteManagers() throws Exception { File routesFile = new File(confPath, ROUTES_FILENAME); if (routesFile.exists()) { routeManager.load(routesFile); } } void loadProperties() throws Exception { File propsFile; String filename = System.getProperty("qlue.properties"); if (filename == null) { filename = PROPERTIES_FILENAME; } if (filename.charAt(0) == '/') { propsFile = new File(filename); } else { propsFile = new File(confPath, filename); } if (propsFile.exists() == false) { throw new QlueException("Unable to find file: " + propsFile.getAbsolutePath()); } properties.load(new FileReader(propsFile)); properties.setProperty("confPath", confPath); properties.setProperty("webRoot", servlet.getServletContext().getRealPath("/")); if (getProperty(PROPERTY_CHARACTER_ENCODING) != null) { setCharacterEncoding(getProperty(PROPERTY_CHARACTER_ENCODING)); } if (getProperty(PROPERTY_DEVMODE_ENABLED) != null) { setApplicationDevelopmentMode(getProperty(PROPERTY_DEVMODE_ENABLED)); } if (getProperty(PROPERTY_DEVMODE_RANGES) != null) { setDevelopmentSubnets(getProperty(PROPERTY_DEVMODE_RANGES)); } if (getProperty(PROPERTY_TRUSTED_PROXIES) != null) { setTrustedProxies(getProperty(PROPERTY_TRUSTED_PROXIES)); } if (getProperty(PROPERTY_FRONTEND_ENCRYPTION) != null) { configureFrontendEncryption(getProperty(PROPERTY_FRONTEND_ENCRYPTION)); } developmentModePassword = getProperty(PROPERTY_DEVMODE_PASSWORD); adminEmail = getProperty(PROPERTY_ADMIN_EMAIL); urgentEmail = getProperty(PROPERTY_URGENT_EMAIL); // Configure the SMTP email senders smtpEmailSender = new SmtpEmailSender(); if (getBooleanProperty("qlue.smtp.async", "false")) { AsyncSmtpEmailSender myAsyncSmtpEmailSender = new AsyncSmtpEmailSender(smtpEmailSender); // Start a new daemon thread to send email in the background. Thread thread = new Thread(myAsyncSmtpEmailSender); thread.setDaemon(true); thread.start(); asyncSmtpEmailSender = myAsyncSmtpEmailSender; } else { // All email sending is synchronous. asyncSmtpEmailSender = smtpEmailSender; } smtpEmailSender.setSmtpServer(getProperty("qlue.smtp.server")); if (getProperty("qlue.smtp.port") != null) { smtpEmailSender.setSmtpPort(Integer.valueOf(getProperty("qlue.smtp.port"))); } if (getProperty("qlue.smtp.protocol") != null) { smtpEmailSender.setSmtpProtocol(getProperty("qlue.smtp.protocol")); } if (getProperty("qlue.smtp.username") != null) { smtpEmailSender.setSmtpUsername(getProperty("qlue.smtp.username")); smtpEmailSender.setSmtpPassword(getProperty("qlue.smtp.password")); } priorityTemplatePath = getProperty("qlue.velocity.priorityTemplatePath"); if (priorityTemplatePath != null) { Path p = FileSystems.getDefault().getPath(priorityTemplatePath); if (!p.isAbsolute()) { priorityTemplatePath = getApplicationRoot() + "/" + priorityTemplatePath; } File f = new File(priorityTemplatePath); if (!f.exists()) { throw new QlueException("Priority template path doesn't exist: " + priorityTemplatePath); } if (!f.isDirectory()) { throw new QlueException("Priority template path is not a directory: " + priorityTemplatePath); } } } private void configureFrontendEncryption(String value) { if ("no".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_NO; } else if ("forceYes".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_FORCE_YES; } else if ("container".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_CONTAINER; } else if ("trustedHeader".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_TRUSTED_HEADER; } else { throw new RuntimeException("Invalid value for the " + PROPERTY_FRONTEND_ENCRYPTION + " parameter:" + value); } } /** * Destroys the application. Invoked when the backing servlet is destroyed. */ public void destroy() { } /** * This method is the main entry point for request processing. */ protected void service(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Remember when processing began. long startTime = System.currentTimeMillis(); // Set the default character encoding. request.setCharacterEncoding(characterEncoding); response.setCharacterEncoding(characterEncoding); // Create a new application session object if one does not exist. HttpSession session = request.getSession(); synchronized (session) { if (session.getAttribute(QlueConstants.QLUE_SESSION_OBJECT) == null) { session.setAttribute(QlueConstants.QLUE_SESSION_OBJECT, createNewSessionObject()); } } // Create a new context. TransactionContext context = new TransactionContext( this, servlet.getServletConfig(), servlet.getServletContext(), request, response); // Expose transaction information to the logging subsystem. MDC.put("txId", context.getTxId()); MDC.put("remoteAddr", context.getEffectiveRemoteAddr()); MDC.put("sessionId", context.getSession().getId()); // Proceed to the second stage of request processing try { log.debug("Processing request: " + request.getRequestURI()); serviceInternal(context); log.debug("Processed request in " + (System.currentTimeMillis() - startTime)); } finally { MDC.clear(); } } protected Object route(TransactionContext context) { return routeManager.route(context); } protected View processPage(Page page) throws Exception { // Check access. The idea with this hook is to run it as early as possible, // before any parameters are accessed, thus minimising the executed code. View view = page.checkAccess(); if (view != null) { return view; } // For persistent pages, we clear errors only on POSTs; that // means that a subsequent GET can access the errors to show // them to the user. if (!page.isPersistent() || page.context.isPost()) { page.getErrors().clear(); } bindParameters(page); // Custom parameter validation. view = page.validateParameters(); if (view != null) { return view; } // Custom error handling. if (page.hasErrors()) { view = page.handleValidationError(); if (view != null) { return view; } } // Initialize the page. This really only makes sense for persistent pages, where you // want to run some code only once. With non-persistent pages, it's better to have // all the code in the same method. if (page.getState().equals(Page.STATE_INIT)) { view = page.init(); if (view != null) { return view; } } // Early call to prepare the page for the main thing. view = page.prepareForService(); if (view != null) { return view; } // Finally, run the main processing entry point. return page.service(); } /** * Request processing entry point. */ protected void serviceInternal(TransactionContext context) throws IOException { Page page = null; try { // First check if this is a request for a persistent page. We can // honour such requests only when we're not handling errors. if (context.isErrorHandler() == false) { // Persistent pages are identified via the "_pid" parameter. If we have // one such parameter, we look for the corresponding page in session storage. String pids[] = context.getParameterValues("_pid"); if ((pids != null) && (pids.length != 0)) { // Only one _pid parameter is allowed. if (pids.length != 1) { throw new RuntimeException("Request contains multiple _pid parameters"); } // Find the page using the requested page ID. PersistentPageRecord pageRecord = context.findPersistentPageRecord(pids[0]); if (pageRecord == null) { throw new PersistentPageNotFoundException("Persistent page not found: " + pids[0]); } // If the replacementUri is set that means that the page no longer // exist and that we need to forward all further request to it. if (pageRecord.getReplacementUri() != null) { context.getResponse().sendRedirect(pageRecord.getReplacementUri()); return; } // Otherwise, let's use this page. page = pageRecord.getPage(); if (page == null) { throw new RuntimeException("Page record doesn't contain page"); } } } // If we don't have a persistent page we'll create a new one by routing this request. if (page == null) { Object routeObject = route(context); if (routeObject == null) { throw new PageNotFoundException(); } else if (routeObject instanceof View) { page = new DirectViewPage((View) routeObject); } else if (routeObject instanceof Page) { page = (Page) routeObject; } else { throw new RuntimeException("Qlue: Unexpected router response: " + routeObject); } } // Run the page. Access to the page is synchronised, which means that only one // HTTP request can handle it at any given time. synchronized (page) { page.setApp(this); page.determineDefaultViewName(viewResolver); page.setContext(context); page.determineCommandObject(); if (page.isPersistent()) { context.persistPage(page); } // Set content type now, before any output happens. context.response.setContentType(page.getContentType()); View view = processPage(page); if (view != null) { renderView(view, context, page); } // Execute page commit. This is what it sounds like, // an opportunity to use a simple approach to transaction // management for simple applications. page.commit(); // Automatic page state transition. if (!page.isPersistent()) { // Non-persistent pages automatically transition to FINISHED so that cleanup can be invoked. page.setState(Page.STATE_FINISHED); } else { // For persistent pages, we change their state only if they're left as NEW // after execution. We change to POSTED in order to prevent multiple calls to init(). if (page.getState().equals(Page.STATE_INIT)) { page.setState(Page.STATE_WORKING); } } } } catch (PersistentPageNotFoundException ppnfe) { // When we encounter an unknown process reference, we // redirect back to the site home page. Showing errors // is probably not going to be helpful, and may actually compel the // user to go back and try again (and that's not going to work). context.getResponse().sendRedirect("/"); } catch (RequestMethodException rme) { if (page != null) { if (page.isDevelopmentMode()) { log.error(rme.getMessage(), rme); } page.rollback(); } // Convert RequestMethodException into a 405 response. context.getResponse().sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } catch (PageNotFoundException pnfe) { if (page != null) { if (page.isDevelopmentMode()) { log.error(pnfe.getMessage(), pnfe); } page.rollback(); } // Convert PageNotFoundException into a 404 response. context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND); } catch (ValidationException ve) { if (!page.isDevelopmentMode()) { if (page != null) { page.rollback(); } // Respond to validation errors with a 400 response. context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST); } else { // In development mode, we let the exception propagate to that it // can be handled by our generic exception handler, which will show // the error information on the screen. throw ve; } } catch (QlueSecurityException se) { if (page != null) { page.rollback(); } log.error("Security exception: " + context.getRequestUriWithQueryString(), se); // Respond to security exceptions with a 400 response. context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST); } catch (Exception e) { if (page != null) { page.rollback(); // Because we are about to throw an exception, which may cause // another page to handle this request, we need to remember // the current page (which is useful for debugging information, etc). setActualPage(page); } // Don't process the exception further if the problem is caused // by the client going away (e.g., interrupted file download). if (!e.getClass().getName().contains("ClientAbortException")) { // Handle application exception, which will record full context // data and, optionally, notify the administrator via email. handleApplicationException(context, page, e); // We do not wish to propagate the exception further, but, if it's not too late // (the response not committed), we should use a meaningful status code. if (context.getResponse().isCommitted() == false) { if (e instanceof ServiceUnavailableException) { context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } } finally { // Invoke cleanup on finished pages. if ((page != null) && (page.isFinished()) && (!page.isCleanupInvoked())) { page.cleanup(); } // In development mode, append debugging information to the end of the page. masterWriteRequestDevelopmentInformation(context, page); } } /** * Handle application exception. We dump debugging information into the * application activity log and, if the admin email address is configured, * we send the same via email. */ protected void handleApplicationException(TransactionContext tx, Page page, Throwable t) { String debugInfo = null; if (tx != null) { // Dump debugging information into a String StringWriter sw = new StringWriter(); sw.append("Debugging information follows:"); try { _masterWriteRequestDevelopmentInformation(tx, page, new PrintWriter(sw)); } catch (IOException e) { // Ignore (but log, in case we do get something) log.error("Exception while preparing debugging information", e); } // Qlue formats debugging information using HTML markup, and here // we want to log it to text files, which means we need to strip // out the markup and convert entity references. HtmlToText htt = new HtmlToText(); try { htt.parse(new StringReader(sw.getBuffer().toString())); debugInfo = htt.toString(); } catch (IOException e) { log.error("Error while converting HTML", e); } } // Record message to the activity log log.error("Qlue: Unhandled application exception", t); // Send email notification try { Email email = new SimpleEmail(); email.setCharset("UTF-8"); if (t.getMessage() != null) { email.setSubject("Application Exception: " + t.getMessage()); } else { email.setSubject("Application Exception"); } StringWriter msgBody = new StringWriter(); PrintWriter pw = new PrintWriter(msgBody); t.printStackTrace(pw); pw.println(); if (debugInfo != null) { pw.print(debugInfo); } email.setMsg(msgBody.toString()); sendAdminEmail(email, true /* fatalError */); } catch (Exception e) { log.error("Failed sending admin email: ", e); } } public synchronized void sendAdminEmail(Email email) { sendAdminEmail(email, false); } public synchronized void sendAdminEmail(Email email, boolean fatalError) { if (adminEmail == null) { return; } // Configure the correct email address. try { email.setFrom(adminEmail); // If this is a fatal error and we have an // email address for emergencies, treat it // as an emergency. if ((fatalError) && (urgentEmail != null)) { email.addTo(urgentEmail); } else { email.addTo(adminEmail); } } catch (EmailException e) { log.error("Invalid admin email address", e); } // Update the email subject to include the application prefix. email.setSubject("[" + getAppPrefix() + "] " + email.getSubject()); // If the email is about a fatal problem, determine // if we want to urgently notify the administrators; we // want to send only one urgent email per time period. if ((fatalError) && (urgentEmail != null)) { // When the counter is at -1 that means we didn't // send any emails in the previous time period. In // other words, we can send one now. if (urgentCounter == -1) { urgentCounter = 0; } else { // Alternatively, just increment the counter // and send nothing. urgentCounter++; log.info("Suppressing fatal error email (" + urgentCounter + "): " + email.getSubject()); return; } } // Send the email now. try { getEmailSender().send(email); } catch (Exception e) { log.error("Failed to send email", e); } } public void renderView(View view, TransactionContext tx, Page page) throws Exception { // For persistent pages, we clear errors only on POSTs; that // means that a subsequent GET can access the errors to show // them to the user. if (!page.isPersistent() || page.context.isPost()) { createShadowInput(page, /* fromRequest */ true); } else { if (page.getState() == Page.STATE_INIT) { createShadowInput(page, /* fromRequest */ false); } } // NullView only indicates that no further output is needed. if (view instanceof NullView) { return; } // If we get a DefaultView or NamedView instance // we have to replace them with a real view, using // the name of the page in the view resolution process. if (view instanceof DefaultView) { view = viewFactory.constructView(page, page.getViewName()); } else if (view instanceof NamedView) { view = viewFactory.constructView(page, ((NamedView) view).getViewName()); } else if (view instanceof ClasspathView) { view = viewFactory.constructView(((ClasspathView) view).getViewName()); } else if (view instanceof FinalRedirectView) { page.setState(Page.STATE_FINISHED); if (((RedirectView) view).getPage() == null) { page.context.replacePage(page, (FinalRedirectView) view); } } if (view == null) { throw new RuntimeException("Qlue: Unable to resolve view"); } view.render(tx, page); } /** * Invoked to store the original text values for parameters. The text is * needed in the cases where it cannot be converted to the intended type. */ private void createShadowInput(Page page, boolean fromRequest) throws Exception { page.clearShadowInput(); // Ask the page to provide a command object, which can be // a custom object or the page itself. Object commandObject = page.getCommandObject(); if (commandObject == null) { throw new RuntimeException("Qlue: Command object cannot be null"); } // Loop through the command object fields in order to determine // if any are annotated as parameters. Remember the original // text values of parameters. Set<Field> fields = getClassPublicFields(commandObject.getClass()); for (Field f : fields) { if (f.isAnnotationPresent(QlueParameter.class)) { if (QlueFile.class.isAssignableFrom(f.getType())) { continue; } if (!Modifier.isPublic(f.getModifiers())) { throw new QlueException("QlueParameter used on a non-public field"); } // Update missing shadow input fields if (page.getShadowInput().get(f.getName()) == null) { if (f.getType().isArray()) { createShadowInputArrayParam(page, f, fromRequest); } else { createShadowInputNonArrayParam(page, f, fromRequest); } } } } } private void createShadowInputArrayParam(Page page, Field f, boolean fromRequest) throws Exception { // Find the property editor PropertyEditor pe = editors.get(f.getType().getComponentType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType().getComponentType()); } // If there is any data in the command object use it to populate shadow input if (f.get(page.getCommandObject()) != null) { Object[] originalValues = (Object[]) f.get(page.getCommandObject()); String[] textValues = new String[originalValues.length]; for (int i = 0; i < originalValues.length; i++) { textValues[i] = pe.toText(originalValues[i]); } page.getShadowInput().set(f.getName(), textValues); } if (fromRequest) { // Overwrite with the value in the request, if present String[] requestParamValues = page.context.getParameterValues(f.getName()); if (requestParamValues != null) { page.getShadowInput().set(f.getName(), requestParamValues); } } } private void createShadowInputNonArrayParam(Page page, Field f, boolean fromRequest) throws Exception { // Find the property editor PropertyEditor pe = editors.get(f.getType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType()); } // If the object exists in the command object, convert it to text using the property editor Object o = f.get(page.getCommandObject()); if (o != null) { page.getShadowInput().set(f.getName(), pe.toText(o)); } // Overwrite with the value in the request, if present if (fromRequest) { String requestParamValue = page.context.getParameter(f.getName()); if (requestParamValue != null) { page.getShadowInput().set(f.getName(), requestParamValue); } } } /** * Appends debugging information to the view, but only if the development mode is active. */ protected void masterWriteRequestDevelopmentInformation(TransactionContext context, Page page) throws IOException { if (page == null) { return; } // Check development mode if (page.isDevelopmentMode() == false) { return; } // We might be in an error handler, in which case we want to display // the state of the actual (original) page and not this one. Page actualPage = getActualPage(page); if (actualPage != null) { // Use the actual page and context page = actualPage; context = page.getContext(); } // Ignore redirections; RedirectView knows to display development // information before redirects, which is why we don't need // to worry here. int status = context.response.getStatus(); if ((status >= 300) && (status <= 399)) { return; } // Ignore responses other than text/html; we don't want to // corrupt images and other resources that are not pages. String contentType = context.response.getContentType(); if (contentType != null) { int i = contentType.indexOf(';'); if (i != -1) { contentType = contentType.substring(0, i); } if (contentType.compareToIgnoreCase("text/html") != 0) { return; } } // Append output _masterWriteRequestDevelopmentInformation(context, page, context.response.getWriter()); } protected void _masterWriteRequestDevelopmentInformation(TransactionContext context, Page page, PrintWriter out) throws IOException { if (page == null) { return; } out.println("<hr><div align=left><pre>"); out.println("<b>Request</b>\n"); context.writeRequestDevelopmentInformation(out); out.println(""); out.println("<b>Page</b>\n"); page.writeDevelopmentInformation(out); out.println(""); out.println("<b>Session</b>\n"); page.getQlueSession().writeDevelopmentInformation(out); out.println(""); out.println("<b>Application</b>\n"); this.writeDevelopmentInformation(out); out.println("</pre></div>"); } /** * Write application-specific debugging output. */ protected void writeDevelopmentInformation(PrintWriter out) { out.println(" Prefix: " + HtmlEncoder.encodeForHTML(appPrefix)); out.println(" Development mode: " + developmentMode); } protected Set<Field> getClassPublicFields(Class klass) { Set<Field> fields = new HashSet<>(); for (; ; ) { Field[] fs = klass.getDeclaredFields(); for (Field f : fs) { fields.add(f); } klass = klass.getSuperclass(); if (klass == null) { break; } if (klass.getCanonicalName().equals(Page.class.getCanonicalName())) { break; } } return fields; } public boolean shouldBindParameter(QlueParameter qp, Page page) { String state = qp.state(); // Always bind. if (state.equals(Page.STATE_ANY)) { return true; } // Bind if the parameter state matches page state. if (state.equals(page.getState())) { return true; } // Special state STATE_DEFAULT: if the page is not persistent, // bind always. Otherwise, bind only on POST. if (state.equals(Page.STATE_DEFAULT)) { if (!page.isPersistent() || page.context.isPost()) { return true; } else { return false; } } // Bind on GET requests. if (state.equals(Page.STATE_GET) && page.context.isGet()) { return true; } // Bind on POST requests. if (state.equals(Page.STATE_POST) && page.context.isPost()) { return true; } return false; } /** * Bind request parameters to the command object provided by the page. */ private void bindParameters(Page page) throws Exception { // Ask the page to provide a command object we can bind to. Simpler pages // might see themselves as the command objects; more complex might use more than one. Object commandObject = page.getCommandObject(); if (commandObject == null) { throw new RuntimeException("Qlue: Command object cannot be null"); } // Loop through the command object fields in order to determine if any are annotated as // parameters. Validate those that are, then bind them. Set<Field> fields = getClassPublicFields(commandObject.getClass()); for (Field f : fields) { // We bind command object fields that have the QlueParameter annotation. if (f.isAnnotationPresent(QlueParameter.class) == false) { continue; } // We bind only to public fields, but it commonly happens that the QlueParameter // annotation is used on other field types, leading to frustration because it's // not obvious why binding is not working. For this reason, we detect that problem // here and force an error to inform the developer. if (!Modifier.isPublic(f.getModifiers())) { throw new QlueException("QlueParameter used on a non-public field"); } try { QlueParameter qp = f.getAnnotation(QlueParameter.class); // Bind parameter when appropriate. if (shouldBindParameter(qp, page)) { if (qp.source().equals(ParamSource.URL)) { // Bind parameters transported in URL. For this to work there needs // to exist a route that parses out the parameter out of the URL. bindParameterFromString(commandObject, f, page, page.context.getUrlParameter(f.getName())); } else { if (qp.source().equals(ParamSource.GET_POST) || (qp.source().equals(ParamSource.GET) && page.context.isGet()) || (qp.source().equals(ParamSource.POST) && page.context.isPost())) { if (f.getType().isArray()) { bindArrayParameter(commandObject, f, page); } else { bindNonArrayParameter(commandObject, f, page); } } } } } catch (IllegalArgumentException e) { // Transform editor exception into a validation error. page.addError(f.getName(), e.getMessage()); } } } /** * Bind an array parameter. */ private void bindArrayParameter(Object commandObject, Field f, Page page) throws Exception { // Get the annotation QlueParameter qp = f.getAnnotation(QlueParameter.class); // Look for a property editor, which will know how // to convert text into a proper native type PropertyEditor pe = editors.get(f.getType().getComponentType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType().getComponentType()); } String[] values = page.context.getParameterValues(f.getName()); if ((values == null) || (values.length == 0)) { // Parameter not in input; create an empty array and set it on the command object. f.set(commandObject, Array.newInstance(f.getType().getComponentType(), 0)); return; } // Parameter in input boolean hasErrors = false; Object[] convertedValues = (Object[]) Array.newInstance(f.getType().getComponentType(), values.length); for (int i = 0; i < values.length; i++) { String newValue = validateParameter(page, f, qp, values[i]); if (newValue != null) { values[i] = newValue; convertedValues[i] = pe.fromText(f, values[i], f.get(commandObject)); } else { hasErrors = true; } } if (hasErrors == false) { f.set(commandObject, convertedValues); } } /** * Validate one parameter. */ protected String validateParameter(Page page, Field f, QlueParameter qp, String value) { // Transform value according to the list // of transformation functions supplied String tfn = qp.tfn(); if (tfn.length() != 0) { StringTokenizer st = new StringTokenizer(tfn, " ,"); while (st.hasMoreTokens()) { String t = st.nextToken(); if (t.compareTo("trim") == 0) { value = value.trim(); } else if (t.compareTo("lowercase") == 0) { value = value.toLowerCase(); } else { throw new RuntimeException("Qlue: Invalid parameter transformation function: " + t); } } } // If the parameter is mandatory, check that is // not empty or that it does not consist only // of whitespace characters. if (qp.mandatory()) { if (TextUtil.isEmptyOrWhitespace(value)) { page.addError(f.getName(), getFieldMissingMessage(qp)); return null; } } // Check size if (qp.maxSize() != -1) { if ((value.length() > qp.maxSize())) { if (qp.ignoreInvalid() == false) { page.addError(f.getName(), "qlue.validation.maxSize"); return null; } else { return null; } } } // Check that it conforms to the supplied regular expression if (qp.pattern().length() != 0) { Pattern p = null; // Compile the pattern first try { p = Pattern.compile(qp.pattern(), Pattern.DOTALL); } catch (PatternSyntaxException e) { throw new RuntimeException("Qlue: Invalid parameter validation pattern: " + qp.pattern()); } // Try to match Matcher m = p.matcher(value); if ((m.matches() == false)) { if (qp.ignoreInvalid() == false) { page.addError(f.getName(), "qlue.validation.pattern"); return null; } else { return null; } } } return value; } /** * Bind a parameter that is not an array. */ private void bindNonArrayParameter(Object commandObject, Field f, Page page) throws Exception { // Get the annotation QlueParameter qp = f.getAnnotation(QlueParameter.class); // First check if the parameter is a file if (QlueFile.class.isAssignableFrom(f.getType())) { bindFileParameter(commandObject, f, page); return; } // Look for a property editor, which will know how // to convert text into a native type PropertyEditor pe = editors.get(f.getType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType()); } // If the parameter is present in request, validate it and set on the command object String value = page.context.getParameter(f.getName()); if (value != null) { String newValue = validateParameter(page, f, qp, value); if (newValue != null) { value = newValue; f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); } } else { f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); // We are here if the parameter is not in the request, in which // case we need to check of the parameter is mandatory if (qp.mandatory()) { page.addError(f.getName(), getFieldMissingMessage(qp)); } } } private void bindParameterFromString(Object commandObject, Field f, Page page, String value) throws Exception { // Get the annotation QlueParameter qp = f.getAnnotation(QlueParameter.class); // First check if the parameter is a file if (QlueFile.class.isAssignableFrom(f.getType())) { throw new RuntimeException("Qlue: Unable to bind a string to file parameter"); } // Look for a property editor, which will know how // to convert text into a native type PropertyEditor pe = editors.get(f.getType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType()); } // If the parameter is present in request, validate it // and set on the command object if (value != null) { String newValue = validateParameter(page, f, qp, value); if (newValue != null) { value = newValue; f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); } } else { f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); // We are here if the parameter is not in request, in which // case we need to check of the parameter is mandatory if (qp.mandatory()) { page.addError(f.getName(), getFieldMissingMessage(qp)); } } } /** * Retrieve field message that we need to emit when a mandatory parameter is * missing. */ private String getFieldMissingMessage(QlueParameter qp) { return (qp.fieldMissingMessage().length() > 0) ? qp.fieldMissingMessage() : "qlue.validation.mandatory"; } /** * Bind file parameter. */ private void bindFileParameter(Object commandObject, Field f, Page page) throws Exception { QlueParameter qp = f.getAnnotation(QlueParameter.class); Part p = null; try { p = page.context.getPart(f.getName()); } catch (ServletException e) { } if ((p == null) || (p.getSize() == 0)) { if (qp.mandatory()) { page.addError(f.getName(), getFieldMissingMessage(qp)); } return; } File file = File.createTempFile("qlue-", ".tmp"); p.write(file.getAbsolutePath()); p.delete(); QlueFile qf = new QlueFile(file.getAbsolutePath()); qf.setContentType(p.getContentType()); qf.setSubmittedFilename(p.getSubmittedFileName()); f.set(commandObject, qf); } /** * Register a new property editor. */ private void registerPropertyEditor(PropertyEditor editor) { editors.put(editor.getEditorClass(), editor); } /** * Register the built-in property editors. */ protected void initPropertyEditors() { registerPropertyEditor(new IntegerEditor()); registerPropertyEditor(new LongEditor()); registerPropertyEditor(new StringEditor()); registerPropertyEditor(new BooleanEditor()); registerPropertyEditor(new DateEditor()); } /** * Retrieve view resolver. */ public ViewResolver getViewResolver() { return viewResolver; } /** * Set view resolver. */ protected void setViewResolver(ViewResolver viewResolver) { this.viewResolver = viewResolver; } /** * Retrieve view factory. */ public ViewFactory getViewFactory() { return viewFactory; } /** * Set view factory. */ protected void setViewFactory(ViewFactory viewFactory) { this.viewFactory = viewFactory; } /** * Get application root directory. */ public String getApplicationRoot() { return servlet.getServletContext().getRealPath("/"); } /** * Get application prefix. */ public String getAppPrefix() { return appPrefix; } /** * Set application prefix. */ protected void setAppPrefix(String appPrefix) { this.appPrefix = appPrefix; } /** * Retrieve this application's format tool, which is used in templates to * format output (but _not_ for output encoding). By default, that's an * instance of DefaultVelocityTool, but subclasses can use something else. */ public Object getVelocityTool() { return new DefaultVelocityTool(); } /** * Retrieve an encoding tool the application can use to write directly to HTML. */ public Object getEncodingTool() { return new HtmlEncoder(); } /** * This method is invoked to create a new session object. A QlueSession * instance is returned by default, but most applications will want to * override this method and provide their own session objects. */ protected QlueSession createNewSessionObject() { return new QlueSession(); } /** * Returns the session object associated with the current HTTP session. */ public QlueSession getQlueSession(HttpServletRequest request) { return (QlueSession) request.getSession().getAttribute(QlueConstants.QLUE_SESSION_OBJECT); } /** * Invalidates the existing session and creates a new one, preserving the * QlueSession object in the process. This method should be invoked * immediately after a user is authenticated to prevent session fixation * attacks. */ public void regenerateSession(HttpServletRequest request) { QlueSession qlueSession = getQlueSession(request); QluePageManager pageManager = (QluePageManager) request.getSession().getAttribute(QlueConstants.QLUE_SESSION_PAGE_MANAGER); request.getSession().invalidate(); request.getSession(true).setAttribute(QlueConstants.QLUE_SESSION_OBJECT, qlueSession); request.getSession().setAttribute(QlueConstants.QLUE_SESSION_PAGE_MANAGER, pageManager); } /** * Set application prefix, which is used in logging as part of the unique transaction identifier. */ protected void setPrefix(String prefix) { this.appPrefix = prefix; } /** * Whether direct output (in which the programmer is expected to manually * encode data) is allowed. We do not allow direct output by default. * Override this method to change the behaviour. */ public boolean allowDirectOutput() { return false; } /** * Configure character encoding. */ protected void setCharacterEncoding(String characterEncoding) { this.characterEncoding = characterEncoding; } /** * Retrieves application's character encoding. */ public String getCharacterEncoding() { return characterEncoding; } /** * Configure development mode. */ protected void setApplicationDevelopmentMode(String input) { if (input.compareToIgnoreCase("on") == 0) { developmentMode = QlueConstants.DEVMODE_ENABLED; return; } else if (input.compareToIgnoreCase("off") == 0) { developmentMode = QlueConstants.DEVMODE_DISABLED; return; } else if (input.compareToIgnoreCase("ondemand") == 0) { developmentMode = QlueConstants.DEVMODE_ONDEMAND; return; } throw new IllegalArgumentException("Invalid value for development mode: " + input); } /** * Get the development mode setting. */ public int getApplicationDevelopmentMode() { return developmentMode; } /** * Set development mode password. */ public void setDevelopmentModePassword(String developmentModePassword) { this.developmentModePassword = developmentModePassword; } private void setTrustedProxies(String combinedSubnets) throws Exception { if (TextUtil.isEmpty(combinedSubnets)) { return; } String[] subnets = combinedSubnets.split("[;,\\x20]"); trustedProxies = new ArrayList<>(); for (String s : subnets) { if (TextUtil.isEmpty(s)) { continue; } if ((!s.contains("/")) && (!s.contains(":"))) { s = s + "/32"; } try { trustedProxies.add(new CIDRUtils(s)); } catch (IllegalArgumentException iae) { throw new RuntimeException("Qlue: Invalid proxy subnet: " + s); } } } public boolean isTrustedProxyRequest(TransactionContext context) { if (trustedProxies == null) { return false; } try { InetAddress remoteAddr = InetAddress.getByName(context.request.getRemoteAddr()); for (CIDRUtils su : trustedProxies) { if (su.isInRange(remoteAddr)) { return true; } } } catch (UnknownHostException e) { // Shouldn't happen. e.printStackTrace(System.err); return false; } return false; } /** * Configure the set of IP addresses that are allowed to use development mode. */ protected void setDevelopmentSubnets(String combinedSubnets) throws Exception { if (TextUtil.isEmpty(combinedSubnets)) { return; } String[] subnets = combinedSubnets.split("[;,\\x20]"); developmentSubnets = new ArrayList<>(); for (String s : subnets) { if (TextUtil.isEmpty(s)) { continue; } if ((!s.contains("/")) && (!s.contains(":"))) { s = s + "/32"; } try { developmentSubnets.add(new CIDRUtils(s)); } catch (IllegalArgumentException iae) { throw new RuntimeException("Qlue: Invalid development subnet: " + s); } } } /** * Check if the current transaction comes from an IP address that is allowed * to use development mode. */ public boolean isDeveloperRequest(TransactionContext context) { if (developmentSubnets == null) { return false; } try { InetAddress remoteAddr = InetAddress.getByName(context.getEffectiveRemoteAddr()); for (CIDRUtils su : developmentSubnets) { if (su.isInRange(remoteAddr)) { return true; } } } catch (UnknownHostException e) { // Shouldn't happen. e.printStackTrace(System.err); return false; } return false; } /** * Check if the current transaction comes from a developer. */ public boolean isDevelopmentMode(TransactionContext context) { // Check IP address first if (isDeveloperRequest(context) == false) { return false; } // Check session development mode (explicitly enabled) if (getQlueSession(context.getRequest()).getDevelopmentMode() == QlueConstants.DEVMODE_ENABLED) { return true; } // Check session development mode (explicitly disabled) if (getQlueSession(context.getRequest()).getDevelopmentMode() == QlueConstants.DEVMODE_DISABLED) { return false; } // Check application development mode if (getApplicationDevelopmentMode() == QlueConstants.DEVMODE_ENABLED) { return true; } return false; } /** * Check given password against the current development password. */ public boolean checkDeveloperPassword(String password) { if ((password == null) || (developmentModePassword == null)) { return false; } if (password.compareTo(developmentModePassword) == 0) { return true; } return false; } /** * Get the current development password. */ public String getDeveloperPassword() { return developmentModePassword; } /** * Retrieve this application's properties. */ public Properties getProperties() { return properties; } /** * Retrieve a single named property as text. */ public String getProperty(String key) { return VariableExpander.expand(properties.getProperty(key), properties); } /** * Retrieve a single named property as text, using the supplied default * value if the property is not set. */ public String getProperty(String key, String defaultValue) { String value = getProperty(key); if (value != null) { return value; } else { return defaultValue; } } public Boolean getBooleanProperty(String key) { String value = getProperty(key); if (value == null) { return null; } return Boolean.parseBoolean(value); } public Boolean getBooleanProperty(String key, String defaultValue) { String value = getProperty(key); if (value == null) { return Boolean.parseBoolean(defaultValue); } return Boolean.parseBoolean(value); } /** * Retrieve a single integer property. */ public Integer getIntProperty(String key) { String value = getProperty(key); if (value == null) { return null; } return Integer.parseInt(value); } /** * Retrieve a single integer property, using the supplied default value if * the property is not set. */ public Integer getIntProperty(String key, int defaultValue) { String value = getProperty(key); if (value == null) { return defaultValue; } return Integer.parseInt(value); } /** * Configure the path to the file that contains localized messages. */ protected void setMessagesFilename(String messagesFilename) { this.messagesFilename = messagesFilename; } /** * Retrieve this application's message source. */ public MessageSource getMessageSource(Locale locale) { MessageSource source = messageSources.get(locale); if (source == null) { source = new MessageSource((PropertyResourceBundle) ResourceBundle.getBundle(messagesFilename, locale), locale); messageSources.put(locale, source); } return source; } /** * Remember the current page for later use (e.g., in an error handler). */ void setActualPage(Page page) { page.context.request.setAttribute(REQUEST_ACTUAL_PAGE_KEY, page); } /** * Retrieve the actual page that tried to handle the current transaction and * failed. */ Page getActualPage(Page currentPage) { return (Page) currentPage.context.request.getAttribute(REQUEST_ACTUAL_PAGE_KEY); } /** * Allocates a new page ID. */ synchronized String generateTransactionId() { return UUID.randomUUID().toString(); } public EmailSender getEmailSender() { return asyncSmtpEmailSender; } public EmailSender getAsyncEmailSender() { return asyncSmtpEmailSender; } public EmailSender getSyncEmailSender() { return smtpEmailSender; } public String getConfPath() { return confPath; } public int getFrontendEncryptionCheck() { return frontendEncryptionCheck; } public String getAdminEmail() { return adminEmail; } protected void scheduleTask(Runnable maintenanceTask, Date firstTime, long period) { if (timer == null) { timer = new Timer(); } timer.scheduleAtFixedRate(new RunnableTaskWrapper(maintenanceTask), firstTime, period); } private class SendUrgentRemindersTask implements Runnable { @Override public void run() { try { if ((adminEmail == null) || (urgentEmail == null) || (urgentCounter < 0)) { return; } log.info("Sending urgent reminder: urgentCounter=" + urgentCounter); if (urgentCounter == 0) { // Nothing has happened in the last period; setting // the counter to -1 means that the next exception // will send an urgent email immediately. urgentCounter = -1; } else { // There were a number of exceptions in the last period, // which means that we should send a reminder email. Email email = new SimpleEmail(); email.setCharset("UTF-8"); email.setFrom(adminEmail); email.addTo(urgentEmail); email.setSubject("[" + getAppPrefix() + "] " + "Suppressed " + urgentCounter + " exception(s) in the last period"); try { getEmailSender().send(email); urgentCounter = 0; } catch (Exception e) { log.error("Failed to send email", e); } } } catch (Exception e) { log.error("SendUrgentRemindersTask exception", e); } } } private class RunnableTaskWrapper extends TimerTask { private Runnable task; RunnableTaskWrapper(Runnable task) { this.task = task; } @Override public void run() { task.run(); } } public String getPriorityTemplatePath() { return priorityTemplatePath; } /** * Returns class given its name. * * @param name * @return */ public static Class classForName(String name) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return Class.forName(name, true /* initialize */, classLoader); } catch (ClassNotFoundException e) { return null; } catch (NoClassDefFoundError e) { // NoClassDefFoundError is thrown when there is a class // that matches the name when ignoring case differences. // We do not care about that. return null; } } }
src/com/webkreator/qlue/QlueApplication.java
/* * Qlue Web Application Framework * Copyright 2009-2012 Ivan Ristic <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webkreator.qlue; import com.webkreator.qlue.editors.*; import com.webkreator.qlue.exceptions.*; import com.webkreator.qlue.router.QlueRouteManager; import com.webkreator.qlue.router.RouteFactory; import com.webkreator.qlue.util.*; import com.webkreator.qlue.view.*; import com.webkreator.qlue.view.velocity.ClasspathVelocityViewFactory; import com.webkreator.qlue.view.velocity.DefaultVelocityTool; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * This class represents one Qlue application. Very simple applications might * use it directly, but most will need to subclass in order to support complex * configuration (page resolver, view resolver, etc). */ public class QlueApplication { public static final String PROPERTIES_FILENAME = "qlue.properties"; public static final String ROUTES_FILENAME = "routes.conf"; public static final String REQUEST_ACTUAL_PAGE_KEY = "QLUE_ACTUAL_PAGE"; public static final String PROPERTY_CONF_PATH = "qlue.confPath"; public static final int FRONTEND_ENCRYPTION_NO = 0; public static final int FRONTEND_ENCRYPTION_CONTAINER = 1; public static final int FRONTEND_ENCRYPTION_FORCE_YES = 2; public static final int FRONTEND_ENCRYPTION_TRUSTED_HEADER = 3; private static final String PROPERTY_CHARACTER_ENCODING = "qlue.characterEncoding"; private static final String PROPERTY_DEVMODE_ENABLED = "qlue.devmode.active"; private static final String PROPERTY_DEVMODE_RANGES = "qlue.devmode.subnets"; private static final String PROPERTY_DEVMODE_PASSWORD = "qlue.devmode.password"; private static final String PROPERTY_TRUSTED_PROXIES = "qlue.trustedProxies"; private static final String PROPERTY_FRONTEND_ENCRYPTION = "qlue.frontendEncryption"; private static final String PROPERTY_ADMIN_EMAIL = "qlue.adminEmail"; private static final String PROPERTY_URGENT_EMAIL = "qlue.urgentEmail"; private String messagesFilename = "com/webkreator/qlue/messages"; private Properties properties = new Properties(); private String appPrefix = "QlueApp"; private HttpServlet servlet; private Logger log = LoggerFactory.getLogger(QlueApplication.class); private QlueRouteManager routeManager = new QlueRouteManager(this); private ViewResolver viewResolver = new ViewResolver(); private ViewFactory viewFactory = new ClasspathVelocityViewFactory(); private HashMap<Class, PropertyEditor> editors = new HashMap<>(); private String characterEncoding = "UTF-8"; private int developmentMode = QlueConstants.DEVMODE_DISABLED; private String developmentModePassword = null; private List<CIDRUtils> developmentSubnets = null; private List<CIDRUtils> trustedProxies = null; private String adminEmail; private String urgentEmail; private int urgentCounter = -1; private SmtpEmailSender smtpEmailSender; private SmtpEmailSender asyncSmtpEmailSender; private HashMap<Locale, MessageSource> messageSources = new HashMap<>(); private String confPath; private int frontendEncryptionCheck = FRONTEND_ENCRYPTION_CONTAINER; private Timer timer; private String priorityTemplatePath; /** * This is the default constructor. The idea is that a subclass will * override it and supplement with its own configuration. */ protected QlueApplication() { initPropertyEditors(); } /** * This constructor is intended for use by very simple web applications that * consist of only one package. */ public QlueApplication(String pagesHome) { initPropertyEditors(); // These are the default routes for a simple application; we use them // to avoid having to provide routing configuration. routeManager.add(RouteFactory.create(routeManager, "/_qlue/{} package:com.webkreator.qlue.pages")); routeManager.add(RouteFactory.create(routeManager, "/{} package:" + pagesHome)); } protected void determineConfigPath() { // First, try a system property. confPath = System.getProperty(PROPERTY_CONF_PATH); if (confPath != null) { return; } // Assume the configuration is in the WEB-INF folder. confPath = servlet.getServletContext().getRealPath("/WEB-INF/"); } /** * Initialize QlueApp instance. Qlue applications are designed to be used by * servlets to delegate both initialization and request processing. */ public void init(HttpServlet servlet) throws Exception { this.servlet = servlet; determineConfigPath(); loadProperties(); initRouteManagers(); if (viewResolver == null) { throw new Exception("View resolver not configured"); } if (viewFactory == null) { throw new Exception("View factory not configured"); } viewFactory.init(this); Calendar nextHour = Calendar.getInstance(); nextHour.set(Calendar.HOUR_OF_DAY, nextHour.get(Calendar.HOUR_OF_DAY) + 1); nextHour.set(Calendar.MINUTE, 0); nextHour.set(Calendar.SECOND, 0); scheduleTask(new SendUrgentRemindersTask(), nextHour.getTime(), 60 * 60 * 1000); } protected void initRouteManagers() throws Exception { File routesFile = new File(confPath, ROUTES_FILENAME); if (routesFile.exists()) { routeManager.load(routesFile); } } void loadProperties() throws Exception { File propsFile; String filename = System.getProperty("qlue.properties"); if (filename == null) { filename = PROPERTIES_FILENAME; } if (filename.charAt(0) == '/') { propsFile = new File(filename); } else { propsFile = new File(confPath, filename); } if (propsFile.exists() == false) { throw new QlueException("Unable to find file: " + propsFile.getAbsolutePath()); } properties.load(new FileReader(propsFile)); properties.setProperty("confPath", confPath); properties.setProperty("webRoot", servlet.getServletContext().getRealPath("/")); if (getProperty(PROPERTY_CHARACTER_ENCODING) != null) { setCharacterEncoding(getProperty(PROPERTY_CHARACTER_ENCODING)); } if (getProperty(PROPERTY_DEVMODE_ENABLED) != null) { setApplicationDevelopmentMode(getProperty(PROPERTY_DEVMODE_ENABLED)); } if (getProperty(PROPERTY_DEVMODE_RANGES) != null) { setDevelopmentSubnets(getProperty(PROPERTY_DEVMODE_RANGES)); } if (getProperty(PROPERTY_TRUSTED_PROXIES) != null) { setTrustedProxies(getProperty(PROPERTY_TRUSTED_PROXIES)); } if (getProperty(PROPERTY_FRONTEND_ENCRYPTION) != null) { configureFrontendEncryption(getProperty(PROPERTY_FRONTEND_ENCRYPTION)); } developmentModePassword = getProperty(PROPERTY_DEVMODE_PASSWORD); adminEmail = getProperty(PROPERTY_ADMIN_EMAIL); urgentEmail = getProperty(PROPERTY_URGENT_EMAIL); // Configure the SMTP email senders smtpEmailSender = new SmtpEmailSender(); if (getBooleanProperty("qlue.smtp.async", "false")) { AsyncSmtpEmailSender myAsyncSmtpEmailSender = new AsyncSmtpEmailSender(smtpEmailSender); // Start a new daemon thread to send email in the background. Thread thread = new Thread(myAsyncSmtpEmailSender); thread.setDaemon(true); thread.start(); asyncSmtpEmailSender = myAsyncSmtpEmailSender; } else { // All email sending is synchronous. asyncSmtpEmailSender = smtpEmailSender; } smtpEmailSender.setSmtpServer(getProperty("qlue.smtp.server")); if (getProperty("qlue.smtp.port") != null) { smtpEmailSender.setSmtpPort(Integer.valueOf(getProperty("qlue.smtp.port"))); } if (getProperty("qlue.smtp.protocol") != null) { smtpEmailSender.setSmtpProtocol(getProperty("qlue.smtp.protocol")); } if (getProperty("qlue.smtp.username") != null) { smtpEmailSender.setSmtpUsername(getProperty("qlue.smtp.username")); smtpEmailSender.setSmtpPassword(getProperty("qlue.smtp.password")); } priorityTemplatePath = getProperty("qlue.velocity.priorityTemplatePath"); if (priorityTemplatePath != null) { Path p = FileSystems.getDefault().getPath(priorityTemplatePath); if (!p.isAbsolute()) { priorityTemplatePath = getApplicationRoot() + "/" + priorityTemplatePath; } File f = new File(priorityTemplatePath); if (!f.exists()) { throw new QlueException("Priority template path doesn't exist: " + priorityTemplatePath); } if (!f.isDirectory()) { throw new QlueException("Priority template path is not a directory: " + priorityTemplatePath); } } } private void configureFrontendEncryption(String value) { if ("no".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_NO; } else if ("forceYes".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_FORCE_YES; } else if ("container".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_CONTAINER; } else if ("trustedHeader".equals(value)) { frontendEncryptionCheck = FRONTEND_ENCRYPTION_TRUSTED_HEADER; } else { throw new RuntimeException("Invalid value for the " + PROPERTY_FRONTEND_ENCRYPTION + " parameter:" + value); } } /** * Destroys the application. Invoked when the backing servlet is destroyed. */ public void destroy() { } /** * This method is the main entry point for request processing. */ protected void service(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Remember when processing began. long startTime = System.currentTimeMillis(); // Set the default character encoding. request.setCharacterEncoding(characterEncoding); response.setCharacterEncoding(characterEncoding); // Create a new application session object if one does not exist. HttpSession session = request.getSession(); synchronized (session) { if (session.getAttribute(QlueConstants.QLUE_SESSION_OBJECT) == null) { session.setAttribute(QlueConstants.QLUE_SESSION_OBJECT, createNewSessionObject()); } } // Create a new context. TransactionContext context = new TransactionContext( this, servlet.getServletConfig(), servlet.getServletContext(), request, response); // Create a logging context using the unique transaction ID. MDC.put("txId", context.getTxId()); // Proceed to the second stage of request processing try { log.debug("Processing request: " + request.getRequestURI()); serviceInternal(context); log.debug("Processed request in " + (System.currentTimeMillis() - startTime)); } finally { MDC.clear(); } } protected Object route(TransactionContext context) { return routeManager.route(context); } protected View processPage(Page page) throws Exception { // Check access. The idea with this hook is to run it as early as possible, // before any parameters are accessed, thus minimising the executed code. View view = page.checkAccess(); if (view != null) { return view; } // For persistent pages, we clear errors only on POSTs; that // means that a subsequent GET can access the errors to show // them to the user. if (!page.isPersistent() || page.context.isPost()) { page.getErrors().clear(); } bindParameters(page); // Custom parameter validation. view = page.validateParameters(); if (view != null) { return view; } // Custom error handling. if (page.hasErrors()) { view = page.handleValidationError(); if (view != null) { return view; } } // Initialize the page. This really only makes sense for persistent pages, where you // want to run some code only once. With non-persistent pages, it's better to have // all the code in the same method. if (page.getState().equals(Page.STATE_INIT)) { view = page.init(); if (view != null) { return view; } } // Early call to prepare the page for the main thing. view = page.prepareForService(); if (view != null) { return view; } // Finally, run the main processing entry point. return page.service(); } /** * Request processing entry point. */ protected void serviceInternal(TransactionContext context) throws IOException { Page page = null; try { // First check if this is a request for a persistent page. We can // honour such requests only when we're not handling errors. if (context.isErrorHandler() == false) { // Persistent pages are identified via the "_pid" parameter. If we have // one such parameter, we look for the corresponding page in session storage. String pids[] = context.getParameterValues("_pid"); if ((pids != null) && (pids.length != 0)) { // Only one _pid parameter is allowed. if (pids.length != 1) { throw new RuntimeException("Request contains multiple _pid parameters"); } // Find the page using the requested page ID. PersistentPageRecord pageRecord = context.findPersistentPageRecord(pids[0]); if (pageRecord == null) { throw new PersistentPageNotFoundException("Persistent page not found: " + pids[0]); } // If the replacementUri is set that means that the page no longer // exist and that we need to forward all further request to it. if (pageRecord.getReplacementUri() != null) { context.getResponse().sendRedirect(pageRecord.getReplacementUri()); return; } // Otherwise, let's use this page. page = pageRecord.getPage(); if (page == null) { throw new RuntimeException("Page record doesn't contain page"); } } } // If we don't have a persistent page we'll create a new one by routing this request. if (page == null) { Object routeObject = route(context); if (routeObject == null) { throw new PageNotFoundException(); } else if (routeObject instanceof View) { page = new DirectViewPage((View) routeObject); } else if (routeObject instanceof Page) { page = (Page) routeObject; } else { throw new RuntimeException("Qlue: Unexpected router response: " + routeObject); } } // Run the page. Access to the page is synchronised, which means that only one // HTTP request can handle it at any given time. synchronized (page) { page.setApp(this); page.determineDefaultViewName(viewResolver); page.setContext(context); page.determineCommandObject(); if (page.isPersistent()) { context.persistPage(page); } // Set content type now, before any output happens. context.response.setContentType(page.getContentType()); View view = processPage(page); if (view != null) { renderView(view, context, page); } // Execute page commit. This is what it sounds like, // an opportunity to use a simple approach to transaction // management for simple applications. page.commit(); // Automatic page state transition. if (!page.isPersistent()) { // Non-persistent pages automatically transition to FINISHED so that cleanup can be invoked. page.setState(Page.STATE_FINISHED); } else { // For persistent pages, we change their state only if they're left as NEW // after execution. We change to POSTED in order to prevent multiple calls to init(). if (page.getState().equals(Page.STATE_INIT)) { page.setState(Page.STATE_WORKING); } } } } catch (PersistentPageNotFoundException ppnfe) { // When we encounter an unknown process reference, we // redirect back to the site home page. Showing errors // is probably not going to be helpful, and may actually compel the // user to go back and try again (and that's not going to work). context.getResponse().sendRedirect("/"); } catch (RequestMethodException rme) { if (page != null) { if (page.isDevelopmentMode()) { log.error(rme.getMessage(), rme); } page.rollback(); } // Convert RequestMethodException into a 405 response. context.getResponse().sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } catch (PageNotFoundException pnfe) { if (page != null) { if (page.isDevelopmentMode()) { log.error(pnfe.getMessage(), pnfe); } page.rollback(); } // Convert PageNotFoundException into a 404 response. context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND); } catch (ValidationException ve) { if (!page.isDevelopmentMode()) { if (page != null) { page.rollback(); } // Respond to validation errors with a 400 response. context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST); } else { // In development mode, we let the exception propagate to that it // can be handled by our generic exception handler, which will show // the error information on the screen. throw ve; } } catch (QlueSecurityException se) { if (page != null) { page.rollback(); } log.error("Security exception: " + context.getRequestUriWithQueryString(), se); // Respond to security exceptions with a 400 response. context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST); } catch (Exception e) { if (page != null) { page.rollback(); // Because we are about to throw an exception, which may cause // another page to handle this request, we need to remember // the current page (which is useful for debugging information, etc). setActualPage(page); } // Don't process the exception further if the problem is caused // by the client going away (e.g., interrupted file download). if (!e.getClass().getName().contains("ClientAbortException")) { // Handle application exception, which will record full context // data and, optionally, notify the administrator via email. handleApplicationException(context, page, e); // We do not wish to propagate the exception further, but, if it's not too late // (the response not committed), we should use a meaningful status code. if (context.getResponse().isCommitted() == false) { if (e instanceof ServiceUnavailableException) { context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } } finally { // Invoke cleanup on finished pages. if ((page != null) && (page.isFinished()) && (!page.isCleanupInvoked())) { page.cleanup(); } // In development mode, append debugging information to the end of the page. masterWriteRequestDevelopmentInformation(context, page); } } /** * Handle application exception. We dump debugging information into the * application activity log and, if the admin email address is configured, * we send the same via email. */ protected void handleApplicationException(TransactionContext tx, Page page, Throwable t) { String debugInfo = null; if (tx != null) { // Dump debugging information into a String StringWriter sw = new StringWriter(); sw.append("Debugging information follows:"); try { _masterWriteRequestDevelopmentInformation(tx, page, new PrintWriter(sw)); } catch (IOException e) { // Ignore (but log, in case we do get something) log.error("Exception while preparing debugging information", e); } // Qlue formats debugging information using HTML markup, and here // we want to log it to text files, which means we need to strip // out the markup and convert entity references. HtmlToText htt = new HtmlToText(); try { htt.parse(new StringReader(sw.getBuffer().toString())); debugInfo = htt.toString(); } catch (IOException e) { log.error("Error while converting HTML", e); } } // Record message to the activity log log.error("Qlue: Unhandled application exception", t); // Send email notification try { Email email = new SimpleEmail(); email.setCharset("UTF-8"); if (t.getMessage() != null) { email.setSubject("Application Exception: " + t.getMessage()); } else { email.setSubject("Application Exception"); } StringWriter msgBody = new StringWriter(); PrintWriter pw = new PrintWriter(msgBody); t.printStackTrace(pw); pw.println(); if (debugInfo != null) { pw.print(debugInfo); } email.setMsg(msgBody.toString()); sendAdminEmail(email, true /* fatalError */); } catch (Exception e) { log.error("Failed sending admin email: ", e); } } public synchronized void sendAdminEmail(Email email) { sendAdminEmail(email, false); } public synchronized void sendAdminEmail(Email email, boolean fatalError) { if (adminEmail == null) { return; } // Configure the correct email address. try { email.setFrom(adminEmail); // If this is a fatal error and we have an // email address for emergencies, treat it // as an emergency. if ((fatalError) && (urgentEmail != null)) { email.addTo(urgentEmail); } else { email.addTo(adminEmail); } } catch (EmailException e) { log.error("Invalid admin email address", e); } // Update the email subject to include the application prefix. email.setSubject("[" + getAppPrefix() + "] " + email.getSubject()); // If the email is about a fatal problem, determine // if we want to urgently notify the administrators; we // want to send only one urgent email per time period. if ((fatalError) && (urgentEmail != null)) { // When the counter is at -1 that means we didn't // send any emails in the previous time period. In // other words, we can send one now. if (urgentCounter == -1) { urgentCounter = 0; } else { // Alternatively, just increment the counter // and send nothing. urgentCounter++; log.info("Suppressing fatal error email (" + urgentCounter + "): " + email.getSubject()); return; } } // Send the email now. try { getEmailSender().send(email); } catch (Exception e) { log.error("Failed to send email", e); } } public void renderView(View view, TransactionContext tx, Page page) throws Exception { // For persistent pages, we clear errors only on POSTs; that // means that a subsequent GET can access the errors to show // them to the user. if (!page.isPersistent() || page.context.isPost()) { createShadowInput(page, /* fromRequest */ true); } else { if (page.getState() == Page.STATE_INIT) { createShadowInput(page, /* fromRequest */ false); } } // NullView only indicates that no further output is needed. if (view instanceof NullView) { return; } // If we get a DefaultView or NamedView instance // we have to replace them with a real view, using // the name of the page in the view resolution process. if (view instanceof DefaultView) { view = viewFactory.constructView(page, page.getViewName()); } else if (view instanceof NamedView) { view = viewFactory.constructView(page, ((NamedView) view).getViewName()); } else if (view instanceof ClasspathView) { view = viewFactory.constructView(((ClasspathView) view).getViewName()); } else if (view instanceof FinalRedirectView) { page.setState(Page.STATE_FINISHED); if (((RedirectView) view).getPage() == null) { page.context.replacePage(page, (FinalRedirectView) view); } } if (view == null) { throw new RuntimeException("Qlue: Unable to resolve view"); } view.render(tx, page); } /** * Invoked to store the original text values for parameters. The text is * needed in the cases where it cannot be converted to the intended type. */ private void createShadowInput(Page page, boolean fromRequest) throws Exception { page.clearShadowInput(); // Ask the page to provide a command object, which can be // a custom object or the page itself. Object commandObject = page.getCommandObject(); if (commandObject == null) { throw new RuntimeException("Qlue: Command object cannot be null"); } // Loop through the command object fields in order to determine // if any are annotated as parameters. Remember the original // text values of parameters. Set<Field> fields = getClassPublicFields(commandObject.getClass()); for (Field f : fields) { if (f.isAnnotationPresent(QlueParameter.class)) { if (QlueFile.class.isAssignableFrom(f.getType())) { continue; } if (!Modifier.isPublic(f.getModifiers())) { throw new QlueException("QlueParameter used on a non-public field"); } // Update missing shadow input fields if (page.getShadowInput().get(f.getName()) == null) { if (f.getType().isArray()) { createShadowInputArrayParam(page, f, fromRequest); } else { createShadowInputNonArrayParam(page, f, fromRequest); } } } } } private void createShadowInputArrayParam(Page page, Field f, boolean fromRequest) throws Exception { // Find the property editor PropertyEditor pe = editors.get(f.getType().getComponentType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType().getComponentType()); } // If there is any data in the command object use it to populate shadow input if (f.get(page.getCommandObject()) != null) { Object[] originalValues = (Object[]) f.get(page.getCommandObject()); String[] textValues = new String[originalValues.length]; for (int i = 0; i < originalValues.length; i++) { textValues[i] = pe.toText(originalValues[i]); } page.getShadowInput().set(f.getName(), textValues); } if (fromRequest) { // Overwrite with the value in the request, if present String[] requestParamValues = page.context.getParameterValues(f.getName()); if (requestParamValues != null) { page.getShadowInput().set(f.getName(), requestParamValues); } } } private void createShadowInputNonArrayParam(Page page, Field f, boolean fromRequest) throws Exception { // Find the property editor PropertyEditor pe = editors.get(f.getType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType()); } // If the object exists in the command object, convert it to text using the property editor Object o = f.get(page.getCommandObject()); if (o != null) { page.getShadowInput().set(f.getName(), pe.toText(o)); } // Overwrite with the value in the request, if present if (fromRequest) { String requestParamValue = page.context.getParameter(f.getName()); if (requestParamValue != null) { page.getShadowInput().set(f.getName(), requestParamValue); } } } /** * Appends debugging information to the view, but only if the development mode is active. */ protected void masterWriteRequestDevelopmentInformation(TransactionContext context, Page page) throws IOException { if (page == null) { return; } // Check development mode if (page.isDevelopmentMode() == false) { return; } // We might be in an error handler, in which case we want to display // the state of the actual (original) page and not this one. Page actualPage = getActualPage(page); if (actualPage != null) { // Use the actual page and context page = actualPage; context = page.getContext(); } // Ignore redirections; RedirectView knows to display development // information before redirects, which is why we don't need // to worry here. int status = context.response.getStatus(); if ((status >= 300) && (status <= 399)) { return; } // Ignore responses other than text/html; we don't want to // corrupt images and other resources that are not pages. String contentType = context.response.getContentType(); if (contentType != null) { int i = contentType.indexOf(';'); if (i != -1) { contentType = contentType.substring(0, i); } if (contentType.compareToIgnoreCase("text/html") != 0) { return; } } // Append output _masterWriteRequestDevelopmentInformation(context, page, context.response.getWriter()); } protected void _masterWriteRequestDevelopmentInformation(TransactionContext context, Page page, PrintWriter out) throws IOException { if (page == null) { return; } out.println("<hr><div align=left><pre>"); out.println("<b>Request</b>\n"); context.writeRequestDevelopmentInformation(out); out.println(""); out.println("<b>Page</b>\n"); page.writeDevelopmentInformation(out); out.println(""); out.println("<b>Session</b>\n"); page.getQlueSession().writeDevelopmentInformation(out); out.println(""); out.println("<b>Application</b>\n"); this.writeDevelopmentInformation(out); out.println("</pre></div>"); } /** * Write application-specific debugging output. */ protected void writeDevelopmentInformation(PrintWriter out) { out.println(" Prefix: " + HtmlEncoder.encodeForHTML(appPrefix)); out.println(" Development mode: " + developmentMode); } protected Set<Field> getClassPublicFields(Class klass) { Set<Field> fields = new HashSet<>(); for (; ; ) { Field[] fs = klass.getDeclaredFields(); for (Field f : fs) { fields.add(f); } klass = klass.getSuperclass(); if (klass == null) { break; } if (klass.getCanonicalName().equals(Page.class.getCanonicalName())) { break; } } return fields; } public boolean shouldBindParameter(QlueParameter qp, Page page) { String state = qp.state(); // Always bind. if (state.equals(Page.STATE_ANY)) { return true; } // Bind if the parameter state matches page state. if (state.equals(page.getState())) { return true; } // Special state STATE_DEFAULT: if the page is not persistent, // bind always. Otherwise, bind only on POST. if (state.equals(Page.STATE_DEFAULT)) { if (!page.isPersistent() || page.context.isPost()) { return true; } else { return false; } } // Bind on GET requests. if (state.equals(Page.STATE_GET) && page.context.isGet()) { return true; } // Bind on POST requests. if (state.equals(Page.STATE_POST) && page.context.isPost()) { return true; } return false; } /** * Bind request parameters to the command object provided by the page. */ private void bindParameters(Page page) throws Exception { // Ask the page to provide a command object we can bind to. Simpler pages // might see themselves as the command objects; more complex might use more than one. Object commandObject = page.getCommandObject(); if (commandObject == null) { throw new RuntimeException("Qlue: Command object cannot be null"); } // Loop through the command object fields in order to determine if any are annotated as // parameters. Validate those that are, then bind them. Set<Field> fields = getClassPublicFields(commandObject.getClass()); for (Field f : fields) { // We bind command object fields that have the QlueParameter annotation. if (f.isAnnotationPresent(QlueParameter.class) == false) { continue; } // We bind only to public fields, but it commonly happens that the QlueParameter // annotation is used on other field types, leading to frustration because it's // not obvious why binding is not working. For this reason, we detect that problem // here and force an error to inform the developer. if (!Modifier.isPublic(f.getModifiers())) { throw new QlueException("QlueParameter used on a non-public field"); } try { QlueParameter qp = f.getAnnotation(QlueParameter.class); // Bind parameter when appropriate. if (shouldBindParameter(qp, page)) { if (qp.source().equals(ParamSource.URL)) { // Bind parameters transported in URL. For this to work there needs // to exist a route that parses out the parameter out of the URL. bindParameterFromString(commandObject, f, page, page.context.getUrlParameter(f.getName())); } else { if (qp.source().equals(ParamSource.GET_POST) || (qp.source().equals(ParamSource.GET) && page.context.isGet()) || (qp.source().equals(ParamSource.POST) && page.context.isPost())) { if (f.getType().isArray()) { bindArrayParameter(commandObject, f, page); } else { bindNonArrayParameter(commandObject, f, page); } } } } } catch (IllegalArgumentException e) { // Transform editor exception into a validation error. page.addError(f.getName(), e.getMessage()); } } } /** * Bind an array parameter. */ private void bindArrayParameter(Object commandObject, Field f, Page page) throws Exception { // Get the annotation QlueParameter qp = f.getAnnotation(QlueParameter.class); // Look for a property editor, which will know how // to convert text into a proper native type PropertyEditor pe = editors.get(f.getType().getComponentType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType().getComponentType()); } String[] values = page.context.getParameterValues(f.getName()); if ((values == null) || (values.length == 0)) { // Parameter not in input; create an empty array and set it on the command object. f.set(commandObject, Array.newInstance(f.getType().getComponentType(), 0)); return; } // Parameter in input boolean hasErrors = false; Object[] convertedValues = (Object[]) Array.newInstance(f.getType().getComponentType(), values.length); for (int i = 0; i < values.length; i++) { String newValue = validateParameter(page, f, qp, values[i]); if (newValue != null) { values[i] = newValue; convertedValues[i] = pe.fromText(f, values[i], f.get(commandObject)); } else { hasErrors = true; } } if (hasErrors == false) { f.set(commandObject, convertedValues); } } /** * Validate one parameter. */ protected String validateParameter(Page page, Field f, QlueParameter qp, String value) { // Transform value according to the list // of transformation functions supplied String tfn = qp.tfn(); if (tfn.length() != 0) { StringTokenizer st = new StringTokenizer(tfn, " ,"); while (st.hasMoreTokens()) { String t = st.nextToken(); if (t.compareTo("trim") == 0) { value = value.trim(); } else if (t.compareTo("lowercase") == 0) { value = value.toLowerCase(); } else { throw new RuntimeException("Qlue: Invalid parameter transformation function: " + t); } } } // If the parameter is mandatory, check that is // not empty or that it does not consist only // of whitespace characters. if (qp.mandatory()) { if (TextUtil.isEmptyOrWhitespace(value)) { page.addError(f.getName(), getFieldMissingMessage(qp)); return null; } } // Check size if (qp.maxSize() != -1) { if ((value.length() > qp.maxSize())) { if (qp.ignoreInvalid() == false) { page.addError(f.getName(), "qlue.validation.maxSize"); return null; } else { return null; } } } // Check that it conforms to the supplied regular expression if (qp.pattern().length() != 0) { Pattern p = null; // Compile the pattern first try { p = Pattern.compile(qp.pattern(), Pattern.DOTALL); } catch (PatternSyntaxException e) { throw new RuntimeException("Qlue: Invalid parameter validation pattern: " + qp.pattern()); } // Try to match Matcher m = p.matcher(value); if ((m.matches() == false)) { if (qp.ignoreInvalid() == false) { page.addError(f.getName(), "qlue.validation.pattern"); return null; } else { return null; } } } return value; } /** * Bind a parameter that is not an array. */ private void bindNonArrayParameter(Object commandObject, Field f, Page page) throws Exception { // Get the annotation QlueParameter qp = f.getAnnotation(QlueParameter.class); // First check if the parameter is a file if (QlueFile.class.isAssignableFrom(f.getType())) { bindFileParameter(commandObject, f, page); return; } // Look for a property editor, which will know how // to convert text into a native type PropertyEditor pe = editors.get(f.getType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType()); } // If the parameter is present in request, validate it and set on the command object String value = page.context.getParameter(f.getName()); if (value != null) { String newValue = validateParameter(page, f, qp, value); if (newValue != null) { value = newValue; f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); } } else { f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); // We are here if the parameter is not in the request, in which // case we need to check of the parameter is mandatory if (qp.mandatory()) { page.addError(f.getName(), getFieldMissingMessage(qp)); } } } private void bindParameterFromString(Object commandObject, Field f, Page page, String value) throws Exception { // Get the annotation QlueParameter qp = f.getAnnotation(QlueParameter.class); // First check if the parameter is a file if (QlueFile.class.isAssignableFrom(f.getType())) { throw new RuntimeException("Qlue: Unable to bind a string to file parameter"); } // Look for a property editor, which will know how // to convert text into a native type PropertyEditor pe = editors.get(f.getType()); if (pe == null) { throw new RuntimeException("Qlue: Binding does not know how to handle type: " + f.getType()); } // If the parameter is present in request, validate it // and set on the command object if (value != null) { String newValue = validateParameter(page, f, qp, value); if (newValue != null) { value = newValue; f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); } } else { f.set(commandObject, pe.fromText(f, value, f.get(commandObject))); // We are here if the parameter is not in request, in which // case we need to check of the parameter is mandatory if (qp.mandatory()) { page.addError(f.getName(), getFieldMissingMessage(qp)); } } } /** * Retrieve field message that we need to emit when a mandatory parameter is * missing. */ private String getFieldMissingMessage(QlueParameter qp) { return (qp.fieldMissingMessage().length() > 0) ? qp.fieldMissingMessage() : "qlue.validation.mandatory"; } /** * Bind file parameter. */ private void bindFileParameter(Object commandObject, Field f, Page page) throws Exception { QlueParameter qp = f.getAnnotation(QlueParameter.class); Part p = null; try { p = page.context.getPart(f.getName()); } catch (ServletException e) { } if ((p == null) || (p.getSize() == 0)) { if (qp.mandatory()) { page.addError(f.getName(), getFieldMissingMessage(qp)); } return; } File file = File.createTempFile("qlue-", ".tmp"); p.write(file.getAbsolutePath()); p.delete(); QlueFile qf = new QlueFile(file.getAbsolutePath()); qf.setContentType(p.getContentType()); qf.setSubmittedFilename(p.getSubmittedFileName()); f.set(commandObject, qf); } /** * Register a new property editor. */ private void registerPropertyEditor(PropertyEditor editor) { editors.put(editor.getEditorClass(), editor); } /** * Register the built-in property editors. */ protected void initPropertyEditors() { registerPropertyEditor(new IntegerEditor()); registerPropertyEditor(new LongEditor()); registerPropertyEditor(new StringEditor()); registerPropertyEditor(new BooleanEditor()); registerPropertyEditor(new DateEditor()); } /** * Retrieve view resolver. */ public ViewResolver getViewResolver() { return viewResolver; } /** * Set view resolver. */ protected void setViewResolver(ViewResolver viewResolver) { this.viewResolver = viewResolver; } /** * Retrieve view factory. */ public ViewFactory getViewFactory() { return viewFactory; } /** * Set view factory. */ protected void setViewFactory(ViewFactory viewFactory) { this.viewFactory = viewFactory; } /** * Get application root directory. */ public String getApplicationRoot() { return servlet.getServletContext().getRealPath("/"); } /** * Get application prefix. */ public String getAppPrefix() { return appPrefix; } /** * Set application prefix. */ protected void setAppPrefix(String appPrefix) { this.appPrefix = appPrefix; } /** * Retrieve this application's format tool, which is used in templates to * format output (but _not_ for output encoding). By default, that's an * instance of DefaultVelocityTool, but subclasses can use something else. */ public Object getVelocityTool() { return new DefaultVelocityTool(); } /** * Retrieve an encoding tool the application can use to write directly to HTML. */ public Object getEncodingTool() { return new HtmlEncoder(); } /** * This method is invoked to create a new session object. A QlueSession * instance is returned by default, but most applications will want to * override this method and provide their own session objects. */ protected QlueSession createNewSessionObject() { return new QlueSession(); } /** * Returns the session object associated with the current HTTP session. */ public QlueSession getQlueSession(HttpServletRequest request) { return (QlueSession) request.getSession().getAttribute(QlueConstants.QLUE_SESSION_OBJECT); } /** * Invalidates the existing session and creates a new one, preserving the * QlueSession object in the process. This method should be invoked * immediately after a user is authenticated to prevent session fixation * attacks. */ public void regenerateSession(HttpServletRequest request) { QlueSession qlueSession = getQlueSession(request); QluePageManager pageManager = (QluePageManager) request.getSession().getAttribute(QlueConstants.QLUE_SESSION_PAGE_MANAGER); request.getSession().invalidate(); request.getSession(true).setAttribute(QlueConstants.QLUE_SESSION_OBJECT, qlueSession); request.getSession().setAttribute(QlueConstants.QLUE_SESSION_PAGE_MANAGER, pageManager); } /** * Set application prefix, which is used in logging as part of the unique transaction identifier. */ protected void setPrefix(String prefix) { this.appPrefix = prefix; } /** * Whether direct output (in which the programmer is expected to manually * encode data) is allowed. We do not allow direct output by default. * Override this method to change the behaviour. */ public boolean allowDirectOutput() { return false; } /** * Configure character encoding. */ protected void setCharacterEncoding(String characterEncoding) { this.characterEncoding = characterEncoding; } /** * Retrieves application's character encoding. */ public String getCharacterEncoding() { return characterEncoding; } /** * Configure development mode. */ protected void setApplicationDevelopmentMode(String input) { if (input.compareToIgnoreCase("on") == 0) { developmentMode = QlueConstants.DEVMODE_ENABLED; return; } else if (input.compareToIgnoreCase("off") == 0) { developmentMode = QlueConstants.DEVMODE_DISABLED; return; } else if (input.compareToIgnoreCase("ondemand") == 0) { developmentMode = QlueConstants.DEVMODE_ONDEMAND; return; } throw new IllegalArgumentException("Invalid value for development mode: " + input); } /** * Get the development mode setting. */ public int getApplicationDevelopmentMode() { return developmentMode; } /** * Set development mode password. */ public void setDevelopmentModePassword(String developmentModePassword) { this.developmentModePassword = developmentModePassword; } private void setTrustedProxies(String combinedSubnets) throws Exception { if (TextUtil.isEmpty(combinedSubnets)) { return; } String[] subnets = combinedSubnets.split("[;,\\x20]"); trustedProxies = new ArrayList<>(); for (String s : subnets) { if (TextUtil.isEmpty(s)) { continue; } if ((!s.contains("/")) && (!s.contains(":"))) { s = s + "/32"; } try { trustedProxies.add(new CIDRUtils(s)); } catch (IllegalArgumentException iae) { throw new RuntimeException("Qlue: Invalid proxy subnet: " + s); } } } public boolean isTrustedProxyRequest(TransactionContext context) { if (trustedProxies == null) { return false; } try { InetAddress remoteAddr = InetAddress.getByName(context.request.getRemoteAddr()); for (CIDRUtils su : trustedProxies) { if (su.isInRange(remoteAddr)) { return true; } } } catch (UnknownHostException e) { // Shouldn't happen. e.printStackTrace(System.err); return false; } return false; } /** * Configure the set of IP addresses that are allowed to use development mode. */ protected void setDevelopmentSubnets(String combinedSubnets) throws Exception { if (TextUtil.isEmpty(combinedSubnets)) { return; } String[] subnets = combinedSubnets.split("[;,\\x20]"); developmentSubnets = new ArrayList<>(); for (String s : subnets) { if (TextUtil.isEmpty(s)) { continue; } if ((!s.contains("/")) && (!s.contains(":"))) { s = s + "/32"; } try { developmentSubnets.add(new CIDRUtils(s)); } catch (IllegalArgumentException iae) { throw new RuntimeException("Qlue: Invalid development subnet: " + s); } } } /** * Check if the current transaction comes from an IP address that is allowed * to use development mode. */ public boolean isDeveloperRequest(TransactionContext context) { if (developmentSubnets == null) { return false; } try { InetAddress remoteAddr = InetAddress.getByName(context.getEffectiveRemoteAddr()); for (CIDRUtils su : developmentSubnets) { if (su.isInRange(remoteAddr)) { return true; } } } catch (UnknownHostException e) { // Shouldn't happen. e.printStackTrace(System.err); return false; } return false; } /** * Check if the current transaction comes from a developer. */ public boolean isDevelopmentMode(TransactionContext context) { // Check IP address first if (isDeveloperRequest(context) == false) { return false; } // Check session development mode (explicitly enabled) if (getQlueSession(context.getRequest()).getDevelopmentMode() == QlueConstants.DEVMODE_ENABLED) { return true; } // Check session development mode (explicitly disabled) if (getQlueSession(context.getRequest()).getDevelopmentMode() == QlueConstants.DEVMODE_DISABLED) { return false; } // Check application development mode if (getApplicationDevelopmentMode() == QlueConstants.DEVMODE_ENABLED) { return true; } return false; } /** * Check given password against the current development password. */ public boolean checkDeveloperPassword(String password) { if ((password == null) || (developmentModePassword == null)) { return false; } if (password.compareTo(developmentModePassword) == 0) { return true; } return false; } /** * Get the current development password. */ public String getDeveloperPassword() { return developmentModePassword; } /** * Retrieve this application's properties. */ public Properties getProperties() { return properties; } /** * Retrieve a single named property as text. */ public String getProperty(String key) { return VariableExpander.expand(properties.getProperty(key), properties); } /** * Retrieve a single named property as text, using the supplied default * value if the property is not set. */ public String getProperty(String key, String defaultValue) { String value = getProperty(key); if (value != null) { return value; } else { return defaultValue; } } public Boolean getBooleanProperty(String key) { String value = getProperty(key); if (value == null) { return null; } return Boolean.parseBoolean(value); } public Boolean getBooleanProperty(String key, String defaultValue) { String value = getProperty(key); if (value == null) { return Boolean.parseBoolean(defaultValue); } return Boolean.parseBoolean(value); } /** * Retrieve a single integer property. */ public Integer getIntProperty(String key) { String value = getProperty(key); if (value == null) { return null; } return Integer.parseInt(value); } /** * Retrieve a single integer property, using the supplied default value if * the property is not set. */ public Integer getIntProperty(String key, int defaultValue) { String value = getProperty(key); if (value == null) { return defaultValue; } return Integer.parseInt(value); } /** * Configure the path to the file that contains localized messages. */ protected void setMessagesFilename(String messagesFilename) { this.messagesFilename = messagesFilename; } /** * Retrieve this application's message source. */ public MessageSource getMessageSource(Locale locale) { MessageSource source = messageSources.get(locale); if (source == null) { source = new MessageSource((PropertyResourceBundle) ResourceBundle.getBundle(messagesFilename, locale), locale); messageSources.put(locale, source); } return source; } /** * Remember the current page for later use (e.g., in an error handler). */ void setActualPage(Page page) { page.context.request.setAttribute(REQUEST_ACTUAL_PAGE_KEY, page); } /** * Retrieve the actual page that tried to handle the current transaction and * failed. */ Page getActualPage(Page currentPage) { return (Page) currentPage.context.request.getAttribute(REQUEST_ACTUAL_PAGE_KEY); } /** * Allocates a new page ID. */ synchronized String generateTransactionId() { return UUID.randomUUID().toString(); } public EmailSender getEmailSender() { return asyncSmtpEmailSender; } public EmailSender getAsyncEmailSender() { return asyncSmtpEmailSender; } public EmailSender getSyncEmailSender() { return smtpEmailSender; } public String getConfPath() { return confPath; } public int getFrontendEncryptionCheck() { return frontendEncryptionCheck; } public String getAdminEmail() { return adminEmail; } protected void scheduleTask(Runnable maintenanceTask, Date firstTime, long period) { if (timer == null) { timer = new Timer(); } timer.scheduleAtFixedRate(new RunnableTaskWrapper(maintenanceTask), firstTime, period); } private class SendUrgentRemindersTask implements Runnable { @Override public void run() { try { if ((adminEmail == null) || (urgentEmail == null) || (urgentCounter < 0)) { return; } log.info("Sending urgent reminder: urgentCounter=" + urgentCounter); if (urgentCounter == 0) { // Nothing has happened in the last period; setting // the counter to -1 means that the next exception // will send an urgent email immediately. urgentCounter = -1; } else { // There were a number of exceptions in the last period, // which means that we should send a reminder email. Email email = new SimpleEmail(); email.setCharset("UTF-8"); email.setFrom(adminEmail); email.addTo(urgentEmail); email.setSubject("[" + getAppPrefix() + "] " + "Suppressed " + urgentCounter + " exception(s) in the last period"); try { getEmailSender().send(email); urgentCounter = 0; } catch (Exception e) { log.error("Failed to send email", e); } } } catch (Exception e) { log.error("SendUrgentRemindersTask exception", e); } } } private class RunnableTaskWrapper extends TimerTask { private Runnable task; RunnableTaskWrapper(Runnable task) { this.task = task; } @Override public void run() { task.run(); } } public String getPriorityTemplatePath() { return priorityTemplatePath; } /** * Returns class given its name. * * @param name * @return */ public static Class classForName(String name) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return Class.forName(name, true /* initialize */, classLoader); } catch (ClassNotFoundException e) { return null; } catch (NoClassDefFoundError e) { // NoClassDefFoundError is thrown when there is a class // that matches the name when ignoring case differences. // We do not care about that. return null; } } }
Add remoteAddr and sessionId fields to MDC.
src/com/webkreator/qlue/QlueApplication.java
Add remoteAddr and sessionId fields to MDC.
<ide><path>rc/com/webkreator/qlue/QlueApplication.java <ide> request, <ide> response); <ide> <del> // Create a logging context using the unique transaction ID. <add> // Expose transaction information to the logging subsystem. <ide> MDC.put("txId", context.getTxId()); <add> MDC.put("remoteAddr", context.getEffectiveRemoteAddr()); <add> MDC.put("sessionId", context.getSession().getId()); <ide> <ide> // Proceed to the second stage of request processing <ide> try {
Java
apache-2.0
cca101fafa9b7ecfa4f03d01a724853b2e1531d1
0
hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly
package com.firefly.net.tcp.aio; import com.codahale.metrics.MetricRegistry; import com.firefly.net.*; import com.firefly.net.buffer.AdaptiveBufferSizePredictor; import com.firefly.net.buffer.FileRegion; import com.firefly.net.exception.NetException; import com.firefly.net.tcp.aio.metric.SessionMetric; import com.firefly.utils.concurrent.Callback; import com.firefly.utils.io.BufferUtils; import com.firefly.utils.time.Millisecond100Clock; import com.firefly.utils.time.SafeSimpleDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class AsynchronousTcpSession implements Session { private static Logger log = LoggerFactory.getLogger("firefly-system"); private final int sessionId; private final long openTime; private long closeTime; private long lastReadTime; private long lastWrittenTime; private long readBytes = 0; private long writtenBytes = 0; private final SessionMetric sessionMetric; private final AtomicBoolean closed = new AtomicBoolean(false); private final AtomicBoolean shutdownOutput = new AtomicBoolean(false); private final AtomicBoolean shutdownInput = new AtomicBoolean(false); private final AtomicBoolean waitingForClose = new AtomicBoolean(false); private final AsynchronousSocketChannel socketChannel; private volatile InetSocketAddress localAddress; private volatile InetSocketAddress remoteAddress; private final Config config; private final EventManager eventManager; private volatile Object attachment; private final Lock outputLock = new ReentrantLock(); private boolean isWriting = false; private final Queue<OutputEntry<?>> outputBuffer = new LinkedList<>(); private final BufferSizePredictor bufferSizePredictor = new AdaptiveBufferSizePredictor(); AsynchronousTcpSession(int sessionId, Config config, EventManager eventManager, AsynchronousSocketChannel socketChannel) { this.sessionId = sessionId; this.openTime = Millisecond100Clock.currentTimeMillis(); this.config = config; this.eventManager = eventManager; this.socketChannel = socketChannel; MetricRegistry metrics = config.getMetricReporterFactory().getMetricRegistry(); sessionMetric = new SessionMetric(metrics, "aio.tcpSession"); sessionMetric.getActiveSessionCount().inc(); } private ByteBuffer allocateReadBuffer() { int size = BufferUtils.normalizeBufferSize(bufferSizePredictor.nextBufferSize()); sessionMetric.getAllocatedInputBufferSize().update(size); return ByteBuffer.allocate(size); } void _read() { try { final ByteBuffer buf = allocateReadBuffer(); if (log.isDebugEnabled()) { log.debug("The session {} allocates buffer. Its size is {}", getSessionId(), buf.remaining()); } socketChannel.read(buf, config.getTimeout(), TimeUnit.MILLISECONDS, this, new InputCompletionHandler(buf)); } catch (Exception e) { log.warn("register read event exception. {}", e.getMessage()); closeNow(); } } private class InputCompletionHandler implements CompletionHandler<Integer, AsynchronousTcpSession> { private final ByteBuffer buf; private InputCompletionHandler(ByteBuffer buf) { this.buf = buf; } @Override public void completed(Integer currentReadBytes, AsynchronousTcpSession session) { session.lastReadTime = Millisecond100Clock.currentTimeMillis(); if (currentReadBytes < 0) { log.info("The session {} input channel is shutdown, {}", session.getSessionId(), currentReadBytes); session.closeNow(); return; } if (log.isDebugEnabled()) { log.debug("The session {} read {} bytes", session.getSessionId(), currentReadBytes); } // Update the predictor. session.bufferSizePredictor.previousReceivedBufferSize(currentReadBytes); session.readBytes += currentReadBytes; buf.flip(); try { config.getDecoder().decode(buf, session); } catch (Throwable t) { eventManager.executeExceptionTask(session, t); } finally { _read(); } } @Override public void failed(Throwable t, AsynchronousTcpSession session) { if (t instanceof InterruptedByTimeoutException) { long idleTime = getIdleTimeout(); log.info("The session {} reading data is timeout. The idle time: {} - {}", getSessionId(), idleTime, getMaxIdleTimeout()); if (idleTime >= getIdleTimeout()) { log.info("The session {} is timeout. It will force to close.", getSessionId()); closeNow(); } else { // The session is active. Register the read event. _read(); } } else { log.warn("The session {} reading data exception. It will force to close.", t, session.getSessionId()); closeNow(); } } } private class OutputEntryCompletionHandler<V extends Number, T> implements CompletionHandler<V, AsynchronousTcpSession> { private final OutputEntry<T> entry; private OutputEntryCompletionHandler(OutputEntry<T> entry) { this.entry = entry; } @Override public void completed(V currentWrittenBytes, AsynchronousTcpSession session) { lastWrittenTime = Millisecond100Clock.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("The session {} completed writing {} bytes, remaining {} bytes", session.getSessionId(), currentWrittenBytes, entry.remaining()); } long w = currentWrittenBytes.longValue(); if (w < 0) { log.info("The session {} output channel is shutdown, {}", getSessionId(), currentWrittenBytes); closeNow(); return; } if (log.isDebugEnabled()) { log.debug("The session {} writes {} bytes", getSessionId(), currentWrittenBytes); } writtenBytes += w; if (entry.remaining() > 0) { _write(entry); } else { writingCompletedCallback(entry.getCallback()); } } @Override public void failed(Throwable t, AsynchronousTcpSession session) { writingFailedCallback(entry.getCallback(), t); } private void writingCompletedCallback(Callback callback) { callback.succeeded(); OutputEntry<?> entry = getNextOutputEntry(); if (entry != null) { _write(entry); } } private OutputEntry<?> getNextOutputEntry() { OutputEntry<?> entry = null; outputLock.lock(); try { sessionMetric.getOutputBufferQueueSize().update(outputBuffer.size()); if (outputBuffer.isEmpty()) { isWriting = false; } else { List<OutputEntry<?>> entries = new LinkedList<>(); OutputEntry<?> obj; boolean disconnection = false; while ((obj = outputBuffer.poll()) != null) { if (disconnection) { log.warn("The session {} is waiting close. The entry [{}/{}] will discard", getSessionId(), obj.getOutputEntryType(), obj.remaining()); continue; } if (obj.getOutputEntryType() != OutputEntryType.DISCONNECTION) { entries.add(obj); } else { disconnection = true; } } if (disconnection) { outputBuffer.offer(DISCONNECTION_FLAG); } if (entries.isEmpty()) { if (!outputBuffer.isEmpty()) { obj = outputBuffer.peek(); if (obj.getOutputEntryType() == OutputEntryType.DISCONNECTION) { entry = DISCONNECTION_FLAG; outputBuffer.poll(); } } } else { if (entries.size() == 1) { entry = entries.get(0); } else { // merge ByteBuffer to ByteBuffer Array List<Callback> callbackList = new LinkedList<>(); List<ByteBuffer> byteBufferList = new LinkedList<>(); entries.forEach(e -> { callbackList.add(e.getCallback()); switch (e.getOutputEntryType()) { case BYTE_BUFFER: ByteBufferOutputEntry byteBufferOutputEntry = (ByteBufferOutputEntry) e; byteBufferList.add(byteBufferOutputEntry.getData()); break; case BYTE_BUFFER_ARRAY: ByteBufferArrayOutputEntry byteBufferArrayOutputEntry = (ByteBufferArrayOutputEntry) e; byteBufferList.addAll(Arrays.asList(byteBufferArrayOutputEntry.getData())); break; case MERGED_BUFFER: MergedOutputEntry mergedOutputEntry = (MergedOutputEntry) e; byteBufferList.addAll(Arrays.asList(mergedOutputEntry.getData())); break; } }); sessionMetric.getMergedOutputBufferSize().update(callbackList.size()); entry = new MergedOutputEntry(callbackList, byteBufferList); } } } } finally { outputLock.unlock(); } return entry; } private void writingFailedCallback(Callback callback, Throwable t) { if (t instanceof InterruptedByTimeoutException) { long idleTime = getIdleTimeout(); log.info("The session {} writing data is timeout. The idle time: {} - {}", getSessionId(), idleTime, getMaxIdleTimeout()); if (idleTime >= getIdleTimeout()) { log.info("The session {} is timeout. It will close.", getSessionId()); _writingFailedCallback(callback, t); } } else { log.warn("The session {} writing data exception. It will close.", t, getSessionId()); _writingFailedCallback(callback, t); } } private void _writingFailedCallback(Callback callback, Throwable t) { outputLock.lock(); try { int bufferSize = outputBuffer.size(); log.warn("The session {} has {} buffer data can not output", getSessionId(), bufferSize); outputBuffer.clear(); isWriting = false; shutdownSocketChannel(); } finally { outputLock.unlock(); } callback.failed(t); } } private void _write(final OutputEntry<?> entry) { try { switch (entry.getOutputEntryType()) { case BYTE_BUFFER: { ByteBufferOutputEntry byteBufferOutputEntry = (ByteBufferOutputEntry) entry; socketChannel.write(byteBufferOutputEntry.getData(), config.getTimeout(), TimeUnit.MILLISECONDS, this, new OutputEntryCompletionHandler<>(byteBufferOutputEntry)); } break; case BYTE_BUFFER_ARRAY: { ByteBufferArrayOutputEntry byteBuffersEntry = (ByteBufferArrayOutputEntry) entry; socketChannel.write(byteBuffersEntry.getData(), 0, byteBuffersEntry.getData().length, config.getTimeout(), TimeUnit.MILLISECONDS, this, new OutputEntryCompletionHandler<>(byteBuffersEntry)); } break; case MERGED_BUFFER: { MergedOutputEntry mergedOutputEntry = (MergedOutputEntry) entry; socketChannel.write(mergedOutputEntry.getData(), 0, mergedOutputEntry.getData().length, config.getTimeout(), TimeUnit.MILLISECONDS, this, new OutputEntryCompletionHandler<>(mergedOutputEntry)); } break; case DISCONNECTION: { log.info("The session {} has completed output. It will close.", getSessionId()); shutdownSocketChannel(); } break; default: throw new NetException("unknown output entry type"); } } catch (Exception e) { log.warn("register write event exception. {}", e.getMessage()); shutdownSocketChannel(); } } @Override public void write(OutputEntry<?> entry) { if (entry == null) { return; } if (waitingForClose.get() && entry.getOutputEntryType() != OutputEntryType.DISCONNECTION) { log.warn("The session {} is waiting for close. The entry [{}/{}] can not write to remote endpoint.", getSessionId(), entry.getOutputEntryType(), entry.remaining()); return; } boolean writeEntry = false; outputLock.lock(); try { if (!isWriting) { isWriting = true; writeEntry = true; } else { outputBuffer.offer(entry); } } finally { outputLock.unlock(); } if (writeEntry) { _write(entry); } } @Override public void write(ByteBuffer byteBuffer, Callback callback) { write(new ByteBufferOutputEntry(callback, byteBuffer)); } @Override public void write(ByteBuffer[] buffers, Callback callback) { write(new ByteBufferArrayOutputEntry(callback, buffers)); } @Override public void write(Collection<ByteBuffer> buffers, Callback callback) { write(new ByteBufferArrayOutputEntry(callback, buffers.toArray(BufferUtils.EMPTY_BYTE_BUFFER_ARRAY))); } @Override public void write(FileRegion file, Callback callback) { try (FileRegion fileRegion = file) { fileRegion.transferTo(callback, (buf, countingCallback, count) -> write(buf, countingCallback)); } catch (Throwable t) { log.error("transfer file error", t); } } @Override public void attachObject(Object attachment) { this.attachment = attachment; } @Override public Object getAttachment() { return attachment; } @Override public void onReceivingMessage(Object message) { eventManager.executeReceiveTask(this, message); } @Override public void encode(Object message) { try { config.getEncoder().encode(message, this); } catch (Throwable t) { eventManager.executeExceptionTask(this, t); } } @Override public void close() { if (waitingForClose.compareAndSet(false, true) && isOpen()) { write(DISCONNECTION_FLAG); log.info("The session {} is waiting for close", sessionId); } else { log.info("The session {} is already waiting for close", sessionId); } } @Override public void closeNow() { if (closed.compareAndSet(false, true)) { closeTime = Millisecond100Clock.currentTimeMillis(); try { socketChannel.close(); log.info("The session {} closed", sessionId); } catch (AsynchronousCloseException e) { log.warn("The session {} asynchronously close exception", sessionId); } catch (IOException e) { log.error("The session " + sessionId + " close exception", e); } finally { eventManager.executeCloseTask(this); sessionMetric.getActiveSessionCount().dec(); sessionMetric.getDuration().update(getDuration()); } } else { log.info("The session {} already closed", sessionId); } } @Override public void shutdownOutput() { if (shutdownOutput.compareAndSet(false, true)) { try { socketChannel.shutdownOutput(); log.info("The session {} is shutdown output", sessionId); } catch (ClosedChannelException e) { log.warn("Shutdown output exception. The session {} is closed", sessionId); } catch (IOException e) { log.error("The session {} shutdown output I/O exception. {}", sessionId, e.getMessage()); } } else { log.info("The session {} is already shutdown output", sessionId); } } @Override public void shutdownInput() { if (shutdownInput.compareAndSet(false, true)) { try { socketChannel.shutdownInput(); log.info("The session {} is shutdown input", sessionId); } catch (ClosedChannelException e) { log.warn("Shutdown input exception. The session {} is closed", sessionId); } catch (IOException e) { log.error("The session {} shutdown input I/O exception. {}", sessionId, e.getMessage()); } } else { log.info("The session {} is already shutdown input", sessionId); } } private void shutdownSocketChannel() { shutdownOutput(); shutdownInput(); } @Override public int getSessionId() { return sessionId; } @Override public long getOpenTime() { return openTime; } @Override public long getCloseTime() { return closeTime; } @Override public long getDuration() { if (closeTime > 0) { return closeTime - openTime; } else { return Millisecond100Clock.currentTimeMillis() - openTime; } } @Override public long getLastReadTime() { return lastReadTime; } @Override public long getLastWrittenTime() { return lastWrittenTime; } @Override public long getLastActiveTime() { return Math.max(Math.max(lastReadTime, lastWrittenTime), openTime); } @Override public long getReadBytes() { return readBytes; } @Override public long getWrittenBytes() { return writtenBytes; } @Override public boolean isOpen() { return !closed.get(); } @Override public boolean isClosed() { return closed.get(); } @Override public boolean isShutdownOutput() { return shutdownOutput.get(); } @Override public boolean isShutdownInput() { return shutdownInput.get(); } @Override public boolean isWaitingForClose() { return waitingForClose.get(); } @Override public InetSocketAddress getLocalAddress() { if (localAddress != null) { return localAddress; } else { try { localAddress = (InetSocketAddress) socketChannel.getLocalAddress(); return localAddress; } catch (IOException e) { log.error("The session {} gets local address error", e, sessionId); return null; } } } @Override public InetSocketAddress getRemoteAddress() { if (remoteAddress != null) { return remoteAddress; } else { try { remoteAddress = (InetSocketAddress) socketChannel.getRemoteAddress(); return remoteAddress; } catch (Throwable t) { log.error("The session {} gets remote address error", t, sessionId); return null; } } } @Override public long getIdleTimeout() { return Millisecond100Clock.currentTimeMillis() - getLastActiveTime(); } @Override public long getMaxIdleTimeout() { return config.getTimeout(); } @Override public String toString() { return "[sessionId=" + sessionId + ", openTime=" + SafeSimpleDateFormat.defaultDateFormat.format(new Date(openTime)) + ", closeTime=" + SafeSimpleDateFormat.defaultDateFormat.format(new Date(closeTime)) + ", duration=" + getDuration() + ", readBytes=" + readBytes + ", writtenBytes=" + writtenBytes + "]"; } }
firefly-nettool/src/main/java/com/firefly/net/tcp/aio/AsynchronousTcpSession.java
package com.firefly.net.tcp.aio; import com.codahale.metrics.MetricRegistry; import com.firefly.net.*; import com.firefly.net.buffer.AdaptiveBufferSizePredictor; import com.firefly.net.buffer.FileRegion; import com.firefly.net.exception.NetException; import com.firefly.net.tcp.aio.metric.SessionMetric; import com.firefly.utils.concurrent.Callback; import com.firefly.utils.io.BufferUtils; import com.firefly.utils.time.Millisecond100Clock; import com.firefly.utils.time.SafeSimpleDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class AsynchronousTcpSession implements Session { private static Logger log = LoggerFactory.getLogger("firefly-system"); private final int sessionId; private final long openTime; private long closeTime; private long lastReadTime; private long lastWrittenTime; private long readBytes = 0; private long writtenBytes = 0; private final SessionMetric sessionMetric; private final AtomicBoolean closed = new AtomicBoolean(false); private final AtomicBoolean shutdownOutput = new AtomicBoolean(false); private final AtomicBoolean shutdownInput = new AtomicBoolean(false); private final AtomicBoolean waitingForClose = new AtomicBoolean(false); private final AsynchronousSocketChannel socketChannel; private volatile InetSocketAddress localAddress; private volatile InetSocketAddress remoteAddress; private final Config config; private final EventManager eventManager; private volatile Object attachment; private final Lock outputLock = new ReentrantLock(); private boolean isWriting = false; private final Queue<OutputEntry<?>> outputBuffer = new LinkedList<>(); private final BufferSizePredictor bufferSizePredictor = new AdaptiveBufferSizePredictor(); AsynchronousTcpSession(int sessionId, Config config, EventManager eventManager, AsynchronousSocketChannel socketChannel) { this.sessionId = sessionId; this.openTime = Millisecond100Clock.currentTimeMillis(); this.config = config; this.eventManager = eventManager; this.socketChannel = socketChannel; MetricRegistry metrics = config.getMetricReporterFactory().getMetricRegistry(); sessionMetric = new SessionMetric(metrics, "aio.tcpSession"); sessionMetric.getActiveSessionCount().inc(); } private ByteBuffer allocateReadBuffer() { int size = BufferUtils.normalizeBufferSize(bufferSizePredictor.nextBufferSize()); sessionMetric.getAllocatedInputBufferSize().update(size); return ByteBuffer.allocate(size); } void _read() { try { final ByteBuffer buf = allocateReadBuffer(); if (log.isDebugEnabled()) { log.debug("The session {} allocates buffer. Its size is {}", getSessionId(), buf.remaining()); } socketChannel.read(buf, config.getTimeout(), TimeUnit.MILLISECONDS, this, new InputCompletionHandler(buf)); } catch (Exception e) { log.warn("register read event exception. {}", e.getMessage()); closeNow(); } } private class InputCompletionHandler implements CompletionHandler<Integer, AsynchronousTcpSession> { private final ByteBuffer buf; private InputCompletionHandler(ByteBuffer buf) { this.buf = buf; } @Override public void completed(Integer currentReadBytes, AsynchronousTcpSession session) { session.lastReadTime = Millisecond100Clock.currentTimeMillis(); if (currentReadBytes < 0) { log.info("The session {} input channel is shutdown, {}", session.getSessionId(), currentReadBytes); session.closeNow(); return; } if (log.isDebugEnabled()) { log.debug("The session {} read {} bytes", session.getSessionId(), currentReadBytes); } // Update the predictor. session.bufferSizePredictor.previousReceivedBufferSize(currentReadBytes); session.readBytes += currentReadBytes; buf.flip(); try { config.getDecoder().decode(buf, session); } catch (Throwable t) { eventManager.executeExceptionTask(session, t); } finally { _read(); } } @Override public void failed(Throwable t, AsynchronousTcpSession session) { if (t instanceof InterruptedByTimeoutException) { long idleTime = getIdleTimeout(); log.info("The session {} reading data is timeout. The idle time: {} - {}", getSessionId(), idleTime, getMaxIdleTimeout()); if (idleTime >= getIdleTimeout()) { log.info("The session {} is timeout. It will force to close.", getSessionId()); closeNow(); } else { // The session is active. Register the read event. _read(); } } else { log.warn("The session {} reading data exception. It will force to close.", t, session.getSessionId()); closeNow(); } } } private class OutputEntryCompletionHandler<V extends Number, T> implements CompletionHandler<V, AsynchronousTcpSession> { private final OutputEntry<T> entry; private OutputEntryCompletionHandler(OutputEntry<T> entry) { this.entry = entry; } @Override public void completed(V currentWrittenBytes, AsynchronousTcpSession session) { lastWrittenTime = Millisecond100Clock.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("The session {} completed writing {} bytes, remaining {} bytes", session.getSessionId(), currentWrittenBytes, entry.remaining()); } long w = currentWrittenBytes.longValue(); if (w < 0) { log.info("The session {} output channel is shutdown, {}", getSessionId(), currentWrittenBytes); closeNow(); return; } if (log.isDebugEnabled()) { log.debug("The session {} writes {} bytes", getSessionId(), currentWrittenBytes); } writtenBytes += w; if (entry.remaining() > 0) { _write(entry); } else { writingCompletedCallback(entry.getCallback()); } } @Override public void failed(Throwable t, AsynchronousTcpSession session) { writingFailedCallback(entry.getCallback(), t); } private void writingCompletedCallback(Callback callback) { callback.succeeded(); OutputEntry<?> entry = null; outputLock.lock(); try { sessionMetric.getOutputBufferQueueSize().update(outputBuffer.size()); if (outputBuffer.isEmpty()) { isWriting = false; } else if (outputBuffer.size() <= 2) { entry = outputBuffer.poll(); } else { // merge ByteBuffer to ByteBuffer Array List<Callback> callbackList = new LinkedList<>(); List<ByteBuffer> byteBufferList = new LinkedList<>(); OutputEntry<?> obj; boolean disconnection = false; while ((obj = outputBuffer.poll()) != null) { if (disconnection) { log.warn("The session {} is waiting close. The entry [{}/{}] will discard", getSessionId(), obj.getOutputEntryType(), obj.remaining()); continue; } if (obj.getOutputEntryType() != OutputEntryType.DISCONNECTION) { callbackList.add(obj.getCallback()); switch (obj.getOutputEntryType()) { case BYTE_BUFFER: ByteBufferOutputEntry byteBufferOutputEntry = (ByteBufferOutputEntry) obj; byteBufferList.add(byteBufferOutputEntry.getData()); break; case BYTE_BUFFER_ARRAY: ByteBufferArrayOutputEntry byteBufferArrayOutputEntry = (ByteBufferArrayOutputEntry) obj; byteBufferList.addAll(Arrays.asList(byteBufferArrayOutputEntry.getData())); break; case MERGED_BUFFER: MergedOutputEntry mergedOutputEntry = (MergedOutputEntry) obj; byteBufferList.addAll(Arrays.asList(mergedOutputEntry.getData())); break; } } else { disconnection = true; } } if (disconnection) { outputBuffer.offer(DISCONNECTION_FLAG); } sessionMetric.getMergedOutputBufferSize().update(callbackList.size()); entry = new MergedOutputEntry(callbackList, byteBufferList); } } finally { outputLock.unlock(); } if (entry != null) { _write(entry); } } private void writingFailedCallback(Callback callback, Throwable t) { if (t instanceof InterruptedByTimeoutException) { long idleTime = getIdleTimeout(); log.info("The session {} writing data is timeout. The idle time: {} - {}", getSessionId(), idleTime, getMaxIdleTimeout()); if (idleTime >= getIdleTimeout()) { log.info("The session {} is timeout. It will close.", getSessionId()); _writingFailedCallback(callback, t); } } else { log.warn("The session {} writing data exception. It will close.", t, getSessionId()); _writingFailedCallback(callback, t); } } private void _writingFailedCallback(Callback callback, Throwable t) { outputLock.lock(); try { int bufferSize = outputBuffer.size(); log.warn("The session {} has {} buffer data can not output", getSessionId(), bufferSize); outputBuffer.clear(); isWriting = false; shutdownSocketChannel(); } finally { outputLock.unlock(); } callback.failed(t); } } private void _write(final OutputEntry<?> entry) { try { switch (entry.getOutputEntryType()) { case BYTE_BUFFER: { ByteBufferOutputEntry byteBufferOutputEntry = (ByteBufferOutputEntry) entry; socketChannel.write(byteBufferOutputEntry.getData(), config.getTimeout(), TimeUnit.MILLISECONDS, this, new OutputEntryCompletionHandler<>(byteBufferOutputEntry)); } break; case BYTE_BUFFER_ARRAY: { ByteBufferArrayOutputEntry byteBuffersEntry = (ByteBufferArrayOutputEntry) entry; socketChannel.write(byteBuffersEntry.getData(), 0, byteBuffersEntry.getData().length, config.getTimeout(), TimeUnit.MILLISECONDS, this, new OutputEntryCompletionHandler<>(byteBuffersEntry)); } break; case MERGED_BUFFER: { MergedOutputEntry mergedOutputEntry = (MergedOutputEntry) entry; socketChannel.write(mergedOutputEntry.getData(), 0, mergedOutputEntry.getData().length, config.getTimeout(), TimeUnit.MILLISECONDS, this, new OutputEntryCompletionHandler<>(mergedOutputEntry)); } break; case DISCONNECTION: { log.info("The session {} has completed output. It will close.", getSessionId()); shutdownSocketChannel(); } break; default: throw new NetException("unknown output entry type"); } } catch (Exception e) { log.warn("register write event exception. {}", e.getMessage()); shutdownSocketChannel(); } } @Override public void write(OutputEntry<?> entry) { if (entry == null) { return; } if (waitingForClose.get() && entry.getOutputEntryType() != OutputEntryType.DISCONNECTION) { log.warn("The session {} is waiting for close. The entry [{}/{}] can not write to remote endpoint.", getSessionId(), entry.getOutputEntryType(), entry.remaining()); return; } boolean writeEntry = false; outputLock.lock(); try { if (!isWriting) { isWriting = true; writeEntry = true; } else { outputBuffer.offer(entry); } } finally { outputLock.unlock(); } if (writeEntry) { _write(entry); } } @Override public void write(ByteBuffer byteBuffer, Callback callback) { write(new ByteBufferOutputEntry(callback, byteBuffer)); } @Override public void write(ByteBuffer[] buffers, Callback callback) { write(new ByteBufferArrayOutputEntry(callback, buffers)); } @Override public void write(Collection<ByteBuffer> buffers, Callback callback) { write(new ByteBufferArrayOutputEntry(callback, buffers.toArray(BufferUtils.EMPTY_BYTE_BUFFER_ARRAY))); } @Override public void write(FileRegion file, Callback callback) { try (FileRegion fileRegion = file) { fileRegion.transferTo(callback, (buf, countingCallback, count) -> write(buf, countingCallback)); } catch (Throwable t) { log.error("transfer file error", t); } } @Override public void attachObject(Object attachment) { this.attachment = attachment; } @Override public Object getAttachment() { return attachment; } @Override public void onReceivingMessage(Object message) { eventManager.executeReceiveTask(this, message); } @Override public void encode(Object message) { try { config.getEncoder().encode(message, this); } catch (Throwable t) { eventManager.executeExceptionTask(this, t); } } @Override public void close() { if (waitingForClose.compareAndSet(false, true) && isOpen()) { write(DISCONNECTION_FLAG); log.info("The session {} is waiting for close", sessionId); } else { log.info("The session {} is already waiting for close", sessionId); } } @Override public void closeNow() { if (closed.compareAndSet(false, true)) { closeTime = Millisecond100Clock.currentTimeMillis(); try { socketChannel.close(); log.info("The session {} closed", sessionId); } catch (AsynchronousCloseException e) { log.warn("The session {} asynchronously close exception", sessionId); } catch (IOException e) { log.error("The session " + sessionId + " close exception", e); } finally { eventManager.executeCloseTask(this); sessionMetric.getActiveSessionCount().dec(); sessionMetric.getDuration().update(getDuration()); } } else { log.info("The session {} already closed", sessionId); } } @Override public void shutdownOutput() { if (shutdownOutput.compareAndSet(false, true)) { try { socketChannel.shutdownOutput(); log.info("The session {} is shutdown output", sessionId); } catch (ClosedChannelException e) { log.warn("Shutdown output exception. The session {} is closed", sessionId); } catch (IOException e) { log.error("The session {} shutdown output I/O exception. {}", sessionId, e.getMessage()); } } else { log.info("The session {} is already shutdown output", sessionId); } } @Override public void shutdownInput() { if (shutdownInput.compareAndSet(false, true)) { try { socketChannel.shutdownInput(); log.info("The session {} is shutdown input", sessionId); } catch (ClosedChannelException e) { log.warn("Shutdown input exception. The session {} is closed", sessionId); } catch (IOException e) { log.error("The session {} shutdown input I/O exception. {}", sessionId, e.getMessage()); } } else { log.info("The session {} is already shutdown input", sessionId); } } private void shutdownSocketChannel() { shutdownOutput(); shutdownInput(); } @Override public int getSessionId() { return sessionId; } @Override public long getOpenTime() { return openTime; } @Override public long getCloseTime() { return closeTime; } @Override public long getDuration() { if (closeTime > 0) { return closeTime - openTime; } else { return Millisecond100Clock.currentTimeMillis() - openTime; } } @Override public long getLastReadTime() { return lastReadTime; } @Override public long getLastWrittenTime() { return lastWrittenTime; } @Override public long getLastActiveTime() { return Math.max(Math.max(lastReadTime, lastWrittenTime), openTime); } @Override public long getReadBytes() { return readBytes; } @Override public long getWrittenBytes() { return writtenBytes; } @Override public boolean isOpen() { return !closed.get(); } @Override public boolean isClosed() { return closed.get(); } @Override public boolean isShutdownOutput() { return shutdownOutput.get(); } @Override public boolean isShutdownInput() { return shutdownInput.get(); } @Override public boolean isWaitingForClose() { return waitingForClose.get(); } @Override public InetSocketAddress getLocalAddress() { if (localAddress != null) { return localAddress; } else { try { localAddress = (InetSocketAddress) socketChannel.getLocalAddress(); return localAddress; } catch (IOException e) { log.error("The session {} gets local address error", e, sessionId); return null; } } } @Override public InetSocketAddress getRemoteAddress() { if (remoteAddress != null) { return remoteAddress; } else { try { remoteAddress = (InetSocketAddress) socketChannel.getRemoteAddress(); return remoteAddress; } catch (Throwable t) { log.error("The session {} gets remote address error", t, sessionId); return null; } } } @Override public long getIdleTimeout() { return Millisecond100Clock.currentTimeMillis() - getLastActiveTime(); } @Override public long getMaxIdleTimeout() { return config.getTimeout(); } @Override public String toString() { return "[sessionId=" + sessionId + ", openTime=" + SafeSimpleDateFormat.defaultDateFormat.format(new Date(openTime)) + ", closeTime=" + SafeSimpleDateFormat.defaultDateFormat.format(new Date(closeTime)) + ", duration=" + getDuration() + ", readBytes=" + readBytes + ", writtenBytes=" + writtenBytes + "]"; } }
[fix]: the disconnection event can not be triggered
firefly-nettool/src/main/java/com/firefly/net/tcp/aio/AsynchronousTcpSession.java
[fix]: the disconnection event can not be triggered
<ide><path>irefly-nettool/src/main/java/com/firefly/net/tcp/aio/AsynchronousTcpSession.java <ide> <ide> private void writingCompletedCallback(Callback callback) { <ide> callback.succeeded(); <add> OutputEntry<?> entry = getNextOutputEntry(); <add> if (entry != null) { <add> _write(entry); <add> } <add> } <add> <add> private OutputEntry<?> getNextOutputEntry() { <ide> OutputEntry<?> entry = null; <ide> outputLock.lock(); <ide> try { <ide> sessionMetric.getOutputBufferQueueSize().update(outputBuffer.size()); <ide> if (outputBuffer.isEmpty()) { <ide> isWriting = false; <del> } else if (outputBuffer.size() <= 2) { <del> entry = outputBuffer.poll(); <ide> } else { <del> // merge ByteBuffer to ByteBuffer Array <del> List<Callback> callbackList = new LinkedList<>(); <del> List<ByteBuffer> byteBufferList = new LinkedList<>(); <add> List<OutputEntry<?>> entries = new LinkedList<>(); <add> <ide> OutputEntry<?> obj; <ide> boolean disconnection = false; <ide> while ((obj = outputBuffer.poll()) != null) { <ide> continue; <ide> } <ide> if (obj.getOutputEntryType() != OutputEntryType.DISCONNECTION) { <del> callbackList.add(obj.getCallback()); <del> switch (obj.getOutputEntryType()) { <del> case BYTE_BUFFER: <del> ByteBufferOutputEntry byteBufferOutputEntry = (ByteBufferOutputEntry) obj; <del> byteBufferList.add(byteBufferOutputEntry.getData()); <del> break; <del> case BYTE_BUFFER_ARRAY: <del> ByteBufferArrayOutputEntry byteBufferArrayOutputEntry = (ByteBufferArrayOutputEntry) obj; <del> byteBufferList.addAll(Arrays.asList(byteBufferArrayOutputEntry.getData())); <del> break; <del> case MERGED_BUFFER: <del> MergedOutputEntry mergedOutputEntry = (MergedOutputEntry) obj; <del> byteBufferList.addAll(Arrays.asList(mergedOutputEntry.getData())); <del> break; <del> } <add> entries.add(obj); <ide> } else { <ide> disconnection = true; <ide> } <ide> if (disconnection) { <ide> outputBuffer.offer(DISCONNECTION_FLAG); <ide> } <del> sessionMetric.getMergedOutputBufferSize().update(callbackList.size()); <del> entry = new MergedOutputEntry(callbackList, byteBufferList); <add> <add> if (entries.isEmpty()) { <add> if (!outputBuffer.isEmpty()) { <add> obj = outputBuffer.peek(); <add> if (obj.getOutputEntryType() == OutputEntryType.DISCONNECTION) { <add> entry = DISCONNECTION_FLAG; <add> outputBuffer.poll(); <add> } <add> } <add> } else { <add> if (entries.size() == 1) { <add> entry = entries.get(0); <add> } else { <add> // merge ByteBuffer to ByteBuffer Array <add> List<Callback> callbackList = new LinkedList<>(); <add> List<ByteBuffer> byteBufferList = new LinkedList<>(); <add> entries.forEach(e -> { <add> callbackList.add(e.getCallback()); <add> switch (e.getOutputEntryType()) { <add> case BYTE_BUFFER: <add> ByteBufferOutputEntry byteBufferOutputEntry = (ByteBufferOutputEntry) e; <add> byteBufferList.add(byteBufferOutputEntry.getData()); <add> break; <add> case BYTE_BUFFER_ARRAY: <add> ByteBufferArrayOutputEntry byteBufferArrayOutputEntry = (ByteBufferArrayOutputEntry) e; <add> byteBufferList.addAll(Arrays.asList(byteBufferArrayOutputEntry.getData())); <add> break; <add> case MERGED_BUFFER: <add> MergedOutputEntry mergedOutputEntry = (MergedOutputEntry) e; <add> byteBufferList.addAll(Arrays.asList(mergedOutputEntry.getData())); <add> break; <add> } <add> }); <add> sessionMetric.getMergedOutputBufferSize().update(callbackList.size()); <add> entry = new MergedOutputEntry(callbackList, byteBufferList); <add> } <add> } <ide> } <ide> } finally { <ide> outputLock.unlock(); <ide> } <del> if (entry != null) { <del> _write(entry); <del> } <add> return entry; <ide> } <ide> <ide> private void writingFailedCallback(Callback callback, Throwable t) {
Java
apache-2.0
8c93c7fb54bd04b55a7ae6619685d5ae539ea270
0
jcam3ron/cassandra-migration,jcam3ron/cassandra-migration,jcam3ron/cassandra-migration
/** * File : SchemaVersionDAO.Java * License : * Original - Copyright (c) 2015 - 2016 Contrast Security * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.builtamont.cassandra.migration.internal.dbsupport; import com.builtamont.cassandra.migration.api.MigrationType; import com.builtamont.cassandra.migration.api.MigrationVersion; import com.builtamont.cassandra.migration.config.Keyspace; import com.builtamont.cassandra.migration.internal.metadatatable.AppliedMigration; import com.builtamont.cassandra.migration.internal.util.CachePrepareStatement; import com.builtamont.cassandra.migration.internal.util.logging.Log; import com.builtamont.cassandra.migration.internal.util.logging.LogFactory; import com.datastax.driver.core.*; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Select; import java.util.*; import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; /** * Schema migrations table Data Access Object. */ // TODO: Convert to Kotlin code... Some challenges with Mockito mocking :) public class SchemaVersionDAO { private static final Log LOG = LogFactory.INSTANCE.getLog(SchemaVersionDAO.class); private static final String COUNTS_TABLE_NAME_SUFFIX = "_counts"; private Session session; private Keyspace keyspace; private String tableName; private CachePrepareStatement cachePs; private ConsistencyLevel consistencyLevel; /** * Creates a new schema version DAO. * * @param session The Cassandra session connection to use to execute the migration. * @param keyspace The Cassandra keyspace to connect to. * @param tableName The Cassandra migration version table name. */ public SchemaVersionDAO(Session session, Keyspace keyspace, String tableName) { this.session = session; this.keyspace = keyspace; this.tableName = tableName; this.cachePs = new CachePrepareStatement(session); // If running on a single host, don't force ConsistencyLevel.ALL boolean isClustered = session.getCluster().getMetadata().getAllHosts().size() > 1; this.consistencyLevel = isClustered ? ConsistencyLevel.ALL : ConsistencyLevel.ONE; } public String getTableName() { return tableName; } public Keyspace getKeyspace() { return this.keyspace; } /** * Create schema migration version table if it does not exists. */ public void createTablesIfNotExist() { if (tablesExist()) { return; } Statement statement = new SimpleStatement( "CREATE TABLE IF NOT EXISTS " + keyspace.getName() + "." + tableName + "(" + " version_rank int," + " installed_rank int," + " version text," + " description text," + " script text," + " checksum int," + " type text," + " installed_by text," + " installed_on timestamp," + " execution_time int," + " success boolean," + " PRIMARY KEY (version)" + ");"); statement.setConsistencyLevel(this.consistencyLevel); session.execute(statement); statement = new SimpleStatement( "CREATE TABLE IF NOT EXISTS " + keyspace.getName() + "." + tableName + COUNTS_TABLE_NAME_SUFFIX + " (" + " name text," + " count counter," + " PRIMARY KEY (name)" + ");"); statement.setConsistencyLevel(this.consistencyLevel); session.execute(statement); } /** * Check if schema migration version table has already been created. * * @return {@code true} if schema migration version table exists in the keyspace. */ public boolean tablesExist() { boolean schemaVersionTableExists = false; boolean schemaVersionCountsTableExists = false; Statement schemaVersionStatement = QueryBuilder .select() .countAll() .from(keyspace.getName(), tableName); Statement schemaVersionCountsStatement = QueryBuilder .select() .countAll() .from(keyspace.getName(), tableName + COUNTS_TABLE_NAME_SUFFIX); schemaVersionStatement.setConsistencyLevel(this.consistencyLevel); schemaVersionCountsStatement.setConsistencyLevel(this.consistencyLevel); try { ResultSet resultsSchemaVersion = session.execute(schemaVersionStatement); if (resultsSchemaVersion.one() != null) { schemaVersionTableExists = true; } } catch (InvalidQueryException e) { LOG.debug("No schema version table found with a name of " + tableName); } try { ResultSet resultsSchemaVersionCounts = session.execute(schemaVersionCountsStatement); if (resultsSchemaVersionCounts.one() != null) { schemaVersionCountsTableExists = true; } } catch (InvalidQueryException e) { LOG.debug("No schema version counts table found with a name of " + tableName + COUNTS_TABLE_NAME_SUFFIX); } return schemaVersionTableExists && schemaVersionCountsTableExists; } /** * Add applied migration record into the schema migration version table. * * @param appliedMigration The applied migration. */ public void addAppliedMigration(AppliedMigration appliedMigration) { createTablesIfNotExist(); MigrationVersion version = appliedMigration.getVersion(); int versionRank = calculateVersionRank(version); PreparedStatement statement = cachePs.prepare( "INSERT INTO " + keyspace.getName() + "." + tableName + "(" + " version_rank, installed_rank, version," + " description, type, script," + " checksum, installed_on, installed_by," + " execution_time, success" + ") VALUES (" + " ?, ?, ?," + " ?, ?, ?," + " ?, dateOf(now()), ?," + " ?, ?" + ");" ); statement.setConsistencyLevel(this.consistencyLevel); session.execute(statement.bind( versionRank, calculateInstalledRank(), version.toString(), appliedMigration.getDescription(), appliedMigration.getType().name(), appliedMigration.getScript(), appliedMigration.getChecksum(), appliedMigration.getInstalledBy(), appliedMigration.getExecutionTime(), appliedMigration.isSuccess() )); LOG.debug("Schema version table " + tableName + " successfully updated to reflect changes"); } /** * Retrieve the applied migrations from the schema migration version table. * * @return The applied migrations. */ public List<AppliedMigration> findAppliedMigrations() { if (!tablesExist()) { return new ArrayList<>(); } Select select = QueryBuilder .select() .column("version_rank") .column("installed_rank") .column("version") .column("description") .column("type") .column("script") .column("checksum") .column("installed_on") .column("installed_by") .column("execution_time") .column("success") .from(keyspace.getName(), tableName); select.setConsistencyLevel(this.consistencyLevel); ResultSet results = session.execute(select); List<AppliedMigration> resultsList = new ArrayList<>(); for (Row row : results) { resultsList.add(new AppliedMigration( row.getInt("version_rank"), row.getInt("installed_rank"), MigrationVersion.Companion.fromVersion(row.getString("version")), row.getString("description"), MigrationType.valueOf(row.getString("type")), row.getString("script"), row.isNull("checksum") ? null : row.getInt("checksum"), row.getTimestamp("installed_on"), row.getString("installed_by"), row.getInt("execution_time"), row.getBool("success") )); } // NOTE: Order by `version_rank` not necessary here, as it eventually gets saved in TreeMap // that uses natural ordering return resultsList; } /** * Retrieve the applied migrations from the metadata table. * * @param migrationTypes The migration types to find. * @return The applied migrations. */ public List<AppliedMigration> findAppliedMigrations(MigrationType... migrationTypes) { if (!tablesExist()) { return new ArrayList<>(); } Select select = QueryBuilder .select() .column("version_rank") .column("installed_rank") .column("version") .column("description") .column("type") .column("script") .column("checksum") .column("installed_on") .column("installed_by") .column("execution_time") .column("success") .from(keyspace.getName(), tableName); select.setConsistencyLevel(ConsistencyLevel.ALL); ResultSet results = session.execute(select); List<AppliedMigration> resultsList = new ArrayList<>(); List<MigrationType> migTypeList = Arrays.asList(migrationTypes); for (Row row : results) { MigrationType migType = MigrationType.valueOf(row.getString("type")); if(migTypeList.contains(migType)){ resultsList.add(new AppliedMigration( row.getInt("version_rank"), row.getInt("installed_rank"), MigrationVersion.Companion.fromVersion(row.getString("version")), row.getString("description"), migType, row.getString("script"), row.getInt("checksum"), row.getTimestamp("installed_on"), row.getString("installed_by"), row.getInt("execution_time"), row.getBool("success") )); } } // NOTE: Order by `version_rank` not necessary here, as it eventually gets saved in TreeMap // that uses natural ordering return resultsList; } /** * Check if the keyspace has applied migrations. * * @return {@code true} if the keyspace has applied migrations. */ public boolean hasAppliedMigrations() { if (!tablesExist()) { return false; } createTablesIfNotExist(); List<AppliedMigration> filteredMigrations = new ArrayList<>(); List<AppliedMigration> appliedMigrations = findAppliedMigrations(); for (AppliedMigration appliedMigration : appliedMigrations) { if (!appliedMigration.getType().equals(MigrationType.BASELINE)) { filteredMigrations.add(appliedMigration); } } return !filteredMigrations.isEmpty(); } /** * Add a baseline version marker. * * @param baselineVersion The baseline version. * @param baselineDescription the baseline version description. * @param user The user's username executing the baselining. */ public void addBaselineMarker(final MigrationVersion baselineVersion, final String baselineDescription, final String user) { addAppliedMigration( new AppliedMigration( baselineVersion, baselineDescription, MigrationType.BASELINE, baselineDescription, 0, user, 0, true ) ); } /** * Get the baseline marker's applied migration. * * @return The baseline marker's applied migration. */ public AppliedMigration getBaselineMarker() { List<AppliedMigration> appliedMigrations = findAppliedMigrations(MigrationType.BASELINE); return appliedMigrations.isEmpty() ? null : appliedMigrations.get(0); } /** * Check if schema migration version table has a baseline marker. * * @return {@code true} if the schema migration version table has a baseline marker. */ public boolean hasBaselineMarker() { if (!tablesExist()) { return false; } createTablesIfNotExist(); return !findAppliedMigrations(MigrationType.BASELINE).isEmpty(); } /** * Calculates the installed rank for the new migration to be inserted. * * @return The installed rank. */ private int calculateInstalledRank() { Statement statement = new SimpleStatement( "UPDATE " + keyspace.getName() + "." + tableName + COUNTS_TABLE_NAME_SUFFIX + " SET count = count + 1" + " WHERE name = 'installed_rank'" + ";"); session.execute(statement); Select select = QueryBuilder .select("count") .from(tableName + COUNTS_TABLE_NAME_SUFFIX); select.where(eq("name", "installed_rank")); select.setConsistencyLevel(this.consistencyLevel); ResultSet result = session.execute(select); return (int) result.one().getLong("count"); } /** * Calculate the rank for this new version about to be inserted. * * @param version The version to calculated for. * @return The rank. */ private int calculateVersionRank(MigrationVersion version) { Statement statement = QueryBuilder .select() .column("version") .column("version_rank") .from(keyspace.getName(), tableName); statement.setConsistencyLevel(this.consistencyLevel); ResultSet versionRows = session.execute(statement); List<MigrationVersion> migrationVersions = new ArrayList<>(); HashMap<String, MigrationMetaHolder> migrationMetaHolders = new HashMap<>(); for (Row versionRow : versionRows) { migrationVersions.add(MigrationVersion.Companion.fromVersion(versionRow.getString("version"))); migrationMetaHolders.put(versionRow.getString("version"), new MigrationMetaHolder( versionRow.getInt("version_rank") )); } Collections.sort(migrationVersions); BatchStatement batchStatement = new BatchStatement(); PreparedStatement preparedStatement = cachePs.prepare( "UPDATE " + keyspace.getName() + "." + tableName + " SET version_rank = ?" + " WHERE version = ?" + ";"); for (int i = 0; i < migrationVersions.size(); i++) { if (version.compareTo(migrationVersions.get(i)) < 0) { for (int z = i; z < migrationVersions.size(); z++) { String migrationVersionStr = migrationVersions.get(z).getVersion(); batchStatement.add(preparedStatement.bind( migrationMetaHolders.get(migrationVersionStr).getVersionRank() + 1, migrationVersionStr)); batchStatement.setConsistencyLevel(this.consistencyLevel); } return i + 1; } } session.execute(batchStatement); return migrationVersions.size() + 1; } /** * Schema migration (transient) metadata. */ class MigrationMetaHolder { private int versionRank; public MigrationMetaHolder(int versionRank) { this.versionRank = versionRank; } public int getVersionRank() { return versionRank; } } }
src/main/java/com/builtamont/cassandra/migration/internal/dbsupport/SchemaVersionDAO.java
/** * File : SchemaVersionDAO.Java * License : * Original - Copyright (c) 2015 - 2016 Contrast Security * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.builtamont.cassandra.migration.internal.dbsupport; import com.builtamont.cassandra.migration.api.MigrationType; import com.builtamont.cassandra.migration.api.MigrationVersion; import com.builtamont.cassandra.migration.config.Keyspace; import com.builtamont.cassandra.migration.internal.metadatatable.AppliedMigration; import com.builtamont.cassandra.migration.internal.util.CachePrepareStatement; import com.builtamont.cassandra.migration.internal.util.logging.Log; import com.builtamont.cassandra.migration.internal.util.logging.LogFactory; import com.datastax.driver.core.*; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Select; import java.util.*; import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; // TODO: Convert to Kotlin code... Some challenges with Mockito mocking :) public class SchemaVersionDAO { private static final Log LOG = LogFactory.INSTANCE.getLog(SchemaVersionDAO.class); private static final String COUNTS_TABLE_NAME_SUFFIX = "_counts"; private Session session; private Keyspace keyspace; private String tableName; private CachePrepareStatement cachePs; private ConsistencyLevel consistencyLevel; public SchemaVersionDAO(Session session, Keyspace keyspace, String tableName) { this.session = session; this.keyspace = keyspace; this.tableName = tableName; this.cachePs = new CachePrepareStatement(session); //If running on a single host, don't force ConsistencyLevel.ALL this.consistencyLevel = session.getCluster().getMetadata().getAllHosts().size() > 1 ? ConsistencyLevel.ALL : ConsistencyLevel.ONE; } public String getTableName() { return tableName; } public Keyspace getKeyspace() { return this.keyspace; } public void createTablesIfNotExist() { if (tablesExist()) { return; } Statement statement = new SimpleStatement( "CREATE TABLE IF NOT EXISTS " + keyspace.getName() + "." + tableName + "(" + " version_rank int," + " installed_rank int," + " version text," + " description text," + " script text," + " checksum int," + " type text," + " installed_by text," + " installed_on timestamp," + " execution_time int," + " success boolean," + " PRIMARY KEY (version)" + ");"); statement.setConsistencyLevel(this.consistencyLevel); session.execute(statement); statement = new SimpleStatement( "CREATE TABLE IF NOT EXISTS " + keyspace.getName() + "." + tableName + COUNTS_TABLE_NAME_SUFFIX + " (" + " name text," + " count counter," + " PRIMARY KEY (name)" + ");"); statement.setConsistencyLevel(this.consistencyLevel); session.execute(statement); } public boolean tablesExist() { boolean schemaVersionTableExists = false; boolean schemaVersionCountsTableExists = false; Statement schemaVersionStatement = QueryBuilder .select() .countAll() .from(keyspace.getName(), tableName); Statement schemaVersionCountsStatement = QueryBuilder .select() .countAll() .from(keyspace.getName(), tableName + COUNTS_TABLE_NAME_SUFFIX); schemaVersionStatement.setConsistencyLevel(this.consistencyLevel); schemaVersionCountsStatement.setConsistencyLevel(this.consistencyLevel); try { ResultSet resultsSchemaVersion = session.execute(schemaVersionStatement); if (resultsSchemaVersion.one() != null) { schemaVersionTableExists = true; } } catch (InvalidQueryException e) { LOG.debug("No schema version table found with a name of " + tableName); } try { ResultSet resultsSchemaVersionCounts = session.execute(schemaVersionCountsStatement); if (resultsSchemaVersionCounts.one() != null) { schemaVersionCountsTableExists = true; } } catch (InvalidQueryException e) { LOG.debug("No schema version counts table found with a name of " + tableName + COUNTS_TABLE_NAME_SUFFIX); } return schemaVersionTableExists && schemaVersionCountsTableExists; } public void addAppliedMigration(AppliedMigration appliedMigration) { createTablesIfNotExist(); MigrationVersion version = appliedMigration.getVersion(); int versionRank = calculateVersionRank(version); PreparedStatement statement = cachePs.prepare( "INSERT INTO " + keyspace.getName() + "." + tableName + " (version_rank, installed_rank, version, description, type, script, checksum, installed_on," + " installed_by, execution_time, success)" + " VALUES" + " (?, ?, ?, ?, ?, ?, ?, dateOf(now()), ?, ?, ?);" ); statement.setConsistencyLevel(this.consistencyLevel); session.execute(statement.bind( versionRank, calculateInstalledRank(), version.toString(), appliedMigration.getDescription(), appliedMigration.getType().name(), appliedMigration.getScript(), appliedMigration.getChecksum(), appliedMigration.getInstalledBy(), appliedMigration.getExecutionTime(), appliedMigration.isSuccess() )); LOG.debug("Schema version table " + tableName + " successfully updated to reflect changes"); } /** * Retrieve the applied migrations from the metadata table. * * @return The applied migrations. */ public List<AppliedMigration> findAppliedMigrations() { if (!tablesExist()) { return new ArrayList<>(); } Select select = QueryBuilder .select() .column("version_rank") .column("installed_rank") .column("version") .column("description") .column("type") .column("script") .column("checksum") .column("installed_on") .column("installed_by") .column("execution_time") .column("success") .from(keyspace.getName(), tableName); select.setConsistencyLevel(this.consistencyLevel); ResultSet results = session.execute(select); List<AppliedMigration> resultsList = new ArrayList<>(); for (Row row : results) { resultsList.add(new AppliedMigration( row.getInt("version_rank"), row.getInt("installed_rank"), MigrationVersion.Companion.fromVersion(row.getString("version")), row.getString("description"), MigrationType.valueOf(row.getString("type")), row.getString("script"), row.isNull("checksum") ? null : row.getInt("checksum"), row.getTimestamp("installed_on"), row.getString("installed_by"), row.getInt("execution_time"), row.getBool("success") )); } //order by version_rank not necessary here as it eventually gets saved in TreeMap that uses natural ordering return resultsList; } /** * Retrieve the applied migrations from the metadata table. * * @param migrationTypes The migration types to find. * @return The applied migrations. */ public List<AppliedMigration> findAppliedMigrations(MigrationType... migrationTypes) { if (!tablesExist()) { return new ArrayList<>(); } Select select = QueryBuilder .select() .column("version_rank") .column("installed_rank") .column("version") .column("description") .column("type") .column("script") .column("checksum") .column("installed_on") .column("installed_by") .column("execution_time") .column("success") .from(keyspace.getName(), tableName); select.setConsistencyLevel(ConsistencyLevel.ALL); ResultSet results = session.execute(select); List<AppliedMigration> resultsList = new ArrayList<>(); List<MigrationType> migTypeList = Arrays.asList(migrationTypes); for (Row row : results) { MigrationType migType = MigrationType.valueOf(row.getString("type")); if(migTypeList.contains(migType)){ resultsList.add(new AppliedMigration( row.getInt("version_rank"), row.getInt("installed_rank"), MigrationVersion.Companion.fromVersion(row.getString("version")), row.getString("description"), migType, row.getString("script"), row.getInt("checksum"), row.getTimestamp("installed_on"), row.getString("installed_by"), row.getInt("execution_time"), row.getBool("success") )); } } //order by version_rank not necessary here as it eventually gets saved in TreeMap that uses natural ordering return resultsList; } public boolean hasAppliedMigrations() { if (!tablesExist()) { return false; } createTablesIfNotExist(); List<AppliedMigration> filteredMigrations = new ArrayList<>(); List<AppliedMigration> appliedMigrations = findAppliedMigrations(); for (AppliedMigration appliedMigration : appliedMigrations) { if (!appliedMigration.getType().equals(MigrationType.BASELINE)) { filteredMigrations.add(appliedMigration); } } return !filteredMigrations.isEmpty(); } public void addBaselineMarker(final MigrationVersion baselineVersion, final String baselineDescription, final String user) { addAppliedMigration( new AppliedMigration( baselineVersion, baselineDescription, MigrationType.BASELINE, baselineDescription, 0, user, 0, true ) ); } public AppliedMigration getBaselineMarker() { List<AppliedMigration> appliedMigrations = findAppliedMigrations(MigrationType.BASELINE); return appliedMigrations.isEmpty() ? null : appliedMigrations.get(0); } public boolean hasBaselineMarker() { if (!tablesExist()) { return false; } createTablesIfNotExist(); return !findAppliedMigrations(MigrationType.BASELINE).isEmpty(); } /** * Calculates the installed rank for the new migration to be inserted. * * @return The installed rank. */ private int calculateInstalledRank() { Statement statement = new SimpleStatement( "UPDATE " + keyspace.getName() + "." + tableName + COUNTS_TABLE_NAME_SUFFIX + " SET count = count + 1" + "WHERE name = 'installed_rank';"); session.execute(statement); Select select = QueryBuilder .select("count") .from(tableName + COUNTS_TABLE_NAME_SUFFIX); select.where(eq("name", "installed_rank")); select.setConsistencyLevel(this.consistencyLevel); ResultSet result = session.execute(select); return (int) result.one().getLong("count"); } /** * Calculate the rank for this new version about to be inserted. * * @param version The version to calculated for. * @return The rank. */ private int calculateVersionRank(MigrationVersion version) { Statement statement = QueryBuilder .select() .column("version") .column("version_rank") .from(keyspace.getName(), tableName); statement.setConsistencyLevel(this.consistencyLevel); ResultSet versionRows = session.execute(statement); List<MigrationVersion> migrationVersions = new ArrayList<>(); HashMap<String, MigrationMetaHolder> migrationMetaHolders = new HashMap<>(); for (Row versionRow : versionRows) { migrationVersions.add(MigrationVersion.Companion.fromVersion(versionRow.getString("version"))); migrationMetaHolders.put(versionRow.getString("version"), new MigrationMetaHolder( versionRow.getInt("version_rank") )); } Collections.sort(migrationVersions); BatchStatement batchStatement = new BatchStatement(); PreparedStatement preparedStatement = cachePs.prepare( "UPDATE " + keyspace.getName() + "." + tableName + " SET version_rank = ?" + " WHERE version = ?;"); for (int i = 0; i < migrationVersions.size(); i++) { if (version.compareTo(migrationVersions.get(i)) < 0) { for (int z = i; z < migrationVersions.size(); z++) { String migrationVersionStr = migrationVersions.get(z).getVersion(); batchStatement.add(preparedStatement.bind( migrationMetaHolders.get(migrationVersionStr).getVersionRank() + 1, migrationVersionStr)); batchStatement.setConsistencyLevel(this.consistencyLevel); } return i + 1; } } session.execute(batchStatement); return migrationVersions.size() + 1; } class MigrationMetaHolder { private int versionRank; public MigrationMetaHolder(int versionRank) { this.versionRank = versionRank; } public int getVersionRank() { return versionRank; } } }
Added some comments and tidy-up `SchemaVersionDAO` class
src/main/java/com/builtamont/cassandra/migration/internal/dbsupport/SchemaVersionDAO.java
Added some comments and tidy-up `SchemaVersionDAO` class
<ide><path>rc/main/java/com/builtamont/cassandra/migration/internal/dbsupport/SchemaVersionDAO.java <ide> <ide> import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; <ide> <add>/** <add> * Schema migrations table Data Access Object. <add> */ <ide> // TODO: Convert to Kotlin code... Some challenges with Mockito mocking :) <ide> public class SchemaVersionDAO { <ide> <ide> private CachePrepareStatement cachePs; <ide> private ConsistencyLevel consistencyLevel; <ide> <add> /** <add> * Creates a new schema version DAO. <add> * <add> * @param session The Cassandra session connection to use to execute the migration. <add> * @param keyspace The Cassandra keyspace to connect to. <add> * @param tableName The Cassandra migration version table name. <add> */ <ide> public SchemaVersionDAO(Session session, Keyspace keyspace, String tableName) { <ide> this.session = session; <ide> this.keyspace = keyspace; <ide> this.tableName = tableName; <ide> this.cachePs = new CachePrepareStatement(session); <del> //If running on a single host, don't force ConsistencyLevel.ALL <del> this.consistencyLevel = <del> session.getCluster().getMetadata().getAllHosts().size() > 1 ? ConsistencyLevel.ALL : ConsistencyLevel.ONE; <add> <add> // If running on a single host, don't force ConsistencyLevel.ALL <add> boolean isClustered = session.getCluster().getMetadata().getAllHosts().size() > 1; <add> this.consistencyLevel = isClustered ? ConsistencyLevel.ALL : ConsistencyLevel.ONE; <ide> } <ide> <ide> public String getTableName() { <ide> return this.keyspace; <ide> } <ide> <add> /** <add> * Create schema migration version table if it does not exists. <add> */ <ide> public void createTablesIfNotExist() { <ide> if (tablesExist()) { <ide> return; <ide> session.execute(statement); <ide> } <ide> <add> /** <add> * Check if schema migration version table has already been created. <add> * <add> * @return {@code true} if schema migration version table exists in the keyspace. <add> */ <ide> public boolean tablesExist() { <ide> boolean schemaVersionTableExists = false; <ide> boolean schemaVersionCountsTableExists = false; <ide> return schemaVersionTableExists && schemaVersionCountsTableExists; <ide> } <ide> <add> /** <add> * Add applied migration record into the schema migration version table. <add> * <add> * @param appliedMigration The applied migration. <add> */ <ide> public void addAppliedMigration(AppliedMigration appliedMigration) { <ide> createTablesIfNotExist(); <ide> <ide> <ide> int versionRank = calculateVersionRank(version); <ide> PreparedStatement statement = cachePs.prepare( <del> "INSERT INTO " + keyspace.getName() + "." + tableName + <del> " (version_rank, installed_rank, version, description, type, script, checksum, installed_on," + <del> " installed_by, execution_time, success)" + <del> " VALUES" + <del> " (?, ?, ?, ?, ?, ?, ?, dateOf(now()), ?, ?, ?);" <add> "INSERT INTO " + keyspace.getName() + "." + tableName + "(" + <add> " version_rank, installed_rank, version," + <add> " description, type, script," + <add> " checksum, installed_on, installed_by," + <add> " execution_time, success" + <add> ") VALUES (" + <add> " ?, ?, ?," + <add> " ?, ?, ?," + <add> " ?, dateOf(now()), ?," + <add> " ?, ?" + <add> ");" <ide> ); <ide> <ide> statement.setConsistencyLevel(this.consistencyLevel); <ide> } <ide> <ide> /** <del> * Retrieve the applied migrations from the metadata table. <add> * Retrieve the applied migrations from the schema migration version table. <ide> * <ide> * @return The applied migrations. <ide> */ <ide> )); <ide> } <ide> <del> //order by version_rank not necessary here as it eventually gets saved in TreeMap that uses natural ordering <del> <add> // NOTE: Order by `version_rank` not necessary here, as it eventually gets saved in TreeMap <add> // that uses natural ordering <ide> return resultsList; <ide> } <ide> <ide> } <ide> } <ide> <del> //order by version_rank not necessary here as it eventually gets saved in TreeMap that uses natural ordering <del> <add> // NOTE: Order by `version_rank` not necessary here, as it eventually gets saved in TreeMap <add> // that uses natural ordering <ide> return resultsList; <ide> } <ide> <add> /** <add> * Check if the keyspace has applied migrations. <add> * <add> * @return {@code true} if the keyspace has applied migrations. <add> */ <ide> public boolean hasAppliedMigrations() { <ide> if (!tablesExist()) { <ide> return false; <ide> return !filteredMigrations.isEmpty(); <ide> } <ide> <add> /** <add> * Add a baseline version marker. <add> * <add> * @param baselineVersion The baseline version. <add> * @param baselineDescription the baseline version description. <add> * @param user The user's username executing the baselining. <add> */ <ide> public void addBaselineMarker(final MigrationVersion baselineVersion, final String baselineDescription, final String user) { <ide> addAppliedMigration( <ide> new AppliedMigration( <ide> ); <ide> } <ide> <add> /** <add> * Get the baseline marker's applied migration. <add> * <add> * @return The baseline marker's applied migration. <add> */ <ide> public AppliedMigration getBaselineMarker() { <ide> List<AppliedMigration> appliedMigrations = findAppliedMigrations(MigrationType.BASELINE); <ide> return appliedMigrations.isEmpty() ? null : appliedMigrations.get(0); <ide> } <ide> <add> /** <add> * Check if schema migration version table has a baseline marker. <add> * <add> * @return {@code true} if the schema migration version table has a baseline marker. <add> */ <ide> public boolean hasBaselineMarker() { <ide> if (!tablesExist()) { <ide> return false; <ide> } <add> <ide> createTablesIfNotExist(); <add> <ide> return !findAppliedMigrations(MigrationType.BASELINE).isEmpty(); <ide> } <ide> <ide> Statement statement = new SimpleStatement( <ide> "UPDATE " + keyspace.getName() + "." + tableName + COUNTS_TABLE_NAME_SUFFIX + <ide> " SET count = count + 1" + <del> "WHERE name = 'installed_rank';"); <add> " WHERE name = 'installed_rank'" + <add> ";"); <add> <ide> session.execute(statement); <add> <ide> Select select = QueryBuilder <ide> .select("count") <ide> .from(tableName + COUNTS_TABLE_NAME_SUFFIX); <ide> select.where(eq("name", "installed_rank")); <add> <ide> select.setConsistencyLevel(this.consistencyLevel); <ide> ResultSet result = session.execute(select); <add> <ide> return (int) result.one().getLong("count"); <ide> } <ide> <ide> .column("version") <ide> .column("version_rank") <ide> .from(keyspace.getName(), tableName); <add> <ide> statement.setConsistencyLevel(this.consistencyLevel); <ide> ResultSet versionRows = session.execute(statement); <ide> <ide> PreparedStatement preparedStatement = cachePs.prepare( <ide> "UPDATE " + keyspace.getName() + "." + tableName + <ide> " SET version_rank = ?" + <del> " WHERE version = ?;"); <add> " WHERE version = ?" + <add> ";"); <ide> <ide> for (int i = 0; i < migrationVersions.size(); i++) { <ide> if (version.compareTo(migrationVersions.get(i)) < 0) { <ide> return migrationVersions.size() + 1; <ide> } <ide> <add> /** <add> * Schema migration (transient) metadata. <add> */ <ide> class MigrationMetaHolder { <ide> private int versionRank; <ide>
Java
mit
0cf462a7abdb0bcac9d494030a2218f47a118c6f
0
mercadopago/px-android,mercadopago/px-android,mercadopago/px-android
package com.mercadopago.core; import android.app.Activity; import android.content.Context; import android.content.Intent; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mercadopago.BankDealsActivity; import com.mercadopago.CallForAuthorizeActivity; import com.mercadopago.CardVaultActivity; import com.mercadopago.CheckoutActivity; import com.mercadopago.CongratsActivity; import com.mercadopago.CustomerCardsActivity; import com.mercadopago.GuessingCardActivity; import com.mercadopago.InstallmentsActivity; import com.mercadopago.InstructionsActivity; import com.mercadopago.IssuersActivity; import com.mercadopago.PaymentMethodsActivity; import com.mercadopago.PaymentResultActivity; import com.mercadopago.PaymentVaultActivity; import com.mercadopago.PendingActivity; import com.mercadopago.RejectionActivity; import com.mercadopago.VaultActivity; import com.mercadopago.adapters.ErrorHandlingCallAdapter; import com.mercadopago.callbacks.Callback; import com.mercadopago.model.BankDeal; import com.mercadopago.model.Card; import com.mercadopago.model.CardToken; import com.mercadopago.model.CheckoutPreference; import com.mercadopago.model.DecorationPreference; import com.mercadopago.model.IdentificationType; import com.mercadopago.model.Installment; import com.mercadopago.model.Instruction; import com.mercadopago.model.Issuer; import com.mercadopago.model.PayerCost; import com.mercadopago.model.Payment; import com.mercadopago.model.PaymentIntent; import com.mercadopago.model.PaymentMethod; import com.mercadopago.model.PaymentMethodSearch; import com.mercadopago.model.PaymentPreference; import com.mercadopago.model.SavedCardToken; import com.mercadopago.model.Site; import com.mercadopago.model.Token; import com.mercadopago.mptracker.MPTracker; import com.mercadopago.services.BankDealService; import com.mercadopago.services.GatewayService; import com.mercadopago.services.IdentificationService; import com.mercadopago.services.PaymentService; import com.mercadopago.util.HttpClientUtil; import com.mercadopago.util.JsonUtil; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MercadoPago { public static final String KEY_TYPE_PUBLIC = "public_key"; public static final String KEY_TYPE_PRIVATE = "private_key"; public static final int CUSTOMER_CARDS_REQUEST_CODE = 0; public static final int PAYMENT_METHODS_REQUEST_CODE = 1; public static final int INSTALLMENTS_REQUEST_CODE = 2; public static final int ISSUERS_REQUEST_CODE = 3; public static final int NEW_CARD_REQUEST_CODE = 4; public static final int RESULT_REQUEST_CODE = 5; public static final int VAULT_REQUEST_CODE = 6; public static final int CALL_FOR_AUTHORIZE_REQUEST_CODE = 7; public static final int PENDING_REQUEST_CODE = 8; public static final int REJECTION_REQUEST_CODE = 9; public static final int PAYMENT_VAULT_REQUEST_CODE = 10; public static final int BANK_DEALS_REQUEST_CODE = 11; public static final int CHECKOUT_REQUEST_CODE = 12; public static final int GUESSING_CARD_REQUEST_CODE = 13; public static final int INSTRUCTIONS_REQUEST_CODE = 14; public static final int CARD_VAULT_REQUEST_CODE = 15; public static final int CONGRATS_REQUEST_CODE = 16; public static final int BIN_LENGTH = 6; private static final String MP_API_BASE_URL = "https://api.mercadopago.com"; private String mKey = null; private String mKeyType = null; private Context mContext = null; Retrofit mRetrofit; private MercadoPago(Builder builder) { this.mContext = builder.mContext; this.mKey = builder.mKey; this.mKeyType = builder.mKeyType; System.setProperty("http.keepAlive", "false"); mRetrofit = new Retrofit.Builder() .baseUrl(MP_API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(JsonUtil.getInstance().getGson())) .client(HttpClientUtil.getClient(this.mContext, 10, 20, 20)) .addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory()) .build(); } public void getPreference(String checkoutPreferenceId, Callback<CheckoutPreference> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "GET_PREFERENCE", "1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getPreference(checkoutPreferenceId, this.mKey).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void createPayment(final PaymentIntent paymentIntent, final Callback<Payment> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "CREATE_PAYMENT", "1", mKeyType, "MLA", "1.0", mContext); Retrofit paymentsRetrofitAdapter = new Retrofit.Builder() .baseUrl(MP_API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(JsonUtil.getInstance().getGson())) .client(HttpClientUtil.getClient(this.mContext, 10, 40, 40)) .addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory()) .build(); PaymentService service = paymentsRetrofitAdapter.create(PaymentService.class); service.createPayment(String.valueOf(paymentIntent.getTransactionId()), paymentIntent).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void createToken(final SavedCardToken savedCardToken, final Callback<Token> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","CREATE_SAVED_TOKEN","1", mKeyType, "MLA", "1.0", mContext); savedCardToken.setDevice(mContext); GatewayService service = mRetrofit.create(GatewayService.class); service.getToken(this.mKey, savedCardToken).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void createToken(final CardToken cardToken, final Callback<Token> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","CREATE_CARD_TOKEN","1", mKeyType, "MLA", "1.0", mContext); cardToken.setDevice(mContext); GatewayService service = mRetrofit.create(GatewayService.class); service.getToken(this.mKey, cardToken).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getBankDeals(final Callback<List<BankDeal>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_BANK_DEALS","1", mKeyType, "MLA", "1.0", mContext); BankDealService service = mRetrofit.create(BankDealService.class); service.getBankDeals(this.mKey, mContext.getResources().getConfiguration().locale.toString()).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getIdentificationTypes(Callback<List<IdentificationType>> callback) { IdentificationService service = mRetrofit.create(IdentificationService.class); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_IDENTIFICATION_TYPES","1", mKeyType, "MLA", "1.0", mContext); service.getIdentificationTypes(this.mKey, null).enqueue(callback); } else { service.getIdentificationTypes(null, this.mKey).enqueue(callback); } } public void getInstallments(String bin, BigDecimal amount, Long issuerId, String paymentMethodId, Callback<List<Installment>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "GET_INSTALLMENTS", "1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getInstallments(this.mKey, bin, amount, issuerId, paymentMethodId, mContext.getResources().getConfiguration().locale.toString()).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getIssuers(String paymentMethodId, String bin, final Callback<List<Issuer>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "GET_ISSUERS", "1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getIssuers(this.mKey, paymentMethodId, bin).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getPaymentMethods(final Callback<List<PaymentMethod>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_PAYMENT_METHODS","1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getPaymentMethods(this.mKey).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getPaymentMethodSearch(BigDecimal amount, List<String> excludedPaymentTypes, List<String> excludedPaymentMethods, final Callback<PaymentMethodSearch> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_PAYMENT_METHOD_SEARCH","1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); StringBuilder stringBuilder = new StringBuilder(); if(excludedPaymentTypes != null) { for (String typeId : excludedPaymentTypes) { stringBuilder.append(typeId); if (!typeId.equals(excludedPaymentTypes.get(excludedPaymentTypes.size() - 1))) { stringBuilder.append(","); } } } String excludedPaymentTypesAppended = stringBuilder.toString(); stringBuilder = new StringBuilder(); if(excludedPaymentMethods != null) { for(String paymentMethodId : excludedPaymentMethods) { stringBuilder.append(paymentMethodId); if (!paymentMethodId.equals(excludedPaymentMethods.get(excludedPaymentMethods.size() - 1))) { stringBuilder.append(","); } } } String excludedPaymentMethodsAppended = stringBuilder.toString(); service.getPaymentMethodSearch(this.mKey, amount, excludedPaymentTypesAppended, excludedPaymentMethodsAppended).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getInstructions(Long paymentId, String paymentTypeId, final Callback<Instruction> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_INSTRUCTIONS","1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getInstruction(paymentId, this.mKey, paymentTypeId).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public static List<PaymentMethod> getValidPaymentMethodsForBin(String bin, List<PaymentMethod> paymentMethods){ if(bin.length() == BIN_LENGTH) { List<PaymentMethod> validPaymentMethods = new ArrayList<>(); for (PaymentMethod pm : paymentMethods) { if (pm.isValidForBin(bin)) { validPaymentMethods.add(pm); } } return validPaymentMethods; } else throw new RuntimeException("Invalid bin: " + BIN_LENGTH + " digits needed, " + bin.length() + " found"); } // * Static methods for StartActivityBuilder implementation private static void startBankDealsActivity(Activity activity, String publicKey, DecorationPreference decorationPreference) { Intent bankDealsIntent = new Intent(activity, BankDealsActivity.class); bankDealsIntent.putExtra("merchantPublicKey", publicKey); bankDealsIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(bankDealsIntent, BANK_DEALS_REQUEST_CODE); } private static void startCheckoutActivity(Activity activity, String merchantPublicKey, String checkoutPreferenceId, Boolean showBankDeals, DecorationPreference decorationPreference) { Intent checkoutIntent = new Intent(activity, CheckoutActivity.class); checkoutIntent.putExtra("merchantPublicKey", merchantPublicKey); checkoutIntent.putExtra("checkoutPreferenceId", checkoutPreferenceId); checkoutIntent.putExtra("showBankDeals", showBankDeals); checkoutIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(checkoutIntent, CHECKOUT_REQUEST_CODE); } private static void startPaymentResultActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent resultIntent = new Intent(activity, PaymentResultActivity.class); resultIntent.putExtra("merchantPublicKey", merchantPublicKey); resultIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); resultIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(resultIntent, RESULT_REQUEST_CODE); } private static void startCongratsActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent congratsIntent = new Intent(activity, CongratsActivity.class); congratsIntent.putExtra("merchantPublicKey", merchantPublicKey); congratsIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); congratsIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(congratsIntent, CONGRATS_REQUEST_CODE); } private static void startCallForAuthorizeActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent callForAuthorizeIntent = new Intent(activity, CallForAuthorizeActivity.class); callForAuthorizeIntent.putExtra("merchantPublicKey", merchantPublicKey); callForAuthorizeIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); callForAuthorizeIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(callForAuthorizeIntent, CALL_FOR_AUTHORIZE_REQUEST_CODE); } private static void startPendingActivity(Activity activity, String merchantPublicKey, Payment payment) { Intent pendingIntent = new Intent(activity, PendingActivity.class); pendingIntent.putExtra("merchantPublicKey", merchantPublicKey); pendingIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); activity.startActivityForResult(pendingIntent, PENDING_REQUEST_CODE); } private static void startRejectionActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent rejectionIntent = new Intent(activity, RejectionActivity.class); rejectionIntent.putExtra("merchantPublicKey", merchantPublicKey); rejectionIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); rejectionIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(rejectionIntent, REJECTION_REQUEST_CODE); } private static void startInstructionsActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent instructionIntent = new Intent(activity, InstructionsActivity.class); instructionIntent.putExtra("merchantPublicKey", merchantPublicKey); instructionIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); instructionIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(instructionIntent, INSTRUCTIONS_REQUEST_CODE); } private static void startCustomerCardsActivity(Activity activity, List<Card> cards) { if ((activity == null) || (cards == null)) { throw new RuntimeException("Invalid parameters"); } Intent paymentMethodsIntent = new Intent(activity, CustomerCardsActivity.class); Gson gson = new Gson(); paymentMethodsIntent.putExtra("cards", gson.toJson(cards)); activity.startActivityForResult(paymentMethodsIntent, CUSTOMER_CARDS_REQUEST_CODE); } private static void startInstallmentsActivity(Activity activity, BigDecimal amount, Site site, Token token, String publicKey, List<PayerCost> payerCosts, PaymentPreference paymentPreference, Issuer issuer, PaymentMethod paymentMethod, DecorationPreference decorationPreference) { Intent intent = new Intent(activity, InstallmentsActivity.class); if(amount != null) { intent.putExtra("amount", amount.toString()); } intent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); intent.putExtra("token", JsonUtil.getInstance().toJson(token)); intent.putExtra("publicKey", publicKey); intent.putExtra("issuer", JsonUtil.getInstance().toJson(issuer)); intent.putExtra("site", JsonUtil.getInstance().toJson(site)); intent.putExtra("payerCosts", JsonUtil.getInstance().toJson(payerCosts)); intent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); intent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(intent, INSTALLMENTS_REQUEST_CODE); } private static void startIssuersActivity(Activity activity, String publicKey, PaymentMethod paymentMethod, Token token, List<Issuer> issuers, DecorationPreference decorationPreference) { Intent intent = new Intent(activity, IssuersActivity.class); intent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); intent.putExtra("token", JsonUtil.getInstance().toJson(token)); intent.putExtra("publicKey", publicKey); intent.putExtra("issuers", JsonUtil.getInstance().toJson(issuers)); intent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(intent, ISSUERS_REQUEST_CODE); } private static void startGuessingCardActivity(Activity activity, String key, Boolean requireSecurityCode, Boolean requireIssuer, Boolean showBankDeals, PaymentPreference paymentPreference, DecorationPreference decorationPreference, Token token, List<PaymentMethod> paymentMethodList) { Intent guessingCardIntent = new Intent(activity, GuessingCardActivity.class); guessingCardIntent.putExtra("publicKey", key); if (requireSecurityCode != null) { guessingCardIntent.putExtra("requireSecurityCode", requireSecurityCode); } if (requireIssuer != null) { guessingCardIntent.putExtra("requireIssuer", requireIssuer); } if(showBankDeals != null){ guessingCardIntent.putExtra("showBankDeals", showBankDeals); } guessingCardIntent.putExtra("showBankDeals", showBankDeals); guessingCardIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); guessingCardIntent.putExtra("token", JsonUtil.getInstance().toJson(token)); guessingCardIntent.putExtra("paymentMethodList", JsonUtil.getInstance().toJson(paymentMethodList)); guessingCardIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(guessingCardIntent, GUESSING_CARD_REQUEST_CODE); } private static void startCardVaultActivity(Activity activity, String key, BigDecimal amount, Site site, Boolean installmentsEnabled, PaymentPreference paymentPreference, DecorationPreference decorationPreference, Token token, List<PaymentMethod> paymentMethodList) { Intent cardVaultIntent = new Intent(activity, CardVaultActivity.class); cardVaultIntent.putExtra("publicKey", key); if(amount != null) { cardVaultIntent.putExtra("amount", amount.toString()); } cardVaultIntent.putExtra("site", JsonUtil.getInstance().toJson(site)); cardVaultIntent.putExtra("installmentsEnabled", installmentsEnabled); cardVaultIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); cardVaultIntent.putExtra("token", JsonUtil.getInstance().toJson(token)); cardVaultIntent.putExtra("paymentMethodList", JsonUtil.getInstance().toJson(paymentMethodList)); cardVaultIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(cardVaultIntent, CARD_VAULT_REQUEST_CODE); } private static void startPaymentMethodsActivity(Activity activity, String merchantPublicKey, Boolean showBankDeals, PaymentPreference paymentPreference, DecorationPreference decorationPreference) { Intent paymentMethodsIntent = new Intent(activity, PaymentMethodsActivity.class); paymentMethodsIntent.putExtra("merchantPublicKey", merchantPublicKey); paymentMethodsIntent.putExtra("showBankDeals", showBankDeals); paymentMethodsIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); paymentMethodsIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(paymentMethodsIntent, PAYMENT_METHODS_REQUEST_CODE); } private static void startPaymentVaultActivity(Activity activity, String merchantPublicKey, String merchantBaseUrl, String merchantGetCustomerUri, String merchantAccessToken, BigDecimal amount, Site site, Boolean installmentsEnabled, Boolean showBankDeals, PaymentPreference paymentPreference, DecorationPreference decorationPreference, PaymentMethodSearch paymentMethodSearch) { Intent vaultIntent = new Intent(activity, PaymentVaultActivity.class); vaultIntent.putExtra("merchantPublicKey", merchantPublicKey); vaultIntent.putExtra("merchantBaseUrl", merchantBaseUrl); vaultIntent.putExtra("merchantGetCustomerUri", merchantGetCustomerUri); vaultIntent.putExtra("merchantAccessToken", merchantAccessToken); vaultIntent.putExtra("amount", amount.toString()); vaultIntent.putExtra("site", JsonUtil.getInstance().toJson(site)); vaultIntent.putExtra("installmentsEnabled", installmentsEnabled); vaultIntent.putExtra("showBankDeals", showBankDeals); vaultIntent.putExtra("paymentMethodSearch", JsonUtil.getInstance().toJson(paymentMethodSearch)); vaultIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); vaultIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(vaultIntent, PAYMENT_VAULT_REQUEST_CODE); } private static void startNewCardActivity(Activity activity, String keyType, String key, PaymentMethod paymentMethod, Boolean requireSecurityCode) { Intent newCardIntent = new Intent(activity, com.mercadopago.NewCardActivity.class); newCardIntent.putExtra("keyType", keyType); newCardIntent.putExtra("key", key); newCardIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); if (requireSecurityCode != null) { newCardIntent.putExtra("requireSecurityCode", requireSecurityCode); } activity.startActivityForResult(newCardIntent, NEW_CARD_REQUEST_CODE); } private static void startVaultActivity(Activity activity, String merchantPublicKey, String merchantBaseUrl, String merchantGetCustomerUri, String merchantAccessToken, BigDecimal amount, Site site, List<String> supportedPaymentTypes, Boolean showBankDeals) { Intent vaultIntent = new Intent(activity, VaultActivity.class); vaultIntent.putExtra("merchantPublicKey", merchantPublicKey); vaultIntent.putExtra("merchantBaseUrl", merchantBaseUrl); vaultIntent.putExtra("merchantGetCustomerUri", merchantGetCustomerUri); vaultIntent.putExtra("merchantAccessToken", merchantAccessToken); vaultIntent.putExtra("site", JsonUtil.getInstance().toJson(site)); vaultIntent.putExtra("amount", amount.toString()); putListExtra(vaultIntent, "supportedPaymentTypes", supportedPaymentTypes); vaultIntent.putExtra("showBankDeals", showBankDeals); activity.startActivityForResult(vaultIntent, VAULT_REQUEST_CODE); } private static void putListExtra(Intent intent, String listName, List<String> list) { if (list != null) { Gson gson = new Gson(); Type listType = new TypeToken<List<String>>(){}.getType(); intent.putExtra(listName, gson.toJson(list, listType)); } } public static class Builder { private Context mContext; private String mKey; private String mKeyType; public Builder() { mContext = null; mKey = null; } public Builder setContext(Context context) { if (context == null) throw new IllegalArgumentException("context is null"); this.mContext = context; return this; } public Builder setKey(String key, String keyType) { this.mKey = key; this.mKeyType = keyType; return this; } public Builder setPrivateKey(String key) { this.mKey = key; this.mKeyType = MercadoPago.KEY_TYPE_PRIVATE; return this; } public Builder setPublicKey(String key) { this.mKey = key; this.mKeyType = MercadoPago.KEY_TYPE_PUBLIC; this.mKeyType = MercadoPago.KEY_TYPE_PUBLIC; return this; } public MercadoPago build() { if (this.mContext == null) throw new IllegalStateException("context is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if ((!this.mKeyType.equals(MercadoPago.KEY_TYPE_PRIVATE)) && (!this.mKeyType.equals(MercadoPago.KEY_TYPE_PUBLIC))) throw new IllegalArgumentException("invalid key type"); return new MercadoPago(this); } } public static class StartActivityBuilder { private Activity mActivity; private BigDecimal mAmount; private List<Card> mCards; private String mCheckoutPreferenceId; private String mKey; private String mKeyType; private String mMerchantAccessToken; private String mMerchantBaseUrl; private String mMerchantGetCustomerUri; private List<PayerCost> mPayerCosts; private List<Issuer> mIssuers; private Payment mPayment; private PaymentMethod mPaymentMethod; private List<PaymentMethod> mPaymentMethodList; private Boolean mRequireIssuer; private Boolean mRequireSecurityCode; private Boolean mShowBankDeals; private PaymentMethodSearch mPaymentMethodSearch; private PaymentPreference mPaymentPreference; private Token mToken; private Issuer mIssuer; private Site mSite; private DecorationPreference mDecorationPreference; private Boolean mInstallmentsEnabled; private List<String> mSupportedPaymentTypes; public StartActivityBuilder() { mActivity = null; mKey = null; mKeyType = KEY_TYPE_PUBLIC; } public StartActivityBuilder setActivity(Activity activity) { if (activity == null) throw new IllegalArgumentException("context is null"); this.mActivity = activity; return this; } public StartActivityBuilder setIssuer(Issuer issuer) { this.mIssuer = issuer; return this; } public StartActivityBuilder setAmount(BigDecimal amount) { this.mAmount = amount; return this; } public StartActivityBuilder setCards(List<Card> cards) { this.mCards = cards; return this; } public StartActivityBuilder setCheckoutPreferenceId(String checkoutPreferenceId) { this.mCheckoutPreferenceId = checkoutPreferenceId; return this; } public StartActivityBuilder setPublicKey(String key) { this.mKey = key; this.mKeyType = MercadoPago.KEY_TYPE_PUBLIC; return this; } public StartActivityBuilder setMerchantAccessToken(String merchantAccessToken) { this.mMerchantAccessToken = merchantAccessToken; return this; } public StartActivityBuilder setMerchantBaseUrl(String merchantBaseUrl) { this.mMerchantBaseUrl = merchantBaseUrl; return this; } public StartActivityBuilder setMerchantGetCustomerUri(String merchantGetCustomerUri) { this.mMerchantGetCustomerUri = merchantGetCustomerUri; return this; } public StartActivityBuilder setPayerCosts(List<PayerCost> payerCosts) { this.mPayerCosts = payerCosts; return this; } public StartActivityBuilder setIssuers(List<Issuer> issuers) { this.mIssuers = issuers; return this; } public StartActivityBuilder setPayment(Payment payment) { this.mPayment = payment; return this; } public StartActivityBuilder setPaymentMethod(PaymentMethod paymentMethod) { this.mPaymentMethod = paymentMethod; return this; } public StartActivityBuilder setSupportedPaymentMethods(List<PaymentMethod> paymentMethodList) { this.mPaymentMethodList = paymentMethodList; return this; } public StartActivityBuilder setRequireSecurityCode(Boolean requireSecurityCode) { this.mRequireSecurityCode = requireSecurityCode; return this; } public StartActivityBuilder setRequireIssuer(Boolean requireIssuer) { this.mRequireIssuer = requireIssuer; return this; } public StartActivityBuilder setShowBankDeals(boolean showBankDeals) { this.mShowBankDeals = showBankDeals; return this; } public StartActivityBuilder setPaymentMethodSearch(PaymentMethodSearch paymentMethodSearch) { this.mPaymentMethodSearch = paymentMethodSearch; return this; } public StartActivityBuilder setPaymentPreference(PaymentPreference paymentPreference) { this.mPaymentPreference = paymentPreference; return this; } public StartActivityBuilder setToken(Token token) { this.mToken = token; return this; } public StartActivityBuilder setSite(Site site) { this.mSite = site; return this; } public StartActivityBuilder setInstallmentsEnabled(Boolean installmentsEnabled) { this.mInstallmentsEnabled = installmentsEnabled; return this; } public StartActivityBuilder setDecorationPreference(DecorationPreference decorationPreference) { this.mDecorationPreference = decorationPreference; return this; } @Deprecated public StartActivityBuilder setSupportedPaymentTypes(List<String> supportedPaymentTypes) { this.mSupportedPaymentTypes = supportedPaymentTypes; return this; } public void startBankDealsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startBankDealsActivity(this.mActivity, this.mKey, this.mDecorationPreference); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCheckoutActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mCheckoutPreferenceId == null) throw new IllegalStateException("checkout preference id is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startCheckoutActivity(this.mActivity, this.mKey, this.mCheckoutPreferenceId, this.mShowBankDeals, this.mDecorationPreference); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startPaymentResultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPaymentResultActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCongratsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startCongratsActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCallForAuthorizeActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startCallForAuthorizeActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startPendingActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPendingActivity(this.mActivity, this.mKey, this.mPayment); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startRejectionActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startRejectionActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startInstructionsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startInstructionsActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCustomerCardsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mCards == null) throw new IllegalStateException("cards is null"); MercadoPago.startCustomerCardsActivity(this.mActivity, this.mCards); } public void startInstallmentsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mSite == null) throw new IllegalStateException("site is null"); if (this.mAmount == null) throw new IllegalStateException("amount is null"); if(mPayerCosts == null) { if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mIssuer == null) throw new IllegalStateException("issuer is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); } MercadoPago.startInstallmentsActivity(mActivity, mAmount, mSite, mToken, mKey, mPayerCosts, mPaymentPreference, mIssuer, mPaymentMethod, mDecorationPreference); } public void startIssuersActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); MercadoPago.startIssuersActivity(this.mActivity, this.mKey, this.mPaymentMethod, this.mToken, this.mIssuers, this.mDecorationPreference); } public void startGuessingCardActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); MercadoPago.startGuessingCardActivity(this.mActivity, this.mKey, this.mRequireSecurityCode, this.mRequireIssuer, this.mShowBankDeals, this.mPaymentPreference, this.mDecorationPreference, this.mToken, this.mPaymentMethodList); } public void startCardVaultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mInstallmentsEnabled != null && this.mInstallmentsEnabled) { if (this.mAmount == null) throw new IllegalStateException("amount is null"); if (this.mSite == null) throw new IllegalStateException("site is null"); } MercadoPago.startCardVaultActivity(this.mActivity, this.mKey, this.mAmount, this.mSite, this.mInstallmentsEnabled, this.mPaymentPreference, this.mDecorationPreference, this.mToken, this.mPaymentMethodList); } public void startPaymentMethodsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPaymentMethodsActivity(this.mActivity, this.mKey, this.mShowBankDeals, this.mPaymentPreference, this.mDecorationPreference); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startPaymentVaultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mAmount == null) throw new IllegalStateException("amount is null"); if (this.mSite == null) throw new IllegalStateException("site is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPaymentVaultActivity(this.mActivity, this.mKey, this.mMerchantBaseUrl, this.mMerchantGetCustomerUri, this.mMerchantAccessToken, this.mAmount, this.mSite, this.mInstallmentsEnabled, this.mShowBankDeals, this.mPaymentPreference, this.mDecorationPreference, this.mPaymentMethodSearch); } else { throw new RuntimeException("Unsupported key type for this method"); } } @Deprecated public void startNewCardActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); MercadoPago.startNewCardActivity(this.mActivity, this.mKeyType, this.mKey, this.mPaymentMethod, this.mRequireSecurityCode); } public void startVaultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mAmount == null) throw new IllegalStateException("amount is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mSite == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startVaultActivity(this.mActivity, this.mKey, this.mMerchantBaseUrl, this.mMerchantGetCustomerUri, this.mMerchantAccessToken, this.mAmount, this.mSite, this.mSupportedPaymentTypes, this.mShowBankDeals); } else { throw new RuntimeException("Unsupported key type for this method"); } } } }
sdk/src/main/java/com/mercadopago/core/MercadoPago.java
package com.mercadopago.core; import android.app.Activity; import android.content.Context; import android.content.Intent; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mercadopago.BankDealsActivity; import com.mercadopago.CallForAuthorizeActivity; import com.mercadopago.CardVaultActivity; import com.mercadopago.CheckoutActivity; import com.mercadopago.CongratsActivity; import com.mercadopago.CustomerCardsActivity; import com.mercadopago.GuessingCardActivity; import com.mercadopago.InstallmentsActivity; import com.mercadopago.InstructionsActivity; import com.mercadopago.IssuersActivity; import com.mercadopago.PaymentMethodsActivity; import com.mercadopago.PaymentResultActivity; import com.mercadopago.PaymentVaultActivity; import com.mercadopago.PendingActivity; import com.mercadopago.RejectionActivity; import com.mercadopago.VaultActivity; import com.mercadopago.adapters.ErrorHandlingCallAdapter; import com.mercadopago.callbacks.Callback; import com.mercadopago.model.BankDeal; import com.mercadopago.model.Card; import com.mercadopago.model.CardToken; import com.mercadopago.model.CheckoutPreference; import com.mercadopago.model.DecorationPreference; import com.mercadopago.model.IdentificationType; import com.mercadopago.model.Installment; import com.mercadopago.model.Instruction; import com.mercadopago.model.Issuer; import com.mercadopago.model.PayerCost; import com.mercadopago.model.Payment; import com.mercadopago.model.PaymentIntent; import com.mercadopago.model.PaymentMethod; import com.mercadopago.model.PaymentMethodSearch; import com.mercadopago.model.PaymentPreference; import com.mercadopago.model.SavedCardToken; import com.mercadopago.model.Site; import com.mercadopago.model.Token; import com.mercadopago.mptracker.MPTracker; import com.mercadopago.services.BankDealService; import com.mercadopago.services.GatewayService; import com.mercadopago.services.IdentificationService; import com.mercadopago.services.PaymentService; import com.mercadopago.util.HttpClientUtil; import com.mercadopago.util.JsonUtil; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MercadoPago { public static final String KEY_TYPE_PUBLIC = "public_key"; public static final String KEY_TYPE_PRIVATE = "private_key"; public static final int CUSTOMER_CARDS_REQUEST_CODE = 0; public static final int PAYMENT_METHODS_REQUEST_CODE = 1; public static final int INSTALLMENTS_REQUEST_CODE = 2; public static final int ISSUERS_REQUEST_CODE = 3; public static final int NEW_CARD_REQUEST_CODE = 4; public static final int RESULT_REQUEST_CODE = 5; public static final int VAULT_REQUEST_CODE = 6; public static final int CALL_FOR_AUTHORIZE_REQUEST_CODE = 7; public static final int PENDING_REQUEST_CODE = 8; public static final int REJECTION_REQUEST_CODE = 9; public static final int PAYMENT_VAULT_REQUEST_CODE = 10; public static final int BANK_DEALS_REQUEST_CODE = 11; public static final int CHECKOUT_REQUEST_CODE = 12; public static final int GUESSING_CARD_REQUEST_CODE = 13; public static final int INSTRUCTIONS_REQUEST_CODE = 14; public static final int CARD_VAULT_REQUEST_CODE = 15; public static final int CONGRATS_REQUEST_CODE = 16; public static final int BIN_LENGTH = 6; private static final String MP_API_BASE_URL = "https://api.mercadopago.com"; private String mKey = null; private String mKeyType = null; private Context mContext = null; Retrofit mRetrofit; private MercadoPago(Builder builder) { this.mContext = builder.mContext; this.mKey = builder.mKey; this.mKeyType = builder.mKeyType; System.setProperty("http.keepAlive", "false"); mRetrofit = new Retrofit.Builder() .baseUrl(MP_API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(JsonUtil.getInstance().getGson())) .client(HttpClientUtil.getClient(this.mContext, 10, 20, 20)) .addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory()) .build(); } public void getPreference(String checkoutPreferenceId, Callback<CheckoutPreference> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "GET_PREFERENCE", "1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getPreference(checkoutPreferenceId, this.mKey).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void createPayment(final PaymentIntent paymentIntent, final Callback<Payment> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "CREATE_PAYMENT", "1", mKeyType, "MLA", "1.0", mContext); Retrofit paymentsRetrofitAdapter = new Retrofit.Builder() .baseUrl(MP_API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(JsonUtil.getInstance().getGson())) .client(HttpClientUtil.getClient(this.mContext, 10, 40, 40)) .addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory()) .build(); PaymentService service = paymentsRetrofitAdapter.create(PaymentService.class); service.createPayment(String.valueOf(paymentIntent.getTransactionId()), paymentIntent).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void createToken(final SavedCardToken savedCardToken, final Callback<Token> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","CREATE_SAVED_TOKEN","1", mKeyType, "MLA", "1.0", mContext); savedCardToken.setDevice(mContext); GatewayService service = mRetrofit.create(GatewayService.class); service.getToken(this.mKey, savedCardToken).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void createToken(final CardToken cardToken, final Callback<Token> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","CREATE_CARD_TOKEN","1", mKeyType, "MLA", "1.0", mContext); cardToken.setDevice(mContext); GatewayService service = mRetrofit.create(GatewayService.class); service.getToken(this.mKey, cardToken).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getBankDeals(final Callback<List<BankDeal>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_BANK_DEALS","1", mKeyType, "MLA", "1.0", mContext); BankDealService service = mRetrofit.create(BankDealService.class); service.getBankDeals(this.mKey, mContext.getResources().getConfiguration().locale.toString()).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getIdentificationTypes(Callback<List<IdentificationType>> callback) { IdentificationService service = mRetrofit.create(IdentificationService.class); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_IDENTIFICATION_TYPES","1", mKeyType, "MLA", "1.0", mContext); service.getIdentificationTypes(this.mKey, null).enqueue(callback); } else { service.getIdentificationTypes(null, this.mKey).enqueue(callback); } } public void getInstallments(String bin, BigDecimal amount, Long issuerId, String paymentMethodId, Callback<List<Installment>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "GET_INSTALLMENTS", "1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getInstallments(this.mKey, bin, amount, issuerId, paymentMethodId, mContext.getResources().getConfiguration().locale.toString()).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getIssuers(String paymentMethodId, String bin, final Callback<List<Issuer>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN", "GET_ISSUERS", "1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getIssuers(this.mKey, paymentMethodId, bin).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getPaymentMethods(final Callback<List<PaymentMethod>> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_PAYMENT_METHODS","1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getPaymentMethods(this.mKey).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getPaymentMethodSearch(BigDecimal amount, List<String> excludedPaymentTypes, List<String> excludedPaymentMethods, final Callback<PaymentMethodSearch> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_PAYMENT_METHOD_SEARCH","1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); StringBuilder stringBuilder = new StringBuilder(); if(excludedPaymentTypes != null) { for (String typeId : excludedPaymentTypes) { stringBuilder.append(typeId); if (!typeId.equals(excludedPaymentTypes.get(excludedPaymentTypes.size() - 1))) { stringBuilder.append(","); } } } String excludedPaymentTypesAppended = stringBuilder.toString(); stringBuilder = new StringBuilder(); if(excludedPaymentMethods != null) { for(String paymentMethodId : excludedPaymentMethods) { stringBuilder.append(paymentMethodId); if (!paymentMethodId.equals(excludedPaymentMethods.get(excludedPaymentMethods.size() - 1))) { stringBuilder.append(","); } } } String excludedPaymentMethodsAppended = stringBuilder.toString(); service.getPaymentMethodSearch(this.mKey, amount, excludedPaymentTypesAppended, excludedPaymentMethodsAppended).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void getInstructions(Long paymentId, String paymentTypeId, final Callback<Instruction> callback) { if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MPTracker.getInstance().trackEvent("NO_SCREEN","GET_INSTRUCTIONS","1", mKeyType, "MLA", "1.0", mContext); PaymentService service = mRetrofit.create(PaymentService.class); service.getInstruction(paymentId, this.mKey, paymentTypeId).enqueue(callback); } else { throw new RuntimeException("Unsupported key type for this method"); } } public static List<PaymentMethod> getValidPaymentMethodsForBin(String bin, List<PaymentMethod> paymentMethods){ if(bin.length() == BIN_LENGTH) { List<PaymentMethod> validPaymentMethods = new ArrayList<>(); for (PaymentMethod pm : paymentMethods) { if (pm.isValidForBin(bin)) { validPaymentMethods.add(pm); } } return validPaymentMethods; } else throw new RuntimeException("Invalid bin: " + BIN_LENGTH + " digits needed, " + bin.length() + " found"); } // * Static methods for StartActivityBuilder implementation private static void startBankDealsActivity(Activity activity, String publicKey, DecorationPreference decorationPreference) { Intent bankDealsIntent = new Intent(activity, BankDealsActivity.class); bankDealsIntent.putExtra("merchantPublicKey", publicKey); bankDealsIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(bankDealsIntent, BANK_DEALS_REQUEST_CODE); } private static void startCheckoutActivity(Activity activity, String merchantPublicKey, String checkoutPreferenceId, Boolean showBankDeals, DecorationPreference decorationPreference) { Intent checkoutIntent = new Intent(activity, CheckoutActivity.class); checkoutIntent.putExtra("merchantPublicKey", merchantPublicKey); checkoutIntent.putExtra("checkoutPreferenceId", checkoutPreferenceId); checkoutIntent.putExtra("showBankDeals", showBankDeals); checkoutIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(checkoutIntent, CHECKOUT_REQUEST_CODE); } private static void startPaymentResultActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent resultIntent = new Intent(activity, PaymentResultActivity.class); resultIntent.putExtra("merchantPublicKey", merchantPublicKey); resultIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); resultIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(resultIntent, RESULT_REQUEST_CODE); } private static void startCongratsActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent congratsIntent = new Intent(activity, CongratsActivity.class); congratsIntent.putExtra("merchantPublicKey", merchantPublicKey); congratsIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); congratsIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(congratsIntent, CONGRATS_REQUEST_CODE); } private static void startCallForAuthorizeActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent callForAuthorizeIntent = new Intent(activity, CallForAuthorizeActivity.class); callForAuthorizeIntent.putExtra("merchantPublicKey", merchantPublicKey); callForAuthorizeIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); callForAuthorizeIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(callForAuthorizeIntent, CALL_FOR_AUTHORIZE_REQUEST_CODE); } private static void startPendingActivity(Activity activity, String merchantPublicKey, Payment payment) { Intent pendingIntent = new Intent(activity, PendingActivity.class); pendingIntent.putExtra("merchantPublicKey", merchantPublicKey); pendingIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); activity.startActivityForResult(pendingIntent, PENDING_REQUEST_CODE); } private static void startRejectionActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent rejectionIntent = new Intent(activity, RejectionActivity.class); rejectionIntent.putExtra("merchantPublicKey", merchantPublicKey); rejectionIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); rejectionIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(rejectionIntent, REJECTION_REQUEST_CODE); } private static void startInstructionsActivity(Activity activity, String merchantPublicKey, Payment payment, PaymentMethod paymentMethod) { Intent instructionIntent = new Intent(activity, InstructionsActivity.class); instructionIntent.putExtra("merchantPublicKey", merchantPublicKey); instructionIntent.putExtra("payment", JsonUtil.getInstance().toJson(payment)); instructionIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); activity.startActivityForResult(instructionIntent, INSTRUCTIONS_REQUEST_CODE); } private static void startCustomerCardsActivity(Activity activity, List<Card> cards) { if ((activity == null) || (cards == null)) { throw new RuntimeException("Invalid parameters"); } Intent paymentMethodsIntent = new Intent(activity, CustomerCardsActivity.class); Gson gson = new Gson(); paymentMethodsIntent.putExtra("cards", gson.toJson(cards)); activity.startActivityForResult(paymentMethodsIntent, CUSTOMER_CARDS_REQUEST_CODE); } private static void startInstallmentsActivity(Activity activity, BigDecimal amount, Site site, Token token, String publicKey, List<PayerCost> payerCosts, PaymentPreference paymentPreference, Issuer issuer, PaymentMethod paymentMethod, DecorationPreference decorationPreference) { Intent intent = new Intent(activity, InstallmentsActivity.class); if(amount != null) { intent.putExtra("amount", amount.toString()); } intent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); intent.putExtra("token", JsonUtil.getInstance().toJson(token)); intent.putExtra("publicKey", publicKey); intent.putExtra("issuer", JsonUtil.getInstance().toJson(issuer)); intent.putExtra("site", JsonUtil.getInstance().toJson(site)); intent.putExtra("payerCosts", JsonUtil.getInstance().toJson(payerCosts)); intent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); intent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(intent, INSTALLMENTS_REQUEST_CODE); } private static void startIssuersActivity(Activity activity, String publicKey, PaymentMethod paymentMethod, Token token, List<Issuer> issuers, DecorationPreference decorationPreference) { Intent intent = new Intent(activity, IssuersActivity.class); intent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); intent.putExtra("token", JsonUtil.getInstance().toJson(token)); intent.putExtra("publicKey", publicKey); intent.putExtra("issuers", JsonUtil.getInstance().toJson(issuers)); intent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(intent, ISSUERS_REQUEST_CODE); } private static void startGuessingCardActivity(Activity activity, String key, Boolean requireSecurityCode, Boolean requireIssuer, Boolean showBankDeals, PaymentPreference paymentPreference, DecorationPreference decorationPreference, Token token, List<PaymentMethod> paymentMethodList) { Intent guessingCardIntent = new Intent(activity, GuessingCardActivity.class); guessingCardIntent.putExtra("publicKey", key); if (requireSecurityCode != null) { guessingCardIntent.putExtra("requireSecurityCode", requireSecurityCode); } if (requireIssuer != null) { guessingCardIntent.putExtra("requireIssuer", requireIssuer); } if(showBankDeals != null){ guessingCardIntent.putExtra("showBankDeals", showBankDeals); } guessingCardIntent.putExtra("showBankDeals", showBankDeals); guessingCardIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); guessingCardIntent.putExtra("token", JsonUtil.getInstance().toJson(token)); guessingCardIntent.putExtra("paymentMethodList", JsonUtil.getInstance().toJson(paymentMethodList)); guessingCardIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(guessingCardIntent, GUESSING_CARD_REQUEST_CODE); } private static void startCardVaultActivity(Activity activity, String key, BigDecimal amount, Site site, Boolean installmentsEnabled, PaymentPreference paymentPreference, DecorationPreference decorationPreference, Token token, List<PaymentMethod> paymentMethodList) { Intent cardVaultIntent = new Intent(activity, CardVaultActivity.class); cardVaultIntent.putExtra("publicKey", key); if(amount != null) { cardVaultIntent.putExtra("amount", amount.toString()); } cardVaultIntent.putExtra("site", JsonUtil.getInstance().toJson(site)); cardVaultIntent.putExtra("installmentsEnabled", installmentsEnabled); cardVaultIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); cardVaultIntent.putExtra("token", JsonUtil.getInstance().toJson(token)); cardVaultIntent.putExtra("paymentMethodList", JsonUtil.getInstance().toJson(paymentMethodList)); cardVaultIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(cardVaultIntent, CARD_VAULT_REQUEST_CODE); } private static void startPaymentMethodsActivity(Activity activity, String merchantPublicKey, Boolean showBankDeals, PaymentPreference paymentPreference, DecorationPreference decorationPreference) { Intent paymentMethodsIntent = new Intent(activity, PaymentMethodsActivity.class); paymentMethodsIntent.putExtra("merchantPublicKey", merchantPublicKey); paymentMethodsIntent.putExtra("showBankDeals", showBankDeals); paymentMethodsIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); paymentMethodsIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(paymentMethodsIntent, PAYMENT_METHODS_REQUEST_CODE); } private static void startPaymentVaultActivity(Activity activity, String merchantPublicKey, String merchantBaseUrl, String merchantGetCustomerUri, String merchantAccessToken, BigDecimal amount, Site site, Boolean installmentsEnabled, Boolean showBankDeals, PaymentPreference paymentPreference, DecorationPreference decorationPreference, PaymentMethodSearch paymentMethodSearch) { Intent vaultIntent = new Intent(activity, PaymentVaultActivity.class); vaultIntent.putExtra("merchantPublicKey", merchantPublicKey); vaultIntent.putExtra("merchantBaseUrl", merchantBaseUrl); vaultIntent.putExtra("merchantGetCustomerUri", merchantGetCustomerUri); vaultIntent.putExtra("merchantAccessToken", merchantAccessToken); vaultIntent.putExtra("amount", amount.toString()); vaultIntent.putExtra("site", JsonUtil.getInstance().toJson(site)); vaultIntent.putExtra("installmentsEnabled", installmentsEnabled); vaultIntent.putExtra("showBankDeals", showBankDeals); vaultIntent.putExtra("paymentMethodSearch", JsonUtil.getInstance().toJson(paymentMethodSearch)); vaultIntent.putExtra("paymentPreference", JsonUtil.getInstance().toJson(paymentPreference)); vaultIntent.putExtra("decorationPreference", JsonUtil.getInstance().toJson(decorationPreference)); activity.startActivityForResult(vaultIntent, PAYMENT_VAULT_REQUEST_CODE); } private static void startNewCardActivity(Activity activity, String keyType, String key, PaymentMethod paymentMethod, Boolean requireSecurityCode) { Intent newCardIntent = new Intent(activity, com.mercadopago.NewCardActivity.class); newCardIntent.putExtra("keyType", keyType); newCardIntent.putExtra("key", key); newCardIntent.putExtra("paymentMethod", JsonUtil.getInstance().toJson(paymentMethod)); if (requireSecurityCode != null) { newCardIntent.putExtra("requireSecurityCode", requireSecurityCode); } activity.startActivityForResult(newCardIntent, NEW_CARD_REQUEST_CODE); } private static void startVaultActivity(Activity activity, String merchantPublicKey, String merchantBaseUrl, String merchantGetCustomerUri, String merchantAccessToken, BigDecimal amount, Site site, List<String> supportedPaymentTypes, Boolean showBankDeals) { Intent vaultIntent = new Intent(activity, VaultActivity.class); vaultIntent.putExtra("merchantPublicKey", merchantPublicKey); vaultIntent.putExtra("merchantBaseUrl", merchantBaseUrl); vaultIntent.putExtra("merchantGetCustomerUri", merchantGetCustomerUri); vaultIntent.putExtra("merchantAccessToken", merchantAccessToken); vaultIntent.putExtra("site", JsonUtil.getInstance().toJson(site)); vaultIntent.putExtra("amount", amount.toString()); putListExtra(vaultIntent, "supportedPaymentTypes", supportedPaymentTypes); vaultIntent.putExtra("showBankDeals", showBankDeals); activity.startActivityForResult(vaultIntent, VAULT_REQUEST_CODE); } private static void putListExtra(Intent intent, String listName, List<String> list) { if (list != null) { Gson gson = new Gson(); Type listType = new TypeToken<List<String>>(){}.getType(); intent.putExtra(listName, gson.toJson(list, listType)); } } public static class Builder { private Context mContext; private String mKey; private String mKeyType; public Builder() { mContext = null; mKey = null; } public Builder setContext(Context context) { if (context == null) throw new IllegalArgumentException("context is null"); this.mContext = context; return this; } public Builder setKey(String key, String keyType) { this.mKey = key; this.mKeyType = keyType; return this; } public Builder setPrivateKey(String key) { this.mKey = key; this.mKeyType = MercadoPago.KEY_TYPE_PRIVATE; return this; } public Builder setPublicKey(String key) { this.mKey = key; this.mKeyType = MercadoPago.KEY_TYPE_PUBLIC; this.mKeyType = MercadoPago.KEY_TYPE_PUBLIC; return this; } public MercadoPago build() { if (this.mContext == null) throw new IllegalStateException("context is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if ((!this.mKeyType.equals(MercadoPago.KEY_TYPE_PRIVATE)) && (!this.mKeyType.equals(MercadoPago.KEY_TYPE_PUBLIC))) throw new IllegalArgumentException("invalid key type"); return new MercadoPago(this); } } public static class StartActivityBuilder { private Activity mActivity; private BigDecimal mAmount; private List<Card> mCards; private String mCheckoutPreferenceId; private String mKey; private String mKeyType; private String mMerchantAccessToken; private String mMerchantBaseUrl; private String mMerchantGetCustomerUri; private List<PayerCost> mPayerCosts; private List<Issuer> mIssuers; private Payment mPayment; private PaymentMethod mPaymentMethod; private List<PaymentMethod> mPaymentMethodList; private Boolean mRequireIssuer; private Boolean mRequireSecurityCode; private Boolean mShowBankDeals; private PaymentMethodSearch mPaymentMethodSearch; private PaymentPreference mPaymentPreference; private Token mToken; private Issuer mIssuer; private Site mSite; private DecorationPreference mDecorationPreference; private Boolean mInstallmentsEnabled; private List<String> mSupportedPaymentTypes; public StartActivityBuilder() { mActivity = null; mKey = null; mKeyType = KEY_TYPE_PUBLIC; } public StartActivityBuilder setActivity(Activity activity) { if (activity == null) throw new IllegalArgumentException("context is null"); this.mActivity = activity; return this; } public StartActivityBuilder setIssuer(Issuer issuer) { this.mIssuer = issuer; return this; } public StartActivityBuilder setAmount(BigDecimal amount) { this.mAmount = amount; return this; } public StartActivityBuilder setCards(List<Card> cards) { this.mCards = cards; return this; } public StartActivityBuilder setCheckoutPreferenceId(String checkoutPreferenceId) { this.mCheckoutPreferenceId = checkoutPreferenceId; return this; } public StartActivityBuilder setPublicKey(String key) { this.mKey = key; this.mKeyType = MercadoPago.KEY_TYPE_PUBLIC; return this; } public StartActivityBuilder setMerchantAccessToken(String merchantAccessToken) { this.mMerchantAccessToken = merchantAccessToken; return this; } public StartActivityBuilder setMerchantBaseUrl(String merchantBaseUrl) { this.mMerchantBaseUrl = merchantBaseUrl; return this; } public StartActivityBuilder setMerchantGetCustomerUri(String merchantGetCustomerUri) { this.mMerchantGetCustomerUri = merchantGetCustomerUri; return this; } public StartActivityBuilder setPayerCosts(List<PayerCost> payerCosts) { this.mPayerCosts = payerCosts; return this; } public StartActivityBuilder setIssuers(List<Issuer> issuers) { this.mIssuers = issuers; return this; } public StartActivityBuilder setPayment(Payment payment) { this.mPayment = payment; return this; } public StartActivityBuilder setPaymentMethod(PaymentMethod paymentMethod) { this.mPaymentMethod = paymentMethod; return this; } @Deprecated public StartActivityBuilder setSupportedPaymentMethods(List<PaymentMethod> paymentMethodList) { this.mPaymentMethodList = paymentMethodList; return this; } public StartActivityBuilder setRequireSecurityCode(Boolean requireSecurityCode) { this.mRequireSecurityCode = requireSecurityCode; return this; } public StartActivityBuilder setRequireIssuer(Boolean requireIssuer) { this.mRequireIssuer = requireIssuer; return this; } public StartActivityBuilder setShowBankDeals(boolean showBankDeals) { this.mShowBankDeals = showBankDeals; return this; } public StartActivityBuilder setPaymentMethodSearch(PaymentMethodSearch paymentMethodSearch) { this.mPaymentMethodSearch = paymentMethodSearch; return this; } public StartActivityBuilder setPaymentPreference(PaymentPreference paymentPreference) { this.mPaymentPreference = paymentPreference; return this; } public StartActivityBuilder setToken(Token token) { this.mToken = token; return this; } public StartActivityBuilder setSite(Site site) { this.mSite = site; return this; } public StartActivityBuilder setInstallmentsEnabled(Boolean installmentsEnabled) { this.mInstallmentsEnabled = installmentsEnabled; return this; } public StartActivityBuilder setDecorationPreference(DecorationPreference decorationPreference) { this.mDecorationPreference = decorationPreference; return this; } public StartActivityBuilder setSupportedPaymentTypes(List<String> supportedPaymentTypes) { this.mSupportedPaymentTypes = supportedPaymentTypes; return this; } public void startBankDealsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startBankDealsActivity(this.mActivity, this.mKey, this.mDecorationPreference); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCheckoutActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mCheckoutPreferenceId == null) throw new IllegalStateException("checkout preference id is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startCheckoutActivity(this.mActivity, this.mKey, this.mCheckoutPreferenceId, this.mShowBankDeals, this.mDecorationPreference); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startPaymentResultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPaymentResultActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCongratsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startCongratsActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCallForAuthorizeActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startCallForAuthorizeActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startPendingActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPendingActivity(this.mActivity, this.mKey, this.mPayment); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startRejectionActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startRejectionActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startInstructionsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mPayment == null) throw new IllegalStateException("payment is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startInstructionsActivity(this.mActivity, this.mKey, this.mPayment, this.mPaymentMethod); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startCustomerCardsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mCards == null) throw new IllegalStateException("cards is null"); MercadoPago.startCustomerCardsActivity(this.mActivity, this.mCards); } public void startInstallmentsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mSite == null) throw new IllegalStateException("site is null"); if (this.mAmount == null) throw new IllegalStateException("amount is null"); if(mPayerCosts == null) { if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mIssuer == null) throw new IllegalStateException("issuer is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); } MercadoPago.startInstallmentsActivity(mActivity, mAmount, mSite, mToken, mKey, mPayerCosts, mPaymentPreference, mIssuer, mPaymentMethod, mDecorationPreference); } public void startIssuersActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); MercadoPago.startIssuersActivity(this.mActivity, this.mKey, this.mPaymentMethod, this.mToken, this.mIssuers, this.mDecorationPreference); } public void startGuessingCardActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); MercadoPago.startGuessingCardActivity(this.mActivity, this.mKey, this.mRequireSecurityCode, this.mRequireIssuer, this.mShowBankDeals, this.mPaymentPreference, this.mDecorationPreference, this.mToken, this.mPaymentMethodList); } public void startCardVaultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mInstallmentsEnabled != null && this.mInstallmentsEnabled) { if (this.mAmount == null) throw new IllegalStateException("amount is null"); if (this.mSite == null) throw new IllegalStateException("site is null"); } MercadoPago.startCardVaultActivity(this.mActivity, this.mKey, this.mAmount, this.mSite, this.mInstallmentsEnabled, this.mPaymentPreference, this.mDecorationPreference, this.mToken, this.mPaymentMethodList); } public void startPaymentMethodsActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPaymentMethodsActivity(this.mActivity, this.mKey, this.mShowBankDeals, this.mPaymentPreference, this.mDecorationPreference); } else { throw new RuntimeException("Unsupported key type for this method"); } } public void startPaymentVaultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mAmount == null) throw new IllegalStateException("amount is null"); if (this.mSite == null) throw new IllegalStateException("site is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startPaymentVaultActivity(this.mActivity, this.mKey, this.mMerchantBaseUrl, this.mMerchantGetCustomerUri, this.mMerchantAccessToken, this.mAmount, this.mSite, this.mInstallmentsEnabled, this.mShowBankDeals, this.mPaymentPreference, this.mDecorationPreference, this.mPaymentMethodSearch); } else { throw new RuntimeException("Unsupported key type for this method"); } } @Deprecated public void startNewCardActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mPaymentMethod == null) throw new IllegalStateException("payment method is null"); MercadoPago.startNewCardActivity(this.mActivity, this.mKeyType, this.mKey, this.mPaymentMethod, this.mRequireSecurityCode); } public void startVaultActivity() { if (this.mActivity == null) throw new IllegalStateException("activity is null"); if (this.mAmount == null) throw new IllegalStateException("amount is null"); if (this.mKey == null) throw new IllegalStateException("key is null"); if (this.mKeyType == null) throw new IllegalStateException("key type is null"); if (this.mSite == null) throw new IllegalStateException("key type is null"); if (this.mKeyType.equals(KEY_TYPE_PUBLIC)) { MercadoPago.startVaultActivity(this.mActivity, this.mKey, this.mMerchantBaseUrl, this.mMerchantGetCustomerUri, this.mMerchantAccessToken, this.mAmount, this.mSite, this.mSupportedPaymentTypes, this.mShowBankDeals); } else { throw new RuntimeException("Unsupported key type for this method"); } } } }
deprecated setSupportedPaymentTypes in MercadoPago class
sdk/src/main/java/com/mercadopago/core/MercadoPago.java
deprecated setSupportedPaymentTypes in MercadoPago class
<ide><path>dk/src/main/java/com/mercadopago/core/MercadoPago.java <ide> return this; <ide> } <ide> <del> @Deprecated <ide> public StartActivityBuilder setSupportedPaymentMethods(List<PaymentMethod> paymentMethodList) { <ide> <ide> this.mPaymentMethodList = paymentMethodList; <ide> return this; <ide> } <ide> <add> @Deprecated <ide> public StartActivityBuilder setSupportedPaymentTypes(List<String> supportedPaymentTypes) { <ide> this.mSupportedPaymentTypes = supportedPaymentTypes; <ide> return this;
Java
mpl-2.0
0c0fc83a799021d4a1e6b84ebb13e270c5aad652
0
msteinhoff/hello-world
7b0d92a8-cb8e-11e5-88f8-00264a111016
src/main/java/HelloWorld.java
7b034f8c-cb8e-11e5-a878-00264a111016
new flies
src/main/java/HelloWorld.java
new flies
<ide><path>rc/main/java/HelloWorld.java <del>7b034f8c-cb8e-11e5-a878-00264a111016 <add>7b0d92a8-cb8e-11e5-88f8-00264a111016
Java
artistic-2.0
ca51806746a910b480747858fb35d62e2bfeb50c
0
gdude2002/WordWarning
package com.archivesmc.wordwarning; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import java.io.File; import java.util.Map; import static org.bukkit.ChatColor.translateAlternateColorCodes; public class ConfigHandler { private WordWarning plugin; private FileConfiguration config; public ConfigHandler(WordWarning plugin) { this.plugin = plugin; File fh = new File(this.plugin.getDataFolder() + "/config.yml"); if (!fh.isFile()) { // Only recreate if it's gone this.plugin.saveDefaultConfig(); } this.config = this.plugin.getConfig(); } public void update() { String version = this.getVersion(); switch (version) { case "": // No version in the config this.config.set("version", this.plugin.getDescription().getVersion()); this.reload(); } } public FileConfiguration get() { return this.config; } public void reload() { this.plugin.reloadConfig(); } public Map<String, Object> getTerms() { ConfigurationSection section = this.config.getConfigurationSection("terms"); if (section == null) { return null; } return section.getValues(false); } public String getPreMessage() { return translateAlternateColorCodes('&', this.config.getString("pre_message", null)); } public String getPostMessage() { return translateAlternateColorCodes('&', this.config.getString("post_message", null)); } public String getVersion() { return this.config.getString("version", ""); } }
src/main/java/com/archivesmc/wordwarning/ConfigHandler.java
package com.archivesmc.wordwarning; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import java.io.File; import java.util.Map; import static org.bukkit.ChatColor.translateAlternateColorCodes; public class ConfigHandler { private WordWarning plugin; private FileConfiguration config; public ConfigHandler(WordWarning plugin) { this.plugin = plugin; File fh = new File(this.plugin.getDataFolder() + "/config.yml"); if (!fh.isFile()) { // Only recreate if it's gone this.plugin.saveDefaultConfig(); } this.config = this.plugin.getConfig(); } public void update() { String version = this.config.getString("version", ""); switch (version) { case "": // No version in the config this.config.set("version", this.plugin.getDescription().getVersion()); } } public FileConfiguration get() { return this.config; } public void reload() { this.plugin.reloadConfig(); } public Map<String, Object> getTerms() { ConfigurationSection section = this.config.getConfigurationSection("terms"); if (section == null) { return null; } return section.getValues(false); } public String getPreMessage() { return translateAlternateColorCodes('&', this.config.getString("pre_message", null)); } public String getPostMessage() { return translateAlternateColorCodes('&', this.config.getString("post_message", null)); } public String getVersion() { return this.config.getString("version", ""); } }
Reload after version change
src/main/java/com/archivesmc/wordwarning/ConfigHandler.java
Reload after version change
<ide><path>rc/main/java/com/archivesmc/wordwarning/ConfigHandler.java <ide> } <ide> <ide> public void update() { <del> String version = this.config.getString("version", ""); <add> String version = this.getVersion(); <ide> <ide> switch (version) { <ide> case "": <ide> // No version in the config <ide> this.config.set("version", this.plugin.getDescription().getVersion()); <add> this.reload(); <ide> } <ide> } <ide>
Java
mit
63807016ec246caeb2f68274698b062ebb743953
0
martinda/git-plugin,abaditsegay/git-plugin,v1v/git-plugin,KostyaSha/git-plugin,PinguinAG/git-plugin,pauxus/git-plugin,loomchild/git-plugin,nKey/git-plugin,nKey/git-plugin,jacob-keller/git-plugin,jenkinsci/git-plugin,mklein0/git-plugin,nKey/git-plugin,Talend/git-plugin,mklein0/git-plugin,Jellyvision/git-plugin,loomchild/git-plugin,Vlatombe/git-plugin,Deveo/git-plugin,avdv/git-plugin,loomchild/git-plugin,pauxus/git-plugin,avdv/git-plugin,abaditsegay/git-plugin,mklein0/git-plugin,v1v/git-plugin,martinda/git-plugin,ydubreuil/git-plugin,MarkEWaite/git-plugin,ydubreuil/git-plugin,bjacklyn/git-plugin,ivan-fedorov/git-plugin,sgargan/git-plugin,kzantow/git-plugin,pauxus/git-plugin,Nonymus/git-plugin,nordstrand/git-plugin,Talend/git-plugin,Jellyvision/git-plugin,kzantow/git-plugin,bjacklyn/git-plugin,ivan-fedorov/git-plugin,sgargan/git-plugin,Vlatombe/git-plugin,mlgiroux/git-plugin,ldtkms/git-plugin,kzantow/git-plugin,bjacklyn/git-plugin,martinda/git-plugin,abaditsegay/git-plugin,jacob-keller/git-plugin,MarkEWaite/git-plugin,MarkEWaite/git-plugin,Nonymus/git-plugin,mlgiroux/git-plugin,Deveo/git-plugin,jacob-keller/git-plugin,avdv/git-plugin,Nonymus/git-plugin,ldtkms/git-plugin,sgargan/git-plugin,ldtkms/git-plugin,PinguinAG/git-plugin,ndeloof/git-plugin,ivan-fedorov/git-plugin,ydubreuil/git-plugin,Jellyvision/git-plugin,Vlatombe/git-plugin,MarkEWaite/git-plugin,jenkinsci/git-plugin,Talend/git-plugin,jenkinsci/git-plugin,ialbors/git-plugin,recena/git-plugin,ialbors/git-plugin,nordstrand/git-plugin,ndeloof/git-plugin,jenkinsci/git-plugin,v1v/git-plugin,recena/git-plugin,Deveo/git-plugin,KostyaSha/git-plugin,mlgiroux/git-plugin,recena/git-plugin,ndeloof/git-plugin,nordstrand/git-plugin
package hudson.plugins.git; import java.io.BufferedReader; import java.io.IOException; import java.security.Principal; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * A Mock implementation of {@link StaplerRequest}. Almost all calls to the methods defined by * StaplerRequest and its parent interfaces are guaranteed to fail. The only ones that will not fail are * {@link #getParameter(String)} and {@link #getParameterValues(String)}. These are backed by a Map that * can be primed by multiple setter methods defined in this class. The setters generally set the values * expected by the GitSCM builder. * * @author ishaaq * */ public class MockStaplerRequest implements StaplerRequest { private final Map<String, String[]> params = new HashMap<String, String[]>(); public String getParameter(String name) { String[] values = params.get(name); if(values != null) { return values[0]; } return null; } public String[] getParameterValues(String name) { return params.get(name); } public MockStaplerRequest setRepos(String[] repoUrls, String[] repoNames, String[] refSpecs) { return put("git.repo.url", repoUrls) .put("git.repo.name", repoNames) .put("git.repo.refspec", refSpecs); } public MockStaplerRequest setRepo(String repoUrl, String repoName, String refSpec) { return put("git.repo.url", repoUrl) .put("git.repo.name", repoName) .put("git.repo.refspec", refSpec); } public MockStaplerRequest setBranches(String[] branches) { return put("git.branch", branches); } public MockStaplerRequest setBranch(String branch) { return put("git.branch", branch); } public MockStaplerRequest setMergeTarget(String mergeTarget) { return put("git.mergeTarget", mergeTarget); } public MockStaplerRequest setGitWebUrl(String gitWebUrl) { return put("gitweb.url", gitWebUrl); } public MockStaplerRequest setGitGenerate(String gitGenerate) { return put("git.generate", gitGenerate); } public MockStaplerRequest setGitClean(String gitClean) { return put("git.clean", gitClean); } public MockStaplerRequest setGitExe(String gitExe) { return put("git.gitExe", gitExe); } /** * In addition to the setter methods you can directly prime values into the parameter map * using this method. * @param key a parameter key. * @param values an array of matching values. */ public MockStaplerRequest put(String key, String[] values) { params.put(key, values); return this; } /** * In addition to the setter methods you can directly prime values into the parameter map * using this method. * @param key a parameter key. * @param values a matching value. */ public MockStaplerRequest put(String key, String value) { params.put(key, new String[]{value}); return this; } public Stapler getStapler() { throw new UnsupportedOperationException(); } public <T> T bindJSON(Class<T> type, JSONObject src) { throw new UnsupportedOperationException(); } public void bindJSON(Object bean, JSONObject src) { throw new UnsupportedOperationException(); } public <T> List<T> bindJSONToList(Class<T> type, Object src) { throw new UnsupportedOperationException(); } public void bindParameters(Object bean) { throw new UnsupportedOperationException(); } public void bindParameters(Object bean, String prefix) { throw new UnsupportedOperationException(); } public <T> T bindParameters(Class<T> type, String prefix) { throw new UnsupportedOperationException(); } public <T> T bindParameters(Class<T> type, String prefix, int index) { throw new UnsupportedOperationException(); } public <T> List<T> bindParametersToList(Class<T> type, String prefix) { throw new UnsupportedOperationException(); } public boolean checkIfModified(long timestampOfResource, StaplerResponse rsp) { throw new UnsupportedOperationException(); } public boolean checkIfModified(Date timestampOfResource, StaplerResponse rsp) { throw new UnsupportedOperationException(); } public Ancestor findAncestor(Class type) { throw new UnsupportedOperationException(); } public Ancestor findAncestor(Object o) { throw new UnsupportedOperationException(); } public <T> T findAncestorObject(Class<T> type) { throw new UnsupportedOperationException(); } public List<Ancestor> getAncestors() { throw new UnsupportedOperationException(); } public FileItem getFileItem(String name) { throw new UnsupportedOperationException(); } public String getOriginalRequestURI() { throw new UnsupportedOperationException(); } public String getReferer() { throw new UnsupportedOperationException(); } public String getRestOfPath() { throw new UnsupportedOperationException(); } public String getOriginalRestOfPath() { throw new UnsupportedOperationException(); } public String getRootPath() { throw new UnsupportedOperationException(); } public ServletContext getServletContext() { throw new UnsupportedOperationException(); } public JSONObject getSubmittedForm() throws ServletException { throw new UnsupportedOperationException(); } public RequestDispatcher getView(Object it, String viewName) { throw new UnsupportedOperationException(); } public RequestDispatcher getView(Class clazz, String viewName) { throw new UnsupportedOperationException(); } public boolean hasParameter(String name) { throw new UnsupportedOperationException(); } public String getAuthType() { throw new UnsupportedOperationException(); } public String getContextPath() { throw new UnsupportedOperationException(); } public Cookie[] getCookies() { throw new UnsupportedOperationException(); } public long getDateHeader(String name) { throw new UnsupportedOperationException(); } public String getHeader(String name) { throw new UnsupportedOperationException(); } public Enumeration getHeaderNames() { throw new UnsupportedOperationException(); } public Enumeration getHeaders(String name) { throw new UnsupportedOperationException(); } public int getIntHeader(String name) { throw new UnsupportedOperationException(); } public String getMethod() { throw new UnsupportedOperationException(); } public String getPathInfo() { throw new UnsupportedOperationException(); } public String getPathTranslated() { throw new UnsupportedOperationException(); } public String getQueryString() { throw new UnsupportedOperationException(); } public String getRemoteUser() { throw new UnsupportedOperationException(); } public String getRequestURI() { throw new UnsupportedOperationException(); } public StringBuffer getRequestURL() { throw new UnsupportedOperationException(); } public String getRequestedSessionId() { throw new UnsupportedOperationException(); } public String getServletPath() { throw new UnsupportedOperationException(); } public HttpSession getSession() { throw new UnsupportedOperationException(); } public HttpSession getSession(boolean create) { throw new UnsupportedOperationException(); } public Principal getUserPrincipal() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdFromCookie() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdFromURL() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdFromUrl() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdValid() { throw new UnsupportedOperationException(); } public boolean isUserInRole(String role) { throw new UnsupportedOperationException(); } public Object getAttribute(String name) { throw new UnsupportedOperationException(); } public Enumeration getAttributeNames() { throw new UnsupportedOperationException(); } public String getCharacterEncoding() { throw new UnsupportedOperationException(); } public int getContentLength() { throw new UnsupportedOperationException(); } public String getContentType() { throw new UnsupportedOperationException(); } public ServletInputStream getInputStream() throws IOException { throw new UnsupportedOperationException(); } public String getLocalAddr() { throw new UnsupportedOperationException(); } public String getLocalName() { throw new UnsupportedOperationException(); } public int getLocalPort() { throw new UnsupportedOperationException(); } public Locale getLocale() { throw new UnsupportedOperationException(); } public Enumeration getLocales() { throw new UnsupportedOperationException(); } public Map getParameterMap() { throw new UnsupportedOperationException(); } public Enumeration getParameterNames() { throw new UnsupportedOperationException(); } public String getProtocol() { throw new UnsupportedOperationException(); } public BufferedReader getReader() throws IOException { throw new UnsupportedOperationException(); } public String getRealPath(String path) { throw new UnsupportedOperationException(); } public String getRemoteAddr() { throw new UnsupportedOperationException(); } public String getRemoteHost() { throw new UnsupportedOperationException(); } public int getRemotePort() { throw new UnsupportedOperationException(); } public RequestDispatcher getRequestDispatcher(String path) { throw new UnsupportedOperationException(); } public String getScheme() { throw new UnsupportedOperationException(); } public String getServerName() { throw new UnsupportedOperationException(); } public int getServerPort() { throw new UnsupportedOperationException(); } public boolean isSecure() { throw new UnsupportedOperationException(); } public void removeAttribute(String name) { throw new UnsupportedOperationException(); } public void setAttribute(String name, Object o) { throw new UnsupportedOperationException(); } public void setCharacterEncoding(String env) { throw new UnsupportedOperationException(); } public boolean checkIfModified(Calendar timestampOfResource, StaplerResponse rsp) { throw new UnsupportedOperationException(); } public boolean checkIfModified(long timestampOfResource, StaplerResponse rsp, long expiration) { throw new UnsupportedOperationException(); } }
src/test/java/hudson/plugins/git/MockStaplerRequest.java
package hudson.plugins.git; import java.io.BufferedReader; import java.io.IOException; import java.security.Principal; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * A Mock implementation of {@link StaplerRequest}. Almost all calls to the methods defined by * StaplerRequest and its parent interfaces are guaranteed to fail. The only ones that will not fail are * {@link #getParameter(String)} and {@link #getParameterValues(String)}. These are backed by a Map that * can be primed by multiple setter methods defined in this class. The setters generally set the values * expected by the GitSCM builder. * * @author ishaaq * */ public class MockStaplerRequest implements StaplerRequest { private final Map<String, String[]> params = new HashMap<String, String[]>(); public String getParameter(String name) { String[] values = params.get(name); if(values != null) { return values[0]; } return null; } public String[] getParameterValues(String name) { return params.get(name); } public MockStaplerRequest setRepos(String[] repoUrls, String[] repoNames, String[] refSpecs) { return put("git.repo.url", repoUrls) .put("git.repo.name", repoNames) .put("git.repo.refspec", refSpecs); } public MockStaplerRequest setRepo(String repoUrl, String repoName, String refSpec) { return put("git.repo.url", repoUrl) .put("git.repo.name", repoName) .put("git.repo.refspec", refSpec); } public MockStaplerRequest setBranches(String[] branches) { return put("git.branch", branches); } public MockStaplerRequest setBranch(String branch) { return put("git.branch", branch); } public MockStaplerRequest setMergeTarget(String mergeTarget) { return put("git.mergeTarget", mergeTarget); } public MockStaplerRequest setGitWebUrl(String gitWebUrl) { return put("gitweb.url", gitWebUrl); } public MockStaplerRequest setGitGenerate(String gitGenerate) { return put("git.generate", gitGenerate); } public MockStaplerRequest setGitClean(String gitClean) { return put("git.clean", gitClean); } public MockStaplerRequest setGitExe(String gitExe) { return put("git.gitExe", gitExe); } /** * In addition to the setter methods you can directly prime values into the parameter map * using this method. * @param key a parameter key. * @param values an array of matching values. */ public MockStaplerRequest put(String key, String[] values) { params.put(key, values); return this; } /** * In addition to the setter methods you can directly prime values into the parameter map * using this method. * @param key a parameter key. * @param values a matching value. */ public MockStaplerRequest put(String key, String value) { params.put(key, new String[]{value}); return this; } public <T> T bindJSON(Class<T> type, JSONObject src) { throw new UnsupportedOperationException(); } public void bindJSON(Object bean, JSONObject src) { throw new UnsupportedOperationException(); } public <T> List<T> bindJSONToList(Class<T> type, Object src) { throw new UnsupportedOperationException(); } public void bindParameters(Object bean) { throw new UnsupportedOperationException(); } public void bindParameters(Object bean, String prefix) { throw new UnsupportedOperationException(); } public <T> T bindParameters(Class<T> type, String prefix) { throw new UnsupportedOperationException(); } public <T> T bindParameters(Class<T> type, String prefix, int index) { throw new UnsupportedOperationException(); } public <T> List<T> bindParametersToList(Class<T> type, String prefix) { throw new UnsupportedOperationException(); } public boolean checkIfModified(long timestampOfResource, StaplerResponse rsp) { throw new UnsupportedOperationException(); } public boolean checkIfModified(Date timestampOfResource, StaplerResponse rsp) { throw new UnsupportedOperationException(); } public Ancestor findAncestor(Class type) { throw new UnsupportedOperationException(); } public Ancestor findAncestor(Object o) { throw new UnsupportedOperationException(); } public <T> T findAncestorObject(Class<T> type) { throw new UnsupportedOperationException(); } public List<Ancestor> getAncestors() { throw new UnsupportedOperationException(); } public FileItem getFileItem(String name) { throw new UnsupportedOperationException(); } public String getOriginalRequestURI() { throw new UnsupportedOperationException(); } public String getReferer() { throw new UnsupportedOperationException(); } public String getRestOfPath() { throw new UnsupportedOperationException(); } public String getRootPath() { throw new UnsupportedOperationException(); } public ServletContext getServletContext() { throw new UnsupportedOperationException(); } public JSONObject getSubmittedForm() throws ServletException { throw new UnsupportedOperationException(); } public RequestDispatcher getView(Object it, String viewName) { throw new UnsupportedOperationException(); } public RequestDispatcher getView(Class clazz, String viewName) { throw new UnsupportedOperationException(); } public boolean hasParameter(String name) { throw new UnsupportedOperationException(); } public String getAuthType() { throw new UnsupportedOperationException(); } public String getContextPath() { throw new UnsupportedOperationException(); } public Cookie[] getCookies() { throw new UnsupportedOperationException(); } public long getDateHeader(String name) { throw new UnsupportedOperationException(); } public String getHeader(String name) { throw new UnsupportedOperationException(); } public Enumeration getHeaderNames() { throw new UnsupportedOperationException(); } public Enumeration getHeaders(String name) { throw new UnsupportedOperationException(); } public int getIntHeader(String name) { throw new UnsupportedOperationException(); } public String getMethod() { throw new UnsupportedOperationException(); } public String getPathInfo() { throw new UnsupportedOperationException(); } public String getPathTranslated() { throw new UnsupportedOperationException(); } public String getQueryString() { throw new UnsupportedOperationException(); } public String getRemoteUser() { throw new UnsupportedOperationException(); } public String getRequestURI() { throw new UnsupportedOperationException(); } public StringBuffer getRequestURL() { throw new UnsupportedOperationException(); } public String getRequestedSessionId() { throw new UnsupportedOperationException(); } public String getServletPath() { throw new UnsupportedOperationException(); } public HttpSession getSession() { throw new UnsupportedOperationException(); } public HttpSession getSession(boolean create) { throw new UnsupportedOperationException(); } public Principal getUserPrincipal() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdFromCookie() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdFromURL() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdFromUrl() { throw new UnsupportedOperationException(); } public boolean isRequestedSessionIdValid() { throw new UnsupportedOperationException(); } public boolean isUserInRole(String role) { throw new UnsupportedOperationException(); } public Object getAttribute(String name) { throw new UnsupportedOperationException(); } public Enumeration getAttributeNames() { throw new UnsupportedOperationException(); } public String getCharacterEncoding() { throw new UnsupportedOperationException(); } public int getContentLength() { throw new UnsupportedOperationException(); } public String getContentType() { throw new UnsupportedOperationException(); } public ServletInputStream getInputStream() throws IOException { throw new UnsupportedOperationException(); } public String getLocalAddr() { throw new UnsupportedOperationException(); } public String getLocalName() { throw new UnsupportedOperationException(); } public int getLocalPort() { throw new UnsupportedOperationException(); } public Locale getLocale() { throw new UnsupportedOperationException(); } public Enumeration getLocales() { throw new UnsupportedOperationException(); } public Map getParameterMap() { throw new UnsupportedOperationException(); } public Enumeration getParameterNames() { throw new UnsupportedOperationException(); } public String getProtocol() { throw new UnsupportedOperationException(); } public BufferedReader getReader() throws IOException { throw new UnsupportedOperationException(); } public String getRealPath(String path) { throw new UnsupportedOperationException(); } public String getRemoteAddr() { throw new UnsupportedOperationException(); } public String getRemoteHost() { throw new UnsupportedOperationException(); } public int getRemotePort() { throw new UnsupportedOperationException(); } public RequestDispatcher getRequestDispatcher(String path) { throw new UnsupportedOperationException(); } public String getScheme() { throw new UnsupportedOperationException(); } public String getServerName() { throw new UnsupportedOperationException(); } public int getServerPort() { throw new UnsupportedOperationException(); } public boolean isSecure() { throw new UnsupportedOperationException(); } public void removeAttribute(String name) { throw new UnsupportedOperationException(); } public void setAttribute(String name, Object o) { throw new UnsupportedOperationException(); } public void setCharacterEncoding(String env) { throw new UnsupportedOperationException(); } public boolean checkIfModified(Calendar timestampOfResource, StaplerResponse rsp) { throw new UnsupportedOperationException(); } public boolean checkIfModified(long timestampOfResource, StaplerResponse rsp, long expiration) { throw new UnsupportedOperationException(); } }
[FIXED HUDSON-5003] Implemented MockStaplerRequest.getOriginalRestOfPath and getStapler This allows the plugin to compile with the latest version of Stapler
src/test/java/hudson/plugins/git/MockStaplerRequest.java
[FIXED HUDSON-5003] Implemented MockStaplerRequest.getOriginalRestOfPath and getStapler
<ide><path>rc/test/java/hudson/plugins/git/MockStaplerRequest.java <ide> <ide> import org.apache.commons.fileupload.FileItem; <ide> import org.kohsuke.stapler.Ancestor; <add>import org.kohsuke.stapler.Stapler; <ide> import org.kohsuke.stapler.StaplerRequest; <ide> import org.kohsuke.stapler.StaplerResponse; <ide> <ide> return this; <ide> } <ide> <add> public Stapler getStapler() { <add> throw new UnsupportedOperationException(); <add> } <add> <ide> public <T> T bindJSON(Class<T> type, JSONObject src) { <ide> throw new UnsupportedOperationException(); <ide> } <ide> throw new UnsupportedOperationException(); <ide> } <ide> <add> public String getOriginalRestOfPath() { <add> throw new UnsupportedOperationException(); <add> } <add> <ide> public String getRootPath() { <ide> throw new UnsupportedOperationException(); <ide> }
Java
mit
5bb8640d78c4e765fe0aaa574b3485aa8e7e38e4
0
games647/FastLogin,sgdc3/FastLogin,AuthMe/FastLogin
package com.github.games647.fastlogin.bukkit.tasks; import com.github.games647.fastlogin.bukkit.FastLoginBukkit; import com.github.games647.fastlogin.bukkit.hooks.AuthMeHook; import com.github.games647.fastlogin.bukkit.hooks.CrazyLoginHook; import com.github.games647.fastlogin.bukkit.hooks.LogItHook; import com.github.games647.fastlogin.bukkit.hooks.LoginSecurityHook; import com.github.games647.fastlogin.bukkit.hooks.UltraAuthHook; import com.github.games647.fastlogin.bukkit.hooks.xAuthHook; import com.github.games647.fastlogin.core.hooks.AuthPlugin; import com.google.common.collect.Lists; import java.util.List; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class DelayedAuthHook implements Runnable { private final FastLoginBukkit plugin; public DelayedAuthHook(FastLoginBukkit plugin) { this.plugin = plugin; } @Override public void run() { boolean hookFound = plugin.getCore().getAuthPluginHook() != null || registerHooks(); if (plugin.isBungeeCord()) { plugin.getLogger().info("BungeeCord setting detected. No auth plugin is required"); } else if (!hookFound) { plugin.getLogger().warning("No auth plugin were found by this plugin " + "(other plugins could hook into this after the intialization of this plugin)" + "and bungeecord is deactivated. " + "Either one or both of the checks have to pass in order to use this plugin"); } } private boolean registerHooks() { AuthPlugin<Player> authPluginHook = null; try { @SuppressWarnings("unchecked") List<Class<? extends AuthPlugin<Player>>> supportedHooks = Lists.newArrayList(AuthMeHook.class , CrazyLoginHook.class, LogItHook.class, LoginSecurityHook.class, UltraAuthHook.class , xAuthHook.class); for (Class<? extends AuthPlugin<Player>> clazz : supportedHooks) { String pluginName = clazz.getSimpleName().replace("Hook", ""); //uses only member classes which uses AuthPlugin interface (skip interfaces) if (Bukkit.getServer().getPluginManager().getPlugin(pluginName) != null) { //check only for enabled plugins. A single plugin could be disabled by plugin managers authPluginHook = clazz.newInstance(); plugin.getLogger().log(Level.INFO, "Hooking into auth plugin: {0}", pluginName); break; } } } catch (InstantiationException | IllegalAccessException ex) { plugin.getLogger().log(Level.SEVERE, "Couldn't load the integration class", ex); } if (authPluginHook == null) { //run this check for exceptions (errors) and not found plugins plugin.getLogger().warning("No support offline Auth plugin found. "); return false; } if (plugin.getCore().getAuthPluginHook() == null) { plugin.getCore().setAuthPluginHook(authPluginHook); plugin.setServerStarted(); } return true; } }
bukkit/src/main/java/com/github/games647/fastlogin/bukkit/tasks/DelayedAuthHook.java
package com.github.games647.fastlogin.bukkit.tasks; import com.github.games647.fastlogin.bukkit.FastLoginBukkit; import com.github.games647.fastlogin.bukkit.hooks.AuthMeHook; import com.github.games647.fastlogin.bukkit.hooks.CrazyLoginHook; import com.github.games647.fastlogin.bukkit.hooks.LogItHook; import com.github.games647.fastlogin.bukkit.hooks.LoginSecurityHook; import com.github.games647.fastlogin.bukkit.hooks.UltraAuthHook; import com.github.games647.fastlogin.bukkit.hooks.xAuthHook; import com.github.games647.fastlogin.core.hooks.AuthPlugin; import com.google.common.collect.Lists; import java.util.List; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class DelayedAuthHook implements Runnable { private final FastLoginBukkit plugin; public DelayedAuthHook(FastLoginBukkit plugin) { this.plugin = plugin; } @Override public void run() { boolean hookFound = registerHooks(); if (plugin.isBungeeCord()) { plugin.getLogger().info("BungeeCord setting detected. No auth plugin is required"); } else if (!hookFound) { plugin.getLogger().warning("No auth plugin were found by this plugin " + "(other plugins could hook into this after the intialization of this plugin)" + "and bungeecord is deactivated. " + "Either one or both of the checks have to pass in order to use this plugin"); } } private boolean registerHooks() { AuthPlugin<Player> authPluginHook = null; try { @SuppressWarnings("unchecked") List<Class<? extends AuthPlugin<Player>>> supportedHooks = Lists.newArrayList(AuthMeHook.class , CrazyLoginHook.class, LogItHook.class, LoginSecurityHook.class, UltraAuthHook.class , xAuthHook.class); for (Class<? extends AuthPlugin<Player>> clazz : supportedHooks) { String pluginName = clazz.getSimpleName().replace("Hook", ""); //uses only member classes which uses AuthPlugin interface (skip interfaces) if (Bukkit.getServer().getPluginManager().getPlugin(pluginName) != null) { //check only for enabled plugins. A single plugin could be disabled by plugin managers authPluginHook = clazz.newInstance(); plugin.getLogger().log(Level.INFO, "Hooking into auth plugin: {0}", pluginName); break; } } } catch (InstantiationException | IllegalAccessException ex) { plugin.getLogger().log(Level.SEVERE, "Couldn't load the integration class", ex); } if (authPluginHook == null) { //run this check for exceptions (errors) and not found plugins plugin.getLogger().warning("No support offline Auth plugin found. "); return false; } if (plugin.getCore().getAuthPluginHook() == null) { plugin.getCore().setAuthPluginHook(authPluginHook); plugin.setServerStarted(); } return true; } }
Do not try to hook into a plugin if auth plugin hook is already set using the FastLogin API
bukkit/src/main/java/com/github/games647/fastlogin/bukkit/tasks/DelayedAuthHook.java
Do not try to hook into a plugin if auth plugin hook is already set using the FastLogin API
<ide><path>ukkit/src/main/java/com/github/games647/fastlogin/bukkit/tasks/DelayedAuthHook.java <ide> <ide> @Override <ide> public void run() { <del> boolean hookFound = registerHooks(); <add> boolean hookFound = plugin.getCore().getAuthPluginHook() != null || registerHooks(); <ide> if (plugin.isBungeeCord()) { <ide> plugin.getLogger().info("BungeeCord setting detected. No auth plugin is required"); <ide> } else if (!hookFound) { <ide> plugin.getCore().setAuthPluginHook(authPluginHook); <ide> plugin.setServerStarted(); <ide> } <del> <add> <ide> return true; <ide> } <ide> }
Java
apache-2.0
60b6c06106e07e23133b2fcd0839ec87289085cc
0
kite-sdk/kite-examples,yuzhu712/cdk-examples,yuzhu712/cdk-examples,kite-sdk/kite-examples,cloudera/cdk-examples,cloudera/cdk-examples,kite-sdk/kite-examples
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.cdk.examples.logging; import com.cloudera.cdk.data.Dataset; import com.cloudera.cdk.data.DatasetReader; import com.cloudera.cdk.data.DatasetRepository; import com.cloudera.cdk.data.filesystem.FileSystemDatasetRepository; import java.net.URI; import org.apache.avro.generic.GenericRecord; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * Read all the event objects from the events dataset using Avro generic records. */ public class ReadDataset extends Configured implements Tool { @Override public int run(String[] args) throws Exception { // Construct a local filesystem dataset repository rooted at /tmp/data DatasetRepository repo = new FileSystemDatasetRepository.Builder() .rootDirectory(new URI("/tmp/data")).configuration(getConf()).get(); // Get the events dataset Dataset events = repo.get("events"); // Get a reader for the dataset and read all the events DatasetReader<GenericRecord> reader = events.getReader(); try { reader.open(); for (GenericRecord event : reader) { System.out.println(event); } } finally { reader.close(); } return 0; } public static void main(String... args) throws Exception { int rc = ToolRunner.run(new ReadDataset(), args); System.exit(rc); } }
logging/src/main/java/com/cloudera/cdk/examples/logging/ReadDataset.java
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.cdk.examples.logging; import com.cloudera.cdk.data.Dataset; import com.cloudera.cdk.data.DatasetReader; import com.cloudera.cdk.data.DatasetRepository; import com.cloudera.cdk.data.filesystem.FileSystemDatasetRepository; import java.net.URI; import org.apache.avro.generic.GenericRecord; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * Read all the event objects from the events dataset using Avro generic records. */ public class ReadDataset extends Configured implements Tool { @Override public int run(String[] args) throws Exception { // Construct a local filesystem dataset repository rooted at /tmp/data DatasetRepository repo = new FileSystemDatasetRepository.Builder() .rootDirectory(new URI("/tmp/data")).configuration(getConf()).get(); // Get the events dataset Dataset events = repo.get("events"); // Get a reader for the dataset and read all the events DatasetReader<GenericRecord> reader = events.getReader(); try { reader.open(); while (reader.hasNext()) { GenericRecord event = reader.read(); System.out.println(event); } } finally { reader.close(); } return 0; } public static void main(String... args) throws Exception { int rc = ToolRunner.run(new ReadDataset(), args); System.exit(rc); } }
Updating ReadDataset for 0.7.0 API.
logging/src/main/java/com/cloudera/cdk/examples/logging/ReadDataset.java
Updating ReadDataset for 0.7.0 API.
<ide><path>ogging/src/main/java/com/cloudera/cdk/examples/logging/ReadDataset.java <ide> DatasetReader<GenericRecord> reader = events.getReader(); <ide> try { <ide> reader.open(); <del> while (reader.hasNext()) { <del> GenericRecord event = reader.read(); <add> for (GenericRecord event : reader) { <ide> System.out.println(event); <ide> } <ide> } finally {
Java
epl-1.0
b44b930ff8dc3783a1a09e36dc62ce301ef774d3
0
ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder
/** * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * Copyright (C) 2016 European Spallation Source ERIC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.csstudio.display.builder.representation.javafx; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import org.controlsfx.control.PopOver; import org.csstudio.display.builder.model.persist.NamedWidgetColors; import org.csstudio.display.builder.model.persist.WidgetColorService; import org.csstudio.display.builder.model.properties.ColorWidgetProperty; import org.csstudio.display.builder.model.properties.NamedWidgetColor; import org.csstudio.display.builder.model.properties.WidgetColor; import org.csstudio.display.builder.model.util.ModelThreadPool; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ColorPicker; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Slider; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; /** * @author claudiorosati, European Spallation Source ERIC * @version 1.0.0 29 Nov 2017 */ public class WidgetColorPopOver implements Initializable { @FXML private ListView<NamedWidgetColor> colorNames; @FXML private ColorPicker picker; @FXML private Slider redSlider; @FXML private Slider greenSlider; @FXML private Slider blueSlider; @FXML private Slider alphaSlider; @FXML private Spinner<Integer> redSpinner; @FXML private Spinner<Integer> greenSpinner; @FXML private Spinner<Integer> blueSpinner; @FXML private Spinner<Integer> alphaSpinner; @FXML private Circle currentColorCircle; @FXML private Circle restoreColorCircle; @FXML private Button restoreButton; @FXML private Button cancelButton; @FXML private Button okButton; private Consumer<WidgetColor> colorChangeConsumer; private PopOver popOver; private final AtomicBoolean namesLoaded = new AtomicBoolean(false); private final Map<Color, NamedWidgetColor> namedColors = Collections.synchronizedMap(new HashMap<>()); private Color restoreColor = null; private boolean updating = false; /* * ---- color property ----------------------------------------------------- */ private final ObjectProperty<Color> color = new SimpleObjectProperty<Color>(this, "color", Color.GOLDENROD) { @Override protected void invalidated() { Color col = get(); if ( col == null ) { set(Color.GOLDENROD); } } }; ObjectProperty<Color> colorProperty() { return color; } Color getColor() { return color.get(); } void setColor( Color color ) { this.color.set(color); } /* * ------------------------------------------------------------------------- */ @Override public void initialize( URL location, ResourceBundle resources ) { picker.valueProperty().bindBidirectional(colorProperty()); currentColorCircle.fillProperty().bind(colorProperty()); okButton.disableProperty().bind(Bindings.createBooleanBinding(() -> getColor().equals(restoreColor), colorProperty())); restoreButton.disableProperty().bind(Bindings.createBooleanBinding(() -> getColor().equals(restoreColor), colorProperty())); redSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); redSpinner.valueProperty().addListener(this::updateFromSpinner); greenSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); greenSpinner.valueProperty().addListener(this::updateFromSpinner); blueSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); blueSpinner.valueProperty().addListener(this::updateFromSpinner); alphaSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); alphaSpinner.valueProperty().addListener(this::updateFromSpinner); redSlider.valueProperty().addListener(this::updateFromSlider); greenSlider.valueProperty().addListener(this::updateFromSlider); blueSlider.valueProperty().addListener(this::updateFromSlider); alphaSlider.valueProperty().addListener(this::updateFromSlider); colorProperty().addListener(( observable, oldValue, newValue ) -> { updating = true; if ( namedColors.containsKey(newValue) ) { colorNames.getSelectionModel().select(namedColors.get(newValue)); } redSlider.setValue(getRed()); redSpinner.getValueFactory().setValue(getRed()); greenSlider.setValue(getGreen()); greenSpinner.getValueFactory().setValue(getGreen()); blueSlider.setValue(getBlue()); blueSpinner.getValueFactory().setValue(getBlue()); alphaSlider.setValue(getAlpha()); alphaSpinner.getValueFactory().setValue(getAlpha()); updating = false; }); colorNames.setCellFactory(view -> new NamedWidgetColorCell()); colorNames.getSelectionModel().selectedItemProperty().addListener(( observable, oldValue, newValue ) -> { if ( newValue != null ) { setColor(JFXUtil.convert(newValue)); } }); // Get colors on background thread ModelThreadPool.getExecutor().execute( ( ) -> { final NamedWidgetColors colors = WidgetColorService.getColors(); final Collection<NamedWidgetColor> values = colors.getColors(); values.parallelStream().forEach(nc -> namedColors.put(JFXUtil.convert(nc), nc)); Platform.runLater(() -> { values.stream().forEach(nc -> { colorNames.getItems().addAll(nc); picker.getCustomColors().add(JFXUtil.convert(nc)); }); namesLoaded.set(true); }); }); } @FXML void cancelPressed ( ActionEvent event ) { if ( popOver != null ) { popOver.hide(); } } @FXML void okPressed ( ActionEvent event ) { if ( colorChangeConsumer != null ) { colorChangeConsumer.accept(JFXUtil.convert(getColor())); } cancelPressed(event); } @FXML void restoreColorClicked ( MouseEvent event ) { setColor(restoreColor); } @FXML void restorePressed ( ActionEvent event ) { setColor(restoreColor); } void setInitialConditions ( final PopOver popOver, final ColorWidgetProperty property, final Consumer<WidgetColor> colorChangeConsumer ) { WidgetColor widgetColor = property.getValue(); this.colorChangeConsumer = colorChangeConsumer; this.popOver = popOver; this.restoreColor = JFXUtil.convert(widgetColor); restoreColorCircle.setFill(restoreColor); setColor(restoreColor); ModelThreadPool.getExecutor().execute( ( ) -> { while ( !namesLoaded.get() ) { Thread.yield(); } Platform.runLater(() -> { if ( widgetColor instanceof NamedWidgetColor ) { colorNames.getSelectionModel().select((NamedWidgetColor) widgetColor); colorNames.scrollTo(colorNames.getSelectionModel().getSelectedIndex()); } }); }); } private int getAlpha() { Color c = getColor(); return c.isOpaque() ? 255 : (int) ( 255 * c.getOpacity() ); } private int getBlue() { return (int) ( 255 * getColor().getBlue() ); } private int getGreen() { return (int) ( 255 * getColor().getGreen() ); } private int getRed() { return (int) ( 255 * getColor().getRed() ); } private Color getSliderColor ( ) { return Color.rgb( (int) redSlider.getValue(), (int) greenSlider.getValue(), (int) blueSlider.getValue(), (int) alphaSlider.getValue() / 255.0 ); } private Color getSpinnerColor ( ) { return Color.rgb( Math.max(0, Math.min(255, redSpinner.getValue())), Math.max(0, Math.min(255, greenSpinner.getValue())), Math.max(0, Math.min(255, blueSpinner.getValue())), Math.max(0, Math.min(255, alphaSpinner.getValue() / 255.0)) ); } private void updateFromSlider ( ObservableValue<? extends Number> observable, Number oldValue, Number newValue ) { if ( !updating ) { setColor(getSliderColor()); } } private void updateFromSpinner ( ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue ) { if ( !updating ) { setColor(getSpinnerColor()); } } /** * List cell for a NamedWidgetColor: Color 'blob' and color's name. */ private static class NamedWidgetColorCell extends ListCell<NamedWidgetColor> { private final static int SIZE = 16; private final Canvas blob = new Canvas(SIZE, SIZE); NamedWidgetColorCell ( ) { setGraphic(blob); } @Override protected void updateItem ( final NamedWidgetColor color, final boolean empty ) { super.updateItem(color, empty); if ( color == null ) { // Content won't change from non-null to null, so no need to clear. return; } setText(color.getName()); final GraphicsContext gc = blob.getGraphicsContext2D(); gc.setFill(JFXUtil.convert(color)); gc.fillRect(0, 0, SIZE, SIZE); } }; }
org.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/WidgetColorPopOver.java
/** * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * Copyright (C) 2016 European Spallation Source ERIC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.csstudio.display.builder.representation.javafx; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import org.controlsfx.control.PopOver; import org.csstudio.display.builder.model.persist.NamedWidgetColors; import org.csstudio.display.builder.model.persist.WidgetColorService; import org.csstudio.display.builder.model.properties.ColorWidgetProperty; import org.csstudio.display.builder.model.properties.NamedWidgetColor; import org.csstudio.display.builder.model.properties.WidgetColor; import org.csstudio.display.builder.model.util.ModelThreadPool; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ColorPicker; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Slider; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; /** * @author claudiorosati, European Spallation Source ERIC * @version 1.0.0 29 Nov 2017 */ public class WidgetColorPopOver { @FXML private ListView<NamedWidgetColor> colorNames; @FXML private ColorPicker picker; @FXML private Slider redSlider; @FXML private Slider greenSlider; @FXML private Slider blueSlider; @FXML private Slider alphaSlider; @FXML private Spinner<Integer> redSpinner; @FXML private Spinner<Integer> greenSpinner; @FXML private Spinner<Integer> blueSpinner; @FXML private Spinner<Integer> alphaSpinner; @FXML private Circle currentColorCircle; @FXML private Circle restoreColorCircle; @FXML private Button restoreButton; @FXML private Button cancelButton; @FXML private Button okButton; private Consumer<WidgetColor> colorChangeConsumer; private PopOver popOver; private final AtomicBoolean namesLoaded = new AtomicBoolean(false); private final Map<Color, NamedWidgetColor> namedColors = Collections.synchronizedMap(new HashMap<>()); private Color restoreColor = null; private boolean updating = false; /* * ---- color property ----------------------------------------------------- */ private final ObjectProperty<Color> color = new SimpleObjectProperty<Color>(this, "color", Color.GOLDENROD) { @Override protected void invalidated() { Color col = get(); if ( col == null ) { set(Color.GOLDENROD); } } }; ObjectProperty<Color> colorProperty() { return color; } Color getColor() { return color.get(); } void setColor( Color color ) { this.color.set(color); } /* * ------------------------------------------------------------------------- */ public void initialize() { picker.valueProperty().bindBidirectional(colorProperty()); currentColorCircle.fillProperty().bind(colorProperty()); okButton.disableProperty().bind(Bindings.createBooleanBinding(() -> getColor().equals(restoreColor), colorProperty())); restoreButton.disableProperty().bind(Bindings.createBooleanBinding(() -> getColor().equals(restoreColor), colorProperty())); redSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); redSpinner.valueProperty().addListener(this::updateFromSpinner); greenSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); greenSpinner.valueProperty().addListener(this::updateFromSpinner); blueSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); blueSpinner.valueProperty().addListener(this::updateFromSpinner); alphaSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255)); alphaSpinner.valueProperty().addListener(this::updateFromSpinner); redSlider.valueProperty().addListener(this::updateFromSlider); greenSlider.valueProperty().addListener(this::updateFromSlider); blueSlider.valueProperty().addListener(this::updateFromSlider); alphaSlider.valueProperty().addListener(this::updateFromSlider); colorProperty().addListener(( observable, oldValue, newValue ) -> { updating = true; if ( namedColors.containsKey(newValue) ) { colorNames.getSelectionModel().select(namedColors.get(newValue)); } redSlider.setValue(getRed()); redSpinner.getValueFactory().setValue(getRed()); greenSlider.setValue(getGreen()); greenSpinner.getValueFactory().setValue(getGreen()); blueSlider.setValue(getBlue()); blueSpinner.getValueFactory().setValue(getBlue()); alphaSlider.setValue(getAlpha()); alphaSpinner.getValueFactory().setValue(getAlpha()); updating = false; }); colorNames.setCellFactory(view -> new NamedWidgetColorCell()); colorNames.getSelectionModel().selectedItemProperty().addListener(( observable, oldValue, newValue ) -> { if ( newValue != null ) { setColor(JFXUtil.convert(newValue)); } }); // Get colors on background thread ModelThreadPool.getExecutor().execute( ( ) -> { final NamedWidgetColors colors = WidgetColorService.getColors(); final Collection<NamedWidgetColor> values = colors.getColors(); values.parallelStream().forEach(nc -> namedColors.put(JFXUtil.convert(nc), nc)); Platform.runLater(() -> { values.stream().forEach(nc -> { colorNames.getItems().addAll(nc); picker.getCustomColors().add(JFXUtil.convert(nc)); }); namesLoaded.set(true); }); }); } @FXML void cancelPressed ( ActionEvent event ) { if ( popOver != null ) { popOver.hide(); } } @FXML void okPressed ( ActionEvent event ) { if ( colorChangeConsumer != null ) { colorChangeConsumer.accept(JFXUtil.convert(getColor())); } cancelPressed(event); } @FXML void restoreColorClicked ( MouseEvent event ) { setColor(restoreColor); } @FXML void restorePressed ( ActionEvent event ) { setColor(restoreColor); } void setInitialConditions ( final PopOver popOver, final ColorWidgetProperty property, final Consumer<WidgetColor> colorChangeConsumer ) { WidgetColor widgetColor = property.getValue(); this.colorChangeConsumer = colorChangeConsumer; this.popOver = popOver; this.restoreColor = JFXUtil.convert(widgetColor); restoreColorCircle.setFill(restoreColor); setColor(restoreColor); ModelThreadPool.getExecutor().execute( ( ) -> { while ( !namesLoaded.get() ) { Thread.yield(); } Platform.runLater(() -> { if ( widgetColor instanceof NamedWidgetColor ) { colorNames.getSelectionModel().select((NamedWidgetColor) widgetColor); colorNames.scrollTo(colorNames.getSelectionModel().getSelectedIndex()); } }); }); } private int getAlpha() { Color c = getColor(); return c.isOpaque() ? 255 : (int) ( 255 * c.getOpacity() ); } private int getBlue() { return (int) ( 255 * getColor().getBlue() ); } private int getGreen() { return (int) ( 255 * getColor().getGreen() ); } private int getRed() { return (int) ( 255 * getColor().getRed() ); } private Color getSliderColor ( ) { return Color.rgb( (int) redSlider.getValue(), (int) greenSlider.getValue(), (int) blueSlider.getValue(), (int) alphaSlider.getValue() / 255.0 ); } private Color getSpinnerColor ( ) { return Color.rgb( Math.max(0, Math.min(255, redSpinner.getValue())), Math.max(0, Math.min(255, greenSpinner.getValue())), Math.max(0, Math.min(255, blueSpinner.getValue())), Math.max(0, Math.min(255, alphaSpinner.getValue() / 255.0)) ); } private void updateFromSlider ( ObservableValue<? extends Number> observable, Number oldValue, Number newValue ) { if ( !updating ) { setColor(getSliderColor()); } } private void updateFromSpinner ( ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue ) { if ( !updating ) { setColor(getSpinnerColor()); } } /** * List cell for a NamedWidgetColor: Color 'blob' and color's name. */ private static class NamedWidgetColorCell extends ListCell<NamedWidgetColor> { private final static int SIZE = 16; private final Canvas blob = new Canvas(SIZE, SIZE); NamedWidgetColorCell ( ) { setGraphic(blob); } @Override protected void updateItem ( final NamedWidgetColor color, final boolean empty ) { super.updateItem(color, empty); if ( color == null ) { // Content won't change from non-null to null, so no need to clear. return; } setText(color.getName()); final GraphicsContext gc = blob.getGraphicsContext2D(); gc.setFill(JFXUtil.convert(color)); gc.fillRect(0, 0, SIZE, SIZE); } }; }
Using explicit initialiser.
org.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/WidgetColorPopOver.java
Using explicit initialiser.
<ide><path>rg.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/WidgetColorPopOver.java <ide> package org.csstudio.display.builder.representation.javafx; <ide> <ide> <add>import java.net.URL; <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.Map; <add>import java.util.ResourceBundle; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> import java.util.function.Consumer; <ide> <ide> import javafx.beans.value.ObservableValue; <ide> import javafx.event.ActionEvent; <ide> import javafx.fxml.FXML; <add>import javafx.fxml.Initializable; <ide> import javafx.scene.canvas.Canvas; <ide> import javafx.scene.canvas.GraphicsContext; <ide> import javafx.scene.control.Button; <ide> * @author claudiorosati, European Spallation Source ERIC <ide> * @version 1.0.0 29 Nov 2017 <ide> */ <del>public class WidgetColorPopOver { <add>public class WidgetColorPopOver implements Initializable { <ide> <ide> @FXML <ide> private ListView<NamedWidgetColor> colorNames; <ide> /* <ide> * ------------------------------------------------------------------------- <ide> */ <del> public void initialize() { <add> @Override <add> public void initialize( URL location, ResourceBundle resources ) { <ide> <ide> picker.valueProperty().bindBidirectional(colorProperty()); <ide> currentColorCircle.fillProperty().bind(colorProperty());
JavaScript
mit
193d3f56a5e907f648db9bda77fd446d714dd784
0
eschwartz/backbone.googlemaps,eschwartz/backbone.googlemaps
/** * Backbone.GoogleMaps * A Backbone JS layer for the GoogleMaps API * Copyright (c)2012 Edan Schwartz * Distributed under MIT license * https://github.com/eschwartz/backbone.googlemaps */ Backbone.GoogleMaps = (function(Backbone, _, $){ var GoogleMaps = {}; /** * GoogleMaps.Location * -------------------- * Representing a lat/lng location on a map */ GoogleMaps.Location = Backbone.Model.extend({ constructor: function() { _.bindAll(this, 'select', 'deselect', 'toggleSelect', 'getLatlng'); this.defaults = _.extend({}, this.defaults, { lat : 0, lng : 0, selected : false, title : "" }); Backbone.Model.prototype.constructor.apply(this, arguments); }, select: function() { if(!this.get("selected")) { this.set("selected", true); this.trigger('selected', this); } }, deselect: function() { if(this.get("selected")) { this.set("selected", false); this.trigger('deselected', this); } }, toggleSelect: function() { if(this.get("selected")) { this.deselect(); } else { this.select(); } }, getLatlng: function() { return new google.maps.LatLng(this.get("lat"), this.get("lng")); } }); /** * GoogleMaps.LocationCollection * ------------------------------ * A collection of map locations */ GoogleMaps.LocationCollection = Backbone.Collection.extend({ model: GoogleMaps.Location, constructor: function() { Backbone.Collection.prototype.constructor.apply(this, arguments); // Deselect other models on model select // ie. Only a single model can be selected in a collection this.on("selected", function(selectedModel) { this.each(function(model) { if(selectedModel.cid !== model.cid) { model.deselect(); } }); }, this); } }); /** * GoogleMaps.MapView * ------------------ * Base maps overlay view from which all other overlay views extend */ GoogleMaps.MapView = Backbone.View.extend({ // Hash of Google Map events // Events will be attached to this.gOverlay (google map or overlay) // eg `zoom_changed': 'handleZoomChange' mapEvents: {}, overlayOptions: {}, constructor: function() { Backbone.View.prototype.constructor.apply(this, arguments); // Ensure map and API loaded if(!google || !google.maps) throw new Error("Google maps API is not loaded."); if(!this.options.map && !this.map) throw new Error("A map must be specified."); this.gOverlay = this.map = this.options.map || this.map; // Set this.overlay options this.overlayOptions || (this.overlayOptions = this.options.overlayOptions); }, // Attach listeners to the this.gOverlay // From the `mapEvents` hash bindMapEvents: function(mapEvents) { mapEvents || (mapEvents = this.mapEvents); for(event in this.mapEvents) { var handler = this.mapEvents[event]; google.maps.event.addListener(this.gOverlay, event, this[handler]); } }, render: function() { if(this.beforeRender) { this.beforeRender(); } this.bindMapEvents(); if(this.onRender) { this.onRender(); } }, // Clean up view // Remove overlay from map and remove event listeners close: function() { if(this.beforeClose) { this.beforeClose(); } google.maps.event.clearInstanceListeners(this.gOverlay); this.gOverlay.setMap(null); this.gOverlay = null; } }); /** * GoogleMaps.InfoWindow * --------------------- * View controller for a google.maps.InfoWindow overlay instance */ GoogleMaps.InfoWindow = GoogleMaps.MapView.extend({ constructor: function() { GoogleMaps.MapView.prototype.constructor.apply(this, arguments); _.bindAll(this, 'render', 'close'); // Require a related marker instance if(!this.options.marker && !this.marker) throw new Error("A marker must be specified for InfoWindow view."); this.marker = this.options.marker || this.marker; // Set InfoWindow template this.template = this.template || this.options.template; }, // Render render: function() { if(this.beforeRender) { this.beforeRender(); } GoogleMaps.MapView.prototype.render.apply(this, arguments); // Render element var tmpl = (this.template)? $(this.template).html(): '<h2><%=title %></h2>'; this.$el.html(_.template(tmpl, this.model.toJSON())); // Create InfoWindow this.gOverlay = new google.maps.InfoWindow(_.extend({ content: this.$el[0] }, this.overlayOptions)); // Display InfoWindow on map this.gOverlay.open(this.map, this.marker); if(this.onRender) { this.onRender(); } return this; }, // Close and delete window, and clean up view close: function() { if(this.beforeClose) { this.beforeClose(); } GoogleMaps.MapView.prototype.close.apply(this, arguments); if(this.onClose) { this.onClose(); } return this; } }); /** * GoogleMaps.MarkerView * --------------------- * View controller for a marker overlay */ GoogleMaps.MarkerView = GoogleMaps.MapView.extend({ // Set associated InfoWindow view infoWindow: GoogleMaps.InfoWindow, constructor: function() { GoogleMaps.MapView.prototype.constructor.apply(this, arguments); _.bindAll(this, 'render', 'close', 'openDetail', 'closeDetail', 'toggleSelect'); // Ensure model if(!this.model) throw new Error("A model must be specified for a MarkerView"); // Instantiate marker, with user defined properties this.gOverlay = new google.maps.Marker(_.extend({ position: this.model.getLatlng(), map: this.map, title: this.model.title, animation: google.maps.Animation.DROP, visible: false // hide, until render }, this.overlayOptions)); // Add default mapEvents _.extend(this.mapEvents, { 'click' : 'toggleSelect' // Select model on marker click }); // Show detail view on model select this.model.on("selected", this.openDetail, this); this.model.on("deselected", this.closeDetail, this); }, toggleSelect: function() { this.model.toggleSelect(); }, // Show the google maps marker overlay render: function() { if(this.beforeRender) { this.beforeRender(); } GoogleMaps.MapView.prototype.render.apply(this, arguments); this.gOverlay.setVisible(true); if(this.onRender) { this.onRender(); } return this; }, close: function() { if(this.beforeClose) { this.beforeClose(); } this.closeDetail(); GoogleMaps.MapView.prototype.close.apply(this, arguments); this.model.off(); if(this.onClose) { this.onClose() } return this; }, openDetail: function() { this.detailView = new this.infoWindow({ model: this.model, map: this.options.map, marker: this.gOverlay }); this.detailView.render(); }, closeDetail: function() { if(this.detailView) { this.detailView.close(); this.detailView = null; } } }); /** * GoogleMaps.MarkerCollectionView * ------------------------------- * Collection of MarkerViews */ GoogleMaps.MarkerCollectionView = Backbone.View.extend({ markerView: GoogleMaps.MarkerView, markerViewChildren: {}, constructor: function() { Backbone.View.prototype.constructor.apply(this, arguments); _.bindAll(this, 'render', 'closeChildren', 'closeChild', 'addChild', 'refresh', 'close'); // Ensure map property if(!this.options.map && !this.map) throw new Error("A map must be specified on MarkerCollectionView instantiation"); this.map || (this.map = this.options.map); // Bind to collection this.collection.on("reset", this.refresh, this); this.collection.on("add", this.addChild, this); this.collection.on("remove", this.closeChild, this); }, // Render MarkerViews for all models in collection render: function(collection) { var collection = collection || this.collection; // Create marker views for each model collection.each(this.addChild); }, // Close all child MarkerViews closeChildren: function() { for(cid in this.markerViewChildren) { this.closeChild(this.markerViewChildren[cid]); } }, closeChild: function(child) { // Param can be child's model, or child view itself var childView = (child instanceof Backbone.Model)? this.markerViewChildren[child.cid]: child; childView.close(); delete this.markerViewChildren[childView.model.cid]; }, // Add a MarkerView and render addChild: function(childModel) { var markerView = new this.markerView({ model: childModel, map: this.map, }); this.markerViewChildren[childModel.cid] = markerView; markerView.render(); }, refresh: function() { this.closeChildren(); this.render(); }, // Close all child MarkerViews close: function() { this.closeChildren(); this.collection.off(); } }) return GoogleMaps; })(Backbone, _, window.jQuery || window.Zepto || window.ender);
lib/backbone.googlemaps.js
/** * Backbone.GoogleMaps * A Backbone JS layer for the GoogleMaps API * Copyright (c)2012 Edan Schwartz * Distributed under MIT license * https://github.com/eschwartz/backbone.googlemaps */ Backbone.GoogleMaps = (function(Backbone, _, $){ var GoogleMaps = {}; /** * GoogleMaps.Location * -------------------- * Representing a lat/lng location on a map */ GoogleMaps.Location = Backbone.Model.extend({ constructor: function() { _.bindAll(this, 'select', 'deselect', 'toggleSelect', 'getLatlng'); this.defaults = _.extend({}, this.defaults, { lat : 0, lng : 0, selected : false, title : "" }); Backbone.Model.prototype.constructor.apply(this, arguments); }, select: function() { if(!this.get("selected")) { this.set("selected", true); this.trigger('selected', this); } }, deselect: function() { if(this.get("selected")) { this.set("selected", false); this.trigger('deselected', this); } }, toggleSelect: function() { if(this.get("selected")) { this.deselect(); } else { this.select(); } }, getLatlng: function() { return new google.maps.LatLng(this.get("lat"), this.get("lng")); } }); /** * GoogleMaps.LocationCollection * ------------------------------ * A collection of map locations */ GoogleMaps.LocationCollection = Backbone.Collection.extend({ model: GoogleMaps.Location, constructor: function() { Backbone.Collection.prototype.constructor.apply(this, arguments); // Deselect other models on model select // ie. Only a single model can be selected in a collection this.on("selected", function(selectedModel) { this.each(function(model) { if(selectedModel.cid !== model.cid) { model.deselect(); } }); }, this); } }); /** * GoogleMaps.MapView * ------------------ * Base maps overlay view from which all other overlay views extend */ GoogleMaps.MapView = Backbone.View.extend({ // Hash of Google Map events // Events will be attached to this.gOverlay (google map or overlay) // eg `zoom_changed': 'handleZoomChange' mapEvents: {}, overlayOptions: {}, constructor: function() { Backbone.View.prototype.constructor.apply(this, arguments); // Ensure map and API loaded if(!google || !google.maps) throw new Error("Google maps API is not loaded."); if(!this.options.map && !this.map) throw new Error("A map must be specified."); this.gOverlay = this.map = this.options.map || this.map; // Set this.overlay options this.overlayOptions || (this.overlayOptions = this.options.overlayOptions); }, // Attach listeners to the this.gOverlay // From the `mapEvents` hash bindMapEvents: function(mapEvents) { mapEvents || (mapEvents = this.mapEvents); for(event in this.mapEvents) { var handler = this.mapEvents[event]; google.maps.event.addListener(this.gOverlay, event, this[handler]); } }, render: function() { if(this.beforeRender) { this.beforeRender(); } this.bindMapEvents(); if(this.onRender) { this.onRender(); } }, // Clean up view // Remove overlay from map and remove event listeners close: function() { if(this.beforeClose) { this.beforeClose(); } google.maps.event.clearInstanceListeners(this.gOverlay); this.gOverlay.setMap(null); this.gOverlay = null; } }); /** * GoogleMaps.InfoWindow * --------------------- * View controller for a google.maps.InfoWindow overlay instance */ GoogleMaps.InfoWindow = GoogleMaps.MapView.extend({ constructor: function() { GoogleMaps.MapView.prototype.constructor.apply(this, arguments); _.bindAll(this, 'render', 'close'); // Require a related marker instance if(!this.options.marker && !this.marker) throw new Error("A marker must be specified for InfoWindow view."); this.marker = this.options.marker || this.marker; // Set InfoWindow template this.template = this.template || this.options.template; }, // Render render: function() { if(this.beforeRender) { this.beforeRender(); } GoogleMaps.MapView.prototype.render.apply(this, arguments); // Render element var tmpl = (this.template)? $(this.template).html(): '<h2><%=title %></h2>'; this.$el.html(_.template(tmpl, this.model.toJSON())); // Create InfoWindow this.gOverlay = new google.maps.InfoWindow(_.extend({ content: this.$el[0] }, this.overlayOptions)); // Display InfoWindow on map this.gOverlay.open(this.map, this.marker); if(this.onRender) { this.onRender(); } return this; }, // Close and delete window, and clean up view close: function() { if(this.beforeClose) { this.beforeClose(); } GoogleMaps.MapView.prototype.close.apply(this, arguments); if(this.onClose) { this.onClose(); } return this; } }); /** * GoogleMaps.MarkerView * --------------------- * View controller for a marker overlay */ GoogleMaps.MarkerView = GoogleMaps.MapView.extend({ // Set associated InfoWindow view infoWindow: GoogleMaps.InfoWindow, constructor: function() { GoogleMaps.MapView.prototype.constructor.apply(this, arguments); _.bindAll(this, 'render', 'close', 'openDetail', 'closeDetail', 'toggleSelect'); // Ensure model if(!this.model) throw new Error("A model must be specified for a MarkerView"); // Instantiate marker, with user defined properties this.gOverlay = new google.maps.Marker(_.extend({ position: this.model.getLatlng(), map: this.map, title: this.model.title, animation: google.maps.Animation.DROP, visible: false // hide, until render }, this.overlayOptions)); // Add default mapEvents _.extend(this.mapEvents, { 'click' : 'toggleSelect' // Select model on marker click }); // Show detail view on model select this.model.on("selected", this.openDetail, this); this.model.on("deselected", this.closeDetail, this); }, toggleSelect: function() { this.model.toggleSelect(); }, // Show the google maps marker overlay render: function() { if(this.beforeRender) { this.beforeRender(); } GoogleMaps.MapView.prototype.render.apply(this, arguments); this.gOverlay.setVisible(true); if(this.onRender) { this.onRender(); } return this; }, close: function() { if(this.beforeClose) { this.beforeClose(); } this.closeDetail(); GoogleMaps.MapView.prototype.close.apply(this, arguments); if(this.onClose) { this.onClose() } return this; }, openDetail: function() { this.detailView = new this.infoWindow({ model: this.model, map: this.options.map, marker: this.gOverlay }); this.detailView.render(); }, closeDetail: function() { if(this.detailView) { this.detailView.close(); this.detailView = null; } } }); /** * GoogleMaps.MarkerCollectionView * ------------------------------- * Collection of MarkerViews */ GoogleMaps.MarkerCollectionView = Backbone.View.extend({ markerView: GoogleMaps.MarkerView, markerViewChildren: {}, constructor: function() { Backbone.View.prototype.constructor.apply(this, arguments); _.bindAll(this, 'render', 'closeChildren', 'closeChild', 'addChild', 'refresh', 'close'); // Ensure map property if(!this.options.map && !this.map) throw new Error("A map must be specified on MarkerCollectionView instantiation"); this.map || (this.map = this.options.map); // Bind to collection this.collection.on("reset", this.refresh, this); this.collection.on("add", this.addChild, this); this.collection.on("remove", this.closeChild, this); }, // Render MarkerViews for all models in collection render: function(collection) { var collection = collection || this.collection; // Create marker views for each model collection.each(this.addChild); }, // Close all child MarkerViews closeChildren: function() { for(cid in this.markerViewChildren) { this.closeChild(this.markerViewChildren[cid]); } }, closeChild: function(child) { // Param can be child's model, or child view itself var childView = (child instanceof Backbone.Model)? this.markerViewChildren[child.cid]: child; childView.close(); delete this.markerViewChildren[childView.model.cid]; }, // Add a MarkerView and render addChild: function(childModel) { var markerView = new this.markerView({ model: childModel, map: this.map, }); this.markerViewChildren[childModel.cid] = markerView; markerView.render(); }, refresh: function() { this.closeChildren(); this.render(); }, // Close all child MarkerViews close: function() { this.closeChildren(); } }) return GoogleMaps; })(Backbone, _, window.jQuery || window.Zepto || window.ender);
Unbind view controller events on close KILL THE ZOMBIES.
lib/backbone.googlemaps.js
Unbind view controller events on close
<ide><path>ib/backbone.googlemaps.js <ide> if(this.beforeClose) { this.beforeClose(); } <ide> this.closeDetail(); <ide> GoogleMaps.MapView.prototype.close.apply(this, arguments); <add> this.model.off(); <ide> <ide> if(this.onClose) { this.onClose() } <ide> <ide> // Close all child MarkerViews <ide> close: function() { <ide> this.closeChildren(); <add> this.collection.off(); <ide> } <ide> }) <ide>
Java
mit
83f3cb1b7a6deeace0c6d5be351cd205de721b1c
0
tdd-pingis/tdd-pingpong,Heliozoa/tdd-pingpong,tdd-pingis/tdd-pingpong,tdd-pingis/tdd-pingpong,tdd-pingis/tdd-pingpong,Heliozoa/tdd-pingpong,Heliozoa/tdd-pingpong,Heliozoa/tdd-pingpong
package pingis.controllers; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import pingis.entities.Challenge; import pingis.entities.ChallengeType; import pingis.entities.CodeStatus; import pingis.entities.Realm; import pingis.entities.Task; import pingis.entities.TaskInstance; import pingis.entities.TaskType; import pingis.entities.User; import pingis.services.ChallengeService; import pingis.services.GameplayService; import pingis.services.GameplayService.TurnType; import pingis.services.TaskInstanceService; import pingis.services.TaskService; import pingis.services.UserService; import pingis.utils.CodeStubBuilder; import pingis.utils.TestStubBuilder; @Controller public class LiveChallengeController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired ChallengeService challengeService; @Autowired TaskService taskService; @Autowired TaskInstanceService taskInstanceService; @Autowired UserService userService; @Autowired GameplayService gameplayService; @RequestMapping(value = "/newchallenge") public String newChallenge(Model model) { return "newchallenge"; } @RequestMapping("/startChallenge/{challengeId}") public String startChallenge(Model model, @PathVariable long challengeId) { Challenge challenge = challengeService.findOne(challengeId); model.addAttribute("challenge", challenge); return "startchallenge"; } @RequestMapping(value = "/createChallenge", method = RequestMethod.POST) public RedirectView createChallenge(String challengeName, String challengeDesc, String challengeType, String realm, RedirectAttributes redirectAttributes) { Challenge newChallenge = new Challenge(challengeName, userService.getCurrentUser(), challengeDesc, ChallengeType.valueOf(challengeType)); newChallenge.setLevel(1); newChallenge.setOpen(true); newChallenge = challengeService.save(newChallenge); logger.info("Created new challenge: " + newChallenge.toString()); return new RedirectView("/playChallenge/" + newChallenge.getId()); } @RequestMapping(value = "/newtaskpair") public String newTaskPair(Model model) { // TODO: add checks logger.info("Displaying new task pair -form."); return "newtaskpair"; } @RequestMapping(value = "/createTaskPair", method = RequestMethod.POST) public RedirectView createTaskPair(String testTaskName, String implementationTaskName, String testTaskDesc, String implementationTaskDesc, String testCodeStub, String implementationCodeStub, long challengeId, RedirectAttributes redirectAttributes) { Challenge currentChallenge = challengeService.findOne(challengeId); String implStub = new CodeStubBuilder("MyImplememtationClass").build().code; String testStub = new TestStubBuilder(implStub).withTestImports().build().code; gameplayService.generateTaskPairAndTaskInstance(testTaskName, implementationTaskName, testTaskDesc, implementationTaskDesc, testStub, implStub, currentChallenge); return playChallenge(redirectAttributes, challengeId); } @RequestMapping("/playChallenge/{challengeId}") public RedirectView playChallenge(RedirectAttributes redirectAttributes, @PathVariable long challengeId) { Challenge currentChallenge = challengeService.findOne(challengeId); if (currentChallenge == null) { redirectAttributes.addFlashAttribute("message", "challenge not found"); return new RedirectView("/error"); } User player = userService.getCurrentUser(); TaskInstance unfinished = taskInstanceService.getUnfinishedInstance(currentChallenge, player); if (unfinished != null) { logger.info("Found unfinished instance. Redirecting to /task."); return new RedirectView("/task/" + unfinished.getId()); } if (currentChallenge.getType() == ChallengeType.ARCADE) { return playArcade(redirectAttributes, currentChallenge); } else if (currentChallenge.getIsOpen()) { return playLive(currentChallenge, redirectAttributes); } return playPractice(redirectAttributes, currentChallenge); } @RequestMapping("/closeChallenge/{challengeId}") public RedirectView closeChallenge(@PathVariable Long challengeId, RedirectAttributes redirectAttributes) { Challenge currentChallenge = challengeService.findOne(challengeId); if (!gameplayService.isParticipating(currentChallenge)) { logger.info("User trying to close somebody else's challenge. Redirecting to /error."); redirectAttributes.addFlashAttribute("message", "user not in challenge"); return new RedirectView("/error"); } currentChallenge.setOpen(false); challengeService.save(currentChallenge); redirectAttributes.addFlashAttribute("message", "Challenge closed."); logger.info("Closing challenge: " + currentChallenge.getId()); return new RedirectView("/user"); } @RequestMapping("/newArcadeChallenge") public String newArcadeChallenge(Model model) { return "newarcadechallenge"; } @RequestMapping(value = "/createArcadeChallenge", method = RequestMethod.POST) public RedirectView createArcadeChallenge(RedirectAttributes redirectAttributes, String challengeName, String challengeDesc, String realm, int level) { Challenge arcadeChallenge = new Challenge( challengeName, userService.getCurrentUser(), challengeDesc, ChallengeType.ARCADE); logger.info("Created new arcade challenge: " + arcadeChallenge.toString()); try { arcadeChallenge.setRealm(Realm.valueOf(realm.toUpperCase())); } catch (Exception e) { logger.info("Realm {} does not exist. Redirecting to /error.", realm); return new RedirectView("/error"); } arcadeChallenge.setOpen(true); arcadeChallenge.setLevel(level); challengeService.save(arcadeChallenge); return new RedirectView("/user"); } @RequestMapping("/newArcadeSession") public RedirectView newArcadeSession(RedirectAttributes redirectAttributes, @RequestParam String realm) { logger.info("playArcade method entered"); User player = userService.getCurrentUser(); Realm currentRealm = null; try { logger.info("Trying to get realm: {}", realm); currentRealm = Realm.valueOf(realm.toUpperCase()); } catch (Exception e) { logger.info("Realm {} does not exist. Redirecting to /error.", realm); return new RedirectView("/error"); } Challenge challenge = gameplayService.getArcadeChallenge(currentRealm); return playArcade(redirectAttributes, challenge); } public RedirectView playLive(Challenge currentChallenge, RedirectAttributes redirectAttributes) { int index = gameplayService.getNumberOfTasks(currentChallenge) / 2; logger.info("Highest index of tasks in current challenge: " + index); if (!gameplayService.isParticipating(currentChallenge)) { logger.info("Not participating."); if (currentChallenge.getSecondPlayer() == null) { currentChallenge.setSecondPlayer(userService.getCurrentUser()); challengeService.save(currentChallenge); logger.info("Current user saved as a participant" + " (second player) to current challenge."); } else { logger.info("Current user not a player in this challenge. Redirecting to /error."); redirectAttributes.addFlashAttribute("message", "this is not your challenge"); return new RedirectView("/error"); } } TaskInstance unfinished = challengeService.getUnfinishedTaskInstance(currentChallenge); if (unfinished != null && !unfinished.getUser().equals(userService.getCurrentUser())) { logger.info("Unfinished taskinstance found, but not owned by the" + " current user. Not user's turn yet, redirecting to \"/user\""); return new RedirectView("/user"); } TurnType turn = gameplayService.getTurnType(currentChallenge); if (turn == TurnType.IMPLEMENTATION) { return playImplementationTurn(redirectAttributes, currentChallenge); } else if (turn == TurnType.TEST) { return playTestTurn(redirectAttributes, currentChallenge); } else { logger.info("Not user's turn, redirecting to \"/user\""); return new RedirectView("/user"); } } private RedirectView playImplementationTurn(RedirectAttributes redirectAttributes, Challenge currentChallenge) { Task implTask = gameplayService.getTopmostImplementationTask(currentChallenge); logger.info("implementation task: " + implTask.toString()); Task testTask = gameplayService.getTopmostTestTask(currentChallenge); logger.info("test task: " + testTask.toString()); TaskInstance testTaskInstance = taskInstanceService.getByTaskAndUser(testTask, testTask.getAuthor()); logger.info("Found uneven number of completed taskinstances, " + "current user has turn, " + "creating new task instance, redirecting to /task."); return newTaskInstance(implTask, testTaskInstance, redirectAttributes); } private RedirectView playTestTurn(RedirectAttributes redirectAttributes, Challenge currentChallenge) { redirectAttributes.addFlashAttribute("challengeId", currentChallenge.getId()); redirectAttributes.addFlashAttribute("challenge", currentChallenge); redirectAttributes.addFlashAttribute("minLength", GameplayService.CHALLENGE_MIN_LENGTH); logger.info("Found even number of completed taskinstances, " + "current user has turn, redirecting to \"/newtaskpair\""); return new RedirectView("/newtaskpair"); } private RedirectView playArcade(RedirectAttributes redirectAttributes, Challenge challenge) { logger.info("playArcade method entered"); User player = userService.getCurrentUser(); if (taskInstanceService.getNumberOfDoneTaskInstancesInChallenge(challenge) % 2 == 0) { redirectAttributes.addFlashAttribute("challengeId", challenge.getId()); redirectAttributes.addFlashAttribute("challenge", challenge); redirectAttributes.addFlashAttribute("minLength", Integer.MAX_VALUE); logger.info("User has test turn. Redirecting to /newtaskpair."); return new RedirectView("/newtaskpair"); } else { Task implTask = gameplayService.getRandomImplementationTask(challenge); Task testTask = taskService.getCorrespondingTask(implTask); TaskInstance testTaskInstance = taskInstanceService.getByTaskAndUser(testTask, testTask.getAuthor()); logger.info("User has implementation turn."); return newTaskInstance(implTask, testTaskInstance, redirectAttributes); } } private RedirectView playPractice(RedirectAttributes redirectAttributes, Challenge challenge) { // check for unfinished instances User player = userService.getCurrentUser(); logger.info("User: " + player.getName()); if (challengeService.isOwnChallenge(challenge, player)) { redirectAttributes.addFlashAttribute("message", "Cannot re-do your own live challenge"); return new RedirectView("/error"); } Task nextTask = taskService.nextPracticeTask(challenge); if (nextTask == null) { // all tasks done. wohoo. return new RedirectView("/challengeFinished/" + challenge.getId()); } if (nextTask.getType() == TaskType.TEST) { logger.info("playing test task"); return newTaskInstance(nextTask, null, redirectAttributes); } logger.info("playing implementation task"); TaskInstance testTaskInstance = taskInstanceService.getRandomTaskInstance(taskService.getCorrespondingTask(nextTask)); return newTaskInstance(nextTask, testTaskInstance, redirectAttributes); } public RedirectView newTaskInstance(Task task, TaskInstance testTaskInstance, RedirectAttributes redirectAttributes) { User user = userService.getCurrentUser(); TaskInstance newTaskInstance = taskInstanceService.createEmpty(user, task); if (task.getType() == TaskType.IMPLEMENTATION) { newTaskInstance.setTestTaskInstance(testTaskInstance); testTaskInstance.addImplementationTaskInstance(newTaskInstance); taskInstanceService.save(newTaskInstance); taskInstanceService.save(testTaskInstance); } return new RedirectView("/task/" + newTaskInstance.getId()); } @RequestMapping("/challengeFinished/{challengeId}") public String challengeFinished(Model model, @PathVariable long challengeId) { Challenge challenge = challengeService.findOne(challengeId); model.addAttribute("challenge", challenge); return "challengefinished"; } }
src/main/java/pingis/controllers/LiveChallengeController.java
package pingis.controllers; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import pingis.entities.Challenge; import pingis.entities.ChallengeType; import pingis.entities.CodeStatus; import pingis.entities.Realm; import pingis.entities.Task; import pingis.entities.TaskInstance; import pingis.entities.TaskType; import pingis.entities.User; import pingis.services.ChallengeService; import pingis.services.GameplayService; import pingis.services.GameplayService.TurnType; import pingis.services.TaskInstanceService; import pingis.services.TaskService; import pingis.services.UserService; @Controller public class LiveChallengeController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired ChallengeService challengeService; @Autowired TaskService taskService; @Autowired TaskInstanceService taskInstanceService; @Autowired UserService userService; @Autowired GameplayService gameplayService; @RequestMapping(value = "/newchallenge") public String newChallenge(Model model) { return "newchallenge"; } @RequestMapping("/startChallenge/{challengeId}") public String startChallenge(Model model, @PathVariable long challengeId) { Challenge challenge = challengeService.findOne(challengeId); model.addAttribute("challenge", challenge); return "startchallenge"; } @RequestMapping(value = "/createChallenge", method = RequestMethod.POST) public RedirectView createChallenge(String challengeName, String challengeDesc, String challengeType, String realm, RedirectAttributes redirectAttributes) { Challenge newChallenge = new Challenge(challengeName, userService.getCurrentUser(), challengeDesc, ChallengeType.valueOf(challengeType)); newChallenge.setLevel(1); newChallenge.setOpen(true); newChallenge = challengeService.save(newChallenge); logger.info("Created new challenge: " + newChallenge.toString()); return new RedirectView("/playChallenge/" + newChallenge.getId()); } @RequestMapping(value = "/newtaskpair") public String newTaskPair(Model model) { // TODO: add checks logger.info("Displaying new task pair -form."); return "newtaskpair"; } @RequestMapping(value = "/createTaskPair", method = RequestMethod.POST) public RedirectView createTaskPair(String testTaskName, String implementationTaskName, String testTaskDesc, String implementationTaskDesc, String testCodeStub, String implementationCodeStub, long challengeId, RedirectAttributes redirectAttributes) { Challenge currentChallenge = challengeService.findOne(challengeId); gameplayService.generateTaskPairAndTaskInstance(testTaskName, implementationTaskName, testTaskDesc, implementationTaskDesc, testCodeStub, implementationCodeStub, currentChallenge); return playChallenge(redirectAttributes, challengeId); } @RequestMapping("/playChallenge/{challengeId}") public RedirectView playChallenge(RedirectAttributes redirectAttributes, @PathVariable long challengeId) { Challenge currentChallenge = challengeService.findOne(challengeId); if (currentChallenge == null) { redirectAttributes.addFlashAttribute("message", "challenge not found"); return new RedirectView("/error"); } User player = userService.getCurrentUser(); TaskInstance unfinished = taskInstanceService.getUnfinishedInstance(currentChallenge, player); if (unfinished != null) { logger.info("Found unfinished instance. Redirecting to /task."); return new RedirectView("/task/" + unfinished.getId()); } if (currentChallenge.getType() == ChallengeType.ARCADE) { return playArcade(redirectAttributes, currentChallenge); } else if (currentChallenge.getIsOpen()) { return playLive(currentChallenge, redirectAttributes); } return playPractice(redirectAttributes, currentChallenge); } @RequestMapping("/closeChallenge/{challengeId}") public RedirectView closeChallenge(@PathVariable Long challengeId, RedirectAttributes redirectAttributes) { Challenge currentChallenge = challengeService.findOne(challengeId); if (!gameplayService.isParticipating(currentChallenge)) { logger.info("User trying to close somebody else's challenge. Redirecting to /error."); redirectAttributes.addFlashAttribute("message", "user not in challenge"); return new RedirectView("/error"); } currentChallenge.setOpen(false); challengeService.save(currentChallenge); redirectAttributes.addFlashAttribute("message", "Challenge closed."); logger.info("Closing challenge: " + currentChallenge.getId()); return new RedirectView("/user"); } @RequestMapping("/newArcadeChallenge") public String newArcadeChallenge(Model model) { return "newarcadechallenge"; } @RequestMapping(value = "/createArcadeChallenge", method = RequestMethod.POST) public RedirectView createArcadeChallenge(RedirectAttributes redirectAttributes, String challengeName, String challengeDesc, String realm, int level) { Challenge arcadeChallenge = new Challenge( challengeName, userService.getCurrentUser(), challengeDesc, ChallengeType.ARCADE); logger.info("Created new arcade challenge: " + arcadeChallenge.toString()); try { arcadeChallenge.setRealm(Realm.valueOf(realm.toUpperCase())); } catch (Exception e) { logger.info("Realm {} does not exist. Redirecting to /error.", realm); return new RedirectView("/error"); } arcadeChallenge.setOpen(true); arcadeChallenge.setLevel(level); challengeService.save(arcadeChallenge); return new RedirectView("/user"); } @RequestMapping("/newArcadeSession") public RedirectView newArcadeSession(RedirectAttributes redirectAttributes, @RequestParam String realm) { logger.info("playArcade method entered"); User player = userService.getCurrentUser(); Realm currentRealm = null; try { logger.info("Trying to get realm: {}", realm); currentRealm = Realm.valueOf(realm.toUpperCase()); } catch (Exception e) { logger.info("Realm {} does not exist. Redirecting to /error.", realm); return new RedirectView("/error"); } Challenge challenge = gameplayService.getArcadeChallenge(currentRealm); return playArcade(redirectAttributes, challenge); } public RedirectView playLive(Challenge currentChallenge, RedirectAttributes redirectAttributes) { int index = gameplayService.getNumberOfTasks(currentChallenge) / 2; logger.info("Highest index of tasks in current challenge: " + index); if (!gameplayService.isParticipating(currentChallenge)) { logger.info("Not participating."); if (currentChallenge.getSecondPlayer() == null) { currentChallenge.setSecondPlayer(userService.getCurrentUser()); challengeService.save(currentChallenge); logger.info("Current user saved as a participant" + " (second player) to current challenge."); } else { logger.info("Current user not a player in this challenge. Redirecting to /error."); redirectAttributes.addFlashAttribute("message", "this is not your challenge"); return new RedirectView("/error"); } } TaskInstance unfinished = challengeService.getUnfinishedTaskInstance(currentChallenge); if (unfinished != null && !unfinished.getUser().equals(userService.getCurrentUser())) { logger.info("Unfinished taskinstance found, but not owned by the" + " current user. Not user's turn yet, redirecting to \"/user\""); return new RedirectView("/user"); } TurnType turn = gameplayService.getTurnType(currentChallenge); if (turn == TurnType.IMPLEMENTATION) { return playImplementationTurn(redirectAttributes, currentChallenge); } else if (turn == TurnType.TEST) { return playTestTurn(redirectAttributes, currentChallenge); } else { logger.info("Not user's turn, redirecting to \"/user\""); return new RedirectView("/user"); } } private RedirectView playImplementationTurn(RedirectAttributes redirectAttributes, Challenge currentChallenge) { Task implTask = gameplayService.getTopmostImplementationTask(currentChallenge); logger.info("implementation task: " + implTask.toString()); Task testTask = gameplayService.getTopmostTestTask(currentChallenge); logger.info("test task: " + testTask.toString()); TaskInstance testTaskInstance = taskInstanceService.getByTaskAndUser(testTask, testTask.getAuthor()); logger.info("Found uneven number of completed taskinstances, " + "current user has turn, " + "creating new task instance, redirecting to /task."); return newTaskInstance(implTask, testTaskInstance, redirectAttributes); } private RedirectView playTestTurn(RedirectAttributes redirectAttributes, Challenge currentChallenge) { redirectAttributes.addFlashAttribute("challengeId", currentChallenge.getId()); redirectAttributes.addFlashAttribute("challenge", currentChallenge); redirectAttributes.addFlashAttribute("minLength", GameplayService.CHALLENGE_MIN_LENGTH); logger.info("Found even number of completed taskinstances, " + "current user has turn, redirecting to \"/newtaskpair\""); return new RedirectView("/newtaskpair"); } private RedirectView playArcade(RedirectAttributes redirectAttributes, Challenge challenge) { logger.info("playArcade method entered"); User player = userService.getCurrentUser(); if (taskInstanceService.getNumberOfDoneTaskInstancesInChallenge(challenge) % 2 == 0) { redirectAttributes.addFlashAttribute("challengeId", challenge.getId()); redirectAttributes.addFlashAttribute("challenge", challenge); redirectAttributes.addFlashAttribute("minLength", Integer.MAX_VALUE); logger.info("User has test turn. Redirecting to /newtaskpair."); return new RedirectView("/newtaskpair"); } else { Task implTask = gameplayService.getRandomImplementationTask(challenge); Task testTask = taskService.getCorrespondingTask(implTask); TaskInstance testTaskInstance = taskInstanceService.getByTaskAndUser(testTask, testTask.getAuthor()); logger.info("User has implementation turn."); return newTaskInstance(implTask, testTaskInstance, redirectAttributes); } } private RedirectView playPractice(RedirectAttributes redirectAttributes, Challenge challenge) { // check for unfinished instances User player = userService.getCurrentUser(); logger.info("User: " + player.getName()); if (challengeService.isOwnChallenge(challenge, player)) { redirectAttributes.addFlashAttribute("message", "Cannot re-do your own live challenge"); return new RedirectView("/error"); } Task nextTask = taskService.nextPracticeTask(challenge); if (nextTask == null) { // all challenges done. wohoo. return new RedirectView("/challengeFinished/" + challenge.getId()); } if (nextTask.getType() == TaskType.TEST) { logger.info("playing test task"); return newTaskInstance(nextTask, null, redirectAttributes); } logger.info("playing implementation task"); TaskInstance testTaskInstance = taskInstanceService.getRandomTaskInstance(taskService.getCorrespondingTask(nextTask)); return newTaskInstance(nextTask, testTaskInstance, redirectAttributes); } public RedirectView newTaskInstance(Task task, TaskInstance testTaskInstance, RedirectAttributes redirectAttributes) { User user = userService.getCurrentUser(); TaskInstance newTaskInstance = taskInstanceService.createEmpty(user, task); if (task.getType() == TaskType.IMPLEMENTATION) { newTaskInstance.setTestTaskInstance(testTaskInstance); testTaskInstance.addImplementationTaskInstance(newTaskInstance); taskInstanceService.save(newTaskInstance); taskInstanceService.save(testTaskInstance); } return new RedirectView("/task/" + newTaskInstance.getId()); } @RequestMapping("/challengeFinished/{challengeId}") public String challengeFinished(Model model, @PathVariable long challengeId) { Challenge challenge = challengeService.findOne(challengeId); model.addAttribute("challenge", challenge); return "challengefinished"; } }
Code stubs generated automatically
src/main/java/pingis/controllers/LiveChallengeController.java
Code stubs generated automatically
<ide><path>rc/main/java/pingis/controllers/LiveChallengeController.java <ide> import pingis.services.TaskInstanceService; <ide> import pingis.services.TaskService; <ide> import pingis.services.UserService; <add>import pingis.utils.CodeStubBuilder; <add>import pingis.utils.TestStubBuilder; <ide> <ide> @Controller <ide> public class LiveChallengeController { <ide> RedirectAttributes redirectAttributes) { <ide> <ide> Challenge currentChallenge = challengeService.findOne(challengeId); <add> String implStub = new CodeStubBuilder("MyImplememtationClass").build().code; <add> String testStub = new TestStubBuilder(implStub).withTestImports().build().code; <add> <ide> gameplayService.generateTaskPairAndTaskInstance(testTaskName, <ide> implementationTaskName, <ide> testTaskDesc, <ide> implementationTaskDesc, <del> testCodeStub, <del> implementationCodeStub, <add> testStub, <add> implStub, <ide> currentChallenge); <ide> return playChallenge(redirectAttributes, challengeId); <ide> } <ide> <ide> Task nextTask = taskService.nextPracticeTask(challenge); <ide> if (nextTask == null) { <del> // all challenges done. wohoo. <add> // all tasks done. wohoo. <ide> return new RedirectView("/challengeFinished/" + challenge.getId()); <ide> } <ide> if (nextTask.getType() == TaskType.TEST) {
Java
apache-2.0
44443a8a17e0715d1b860f0169cbce417fbe8e12
0
xfournet/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,slisson/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,youdonghai/intellij-community,clumsy/intellij-community,holmes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,slisson/intellij-community,jagguli/intellij-community,consulo/consulo,ahb0327/intellij-community,holmes/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,tmpgit/intellij-community,da1z/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,fitermay/intellij-community,adedayo/intellij-community,diorcety/intellij-community,supersven/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,caot/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ernestp/consulo,holmes/intellij-community,supersven/intellij-community,FHannes/intellij-community,dslomov/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,caot/intellij-community,allotria/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,samthor/intellij-community,caot/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,da1z/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,hurricup/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,petteyg/intellij-community,semonte/intellij-community,jagguli/intellij-community,caot/intellij-community,petteyg/intellij-community,consulo/consulo,hurricup/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,izonder/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,holmes/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,da1z/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,semonte/intellij-community,da1z/intellij-community,asedunov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ryano144/intellij-community,kool79/intellij-community,orekyuu/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,petteyg/intellij-community,FHannes/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,kool79/intellij-community,Lekanich/intellij-community,kool79/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,retomerz/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,consulo/consulo,asedunov/intellij-community,kdwink/intellij-community,robovm/robovm-studio,FHannes/intellij-community,gnuhub/intellij-community,signed/intellij-community,da1z/intellij-community,holmes/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ryano144/intellij-community,semonte/intellij-community,allotria/intellij-community,nicolargo/intellij-community,consulo/consulo,diorcety/intellij-community,signed/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,amith01994/intellij-community,izonder/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,petteyg/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,supersven/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,SerCeMan/intellij-community,retomerz/intellij-community,izonder/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,slisson/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,amith01994/intellij-community,blademainer/intellij-community,dslomov/intellij-community,jagguli/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,amith01994/intellij-community,apixandru/intellij-community,supersven/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,semonte/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,semonte/intellij-community,adedayo/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,caot/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,diorcety/intellij-community,vladmm/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,supersven/intellij-community,signed/intellij-community,jagguli/intellij-community,signed/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,adedayo/intellij-community,da1z/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,allotria/intellij-community,suncycheng/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,slisson/intellij-community,signed/intellij-community,holmes/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,supersven/intellij-community,holmes/intellij-community,retomerz/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,kdwink/intellij-community,semonte/intellij-community,izonder/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fnouama/intellij-community,vladmm/intellij-community,slisson/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,slisson/intellij-community,robovm/robovm-studio,signed/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,slisson/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ibinti/intellij-community,petteyg/intellij-community,apixandru/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,semonte/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,xfournet/intellij-community,kool79/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ryano144/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,consulo/consulo,salguarnieri/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,signed/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,samthor/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,kool79/intellij-community,apixandru/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,signed/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,ernestp/consulo,dslomov/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,xfournet/intellij-community,consulo/consulo,orekyuu/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,allotria/intellij-community,samthor/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,izonder/intellij-community,signed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,semonte/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,caot/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,kdwink/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,caot/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ryano144/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,supersven/intellij-community,vladmm/intellij-community,dslomov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,da1z/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,xfournet/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,blademainer/intellij-community,signed/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,kool79/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,dslomov/intellij-community,izonder/intellij-community,amith01994/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,petteyg/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,caot/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,asedunov/intellij-community,FHannes/intellij-community,slisson/intellij-community,orekyuu/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,da1z/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community
package com.intellij.xml.index; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.IdeaTestCase; import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * @author Dmitry Avdeev */ public class XmlSchemaIndexTest extends CodeInsightFixtureTestCase { private static final String NS = "http://java.jb.com/xml/ns/javaee"; @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") public XmlSchemaIndexTest() { IdeaTestCase.initPlatformPrefix(); } public void testBuilder() throws IOException { VirtualFile file = myFixture.copyFileToProject("spring-beans-2.0.xsd"); assert file != null; final Collection<String> tags = XsdTagNameBuilder.computeTagNames(file.getInputStream()); assert tags != null; assertEquals(22, tags.size()); final String ns = XsdNamespaceBuilder.computeNamespace(file.getInputStream()); assertEquals("http://www.springframework.org/schema/beans", ns); final VirtualFile xsd = myFixture.copyFileToProject("XMLSchema.xsd"); assert xsd != null; final String xsns = XsdNamespaceBuilder.computeNamespace(xsd.getInputStream()); assertEquals("http://www.w3.org/2001/XMLSchema", xsns); final Collection<String> xstags = XsdTagNameBuilder.computeTagNames(xsd.getInputStream()); assert xstags != null; assertEquals(69, xstags.size()); assertTrue(xstags.contains("schema")); } public void testXsdNamespaceBuilder() throws Exception { VirtualFile file = myFixture.copyFileToProject("web-app_2_5.xsd"); final XsdNamespaceBuilder builder = XsdNamespaceBuilder.computeNamespace(new InputStreamReader(file.getInputStream())); assertEquals(NS, builder.getNamespace()); assertEquals("2.5", builder.getVersion()); assertEquals(Arrays.asList("web-app"), builder.getTags()); } public void testTagNameIndex() { myFixture.copyDirectoryToProject("", ""); final Project project = getProject(); final Collection<String> tags = XmlTagNamesIndex.getAllTagNames(project); assertTrue(tags.size() > 26); final Collection<VirtualFile> files = XmlTagNamesIndex.getFilesByTagName("bean", project); assertEquals(1, files.size()); final Collection<VirtualFile> files1 = XmlTagNamesIndex.getFilesByTagName("web-app", project); assertEquals(files1.toString(), 2, files1.size()); List<String> names = new ArrayList<String>(ContainerUtil.map(files1, new Function<VirtualFile, String>() { @Override public String fun(VirtualFile virtualFile) { return virtualFile.getName(); } })); Collections.sort(names); assertEquals(Arrays.asList("web-app_2_5.xsd", "web-app_3_0.xsd"), names); } public void testNamespaceIndex() { myFixture.copyDirectoryToProject("", ""); final List<IndexedRelevantResource<String, XsdNamespaceBuilder>> files = XmlNamespaceIndex.getResourcesByNamespace(NS, getProject(), myModule); assertEquals(2, files.size()); IndexedRelevantResource<String, XsdNamespaceBuilder> resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "3.0", myModule); assertNotNull(resource); XsdNamespaceBuilder builder = resource.getValue(); assertEquals(NS, builder.getNamespace()); assertEquals("3.0", builder.getVersion()); assertEquals(Arrays.asList("web-app"), builder.getTags()); resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "2.5", myModule); assertNotNull(resource); builder = resource.getValue(); assertEquals(NS, builder.getNamespace()); assertEquals("2.5", builder.getVersion()); assertEquals(Arrays.asList("web-app"), builder.getTags()); } @Override protected String getBasePath() { return "/xml/tests/testData/index"; } @Override protected boolean isCommunity() { return true; } }
xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java
package com.intellij.xml.index; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.IdeaTestCase; import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * @author Dmitry Avdeev */ public class XmlSchemaIndexTest extends CodeInsightFixtureTestCase { private static final String NS = "http://java.jb.com/xml/ns/javaee"; @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") public XmlSchemaIndexTest() { IdeaTestCase.initPlatformPrefix(); } public void testBuilder() throws IOException { VirtualFile file = myFixture.copyFileToProject("spring-beans-2.0.xsd"); assert file != null; final Collection<String> tags = XsdTagNameBuilder.computeTagNames(file.getInputStream()); assert tags != null; assertEquals(22, tags.size()); final String ns = XsdNamespaceBuilder.computeNamespace(file.getInputStream()); assertEquals("http://www.springframework.org/schema/beans", ns); final VirtualFile xsd = myFixture.copyFileToProject("XMLSchema.xsd"); assert xsd != null; final String xsns = XsdNamespaceBuilder.computeNamespace(xsd.getInputStream()); assertEquals("http://www.w3.org/2001/XMLSchema", xsns); final Collection<String> xstags = XsdTagNameBuilder.computeTagNames(xsd.getInputStream()); assert xstags != null; assertEquals(69, xstags.size()); assertTrue(xstags.contains("schema")); } public void testXsdNamespaceBuilder() throws Exception { VirtualFile file = myFixture.copyFileToProject("web-app_2_5.xsd"); final XsdNamespaceBuilder builder = XsdNamespaceBuilder.computeNamespace(new InputStreamReader(file.getInputStream())); assertEquals(NS, builder.getNamespace()); assertEquals("2.5", builder.getVersion()); assertEquals(Arrays.asList("web-app"), builder.getTags()); } public void testTagNameIndex() { myFixture.copyDirectoryToProject("", ""); final Project project = getProject(); final Collection<String> tags = XmlTagNamesIndex.getAllTagNames(project); assertTrue(tags.size() > 26); final Collection<VirtualFile> files = XmlTagNamesIndex.getFilesByTagName("bean", project); assertEquals(1, files.size()); final Collection<VirtualFile> files1 = XmlTagNamesIndex.getFilesByTagName("web-app", project); assertEquals(files1.toString(), 2, files1.size()); List<String> names = new ArrayList<String>(ContainerUtil.map(files1, new Function<VirtualFile, String>() { @Override public String fun(VirtualFile virtualFile) { return virtualFile.getName(); } })); assertEquals(Arrays.asList("web-app_3_0.xsd", "web-app_2_5.xsd"), names); } public void testNamespaceIndex() { myFixture.copyDirectoryToProject("", ""); final List<IndexedRelevantResource<String, XsdNamespaceBuilder>> files = XmlNamespaceIndex.getResourcesByNamespace(NS, getProject(), myModule); assertEquals(2, files.size()); IndexedRelevantResource<String, XsdNamespaceBuilder> resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "3.0", myModule); assertNotNull(resource); XsdNamespaceBuilder builder = resource.getValue(); assertEquals(NS, builder.getNamespace()); assertEquals("3.0", builder.getVersion()); assertEquals(Arrays.asList("web-app"), builder.getTags()); resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "2.5", myModule); assertNotNull(resource); builder = resource.getValue(); assertEquals(NS, builder.getNamespace()); assertEquals("2.5", builder.getVersion()); assertEquals(Arrays.asList("web-app"), builder.getTags()); } @Override protected String getBasePath() { return "/xml/tests/testData/index"; } @Override protected boolean isCommunity() { return true; } }
fixing test
xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java
fixing test
<ide><path>ml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java <ide> <ide> import java.io.IOException; <ide> import java.io.InputStreamReader; <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.Collection; <del>import java.util.List; <add>import java.util.*; <ide> <ide> /** <ide> * @author Dmitry Avdeev <ide> return virtualFile.getName(); <ide> } <ide> })); <del> assertEquals(Arrays.asList("web-app_3_0.xsd", "web-app_2_5.xsd"), names); <add> Collections.sort(names); <add> assertEquals(Arrays.asList("web-app_2_5.xsd", "web-app_3_0.xsd"), names); <ide> } <ide> <ide> public void testNamespaceIndex() {
Java
apache-2.0
af6169fe9d4af8b6d925d85efe3d8047f799c0f1
0
lVlA/AnimationProgressBar
package com.lvla.android.animation_progress_bar; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.content.Context; import android.util.AttributeSet; import android.widget.ProgressBar; /** * Created by lvla on 2016/04/13. */ public class AnimationProgressBar extends ProgressBar { private ObjectAnimator animator = null; private TimeInterpolator interpolator = null; public AnimationProgressBar(Context context) { super(context); } public AnimationProgressBar(Context context, AttributeSet attrs) { super(context, attrs); } public AnimationProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setInterpolatorForHorizontal(TimeInterpolator interpolator) { this.interpolator = interpolator; } public void setProgress(int progress, int animationDurationMilliSec) { animator = ObjectAnimator.ofInt(this, "progress", progress); animator.setDuration(animationDurationMilliSec); if(interpolator != null) { animator.setInterpolator(interpolator); } animator.start(); } public void end() { if(animator != null) { animator.end(); } } }
animation_progress_bar/src/main/java/com/lvla/android/animation_progress_bar/AnimationProgressBar.java
package com.lvla.android.animation_progress_bar; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.content.Context; import android.util.AttributeSet; import android.widget.ProgressBar; /** * Created by lvla on 2016/04/13. */ public class AnimationProgressBar extends ProgressBar { private ObjectAnimator animator = null; private TimeInterpolator interpolator = null; public AnimationProgressBar(Context context) { super(context); } public AnimationProgressBar(Context context, AttributeSet attrs) { super(context, attrs); } public AnimationProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setInterpolator(TimeInterpolator interpolator) { this.interpolator = interpolator; } public void setProgress(int progress, int animationDurationMilliSec) { animator = ObjectAnimator.ofInt(this, "progress", progress); animator.setDuration(animationDurationMilliSec); if(interpolator != null) { animator.setInterpolator(interpolator); } animator.start(); } public void end() { if(animator != null) { animator.end(); } } }
Change method name conflict with parent class’s method
animation_progress_bar/src/main/java/com/lvla/android/animation_progress_bar/AnimationProgressBar.java
Change method name
<ide><path>nimation_progress_bar/src/main/java/com/lvla/android/animation_progress_bar/AnimationProgressBar.java <ide> super(context, attrs, defStyleAttr); <ide> } <ide> <del> public void setInterpolator(TimeInterpolator interpolator) { <add> public void setInterpolatorForHorizontal(TimeInterpolator interpolator) { <ide> this.interpolator = interpolator; <ide> } <ide>
Java
apache-2.0
5709c8ac7ee0f7de4c66a9139e0080fcefb896bf
0
treasure-data/presto,hgschmie/presto,11xor6/presto,hgschmie/presto,smartnews/presto,Praveen2112/presto,losipiuk/presto,electrum/presto,ebyhr/presto,Praveen2112/presto,ebyhr/presto,hgschmie/presto,treasure-data/presto,martint/presto,smartnews/presto,hgschmie/presto,electrum/presto,electrum/presto,dain/presto,erichwang/presto,smartnews/presto,treasure-data/presto,smartnews/presto,treasure-data/presto,losipiuk/presto,Praveen2112/presto,dain/presto,erichwang/presto,treasure-data/presto,Praveen2112/presto,Praveen2112/presto,treasure-data/presto,11xor6/presto,11xor6/presto,losipiuk/presto,martint/presto,ebyhr/presto,dain/presto,electrum/presto,dain/presto,martint/presto,martint/presto,erichwang/presto,11xor6/presto,smartnews/presto,losipiuk/presto,11xor6/presto,ebyhr/presto,dain/presto,ebyhr/presto,losipiuk/presto,martint/presto,hgschmie/presto,erichwang/presto,erichwang/presto,electrum/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.sql.planner.optimizations; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import io.prestosql.Session; import io.prestosql.execution.warnings.WarningCollector; import io.prestosql.metadata.Metadata; import io.prestosql.spi.type.Type; import io.prestosql.sql.planner.DomainTranslator; import io.prestosql.sql.planner.EffectivePredicateExtractor; import io.prestosql.sql.planner.EqualityInference; import io.prestosql.sql.planner.ExpressionInterpreter; import io.prestosql.sql.planner.LiteralEncoder; import io.prestosql.sql.planner.NoOpSymbolResolver; import io.prestosql.sql.planner.PlanNodeIdAllocator; import io.prestosql.sql.planner.Symbol; import io.prestosql.sql.planner.SymbolAllocator; import io.prestosql.sql.planner.SymbolsExtractor; import io.prestosql.sql.planner.TypeAnalyzer; import io.prestosql.sql.planner.TypeProvider; import io.prestosql.sql.planner.plan.AggregationNode; import io.prestosql.sql.planner.plan.AssignUniqueId; import io.prestosql.sql.planner.plan.Assignments; import io.prestosql.sql.planner.plan.ExchangeNode; import io.prestosql.sql.planner.plan.FilterNode; import io.prestosql.sql.planner.plan.GroupIdNode; import io.prestosql.sql.planner.plan.JoinNode; import io.prestosql.sql.planner.plan.MarkDistinctNode; import io.prestosql.sql.planner.plan.PlanNode; import io.prestosql.sql.planner.plan.ProjectNode; import io.prestosql.sql.planner.plan.SampleNode; import io.prestosql.sql.planner.plan.SemiJoinNode; import io.prestosql.sql.planner.plan.SimplePlanRewriter; import io.prestosql.sql.planner.plan.SortNode; import io.prestosql.sql.planner.plan.SpatialJoinNode; import io.prestosql.sql.planner.plan.TableScanNode; import io.prestosql.sql.planner.plan.UnionNode; import io.prestosql.sql.planner.plan.UnnestNode; import io.prestosql.sql.planner.plan.WindowNode; import io.prestosql.sql.tree.BooleanLiteral; import io.prestosql.sql.tree.ComparisonExpression; import io.prestosql.sql.tree.Expression; import io.prestosql.sql.tree.Literal; import io.prestosql.sql.tree.NodeRef; import io.prestosql.sql.tree.NullLiteral; import io.prestosql.sql.tree.SymbolReference; import io.prestosql.sql.tree.TryExpression; import io.prestosql.sql.util.AstUtils; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static io.prestosql.SystemSessionProperties.isEnableDynamicFiltering; import static io.prestosql.SystemSessionProperties.isPredicatePushdownUseTableProperties; import static io.prestosql.sql.DynamicFilters.createDynamicFilterExpression; import static io.prestosql.sql.ExpressionUtils.combineConjuncts; import static io.prestosql.sql.ExpressionUtils.extractConjuncts; import static io.prestosql.sql.ExpressionUtils.filterDeterministicConjuncts; import static io.prestosql.sql.planner.DeterminismEvaluator.isDeterministic; import static io.prestosql.sql.planner.ExpressionSymbolInliner.inlineSymbols; import static io.prestosql.sql.planner.iterative.rule.CanonicalizeExpressionRewriter.canonicalizeExpression; import static io.prestosql.sql.planner.iterative.rule.UnwrapCastInComparison.unwrapCasts; import static io.prestosql.sql.planner.plan.JoinNode.Type.FULL; import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER; import static io.prestosql.sql.planner.plan.JoinNode.Type.LEFT; import static io.prestosql.sql.planner.plan.JoinNode.Type.RIGHT; import static io.prestosql.sql.tree.BooleanLiteral.TRUE_LITERAL; import static java.util.Objects.requireNonNull; public class PredicatePushDown implements PlanOptimizer { private final Metadata metadata; private final LiteralEncoder literalEncoder; private final TypeAnalyzer typeAnalyzer; private final boolean useTableProperties; private final boolean dynamicFiltering; public PredicatePushDown(Metadata metadata, TypeAnalyzer typeAnalyzer, boolean useTableProperties, boolean dynamicFiltering) { this.metadata = requireNonNull(metadata, "metadata is null"); this.literalEncoder = new LiteralEncoder(metadata); this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null"); this.useTableProperties = useTableProperties; this.dynamicFiltering = dynamicFiltering; } @Override public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { requireNonNull(plan, "plan is null"); requireNonNull(session, "session is null"); requireNonNull(types, "types is null"); requireNonNull(idAllocator, "idAllocator is null"); EffectivePredicateExtractor effectivePredicateExtractor = new EffectivePredicateExtractor( new DomainTranslator(metadata), metadata, useTableProperties && isPredicatePushdownUseTableProperties(session)); return SimplePlanRewriter.rewriteWith( new Rewriter(symbolAllocator, idAllocator, metadata, literalEncoder, effectivePredicateExtractor, typeAnalyzer, session, types, dynamicFiltering), plan, TRUE_LITERAL); } private static class Rewriter extends SimplePlanRewriter<Expression> { private final SymbolAllocator symbolAllocator; private final PlanNodeIdAllocator idAllocator; private final Metadata metadata; private final LiteralEncoder literalEncoder; private final EffectivePredicateExtractor effectivePredicateExtractor; private final TypeAnalyzer typeAnalyzer; private final Session session; private final TypeProvider types; private final ExpressionEquivalence expressionEquivalence; private final boolean dynamicFiltering; private Rewriter( SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, Metadata metadata, LiteralEncoder literalEncoder, EffectivePredicateExtractor effectivePredicateExtractor, TypeAnalyzer typeAnalyzer, Session session, TypeProvider types, boolean dynamicFiltering) { this.symbolAllocator = requireNonNull(symbolAllocator, "symbolAllocator is null"); this.idAllocator = requireNonNull(idAllocator, "idAllocator is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.literalEncoder = requireNonNull(literalEncoder, "literalEncoder is null"); this.effectivePredicateExtractor = requireNonNull(effectivePredicateExtractor, "effectivePredicateExtractor is null"); this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null"); this.session = requireNonNull(session, "session is null"); this.types = requireNonNull(types, "types is null"); this.expressionEquivalence = new ExpressionEquivalence(metadata, typeAnalyzer); this.dynamicFiltering = dynamicFiltering; } @Override public PlanNode visitPlan(PlanNode node, RewriteContext<Expression> context) { PlanNode rewrittenNode = context.defaultRewrite(node, TRUE_LITERAL); if (!context.get().equals(TRUE_LITERAL)) { // Drop in a FilterNode b/c we cannot push our predicate down any further rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, context.get()); } return rewrittenNode; } @Override public PlanNode visitExchange(ExchangeNode node, RewriteContext<Expression> context) { boolean modified = false; ImmutableList.Builder<PlanNode> builder = ImmutableList.builder(); for (int i = 0; i < node.getSources().size(); i++) { Map<Symbol, SymbolReference> outputsToInputs = new HashMap<>(); for (int index = 0; index < node.getInputs().get(i).size(); index++) { outputsToInputs.put( node.getOutputSymbols().get(index), node.getInputs().get(i).get(index).toSymbolReference()); } Expression sourcePredicate = inlineSymbols(outputsToInputs, context.get()); PlanNode source = node.getSources().get(i); PlanNode rewrittenSource = context.rewrite(source, sourcePredicate); if (rewrittenSource != source) { modified = true; } builder.add(rewrittenSource); } if (modified) { return new ExchangeNode( node.getId(), node.getType(), node.getScope(), node.getPartitioningScheme(), builder.build(), node.getInputs(), node.getOrderingScheme()); } return node; } @Override public PlanNode visitWindow(WindowNode node, RewriteContext<Expression> context) { List<Symbol> partitionSymbols = node.getPartitionBy(); // TODO: This could be broader. We can push down conjucts if they are constant for all rows in a window partition. // The simplest way to guarantee this is if the conjucts are deterministic functions of the partitioning symbols. // This can leave out cases where they're both functions of some set of common expressions and the partitioning // function is injective, but that's a rare case. The majority of window nodes are expected to be partitioned by // pre-projected symbols. Predicate<Expression> isSupported = conjunct -> isDeterministic(conjunct, metadata) && SymbolsExtractor.extractUnique(conjunct).stream() .allMatch(partitionSymbols::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(isSupported)); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(metadata, conjuncts.get(true))); if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, conjuncts.get(false))); } return rewrittenNode; } @Override public PlanNode visitProject(ProjectNode node, RewriteContext<Expression> context) { Set<Symbol> deterministicSymbols = node.getAssignments().entrySet().stream() .filter(entry -> isDeterministic(entry.getValue(), metadata)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); Predicate<Expression> deterministic = conjunct -> SymbolsExtractor.extractUnique(conjunct).stream() .allMatch(deterministicSymbols::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(deterministic)); // Push down conjuncts from the inherited predicate that only depend on deterministic assignments with // certain limitations. List<Expression> deterministicConjuncts = conjuncts.get(true); // We partition the expressions in the deterministicConjuncts into two lists, and only inline the // expressions that are in the inlining targets list. Map<Boolean, List<Expression>> inlineConjuncts = deterministicConjuncts.stream() .collect(Collectors.partitioningBy(expression -> isInliningCandidate(expression, node))); List<Expression> inlinedDeterministicConjuncts = inlineConjuncts.get(true).stream() .map(entry -> inlineSymbols(node.getAssignments().getMap(), entry)) .map(conjunct -> canonicalizeExpression(conjunct, typeAnalyzer.getTypes(session, types, conjunct), metadata)) // normalize expressions to a form that unwrapCasts understands .map(conjunct -> unwrapCasts(session, metadata, typeAnalyzer, types, conjunct)) .collect(Collectors.toList()); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(metadata, inlinedDeterministicConjuncts)); // All deterministic conjuncts that contains non-inlining targets, and non-deterministic conjuncts, // if any, will be in the filter node. List<Expression> nonInliningConjuncts = inlineConjuncts.get(false); nonInliningConjuncts.addAll(conjuncts.get(false)); if (!nonInliningConjuncts.isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, nonInliningConjuncts)); } return rewrittenNode; } private boolean isInliningCandidate(Expression expression, ProjectNode node) { // TryExpressions should not be pushed down. However they are now being handled as lambda // passed to a FunctionCall now and should not affect predicate push down. So we want to make // sure the conjuncts are not TryExpressions. verify(AstUtils.preOrder(expression).noneMatch(TryExpression.class::isInstance)); // candidate symbols for inlining are // 1. references to simple constants or symbol references // 2. references to complex expressions that appear only once // which come from the node, as opposed to an enclosing scope. Set<Symbol> childOutputSet = ImmutableSet.copyOf(node.getOutputSymbols()); Map<Symbol, Long> dependencies = SymbolsExtractor.extractAll(expression).stream() .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); return dependencies.entrySet().stream() .allMatch(entry -> entry.getValue() == 1 || node.getAssignments().get(entry.getKey()) instanceof Literal || node.getAssignments().get(entry.getKey()) instanceof SymbolReference); } @Override public PlanNode visitGroupId(GroupIdNode node, RewriteContext<Expression> context) { Map<Symbol, SymbolReference> commonGroupingSymbolMapping = node.getGroupingColumns().entrySet().stream() .filter(entry -> node.getCommonGroupingColumns().contains(entry.getKey())) .collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference())); Predicate<Expression> pushdownEligiblePredicate = conjunct -> commonGroupingSymbolMapping.keySet().containsAll(SymbolsExtractor.extractUnique(conjunct)); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(pushdownEligiblePredicate)); // Push down conjuncts from the inherited predicate that apply to common grouping symbols PlanNode rewrittenNode = context.defaultRewrite(node, inlineSymbols(commonGroupingSymbolMapping, combineConjuncts(metadata, conjuncts.get(true)))); // All other conjuncts, if any, will be in the filter node. if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, conjuncts.get(false))); } return rewrittenNode; } @Override public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Expression> context) { Set<Symbol> pushDownableSymbols = ImmutableSet.copyOf(node.getDistinctSymbols()); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream() .collect(Collectors.partitioningBy(conjunct -> SymbolsExtractor.extractUnique(conjunct).stream().allMatch(pushDownableSymbols::contains))); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(metadata, conjuncts.get(true))); if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, conjuncts.get(false))); } return rewrittenNode; } @Override public PlanNode visitSort(SortNode node, RewriteContext<Expression> context) { return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitUnion(UnionNode node, RewriteContext<Expression> context) { boolean modified = false; ImmutableList.Builder<PlanNode> builder = ImmutableList.builder(); for (int i = 0; i < node.getSources().size(); i++) { Expression sourcePredicate = inlineSymbols(node.sourceSymbolMap(i), context.get()); PlanNode source = node.getSources().get(i); PlanNode rewrittenSource = context.rewrite(source, sourcePredicate); if (rewrittenSource != source) { modified = true; } builder.add(rewrittenSource); } if (modified) { return new UnionNode(node.getId(), builder.build(), node.getSymbolMapping(), node.getOutputSymbols()); } return node; } @Deprecated @Override public PlanNode visitFilter(FilterNode node, RewriteContext<Expression> context) { PlanNode rewrittenPlan = context.rewrite(node.getSource(), combineConjuncts(metadata, node.getPredicate(), context.get())); if (!(rewrittenPlan instanceof FilterNode)) { return rewrittenPlan; } FilterNode rewrittenFilterNode = (FilterNode) rewrittenPlan; if (!areExpressionsEquivalent(rewrittenFilterNode.getPredicate(), node.getPredicate()) || node.getSource() != rewrittenFilterNode.getSource()) { return rewrittenPlan; } return node; } @Override public PlanNode visitJoin(JoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); // See if we can rewrite outer joins in terms of a plain inner join node = tryNormalizeToOuterToInnerJoin(node, inheritedPredicate); Expression leftEffectivePredicate = effectivePredicateExtractor.extract(session, node.getLeft(), types, typeAnalyzer); Expression rightEffectivePredicate = effectivePredicateExtractor.extract(session, node.getRight(), types, typeAnalyzer); Expression joinPredicate = extractJoinPredicate(node); Expression leftPredicate; Expression rightPredicate; Expression postJoinPredicate; Expression newJoinPredicate; switch (node.getType()) { case INNER: InnerJoinPushDownResult innerJoinPushDownResult = processInnerJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = innerJoinPushDownResult.getLeftPredicate(); rightPredicate = innerJoinPushDownResult.getRightPredicate(); postJoinPredicate = innerJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = innerJoinPushDownResult.getJoinPredicate(); break; case LEFT: OuterJoinPushDownResult leftOuterJoinPushDownResult = processLimitedOuterJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = leftOuterJoinPushDownResult.getOuterJoinPredicate(); rightPredicate = leftOuterJoinPushDownResult.getInnerJoinPredicate(); postJoinPredicate = leftOuterJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = leftOuterJoinPushDownResult.getJoinPredicate(); break; case RIGHT: OuterJoinPushDownResult rightOuterJoinPushDownResult = processLimitedOuterJoin( inheritedPredicate, rightEffectivePredicate, leftEffectivePredicate, joinPredicate, node.getRight().getOutputSymbols(), node.getLeft().getOutputSymbols()); leftPredicate = rightOuterJoinPushDownResult.getInnerJoinPredicate(); rightPredicate = rightOuterJoinPushDownResult.getOuterJoinPredicate(); postJoinPredicate = rightOuterJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = rightOuterJoinPushDownResult.getJoinPredicate(); break; case FULL: leftPredicate = TRUE_LITERAL; rightPredicate = TRUE_LITERAL; postJoinPredicate = inheritedPredicate; newJoinPredicate = joinPredicate; break; default: throw new UnsupportedOperationException("Unsupported join type: " + node.getType()); } newJoinPredicate = simplifyExpression(newJoinPredicate); // Create identity projections for all existing symbols Assignments.Builder leftProjections = Assignments.builder(); leftProjections.putAll(node.getLeft() .getOutputSymbols().stream() .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); Assignments.Builder rightProjections = Assignments.builder(); rightProjections.putAll(node.getRight() .getOutputSymbols().stream() .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); // Create new projections for the new join clauses List<JoinNode.EquiJoinClause> equiJoinClauses = new ArrayList<>(); ImmutableList.Builder<Expression> joinFilterBuilder = ImmutableList.builder(); for (Expression conjunct : extractConjuncts(newJoinPredicate)) { if (joinEqualityExpression(conjunct, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols())) { ComparisonExpression equality = (ComparisonExpression) conjunct; boolean alignedComparison = node.getLeft().getOutputSymbols().containsAll(SymbolsExtractor.extractUnique(equality.getLeft())); Expression leftExpression = (alignedComparison) ? equality.getLeft() : equality.getRight(); Expression rightExpression = (alignedComparison) ? equality.getRight() : equality.getLeft(); Symbol leftSymbol = symbolForExpression(leftExpression); if (!node.getLeft().getOutputSymbols().contains(leftSymbol)) { leftProjections.put(leftSymbol, leftExpression); } Symbol rightSymbol = symbolForExpression(rightExpression); if (!node.getRight().getOutputSymbols().contains(rightSymbol)) { rightProjections.put(rightSymbol, rightExpression); } equiJoinClauses.add(new JoinNode.EquiJoinClause(leftSymbol, rightSymbol)); } else { joinFilterBuilder.add(conjunct); } } DynamicFiltersResult dynamicFiltersResult = createDynamicFilters(node, equiJoinClauses, session, idAllocator); Map<String, Symbol> dynamicFilters = dynamicFiltersResult.getDynamicFilters(); leftPredicate = combineConjuncts(metadata, leftPredicate, combineConjuncts(metadata, dynamicFiltersResult.getPredicates())); PlanNode leftSource; PlanNode rightSource; boolean equiJoinClausesUnmodified = ImmutableSet.copyOf(equiJoinClauses).equals(ImmutableSet.copyOf(node.getCriteria())); if (!equiJoinClausesUnmodified) { leftSource = context.rewrite(new ProjectNode(idAllocator.getNextId(), node.getLeft(), leftProjections.build()), leftPredicate); rightSource = context.rewrite(new ProjectNode(idAllocator.getNextId(), node.getRight(), rightProjections.build()), rightPredicate); } else { leftSource = context.rewrite(node.getLeft(), leftPredicate); rightSource = context.rewrite(node.getRight(), rightPredicate); } Optional<Expression> newJoinFilter = Optional.of(combineConjuncts(metadata, joinFilterBuilder.build())); if (newJoinFilter.get() == TRUE_LITERAL) { newJoinFilter = Optional.empty(); } if (node.getType() == INNER && newJoinFilter.isPresent() && equiJoinClauses.isEmpty()) { // if we do not have any equi conjunct we do not pushdown non-equality condition into // inner join, so we plan execution as nested-loops-join followed by filter instead // hash join. // todo: remove the code when we have support for filter function in nested loop join postJoinPredicate = combineConjuncts(metadata, postJoinPredicate, newJoinFilter.get()); newJoinFilter = Optional.empty(); } boolean filtersEquivalent = newJoinFilter.isPresent() == node.getFilter().isPresent() && (newJoinFilter.isEmpty() || areExpressionsEquivalent(newJoinFilter.get(), node.getFilter().get())); PlanNode output = node; if (leftSource != node.getLeft() || rightSource != node.getRight() || !filtersEquivalent || !dynamicFilters.equals(node.getDynamicFilters()) || !equiJoinClausesUnmodified) { leftSource = new ProjectNode(idAllocator.getNextId(), leftSource, leftProjections.build()); rightSource = new ProjectNode(idAllocator.getNextId(), rightSource, rightProjections.build()); output = new JoinNode( node.getId(), node.getType(), leftSource, rightSource, equiJoinClauses, leftSource.getOutputSymbols(), rightSource.getOutputSymbols(), newJoinFilter, node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), dynamicFilters, node.getReorderJoinStatsAndCost()); } if (!postJoinPredicate.equals(TRUE_LITERAL)) { output = new FilterNode(idAllocator.getNextId(), output, postJoinPredicate); } if (!node.getOutputSymbols().equals(output.getOutputSymbols())) { output = new ProjectNode(idAllocator.getNextId(), output, Assignments.identity(node.getOutputSymbols())); } return output; } private DynamicFiltersResult createDynamicFilters(JoinNode node, List<JoinNode.EquiJoinClause> equiJoinClauses, Session session, PlanNodeIdAllocator idAllocator) { Map<String, Symbol> dynamicFilters = ImmutableMap.of(); List<Expression> predicates = ImmutableList.of(); if (node.getType() == INNER && isEnableDynamicFiltering(session) && dynamicFiltering) { // New equiJoinClauses could potentially not contain symbols used in current dynamic filters. // Since we use PredicatePushdown to push dynamic filters themselves, // instead of separate ApplyDynamicFilters rule we derive dynamic filters within PredicatePushdown itself. // Even if equiJoinClauses.equals(node.getCriteria), current dynamic filters may not match equiJoinClauses ImmutableMap.Builder<String, Symbol> dynamicFiltersBuilder = ImmutableMap.builder(); ImmutableList.Builder<Expression> predicatesBuilder = ImmutableList.builder(); for (JoinNode.EquiJoinClause clause : equiJoinClauses) { Symbol probeSymbol = clause.getLeft(); Symbol buildSymbol = clause.getRight(); String id = "df_" + idAllocator.getNextId().toString(); predicatesBuilder.add(createDynamicFilterExpression(metadata, id, symbolAllocator.getTypes().get(probeSymbol), probeSymbol.toSymbolReference())); dynamicFiltersBuilder.put(id, buildSymbol); } dynamicFilters = dynamicFiltersBuilder.build(); predicates = predicatesBuilder.build(); } return new DynamicFiltersResult(dynamicFilters, predicates); } private static class DynamicFiltersResult { private final Map<String, Symbol> dynamicFilters; private final List<Expression> predicates; public DynamicFiltersResult(Map<String, Symbol> dynamicFilters, List<Expression> predicates) { this.dynamicFilters = dynamicFilters; this.predicates = predicates; } public Map<String, Symbol> getDynamicFilters() { return dynamicFilters; } public List<Expression> getPredicates() { return predicates; } } @Override public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); // See if we can rewrite left join in terms of a plain inner join if (node.getType() == SpatialJoinNode.Type.LEFT && canConvertOuterToInner(node.getRight().getOutputSymbols(), inheritedPredicate)) { node = new SpatialJoinNode(node.getId(), SpatialJoinNode.Type.INNER, node.getLeft(), node.getRight(), node.getOutputSymbols(), node.getFilter(), node.getLeftPartitionSymbol(), node.getRightPartitionSymbol(), node.getKdbTree()); } Expression leftEffectivePredicate = effectivePredicateExtractor.extract(session, node.getLeft(), types, typeAnalyzer); Expression rightEffectivePredicate = effectivePredicateExtractor.extract(session, node.getRight(), types, typeAnalyzer); Expression joinPredicate = node.getFilter(); Expression leftPredicate; Expression rightPredicate; Expression postJoinPredicate; Expression newJoinPredicate; switch (node.getType()) { case INNER: InnerJoinPushDownResult innerJoinPushDownResult = processInnerJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = innerJoinPushDownResult.getLeftPredicate(); rightPredicate = innerJoinPushDownResult.getRightPredicate(); postJoinPredicate = innerJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = innerJoinPushDownResult.getJoinPredicate(); break; case LEFT: OuterJoinPushDownResult leftOuterJoinPushDownResult = processLimitedOuterJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = leftOuterJoinPushDownResult.getOuterJoinPredicate(); rightPredicate = leftOuterJoinPushDownResult.getInnerJoinPredicate(); postJoinPredicate = leftOuterJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = leftOuterJoinPushDownResult.getJoinPredicate(); break; default: throw new IllegalArgumentException("Unsupported spatial join type: " + node.getType()); } newJoinPredicate = simplifyExpression(newJoinPredicate); verify(!newJoinPredicate.equals(BooleanLiteral.FALSE_LITERAL), "Spatial join predicate is missing"); PlanNode leftSource = context.rewrite(node.getLeft(), leftPredicate); PlanNode rightSource = context.rewrite(node.getRight(), rightPredicate); PlanNode output = node; if (leftSource != node.getLeft() || rightSource != node.getRight() || !areExpressionsEquivalent(newJoinPredicate, joinPredicate)) { // Create identity projections for all existing symbols Assignments.Builder leftProjections = Assignments.builder(); leftProjections.putAll(node.getLeft() .getOutputSymbols().stream() .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); Assignments.Builder rightProjections = Assignments.builder(); rightProjections.putAll(node.getRight() .getOutputSymbols().stream() .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); leftSource = new ProjectNode(idAllocator.getNextId(), leftSource, leftProjections.build()); rightSource = new ProjectNode(idAllocator.getNextId(), rightSource, rightProjections.build()); output = new SpatialJoinNode( node.getId(), node.getType(), leftSource, rightSource, node.getOutputSymbols(), newJoinPredicate, node.getLeftPartitionSymbol(), node.getRightPartitionSymbol(), node.getKdbTree()); } if (!postJoinPredicate.equals(TRUE_LITERAL)) { output = new FilterNode(idAllocator.getNextId(), output, postJoinPredicate); } return output; } private Symbol symbolForExpression(Expression expression) { if (expression instanceof SymbolReference) { return Symbol.from(expression); } return symbolAllocator.newSymbol(expression, typeAnalyzer.getType(session, symbolAllocator.getTypes(), expression)); } private OuterJoinPushDownResult processLimitedOuterJoin( Expression inheritedPredicate, Expression outerEffectivePredicate, Expression innerEffectivePredicate, Expression joinPredicate, Collection<Symbol> outerSymbols, Collection<Symbol> innerSymbols) { checkArgument(outerSymbols.containsAll(SymbolsExtractor.extractUnique(outerEffectivePredicate)), "outerEffectivePredicate must only contain symbols from outerSymbols"); checkArgument(innerSymbols.containsAll(SymbolsExtractor.extractUnique(innerEffectivePredicate)), "innerEffectivePredicate must only contain symbols from innerSymbols"); ImmutableList.Builder<Expression> outerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> innerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> postJoinConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> joinConjuncts = ImmutableList.builder(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(postJoinConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); outerEffectivePredicate = filterDeterministicConjuncts(metadata, outerEffectivePredicate); innerEffectivePredicate = filterDeterministicConjuncts(metadata, innerEffectivePredicate); extractConjuncts(joinPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(joinConjuncts::add); joinPredicate = filterDeterministicConjuncts(metadata, joinPredicate); // Generate equality inferences EqualityInference inheritedInference = EqualityInference.newInstance(metadata, inheritedPredicate); EqualityInference outerInference = EqualityInference.newInstance(metadata, inheritedPredicate, outerEffectivePredicate); Set<Symbol> innerScope = ImmutableSet.copyOf(innerSymbols); Set<Symbol> outerScope = ImmutableSet.copyOf(outerSymbols); EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(outerScope); Expression outerOnlyInheritedEqualities = combineConjuncts(metadata, equalityPartition.getScopeEqualities()); EqualityInference potentialNullSymbolInference = EqualityInference.newInstance(metadata, outerOnlyInheritedEqualities, outerEffectivePredicate, innerEffectivePredicate, joinPredicate); // Push outer and join equalities into the inner side. For example: // SELECT * FROM nation LEFT OUTER JOIN region ON nation.regionkey = region.regionkey and nation.name = region.name WHERE nation.name = 'blah' EqualityInference potentialNullSymbolInferenceWithoutInnerInferred = EqualityInference.newInstance(metadata, outerOnlyInheritedEqualities, outerEffectivePredicate, joinPredicate); innerPushdownConjuncts.addAll(potentialNullSymbolInferenceWithoutInnerInferred.generateEqualitiesPartitionedBy(innerScope).getScopeEqualities()); // TODO: we can further improve simplifying the equalities by considering other relationships from the outer side EqualityInference.EqualityPartition joinEqualityPartition = EqualityInference.newInstance(metadata, joinPredicate).generateEqualitiesPartitionedBy(innerScope); innerPushdownConjuncts.addAll(joinEqualityPartition.getScopeEqualities()); joinConjuncts.addAll(joinEqualityPartition.getScopeComplementEqualities()) .addAll(joinEqualityPartition.getScopeStraddlingEqualities()); // Add the equalities from the inferences back in outerPushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); // See if we can push inherited predicates down for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression outerRewritten = outerInference.rewrite(conjunct, outerScope); if (outerRewritten != null) { outerPushdownConjuncts.add(outerRewritten); // A conjunct can only be pushed down into an inner side if it can be rewritten in terms of the outer side Expression innerRewritten = potentialNullSymbolInference.rewrite(outerRewritten, innerScope); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } } else { postJoinConjuncts.add(conjunct); } } // See if we can push down any outer effective predicates to the inner side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, outerEffectivePredicate)) { Expression rewritten = potentialNullSymbolInference.rewrite(conjunct, innerScope); if (rewritten != null) { innerPushdownConjuncts.add(rewritten); } } // See if we can push down join predicates to the inner side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, joinPredicate)) { Expression innerRewritten = potentialNullSymbolInference.rewrite(conjunct, innerScope); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } else { joinConjuncts.add(conjunct); } } return new OuterJoinPushDownResult(combineConjuncts(metadata, outerPushdownConjuncts.build()), combineConjuncts(metadata, innerPushdownConjuncts.build()), combineConjuncts(metadata, joinConjuncts.build()), combineConjuncts(metadata, postJoinConjuncts.build())); } private static class OuterJoinPushDownResult { private final Expression outerJoinPredicate; private final Expression innerJoinPredicate; private final Expression joinPredicate; private final Expression postJoinPredicate; private OuterJoinPushDownResult(Expression outerJoinPredicate, Expression innerJoinPredicate, Expression joinPredicate, Expression postJoinPredicate) { this.outerJoinPredicate = outerJoinPredicate; this.innerJoinPredicate = innerJoinPredicate; this.joinPredicate = joinPredicate; this.postJoinPredicate = postJoinPredicate; } private Expression getOuterJoinPredicate() { return outerJoinPredicate; } private Expression getInnerJoinPredicate() { return innerJoinPredicate; } public Expression getJoinPredicate() { return joinPredicate; } private Expression getPostJoinPredicate() { return postJoinPredicate; } } private InnerJoinPushDownResult processInnerJoin( Expression inheritedPredicate, Expression leftEffectivePredicate, Expression rightEffectivePredicate, Expression joinPredicate, Collection<Symbol> leftSymbols, Collection<Symbol> rightSymbols) { checkArgument(leftSymbols.containsAll(SymbolsExtractor.extractUnique(leftEffectivePredicate)), "leftEffectivePredicate must only contain symbols from leftSymbols"); checkArgument(rightSymbols.containsAll(SymbolsExtractor.extractUnique(rightEffectivePredicate)), "rightEffectivePredicate must only contain symbols from rightSymbols"); ImmutableList.Builder<Expression> leftPushDownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> rightPushDownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> joinConjuncts = ImmutableList.builder(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(deterministic -> !isDeterministic(deterministic, metadata)) .forEach(joinConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); extractConjuncts(joinPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(joinConjuncts::add); joinPredicate = filterDeterministicConjuncts(metadata, joinPredicate); leftEffectivePredicate = filterDeterministicConjuncts(metadata, leftEffectivePredicate); rightEffectivePredicate = filterDeterministicConjuncts(metadata, rightEffectivePredicate); ImmutableSet<Symbol> leftScope = ImmutableSet.copyOf(leftSymbols); ImmutableSet<Symbol> rightScope = ImmutableSet.copyOf(rightSymbols); // Attempt to simplify the effective left/right predicates with the predicate we're pushing down // This, effectively, inlines any constants derived from such predicate EqualityInference predicateInference = EqualityInference.newInstance(metadata, inheritedPredicate); Expression simplifiedLeftEffectivePredicate = predicateInference.rewrite(leftEffectivePredicate, leftScope); Expression simplifiedRightEffectivePredicate = predicateInference.rewrite(rightEffectivePredicate, rightScope); // simplify predicate based on known equalities guaranteed by the left/right side EqualityInference assertions = EqualityInference.newInstance(metadata, leftEffectivePredicate, rightEffectivePredicate); inheritedPredicate = assertions.rewrite(inheritedPredicate, Sets.union(leftScope, rightScope)); // Generate equality inferences EqualityInference allInference = EqualityInference.newInstance(metadata, inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, simplifiedLeftEffectivePredicate, simplifiedRightEffectivePredicate); EqualityInference allInferenceWithoutLeftInferred = EqualityInference.newInstance(metadata, inheritedPredicate, rightEffectivePredicate, joinPredicate, simplifiedRightEffectivePredicate); EqualityInference allInferenceWithoutRightInferred = EqualityInference.newInstance(metadata, inheritedPredicate, leftEffectivePredicate, joinPredicate, simplifiedLeftEffectivePredicate); // Add equalities from the inference back in leftPushDownConjuncts.addAll(allInferenceWithoutLeftInferred.generateEqualitiesPartitionedBy(leftScope).getScopeEqualities()); rightPushDownConjuncts.addAll(allInferenceWithoutRightInferred.generateEqualitiesPartitionedBy(rightScope).getScopeEqualities()); joinConjuncts.addAll(allInference.generateEqualitiesPartitionedBy(leftScope).getScopeStraddlingEqualities()); // scope straddling equalities get dropped in as part of the join predicate // Sort through conjuncts in inheritedPredicate that were not used for inference for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression leftRewrittenConjunct = allInference.rewrite(conjunct, leftScope); if (leftRewrittenConjunct != null) { leftPushDownConjuncts.add(leftRewrittenConjunct); } Expression rightRewrittenConjunct = allInference.rewrite(conjunct, rightScope); if (rightRewrittenConjunct != null) { rightPushDownConjuncts.add(rightRewrittenConjunct); } // Drop predicate after join only if unable to push down to either side if (leftRewrittenConjunct == null && rightRewrittenConjunct == null) { joinConjuncts.add(conjunct); } } // See if we can push the right effective predicate to the left side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, simplifiedRightEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, leftScope); if (rewritten != null) { leftPushDownConjuncts.add(rewritten); } } // See if we can push the left effective predicate to the right side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, simplifiedLeftEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, rightScope); if (rewritten != null) { rightPushDownConjuncts.add(rewritten); } } // See if we can push any parts of the join predicates to either side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, joinPredicate)) { Expression leftRewritten = allInference.rewrite(conjunct, leftScope); if (leftRewritten != null) { leftPushDownConjuncts.add(leftRewritten); } Expression rightRewritten = allInference.rewrite(conjunct, rightScope); if (rightRewritten != null) { rightPushDownConjuncts.add(rightRewritten); } if (leftRewritten == null && rightRewritten == null) { joinConjuncts.add(conjunct); } } return new InnerJoinPushDownResult( combineConjuncts(metadata, leftPushDownConjuncts.build()), combineConjuncts(metadata, rightPushDownConjuncts.build()), combineConjuncts(metadata, joinConjuncts.build()), TRUE_LITERAL); } private static class InnerJoinPushDownResult { private final Expression leftPredicate; private final Expression rightPredicate; private final Expression joinPredicate; private final Expression postJoinPredicate; private InnerJoinPushDownResult(Expression leftPredicate, Expression rightPredicate, Expression joinPredicate, Expression postJoinPredicate) { this.leftPredicate = leftPredicate; this.rightPredicate = rightPredicate; this.joinPredicate = joinPredicate; this.postJoinPredicate = postJoinPredicate; } private Expression getLeftPredicate() { return leftPredicate; } private Expression getRightPredicate() { return rightPredicate; } private Expression getJoinPredicate() { return joinPredicate; } private Expression getPostJoinPredicate() { return postJoinPredicate; } } private Expression extractJoinPredicate(JoinNode joinNode) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (JoinNode.EquiJoinClause equiJoinClause : joinNode.getCriteria()) { builder.add(equiJoinClause.toExpression()); } joinNode.getFilter().ifPresent(builder::add); return combineConjuncts(metadata, builder.build()); } private JoinNode tryNormalizeToOuterToInnerJoin(JoinNode node, Expression inheritedPredicate) { checkArgument(EnumSet.of(INNER, RIGHT, LEFT, FULL).contains(node.getType()), "Unsupported join type: %s", node.getType()); if (node.getType() == JoinNode.Type.INNER) { return node; } if (node.getType() == JoinNode.Type.FULL) { boolean canConvertToLeftJoin = canConvertOuterToInner(node.getLeft().getOutputSymbols(), inheritedPredicate); boolean canConvertToRightJoin = canConvertOuterToInner(node.getRight().getOutputSymbols(), inheritedPredicate); if (!canConvertToLeftJoin && !canConvertToRightJoin) { return node; } if (canConvertToLeftJoin && canConvertToRightJoin) { return new JoinNode( node.getId(), INNER, node.getLeft(), node.getRight(), node.getCriteria(), node.getLeftOutputSymbols(), node.getRightOutputSymbols(), node.getFilter(), node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), node.getDynamicFilters(), node.getReorderJoinStatsAndCost()); } else { return new JoinNode( node.getId(), canConvertToLeftJoin ? LEFT : RIGHT, node.getLeft(), node.getRight(), node.getCriteria(), node.getLeftOutputSymbols(), node.getRightOutputSymbols(), node.getFilter(), node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), node.getDynamicFilters(), node.getReorderJoinStatsAndCost()); } } if (node.getType() == JoinNode.Type.LEFT && !canConvertOuterToInner(node.getRight().getOutputSymbols(), inheritedPredicate) || node.getType() == JoinNode.Type.RIGHT && !canConvertOuterToInner(node.getLeft().getOutputSymbols(), inheritedPredicate)) { return node; } return new JoinNode( node.getId(), JoinNode.Type.INNER, node.getLeft(), node.getRight(), node.getCriteria(), node.getLeftOutputSymbols(), node.getRightOutputSymbols(), node.getFilter(), node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), node.getDynamicFilters(), node.getReorderJoinStatsAndCost()); } private boolean canConvertOuterToInner(List<Symbol> innerSymbolsForOuterJoin, Expression inheritedPredicate) { Set<Symbol> innerSymbols = ImmutableSet.copyOf(innerSymbolsForOuterJoin); for (Expression conjunct : extractConjuncts(inheritedPredicate)) { if (isDeterministic(conjunct, metadata)) { // Ignore a conjunct for this test if we cannot deterministically get responses from it Object response = nullInputEvaluator(innerSymbols, conjunct); if (response == null || response instanceof NullLiteral || Boolean.FALSE.equals(response)) { // If there is a single conjunct that returns FALSE or NULL given all NULL inputs for the inner side symbols of an outer join // then this conjunct removes all effects of the outer join, and effectively turns this into an equivalent of an inner join. // So, let's just rewrite this join as an INNER join return true; } } } return false; } // Temporary implementation for joins because the SimplifyExpressions optimizers cannot run properly on join clauses private Expression simplifyExpression(Expression expression) { Map<NodeRef<Expression>, Type> expressionTypes = typeAnalyzer.getTypes(session, symbolAllocator.getTypes(), expression); ExpressionInterpreter optimizer = ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes); return literalEncoder.toExpression(optimizer.optimize(NoOpSymbolResolver.INSTANCE), expressionTypes.get(NodeRef.of(expression))); } private boolean areExpressionsEquivalent(Expression leftExpression, Expression rightExpression) { return expressionEquivalence.areExpressionsEquivalent(session, leftExpression, rightExpression, types); } /** * Evaluates an expression's response to binding the specified input symbols to NULL */ private Object nullInputEvaluator(final Collection<Symbol> nullSymbols, Expression expression) { Map<NodeRef<Expression>, Type> expressionTypes = typeAnalyzer.getTypes(session, symbolAllocator.getTypes(), expression); return ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes) .optimize(symbol -> nullSymbols.contains(symbol) ? null : symbol.toSymbolReference()); } private boolean joinEqualityExpression(Expression expression, Collection<Symbol> leftSymbols, Collection<Symbol> rightSymbols) { // At this point in time, our join predicates need to be deterministic if (expression instanceof ComparisonExpression && isDeterministic(expression, metadata)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getOperator() == ComparisonExpression.Operator.EQUAL) { Set<Symbol> symbols1 = SymbolsExtractor.extractUnique(comparison.getLeft()); Set<Symbol> symbols2 = SymbolsExtractor.extractUnique(comparison.getRight()); if (symbols1.isEmpty() || symbols2.isEmpty()) { return false; } return (leftSymbols.containsAll(symbols1) && rightSymbols.containsAll(symbols2)) || (rightSymbols.containsAll(symbols1) && leftSymbols.containsAll(symbols2)); } } return false; } @Override public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); if (!extractConjuncts(inheritedPredicate).contains(node.getSemiJoinOutput().toSymbolReference())) { return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); } private PlanNode visitNonFilteringSemiJoin(SemiJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); List<Expression> sourceConjuncts = new ArrayList<>(); List<Expression> postJoinConjuncts = new ArrayList<>(); // TODO: see if there are predicates that can be inferred from the semi join output PlanNode rewrittenFilteringSource = context.defaultRewrite(node.getFilteringSource(), TRUE_LITERAL); // Push inheritedPredicates down to the source if they don't involve the semi join output ImmutableSet<Symbol> sourceScope = ImmutableSet.copyOf(node.getSource().getOutputSymbols()); EqualityInference inheritedInference = EqualityInference.newInstance(metadata, inheritedPredicate); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression rewrittenConjunct = inheritedInference.rewrite(conjunct, sourceScope); // Since each source row is reflected exactly once in the output, ok to push non-deterministic predicates down if (rewrittenConjunct != null) { sourceConjuncts.add(rewrittenConjunct); } else { postJoinConjuncts.add(conjunct); } } // Add the inherited equality predicates back in EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(sourceScope); sourceConjuncts.addAll(equalityPartition.getScopeEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, sourceConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource() || rewrittenFilteringSource != node.getFilteringSource()) { output = new SemiJoinNode(node.getId(), rewrittenSource, rewrittenFilteringSource, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput(), node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol(), node.getDistributionType()); } if (!postJoinConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postJoinConjuncts)); } return output; } private PlanNode visitFilteringSemiJoin(SemiJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); Expression deterministicInheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); Expression sourceEffectivePredicate = filterDeterministicConjuncts(metadata, effectivePredicateExtractor.extract(session, node.getSource(), types, typeAnalyzer)); Expression filteringSourceEffectivePredicate = filterDeterministicConjuncts(metadata, effectivePredicateExtractor.extract(session, node.getFilteringSource(), types, typeAnalyzer)); Expression joinExpression = new ComparisonExpression( ComparisonExpression.Operator.EQUAL, node.getSourceJoinSymbol().toSymbolReference(), node.getFilteringSourceJoinSymbol().toSymbolReference()); List<Symbol> sourceSymbols = node.getSource().getOutputSymbols(); List<Symbol> filteringSourceSymbols = node.getFilteringSource().getOutputSymbols(); List<Expression> sourceConjuncts = new ArrayList<>(); List<Expression> filteringSourceConjuncts = new ArrayList<>(); List<Expression> postJoinConjuncts = new ArrayList<>(); // Generate equality inferences EqualityInference allInference = EqualityInference.newInstance(metadata, deterministicInheritedPredicate, sourceEffectivePredicate, filteringSourceEffectivePredicate, joinExpression); EqualityInference allInferenceWithoutSourceInferred = EqualityInference.newInstance(metadata, deterministicInheritedPredicate, filteringSourceEffectivePredicate, joinExpression); EqualityInference allInferenceWithoutFilteringSourceInferred = EqualityInference.newInstance(metadata, deterministicInheritedPredicate, sourceEffectivePredicate, joinExpression); // Push inheritedPredicates down to the source if they don't involve the semi join output Set<Symbol> sourceScope = ImmutableSet.copyOf(sourceSymbols); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression rewrittenConjunct = allInference.rewrite(conjunct, sourceScope); // Since each source row is reflected exactly once in the output, ok to push non-deterministic predicates down if (rewrittenConjunct != null) { sourceConjuncts.add(rewrittenConjunct); } else { postJoinConjuncts.add(conjunct); } } // Push inheritedPredicates down to the filtering source if possible Set<Symbol> filterScope = ImmutableSet.copyOf(filteringSourceSymbols); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, deterministicInheritedPredicate)) { Expression rewrittenConjunct = allInference.rewrite(conjunct, filterScope); // We cannot push non-deterministic predicates to filtering side. Each filtering side row have to be // logically reevaluated for each source row. if (rewrittenConjunct != null) { filteringSourceConjuncts.add(rewrittenConjunct); } } // move effective predicate conjuncts source <-> filter // See if we can push the filtering source effective predicate to the source side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, filteringSourceEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, sourceScope); if (rewritten != null) { sourceConjuncts.add(rewritten); } } // See if we can push the source effective predicate to the filtering soruce side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, sourceEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, filterScope); if (rewritten != null) { filteringSourceConjuncts.add(rewritten); } } // Add equalities from the inference back in sourceConjuncts.addAll(allInferenceWithoutSourceInferred.generateEqualitiesPartitionedBy(sourceScope).getScopeEqualities()); filteringSourceConjuncts.addAll(allInferenceWithoutFilteringSourceInferred.generateEqualitiesPartitionedBy(filterScope).getScopeEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, sourceConjuncts)); PlanNode rewrittenFilteringSource = context.rewrite(node.getFilteringSource(), combineConjuncts(metadata, filteringSourceConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource() || rewrittenFilteringSource != node.getFilteringSource()) { output = new SemiJoinNode( node.getId(), rewrittenSource, rewrittenFilteringSource, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput(), node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol(), node.getDistributionType()); } if (!postJoinConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postJoinConjuncts)); } return output; } @Override public PlanNode visitAggregation(AggregationNode node, RewriteContext<Expression> context) { if (node.hasEmptyGroupingSet()) { // TODO: in case of grouping sets, we should be able to push the filters over grouping keys below the aggregation // and also preserve the filter above the aggregation if it has an empty grouping set return visitPlan(node, context); } Expression inheritedPredicate = context.get(); EqualityInference equalityInference = EqualityInference.newInstance(metadata, inheritedPredicate); List<Expression> pushdownConjuncts = new ArrayList<>(); List<Expression> postAggregationConjuncts = new ArrayList<>(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(postAggregationConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); // Sort non-equality predicates by those that can be pushed down and those that cannot Set<Symbol> groupingKeys = ImmutableSet.copyOf(node.getGroupingKeys()); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { if (node.getGroupIdSymbol().isPresent() && SymbolsExtractor.extractUnique(conjunct).contains(node.getGroupIdSymbol().get())) { // aggregation operator synthesizes outputs for group ids corresponding to the global grouping set (i.e., ()), so we // need to preserve any predicates that evaluate the group id to run after the aggregation // TODO: we should be able to infer if conditions on grouping() correspond to global grouping sets to determine whether // we need to do this for each specific case postAggregationConjuncts.add(conjunct); continue; } Expression rewrittenConjunct = equalityInference.rewrite(conjunct, groupingKeys); if (rewrittenConjunct != null) { pushdownConjuncts.add(rewrittenConjunct); } else { postAggregationConjuncts.add(conjunct); } } // Add the equality predicates back in EqualityInference.EqualityPartition equalityPartition = equalityInference.generateEqualitiesPartitionedBy(groupingKeys); pushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postAggregationConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postAggregationConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, pushdownConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource()) { output = new AggregationNode(node.getId(), rewrittenSource, node.getAggregations(), node.getGroupingSets(), ImmutableList.of(), node.getStep(), node.getHashSymbol(), node.getGroupIdSymbol()); } if (!postAggregationConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postAggregationConjuncts)); } return output; } @Override public PlanNode visitUnnest(UnnestNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); if (node.getJoinType() == RIGHT || node.getJoinType() == FULL) { return new FilterNode(idAllocator.getNextId(), node, inheritedPredicate); } //TODO for LEFT or INNER join type, push down UnnestNode's filter on replicate symbols EqualityInference equalityInference = EqualityInference.newInstance(metadata, inheritedPredicate); List<Expression> pushdownConjuncts = new ArrayList<>(); List<Expression> postUnnestConjuncts = new ArrayList<>(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(postUnnestConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); // Sort non-equality predicates by those that can be pushed down and those that cannot Set<Symbol> replicatedSymbols = ImmutableSet.copyOf(node.getReplicateSymbols()); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression rewrittenConjunct = equalityInference.rewrite(conjunct, replicatedSymbols); if (rewrittenConjunct != null) { pushdownConjuncts.add(rewrittenConjunct); } else { postUnnestConjuncts.add(conjunct); } } // Add the equality predicates back in EqualityInference.EqualityPartition equalityPartition = equalityInference.generateEqualitiesPartitionedBy(replicatedSymbols); pushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postUnnestConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postUnnestConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, pushdownConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource()) { output = new UnnestNode(node.getId(), rewrittenSource, node.getReplicateSymbols(), node.getMappings(), node.getOrdinalitySymbol(), node.getJoinType(), node.getFilter()); } if (!postUnnestConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postUnnestConjuncts)); } return output; } @Override public PlanNode visitSample(SampleNode node, RewriteContext<Expression> context) { return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitTableScan(TableScanNode node, RewriteContext<Expression> context) { Expression predicate = simplifyExpression(context.get()); if (!TRUE_LITERAL.equals(predicate)) { return new FilterNode(idAllocator.getNextId(), node, predicate); } return node; } @Override public PlanNode visitAssignUniqueId(AssignUniqueId node, RewriteContext<Expression> context) { Set<Symbol> predicateSymbols = SymbolsExtractor.extractUnique(context.get()); checkState(!predicateSymbols.contains(node.getIdColumn()), "UniqueId in predicate is not yet supported"); return context.defaultRewrite(node, context.get()); } } }
presto-main/src/main/java/io/prestosql/sql/planner/optimizations/PredicatePushDown.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.sql.planner.optimizations; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import io.prestosql.Session; import io.prestosql.execution.warnings.WarningCollector; import io.prestosql.metadata.Metadata; import io.prestosql.spi.type.Type; import io.prestosql.sql.planner.DomainTranslator; import io.prestosql.sql.planner.EffectivePredicateExtractor; import io.prestosql.sql.planner.EqualityInference; import io.prestosql.sql.planner.ExpressionInterpreter; import io.prestosql.sql.planner.LiteralEncoder; import io.prestosql.sql.planner.NoOpSymbolResolver; import io.prestosql.sql.planner.PlanNodeIdAllocator; import io.prestosql.sql.planner.Symbol; import io.prestosql.sql.planner.SymbolAllocator; import io.prestosql.sql.planner.SymbolsExtractor; import io.prestosql.sql.planner.TypeAnalyzer; import io.prestosql.sql.planner.TypeProvider; import io.prestosql.sql.planner.plan.AggregationNode; import io.prestosql.sql.planner.plan.AssignUniqueId; import io.prestosql.sql.planner.plan.Assignments; import io.prestosql.sql.planner.plan.ExchangeNode; import io.prestosql.sql.planner.plan.FilterNode; import io.prestosql.sql.planner.plan.GroupIdNode; import io.prestosql.sql.planner.plan.JoinNode; import io.prestosql.sql.planner.plan.MarkDistinctNode; import io.prestosql.sql.planner.plan.PlanNode; import io.prestosql.sql.planner.plan.ProjectNode; import io.prestosql.sql.planner.plan.SampleNode; import io.prestosql.sql.planner.plan.SemiJoinNode; import io.prestosql.sql.planner.plan.SimplePlanRewriter; import io.prestosql.sql.planner.plan.SortNode; import io.prestosql.sql.planner.plan.SpatialJoinNode; import io.prestosql.sql.planner.plan.TableScanNode; import io.prestosql.sql.planner.plan.UnionNode; import io.prestosql.sql.planner.plan.UnnestNode; import io.prestosql.sql.planner.plan.WindowNode; import io.prestosql.sql.tree.BooleanLiteral; import io.prestosql.sql.tree.ComparisonExpression; import io.prestosql.sql.tree.Expression; import io.prestosql.sql.tree.Literal; import io.prestosql.sql.tree.NodeRef; import io.prestosql.sql.tree.NullLiteral; import io.prestosql.sql.tree.SymbolReference; import io.prestosql.sql.tree.TryExpression; import io.prestosql.sql.util.AstUtils; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static io.prestosql.SystemSessionProperties.isEnableDynamicFiltering; import static io.prestosql.SystemSessionProperties.isPredicatePushdownUseTableProperties; import static io.prestosql.sql.DynamicFilters.createDynamicFilterExpression; import static io.prestosql.sql.ExpressionUtils.combineConjuncts; import static io.prestosql.sql.ExpressionUtils.extractConjuncts; import static io.prestosql.sql.ExpressionUtils.filterDeterministicConjuncts; import static io.prestosql.sql.planner.DeterminismEvaluator.isDeterministic; import static io.prestosql.sql.planner.ExpressionSymbolInliner.inlineSymbols; import static io.prestosql.sql.planner.iterative.rule.CanonicalizeExpressionRewriter.canonicalizeExpression; import static io.prestosql.sql.planner.iterative.rule.UnwrapCastInComparison.unwrapCasts; import static io.prestosql.sql.planner.plan.JoinNode.Type.FULL; import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER; import static io.prestosql.sql.planner.plan.JoinNode.Type.LEFT; import static io.prestosql.sql.planner.plan.JoinNode.Type.RIGHT; import static io.prestosql.sql.tree.BooleanLiteral.TRUE_LITERAL; import static java.util.Objects.requireNonNull; public class PredicatePushDown implements PlanOptimizer { private final Metadata metadata; private final LiteralEncoder literalEncoder; private final TypeAnalyzer typeAnalyzer; private final boolean useTableProperties; private final boolean dynamicFiltering; public PredicatePushDown(Metadata metadata, TypeAnalyzer typeAnalyzer, boolean useTableProperties, boolean dynamicFiltering) { this.metadata = requireNonNull(metadata, "metadata is null"); this.literalEncoder = new LiteralEncoder(metadata); this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null"); this.useTableProperties = useTableProperties; this.dynamicFiltering = dynamicFiltering; } @Override public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { requireNonNull(plan, "plan is null"); requireNonNull(session, "session is null"); requireNonNull(types, "types is null"); requireNonNull(idAllocator, "idAllocator is null"); EffectivePredicateExtractor effectivePredicateExtractor = new EffectivePredicateExtractor( new DomainTranslator(metadata), metadata, useTableProperties && isPredicatePushdownUseTableProperties(session)); return SimplePlanRewriter.rewriteWith( new Rewriter(symbolAllocator, idAllocator, metadata, literalEncoder, effectivePredicateExtractor, typeAnalyzer, session, types, dynamicFiltering), plan, TRUE_LITERAL); } private static class Rewriter extends SimplePlanRewriter<Expression> { private final SymbolAllocator symbolAllocator; private final PlanNodeIdAllocator idAllocator; private final Metadata metadata; private final LiteralEncoder literalEncoder; private final EffectivePredicateExtractor effectivePredicateExtractor; private final TypeAnalyzer typeAnalyzer; private final Session session; private final TypeProvider types; private final ExpressionEquivalence expressionEquivalence; private final boolean dynamicFiltering; private Rewriter( SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, Metadata metadata, LiteralEncoder literalEncoder, EffectivePredicateExtractor effectivePredicateExtractor, TypeAnalyzer typeAnalyzer, Session session, TypeProvider types, boolean dynamicFiltering) { this.symbolAllocator = requireNonNull(symbolAllocator, "symbolAllocator is null"); this.idAllocator = requireNonNull(idAllocator, "idAllocator is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.literalEncoder = requireNonNull(literalEncoder, "literalEncoder is null"); this.effectivePredicateExtractor = requireNonNull(effectivePredicateExtractor, "effectivePredicateExtractor is null"); this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null"); this.session = requireNonNull(session, "session is null"); this.types = requireNonNull(types, "types is null"); this.expressionEquivalence = new ExpressionEquivalence(metadata, typeAnalyzer); this.dynamicFiltering = dynamicFiltering; } @Override public PlanNode visitPlan(PlanNode node, RewriteContext<Expression> context) { PlanNode rewrittenNode = context.defaultRewrite(node, TRUE_LITERAL); if (!context.get().equals(TRUE_LITERAL)) { // Drop in a FilterNode b/c we cannot push our predicate down any further rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, context.get()); } return rewrittenNode; } @Override public PlanNode visitExchange(ExchangeNode node, RewriteContext<Expression> context) { boolean modified = false; ImmutableList.Builder<PlanNode> builder = ImmutableList.builder(); for (int i = 0; i < node.getSources().size(); i++) { Map<Symbol, SymbolReference> outputsToInputs = new HashMap<>(); for (int index = 0; index < node.getInputs().get(i).size(); index++) { outputsToInputs.put( node.getOutputSymbols().get(index), node.getInputs().get(i).get(index).toSymbolReference()); } Expression sourcePredicate = inlineSymbols(outputsToInputs, context.get()); PlanNode source = node.getSources().get(i); PlanNode rewrittenSource = context.rewrite(source, sourcePredicate); if (rewrittenSource != source) { modified = true; } builder.add(rewrittenSource); } if (modified) { return new ExchangeNode( node.getId(), node.getType(), node.getScope(), node.getPartitioningScheme(), builder.build(), node.getInputs(), node.getOrderingScheme()); } return node; } @Override public PlanNode visitWindow(WindowNode node, RewriteContext<Expression> context) { List<Symbol> partitionSymbols = node.getPartitionBy(); // TODO: This could be broader. We can push down conjucts if they are constant for all rows in a window partition. // The simplest way to guarantee this is if the conjucts are deterministic functions of the partitioning symbols. // This can leave out cases where they're both functions of some set of common expressions and the partitioning // function is injective, but that's a rare case. The majority of window nodes are expected to be partitioned by // pre-projected symbols. Predicate<Expression> isSupported = conjunct -> isDeterministic(conjunct, metadata) && SymbolsExtractor.extractUnique(conjunct).stream() .allMatch(partitionSymbols::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(isSupported)); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(metadata, conjuncts.get(true))); if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, conjuncts.get(false))); } return rewrittenNode; } @Override public PlanNode visitProject(ProjectNode node, RewriteContext<Expression> context) { Set<Symbol> deterministicSymbols = node.getAssignments().entrySet().stream() .filter(entry -> isDeterministic(entry.getValue(), metadata)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); Predicate<Expression> deterministic = conjunct -> SymbolsExtractor.extractUnique(conjunct).stream() .allMatch(deterministicSymbols::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(deterministic)); // Push down conjuncts from the inherited predicate that only depend on deterministic assignments with // certain limitations. List<Expression> deterministicConjuncts = conjuncts.get(true); // We partition the expressions in the deterministicConjuncts into two lists, and only inline the // expressions that are in the inlining targets list. Map<Boolean, List<Expression>> inlineConjuncts = deterministicConjuncts.stream() .collect(Collectors.partitioningBy(expression -> isInliningCandidate(expression, node))); List<Expression> inlinedDeterministicConjuncts = inlineConjuncts.get(true).stream() .map(entry -> inlineSymbols(node.getAssignments().getMap(), entry)) .map(conjunct -> canonicalizeExpression(conjunct, typeAnalyzer.getTypes(session, types, conjunct), metadata)) // normalize expressions to a form that unwrapCasts understands .map(conjunct -> unwrapCasts(session, metadata, typeAnalyzer, types, conjunct)) .collect(Collectors.toList()); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(metadata, inlinedDeterministicConjuncts)); // All deterministic conjuncts that contains non-inlining targets, and non-deterministic conjuncts, // if any, will be in the filter node. List<Expression> nonInliningConjuncts = inlineConjuncts.get(false); nonInliningConjuncts.addAll(conjuncts.get(false)); if (!nonInliningConjuncts.isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, nonInliningConjuncts)); } return rewrittenNode; } private boolean isInliningCandidate(Expression expression, ProjectNode node) { // TryExpressions should not be pushed down. However they are now being handled as lambda // passed to a FunctionCall now and should not affect predicate push down. So we want to make // sure the conjuncts are not TryExpressions. verify(AstUtils.preOrder(expression).noneMatch(TryExpression.class::isInstance)); // candidate symbols for inlining are // 1. references to simple constants or symbol references // 2. references to complex expressions that appear only once // which come from the node, as opposed to an enclosing scope. Set<Symbol> childOutputSet = ImmutableSet.copyOf(node.getOutputSymbols()); Map<Symbol, Long> dependencies = SymbolsExtractor.extractAll(expression).stream() .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); return dependencies.entrySet().stream() .allMatch(entry -> entry.getValue() == 1 || node.getAssignments().get(entry.getKey()) instanceof Literal || node.getAssignments().get(entry.getKey()) instanceof SymbolReference); } @Override public PlanNode visitGroupId(GroupIdNode node, RewriteContext<Expression> context) { Map<Symbol, SymbolReference> commonGroupingSymbolMapping = node.getGroupingColumns().entrySet().stream() .filter(entry -> node.getCommonGroupingColumns().contains(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference())); Predicate<Expression> pushdownEligiblePredicate = conjunct -> commonGroupingSymbolMapping.keySet().containsAll(SymbolsExtractor.extractUnique(conjunct)); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(pushdownEligiblePredicate)); // Push down conjuncts from the inherited predicate that apply to common grouping symbols PlanNode rewrittenNode = context.defaultRewrite(node, inlineSymbols(commonGroupingSymbolMapping, combineConjuncts(metadata, conjuncts.get(true)))); // All other conjuncts, if any, will be in the filter node. if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, conjuncts.get(false))); } return rewrittenNode; } @Override public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Expression> context) { Set<Symbol> pushDownableSymbols = ImmutableSet.copyOf(node.getDistinctSymbols()); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream() .collect(Collectors.partitioningBy(conjunct -> SymbolsExtractor.extractUnique(conjunct).stream().allMatch(pushDownableSymbols::contains))); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(metadata, conjuncts.get(true))); if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(metadata, conjuncts.get(false))); } return rewrittenNode; } @Override public PlanNode visitSort(SortNode node, RewriteContext<Expression> context) { return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitUnion(UnionNode node, RewriteContext<Expression> context) { boolean modified = false; ImmutableList.Builder<PlanNode> builder = ImmutableList.builder(); for (int i = 0; i < node.getSources().size(); i++) { Expression sourcePredicate = inlineSymbols(node.sourceSymbolMap(i), context.get()); PlanNode source = node.getSources().get(i); PlanNode rewrittenSource = context.rewrite(source, sourcePredicate); if (rewrittenSource != source) { modified = true; } builder.add(rewrittenSource); } if (modified) { return new UnionNode(node.getId(), builder.build(), node.getSymbolMapping(), node.getOutputSymbols()); } return node; } @Deprecated @Override public PlanNode visitFilter(FilterNode node, RewriteContext<Expression> context) { PlanNode rewrittenPlan = context.rewrite(node.getSource(), combineConjuncts(metadata, node.getPredicate(), context.get())); if (!(rewrittenPlan instanceof FilterNode)) { return rewrittenPlan; } FilterNode rewrittenFilterNode = (FilterNode) rewrittenPlan; if (!areExpressionsEquivalent(rewrittenFilterNode.getPredicate(), node.getPredicate()) || node.getSource() != rewrittenFilterNode.getSource()) { return rewrittenPlan; } return node; } @Override public PlanNode visitJoin(JoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); // See if we can rewrite outer joins in terms of a plain inner join node = tryNormalizeToOuterToInnerJoin(node, inheritedPredicate); Expression leftEffectivePredicate = effectivePredicateExtractor.extract(session, node.getLeft(), types, typeAnalyzer); Expression rightEffectivePredicate = effectivePredicateExtractor.extract(session, node.getRight(), types, typeAnalyzer); Expression joinPredicate = extractJoinPredicate(node); Expression leftPredicate; Expression rightPredicate; Expression postJoinPredicate; Expression newJoinPredicate; switch (node.getType()) { case INNER: InnerJoinPushDownResult innerJoinPushDownResult = processInnerJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = innerJoinPushDownResult.getLeftPredicate(); rightPredicate = innerJoinPushDownResult.getRightPredicate(); postJoinPredicate = innerJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = innerJoinPushDownResult.getJoinPredicate(); break; case LEFT: OuterJoinPushDownResult leftOuterJoinPushDownResult = processLimitedOuterJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = leftOuterJoinPushDownResult.getOuterJoinPredicate(); rightPredicate = leftOuterJoinPushDownResult.getInnerJoinPredicate(); postJoinPredicate = leftOuterJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = leftOuterJoinPushDownResult.getJoinPredicate(); break; case RIGHT: OuterJoinPushDownResult rightOuterJoinPushDownResult = processLimitedOuterJoin( inheritedPredicate, rightEffectivePredicate, leftEffectivePredicate, joinPredicate, node.getRight().getOutputSymbols(), node.getLeft().getOutputSymbols()); leftPredicate = rightOuterJoinPushDownResult.getInnerJoinPredicate(); rightPredicate = rightOuterJoinPushDownResult.getOuterJoinPredicate(); postJoinPredicate = rightOuterJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = rightOuterJoinPushDownResult.getJoinPredicate(); break; case FULL: leftPredicate = TRUE_LITERAL; rightPredicate = TRUE_LITERAL; postJoinPredicate = inheritedPredicate; newJoinPredicate = joinPredicate; break; default: throw new UnsupportedOperationException("Unsupported join type: " + node.getType()); } newJoinPredicate = simplifyExpression(newJoinPredicate); // Create identity projections for all existing symbols Assignments.Builder leftProjections = Assignments.builder(); leftProjections.putAll(node.getLeft() .getOutputSymbols().stream() .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); Assignments.Builder rightProjections = Assignments.builder(); rightProjections.putAll(node.getRight() .getOutputSymbols().stream() .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); // Create new projections for the new join clauses List<JoinNode.EquiJoinClause> equiJoinClauses = new ArrayList<>(); ImmutableList.Builder<Expression> joinFilterBuilder = ImmutableList.builder(); for (Expression conjunct : extractConjuncts(newJoinPredicate)) { if (joinEqualityExpression(conjunct, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols())) { ComparisonExpression equality = (ComparisonExpression) conjunct; boolean alignedComparison = node.getLeft().getOutputSymbols().containsAll(SymbolsExtractor.extractUnique(equality.getLeft())); Expression leftExpression = (alignedComparison) ? equality.getLeft() : equality.getRight(); Expression rightExpression = (alignedComparison) ? equality.getRight() : equality.getLeft(); Symbol leftSymbol = symbolForExpression(leftExpression); if (!node.getLeft().getOutputSymbols().contains(leftSymbol)) { leftProjections.put(leftSymbol, leftExpression); } Symbol rightSymbol = symbolForExpression(rightExpression); if (!node.getRight().getOutputSymbols().contains(rightSymbol)) { rightProjections.put(rightSymbol, rightExpression); } equiJoinClauses.add(new JoinNode.EquiJoinClause(leftSymbol, rightSymbol)); } else { joinFilterBuilder.add(conjunct); } } DynamicFiltersResult dynamicFiltersResult = createDynamicFilters(node, equiJoinClauses, session, idAllocator); Map<String, Symbol> dynamicFilters = dynamicFiltersResult.getDynamicFilters(); leftPredicate = combineConjuncts(metadata, leftPredicate, combineConjuncts(metadata, dynamicFiltersResult.getPredicates())); PlanNode leftSource; PlanNode rightSource; boolean equiJoinClausesUnmodified = ImmutableSet.copyOf(equiJoinClauses).equals(ImmutableSet.copyOf(node.getCriteria())); if (!equiJoinClausesUnmodified) { leftSource = context.rewrite(new ProjectNode(idAllocator.getNextId(), node.getLeft(), leftProjections.build()), leftPredicate); rightSource = context.rewrite(new ProjectNode(idAllocator.getNextId(), node.getRight(), rightProjections.build()), rightPredicate); } else { leftSource = context.rewrite(node.getLeft(), leftPredicate); rightSource = context.rewrite(node.getRight(), rightPredicate); } Optional<Expression> newJoinFilter = Optional.of(combineConjuncts(metadata, joinFilterBuilder.build())); if (newJoinFilter.get() == TRUE_LITERAL) { newJoinFilter = Optional.empty(); } if (node.getType() == INNER && newJoinFilter.isPresent() && equiJoinClauses.isEmpty()) { // if we do not have any equi conjunct we do not pushdown non-equality condition into // inner join, so we plan execution as nested-loops-join followed by filter instead // hash join. // todo: remove the code when we have support for filter function in nested loop join postJoinPredicate = combineConjuncts(metadata, postJoinPredicate, newJoinFilter.get()); newJoinFilter = Optional.empty(); } boolean filtersEquivalent = newJoinFilter.isPresent() == node.getFilter().isPresent() && (newJoinFilter.isEmpty() || areExpressionsEquivalent(newJoinFilter.get(), node.getFilter().get())); PlanNode output = node; if (leftSource != node.getLeft() || rightSource != node.getRight() || !filtersEquivalent || !dynamicFilters.equals(node.getDynamicFilters()) || !equiJoinClausesUnmodified) { leftSource = new ProjectNode(idAllocator.getNextId(), leftSource, leftProjections.build()); rightSource = new ProjectNode(idAllocator.getNextId(), rightSource, rightProjections.build()); output = new JoinNode( node.getId(), node.getType(), leftSource, rightSource, equiJoinClauses, leftSource.getOutputSymbols(), rightSource.getOutputSymbols(), newJoinFilter, node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), dynamicFilters, node.getReorderJoinStatsAndCost()); } if (!postJoinPredicate.equals(TRUE_LITERAL)) { output = new FilterNode(idAllocator.getNextId(), output, postJoinPredicate); } if (!node.getOutputSymbols().equals(output.getOutputSymbols())) { output = new ProjectNode(idAllocator.getNextId(), output, Assignments.identity(node.getOutputSymbols())); } return output; } private DynamicFiltersResult createDynamicFilters(JoinNode node, List<JoinNode.EquiJoinClause> equiJoinClauses, Session session, PlanNodeIdAllocator idAllocator) { Map<String, Symbol> dynamicFilters = ImmutableMap.of(); List<Expression> predicates = ImmutableList.of(); if (node.getType() == INNER && isEnableDynamicFiltering(session) && dynamicFiltering) { // New equiJoinClauses could potentially not contain symbols used in current dynamic filters. // Since we use PredicatePushdown to push dynamic filters themselves, // instead of separate ApplyDynamicFilters rule we derive dynamic filters within PredicatePushdown itself. // Even if equiJoinClauses.equals(node.getCriteria), current dynamic filters may not match equiJoinClauses ImmutableMap.Builder<String, Symbol> dynamicFiltersBuilder = ImmutableMap.builder(); ImmutableList.Builder<Expression> predicatesBuilder = ImmutableList.builder(); for (JoinNode.EquiJoinClause clause : equiJoinClauses) { Symbol probeSymbol = clause.getLeft(); Symbol buildSymbol = clause.getRight(); String id = "df_" + idAllocator.getNextId().toString(); predicatesBuilder.add(createDynamicFilterExpression(metadata, id, symbolAllocator.getTypes().get(probeSymbol), probeSymbol.toSymbolReference())); dynamicFiltersBuilder.put(id, buildSymbol); } dynamicFilters = dynamicFiltersBuilder.build(); predicates = predicatesBuilder.build(); } return new DynamicFiltersResult(dynamicFilters, predicates); } private static class DynamicFiltersResult { private final Map<String, Symbol> dynamicFilters; private final List<Expression> predicates; public DynamicFiltersResult(Map<String, Symbol> dynamicFilters, List<Expression> predicates) { this.dynamicFilters = dynamicFilters; this.predicates = predicates; } public Map<String, Symbol> getDynamicFilters() { return dynamicFilters; } public List<Expression> getPredicates() { return predicates; } } @Override public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); // See if we can rewrite left join in terms of a plain inner join if (node.getType() == SpatialJoinNode.Type.LEFT && canConvertOuterToInner(node.getRight().getOutputSymbols(), inheritedPredicate)) { node = new SpatialJoinNode(node.getId(), SpatialJoinNode.Type.INNER, node.getLeft(), node.getRight(), node.getOutputSymbols(), node.getFilter(), node.getLeftPartitionSymbol(), node.getRightPartitionSymbol(), node.getKdbTree()); } Expression leftEffectivePredicate = effectivePredicateExtractor.extract(session, node.getLeft(), types, typeAnalyzer); Expression rightEffectivePredicate = effectivePredicateExtractor.extract(session, node.getRight(), types, typeAnalyzer); Expression joinPredicate = node.getFilter(); Expression leftPredicate; Expression rightPredicate; Expression postJoinPredicate; Expression newJoinPredicate; switch (node.getType()) { case INNER: InnerJoinPushDownResult innerJoinPushDownResult = processInnerJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = innerJoinPushDownResult.getLeftPredicate(); rightPredicate = innerJoinPushDownResult.getRightPredicate(); postJoinPredicate = innerJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = innerJoinPushDownResult.getJoinPredicate(); break; case LEFT: OuterJoinPushDownResult leftOuterJoinPushDownResult = processLimitedOuterJoin( inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, node.getLeft().getOutputSymbols(), node.getRight().getOutputSymbols()); leftPredicate = leftOuterJoinPushDownResult.getOuterJoinPredicate(); rightPredicate = leftOuterJoinPushDownResult.getInnerJoinPredicate(); postJoinPredicate = leftOuterJoinPushDownResult.getPostJoinPredicate(); newJoinPredicate = leftOuterJoinPushDownResult.getJoinPredicate(); break; default: throw new IllegalArgumentException("Unsupported spatial join type: " + node.getType()); } newJoinPredicate = simplifyExpression(newJoinPredicate); verify(!newJoinPredicate.equals(BooleanLiteral.FALSE_LITERAL), "Spatial join predicate is missing"); PlanNode leftSource = context.rewrite(node.getLeft(), leftPredicate); PlanNode rightSource = context.rewrite(node.getRight(), rightPredicate); PlanNode output = node; if (leftSource != node.getLeft() || rightSource != node.getRight() || !areExpressionsEquivalent(newJoinPredicate, joinPredicate)) { // Create identity projections for all existing symbols Assignments.Builder leftProjections = Assignments.builder(); leftProjections.putAll(node.getLeft() .getOutputSymbols().stream() .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); Assignments.Builder rightProjections = Assignments.builder(); rightProjections.putAll(node.getRight() .getOutputSymbols().stream() .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); leftSource = new ProjectNode(idAllocator.getNextId(), leftSource, leftProjections.build()); rightSource = new ProjectNode(idAllocator.getNextId(), rightSource, rightProjections.build()); output = new SpatialJoinNode( node.getId(), node.getType(), leftSource, rightSource, node.getOutputSymbols(), newJoinPredicate, node.getLeftPartitionSymbol(), node.getRightPartitionSymbol(), node.getKdbTree()); } if (!postJoinPredicate.equals(TRUE_LITERAL)) { output = new FilterNode(idAllocator.getNextId(), output, postJoinPredicate); } return output; } private Symbol symbolForExpression(Expression expression) { if (expression instanceof SymbolReference) { return Symbol.from(expression); } return symbolAllocator.newSymbol(expression, typeAnalyzer.getType(session, symbolAllocator.getTypes(), expression)); } private OuterJoinPushDownResult processLimitedOuterJoin( Expression inheritedPredicate, Expression outerEffectivePredicate, Expression innerEffectivePredicate, Expression joinPredicate, Collection<Symbol> outerSymbols, Collection<Symbol> innerSymbols) { checkArgument(outerSymbols.containsAll(SymbolsExtractor.extractUnique(outerEffectivePredicate)), "outerEffectivePredicate must only contain symbols from outerSymbols"); checkArgument(innerSymbols.containsAll(SymbolsExtractor.extractUnique(innerEffectivePredicate)), "innerEffectivePredicate must only contain symbols from innerSymbols"); ImmutableList.Builder<Expression> outerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> innerPushdownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> postJoinConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> joinConjuncts = ImmutableList.builder(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(postJoinConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); outerEffectivePredicate = filterDeterministicConjuncts(metadata, outerEffectivePredicate); innerEffectivePredicate = filterDeterministicConjuncts(metadata, innerEffectivePredicate); extractConjuncts(joinPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(joinConjuncts::add); joinPredicate = filterDeterministicConjuncts(metadata, joinPredicate); // Generate equality inferences EqualityInference inheritedInference = EqualityInference.newInstance(metadata, inheritedPredicate); EqualityInference outerInference = EqualityInference.newInstance(metadata, inheritedPredicate, outerEffectivePredicate); Set<Symbol> innerScope = ImmutableSet.copyOf(innerSymbols); Set<Symbol> outerScope = ImmutableSet.copyOf(outerSymbols); EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(outerScope); Expression outerOnlyInheritedEqualities = combineConjuncts(metadata, equalityPartition.getScopeEqualities()); EqualityInference potentialNullSymbolInference = EqualityInference.newInstance(metadata, outerOnlyInheritedEqualities, outerEffectivePredicate, innerEffectivePredicate, joinPredicate); // Push outer and join equalities into the inner side. For example: // SELECT * FROM nation LEFT OUTER JOIN region ON nation.regionkey = region.regionkey and nation.name = region.name WHERE nation.name = 'blah' EqualityInference potentialNullSymbolInferenceWithoutInnerInferred = EqualityInference.newInstance(metadata, outerOnlyInheritedEqualities, outerEffectivePredicate, joinPredicate); innerPushdownConjuncts.addAll(potentialNullSymbolInferenceWithoutInnerInferred.generateEqualitiesPartitionedBy(innerScope).getScopeEqualities()); // TODO: we can further improve simplifying the equalities by considering other relationships from the outer side EqualityInference.EqualityPartition joinEqualityPartition = EqualityInference.newInstance(metadata, joinPredicate).generateEqualitiesPartitionedBy(innerScope); innerPushdownConjuncts.addAll(joinEqualityPartition.getScopeEqualities()); joinConjuncts.addAll(joinEqualityPartition.getScopeComplementEqualities()) .addAll(joinEqualityPartition.getScopeStraddlingEqualities()); // Add the equalities from the inferences back in outerPushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); // See if we can push inherited predicates down for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression outerRewritten = outerInference.rewrite(conjunct, outerScope); if (outerRewritten != null) { outerPushdownConjuncts.add(outerRewritten); // A conjunct can only be pushed down into an inner side if it can be rewritten in terms of the outer side Expression innerRewritten = potentialNullSymbolInference.rewrite(outerRewritten, innerScope); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } } else { postJoinConjuncts.add(conjunct); } } // See if we can push down any outer effective predicates to the inner side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, outerEffectivePredicate)) { Expression rewritten = potentialNullSymbolInference.rewrite(conjunct, innerScope); if (rewritten != null) { innerPushdownConjuncts.add(rewritten); } } // See if we can push down join predicates to the inner side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, joinPredicate)) { Expression innerRewritten = potentialNullSymbolInference.rewrite(conjunct, innerScope); if (innerRewritten != null) { innerPushdownConjuncts.add(innerRewritten); } else { joinConjuncts.add(conjunct); } } return new OuterJoinPushDownResult(combineConjuncts(metadata, outerPushdownConjuncts.build()), combineConjuncts(metadata, innerPushdownConjuncts.build()), combineConjuncts(metadata, joinConjuncts.build()), combineConjuncts(metadata, postJoinConjuncts.build())); } private static class OuterJoinPushDownResult { private final Expression outerJoinPredicate; private final Expression innerJoinPredicate; private final Expression joinPredicate; private final Expression postJoinPredicate; private OuterJoinPushDownResult(Expression outerJoinPredicate, Expression innerJoinPredicate, Expression joinPredicate, Expression postJoinPredicate) { this.outerJoinPredicate = outerJoinPredicate; this.innerJoinPredicate = innerJoinPredicate; this.joinPredicate = joinPredicate; this.postJoinPredicate = postJoinPredicate; } private Expression getOuterJoinPredicate() { return outerJoinPredicate; } private Expression getInnerJoinPredicate() { return innerJoinPredicate; } public Expression getJoinPredicate() { return joinPredicate; } private Expression getPostJoinPredicate() { return postJoinPredicate; } } private InnerJoinPushDownResult processInnerJoin( Expression inheritedPredicate, Expression leftEffectivePredicate, Expression rightEffectivePredicate, Expression joinPredicate, Collection<Symbol> leftSymbols, Collection<Symbol> rightSymbols) { checkArgument(leftSymbols.containsAll(SymbolsExtractor.extractUnique(leftEffectivePredicate)), "leftEffectivePredicate must only contain symbols from leftSymbols"); checkArgument(rightSymbols.containsAll(SymbolsExtractor.extractUnique(rightEffectivePredicate)), "rightEffectivePredicate must only contain symbols from rightSymbols"); ImmutableList.Builder<Expression> leftPushDownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> rightPushDownConjuncts = ImmutableList.builder(); ImmutableList.Builder<Expression> joinConjuncts = ImmutableList.builder(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(deterministic -> !isDeterministic(deterministic, metadata)) .forEach(joinConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); extractConjuncts(joinPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(joinConjuncts::add); joinPredicate = filterDeterministicConjuncts(metadata, joinPredicate); leftEffectivePredicate = filterDeterministicConjuncts(metadata, leftEffectivePredicate); rightEffectivePredicate = filterDeterministicConjuncts(metadata, rightEffectivePredicate); ImmutableSet<Symbol> leftScope = ImmutableSet.copyOf(leftSymbols); ImmutableSet<Symbol> rightScope = ImmutableSet.copyOf(rightSymbols); // Attempt to simplify the effective left/right predicates with the predicate we're pushing down // This, effectively, inlines any constants derived from such predicate EqualityInference predicateInference = EqualityInference.newInstance(metadata, inheritedPredicate); Expression simplifiedLeftEffectivePredicate = predicateInference.rewrite(leftEffectivePredicate, leftScope); Expression simplifiedRightEffectivePredicate = predicateInference.rewrite(rightEffectivePredicate, rightScope); // simplify predicate based on known equalities guaranteed by the left/right side EqualityInference assertions = EqualityInference.newInstance(metadata, leftEffectivePredicate, rightEffectivePredicate); inheritedPredicate = assertions.rewrite(inheritedPredicate, Sets.union(leftScope, rightScope)); // Generate equality inferences EqualityInference allInference = EqualityInference.newInstance(metadata, inheritedPredicate, leftEffectivePredicate, rightEffectivePredicate, joinPredicate, simplifiedLeftEffectivePredicate, simplifiedRightEffectivePredicate); EqualityInference allInferenceWithoutLeftInferred = EqualityInference.newInstance(metadata, inheritedPredicate, rightEffectivePredicate, joinPredicate, simplifiedRightEffectivePredicate); EqualityInference allInferenceWithoutRightInferred = EqualityInference.newInstance(metadata, inheritedPredicate, leftEffectivePredicate, joinPredicate, simplifiedLeftEffectivePredicate); // Add equalities from the inference back in leftPushDownConjuncts.addAll(allInferenceWithoutLeftInferred.generateEqualitiesPartitionedBy(leftScope).getScopeEqualities()); rightPushDownConjuncts.addAll(allInferenceWithoutRightInferred.generateEqualitiesPartitionedBy(rightScope).getScopeEqualities()); joinConjuncts.addAll(allInference.generateEqualitiesPartitionedBy(leftScope).getScopeStraddlingEqualities()); // scope straddling equalities get dropped in as part of the join predicate // Sort through conjuncts in inheritedPredicate that were not used for inference for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression leftRewrittenConjunct = allInference.rewrite(conjunct, leftScope); if (leftRewrittenConjunct != null) { leftPushDownConjuncts.add(leftRewrittenConjunct); } Expression rightRewrittenConjunct = allInference.rewrite(conjunct, rightScope); if (rightRewrittenConjunct != null) { rightPushDownConjuncts.add(rightRewrittenConjunct); } // Drop predicate after join only if unable to push down to either side if (leftRewrittenConjunct == null && rightRewrittenConjunct == null) { joinConjuncts.add(conjunct); } } // See if we can push the right effective predicate to the left side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, simplifiedRightEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, leftScope); if (rewritten != null) { leftPushDownConjuncts.add(rewritten); } } // See if we can push the left effective predicate to the right side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, simplifiedLeftEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, rightScope); if (rewritten != null) { rightPushDownConjuncts.add(rewritten); } } // See if we can push any parts of the join predicates to either side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, joinPredicate)) { Expression leftRewritten = allInference.rewrite(conjunct, leftScope); if (leftRewritten != null) { leftPushDownConjuncts.add(leftRewritten); } Expression rightRewritten = allInference.rewrite(conjunct, rightScope); if (rightRewritten != null) { rightPushDownConjuncts.add(rightRewritten); } if (leftRewritten == null && rightRewritten == null) { joinConjuncts.add(conjunct); } } return new InnerJoinPushDownResult( combineConjuncts(metadata, leftPushDownConjuncts.build()), combineConjuncts(metadata, rightPushDownConjuncts.build()), combineConjuncts(metadata, joinConjuncts.build()), TRUE_LITERAL); } private static class InnerJoinPushDownResult { private final Expression leftPredicate; private final Expression rightPredicate; private final Expression joinPredicate; private final Expression postJoinPredicate; private InnerJoinPushDownResult(Expression leftPredicate, Expression rightPredicate, Expression joinPredicate, Expression postJoinPredicate) { this.leftPredicate = leftPredicate; this.rightPredicate = rightPredicate; this.joinPredicate = joinPredicate; this.postJoinPredicate = postJoinPredicate; } private Expression getLeftPredicate() { return leftPredicate; } private Expression getRightPredicate() { return rightPredicate; } private Expression getJoinPredicate() { return joinPredicate; } private Expression getPostJoinPredicate() { return postJoinPredicate; } } private Expression extractJoinPredicate(JoinNode joinNode) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (JoinNode.EquiJoinClause equiJoinClause : joinNode.getCriteria()) { builder.add(equiJoinClause.toExpression()); } joinNode.getFilter().ifPresent(builder::add); return combineConjuncts(metadata, builder.build()); } private JoinNode tryNormalizeToOuterToInnerJoin(JoinNode node, Expression inheritedPredicate) { checkArgument(EnumSet.of(INNER, RIGHT, LEFT, FULL).contains(node.getType()), "Unsupported join type: %s", node.getType()); if (node.getType() == JoinNode.Type.INNER) { return node; } if (node.getType() == JoinNode.Type.FULL) { boolean canConvertToLeftJoin = canConvertOuterToInner(node.getLeft().getOutputSymbols(), inheritedPredicate); boolean canConvertToRightJoin = canConvertOuterToInner(node.getRight().getOutputSymbols(), inheritedPredicate); if (!canConvertToLeftJoin && !canConvertToRightJoin) { return node; } if (canConvertToLeftJoin && canConvertToRightJoin) { return new JoinNode( node.getId(), INNER, node.getLeft(), node.getRight(), node.getCriteria(), node.getLeftOutputSymbols(), node.getRightOutputSymbols(), node.getFilter(), node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), node.getDynamicFilters(), node.getReorderJoinStatsAndCost()); } else { return new JoinNode( node.getId(), canConvertToLeftJoin ? LEFT : RIGHT, node.getLeft(), node.getRight(), node.getCriteria(), node.getLeftOutputSymbols(), node.getRightOutputSymbols(), node.getFilter(), node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), node.getDynamicFilters(), node.getReorderJoinStatsAndCost()); } } if (node.getType() == JoinNode.Type.LEFT && !canConvertOuterToInner(node.getRight().getOutputSymbols(), inheritedPredicate) || node.getType() == JoinNode.Type.RIGHT && !canConvertOuterToInner(node.getLeft().getOutputSymbols(), inheritedPredicate)) { return node; } return new JoinNode( node.getId(), JoinNode.Type.INNER, node.getLeft(), node.getRight(), node.getCriteria(), node.getLeftOutputSymbols(), node.getRightOutputSymbols(), node.getFilter(), node.getLeftHashSymbol(), node.getRightHashSymbol(), node.getDistributionType(), node.isSpillable(), node.getDynamicFilters(), node.getReorderJoinStatsAndCost()); } private boolean canConvertOuterToInner(List<Symbol> innerSymbolsForOuterJoin, Expression inheritedPredicate) { Set<Symbol> innerSymbols = ImmutableSet.copyOf(innerSymbolsForOuterJoin); for (Expression conjunct : extractConjuncts(inheritedPredicate)) { if (isDeterministic(conjunct, metadata)) { // Ignore a conjunct for this test if we cannot deterministically get responses from it Object response = nullInputEvaluator(innerSymbols, conjunct); if (response == null || response instanceof NullLiteral || Boolean.FALSE.equals(response)) { // If there is a single conjunct that returns FALSE or NULL given all NULL inputs for the inner side symbols of an outer join // then this conjunct removes all effects of the outer join, and effectively turns this into an equivalent of an inner join. // So, let's just rewrite this join as an INNER join return true; } } } return false; } // Temporary implementation for joins because the SimplifyExpressions optimizers cannot run properly on join clauses private Expression simplifyExpression(Expression expression) { Map<NodeRef<Expression>, Type> expressionTypes = typeAnalyzer.getTypes(session, symbolAllocator.getTypes(), expression); ExpressionInterpreter optimizer = ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes); return literalEncoder.toExpression(optimizer.optimize(NoOpSymbolResolver.INSTANCE), expressionTypes.get(NodeRef.of(expression))); } private boolean areExpressionsEquivalent(Expression leftExpression, Expression rightExpression) { return expressionEquivalence.areExpressionsEquivalent(session, leftExpression, rightExpression, types); } /** * Evaluates an expression's response to binding the specified input symbols to NULL */ private Object nullInputEvaluator(final Collection<Symbol> nullSymbols, Expression expression) { Map<NodeRef<Expression>, Type> expressionTypes = typeAnalyzer.getTypes(session, symbolAllocator.getTypes(), expression); return ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes) .optimize(symbol -> nullSymbols.contains(symbol) ? null : symbol.toSymbolReference()); } private boolean joinEqualityExpression(Expression expression, Collection<Symbol> leftSymbols, Collection<Symbol> rightSymbols) { // At this point in time, our join predicates need to be deterministic if (expression instanceof ComparisonExpression && isDeterministic(expression, metadata)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getOperator() == ComparisonExpression.Operator.EQUAL) { Set<Symbol> symbols1 = SymbolsExtractor.extractUnique(comparison.getLeft()); Set<Symbol> symbols2 = SymbolsExtractor.extractUnique(comparison.getRight()); if (symbols1.isEmpty() || symbols2.isEmpty()) { return false; } return (leftSymbols.containsAll(symbols1) && rightSymbols.containsAll(symbols2)) || (rightSymbols.containsAll(symbols1) && leftSymbols.containsAll(symbols2)); } } return false; } @Override public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); if (!extractConjuncts(inheritedPredicate).contains(node.getSemiJoinOutput().toSymbolReference())) { return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); } private PlanNode visitNonFilteringSemiJoin(SemiJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); List<Expression> sourceConjuncts = new ArrayList<>(); List<Expression> postJoinConjuncts = new ArrayList<>(); // TODO: see if there are predicates that can be inferred from the semi join output PlanNode rewrittenFilteringSource = context.defaultRewrite(node.getFilteringSource(), TRUE_LITERAL); // Push inheritedPredicates down to the source if they don't involve the semi join output ImmutableSet<Symbol> sourceScope = ImmutableSet.copyOf(node.getSource().getOutputSymbols()); EqualityInference inheritedInference = EqualityInference.newInstance(metadata, inheritedPredicate); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression rewrittenConjunct = inheritedInference.rewrite(conjunct, sourceScope); // Since each source row is reflected exactly once in the output, ok to push non-deterministic predicates down if (rewrittenConjunct != null) { sourceConjuncts.add(rewrittenConjunct); } else { postJoinConjuncts.add(conjunct); } } // Add the inherited equality predicates back in EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(sourceScope); sourceConjuncts.addAll(equalityPartition.getScopeEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, sourceConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource() || rewrittenFilteringSource != node.getFilteringSource()) { output = new SemiJoinNode(node.getId(), rewrittenSource, rewrittenFilteringSource, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput(), node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol(), node.getDistributionType()); } if (!postJoinConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postJoinConjuncts)); } return output; } private PlanNode visitFilteringSemiJoin(SemiJoinNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); Expression deterministicInheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); Expression sourceEffectivePredicate = filterDeterministicConjuncts(metadata, effectivePredicateExtractor.extract(session, node.getSource(), types, typeAnalyzer)); Expression filteringSourceEffectivePredicate = filterDeterministicConjuncts(metadata, effectivePredicateExtractor.extract(session, node.getFilteringSource(), types, typeAnalyzer)); Expression joinExpression = new ComparisonExpression( ComparisonExpression.Operator.EQUAL, node.getSourceJoinSymbol().toSymbolReference(), node.getFilteringSourceJoinSymbol().toSymbolReference()); List<Symbol> sourceSymbols = node.getSource().getOutputSymbols(); List<Symbol> filteringSourceSymbols = node.getFilteringSource().getOutputSymbols(); List<Expression> sourceConjuncts = new ArrayList<>(); List<Expression> filteringSourceConjuncts = new ArrayList<>(); List<Expression> postJoinConjuncts = new ArrayList<>(); // Generate equality inferences EqualityInference allInference = EqualityInference.newInstance(metadata, deterministicInheritedPredicate, sourceEffectivePredicate, filteringSourceEffectivePredicate, joinExpression); EqualityInference allInferenceWithoutSourceInferred = EqualityInference.newInstance(metadata, deterministicInheritedPredicate, filteringSourceEffectivePredicate, joinExpression); EqualityInference allInferenceWithoutFilteringSourceInferred = EqualityInference.newInstance(metadata, deterministicInheritedPredicate, sourceEffectivePredicate, joinExpression); // Push inheritedPredicates down to the source if they don't involve the semi join output Set<Symbol> sourceScope = ImmutableSet.copyOf(sourceSymbols); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression rewrittenConjunct = allInference.rewrite(conjunct, sourceScope); // Since each source row is reflected exactly once in the output, ok to push non-deterministic predicates down if (rewrittenConjunct != null) { sourceConjuncts.add(rewrittenConjunct); } else { postJoinConjuncts.add(conjunct); } } // Push inheritedPredicates down to the filtering source if possible Set<Symbol> filterScope = ImmutableSet.copyOf(filteringSourceSymbols); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, deterministicInheritedPredicate)) { Expression rewrittenConjunct = allInference.rewrite(conjunct, filterScope); // We cannot push non-deterministic predicates to filtering side. Each filtering side row have to be // logically reevaluated for each source row. if (rewrittenConjunct != null) { filteringSourceConjuncts.add(rewrittenConjunct); } } // move effective predicate conjuncts source <-> filter // See if we can push the filtering source effective predicate to the source side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, filteringSourceEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, sourceScope); if (rewritten != null) { sourceConjuncts.add(rewritten); } } // See if we can push the source effective predicate to the filtering soruce side for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, sourceEffectivePredicate)) { Expression rewritten = allInference.rewrite(conjunct, filterScope); if (rewritten != null) { filteringSourceConjuncts.add(rewritten); } } // Add equalities from the inference back in sourceConjuncts.addAll(allInferenceWithoutSourceInferred.generateEqualitiesPartitionedBy(sourceScope).getScopeEqualities()); filteringSourceConjuncts.addAll(allInferenceWithoutFilteringSourceInferred.generateEqualitiesPartitionedBy(filterScope).getScopeEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, sourceConjuncts)); PlanNode rewrittenFilteringSource = context.rewrite(node.getFilteringSource(), combineConjuncts(metadata, filteringSourceConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource() || rewrittenFilteringSource != node.getFilteringSource()) { output = new SemiJoinNode( node.getId(), rewrittenSource, rewrittenFilteringSource, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput(), node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol(), node.getDistributionType()); } if (!postJoinConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postJoinConjuncts)); } return output; } @Override public PlanNode visitAggregation(AggregationNode node, RewriteContext<Expression> context) { if (node.hasEmptyGroupingSet()) { // TODO: in case of grouping sets, we should be able to push the filters over grouping keys below the aggregation // and also preserve the filter above the aggregation if it has an empty grouping set return visitPlan(node, context); } Expression inheritedPredicate = context.get(); EqualityInference equalityInference = EqualityInference.newInstance(metadata, inheritedPredicate); List<Expression> pushdownConjuncts = new ArrayList<>(); List<Expression> postAggregationConjuncts = new ArrayList<>(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(postAggregationConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); // Sort non-equality predicates by those that can be pushed down and those that cannot Set<Symbol> groupingKeys = ImmutableSet.copyOf(node.getGroupingKeys()); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { if (node.getGroupIdSymbol().isPresent() && SymbolsExtractor.extractUnique(conjunct).contains(node.getGroupIdSymbol().get())) { // aggregation operator synthesizes outputs for group ids corresponding to the global grouping set (i.e., ()), so we // need to preserve any predicates that evaluate the group id to run after the aggregation // TODO: we should be able to infer if conditions on grouping() correspond to global grouping sets to determine whether // we need to do this for each specific case postAggregationConjuncts.add(conjunct); continue; } Expression rewrittenConjunct = equalityInference.rewrite(conjunct, groupingKeys); if (rewrittenConjunct != null) { pushdownConjuncts.add(rewrittenConjunct); } else { postAggregationConjuncts.add(conjunct); } } // Add the equality predicates back in EqualityInference.EqualityPartition equalityPartition = equalityInference.generateEqualitiesPartitionedBy(groupingKeys); pushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postAggregationConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postAggregationConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, pushdownConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource()) { output = new AggregationNode(node.getId(), rewrittenSource, node.getAggregations(), node.getGroupingSets(), ImmutableList.of(), node.getStep(), node.getHashSymbol(), node.getGroupIdSymbol()); } if (!postAggregationConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postAggregationConjuncts)); } return output; } @Override public PlanNode visitUnnest(UnnestNode node, RewriteContext<Expression> context) { Expression inheritedPredicate = context.get(); if (node.getJoinType() == RIGHT || node.getJoinType() == FULL) { return new FilterNode(idAllocator.getNextId(), node, inheritedPredicate); } //TODO for LEFT or INNER join type, push down UnnestNode's filter on replicate symbols EqualityInference equalityInference = EqualityInference.newInstance(metadata, inheritedPredicate); List<Expression> pushdownConjuncts = new ArrayList<>(); List<Expression> postUnnestConjuncts = new ArrayList<>(); // Strip out non-deterministic conjuncts extractConjuncts(inheritedPredicate).stream() .filter(expression -> !isDeterministic(expression, metadata)) .forEach(postUnnestConjuncts::add); inheritedPredicate = filterDeterministicConjuncts(metadata, inheritedPredicate); // Sort non-equality predicates by those that can be pushed down and those that cannot Set<Symbol> replicatedSymbols = ImmutableSet.copyOf(node.getReplicateSymbols()); for (Expression conjunct : EqualityInference.nonInferrableConjuncts(metadata, inheritedPredicate)) { Expression rewrittenConjunct = equalityInference.rewrite(conjunct, replicatedSymbols); if (rewrittenConjunct != null) { pushdownConjuncts.add(rewrittenConjunct); } else { postUnnestConjuncts.add(conjunct); } } // Add the equality predicates back in EqualityInference.EqualityPartition equalityPartition = equalityInference.generateEqualitiesPartitionedBy(replicatedSymbols); pushdownConjuncts.addAll(equalityPartition.getScopeEqualities()); postUnnestConjuncts.addAll(equalityPartition.getScopeComplementEqualities()); postUnnestConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities()); PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(metadata, pushdownConjuncts)); PlanNode output = node; if (rewrittenSource != node.getSource()) { output = new UnnestNode(node.getId(), rewrittenSource, node.getReplicateSymbols(), node.getMappings(), node.getOrdinalitySymbol(), node.getJoinType(), node.getFilter()); } if (!postUnnestConjuncts.isEmpty()) { output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(metadata, postUnnestConjuncts)); } return output; } @Override public PlanNode visitSample(SampleNode node, RewriteContext<Expression> context) { return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitTableScan(TableScanNode node, RewriteContext<Expression> context) { Expression predicate = simplifyExpression(context.get()); if (!TRUE_LITERAL.equals(predicate)) { return new FilterNode(idAllocator.getNextId(), node, predicate); } return node; } @Override public PlanNode visitAssignUniqueId(AssignUniqueId node, RewriteContext<Expression> context) { Set<Symbol> predicateSymbols = SymbolsExtractor.extractUnique(context.get()); checkState(!predicateSymbols.contains(node.getIdColumn()), "UniqueId in predicate is not yet supported"); return context.defaultRewrite(node, context.get()); } } }
Use ImmutableMap collector in Predicte Push Down
presto-main/src/main/java/io/prestosql/sql/planner/optimizations/PredicatePushDown.java
Use ImmutableMap collector in Predicte Push Down
<ide><path>resto-main/src/main/java/io/prestosql/sql/planner/optimizations/PredicatePushDown.java <ide> import static com.google.common.base.Preconditions.checkArgument; <ide> import static com.google.common.base.Preconditions.checkState; <ide> import static com.google.common.base.Verify.verify; <add>import static com.google.common.collect.ImmutableMap.toImmutableMap; <ide> import static io.prestosql.SystemSessionProperties.isEnableDynamicFiltering; <ide> import static io.prestosql.SystemSessionProperties.isPredicatePushdownUseTableProperties; <ide> import static io.prestosql.sql.DynamicFilters.createDynamicFilterExpression; <ide> { <ide> Map<Symbol, SymbolReference> commonGroupingSymbolMapping = node.getGroupingColumns().entrySet().stream() <ide> .filter(entry -> node.getCommonGroupingColumns().contains(entry.getKey())) <del> .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference())); <add> .collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference())); <ide> <ide> Predicate<Expression> pushdownEligiblePredicate = conjunct -> commonGroupingSymbolMapping.keySet().containsAll(SymbolsExtractor.extractUnique(conjunct)); <ide> <ide> Assignments.Builder leftProjections = Assignments.builder(); <ide> leftProjections.putAll(node.getLeft() <ide> .getOutputSymbols().stream() <del> .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); <add> .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); <ide> <ide> Assignments.Builder rightProjections = Assignments.builder(); <ide> rightProjections.putAll(node.getRight() <ide> .getOutputSymbols().stream() <del> .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); <add> .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); <ide> <ide> // Create new projections for the new join clauses <ide> List<JoinNode.EquiJoinClause> equiJoinClauses = new ArrayList<>(); <ide> Assignments.Builder leftProjections = Assignments.builder(); <ide> leftProjections.putAll(node.getLeft() <ide> .getOutputSymbols().stream() <del> .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); <add> .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); <ide> <ide> Assignments.Builder rightProjections = Assignments.builder(); <ide> rightProjections.putAll(node.getRight() <ide> .getOutputSymbols().stream() <del> .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference))); <add> .collect(toImmutableMap(key -> key, Symbol::toSymbolReference))); <ide> <ide> leftSource = new ProjectNode(idAllocator.getNextId(), leftSource, leftProjections.build()); <ide> rightSource = new ProjectNode(idAllocator.getNextId(), rightSource, rightProjections.build());
JavaScript
mit
55c5c5d8e053b0db7b8bc2a4d181f7d4ca82e20b
0
jasnell/citgm
'use strict'; var test = require('tap').test; var rewire = require('rewire'); var spawn = rewire('../lib/spawn'); test('spawn:', function (t) { var child = spawn('echo', ['Hello world.']); var error = ''; var message = ''; child.stdout.on('data', function (chunk) { message += chunk; }); child.on('close', function () { t.equals(message, 'Hello world.\n', 'we should receive "Hello world." on stdout'); t.equals(error, '', 'there should be no data on stderr'); t.end(); }); child.on('error', t.error); }); test('spawn: windows mock', function (t) { var child = spawn.__get__('child'); var sp = child.spawn; var platform = process.platform; Object.defineProperty(process, 'platform', { value: 'win32' }); child.spawn = function (cmd, args, options) { return { cmd: cmd, args: args, options: options }; }; var result = spawn('echo', ['Hello world.']); var expected = { cmd: 'cmd', args: [ '/c', 'echo', 'Hello world.' ], options: undefined }; child.spawn = sp; Object.defineProperty(process, 'platform', { value: platform }); t.deepEqual(result, expected, 'we should have the expected options for win32'); t.end(); });
test/test-spawn.js
'use strict'; var test = require('tap').test; var spawn = require('../lib/spawn'); test('spawn:', function (t) { var child = spawn('echo', ['Hello world.']); var error = ''; var message = ''; child.stdout.on('data', function (chunk) { message += chunk; }); child.on('close', function () { t.equals(message, 'Hello world.\n', 'we should receive "Hello world." on stdout'); t.equals(error, '', 'there should be no data on stderr'); t.end(); }); child.on('error', t.error); });
test: 100% coverage on lib/spawn
test/test-spawn.js
test: 100% coverage on lib/spawn
<ide><path>est/test-spawn.js <ide> 'use strict'; <ide> <ide> var test = require('tap').test; <add>var rewire = require('rewire'); <ide> <del>var spawn = require('../lib/spawn'); <add>var spawn = rewire('../lib/spawn'); <ide> <ide> test('spawn:', function (t) { <ide> var child = spawn('echo', ['Hello world.']); <del> <add> <ide> var error = ''; <ide> var message = ''; <del> <add> <ide> child.stdout.on('data', function (chunk) { <ide> message += chunk; <ide> }); <ide> <ide> child.on('error', t.error); <ide> }); <add> <add>test('spawn: windows mock', function (t) { <add> var child = spawn.__get__('child'); <add> var sp = child.spawn; <add> var platform = process.platform; <add> Object.defineProperty(process, 'platform', { <add> value: 'win32' <add> }); <add> <add> child.spawn = function (cmd, args, options) { <add> return { <add> cmd: cmd, <add> args: args, <add> options: options <add> }; <add> }; <add> <add> var result = spawn('echo', ['Hello world.']); <add> var expected = { <add> cmd: 'cmd', <add> args: [ <add> '/c', <add> 'echo', <add> 'Hello world.' <add> ], <add> options: undefined <add> }; <add> <add> child.spawn = sp; <add> Object.defineProperty(process, 'platform', { <add> value: platform <add> }); <add> <add> t.deepEqual(result, expected, 'we should have the expected options for win32'); <add> t.end(); <add>});
Java
agpl-3.0
5da54a8ccee6e3af64f1151a7593a9d4a13f27f1
0
rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat
package roart.indicator.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.math3.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.category.AbstractCategory; import roart.common.config.MyMyConfig; import roart.common.pipeline.PipelineConstants; import roart.indicator.AbstractIndicator; import roart.indicator.impl.IndicatorMACD; import roart.indicator.impl.IndicatorRSI; import roart.common.constants.CategoryConstants; import roart.common.constants.Constants; import roart.model.StockItem; import roart.pipeline.Pipeline; import roart.pipeline.data.ExtraData; import roart.pipeline.impl.ExtraReader; import roart.model.data.MarketData; import roart.model.data.PeriodData; import roart.stockutil.StockUtil; import roart.talib.util.TaUtil; public class IndicatorUtils { protected static Logger log = LoggerFactory.getLogger(IndicatorUtils.class); /** * * Get an array with two arrays * First a map from day to related macd map from id to values * Second a map from day to all macd values * * @param conf Main config, not evolution * @param objectMap map from stock id to macd map * @param listMap map from stock id to values * @param tu * @return * @throws Exception */ @Deprecated public static Object[] getDayMomMap(MyMyConfig conf, Map<String, Object[]> objectMap, Map<String, Double[]> listMap, TaUtil tu) throws Exception { Object[] retobj = new Object[2]; Map<Integer, Map<String, Double[]>> dayMomMap = new HashMap<>(); Map<Integer, List<Double>[]> dayMacdsMap = new HashMap<>(); List<Double> macdLists[] = new ArrayList[4]; List<Double> macdMinMax[] = new ArrayList[4]; for (int tmpj = 0; tmpj < 4; tmpj ++) { macdLists[tmpj] = new ArrayList<>(); macdMinMax[tmpj] = new ArrayList<>(); } for (int j = conf.getTestIndicatorRecommenderComplexFutureDays(); j < conf.getTableDays(); j += conf.getTestIndicatorRecommenderComplexIntervalDays()) { Map<String, Double[]> momMap = new HashMap<>(); for (String id : listMap.keySet()) { Object[] objs = objectMap.get(id); Double[] momentum = tu.getMomAndDelta(conf.getMACDDeltaDays(), conf.getMACDHistogramDeltaDays(), objs, j); if (momentum != null) { momMap.put(id, momentum); IndicatorUtils.addToLists(macdLists, momentum); } } dayMomMap.put(j, momMap); dayMacdsMap.put(j, macdLists); } macdMinMax[0].add(Collections.min(macdLists[0])); macdMinMax[0].add(Collections.max(macdLists[0])); macdMinMax[1].add(Collections.min(macdLists[1])); macdMinMax[1].add(Collections.max(macdLists[1])); retobj[0] = dayMomMap; retobj[1] = macdMinMax; return retobj; } @Deprecated public static Object[] getDayRsiMap(MyMyConfig conf, Map<String, Object[]> objectMap, Map<String, Double[]> listMap, TaUtil tu) throws Exception { Object[] retobj = new Object[2]; Map<Integer, Map<String, Double[]>> dayRsiMap = new HashMap<>(); List<Double> rsiLists[] = new ArrayList[2]; List<Double> rsiMinMax[] = new ArrayList[2]; for (int tmpj = 0; tmpj < 2; tmpj ++) { rsiLists[tmpj] = new ArrayList<>(); rsiMinMax[tmpj] = new ArrayList<>(); } for (int j = conf.getTestIndicatorRecommenderComplexFutureDays(); j < conf.getTableDays(); j += conf.getTestIndicatorRecommenderComplexIntervalDays()) { Map<String, Double[]> rsiMap = new HashMap<>(); for (String id : listMap.keySet()) { Object[] objs = objectMap.get(id); Double[] rsi = tu.getRsiAndDelta(conf.getRSIDeltaDays(), objs, j); if (rsi != null) { rsiMap.put(id, rsi); IndicatorUtils.addToLists(rsiLists, rsi); } } dayRsiMap.put(j, rsiMap); } rsiMinMax[0].add(Collections.min(rsiLists[0])); rsiMinMax[0].add(Collections.max(rsiLists[0])); rsiMinMax[1].add(Collections.min(rsiLists[1])); rsiMinMax[1].add(Collections.max(rsiLists[1])); retobj[0] = dayRsiMap; retobj[1] = rsiMinMax; return retobj; } @Deprecated public static Object[] getDayMomRsiMap(MyMyConfig conf, Map<String, Object[]> objectMacdMap, Map<String, Double[]> listMacdMap, Map<String, Object[]> objectRsiMap, Map<String, Double[]> listRsiMap, TaUtil tu) throws Exception { Object[] retobj = new Object[2]; Map<Integer, Map<String, Double[]>> dayMomRsiMap = new HashMap<>(); List<Double>[] macdrsiLists = new ArrayList[6]; List<Double>[] macdrsiMinMax = new ArrayList[6]; for (int tmpj = 0; tmpj < 4 + 2; tmpj ++) { macdrsiLists[tmpj] = new ArrayList<>(); macdrsiMinMax[tmpj] = new ArrayList<>(); } for (int j = conf.getTestIndicatorRecommenderComplexFutureDays(); j < conf.getTableDays(); j += conf.getTestIndicatorRecommenderComplexIntervalDays()) { Map<String, Double[]> momrsiMap = new HashMap<>(); for (String id : listMacdMap.keySet()) { Object[] objsMacd = objectMacdMap.get(id); Object[] objsRSI = objectRsiMap.get(id); Double[] momentum = tu.getMomAndDelta(conf.getMACDDeltaDays(), conf.getMACDHistogramDeltaDays(), objsMacd, j); Double[] rsi = tu.getRsiAndDelta(conf.getRSIDeltaDays(), objsRSI, j); if (momentum != null) { Double[] momrsi = ArrayUtils.addAll(momentum, rsi); momrsiMap.put(id, momrsi); IndicatorUtils.addToLists(macdrsiLists, momrsi); } } dayMomRsiMap.put(j, momrsiMap); } for (int i = 0; i < 4 + 2; i++) { macdrsiMinMax[i].add(Collections.min(macdrsiLists[i])); macdrsiMinMax[i].add(Collections.max(macdrsiLists[i])); } retobj[0] = dayMomRsiMap; retobj[1] = macdrsiMinMax; return retobj; } @Deprecated public static Object[] getDayIndicatorMap(MyMyConfig conf, TaUtil tu, List<AbstractIndicator> indicators, int futureDays, int tableDays, int intervalDays) throws Exception { List<Map<String, Object[]>> objectMapsList = new ArrayList<>(); List<Map<String, Double[][]>> listList = new ArrayList<>(); int arraySize = 0; for (AbstractIndicator indicator : indicators) { Map<String, Object> resultMap = indicator.getLocalResultMap(); Map<String, Object[]> objMap = (Map<String, Object[]>) resultMap.get(PipelineConstants.OBJECT); if (objMap != null) { objectMapsList.add(objMap); listList.add((Map<String, Double[][]>) resultMap.get(PipelineConstants.LIST)); arraySize += indicator.getResultSize(); System.out.println("sizes " + listList.get(listList.size() - 1).size()); } } Object[] retobj = new Object[3]; Map<Integer, Map<String, Double[]>> dayIndicatorMap = new HashMap<>(); List<Double>[] indicatorLists = new ArrayList[arraySize]; List<Double>[] indicatorMinMax = new ArrayList[arraySize]; for (int tmpj = 0; tmpj < arraySize; tmpj ++) { indicatorLists[tmpj] = new ArrayList<>(); indicatorMinMax[tmpj] = new ArrayList<>(); } if (listList.isEmpty()) { return retobj; } // TODO copy the retain from aggregator? Set<String> ids = new HashSet<>(); ids.addAll(listList.get(0).keySet()); // TODO change for (int j = futureDays; j < tableDays; j += intervalDays) { Map<String, Double[]> indicatorMap = new HashMap<>(); for (String id : listList.get(0).keySet()) { Double[] result = new Double[0]; result = getCommonResult(indicators, objectMapsList, j, id, result); if (result.length == arraySize) { indicatorMap.put(id, result); IndicatorUtils.addToLists(indicatorLists, result); log.info("outid {} {}", id, Arrays.asList(result)); } else { continue; } dayIndicatorMap.put(j, indicatorMap); } } findMinMax(arraySize, dayIndicatorMap, indicatorLists, indicatorMinMax); retobj[0] = dayIndicatorMap; retobj[1] = indicatorMinMax; retobj[2] = listList; return retobj; } public static Object[] getDayIndicatorMap(MyMyConfig conf, TaUtil tu, List<AbstractIndicator> indicators, int futureDays, int tableDays, int intervalDays, ExtraData extraData) throws Exception { List<Map<String, Object[]>> objectMapsList = new ArrayList<>(); List<Map<String, Double[][]>> listList = new ArrayList<>(); int arraySize = getCommonArraySizeAndObjectMap(indicators, objectMapsList, listList); Object[] retobj = new Object[3]; Map<Integer, Map<String, Double[]>> dayIndicatorMap = new HashMap<>(); List<Double>[] indicatorLists = new ArrayList[arraySize]; List<Double>[] indicatorMinMax = new ArrayList[arraySize]; for (int tmpj = 0; tmpj < arraySize; tmpj ++) { indicatorLists[tmpj] = new ArrayList<>(); indicatorMinMax[tmpj] = new ArrayList<>(); } if (listList.isEmpty()) { return retobj; } // TODO copy the retain from aggregator? Set<String> ids = new HashSet<>(); ids.addAll(listList.get(0).keySet()); List<AbstractIndicator> allIndicators = new ArrayList<>(); // for extrareader data if (extraData != null) { arraySize = getExtraDataSize(conf, extraData, arraySize, allIndicators); } // for more extra end // TODO change for (int j = futureDays; j < tableDays; j += intervalDays) { Map<String, Double[]> indicatorMap = new HashMap<>(); for (String id : listList.get(0).keySet()) { Double[] result = new Double[0]; result = getCommonResult(indicators, objectMapsList, j, id, result); if (extraData != null) { // for extrareader data result = ExtraReader.getExtraData(conf, extraData.dateList, extraData.pairDateMap, extraData.pairCatMap, j, id, result); // for extrareader data end // for more extrareader data result = getExtraIndicatorsResult(extraData.categories, j, result, extraData.pairDateMap, extraData.pairCatMap, extraData.datareaders, allIndicators); // for more extrareader data end } if (result.length == arraySize) { indicatorMap.put(id, result); IndicatorUtils.addToLists(indicatorLists, result); log.info("outid {} {}", id, Arrays.asList(result)); } else { continue; } dayIndicatorMap.put(j, indicatorMap); } } findMinMax(arraySize, dayIndicatorMap, indicatorLists, indicatorMinMax); retobj[0] = dayIndicatorMap; retobj[1] = indicatorMinMax; retobj[2] = listList; return retobj; } private static void findMinMax(int arraySize, Map<Integer, Map<String, Double[]>> dayIndicatorMap, List<Double>[] indicatorLists, List<Double>[] indicatorMinMax) { if (!dayIndicatorMap.isEmpty()) { for (int i = 0; i < arraySize; i++) { indicatorMinMax[i].add(Collections.min(indicatorLists[i])); indicatorMinMax[i].add(Collections.max(indicatorLists[i])); } } } private static Double[] getCommonResult(List<AbstractIndicator> indicators, List<Map<String, Object[]>> objectMapsList, int j, String id, Double[] result) { int idx = 0; for (Map<String, Object[]> objectMap : objectMapsList) { AbstractIndicator ind = indicators.get(idx++); Object[] objsIndicator = objectMap.get(id); result = appendDayResult(j, result, ind, objsIndicator); } return result; } private static int getCommonArraySizeAndObjectMap(List<AbstractIndicator> indicators, List<Map<String, Object[]>> objectMapsList, List<Map<String, Double[][]>> listList) { int arraySize = 0; for (AbstractIndicator indicator : indicators) { Map<String, Object> resultMap = indicator.getLocalResultMap(); Map<String, Object[]> objMap = (Map<String, Object[]>) resultMap.get(PipelineConstants.OBJECT); if (objMap != null) { objectMapsList.add(objMap); listList.add((Map<String, Double[][]>) resultMap.get(PipelineConstants.LIST)); arraySize += indicator.getResultSize(); log.info("sizes {}", listList.get(listList.size() - 1).size()); } } return arraySize; } private static int getExtraDataSize(MyMyConfig conf, ExtraData extraData, int arraySize, List<AbstractIndicator> allIndicators) throws Exception { if (extraData.pairDateMap != null) { arraySize += 2 * extraData.pairDateMap.keySet().size(); System.out.println("sizes " + arraySize); } // for extrareader data end // for more extra getAllIndicators(allIndicators, conf, extraData.categories, extraData.pairCatMap, extraData.datareaders); for (AbstractIndicator indicator : allIndicators) { int aSize = indicator.getResultSize(); arraySize += extraData.pairCatMap.size() * aSize; } log.info("listsize {}", extraData.dateList.size()); return arraySize; } public static int getCategoryFromString(Map<Pair<String, String>, String> pairCatMap, Pair<String, String> pairKey) { String categoryString = pairCatMap.get(pairKey); int category = 0; switch (categoryString) { case Constants.PRICE: category = Constants.PRICECOLUMN; break; case Constants.INDEX: category = Constants.INDEXVALUECOLUMN; break; } return category; } private static Double[] getExtraIndicatorsResult(AbstractCategory[] categories, int j, Double[] result, Map<Pair<String, String>, Map<Date, StockItem>> pairDateMap, Map<Pair<String, String>, String> pairCatMap, Pipeline[] datareaders, List<AbstractIndicator> allIndicators) throws Exception { for (AbstractIndicator indicator : allIndicators) { if (indicator.wantForExtras()) { Map<String, Object> localIndicatorResults = indicator.getLocalResultMap(); Map<String, Map<String, Object[]>> marketObjectMap = (Map<String, Map<String, Object[]>>) localIndicatorResults.get(PipelineConstants.MARKETOBJECT); for (Entry<String, Map<String, Object[]>> marketEntry : marketObjectMap.entrySet()) { Map<String, Object[]> objectMap = marketEntry.getValue(); for (Entry<String, Object[]> entry : objectMap.entrySet()) { Object[] objsIndicator = entry.getValue(); result = appendDayResult(j, result, indicator, objsIndicator); } } } } return result; } private static Double[] appendDayResult(int j, Double[] result, AbstractIndicator indicator, Object[] objsIndicator) { Object[] arr = indicator.getDayResult(objsIndicator, j); if (arr != null && arr.length > 0) { result = (Double[]) ArrayUtils.addAll(result, arr); } return result; } private static void getAllIndicators(List<AbstractIndicator> allIndicators, MyMyConfig conf, AbstractCategory[] categories, Map<Pair<String, String>, String> pairCatMap, Pipeline[] datareaders) throws Exception { Set<String> indicatorSet = new HashSet<>(); for (Entry<Pair<String, String>, String> pairEntry : pairCatMap.entrySet()) { String market = pairEntry.getKey().getFirst(); String cat = pairEntry.getValue(); if (market.equals(conf.getMarket())) { for (AbstractCategory category : categories) { if (cat.equals(category.getTitle())) { Map<String, AbstractIndicator> indicatorMap = category.getIndicatorMap(); for (Entry<String, AbstractIndicator> entry : indicatorMap.entrySet()) { AbstractIndicator indicator = entry.getValue(); if (indicator.wantForExtras()) { allIndicators.add(indicator); indicatorSet.add(entry.getKey()); } } } } } } // TODO make indicator factory if (indicatorSet.add(PipelineConstants.INDICATORMACD) && conf.wantAggregatorsIndicatorExtrasMACD()) { allIndicators.add(new IndicatorMACD(conf, null, null, 42, datareaders, true)); } if (indicatorSet.add(PipelineConstants.INDICATORRSI) && conf.wantAggregatorsIndicatorExtrasRSI()) { allIndicators.add(new IndicatorRSI(conf, null, null, 42, datareaders, true)); } } public static void addToLists(List<Double> macdLists[], Double[] momentum) throws Exception { for (int i = 0; i < macdLists.length; i ++) { List<Double> macdList = macdLists[i]; if (momentum[i] != null) { macdList.add(momentum[i]); } } } public static void addToLists(Map<String, MarketData> marketdatamap, int category, List<Double> macdLists[], String market, Double[] momentum) throws Exception { for (int i = 0; i < macdLists.length; i ++) { List<Double> macdList = macdLists[i]; if (momentum[i] != null) { macdList.add(momentum[i]); } } } public static Map<String, Pipeline> getPipelineMap(Pipeline[] datareaders) { Map<String, Pipeline> pipelineMap = new HashMap<>(); for (Pipeline datareader : datareaders) { pipelineMap.put(datareader.pipelineName(), datareader); } return pipelineMap; } public static AbstractCategory getWantedCategory(AbstractCategory[] categories) throws Exception { List<String> wantedList = new ArrayList<>(); wantedList.add(CategoryConstants.PRICE); wantedList.add(CategoryConstants.INDEX); wantedList.add("cy"); AbstractCategory cat = null; for (String wanted : wantedList) { for (AbstractCategory category : categories) { if (cat == null && category.hasContent() && category.getTitle().equals(wanted)) { cat = category; break; } } } return cat; } public static AbstractCategory getWantedCategory(AbstractCategory[] categories, int cat) throws Exception { for (AbstractCategory category : categories) { if (cat == category.getPeriod()) { return category; } } return null; } public static Integer getWantedCategory(List<StockItem> stocks, PeriodData periodData) throws Exception { if (StockUtil.hasStockValue(stocks, Constants.PRICECOLUMN)) { return Constants.PRICECOLUMN; } if (StockUtil.hasStockValue(stocks, Constants.INDEXVALUECOLUMN)) { return Constants.INDEXVALUECOLUMN; } if (periodData == null) { return null; } Set<Pair<String, Integer>> pairs = periodData.pairs; for (Pair<String, Integer> pair : pairs) { int cat = (int) pair.getSecond(); if (StockUtil.hasStockValue(stocks, cat)) { return cat; } } return null; } public static void filterNonExistingClassifications(Map<Double, String> labelMapShort, Map<String, Double[]> classifyResult) { log.info("Values " + classifyResult.values()); // due to tensorflow l classifying to 3drd (not inc dec) List<String> filterNonExistingClassifications = new ArrayList<>(); for (Entry<String, Double[]> entry : classifyResult.entrySet()) { Double[] value = entry.getValue(); if (labelMapShort.get(value[0]) == null) { filterNonExistingClassifications.add(entry.getKey()); } } for (String key : filterNonExistingClassifications) { classifyResult.remove(key); log.error("Removing key {}", key); } } public static void filterNonExistingClassifications2(Map labelMapShort, Map map) { log.info("Values " + map.values()); // due to tensorflow l classifying to 3rd (not inc dec) List<Object> filterNonExistingClassifications = new ArrayList<>(); for (Object key : map.keySet()) { Object value = map.get(key); if (labelMapShort.get(value) == null) { filterNonExistingClassifications.add(key); } } for (Object key : filterNonExistingClassifications) { map.remove(key); log.error("Removing key {}", key); } } }
main/pipeline/indicator/src/main/java/roart/indicator/util/IndicatorUtils.java
package roart.indicator.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.math3.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.category.AbstractCategory; import roart.common.config.MyMyConfig; import roart.common.pipeline.PipelineConstants; import roart.indicator.AbstractIndicator; import roart.indicator.impl.IndicatorMACD; import roart.indicator.impl.IndicatorRSI; import roart.common.constants.CategoryConstants; import roart.common.constants.Constants; import roart.model.StockItem; import roart.pipeline.Pipeline; import roart.pipeline.data.ExtraData; import roart.pipeline.impl.ExtraReader; import roart.model.data.MarketData; import roart.model.data.PeriodData; import roart.stockutil.StockUtil; import roart.talib.util.TaUtil; public class IndicatorUtils { protected static Logger log = LoggerFactory.getLogger(IndicatorUtils.class); /** * * Get an array with two arrays * First a map from day to related macd map from id to values * Second a map from day to all macd values * * @param conf Main config, not evolution * @param objectMap map from stock id to macd map * @param listMap map from stock id to values * @param tu * @return * @throws Exception */ @Deprecated public static Object[] getDayMomMap(MyMyConfig conf, Map<String, Object[]> objectMap, Map<String, Double[]> listMap, TaUtil tu) throws Exception { Object[] retobj = new Object[2]; Map<Integer, Map<String, Double[]>> dayMomMap = new HashMap<>(); Map<Integer, List<Double>[]> dayMacdsMap = new HashMap<>(); List<Double> macdLists[] = new ArrayList[4]; List<Double> macdMinMax[] = new ArrayList[4]; for (int tmpj = 0; tmpj < 4; tmpj ++) { macdLists[tmpj] = new ArrayList<>(); macdMinMax[tmpj] = new ArrayList<>(); } for (int j = conf.getTestIndicatorRecommenderComplexFutureDays(); j < conf.getTableDays(); j += conf.getTestIndicatorRecommenderComplexIntervalDays()) { Map<String, Double[]> momMap = new HashMap<>(); for (String id : listMap.keySet()) { Object[] objs = objectMap.get(id); Double[] momentum = tu.getMomAndDelta(conf.getMACDDeltaDays(), conf.getMACDHistogramDeltaDays(), objs, j); if (momentum != null) { momMap.put(id, momentum); IndicatorUtils.addToLists(macdLists, momentum); } } dayMomMap.put(j, momMap); dayMacdsMap.put(j, macdLists); } macdMinMax[0].add(Collections.min(macdLists[0])); macdMinMax[0].add(Collections.max(macdLists[0])); macdMinMax[1].add(Collections.min(macdLists[1])); macdMinMax[1].add(Collections.max(macdLists[1])); retobj[0] = dayMomMap; retobj[1] = macdMinMax; return retobj; } @Deprecated public static Object[] getDayRsiMap(MyMyConfig conf, Map<String, Object[]> objectMap, Map<String, Double[]> listMap, TaUtil tu) throws Exception { Object[] retobj = new Object[2]; Map<Integer, Map<String, Double[]>> dayRsiMap = new HashMap<>(); List<Double> rsiLists[] = new ArrayList[2]; List<Double> rsiMinMax[] = new ArrayList[2]; for (int tmpj = 0; tmpj < 2; tmpj ++) { rsiLists[tmpj] = new ArrayList<>(); rsiMinMax[tmpj] = new ArrayList<>(); } for (int j = conf.getTestIndicatorRecommenderComplexFutureDays(); j < conf.getTableDays(); j += conf.getTestIndicatorRecommenderComplexIntervalDays()) { Map<String, Double[]> rsiMap = new HashMap<>(); for (String id : listMap.keySet()) { Object[] objs = objectMap.get(id); Double[] rsi = tu.getRsiAndDelta(conf.getRSIDeltaDays(), objs, j); if (rsi != null) { rsiMap.put(id, rsi); IndicatorUtils.addToLists(rsiLists, rsi); } } dayRsiMap.put(j, rsiMap); } rsiMinMax[0].add(Collections.min(rsiLists[0])); rsiMinMax[0].add(Collections.max(rsiLists[0])); rsiMinMax[1].add(Collections.min(rsiLists[1])); rsiMinMax[1].add(Collections.max(rsiLists[1])); retobj[0] = dayRsiMap; retobj[1] = rsiMinMax; return retobj; } @Deprecated public static Object[] getDayMomRsiMap(MyMyConfig conf, Map<String, Object[]> objectMacdMap, Map<String, Double[]> listMacdMap, Map<String, Object[]> objectRsiMap, Map<String, Double[]> listRsiMap, TaUtil tu) throws Exception { Object[] retobj = new Object[2]; Map<Integer, Map<String, Double[]>> dayMomRsiMap = new HashMap<>(); List<Double>[] macdrsiLists = new ArrayList[6]; List<Double>[] macdrsiMinMax = new ArrayList[6]; for (int tmpj = 0; tmpj < 4 + 2; tmpj ++) { macdrsiLists[tmpj] = new ArrayList<>(); macdrsiMinMax[tmpj] = new ArrayList<>(); } for (int j = conf.getTestIndicatorRecommenderComplexFutureDays(); j < conf.getTableDays(); j += conf.getTestIndicatorRecommenderComplexIntervalDays()) { Map<String, Double[]> momrsiMap = new HashMap<>(); for (String id : listMacdMap.keySet()) { Object[] objsMacd = objectMacdMap.get(id); Object[] objsRSI = objectRsiMap.get(id); Double[] momentum = tu.getMomAndDelta(conf.getMACDDeltaDays(), conf.getMACDHistogramDeltaDays(), objsMacd, j); Double[] rsi = tu.getRsiAndDelta(conf.getRSIDeltaDays(), objsRSI, j); if (momentum != null) { Double[] momrsi = ArrayUtils.addAll(momentum, rsi); momrsiMap.put(id, momrsi); IndicatorUtils.addToLists(macdrsiLists, momrsi); } } dayMomRsiMap.put(j, momrsiMap); } for (int i = 0; i < 4 + 2; i++) { macdrsiMinMax[i].add(Collections.min(macdrsiLists[i])); macdrsiMinMax[i].add(Collections.max(macdrsiLists[i])); } retobj[0] = dayMomRsiMap; retobj[1] = macdrsiMinMax; return retobj; } @Deprecated public static Object[] getDayIndicatorMap(MyMyConfig conf, TaUtil tu, List<AbstractIndicator> indicators, int futureDays, int tableDays, int intervalDays) throws Exception { List<Map<String, Object[]>> objectMapsList = new ArrayList<>(); List<Map<String, Double[][]>> listList = new ArrayList<>(); int arraySize = 0; for (AbstractIndicator indicator : indicators) { Map<String, Object> resultMap = indicator.getLocalResultMap(); Map<String, Object[]> objMap = (Map<String, Object[]>) resultMap.get(PipelineConstants.OBJECT); if (objMap != null) { objectMapsList.add(objMap); listList.add((Map<String, Double[][]>) resultMap.get(PipelineConstants.LIST)); arraySize += indicator.getResultSize(); System.out.println("sizes " + listList.get(listList.size() - 1).size()); } } Object[] retobj = new Object[3]; Map<Integer, Map<String, Double[]>> dayIndicatorMap = new HashMap<>(); List<Double>[] indicatorLists = new ArrayList[arraySize]; List<Double>[] indicatorMinMax = new ArrayList[arraySize]; for (int tmpj = 0; tmpj < arraySize; tmpj ++) { indicatorLists[tmpj] = new ArrayList<>(); indicatorMinMax[tmpj] = new ArrayList<>(); } if (listList.isEmpty()) { return retobj; } // TODO copy the retain from aggregator? Set<String> ids = new HashSet<>(); ids.addAll(listList.get(0).keySet()); // TODO change for (int j = futureDays; j < tableDays; j += intervalDays) { Map<String, Double[]> indicatorMap = new HashMap<>(); for (String id : listList.get(0).keySet()) { Double[] result = new Double[0]; result = getCommonResult(indicators, objectMapsList, j, id, result); if (result.length == arraySize) { indicatorMap.put(id, result); IndicatorUtils.addToLists(indicatorLists, result); log.info("outid {} {}", id, Arrays.asList(result)); } else { continue; } dayIndicatorMap.put(j, indicatorMap); } } findMinMax(arraySize, dayIndicatorMap, indicatorLists, indicatorMinMax); retobj[0] = dayIndicatorMap; retobj[1] = indicatorMinMax; retobj[2] = listList; return retobj; } public static Object[] getDayIndicatorMap(MyMyConfig conf, TaUtil tu, List<AbstractIndicator> indicators, int futureDays, int tableDays, int intervalDays, ExtraData extraData) throws Exception { List<Map<String, Object[]>> objectMapsList = new ArrayList<>(); List<Map<String, Double[][]>> listList = new ArrayList<>(); int arraySize = getCommonArraySizeAndObjectMap(indicators, objectMapsList, listList); Object[] retobj = new Object[3]; Map<Integer, Map<String, Double[]>> dayIndicatorMap = new HashMap<>(); List<Double>[] indicatorLists = new ArrayList[arraySize]; List<Double>[] indicatorMinMax = new ArrayList[arraySize]; for (int tmpj = 0; tmpj < arraySize; tmpj ++) { indicatorLists[tmpj] = new ArrayList<>(); indicatorMinMax[tmpj] = new ArrayList<>(); } if (listList.isEmpty()) { return retobj; } // TODO copy the retain from aggregator? Set<String> ids = new HashSet<>(); ids.addAll(listList.get(0).keySet()); List<AbstractIndicator> allIndicators = new ArrayList<>(); // for extrareader data if (extraData != null) { arraySize = getExtraDataSize(conf, extraData, arraySize, allIndicators); } // for more extra end // TODO change for (int j = futureDays; j < tableDays; j += intervalDays) { Map<String, Double[]> indicatorMap = new HashMap<>(); for (String id : listList.get(0).keySet()) { Double[] result = new Double[0]; result = getCommonResult(indicators, objectMapsList, j, id, result); if (extraData != null) { // for extrareader data result = ExtraReader.getExtraData(conf, extraData.dateList, extraData.pairDateMap, extraData.pairCatMap, j, id, result); // for extrareader data end // for more extrareader data result = getExtraIndicatorsResult(extraData.categories, j, result, extraData.pairDateMap, extraData.pairCatMap, extraData.datareaders, allIndicators); // for more extrareader data end } if (result.length == arraySize) { indicatorMap.put(id, result); IndicatorUtils.addToLists(indicatorLists, result); log.info("outid {} {}", id, Arrays.asList(result)); } else { continue; } dayIndicatorMap.put(j, indicatorMap); } } findMinMax(arraySize, dayIndicatorMap, indicatorLists, indicatorMinMax); retobj[0] = dayIndicatorMap; retobj[1] = indicatorMinMax; retobj[2] = listList; return retobj; } private static void findMinMax(int arraySize, Map<Integer, Map<String, Double[]>> dayIndicatorMap, List<Double>[] indicatorLists, List<Double>[] indicatorMinMax) { if (!dayIndicatorMap.isEmpty()) { for (int i = 0; i < arraySize; i++) { indicatorMinMax[i].add(Collections.min(indicatorLists[i])); indicatorMinMax[i].add(Collections.max(indicatorLists[i])); } } } private static Double[] getCommonResult(List<AbstractIndicator> indicators, List<Map<String, Object[]>> objectMapsList, int j, String id, Double[] result) { int idx = 0; for (Map<String, Object[]> objectMap : objectMapsList) { AbstractIndicator ind = indicators.get(idx++); Object[] objsIndicator = objectMap.get(id); result = appendDayResult(j, result, ind, objsIndicator); } return result; } private static int getCommonArraySizeAndObjectMap(List<AbstractIndicator> indicators, List<Map<String, Object[]>> objectMapsList, List<Map<String, Double[][]>> listList) { int arraySize = 0; for (AbstractIndicator indicator : indicators) { Map<String, Object> resultMap = indicator.getLocalResultMap(); Map<String, Object[]> objMap = (Map<String, Object[]>) resultMap.get(PipelineConstants.OBJECT); if (objMap != null) { objectMapsList.add(objMap); listList.add((Map<String, Double[][]>) resultMap.get(PipelineConstants.LIST)); arraySize += indicator.getResultSize(); log.info("sizes {}", listList.get(listList.size() - 1).size()); } } return arraySize; } private static int getExtraDataSize(MyMyConfig conf, ExtraData extraData, int arraySize, List<AbstractIndicator> allIndicators) throws Exception { if (extraData.pairDateMap != null) { arraySize += 2 * extraData.pairDateMap.keySet().size(); System.out.println("sizes " + arraySize); } // for extrareader data end // for more extra getAllIndicators(allIndicators, conf, extraData.categories, extraData.pairCatMap, extraData.datareaders); for (AbstractIndicator indicator : allIndicators) { int aSize = indicator.getResultSize(); arraySize += extraData.pairCatMap.size() * aSize; } log.info("listsize {}", extraData.dateList.size()); return arraySize; } public static int getCategoryFromString(Map<Pair<String, String>, String> pairCatMap, Pair<String, String> pairKey) { String categoryString = pairCatMap.get(pairKey); int category = 0; switch (categoryString) { case Constants.PRICE: category = Constants.PRICECOLUMN; break; case Constants.INDEX: category = Constants.INDEXVALUECOLUMN; break; } return category; } private static Double[] getExtraIndicatorsResult(AbstractCategory[] categories, int j, Double[] result, Map<Pair<String, String>, Map<Date, StockItem>> pairDateMap, Map<Pair<String, String>, String> pairCatMap, Pipeline[] datareaders, List<AbstractIndicator> allIndicators) throws Exception { for (AbstractIndicator indicator : allIndicators) { if (indicator.wantForExtras()) { Map<String, Object> localIndicatorResults = indicator.getLocalResultMap(); Map<String, Map<String, Object[]>> marketObjectMap = (Map<String, Map<String, Object[]>>) localIndicatorResults.get(PipelineConstants.MARKETOBJECT); for (Entry<String, Map<String, Object[]>> marketEntry : marketObjectMap.entrySet()) { Map<String, Object[]> objectMap = marketEntry.getValue(); for (Entry<String, Object[]> entry : objectMap.entrySet()) { Object[] objsIndicator = entry.getValue(); result = appendDayResult(j, result, indicator, objsIndicator); } } } } return result; } private static Double[] appendDayResult(int j, Double[] result, AbstractIndicator indicator, Object[] objsIndicator) { Object[] arr = indicator.getDayResult(objsIndicator, j); if (arr != null && arr.length > 0) { result = (Double[]) ArrayUtils.addAll(result, arr); } return result; } private static void getAllIndicators(List<AbstractIndicator> allIndicators, MyMyConfig conf, AbstractCategory[] categories, Map<Pair<String, String>, String> pairCatMap, Pipeline[] datareaders) throws Exception { Set<String> indicatorSet = new HashSet<>(); for (Entry<Pair<String, String>, String> pairEntry : pairCatMap.entrySet()) { String market = pairEntry.getKey().getFirst(); String cat = pairEntry.getValue(); if (market.equals(conf.getMarket())) { for (AbstractCategory category : categories) { if (cat.equals(category.getTitle())) { Map<String, AbstractIndicator> indicatorMap = category.getIndicatorMap(); for (Entry<String, AbstractIndicator> entry : indicatorMap.entrySet()) { AbstractIndicator indicator = entry.getValue(); if (indicator.wantForExtras()) { allIndicators.add(indicator); indicatorSet.add(entry.getKey()); } } } } } } // TODO make indicator factory if (indicatorSet.add(PipelineConstants.INDICATORMACD) && conf.wantAggregatorsIndicatorExtrasMACD()) { allIndicators.add(new IndicatorMACD(conf, null, null, 42, datareaders, true)); } if (indicatorSet.add(PipelineConstants.INDICATORRSI) && conf.wantAggregatorsIndicatorExtrasRSI()) { allIndicators.add(new IndicatorRSI(conf, null, null, 42, datareaders, true)); } } public static void addToLists(List<Double> macdLists[], Double[] momentum) throws Exception { for (int i = 0; i < macdLists.length; i ++) { List<Double> macdList = macdLists[i]; if (momentum[i] != null) { macdList.add(momentum[i]); } } } public static void addToLists(Map<String, MarketData> marketdatamap, int category, List<Double> macdLists[], String market, Double[] momentum) throws Exception { for (int i = 0; i < macdLists.length; i ++) { List<Double> macdList = macdLists[i]; if (momentum[i] != null) { macdList.add(momentum[i]); } } } public static Map<String, Pipeline> getPipelineMap(Pipeline[] datareaders) { Map<String, Pipeline> pipelineMap = new HashMap<>(); for (Pipeline datareader : datareaders) { pipelineMap.put(datareader.pipelineName(), datareader); } return pipelineMap; } public static AbstractCategory getWantedCategory(AbstractCategory[] categories) throws Exception { List<String> wantedList = new ArrayList<>(); wantedList.add(CategoryConstants.PRICE); wantedList.add(CategoryConstants.INDEX); wantedList.add("cy"); AbstractCategory cat = null; for (String wanted : wantedList) { for (AbstractCategory category : categories) { if (cat == null && category.hasContent() && category.getTitle().equals(wanted)) { cat = category; break; } } } return cat; } public static Integer getWantedCategory(List<StockItem> stocks, PeriodData periodData) throws Exception { if (StockUtil.hasStockValue(stocks, Constants.PRICECOLUMN)) { return Constants.PRICECOLUMN; } if (StockUtil.hasStockValue(stocks, Constants.INDEXVALUECOLUMN)) { return Constants.INDEXVALUECOLUMN; } if (periodData == null) { return null; } Set<Pair<String, Integer>> pairs = periodData.pairs; for (Pair<String, Integer> pair : pairs) { int cat = (int) pair.getSecond(); if (StockUtil.hasStockValue(stocks, cat)) { return cat; } } return null; } public static void filterNonExistingClassifications(Map<Double, String> labelMapShort, Map<String, Double[]> classifyResult) { log.info("Values " + classifyResult.values()); // due to tensorflow l classifying to 3drd (not inc dec) List<String> filterNonExistingClassifications = new ArrayList<>(); for (Entry<String, Double[]> entry : classifyResult.entrySet()) { Double[] value = entry.getValue(); if (labelMapShort.get(value[0]) == null) { filterNonExistingClassifications.add(entry.getKey()); } } for (String key : filterNonExistingClassifications) { classifyResult.remove(key); log.error("Removing key {}", key); } } public static void filterNonExistingClassifications2(Map labelMapShort, Map map) { log.info("Values " + map.values()); // due to tensorflow l classifying to 3rd (not inc dec) List<Object> filterNonExistingClassifications = new ArrayList<>(); for (Object key : map.keySet()) { Object value = map.get(key); if (labelMapShort.get(value) == null) { filterNonExistingClassifications.add(key); } } for (Object key : filterNonExistingClassifications) { map.remove(key); log.error("Removing key {}", key); } } }
Change category getter.
main/pipeline/indicator/src/main/java/roart/indicator/util/IndicatorUtils.java
Change category getter.
<ide><path>ain/pipeline/indicator/src/main/java/roart/indicator/util/IndicatorUtils.java <ide> return cat; <ide> } <ide> <add> public static AbstractCategory getWantedCategory(AbstractCategory[] categories, int cat) throws Exception { <add> for (AbstractCategory category : categories) { <add> if (cat == category.getPeriod()) { <add> return category; <add> } <add> } <add> return null; <add> } <add> <ide> public static Integer getWantedCategory(List<StockItem> stocks, PeriodData periodData) throws Exception { <ide> if (StockUtil.hasStockValue(stocks, Constants.PRICECOLUMN)) { <ide> return Constants.PRICECOLUMN;
Java
mit
6421555a2fe22d91ecb396fdd546598b1c1d4a35
0
raoulvdberge/refinedstorage,raoulvdberge/refinedstorage,way2muchnoise/refinedstorage,way2muchnoise/refinedstorage
package refinedstorage.tile; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; import refinedstorage.RefinedStorage; import refinedstorage.RefinedStorageBlocks; import refinedstorage.block.BlockGrid; import refinedstorage.block.EnumGridType; import refinedstorage.inventory.InventorySimple; import refinedstorage.network.MessageGridCraftingUpdate; import refinedstorage.storage.StorageItem; import refinedstorage.util.InventoryUtils; public class TileGrid extends TileMachine { public static final String NBT_SORTING_DIRECTION = "SortingDirection"; public static final String NBT_SORTING_TYPE = "SortingType"; public static final int SORTING_DIRECTION_ASCENDING = 0; public static final int SORTING_DIRECTION_DESCENDING = 1; public static final int SORTING_TYPE_QUANTITY = 0; public static final int SORTING_TYPE_NAME = 1; private Container craftingContainer = new Container() { @Override public boolean canInteractWith(EntityPlayer player) { return false; } @Override public void onCraftMatrixChanged(IInventory inventory) { onCraftingMatrixChanged(); } }; private InventoryCrafting craftingInventory = new InventoryCrafting(craftingContainer, 3, 3); private InventorySimple craftingResultInventory = new InventorySimple("crafting_result", 1); private int sortingDirection = SORTING_DIRECTION_DESCENDING; private int sortingType = SORTING_TYPE_NAME; @Override public int getEnergyUsage() { return 4; } @Override public void updateMachine() { } public EnumGridType getType() { if (worldObj.getBlockState(pos).getBlock() == RefinedStorageBlocks.GRID) { return (EnumGridType) worldObj.getBlockState(pos).getValue(BlockGrid.TYPE); } return EnumGridType.NORMAL; } public InventoryCrafting getCraftingInventory() { return craftingInventory; } public InventorySimple getCraftingResultInventory() { return craftingResultInventory; } public void onCraftingMatrixChanged() { markDirty(); craftingResultInventory.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(craftingInventory, worldObj)); } public void onCrafted(ItemStack[] matrixSlots) { if (isConnected() && !worldObj.isRemote) { for (int i = 0; i < craftingInventory.getSizeInventory(); ++i) { ItemStack slot = craftingInventory.getStackInSlot(i); if (slot == null && matrixSlots[i] != null) { for (StorageItem item : getController().getItems()) { if (item.compareNoQuantity(matrixSlots[i].copy())) { craftingInventory.setInventorySlotContents(i, getController().take(matrixSlots[i].copy())); break; } } } } onCraftingMatrixChanged(); TargetPoint target = new TargetPoint(worldObj.provider.getDimensionType().getId(), pos.getX(), pos.getY(), pos.getZ(), UPDATE_RANGE); RefinedStorage.NETWORK.sendToAllAround(new MessageGridCraftingUpdate(this), target); } } public int getSortingDirection() { return sortingDirection; } public void setSortingDirection(int sortingDirection) { markDirty(); this.sortingDirection = sortingDirection; } public int getSortingType() { return sortingType; } public void setSortingType(int sortingType) { markDirty(); this.sortingType = sortingType; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); InventoryUtils.restoreInventory(craftingInventory, 0, nbt); if (nbt.hasKey(NBT_SORTING_DIRECTION)) { sortingDirection = nbt.getInteger(NBT_SORTING_DIRECTION); } if (nbt.hasKey(NBT_SORTING_TYPE)) { sortingType = nbt.getInteger(NBT_SORTING_TYPE); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); InventoryUtils.saveInventory(craftingInventory, 0, nbt); nbt.setInteger(NBT_SORTING_DIRECTION, sortingDirection); nbt.setInteger(NBT_SORTING_TYPE, sortingType); } @Override public void toBytes(ByteBuf buf) { super.toBytes(buf); buf.writeInt(sortingDirection); buf.writeInt(sortingType); } @Override public void fromBytes(ByteBuf buf) { super.fromBytes(buf); sortingDirection = buf.readInt(); sortingType = buf.readInt(); } @Override public IInventory getDroppedInventory() { if (getType() == EnumGridType.CRAFTING) { return craftingInventory; } return null; } }
src/main/java/refinedstorage/tile/TileGrid.java
package refinedstorage.tile; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; import refinedstorage.RefinedStorage; import refinedstorage.RefinedStorageBlocks; import refinedstorage.block.BlockGrid; import refinedstorage.block.EnumGridType; import refinedstorage.inventory.InventorySimple; import refinedstorage.network.MessageGridCraftingUpdate; import refinedstorage.storage.StorageItem; import refinedstorage.util.InventoryUtils; public class TileGrid extends TileMachine { public static final String NBT_SORTING_DIRECTION = "SortingDirection"; public static final String NBT_SORTING_TYPE = "SortingType"; public static final int SORTING_DIRECTION_ASCENDING = 0; public static final int SORTING_DIRECTION_DESCENDING = 1; public static final int SORTING_TYPE_QUANTITY = 0; public static final int SORTING_TYPE_NAME = 1; private Container craftingContainer = new Container() { @Override public boolean canInteractWith(EntityPlayer player) { return false; } @Override public void onCraftMatrixChanged(IInventory inventory) { onCraftingMatrixChanged(); } }; private InventoryCrafting craftingInventory = new InventoryCrafting(craftingContainer, 3, 3); private InventorySimple craftingResultInventory = new InventorySimple("crafting_result", 1); private int sortingDirection = 0; private int sortingType = 0; @Override public int getEnergyUsage() { return 4; } @Override public void updateMachine() { } public EnumGridType getType() { if (worldObj.getBlockState(pos).getBlock() == RefinedStorageBlocks.GRID) { return (EnumGridType) worldObj.getBlockState(pos).getValue(BlockGrid.TYPE); } return EnumGridType.NORMAL; } public InventoryCrafting getCraftingInventory() { return craftingInventory; } public InventorySimple getCraftingResultInventory() { return craftingResultInventory; } public void onCraftingMatrixChanged() { markDirty(); craftingResultInventory.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(craftingInventory, worldObj)); } public void onCrafted(ItemStack[] matrixSlots) { if (isConnected() && !worldObj.isRemote) { for (int i = 0; i < craftingInventory.getSizeInventory(); ++i) { ItemStack slot = craftingInventory.getStackInSlot(i); if (slot == null && matrixSlots[i] != null) { for (StorageItem item : getController().getItems()) { if (item.compareNoQuantity(matrixSlots[i].copy())) { craftingInventory.setInventorySlotContents(i, getController().take(matrixSlots[i].copy())); break; } } } } onCraftingMatrixChanged(); TargetPoint target = new TargetPoint(worldObj.provider.getDimensionType().getId(), pos.getX(), pos.getY(), pos.getZ(), UPDATE_RANGE); RefinedStorage.NETWORK.sendToAllAround(new MessageGridCraftingUpdate(this), target); } } public int getSortingDirection() { return sortingDirection; } public void setSortingDirection(int sortingDirection) { markDirty(); this.sortingDirection = sortingDirection; } public int getSortingType() { return sortingType; } public void setSortingType(int sortingType) { markDirty(); this.sortingType = sortingType; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); InventoryUtils.restoreInventory(craftingInventory, 0, nbt); if (nbt.hasKey(NBT_SORTING_DIRECTION)) { sortingDirection = nbt.getInteger(NBT_SORTING_DIRECTION); } if (nbt.hasKey(NBT_SORTING_TYPE)) { sortingType = nbt.getInteger(NBT_SORTING_TYPE); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); InventoryUtils.saveInventory(craftingInventory, 0, nbt); nbt.setInteger(NBT_SORTING_DIRECTION, sortingDirection); nbt.setInteger(NBT_SORTING_TYPE, sortingType); } @Override public void toBytes(ByteBuf buf) { super.toBytes(buf); buf.writeInt(sortingDirection); buf.writeInt(sortingType); } @Override public void fromBytes(ByteBuf buf) { super.fromBytes(buf); sortingDirection = buf.readInt(); sortingType = buf.readInt(); } @Override public IInventory getDroppedInventory() { if (getType() == EnumGridType.CRAFTING) { return craftingInventory; } return null; } }
Better defaults for grid
src/main/java/refinedstorage/tile/TileGrid.java
Better defaults for grid
<ide><path>rc/main/java/refinedstorage/tile/TileGrid.java <ide> private InventoryCrafting craftingInventory = new InventoryCrafting(craftingContainer, 3, 3); <ide> private InventorySimple craftingResultInventory = new InventorySimple("crafting_result", 1); <ide> <del> private int sortingDirection = 0; <del> private int sortingType = 0; <add> private int sortingDirection = SORTING_DIRECTION_DESCENDING; <add> private int sortingType = SORTING_TYPE_NAME; <ide> <ide> @Override <ide> public int getEnergyUsage() {
Java
apache-2.0
f8a489723ef8cc2ee5f3bb5bc13d702219d3e8b9
0
monkey2000/Wikidata-Toolkit,dswarm/Wikidata-Toolkit,dswarm/Wikidata-Toolkit,monkey2000/Wikidata-Toolkit,Wikidata/Wikidata-Toolkit,Wikidata/Wikidata-Toolkit,noa/Wikidata-Toolkit,noa/Wikidata-Toolkit,notconfusing/Wikidata-Toolkit,zazi/Wikidata-Toolkit,notconfusing/Wikidata-Toolkit,noa/Wikidata-Toolkit,noa/Wikidata-Toolkit,zazi/Wikidata-Toolkit
package org.wikidata.wdtk.storage.datastructure.impl; /* * #%L * Wikidata Toolkit Data Model * %% * Copyright (C) 2014 Wikidata Toolkit Developers * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.Iterator; import org.junit.Assert; import org.junit.Test; import org.wikidata.wdtk.storage.datastructure.intf.BitVector; import org.wikidata.wdtk.storage.datastructure.intf.RankedBitVector; /** * Test class for {@link RankedRankedBitVectorImpl}. * * @author Julian Mendez * */ public class RankedBitVectorImplTest { /** * Asserts that for every position in a bit vector, * {@link RankedBitVector#countBits(boolean, long)} works as expected. * * @param bv * bit vector */ void assertCorrectCount(RankedBitVector bv) { for (long index = 0; index < bv.size(); index++) { assertCorrectCount(bv, index); } } /** * Asserts that {@link RankedBitVector#countBits(boolean, long)} works as * expected at a particular position. * * @param bv * bit vector * @param position * position */ void assertCorrectCount(RankedBitVector bv, long position) { { long expectedCount = countBits(bv, false, position); long computedCount = bv.countBits(false, position); Assert.assertEquals(expectedCount, computedCount); } { long expectedCount = countBits(bv, true, position); long computedCount = bv.countBits(true, position); Assert.assertEquals(expectedCount, computedCount); } } /** * Asserts that for every number of occurrences of a bit value in a bit * vector, {@link RankedBitVector#findPosition(boolean, long)} works as * expected. * * @param bv * bit vector */ void assertCorrectFindPosition(RankedBitVector bv) { for (long index = 0; index < bv.size(); index++) { assertCorrectFindPosition(bv, index); } } /** * Asserts that {@link RankedBitVector#findPosition(boolean, long)} works as * expected considering the given number of occurrences of a bit value. * * @param bv * bit vector * @param nOccurrences * number of occurrences */ void assertCorrectFindPosition(RankedBitVector bv, long nOccurrences) { { long expectedFindPosition = findPosition(bv, false, nOccurrences); long computedFindPosition = bv.findPosition(false, nOccurrences); Assert.assertEquals(expectedFindPosition, computedFindPosition); } { long expectedFindPosition = findPosition(bv, true, nOccurrences); long computedFindPosition = bv.findPosition(true, nOccurrences); Assert.assertEquals(expectedFindPosition, computedFindPosition); } } /** * Asserts that two ranked bit vectors are equal, and also that the first * bit vector is equal to itself. * * @param bv0 * one bit vector * @param bv1 * another bit vector */ void assertEqualsForBitVector(RankedBitVector bv0, RankedBitVector bv1) { Assert.assertEquals(bv0, bv0); Assert.assertEquals(bv0, bv1); Assert.assertEquals(bv1, bv0); Assert.assertEquals(bv0.hashCode(), bv1.hashCode()); } /** * Returns the expected value of * {@link RankedBitVector#countBits(boolean, long)}. * * @param bv * bit vector * @param bit * bit value * @param position * position * @return the expected value of * {@link RankedBitVector#countBits(boolean, long)} */ long countBits(BitVector bv, boolean bit, long position) { long ret = 0; for (long index = 0; index <= position; index++) { if (bv.getBit(index) == bit) { ret++; } } return ret; } /** * Returns the expected value of * {@link RankedBitVector#findPosition(boolean, long)}. * * @param bv * bit vector * @param bit * bit value * @param nOccurrences * number of occurrences * @return the expected value of * {@link RankedBitVector#findPosition(boolean, long)} */ long findPosition(BitVector bv, boolean bit, long nOccurrences) { if (nOccurrences == 0) { return RankedBitVector.NOT_FOUND; } long accumOccurrences = 0; for (long index = 0; index < bv.size(); index++) { if (bv.getBit(index) == bit) { accumOccurrences++; } if (accumOccurrences == nOccurrences) { return index; } } return RankedBitVector.NOT_FOUND; } @Test public void testAdd() { RankedBitVectorImpl bv = new RankedBitVectorImpl(); Assert.assertEquals(0, bv.size()); bv.addBit(true); Assert.assertEquals(1, bv.size()); Assert.assertEquals(true, bv.getBit(0)); bv.addBit(false); Assert.assertEquals(2, bv.size()); Assert.assertEquals(false, bv.getBit(1)); bv.addBit(false); Assert.assertEquals(3, bv.size()); Assert.assertEquals(false, bv.getBit(2)); for (int i = 3; i < 0x1000; i++) { boolean value = (i % 3) == 0; bv.addBit(value); Assert.assertEquals(value, bv.getBit(i)); assertCorrectCount(bv, i); } } @Test public void testCountBits() { final long aLargeNumber = 0x100000; PseudorandomNumberGenerator generator = new PseudorandomNumberGenerator( 0x1234); RankedBitVectorImpl bv = new RankedBitVectorImpl(new BitVectorImpl()); for (int i = 0; i < aLargeNumber; i++) { boolean value = generator.getPseudorandomBoolean(); bv.addBit(value); } for (int i = 0; i < aLargeNumber; i++) { if ((i % 0x6785) == 0) { assertCorrectCount(bv, i); } } } @Test public void testEmptyBitVector() { RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); Assert.assertEquals(0, bv0.size()); assertCorrectCount(bv0); assertCorrectFindPosition(bv0); Assert.assertNotEquals(bv0, new Object()); Assert.assertEquals(bv0, new BitVectorImpl()); RankedBitVector bv1 = new RankedBitVectorImpl(); RankedBitVectorImpl bv2 = new RankedBitVectorImpl(0); assertEqualsForBitVector(bv1, bv2); assertCorrectCount(bv2); assertCorrectFindPosition(bv2); } @Test public void testEqualityAndCopyConstructor() { final long aLargeNumber = 0x100000; RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); RankedBitVectorImpl bv1 = new RankedBitVectorImpl(); PseudorandomNumberGenerator generator = new PseudorandomNumberGenerator( 0x1234); for (int i = 0; i < aLargeNumber; i++) { boolean value = generator.getPseudorandomBoolean(); bv0.addBit(value); bv1.addBit(value); } assertEqualsForBitVector(bv0, bv1); RankedBitVectorImpl bv2 = new RankedBitVectorImpl(bv1); assertEqualsForBitVector(bv0, bv2); } @Test public void testFindPositionBlockSize() { for (int x = 0x80; x >= 0x40; x--) { testFindPositionWithBitVector(new RankedBitVectorImpl(0, 0x10, x)); } } void testFindPositionWithBitVector(RankedBitVectorImpl bv) { Assert.assertEquals(0, bv.size()); bv.addBit(true); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 0)); Assert.assertEquals(0, bv.findPosition(true, 1)); bv.addBit(true); bv.addBit(false); bv.addBit(true); bv.addBit(false); bv.addBit(false); bv.addBit(false); bv.addBit(true); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(false, 0)); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 0)); Assert.assertEquals(0, bv.findPosition(true, 1)); Assert.assertEquals(1, bv.findPosition(true, 2)); Assert.assertEquals(2, bv.findPosition(false, 1)); Assert.assertEquals(3, bv.findPosition(true, 3)); Assert.assertEquals(4, bv.findPosition(false, 2)); Assert.assertEquals(5, bv.findPosition(false, 3)); Assert.assertEquals(6, bv.findPosition(false, 4)); Assert.assertEquals(7, bv.findPosition(true, 4)); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(false, 5)); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 5)); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes0() { new RankedBitVectorImpl(1, 0, 0x40); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes1() { new RankedBitVectorImpl(1, 2, 0x3F); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes2() { new CountBitsArray(new BitVectorImpl(), 0); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes3() { new FindPositionArray(0, new BitVectorImpl(), true); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes4() { new FindPositionArray(new BitVectorImpl(), true, 0x3F); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes5() { new RankedBitVectorImpl(-1); } @Test public void testIterator() { RankedBitVectorImpl bv = new RankedBitVectorImpl(new BitVectorImpl()); PseudorandomNumberGenerator generator = new PseudorandomNumberGenerator( 0x7531); Assert.assertEquals(0, bv.size()); for (int i = 0; i < 0x300; i++) { bv.addBit(generator.getPseudorandomBoolean()); } Iterator<Boolean> it = bv.iterator(); for (int i = 0; i < 0x300; i++) { boolean value = it.next(); Assert.assertEquals(bv.getBit(i), value); } Assert.assertFalse(it.hasNext()); } @Test public void testSize() { { RankedBitVectorImpl bv = new RankedBitVectorImpl(0x100); Assert.assertEquals(0x100, bv.size()); bv.addBit(false); bv.addBit(true); Assert.assertEquals(0x102, bv.size()); assertCorrectCount(bv); assertCorrectFindPosition(bv); } { RankedBitVectorImpl bv = new RankedBitVectorImpl(); Assert.assertEquals(0, bv.size()); for (int i = 0; i < 0x300; i++) { bv.addBit((i % 5) == 0); Assert.assertEquals(i + 1, bv.size()); } assertCorrectCount(bv); assertCorrectFindPosition(bv); } } @Test public void testToString() { RankedBitVectorImpl bv = new RankedBitVectorImpl(); for (int i = 0; i < 0x10; i++) { boolean value = (i % 3) == 0; bv.addBit(value); } Assert.assertEquals("1001001001001001", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); for (int i = 0; i < 0x10; i++) { boolean value = (i % 2) == 0; bv.addBit(value); } Assert.assertEquals("10010010010010011010101010101010", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); for (int i = 0; i < 0x20; i++) { bv.setBit(i, bv.getBit(i)); } Assert.assertEquals("10010010010010011010101010101010", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); for (int i = 0; i < 0x20; i++) { bv.setBit(i, !bv.getBit(i)); } Assert.assertEquals("01101101101101100101010101010101", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); } @Test public void testToStringOfAuxClasses() { BitVectorImpl bv = new BitVectorImpl(); bv.addBit(true); bv.addBit(false); bv.addBit(true); bv.addBit(true); bv.addBit(false); bv.addBit(false); bv.addBit(false); bv.addBit(true); CountBitsArray cba = new CountBitsArray(bv, 2); Assert.assertEquals("[1, 3, 3, 4]", cba.toString()); FindPositionArray fpa = new FindPositionArray(2, bv, false); Assert.assertEquals("[-1, 4, 6]", fpa.toString()); Assert.assertEquals(RankedBitVector.NOT_FOUND, fpa.findPosition(0)); Assert.assertEquals(4, fpa.findPosition(2)); } @Test public void testValidInitialSizes() { new RankedBitVectorImpl(1, 1, 0x40); new RankedBitVectorImpl(1, 2, 0x40); new CountBitsArray(new BitVectorImpl(), 1); new FindPositionArray(1, new BitVectorImpl(), true); new FindPositionArray(new BitVectorImpl(), true, 0x40); new RankedBitVectorImpl(0); } }
wdtk-storage/src/test/java/org/wikidata/wdtk/storage/datastructure/impl/RankedBitVectorImplTest.java
package org.wikidata.wdtk.storage.datastructure.impl; /* * #%L * Wikidata Toolkit Data Model * %% * Copyright (C) 2014 Wikidata Toolkit Developers * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.Iterator; import org.junit.Assert; import org.junit.Test; import org.wikidata.wdtk.storage.datastructure.intf.BitVector; import org.wikidata.wdtk.storage.datastructure.intf.RankedBitVector; /** * Test class for {@link RankedRankedBitVectorImpl}. * * @author Julian Mendez * */ public class RankedBitVectorImplTest { void assertCorrectCount(RankedBitVector bv) { for (long index = 0; index < bv.size(); index++) { assertCorrectCount(bv, index); } } void assertCorrectCount(RankedBitVector bv, long position) { { long expectedCount = countBits(bv, false, position); long computedCount = bv.countBits(false, position); Assert.assertEquals(expectedCount, computedCount); } { long expectedCount = countBits(bv, true, position); long computedCount = bv.countBits(true, position); Assert.assertEquals(expectedCount, computedCount); } } void assertCorrectFindPosition(RankedBitVector bv) { for (long index = 0; index < bv.size(); index++) { assertCorrectFindPosition(bv, index); } } void assertCorrectFindPosition(RankedBitVector bv, long nOccurrences) { { long expectedFindPosition = findPosition(bv, false, nOccurrences); long computedFindPosition = bv.findPosition(false, nOccurrences); Assert.assertEquals(expectedFindPosition, computedFindPosition); } { long expectedFindPosition = findPosition(bv, true, nOccurrences); long computedFindPosition = bv.findPosition(true, nOccurrences); Assert.assertEquals(expectedFindPosition, computedFindPosition); } } void assertEqualsForBitVector(RankedBitVector bv0, BitVector bv1) { Assert.assertEquals(bv0, bv0); Assert.assertEquals(bv0, bv1); Assert.assertEquals(bv1, bv0); Assert.assertEquals(bv1, bv1); Assert.assertEquals(bv0.hashCode(), bv1.hashCode()); } long countBits(BitVector bv, boolean bit, long position) { long ret = 0; for (long index = 0; index <= position; index++) { if (bv.getBit(index) == bit) { ret++; } } return ret; } long findPosition(BitVector bv, boolean bit, long nOccurrences) { if (nOccurrences == 0) { return RankedBitVector.NOT_FOUND; } long accumOccurrences = 0; for (long index = 0; index < bv.size(); index++) { if (bv.getBit(index) == bit) { accumOccurrences++; } if (accumOccurrences == nOccurrences) { return index; } } return RankedBitVector.NOT_FOUND; } @Test public void testAdd() { RankedBitVectorImpl bv = new RankedBitVectorImpl(); Assert.assertEquals(0, bv.size()); bv.addBit(true); Assert.assertEquals(1, bv.size()); Assert.assertEquals(true, bv.getBit(0)); bv.addBit(false); Assert.assertEquals(2, bv.size()); Assert.assertEquals(false, bv.getBit(1)); bv.addBit(false); Assert.assertEquals(3, bv.size()); Assert.assertEquals(false, bv.getBit(2)); for (int i = 3; i < 0x1000; i++) { boolean value = (i % 3) == 0; bv.addBit(value); Assert.assertEquals(value, bv.getBit(i)); assertCorrectCount(bv, i); } } @Test public void testCountBits() { final long aLargeNumber = 0x100000; PseudorandomNumberGenerator generator = new PseudorandomNumberGenerator( 0x1234); RankedBitVectorImpl bv = new RankedBitVectorImpl(new BitVectorImpl()); for (int i = 0; i < aLargeNumber; i++) { boolean value = generator.getPseudorandomBoolean(); bv.addBit(value); } for (int i = 0; i < aLargeNumber; i++) { if ((i % 0x6785) == 0) { assertCorrectCount(bv, i); } } } @Test public void testEmptyBitVector() { RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); RankedBitVector bv1 = new RankedBitVectorImpl(); assertEqualsForBitVector(bv0, bv1); assertCorrectCount(bv0); assertCorrectCount(bv1); assertCorrectFindPosition(bv0); assertCorrectFindPosition(bv1); RankedBitVectorImpl bv2 = new RankedBitVectorImpl(0); assertEqualsForBitVector(bv1, bv2); assertCorrectCount(bv2); assertCorrectFindPosition(bv2); Assert.assertNotEquals(bv0, new Object()); Assert.assertEquals(bv0, new BitVectorImpl()); } @Test public void testEqualityAndCopyConstructor() { final long aLargeNumber = 0x100000; RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); RankedBitVectorImpl bv1 = new RankedBitVectorImpl(); PseudorandomNumberGenerator generator = new PseudorandomNumberGenerator( 0x1234); for (int i = 0; i < aLargeNumber; i++) { boolean value = generator.getPseudorandomBoolean(); bv0.addBit(value); bv1.addBit(value); } assertEqualsForBitVector(bv0, bv1); RankedBitVectorImpl bv2 = new RankedBitVectorImpl(bv1); assertEqualsForBitVector(bv0, bv2); } @Test public void testFindPositionBlockSize() { for (int x = 0x80; x >= 0x40; x--) { testFindPositionWithBitVector(new RankedBitVectorImpl(0, 0x10, x)); } } void testFindPositionWithBitVector(RankedBitVectorImpl bv) { Assert.assertEquals(0, bv.size()); bv.addBit(true); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 0)); Assert.assertEquals(0, bv.findPosition(true, 1)); bv.addBit(true); bv.addBit(false); bv.addBit(true); bv.addBit(false); bv.addBit(false); bv.addBit(false); bv.addBit(true); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(false, 0)); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 0)); Assert.assertEquals(0, bv.findPosition(true, 1)); Assert.assertEquals(1, bv.findPosition(true, 2)); Assert.assertEquals(2, bv.findPosition(false, 1)); Assert.assertEquals(3, bv.findPosition(true, 3)); Assert.assertEquals(4, bv.findPosition(false, 2)); Assert.assertEquals(5, bv.findPosition(false, 3)); Assert.assertEquals(6, bv.findPosition(false, 4)); Assert.assertEquals(7, bv.findPosition(true, 4)); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(false, 5)); Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 5)); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes0() { new RankedBitVectorImpl(1, 0, 0x40); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes1() { new RankedBitVectorImpl(1, 2, 0x3F); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes2() { new CountBitsArray(new BitVectorImpl(), 0); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes3() { new FindPositionArray(0, new BitVectorImpl(), true); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes4() { new FindPositionArray(new BitVectorImpl(), true, 0x3F); } @Test(expected = IllegalArgumentException.class) public void testInvalidInitialSizes5() { new RankedBitVectorImpl(-1); } @Test public void testIterator() { RankedBitVectorImpl bv = new RankedBitVectorImpl(new BitVectorImpl()); Assert.assertEquals(0, bv.size()); for (int i = 0; i < 0x300; i++) { bv.addBit((i % 5) == 0); } Iterator<Boolean> it = bv.iterator(); for (int i = 0; i < 0x300; i++) { boolean value = it.next(); Assert.assertEquals(bv.getBit(i), value); } Assert.assertFalse(it.hasNext()); } @Test public void testSize() { { RankedBitVectorImpl bv = new RankedBitVectorImpl(0x100); Assert.assertEquals(0x100, bv.size()); bv.addBit(false); bv.addBit(true); Assert.assertEquals(0x102, bv.size()); assertCorrectCount(bv); assertCorrectFindPosition(bv); } { RankedBitVectorImpl bv = new RankedBitVectorImpl(); Assert.assertEquals(0, bv.size()); for (int i = 0; i < 0x300; i++) { bv.addBit((i % 5) == 0); Assert.assertEquals(i + 1, bv.size()); } assertCorrectCount(bv); assertCorrectFindPosition(bv); } } @Test public void testToString() { RankedBitVectorImpl bv = new RankedBitVectorImpl(); for (int i = 0; i < 0x10; i++) { boolean value = (i % 3) == 0; bv.addBit(value); } Assert.assertEquals("1001001001001001", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); for (int i = 0; i < 0x10; i++) { boolean value = (i % 2) == 0; bv.addBit(value); } Assert.assertEquals("10010010010010011010101010101010", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); for (int i = 0; i < 0x20; i++) { bv.setBit(i, bv.getBit(i)); } Assert.assertEquals("10010010010010011010101010101010", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); for (int i = 0; i < 0x20; i++) { bv.setBit(i, !bv.getBit(i)); } Assert.assertEquals("01101101101101100101010101010101", bv.toString()); assertCorrectCount(bv); assertCorrectFindPosition(bv); } @Test public void testToStringOfAuxClasses() { BitVectorImpl bv = new BitVectorImpl(); bv.addBit(true); bv.addBit(false); bv.addBit(true); bv.addBit(true); bv.addBit(false); bv.addBit(false); bv.addBit(false); bv.addBit(true); CountBitsArray cba = new CountBitsArray(bv, 2); Assert.assertEquals("[1, 3, 3, 4]", cba.toString()); FindPositionArray fpa = new FindPositionArray(2, bv, false); Assert.assertEquals("[-1, 4, 6]", fpa.toString()); Assert.assertEquals(RankedBitVector.NOT_FOUND, fpa.findPosition(0)); Assert.assertEquals(4, fpa.findPosition(2)); } @Test public void testValidInitialSizes() { new RankedBitVectorImpl(1, 1, 0x40); new RankedBitVectorImpl(1, 2, 0x40); new CountBitsArray(new BitVectorImpl(), 1); new FindPositionArray(1, new BitVectorImpl(), true); new FindPositionArray(new BitVectorImpl(), true, 0x40); new RankedBitVectorImpl(0); } }
Reduce redundancy in unit tests
wdtk-storage/src/test/java/org/wikidata/wdtk/storage/datastructure/impl/RankedBitVectorImplTest.java
Reduce redundancy in unit tests
<ide><path>dtk-storage/src/test/java/org/wikidata/wdtk/storage/datastructure/impl/RankedBitVectorImplTest.java <ide> */ <ide> public class RankedBitVectorImplTest { <ide> <add> /** <add> * Asserts that for every position in a bit vector, <add> * {@link RankedBitVector#countBits(boolean, long)} works as expected. <add> * <add> * @param bv <add> * bit vector <add> */ <ide> void assertCorrectCount(RankedBitVector bv) { <ide> for (long index = 0; index < bv.size(); index++) { <ide> assertCorrectCount(bv, index); <ide> } <ide> } <ide> <add> /** <add> * Asserts that {@link RankedBitVector#countBits(boolean, long)} works as <add> * expected at a particular position. <add> * <add> * @param bv <add> * bit vector <add> * @param position <add> * position <add> */ <ide> void assertCorrectCount(RankedBitVector bv, long position) { <ide> { <ide> long expectedCount = countBits(bv, false, position); <ide> } <ide> } <ide> <add> /** <add> * Asserts that for every number of occurrences of a bit value in a bit <add> * vector, {@link RankedBitVector#findPosition(boolean, long)} works as <add> * expected. <add> * <add> * @param bv <add> * bit vector <add> */ <ide> void assertCorrectFindPosition(RankedBitVector bv) { <ide> for (long index = 0; index < bv.size(); index++) { <ide> assertCorrectFindPosition(bv, index); <ide> } <ide> } <ide> <add> /** <add> * Asserts that {@link RankedBitVector#findPosition(boolean, long)} works as <add> * expected considering the given number of occurrences of a bit value. <add> * <add> * @param bv <add> * bit vector <add> * @param nOccurrences <add> * number of occurrences <add> */ <ide> void assertCorrectFindPosition(RankedBitVector bv, long nOccurrences) { <ide> { <ide> long expectedFindPosition = findPosition(bv, false, nOccurrences); <ide> } <ide> } <ide> <del> void assertEqualsForBitVector(RankedBitVector bv0, BitVector bv1) { <add> /** <add> * Asserts that two ranked bit vectors are equal, and also that the first <add> * bit vector is equal to itself. <add> * <add> * @param bv0 <add> * one bit vector <add> * @param bv1 <add> * another bit vector <add> */ <add> void assertEqualsForBitVector(RankedBitVector bv0, RankedBitVector bv1) { <ide> Assert.assertEquals(bv0, bv0); <ide> Assert.assertEquals(bv0, bv1); <ide> Assert.assertEquals(bv1, bv0); <del> Assert.assertEquals(bv1, bv1); <ide> Assert.assertEquals(bv0.hashCode(), bv1.hashCode()); <ide> } <ide> <add> /** <add> * Returns the expected value of <add> * {@link RankedBitVector#countBits(boolean, long)}. <add> * <add> * @param bv <add> * bit vector <add> * @param bit <add> * bit value <add> * @param position <add> * position <add> * @return the expected value of <add> * {@link RankedBitVector#countBits(boolean, long)} <add> */ <ide> long countBits(BitVector bv, boolean bit, long position) { <ide> long ret = 0; <ide> for (long index = 0; index <= position; index++) { <ide> return ret; <ide> } <ide> <add> /** <add> * Returns the expected value of <add> * {@link RankedBitVector#findPosition(boolean, long)}. <add> * <add> * @param bv <add> * bit vector <add> * @param bit <add> * bit value <add> * @param nOccurrences <add> * number of occurrences <add> * @return the expected value of <add> * {@link RankedBitVector#findPosition(boolean, long)} <add> */ <ide> long findPosition(BitVector bv, boolean bit, long nOccurrences) { <ide> if (nOccurrences == 0) { <ide> return RankedBitVector.NOT_FOUND; <ide> @Test <ide> public void testEmptyBitVector() { <ide> RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); <add> Assert.assertEquals(0, bv0.size()); <add> assertCorrectCount(bv0); <add> assertCorrectFindPosition(bv0); <add> Assert.assertNotEquals(bv0, new Object()); <add> Assert.assertEquals(bv0, new BitVectorImpl()); <add> <ide> RankedBitVector bv1 = new RankedBitVectorImpl(); <del> assertEqualsForBitVector(bv0, bv1); <del> assertCorrectCount(bv0); <del> assertCorrectCount(bv1); <del> assertCorrectFindPosition(bv0); <del> assertCorrectFindPosition(bv1); <del> <ide> RankedBitVectorImpl bv2 = new RankedBitVectorImpl(0); <ide> assertEqualsForBitVector(bv1, bv2); <ide> assertCorrectCount(bv2); <ide> assertCorrectFindPosition(bv2); <del> <del> Assert.assertNotEquals(bv0, new Object()); <del> Assert.assertEquals(bv0, new BitVectorImpl()); <ide> } <ide> <ide> @Test <ide> Assert.assertEquals(RankedBitVector.NOT_FOUND, <ide> bv.findPosition(false, 5)); <ide> Assert.assertEquals(RankedBitVector.NOT_FOUND, bv.findPosition(true, 5)); <del> <ide> } <ide> <ide> @Test(expected = IllegalArgumentException.class) <ide> @Test <ide> public void testIterator() { <ide> RankedBitVectorImpl bv = new RankedBitVectorImpl(new BitVectorImpl()); <add> PseudorandomNumberGenerator generator = new PseudorandomNumberGenerator( <add> 0x7531); <ide> Assert.assertEquals(0, bv.size()); <ide> for (int i = 0; i < 0x300; i++) { <del> bv.addBit((i % 5) == 0); <del> } <del> <add> bv.addBit(generator.getPseudorandomBoolean()); <add> } <ide> Iterator<Boolean> it = bv.iterator(); <ide> for (int i = 0; i < 0x300; i++) { <ide> boolean value = it.next(); <ide> Assert.assertEquals("01101101101101100101010101010101", bv.toString()); <ide> assertCorrectCount(bv); <ide> assertCorrectFindPosition(bv); <del> <ide> } <ide> <ide> @Test
Java
mpl-2.0
16899d2621c850610158ba6842b557f6ec199b5c
0
Angelfirenze/rhino,Distrotech/rhino,tuchida/rhino,sainaen/rhino,tntim96/rhino-apigee,ashwinrayaprolu1984/rhino,tntim96/htmlunit-rhino-fork,sainaen/rhino,tejassaoji/RhinoCoarseTainting,sainaen/rhino,tntim96/rhino-jscover-repackaged,tejassaoji/RhinoCoarseTainting,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,swannodette/rhino,ashwinrayaprolu1984/rhino,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,rasmuserik/rhino,rasmuserik/rhino,AlexTrotsenko/rhino,ashwinrayaprolu1984/rhino,ashwinrayaprolu1984/rhino,Angelfirenze/rhino,tntim96/rhino-jscover,Angelfirenze/rhino,sainaen/rhino,sainaen/rhino,sam/htmlunit-rhino-fork,Pilarbrist/rhino,qhanam/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-apigee,AlexTrotsenko/rhino,InstantWebP2P/rhino-android,tejassaoji/RhinoCoarseTainting,sainaen/rhino,Distrotech/rhino,jsdoc3/rhino,sainaen/rhino,tntim96/rhino-jscover-repackaged,InstantWebP2P/rhino-android,tuchida/rhino,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,tntim96/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,qhanam/rhino,AlexTrotsenko/rhino,Pilarbrist/rhino,lv7777/egit_test,swannodette/rhino,sam/htmlunit-rhino-fork,qhanam/rhino,swannodette/rhino,tntim96/rhino-jscover,tuchida/rhino,sam/htmlunit-rhino-fork,AlexTrotsenko/rhino,swannodette/rhino,AlexTrotsenko/rhino,ashwinrayaprolu1984/rhino,tejassaoji/RhinoCoarseTainting,AlexTrotsenko/rhino,swannodette/rhino,qhanam/rhino,Pilarbrist/rhino,lv7777/egit_test,Angelfirenze/rhino,lv7777/egit_test,Pilarbrist/rhino,swannodette/rhino,Pilarbrist/rhino,jsdoc3/rhino,Pilarbrist/rhino,lv7777/egit_test,Angelfirenze/rhino,tuchida/rhino,tuchida/rhino,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,lv7777/egit_test,lv7777/egit_test,tuchida/rhino,Angelfirenze/rhino,jsdoc3/rhino,swannodette/rhino,AlexTrotsenko/rhino,tuchida/rhino,tntim96/rhino-apigee,lv7777/egit_test,tejassaoji/RhinoCoarseTainting
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Kemal Bayram * Igor Bukanov * Bob Jervis * Roger Lawrence * Andi Vajda * Hannes Wallnoefer * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.optimizer; import org.mozilla.javascript.*; import org.mozilla.javascript.ast.FunctionNode; import org.mozilla.javascript.ast.Jump; import org.mozilla.javascript.ast.Name; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.classfile.*; import java.util.*; import java.lang.reflect.Constructor; /** * This class generates code for a given IR tree. * * @author Norris Boyd * @author Roger Lawrence */ public class Codegen implements Evaluator { public void captureStackInfo(RhinoException ex) { throw new UnsupportedOperationException(); } public String getSourcePositionFromStack(Context cx, int[] linep) { throw new UnsupportedOperationException(); } public String getPatchedStack(RhinoException ex, String nativeStackTrace) { throw new UnsupportedOperationException(); } public List<String> getScriptStack(RhinoException ex) { throw new UnsupportedOperationException(); } public void setEvalScriptFlag(Script script) { throw new UnsupportedOperationException(); } public Object compile(CompilerEnvirons compilerEnv, ScriptNode tree, String encodedSource, boolean returnFunction) { int serial; synchronized (globalLock) { serial = ++globalSerialClassCounter; } String baseName = "c"; if (tree.getSourceName().length() > 0) { baseName = tree.getSourceName().replaceAll("\\W", "_"); if (!Character.isJavaIdentifierStart(baseName.charAt(0))) { baseName = "_" + baseName; } } String mainClassName = "org.mozilla.javascript.gen." + baseName + "_" + serial; byte[] mainClassBytes = compileToClassFile(compilerEnv, mainClassName, tree, encodedSource, returnFunction); return new Object[] { mainClassName, mainClassBytes }; } public Script createScriptObject(Object bytecode, Object staticSecurityDomain) { Class<?> cl = defineClass(bytecode, staticSecurityDomain); Script script; try { script = (Script)cl.newInstance(); } catch (Exception ex) { throw new RuntimeException ("Unable to instantiate compiled class:" + ex.toString()); } return script; } public Function createFunctionObject(Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain) { Class<?> cl = defineClass(bytecode, staticSecurityDomain); NativeFunction f; try { Constructor<?>ctor = cl.getConstructors()[0]; Object[] initArgs = { scope, cx, Integer.valueOf(0) }; f = (NativeFunction)ctor.newInstance(initArgs); } catch (Exception ex) { throw new RuntimeException ("Unable to instantiate compiled class:"+ex.toString()); } return f; } private Class<?> defineClass(Object bytecode, Object staticSecurityDomain) { Object[] nameBytesPair = (Object[])bytecode; String className = (String)nameBytesPair[0]; byte[] classBytes = (byte[])nameBytesPair[1]; // The generated classes in this case refer only to Rhino classes // which must be accessible through this class loader ClassLoader rhinoLoader = getClass().getClassLoader(); GeneratedClassLoader loader; loader = SecurityController.createLoader(rhinoLoader, staticSecurityDomain); Exception e; try { Class<?> cl = loader.defineClass(className, classBytes); loader.linkClass(cl); return cl; } catch (SecurityException x) { e = x; } catch (IllegalArgumentException x) { e = x; } throw new RuntimeException("Malformed optimizer package " + e); } byte[] compileToClassFile(CompilerEnvirons compilerEnv, String mainClassName, ScriptNode scriptOrFn, String encodedSource, boolean returnFunction) { this.compilerEnv = compilerEnv; transform(scriptOrFn); if (Token.printTrees) { System.out.println(scriptOrFn.toStringTree(scriptOrFn)); } if (returnFunction) { scriptOrFn = scriptOrFn.getFunctionNode(0); } initScriptNodesData(scriptOrFn); this.mainClassName = mainClassName; this.mainClassSignature = ClassFileWriter.classNameToSignature(mainClassName); try { return generateCode(encodedSource); } catch (ClassFileWriter.ClassFileFormatException e) { throw reportClassFileFormatException(scriptOrFn, e.getMessage()); } } private RuntimeException reportClassFileFormatException( ScriptNode scriptOrFn, String message) { String msg = scriptOrFn instanceof FunctionNode ? ScriptRuntime.getMessage2("msg.while.compiling.fn", ((FunctionNode)scriptOrFn).getFunctionName(), message) : ScriptRuntime.getMessage1("msg.while.compiling.script", message); return Context.reportRuntimeError(msg, scriptOrFn.getSourceName(), scriptOrFn.getLineno(), null, 0); } private void transform(ScriptNode tree) { initOptFunctions_r(tree); int optLevel = compilerEnv.getOptimizationLevel(); Map<String,OptFunctionNode> possibleDirectCalls = null; if (optLevel > 0) { /* * Collect all of the contained functions into a hashtable * so that the call optimizer can access the class name & parameter * count for any call it encounters */ if (tree.getType() == Token.SCRIPT) { int functionCount = tree.getFunctionCount(); for (int i = 0; i != functionCount; ++i) { OptFunctionNode ofn = OptFunctionNode.get(tree, i); if (ofn.fnode.getFunctionType() == FunctionNode.FUNCTION_STATEMENT) { String name = ofn.fnode.getName(); if (name.length() != 0) { if (possibleDirectCalls == null) { possibleDirectCalls = new HashMap<String,OptFunctionNode>(); } possibleDirectCalls.put(name, ofn); } } } } } if (possibleDirectCalls != null) { directCallTargets = new ObjArray(); } OptTransformer ot = new OptTransformer(possibleDirectCalls, directCallTargets); ot.transform(tree); if (optLevel > 0) { (new Optimizer()).optimize(tree); } } private static void initOptFunctions_r(ScriptNode scriptOrFn) { for (int i = 0, N = scriptOrFn.getFunctionCount(); i != N; ++i) { FunctionNode fn = scriptOrFn.getFunctionNode(i); new OptFunctionNode(fn); initOptFunctions_r(fn); } } private void initScriptNodesData(ScriptNode scriptOrFn) { ObjArray x = new ObjArray(); collectScriptNodes_r(scriptOrFn, x); int count = x.size(); scriptOrFnNodes = new ScriptNode[count]; x.toArray(scriptOrFnNodes); scriptOrFnIndexes = new ObjToIntMap(count); for (int i = 0; i != count; ++i) { scriptOrFnIndexes.put(scriptOrFnNodes[i], i); } } private static void collectScriptNodes_r(ScriptNode n, ObjArray x) { x.add(n); int nestedCount = n.getFunctionCount(); for (int i = 0; i != nestedCount; ++i) { collectScriptNodes_r(n.getFunctionNode(i), x); } } private byte[] generateCode(String encodedSource) { boolean hasScript = (scriptOrFnNodes[0].getType() == Token.SCRIPT); boolean hasFunctions = (scriptOrFnNodes.length > 1 || !hasScript); String sourceFile = null; if (compilerEnv.isGenerateDebugInfo()) { sourceFile = scriptOrFnNodes[0].getSourceName(); } ClassFileWriter cfw = new ClassFileWriter(mainClassName, SUPER_CLASS_NAME, sourceFile); cfw.addField(ID_FIELD_NAME, "I", ClassFileWriter.ACC_PRIVATE); cfw.addField(DIRECT_CALL_PARENT_FIELD, mainClassSignature, ClassFileWriter.ACC_PRIVATE); cfw.addField(REGEXP_ARRAY_FIELD_NAME, REGEXP_ARRAY_FIELD_TYPE, ClassFileWriter.ACC_PRIVATE); if (hasFunctions) { generateFunctionConstructor(cfw); } if (hasScript) { cfw.addInterface("org/mozilla/javascript/Script"); generateScriptCtor(cfw); generateMain(cfw); generateExecute(cfw); } generateCallMethod(cfw); generateResumeGenerator(cfw); generateNativeFunctionOverrides(cfw, encodedSource); int count = scriptOrFnNodes.length; for (int i = 0; i != count; ++i) { ScriptNode n = scriptOrFnNodes[i]; BodyCodegen bodygen = new BodyCodegen(); bodygen.cfw = cfw; bodygen.codegen = this; bodygen.compilerEnv = compilerEnv; bodygen.scriptOrFn = n; bodygen.scriptOrFnIndex = i; try { bodygen.generateBodyCode(); } catch (ClassFileWriter.ClassFileFormatException e) { throw reportClassFileFormatException(n, e.getMessage()); } if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); generateFunctionInit(cfw, ofn); if (ofn.isTargetOfDirectCall()) { emitDirectConstructor(cfw, ofn); } } } if (directCallTargets != null) { int N = directCallTargets.size(); for (int j = 0; j != N; ++j) { cfw.addField(getDirectTargetFieldName(j), mainClassSignature, ClassFileWriter.ACC_PRIVATE); } } emitRegExpInit(cfw); emitConstantDudeInitializers(cfw); return cfw.toByteArray(); } private void emitDirectConstructor(ClassFileWriter cfw, OptFunctionNode ofn) { /* we generate .. Scriptable directConstruct(<directCallArgs>) { Scriptable newInstance = createObject(cx, scope); Object val = <body-name>(cx, scope, newInstance, <directCallArgs>); if (val instanceof Scriptable) { return (Scriptable) val; } return newInstance; } */ cfw.startMethod(getDirectCtorName(ofn.fnode), getBodyMethodSignature(ofn.fnode), (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); int argCount = ofn.fnode.getParamCount(); int firstLocal = (4 + argCount * 3) + 1; cfw.addALoad(0); // this cfw.addALoad(1); // cx cfw.addALoad(2); // scope cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "org/mozilla/javascript/BaseFunction", "createObject", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(firstLocal); cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(firstLocal); for (int i = 0; i < argCount; i++) { cfw.addALoad(4 + (i * 3)); cfw.addDLoad(5 + (i * 3)); } cfw.addALoad(4 + argCount * 3); cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(ofn.fnode), getBodyMethodSignature(ofn.fnode)); int exitLabel = cfw.acquireLabel(); cfw.add(ByteCode.DUP); // make a copy of direct call result cfw.add(ByteCode.INSTANCEOF, "org/mozilla/javascript/Scriptable"); cfw.add(ByteCode.IFEQ, exitLabel); // cast direct call result cfw.add(ByteCode.CHECKCAST, "org/mozilla/javascript/Scriptable"); cfw.add(ByteCode.ARETURN); cfw.markLabel(exitLabel); cfw.addALoad(firstLocal); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)(firstLocal + 1)); } static boolean isGenerator(ScriptNode node) { return (node.getType() == Token.FUNCTION ) && ((FunctionNode)node).isGenerator(); } // How dispatch to generators works: // Two methods are generated corresponding to a user-written generator. // One of these creates a generator object (NativeGenerator), which is // returned to the user. The other method contains all of the body code // of the generator. // When a user calls a generator, the call() method dispatches control to // to the method that creates the NativeGenerator object. Subsequently when // the user invokes .next(), .send() or any such method on the generator // object, the resumeGenerator() below dispatches the call to the // method corresponding to the generator body. As a matter of convention // the generator body is given the name of the generator activation function // appended by "_gen". private void generateResumeGenerator(ClassFileWriter cfw) { boolean hasGenerators = false; for (int i=0; i < scriptOrFnNodes.length; i++) { if (isGenerator(scriptOrFnNodes[i])) hasGenerators = true; } // if there are no generators defined, we don't implement a // resumeGenerator(). The base class provides a default implementation. if (!hasGenerators) return; cfw.startMethod("resumeGenerator", "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "ILjava/lang/Object;" + "Ljava/lang/Object;)Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // load arguments for dispatch to the corresponding *_gen method cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(4); cfw.addALoad(5); cfw.addILoad(3); cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); int startSwitch = cfw.addTableSwitch(0, scriptOrFnNodes.length - 1); cfw.markTableSwitchDefault(startSwitch); int endlabel = cfw.acquireLabel(); for (int i = 0; i < scriptOrFnNodes.length; i++) { ScriptNode n = scriptOrFnNodes[i]; cfw.markTableSwitchCase(startSwitch, i, (short)6); if (isGenerator(n)) { String type = "(" + mainClassSignature + "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Ljava/lang/Object;" + "Ljava/lang/Object;I)Ljava/lang/Object;"; cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(n) + "_gen", type); cfw.add(ByteCode.ARETURN); } else { cfw.add(ByteCode.GOTO, endlabel); } } cfw.markLabel(endlabel); pushUndefined(cfw); cfw.add(ByteCode.ARETURN); // this method uses as many locals as there are arguments (hence 6) cfw.stopMethod((short)6); } private void generateCallMethod(ClassFileWriter cfw) { cfw.startMethod("call", "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Lorg/mozilla/javascript/Scriptable;" + "[Ljava/lang/Object;)Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // Generate code for: // if (!ScriptRuntime.hasTopCall(cx)) { // return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args); // } int nonTopCallLabel = cfw.acquireLabel(); cfw.addALoad(1); //cx cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "hasTopCall", "(Lorg/mozilla/javascript/Context;" +")Z"); cfw.add(ByteCode.IFNE, nonTopCallLabel); cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(3); cfw.addALoad(4); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "doTopCall", "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); cfw.add(ByteCode.ARETURN); cfw.markLabel(nonTopCallLabel); // Now generate switch to call the real methods cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(3); cfw.addALoad(4); int end = scriptOrFnNodes.length; boolean generateSwitch = (2 <= end); int switchStart = 0; int switchStackTop = 0; if (generateSwitch) { cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); // do switch from (1, end - 1) mapping 0 to // the default case switchStart = cfw.addTableSwitch(1, end - 1); } for (int i = 0; i != end; ++i) { ScriptNode n = scriptOrFnNodes[i]; if (generateSwitch) { if (i == 0) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } else { cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop); } } if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); if (ofn.isTargetOfDirectCall()) { int pcount = ofn.fnode.getParamCount(); if (pcount != 0) { // loop invariant: // stack top == arguments array from addALoad4() for (int p = 0; p != pcount; ++p) { cfw.add(ByteCode.ARRAYLENGTH); cfw.addPush(p); int undefArg = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.IF_ICMPLE, undefArg); // get array[p] cfw.addALoad(4); cfw.addPush(p); cfw.add(ByteCode.AALOAD); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(undefArg); pushUndefined(cfw); cfw.markLabel(beyond); // Only one push cfw.adjustStackTop(-1); cfw.addPush(0.0); // restore invariant cfw.addALoad(4); } } } } cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(n), getBodyMethodSignature(n)); cfw.add(ByteCode.ARETURN); } cfw.stopMethod((short)5); // 5: this, cx, scope, js this, args[] } private void generateMain(ClassFileWriter cfw) { cfw.startMethod("main", "([Ljava/lang/String;)V", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_STATIC)); // load new ScriptImpl() cfw.add(ByteCode.NEW, cfw.getClassName()); cfw.add(ByteCode.DUP); cfw.addInvoke(ByteCode.INVOKESPECIAL, cfw.getClassName(), "<init>", "()V"); // load 'args' cfw.add(ByteCode.ALOAD_0); // Call mainMethodClass.main(Script script, String[] args) cfw.addInvoke(ByteCode.INVOKESTATIC, mainMethodClass, "main", "(Lorg/mozilla/javascript/Script;[Ljava/lang/String;)V"); cfw.add(ByteCode.RETURN); // 1 = String[] args cfw.stopMethod((short)1); } private void generateExecute(ClassFileWriter cfw) { cfw.startMethod("exec", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); final int CONTEXT_ARG = 1; final int SCOPE_ARG = 2; cfw.addLoadThis(); cfw.addALoad(CONTEXT_ARG); cfw.addALoad(SCOPE_ARG); cfw.add(ByteCode.DUP); cfw.add(ByteCode.ACONST_NULL); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, cfw.getClassName(), "call", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); cfw.add(ByteCode.ARETURN); // 3 = this + context + scope cfw.stopMethod((short)3); } private void generateScriptCtor(ClassFileWriter cfw) { cfw.startMethod("<init>", "()V", ClassFileWriter.ACC_PUBLIC); cfw.addLoadThis(); cfw.addInvoke(ByteCode.INVOKESPECIAL, SUPER_CLASS_NAME, "<init>", "()V"); // set id to 0 cfw.addLoadThis(); cfw.addPush(0); cfw.add(ByteCode.PUTFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); cfw.add(ByteCode.RETURN); // 1 parameter = this cfw.stopMethod((short)1); } private void generateFunctionConstructor(ClassFileWriter cfw) { final int SCOPE_ARG = 1; final int CONTEXT_ARG = 2; final int ID_ARG = 3; cfw.startMethod("<init>", FUNCTION_CONSTRUCTOR_SIGNATURE, ClassFileWriter.ACC_PUBLIC); cfw.addALoad(0); cfw.addInvoke(ByteCode.INVOKESPECIAL, SUPER_CLASS_NAME, "<init>", "()V"); cfw.addLoadThis(); cfw.addILoad(ID_ARG); cfw.add(ByteCode.PUTFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); cfw.addLoadThis(); cfw.addALoad(CONTEXT_ARG); cfw.addALoad(SCOPE_ARG); int start = (scriptOrFnNodes[0].getType() == Token.SCRIPT) ? 1 : 0; int end = scriptOrFnNodes.length; if (start == end) throw badTree(); boolean generateSwitch = (2 <= end - start); int switchStart = 0; int switchStackTop = 0; if (generateSwitch) { cfw.addILoad(ID_ARG); // do switch from (start + 1, end - 1) mapping start to // the default case switchStart = cfw.addTableSwitch(start + 1, end - 1); } for (int i = start; i != end; ++i) { if (generateSwitch) { if (i == start) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } else { cfw.markTableSwitchCase(switchStart, i - 1 - start, switchStackTop); } } OptFunctionNode ofn = OptFunctionNode.get(scriptOrFnNodes[i]); cfw.addInvoke(ByteCode.INVOKESPECIAL, mainClassName, getFunctionInitMethodName(ofn), FUNCTION_INIT_SIGNATURE); cfw.add(ByteCode.RETURN); } // 4 = this + scope + context + id cfw.stopMethod((short)4); } private void generateFunctionInit(ClassFileWriter cfw, OptFunctionNode ofn) { final int CONTEXT_ARG = 1; final int SCOPE_ARG = 2; cfw.startMethod(getFunctionInitMethodName(ofn), FUNCTION_INIT_SIGNATURE, (short)(ClassFileWriter.ACC_PRIVATE | ClassFileWriter.ACC_FINAL)); // Call NativeFunction.initScriptFunction cfw.addLoadThis(); cfw.addALoad(CONTEXT_ARG); cfw.addALoad(SCOPE_ARG); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "org/mozilla/javascript/NativeFunction", "initScriptFunction", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")V"); // precompile all regexp literals int regexpCount = ofn.fnode.getRegexpCount(); if (regexpCount != 0) { cfw.addLoadThis(); pushRegExpArray(cfw, ofn.fnode, CONTEXT_ARG, SCOPE_ARG); cfw.add(ByteCode.PUTFIELD, mainClassName, REGEXP_ARRAY_FIELD_NAME, REGEXP_ARRAY_FIELD_TYPE); } cfw.add(ByteCode.RETURN); // 3 = (scriptThis/functionRef) + scope + context cfw.stopMethod((short)3); } private void generateNativeFunctionOverrides(ClassFileWriter cfw, String encodedSource) { // Override NativeFunction.getLanguageVersion() with // public int getLanguageVersion() { return <version-constant>; } cfw.startMethod("getLanguageVersion", "()I", ClassFileWriter.ACC_PUBLIC); cfw.addPush(compilerEnv.getLanguageVersion()); cfw.add(ByteCode.IRETURN); // 1: this and no argument or locals cfw.stopMethod((short)1); // The rest of NativeFunction overrides require specific code for each // script/function id final int Do_getFunctionName = 0; final int Do_getParamCount = 1; final int Do_getParamAndVarCount = 2; final int Do_getParamOrVarName = 3; final int Do_getEncodedSource = 4; final int Do_getParamOrVarConst = 5; final int SWITCH_COUNT = 6; for (int methodIndex = 0; methodIndex != SWITCH_COUNT; ++methodIndex) { if (methodIndex == Do_getEncodedSource && encodedSource == null) { continue; } // Generate: // prologue; // switch over function id to implement function-specific action // epilogue short methodLocals; switch (methodIndex) { case Do_getFunctionName: methodLocals = 1; // Only this cfw.startMethod("getFunctionName", "()Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamCount: methodLocals = 1; // Only this cfw.startMethod("getParamCount", "()I", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamAndVarCount: methodLocals = 1; // Only this cfw.startMethod("getParamAndVarCount", "()I", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamOrVarName: methodLocals = 1 + 1; // this + paramOrVarIndex cfw.startMethod("getParamOrVarName", "(I)Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamOrVarConst: methodLocals = 1 + 1 + 1; // this + paramOrVarName cfw.startMethod("getParamOrVarConst", "(I)Z", ClassFileWriter.ACC_PUBLIC); break; case Do_getEncodedSource: methodLocals = 1; // Only this cfw.startMethod("getEncodedSource", "()Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC); cfw.addPush(encodedSource); break; default: throw Kit.codeBug(); } int count = scriptOrFnNodes.length; int switchStart = 0; int switchStackTop = 0; if (count > 1) { // Generate switch but only if there is more then one // script/function cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); // do switch from 1 .. count - 1 mapping 0 to the default case switchStart = cfw.addTableSwitch(1, count - 1); } for (int i = 0; i != count; ++i) { ScriptNode n = scriptOrFnNodes[i]; if (i == 0) { if (count > 1) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } } else { cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop); } // Impelemnet method-specific switch code switch (methodIndex) { case Do_getFunctionName: // Push function name if (n.getType() == Token.SCRIPT) { cfw.addPush(""); } else { String name = ((FunctionNode)n).getName(); cfw.addPush(name); } cfw.add(ByteCode.ARETURN); break; case Do_getParamCount: // Push number of defined parameters cfw.addPush(n.getParamCount()); cfw.add(ByteCode.IRETURN); break; case Do_getParamAndVarCount: // Push number of defined parameters and declared variables cfw.addPush(n.getParamAndVarCount()); cfw.add(ByteCode.IRETURN); break; case Do_getParamOrVarName: // Push name of parameter using another switch // over paramAndVarCount int paramAndVarCount = n.getParamAndVarCount(); if (paramAndVarCount == 0) { // The runtime should never call the method in this // case but to make bytecode verifier happy return null // as throwing execption takes more code cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.ARETURN); } else if (paramAndVarCount == 1) { // As above do not check for valid index but always // return the name of the first param cfw.addPush(n.getParamOrVarName(0)); cfw.add(ByteCode.ARETURN); } else { // Do switch over getParamOrVarName cfw.addILoad(1); // param or var index // do switch from 1 .. paramAndVarCount - 1 mapping 0 // to the default case int paramSwitchStart = cfw.addTableSwitch( 1, paramAndVarCount - 1); for (int j = 0; j != paramAndVarCount; ++j) { if (cfw.getStackTop() != 0) Kit.codeBug(); String s = n.getParamOrVarName(j); if (j == 0) { cfw.markTableSwitchDefault(paramSwitchStart); } else { cfw.markTableSwitchCase(paramSwitchStart, j - 1, 0); } cfw.addPush(s); cfw.add(ByteCode.ARETURN); } } break; case Do_getParamOrVarConst: // Push name of parameter using another switch // over paramAndVarCount paramAndVarCount = n.getParamAndVarCount(); boolean [] constness = n.getParamAndVarConst(); if (paramAndVarCount == 0) { // The runtime should never call the method in this // case but to make bytecode verifier happy return null // as throwing execption takes more code cfw.add(ByteCode.ICONST_0); cfw.add(ByteCode.IRETURN); } else if (paramAndVarCount == 1) { // As above do not check for valid index but always // return the name of the first param cfw.addPush(constness[0]); cfw.add(ByteCode.IRETURN); } else { // Do switch over getParamOrVarName cfw.addILoad(1); // param or var index // do switch from 1 .. paramAndVarCount - 1 mapping 0 // to the default case int paramSwitchStart = cfw.addTableSwitch( 1, paramAndVarCount - 1); for (int j = 0; j != paramAndVarCount; ++j) { if (cfw.getStackTop() != 0) Kit.codeBug(); if (j == 0) { cfw.markTableSwitchDefault(paramSwitchStart); } else { cfw.markTableSwitchCase(paramSwitchStart, j - 1, 0); } cfw.addPush(constness[j]); cfw.add(ByteCode.IRETURN); } } break; case Do_getEncodedSource: // Push number encoded source start and end // to prepare for encodedSource.substring(start, end) cfw.addPush(n.getEncodedSourceStart()); cfw.addPush(n.getEncodedSourceEnd()); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "substring", "(II)Ljava/lang/String;"); cfw.add(ByteCode.ARETURN); break; default: throw Kit.codeBug(); } } cfw.stopMethod(methodLocals); } } private void emitRegExpInit(ClassFileWriter cfw) { // precompile all regexp literals int totalRegCount = 0; for (int i = 0; i != scriptOrFnNodes.length; ++i) { totalRegCount += scriptOrFnNodes[i].getRegexpCount(); } if (totalRegCount == 0) { return; } cfw.startMethod(REGEXP_INIT_METHOD_NAME, REGEXP_INIT_METHOD_SIGNATURE, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE | ClassFileWriter.ACC_SYNCHRONIZED)); cfw.addField("_reInitDone", "Z", (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); cfw.add(ByteCode.GETSTATIC, mainClassName, "_reInitDone", "Z"); int doInit = cfw.acquireLabel(); cfw.add(ByteCode.IFEQ, doInit); cfw.add(ByteCode.RETURN); cfw.markLabel(doInit); for (int i = 0; i != scriptOrFnNodes.length; ++i) { ScriptNode n = scriptOrFnNodes[i]; int regCount = n.getRegexpCount(); for (int j = 0; j != regCount; ++j) { String reFieldName = getCompiledRegexpName(n, j); String reFieldType = "Ljava/lang/Object;"; String reString = n.getRegexpString(j); String reFlags = n.getRegexpFlags(j); cfw.addField(reFieldName, reFieldType, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); cfw.addALoad(0); // proxy cfw.addALoad(1); // context cfw.addPush(reString); if (reFlags == null) { cfw.add(ByteCode.ACONST_NULL); } else { cfw.addPush(reFlags); } cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/RegExpProxy", "compileRegExp", "(Lorg/mozilla/javascript/Context;" +"Ljava/lang/String;Ljava/lang/String;" +")Ljava/lang/Object;"); cfw.add(ByteCode.PUTSTATIC, mainClassName, reFieldName, reFieldType); } } cfw.addPush(1); cfw.add(ByteCode.PUTSTATIC, mainClassName, "_reInitDone", "Z"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)2); } private void emitConstantDudeInitializers(ClassFileWriter cfw) { int N = itsConstantListSize; if (N == 0) return; cfw.startMethod("<clinit>", "()V", (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_FINAL)); double[] array = itsConstantList; for (int i = 0; i != N; ++i) { double num = array[i]; String constantName = "_k" + i; String constantType = getStaticConstantWrapperType(num); cfw.addField(constantName, constantType, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); int inum = (int)num; if (inum == num) { cfw.add(ByteCode.NEW, "java/lang/Integer"); cfw.add(ByteCode.DUP); cfw.addPush(inum); cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Integer", "<init>", "(I)V"); } else { cfw.addPush(num); addDoubleWrap(cfw); } cfw.add(ByteCode.PUTSTATIC, mainClassName, constantName, constantType); } cfw.add(ByteCode.RETURN); cfw.stopMethod((short)0); } void pushRegExpArray(ClassFileWriter cfw, ScriptNode n, int contextArg, int scopeArg) { int regexpCount = n.getRegexpCount(); if (regexpCount == 0) throw badTree(); cfw.addPush(regexpCount); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); cfw.addALoad(contextArg); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "checkRegExpProxy", "(Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/RegExpProxy;"); // Stack: proxy, array cfw.add(ByteCode.DUP); cfw.addALoad(contextArg); cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, REGEXP_INIT_METHOD_NAME, REGEXP_INIT_METHOD_SIGNATURE); for (int i = 0; i != regexpCount; ++i) { // Stack: proxy, array cfw.add(ByteCode.DUP2); cfw.addALoad(contextArg); cfw.addALoad(scopeArg); cfw.add(ByteCode.GETSTATIC, mainClassName, getCompiledRegexpName(n, i), "Ljava/lang/Object;"); // Stack: compiledRegExp, scope, cx, proxy, array, proxy, array cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/RegExpProxy", "wrapRegExp", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); // Stack: wrappedRegExp, array, proxy, array cfw.addPush(i); cfw.add(ByteCode.SWAP); cfw.add(ByteCode.AASTORE); // Stack: proxy, array } // remove proxy cfw.add(ByteCode.POP); } void pushNumberAsObject(ClassFileWriter cfw, double num) { if (num == 0.0) { if (1 / num > 0) { // +0.0 cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "zeroObj", "Ljava/lang/Double;"); } else { cfw.addPush(num); addDoubleWrap(cfw); } } else if (num == 1.0) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "oneObj", "Ljava/lang/Double;"); return; } else if (num == -1.0) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "minusOneObj", "Ljava/lang/Double;"); } else if (num != num) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "NaNobj", "Ljava/lang/Double;"); } else if (itsConstantListSize >= 2000) { // There appears to be a limit in the JVM on either the number // of static fields in a class or the size of the class // initializer. Either way, we can't have any more than 2000 // statically init'd constants. cfw.addPush(num); addDoubleWrap(cfw); } else { int N = itsConstantListSize; int index = 0; if (N == 0) { itsConstantList = new double[64]; } else { double[] array = itsConstantList; while (index != N && array[index] != num) { ++index; } if (N == array.length) { array = new double[N * 2]; System.arraycopy(itsConstantList, 0, array, 0, N); itsConstantList = array; } } if (index == N) { itsConstantList[N] = num; itsConstantListSize = N + 1; } String constantName = "_k" + index; String constantType = getStaticConstantWrapperType(num); cfw.add(ByteCode.GETSTATIC, mainClassName, constantName, constantType); } } private static void addDoubleWrap(ClassFileWriter cfw) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "wrapDouble", "(D)Ljava/lang/Double;"); } private static String getStaticConstantWrapperType(double num) { int inum = (int)num; if (inum == num) { return "Ljava/lang/Integer;"; } else { return "Ljava/lang/Double;"; } } static void pushUndefined(ClassFileWriter cfw) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/Undefined", "instance", "Ljava/lang/Object;"); } int getIndex(ScriptNode n) { return scriptOrFnIndexes.getExisting(n); } static String getDirectTargetFieldName(int i) { return "_dt" + i; } String getDirectCtorName(ScriptNode n) { return "_n" + getIndex(n); } String getBodyMethodName(ScriptNode n) { return "_c_" + cleanName(n) + "_" + getIndex(n); } /** * Gets a Java-compatible "informative" name for the the ScriptOrFnNode */ String cleanName(final ScriptNode n) { String result = ""; if (n instanceof FunctionNode) { Name name = ((FunctionNode) n).getFunctionName(); if (name == null) { result = "anonymous"; } else { result = name.getIdentifier(); } } else { result = "script"; } return result; } String getBodyMethodSignature(ScriptNode n) { StringBuffer sb = new StringBuffer(); sb.append('('); sb.append(mainClassSignature); sb.append("Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;"); if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); if (ofn.isTargetOfDirectCall()) { int pCount = ofn.fnode.getParamCount(); for (int i = 0; i != pCount; i++) { sb.append("Ljava/lang/Object;D"); } } } sb.append("[Ljava/lang/Object;)Ljava/lang/Object;"); return sb.toString(); } String getFunctionInitMethodName(OptFunctionNode ofn) { return "_i"+getIndex(ofn.fnode); } String getCompiledRegexpName(ScriptNode n, int regexpIndex) { return "_re"+getIndex(n)+"_"+regexpIndex; } static RuntimeException badTree() { throw new RuntimeException("Bad tree in codegen"); } void setMainMethodClass(String className) { mainMethodClass = className; } static final String DEFAULT_MAIN_METHOD_CLASS = "org.mozilla.javascript.optimizer.OptRuntime"; private static final String SUPER_CLASS_NAME = "org.mozilla.javascript.NativeFunction"; static final String DIRECT_CALL_PARENT_FIELD = "_dcp"; private static final String ID_FIELD_NAME = "_id"; private static final String REGEXP_INIT_METHOD_NAME = "_reInit"; private static final String REGEXP_INIT_METHOD_SIGNATURE = "(Lorg/mozilla/javascript/RegExpProxy;" +"Lorg/mozilla/javascript/Context;" +")V"; static final String REGEXP_ARRAY_FIELD_NAME = "_re"; static final String REGEXP_ARRAY_FIELD_TYPE = "[Ljava/lang/Object;"; static final String FUNCTION_INIT_SIGNATURE = "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")V"; static final String FUNCTION_CONSTRUCTOR_SIGNATURE = "(Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;I)V"; private static final Object globalLock = new Object(); private static int globalSerialClassCounter; private CompilerEnvirons compilerEnv; private ObjArray directCallTargets; ScriptNode[] scriptOrFnNodes; private ObjToIntMap scriptOrFnIndexes; private String mainMethodClass = DEFAULT_MAIN_METHOD_CLASS; String mainClassName; String mainClassSignature; private double[] itsConstantList; private int itsConstantListSize; } class BodyCodegen { void generateBodyCode() { isGenerator = Codegen.isGenerator(scriptOrFn); // generate the body of the current function or script object initBodyGeneration(); if (isGenerator) { // All functions in the generated bytecode have a unique name. Every // generator has a unique prefix followed by _gen String type = "(" + codegen.mainClassSignature + "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Ljava/lang/Object;" + "Ljava/lang/Object;I)Ljava/lang/Object;"; cfw.startMethod(codegen.getBodyMethodName(scriptOrFn) + "_gen", type, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); } else { cfw.startMethod(codegen.getBodyMethodName(scriptOrFn), codegen.getBodyMethodSignature(scriptOrFn), (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); } generatePrologue(); Node treeTop; if (fnCurrent != null) { treeTop = scriptOrFn.getLastChild(); } else { treeTop = scriptOrFn; } generateStatement(treeTop); generateEpilogue(); cfw.stopMethod((short)(localsMax + 1)); if (isGenerator) { // generate the user visible method which when invoked will // return a generator object generateGenerator(); } } // This creates a the user-facing function that returns a NativeGenerator // object. private void generateGenerator() { cfw.startMethod(codegen.getBodyMethodName(scriptOrFn), codegen.getBodyMethodSignature(scriptOrFn), (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); initBodyGeneration(); argsLocal = firstFreeLocal++; localsMax = firstFreeLocal; // get top level scope if (fnCurrent != null && !inDirectCallFunction && (!compilerEnv.isUseDynamicScope() || fnCurrent.fnode.getIgnoreDynamicScope())) { // Unless we're either in a direct call or using dynamic scope, // use the enclosing scope of the function as our variable object. cfw.addALoad(funObjLocal); cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } // generators are forced to have an activation record cfw.addALoad(funObjLocal); cfw.addALoad(variableObjectLocal); cfw.addALoad(argsLocal); addScriptRuntimeInvoke("createFunctionActivation", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // create a function object cfw.add(ByteCode.NEW, codegen.mainClassName); // Call function constructor cfw.add(ByteCode.DUP); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' cfw.addPush(scriptOrFnIndex); cfw.addInvoke(ByteCode.INVOKESPECIAL, codegen.mainClassName, "<init>", Codegen.FUNCTION_CONSTRUCTOR_SIGNATURE); // Init mainScript field cfw.add(ByteCode.DUP); if (isTopLevel) Kit.codeBug(); // Only functions can be generators cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); cfw.add(ByteCode.PUTFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); generateNestedFunctionInits(); // create the NativeGenerator object that we return cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addLoadConstant(maxLocals); cfw.addLoadConstant(maxStack); addOptRuntimeInvoke("createNativeGenerator", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;II" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)(localsMax + 1)); } private void generateNestedFunctionInits() { int functionCount = scriptOrFn.getFunctionCount(); for (int i = 0; i != functionCount; i++) { OptFunctionNode ofn = OptFunctionNode.get(scriptOrFn, i); if (ofn.fnode.getFunctionType() == FunctionNode.FUNCTION_STATEMENT) { visitFunction(ofn, FunctionNode.FUNCTION_STATEMENT); } } } private void initBodyGeneration() { isTopLevel = (scriptOrFn == codegen.scriptOrFnNodes[0]); varRegisters = null; if (scriptOrFn.getType() == Token.FUNCTION) { fnCurrent = OptFunctionNode.get(scriptOrFn); hasVarsInRegs = !fnCurrent.fnode.requiresActivation(); if (hasVarsInRegs) { int n = fnCurrent.fnode.getParamAndVarCount(); if (n != 0) { varRegisters = new short[n]; } } inDirectCallFunction = fnCurrent.isTargetOfDirectCall(); if (inDirectCallFunction && !hasVarsInRegs) Codegen.badTree(); } else { fnCurrent = null; hasVarsInRegs = false; inDirectCallFunction = false; } locals = new int[MAX_LOCALS]; funObjLocal = 0; contextLocal = 1; variableObjectLocal = 2; thisObjLocal = 3; localsMax = (short) 4; // number of parms + "this" firstFreeLocal = 4; popvLocal = -1; argsLocal = -1; itsZeroArgArray = -1; itsOneArgArray = -1; scriptRegexpLocal = -1; epilogueLabel = -1; enterAreaStartLabel = -1; generatorStateLocal = -1; } /** * Generate the prologue for a function or script. */ private void generatePrologue() { if (inDirectCallFunction) { int directParameterCount = scriptOrFn.getParamCount(); // 0 is reserved for function Object 'this' // 1 is reserved for context // 2 is reserved for parentScope // 3 is reserved for script 'this' if (firstFreeLocal != 4) Kit.codeBug(); for (int i = 0; i != directParameterCount; ++i) { varRegisters[i] = firstFreeLocal; // 3 is 1 for Object parm and 2 for double parm firstFreeLocal += 3; } if (!fnCurrent.getParameterNumberContext()) { // make sure that all parameters are objects itsForcedObjectParameters = true; for (int i = 0; i != directParameterCount; ++i) { short reg = varRegisters[i]; cfw.addALoad(reg); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isObjectLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPNE, isObjectLabel); cfw.addDLoad(reg + 1); addDoubleWrap(); cfw.addAStore(reg); cfw.markLabel(isObjectLabel); } } } if (fnCurrent != null && !inDirectCallFunction && (!compilerEnv.isUseDynamicScope() || fnCurrent.fnode.getIgnoreDynamicScope())) { // Unless we're either in a direct call or using dynamic scope, // use the enclosing scope of the function as our variable object. cfw.addALoad(funObjLocal); cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } // reserve 'args[]' argsLocal = firstFreeLocal++; localsMax = firstFreeLocal; // Generate Generator specific prelude if (isGenerator) { // reserve 'args[]' operationLocal = firstFreeLocal++; localsMax = firstFreeLocal; // Local 3 is a reference to a GeneratorState object. The rest // of codegen expects local 3 to be a reference to the thisObj. // So move the value in local 3 to generatorStateLocal, and load // the saved thisObj from the GeneratorState object. cfw.addALoad(thisObjLocal); generatorStateLocal = firstFreeLocal++; localsMax = firstFreeLocal; cfw.add(ByteCode.CHECKCAST, OptRuntime.GeneratorState.CLASS_NAME); cfw.add(ByteCode.DUP); cfw.addAStore(generatorStateLocal); cfw.add(ByteCode.GETFIELD, OptRuntime.GeneratorState.CLASS_NAME, OptRuntime.GeneratorState.thisObj_NAME, OptRuntime.GeneratorState.thisObj_TYPE); cfw.addAStore(thisObjLocal); if (epilogueLabel == -1) { epilogueLabel = cfw.acquireLabel(); } List<Node> targets = ((FunctionNode)scriptOrFn).getResumptionPoints(); if (targets != null) { // get resumption point generateGetGeneratorResumptionPoint(); // generate dispatch table generatorSwitch = cfw.addTableSwitch(0, targets.size() + GENERATOR_START); generateCheckForThrowOrClose(-1, false, GENERATOR_START); } } if (fnCurrent == null) { // See comments in case Token.REGEXP if (scriptOrFn.getRegexpCount() != 0) { scriptRegexpLocal = getNewWordLocal(); codegen.pushRegExpArray(cfw, scriptOrFn, contextLocal, variableObjectLocal); cfw.addAStore(scriptRegexpLocal); } } if (compilerEnv.isGenerateObserverCount()) saveCurrentCodeOffset(); if (hasVarsInRegs) { // No need to create activation. Pad arguments if need be. int parmCount = scriptOrFn.getParamCount(); if (parmCount > 0 && !inDirectCallFunction) { // Set up args array // check length of arguments, pad if need be cfw.addALoad(argsLocal); cfw.add(ByteCode.ARRAYLENGTH); cfw.addPush(parmCount); int label = cfw.acquireLabel(); cfw.add(ByteCode.IF_ICMPGE, label); cfw.addALoad(argsLocal); cfw.addPush(parmCount); addScriptRuntimeInvoke("padArguments", "([Ljava/lang/Object;I" +")[Ljava/lang/Object;"); cfw.addAStore(argsLocal); cfw.markLabel(label); } int paramCount = fnCurrent.fnode.getParamCount(); int varCount = fnCurrent.fnode.getParamAndVarCount(); boolean [] constDeclarations = fnCurrent.fnode.getParamAndVarConst(); // REMIND - only need to initialize the vars that don't get a value // before the next call and are used in the function short firstUndefVar = -1; for (int i = 0; i != varCount; ++i) { short reg = -1; if (i < paramCount) { if (!inDirectCallFunction) { reg = getNewWordLocal(); cfw.addALoad(argsLocal); cfw.addPush(i); cfw.add(ByteCode.AALOAD); cfw.addAStore(reg); } } else if (fnCurrent.isNumberVar(i)) { reg = getNewWordPairLocal(constDeclarations[i]); cfw.addPush(0.0); cfw.addDStore(reg); } else { reg = getNewWordLocal(constDeclarations[i]); if (firstUndefVar == -1) { Codegen.pushUndefined(cfw); firstUndefVar = reg; } else { cfw.addALoad(firstUndefVar); } cfw.addAStore(reg); } if (reg >= 0) { if (constDeclarations[i]) { cfw.addPush(0); cfw.addIStore(reg + (fnCurrent.isNumberVar(i) ? 2 : 1)); } varRegisters[i] = reg; } // Add debug table entry if we're generating debug info if (compilerEnv.isGenerateDebugInfo()) { String name = fnCurrent.fnode.getParamOrVarName(i); String type = fnCurrent.isNumberVar(i) ? "D" : "Ljava/lang/Object;"; int startPC = cfw.getCurrentCodeOffset(); if (reg < 0) { reg = varRegisters[i]; } cfw.addVariableDescriptor(name, type, startPC, reg); } } // Skip creating activation object. return; } // skip creating activation object for the body of a generator. The // activation record required by a generator has already been created // in generateGenerator(). if (isGenerator) return; String debugVariableName; if (fnCurrent != null) { debugVariableName = "activation"; cfw.addALoad(funObjLocal); cfw.addALoad(variableObjectLocal); cfw.addALoad(argsLocal); addScriptRuntimeInvoke("createFunctionActivation", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("enterActivationFunction", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")V"); } else { debugVariableName = "global"; cfw.addALoad(funObjLocal); cfw.addALoad(thisObjLocal); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(0); // false to indicate it is not eval script addScriptRuntimeInvoke("initScript", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Z" +")V"); } enterAreaStartLabel = cfw.acquireLabel(); epilogueLabel = cfw.acquireLabel(); cfw.markLabel(enterAreaStartLabel); generateNestedFunctionInits(); // default is to generate debug info if (compilerEnv.isGenerateDebugInfo()) { cfw.addVariableDescriptor(debugVariableName, "Lorg/mozilla/javascript/Scriptable;", cfw.getCurrentCodeOffset(), variableObjectLocal); } if (fnCurrent == null) { // OPT: use dataflow to prove that this assignment is dead popvLocal = getNewWordLocal(); Codegen.pushUndefined(cfw); cfw.addAStore(popvLocal); int linenum = scriptOrFn.getEndLineno(); if (linenum != -1) cfw.addLineNumberEntry((short)linenum); } else { if (fnCurrent.itsContainsCalls0) { itsZeroArgArray = getNewWordLocal(); cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "emptyArgs", "[Ljava/lang/Object;"); cfw.addAStore(itsZeroArgArray); } if (fnCurrent.itsContainsCalls1) { itsOneArgArray = getNewWordLocal(); cfw.addPush(1); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); cfw.addAStore(itsOneArgArray); } } } private void generateGetGeneratorResumptionPoint() { cfw.addALoad(generatorStateLocal); cfw.add(ByteCode.GETFIELD, OptRuntime.GeneratorState.CLASS_NAME, OptRuntime.GeneratorState.resumptionPoint_NAME, OptRuntime.GeneratorState.resumptionPoint_TYPE); } private void generateSetGeneratorResumptionPoint(int nextState) { cfw.addALoad(generatorStateLocal); cfw.addLoadConstant(nextState); cfw.add(ByteCode.PUTFIELD, OptRuntime.GeneratorState.CLASS_NAME, OptRuntime.GeneratorState.resumptionPoint_NAME, OptRuntime.GeneratorState.resumptionPoint_TYPE); } private void generateGetGeneratorStackState() { cfw.addALoad(generatorStateLocal); addOptRuntimeInvoke("getGeneratorStackState", "(Ljava/lang/Object;)[Ljava/lang/Object;"); } private void generateEpilogue() { if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); if (isGenerator) { // generate locals initialization Map<Node,int[]> liveLocals = ((FunctionNode)scriptOrFn).getLiveLocals(); if (liveLocals != null) { List<Node> nodes = ((FunctionNode)scriptOrFn).getResumptionPoints(); for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); int[] live = liveLocals.get(node); if (live != null) { cfw.markTableSwitchCase(generatorSwitch, getNextGeneratorState(node)); generateGetGeneratorLocalsState(); for (int j = 0; j < live.length; j++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(j); cfw.add(ByteCode.AALOAD); cfw.addAStore(live[j]); } cfw.add(ByteCode.POP); cfw.add(ByteCode.GOTO, getTargetLabel(node)); } } } // generate dispatch tables for finally if (finallys != null) { for (Node n: finallys.keySet()) { if (n.getType() == Token.FINALLY) { FinallyReturnPoint ret = finallys.get(n); // the finally will jump here cfw.markLabel(ret.tableLabel, (short)1); // start generating a dispatch table int startSwitch = cfw.addTableSwitch(0, ret.jsrPoints.size() - 1); int c = 0; cfw.markTableSwitchDefault(startSwitch); for (int i = 0; i < ret.jsrPoints.size(); i++) { // generate gotos back to the JSR location cfw.markTableSwitchCase(startSwitch, c); cfw.add(ByteCode.GOTO, ret.jsrPoints.get(i).intValue()); c++; } } } } } if (epilogueLabel != -1) { cfw.markLabel(epilogueLabel); } if (hasVarsInRegs) { cfw.add(ByteCode.ARETURN); return; } else if (isGenerator) { if (((FunctionNode)scriptOrFn).getResumptionPoints() != null) { cfw.markTableSwitchDefault(generatorSwitch); } // change state for re-entry generateSetGeneratorResumptionPoint(GENERATOR_TERMINATE); // throw StopIteration cfw.addALoad(variableObjectLocal); addOptRuntimeInvoke("throwStopIteration", "(Ljava/lang/Object;)V"); Codegen.pushUndefined(cfw); cfw.add(ByteCode.ARETURN); } else if (fnCurrent == null) { cfw.addALoad(popvLocal); cfw.add(ByteCode.ARETURN); } else { generateActivationExit(); cfw.add(ByteCode.ARETURN); // Generate catch block to catch all and rethrow to call exit code // under exception propagation as well. int finallyHandler = cfw.acquireLabel(); cfw.markHandler(finallyHandler); short exceptionObject = getNewWordLocal(); cfw.addAStore(exceptionObject); // Duplicate generateActivationExit() in the catch block since it // takes less space then full-featured ByteCode.JSR/ByteCode.RET generateActivationExit(); cfw.addALoad(exceptionObject); releaseWordLocal(exceptionObject); // rethrow cfw.add(ByteCode.ATHROW); // mark the handler cfw.addExceptionHandler(enterAreaStartLabel, epilogueLabel, finallyHandler, null); // catch any } } private void generateGetGeneratorLocalsState() { cfw.addALoad(generatorStateLocal); addOptRuntimeInvoke("getGeneratorLocalsState", "(Ljava/lang/Object;)[Ljava/lang/Object;"); } private void generateActivationExit() { if (fnCurrent == null || hasVarsInRegs) throw Kit.codeBug(); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("exitActivationFunction", "(Lorg/mozilla/javascript/Context;)V"); } private void generateStatement(Node node) { updateLineNumber(node); int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.LOOP: case Token.LABEL: case Token.WITH: case Token.SCRIPT: case Token.BLOCK: case Token.EMPTY: // no-ops. if (compilerEnv.isGenerateObserverCount()) { // Need to add instruction count even for no-ops to catch // cases like while (1) {} addInstructionCount(1); } while (child != null) { generateStatement(child); child = child.getNext(); } break; case Token.LOCAL_BLOCK: { int local = getNewWordLocal(); if (isGenerator) { cfw.add(ByteCode.ACONST_NULL); cfw.addAStore(local); } node.putIntProp(Node.LOCAL_PROP, local); while (child != null) { generateStatement(child); child = child.getNext(); } releaseWordLocal((short)local); node.removeProp(Node.LOCAL_PROP); break; } case Token.FUNCTION: { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); OptFunctionNode ofn = OptFunctionNode.get(scriptOrFn, fnIndex); int t = ofn.fnode.getFunctionType(); if (t == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) { visitFunction(ofn, t); } else { if (t != FunctionNode.FUNCTION_STATEMENT) { throw Codegen.badTree(); } } break; } case Token.TRY: visitTryCatchFinally((Jump)node, child); break; case Token.CATCH_SCOPE: { // nothing stays on the stack on entry into a catch scope cfw.setStackTop((short) 0); int local = getLocalBlockRegister(node); int scopeIndex = node.getExistingIntProp(Node.CATCH_SCOPE_PROP); String name = child.getString(); // name of exception child = child.getNext(); generateExpression(child, node); // load expression object if (scopeIndex == 0) { cfw.add(ByteCode.ACONST_NULL); } else { // Load previous catch scope object cfw.addALoad(local); } cfw.addPush(name); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "newCatchScope", "(Ljava/lang/Throwable;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(local); } break; case Token.THROW: generateExpression(child, node); if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); generateThrowJavaScriptException(); break; case Token.RETHROW: if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); cfw.addALoad(getLocalBlockRegister(node)); cfw.add(ByteCode.ATHROW); break; case Token.RETURN_RESULT: case Token.RETURN: if (!isGenerator) { if (child != null) { generateExpression(child, node); } else if (type == Token.RETURN) { Codegen.pushUndefined(cfw); } else { if (popvLocal < 0) throw Codegen.badTree(); cfw.addALoad(popvLocal); } } if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); if (epilogueLabel == -1) { if (!hasVarsInRegs) throw Codegen.badTree(); epilogueLabel = cfw.acquireLabel(); } cfw.add(ByteCode.GOTO, epilogueLabel); break; case Token.SWITCH: if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); visitSwitch((Jump)node, child); break; case Token.ENTERWITH: generateExpression(child, node); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "enterWith", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); incReferenceWordLocal(variableObjectLocal); break; case Token.LEAVEWITH: cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "leaveWith", "(Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); decReferenceWordLocal(variableObjectLocal); break; case Token.ENUM_INIT_KEYS: case Token.ENUM_INIT_VALUES: case Token.ENUM_INIT_ARRAY: generateExpression(child, node); cfw.addALoad(contextLocal); int enumType = type == Token.ENUM_INIT_KEYS ? ScriptRuntime.ENUMERATE_KEYS : type == Token.ENUM_INIT_VALUES ? ScriptRuntime.ENUMERATE_VALUES : ScriptRuntime.ENUMERATE_ARRAY; cfw.addPush(enumType); addScriptRuntimeInvoke("enumInit", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Ljava/lang/Object;"); cfw.addAStore(getLocalBlockRegister(node)); break; case Token.EXPR_VOID: if (child.getType() == Token.SETVAR) { /* special case this so as to avoid unnecessary load's & pop's */ visitSetVar(child, child.getFirstChild(), false); } else if (child.getType() == Token.SETCONSTVAR) { /* special case this so as to avoid unnecessary load's & pop's */ visitSetConstVar(child, child.getFirstChild(), false); } else if (child.getType() == Token.YIELD) { generateYieldPoint(child, false); } else { generateExpression(child, node); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) cfw.add(ByteCode.POP2); else cfw.add(ByteCode.POP); } break; case Token.EXPR_RESULT: generateExpression(child, node); if (popvLocal < 0) { popvLocal = getNewWordLocal(); } cfw.addAStore(popvLocal); break; case Token.TARGET: { if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); int label = getTargetLabel(node); cfw.markLabel(label); if (compilerEnv.isGenerateObserverCount()) saveCurrentCodeOffset(); } break; case Token.JSR: case Token.GOTO: case Token.IFEQ: case Token.IFNE: if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); visitGoto((Jump)node, type, child); break; case Token.FINALLY: { if (compilerEnv.isGenerateObserverCount()) saveCurrentCodeOffset(); // there is exactly one value on the stack when enterring // finally blocks: the return address (or its int encoding) cfw.setStackTop((short)1); // Save return address in a new local int finallyRegister = getNewWordLocal(); if (isGenerator) generateIntegerWrap(); cfw.addAStore(finallyRegister); while (child != null) { generateStatement(child); child = child.getNext(); } if (isGenerator) { cfw.addALoad(finallyRegister); cfw.add(ByteCode.CHECKCAST, "java/lang/Integer"); generateIntegerUnwrap(); FinallyReturnPoint ret = finallys.get(node); ret.tableLabel = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, ret.tableLabel); } else { cfw.add(ByteCode.RET, finallyRegister); } releaseWordLocal((short)finallyRegister); } break; case Token.DEBUGGER: break; default: throw Codegen.badTree(); } } private void generateIntegerWrap() { cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } private void generateIntegerUnwrap() { cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"); } private void generateThrowJavaScriptException() { cfw.add(ByteCode.NEW, "org/mozilla/javascript/JavaScriptException"); cfw.add(ByteCode.DUP_X1); cfw.add(ByteCode.SWAP); cfw.addPush(scriptOrFn.getSourceName()); cfw.addPush(itsLineNumber); cfw.addInvoke( ByteCode.INVOKESPECIAL, "org/mozilla/javascript/JavaScriptException", "<init>", "(Ljava/lang/Object;Ljava/lang/String;I)V"); cfw.add(ByteCode.ATHROW); } private int getNextGeneratorState(Node node) { int nodeIndex = ((FunctionNode)scriptOrFn).getResumptionPoints() .indexOf(node); return nodeIndex + GENERATOR_YIELD_START; } private void generateExpression(Node node, Node parent) { int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.USE_STACK: break; case Token.FUNCTION: if (fnCurrent != null || parent.getType() != Token.SCRIPT) { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); OptFunctionNode ofn = OptFunctionNode.get(scriptOrFn, fnIndex); int t = ofn.fnode.getFunctionType(); if (t != FunctionNode.FUNCTION_EXPRESSION) { throw Codegen.badTree(); } visitFunction(ofn, t); } break; case Token.NAME: { cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(node.getString()); addScriptRuntimeInvoke( "name", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } break; case Token.CALL: case Token.NEW: { int specialType = node.getIntProp(Node.SPECIALCALL_PROP, Node.NON_SPECIALCALL); if (specialType == Node.NON_SPECIALCALL) { OptFunctionNode target; target = (OptFunctionNode)node.getProp( Node.DIRECTCALL_PROP); if (target != null) { visitOptimizedCall(node, target, type, child); } else if (type == Token.CALL) { visitStandardCall(node, child); } else { visitStandardNew(node, child); } } else { visitSpecialCall(node, type, specialType, child); } } break; case Token.REF_CALL: generateFunctionAndThisObj(child, node); // stack: ... functionObj thisObj child = child.getNext(); generateCallArgArray(node, child, false); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "callRef", "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Ref;"); break; case Token.NUMBER: { double num = node.getDouble(); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { cfw.addPush(num); } else { codegen.pushNumberAsObject(cfw, num); } } break; case Token.STRING: cfw.addPush(node.getString()); break; case Token.THIS: cfw.addALoad(thisObjLocal); break; case Token.THISFN: cfw.add(ByteCode.ALOAD_0); break; case Token.NULL: cfw.add(ByteCode.ACONST_NULL); break; case Token.TRUE: cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); break; case Token.FALSE: cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); break; case Token.REGEXP: { int i = node.getExistingIntProp(Node.REGEXP_PROP); // Scripts can not use REGEXP_ARRAY_FIELD_NAME since // it it will make script.exec non-reentrant so they // store regexp array in a local variable while // functions always access precomputed // REGEXP_ARRAY_FIELD_NAME not to consume locals if (fnCurrent == null) { cfw.addALoad(scriptRegexpLocal); } else { cfw.addALoad(funObjLocal); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.REGEXP_ARRAY_FIELD_NAME, Codegen.REGEXP_ARRAY_FIELD_TYPE); } cfw.addPush(i); cfw.add(ByteCode.AALOAD); } break; case Token.COMMA: { Node next = child.getNext(); while (next != null) { generateExpression(child, node); cfw.add(ByteCode.POP); child = next; next = next.getNext(); } generateExpression(child, node); break; } case Token.ENUM_NEXT: case Token.ENUM_ID: { int local = getLocalBlockRegister(node); cfw.addALoad(local); if (type == Token.ENUM_NEXT) { addScriptRuntimeInvoke( "enumNext", "(Ljava/lang/Object;)Ljava/lang/Boolean;"); } else { cfw.addALoad(contextLocal); addScriptRuntimeInvoke("enumId", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } break; } case Token.ARRAYLIT: visitArrayLiteral(node, child); break; case Token.OBJECTLIT: visitObjectLiteral(node, child); break; case Token.NOT: { int trueTarget = cfw.acquireLabel(); int falseTarget = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); generateIfJump(child, node, trueTarget, falseTarget); cfw.markLabel(trueTarget); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(falseTarget); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); cfw.markLabel(beyond); cfw.adjustStackTop(-1); break; } case Token.BITNOT: generateExpression(child, node); addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); cfw.addPush(-1); // implement ~a as (a ^ -1) cfw.add(ByteCode.IXOR); cfw.add(ByteCode.I2D); addDoubleWrap(); break; case Token.VOID: generateExpression(child, node); cfw.add(ByteCode.POP); Codegen.pushUndefined(cfw); break; case Token.TYPEOF: generateExpression(child, node); addScriptRuntimeInvoke("typeof", "(Ljava/lang/Object;" +")Ljava/lang/String;"); break; case Token.TYPEOFNAME: visitTypeofname(node); break; case Token.INC: case Token.DEC: visitIncDec(node); break; case Token.OR: case Token.AND: { generateExpression(child, node); cfw.add(ByteCode.DUP); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); int falseTarget = cfw.acquireLabel(); if (type == Token.AND) cfw.add(ByteCode.IFEQ, falseTarget); else cfw.add(ByteCode.IFNE, falseTarget); cfw.add(ByteCode.POP); generateExpression(child.getNext(), node); cfw.markLabel(falseTarget); } break; case Token.HOOK : { Node ifThen = child.getNext(); Node ifElse = ifThen.getNext(); generateExpression(child, node); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); int elseTarget = cfw.acquireLabel(); cfw.add(ByteCode.IFEQ, elseTarget); short stack = cfw.getStackTop(); generateExpression(ifThen, node); int afterHook = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, afterHook); cfw.markLabel(elseTarget, stack); generateExpression(ifElse, node); cfw.markLabel(afterHook); } break; case Token.ADD: { generateExpression(child, node); generateExpression(child.getNext(), node); switch (node.getIntProp(Node.ISNUMBER_PROP, -1)) { case Node.BOTH: cfw.add(ByteCode.DADD); break; case Node.LEFT: addOptRuntimeInvoke("add", "(DLjava/lang/Object;)Ljava/lang/Object;"); break; case Node.RIGHT: addOptRuntimeInvoke("add", "(Ljava/lang/Object;D)Ljava/lang/Object;"); break; default: if (child.getType() == Token.STRING) { addScriptRuntimeInvoke("add", "(Ljava/lang/String;" +"Ljava/lang/Object;" +")Ljava/lang/String;"); } else if (child.getNext().getType() == Token.STRING) { addScriptRuntimeInvoke("add", "(Ljava/lang/Object;" +"Ljava/lang/String;" +")Ljava/lang/String;"); } else { cfw.addALoad(contextLocal); addScriptRuntimeInvoke("add", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } } break; case Token.MUL: visitArithmetic(node, ByteCode.DMUL, child, parent); break; case Token.SUB: visitArithmetic(node, ByteCode.DSUB, child, parent); break; case Token.DIV: case Token.MOD: visitArithmetic(node, type == Token.DIV ? ByteCode.DDIV : ByteCode.DREM, child, parent); break; case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.LSH: case Token.RSH: case Token.URSH: visitBitOp(node, type, child); break; case Token.POS: case Token.NEG: generateExpression(child, node); addObjectToDouble(); if (type == Token.NEG) { cfw.add(ByteCode.DNEG); } addDoubleWrap(); break; case Token.TO_DOUBLE: // cnvt to double (not Double) generateExpression(child, node); addObjectToDouble(); break; case Token.TO_OBJECT: { // convert from double int prop = -1; if (child.getType() == Token.NUMBER) { prop = child.getIntProp(Node.ISNUMBER_PROP, -1); } if (prop != -1) { child.removeProp(Node.ISNUMBER_PROP); generateExpression(child, node); child.putIntProp(Node.ISNUMBER_PROP, prop); } else { generateExpression(child, node); addDoubleWrap(); } break; } case Token.IN: case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: { int trueGOTO = cfw.acquireLabel(); int falseGOTO = cfw.acquireLabel(); visitIfJumpRelOp(node, child, trueGOTO, falseGOTO); addJumpedBooleanWrap(trueGOTO, falseGOTO); break; } case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: { int trueGOTO = cfw.acquireLabel(); int falseGOTO = cfw.acquireLabel(); visitIfJumpEqOp(node, child, trueGOTO, falseGOTO); addJumpedBooleanWrap(trueGOTO, falseGOTO); break; } case Token.GETPROP: case Token.GETPROPNOWARN: visitGetProp(node, child); break; case Token.GETELEM: generateExpression(child, node); // object generateExpression(child.getNext(), node); // id cfw.addALoad(contextLocal); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { addScriptRuntimeInvoke( "getObjectIndex", "(Ljava/lang/Object;D" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getObjectElem", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"); } break; case Token.GET_REF: generateExpression(child, node); // reference cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "refGet", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.GETVAR: visitGetVar(node); break; case Token.SETVAR: visitSetVar(node, child, true); break; case Token.SETNAME: visitSetName(node, child); break; case Token.STRICT_SETNAME: visitStrictSetName(node, child); break; case Token.SETCONST: visitSetConst(node, child); break; case Token.SETCONSTVAR: visitSetConstVar(node, child, true); break; case Token.SETPROP: case Token.SETPROP_OP: visitSetProp(type, node, child); break; case Token.SETELEM: case Token.SETELEM_OP: visitSetElem(type, node, child); break; case Token.SET_REF: case Token.SET_REF_OP: { generateExpression(child, node); child = child.getNext(); if (type == Token.SET_REF_OP) { cfw.add(ByteCode.DUP); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "refGet", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "refSet", "(Lorg/mozilla/javascript/Ref;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } break; case Token.DEL_REF: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("refDel", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.DELPROP: generateExpression(child, node); child = child.getNext(); generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("delete", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.BINDNAME: { while (child != null) { generateExpression(child, node); child = child.getNext(); } // Generate code for "ScriptRuntime.bind(varObj, "s")" cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(node.getString()); addScriptRuntimeInvoke( "bind", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Lorg/mozilla/javascript/Scriptable;"); } break; case Token.LOCAL_LOAD: cfw.addALoad(getLocalBlockRegister(node)); break; case Token.REF_SPECIAL: { String special = (String)node.getProp(Node.NAME_PROP); generateExpression(child, node); cfw.addPush(special); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "specialRef", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Ref;"); } break; case Token.REF_MEMBER: case Token.REF_NS_MEMBER: case Token.REF_NAME: case Token.REF_NS_NAME: { int memberTypeFlags = node.getIntProp(Node.MEMBER_TYPE_PROP, 0); // generate possible target, possible namespace and member do { generateExpression(child, node); child = child.getNext(); } while (child != null); cfw.addALoad(contextLocal); String methodName, signature; switch (type) { case Token.REF_MEMBER: methodName = "memberRef"; signature = "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Lorg/mozilla/javascript/Ref;"; break; case Token.REF_NS_MEMBER: methodName = "memberRef"; signature = "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Lorg/mozilla/javascript/Ref;"; break; case Token.REF_NAME: methodName = "nameRef"; signature = "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"I" +")Lorg/mozilla/javascript/Ref;"; cfw.addALoad(variableObjectLocal); break; case Token.REF_NS_NAME: methodName = "nameRef"; signature = "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"I" +")Lorg/mozilla/javascript/Ref;"; cfw.addALoad(variableObjectLocal); break; default: throw Kit.codeBug(); } cfw.addPush(memberTypeFlags); addScriptRuntimeInvoke(methodName, signature); } break; case Token.DOTQUERY: visitDotQuery(node, child); break; case Token.ESCXMLATTR: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("escapeAttributeValue", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/String;"); break; case Token.ESCXMLTEXT: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("escapeTextValue", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/String;"); break; case Token.DEFAULTNAMESPACE: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("setDefaultNamespace", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.YIELD: generateYieldPoint(node, true); break; case Token.WITHEXPR: { Node enterWith = child; Node with = enterWith.getNext(); Node leaveWith = with.getNext(); generateStatement(enterWith); generateExpression(with.getFirstChild(), with); generateStatement(leaveWith); break; } case Token.ARRAYCOMP: { Node initStmt = child; Node expr = child.getNext(); generateStatement(initStmt); generateExpression(expr, node); break; } default: throw new RuntimeException("Unexpected node type "+type); } } private void generateYieldPoint(Node node, boolean exprContext) { // save stack state int top = cfw.getStackTop(); maxStack = maxStack > top ? maxStack : top; if (cfw.getStackTop() != 0) { generateGetGeneratorStackState(); for (int i = 0; i < top; i++) { cfw.add(ByteCode.DUP_X1); cfw.add(ByteCode.SWAP); cfw.addLoadConstant(i); cfw.add(ByteCode.SWAP); cfw.add(ByteCode.AASTORE); } // pop the array object cfw.add(ByteCode.POP); } // generate the yield argument Node child = node.getFirstChild(); if (child != null) generateExpression(child, node); else Codegen.pushUndefined(cfw); // change the resumption state int nextState = getNextGeneratorState(node); generateSetGeneratorResumptionPoint(nextState); boolean hasLocals = generateSaveLocals(node); cfw.add(ByteCode.ARETURN); generateCheckForThrowOrClose(getTargetLabel(node), hasLocals, nextState); // reconstruct the stack if (top != 0) { generateGetGeneratorStackState(); for (int i = 0; i < top; i++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(top - i - 1); cfw.add(ByteCode.AALOAD); cfw.add(ByteCode.SWAP); } cfw.add(ByteCode.POP); } // load return value from yield if (exprContext) { cfw.addALoad(argsLocal); } } private void generateCheckForThrowOrClose(int label, boolean hasLocals, int nextState) { int throwLabel = cfw.acquireLabel(); int closeLabel = cfw.acquireLabel(); // throw the user provided object, if the operation is .throw() cfw.markLabel(throwLabel); cfw.addALoad(argsLocal); generateThrowJavaScriptException(); // throw our special internal exception if the generator is being closed cfw.markLabel(closeLabel); cfw.addALoad(argsLocal); cfw.add(ByteCode.CHECKCAST, "java/lang/Throwable"); cfw.add(ByteCode.ATHROW); // mark the re-entry point // jump here after initializing the locals if (label != -1) cfw.markLabel(label); if (!hasLocals) { // jump here directly if there are no locals cfw.markTableSwitchCase(generatorSwitch, nextState); } // see if we need to dispatch for .close() or .throw() cfw.addILoad(operationLocal); cfw.addLoadConstant(NativeGenerator.GENERATOR_CLOSE); cfw.add(ByteCode.IF_ICMPEQ, closeLabel); cfw.addILoad(operationLocal); cfw.addLoadConstant(NativeGenerator.GENERATOR_THROW); cfw.add(ByteCode.IF_ICMPEQ, throwLabel); } private void generateIfJump(Node node, Node parent, int trueLabel, int falseLabel) { // System.out.println("gen code for " + node.toString()); int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.NOT: generateIfJump(child, node, falseLabel, trueLabel); break; case Token.OR: case Token.AND: { int interLabel = cfw.acquireLabel(); if (type == Token.AND) { generateIfJump(child, node, interLabel, falseLabel); } else { generateIfJump(child, node, trueLabel, interLabel); } cfw.markLabel(interLabel); child = child.getNext(); generateIfJump(child, node, trueLabel, falseLabel); break; } case Token.IN: case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: visitIfJumpRelOp(node, child, trueLabel, falseLabel); break; case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: visitIfJumpEqOp(node, child, trueLabel, falseLabel); break; default: // Generate generic code for non-optimized jump generateExpression(node, parent); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); cfw.add(ByteCode.IFNE, trueLabel); cfw.add(ByteCode.GOTO, falseLabel); } } private void visitFunction(OptFunctionNode ofn, int functionType) { int fnIndex = codegen.getIndex(ofn.fnode); cfw.add(ByteCode.NEW, codegen.mainClassName); // Call function constructor cfw.add(ByteCode.DUP); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' cfw.addPush(fnIndex); cfw.addInvoke(ByteCode.INVOKESPECIAL, codegen.mainClassName, "<init>", Codegen.FUNCTION_CONSTRUCTOR_SIGNATURE); // Init mainScript field; cfw.add(ByteCode.DUP); if (isTopLevel) { cfw.add(ByteCode.ALOAD_0); } else { cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); } cfw.add(ByteCode.PUTFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); int directTargetIndex = ofn.getDirectTargetIndex(); if (directTargetIndex >= 0) { cfw.add(ByteCode.DUP); if (isTopLevel) { cfw.add(ByteCode.ALOAD_0); } else { cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); } cfw.add(ByteCode.SWAP); cfw.add(ByteCode.PUTFIELD, codegen.mainClassName, Codegen.getDirectTargetFieldName(directTargetIndex), codegen.mainClassSignature); } if (functionType == FunctionNode.FUNCTION_EXPRESSION) { // Leave closure object on stack and do not pass it to // initFunction which suppose to connect statements to scope return; } cfw.addPush(functionType); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' addOptRuntimeInvoke("initFunction", "(Lorg/mozilla/javascript/NativeFunction;" +"I" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;" +")V"); } private int getTargetLabel(Node target) { int labelId = target.labelId(); if (labelId == -1) { labelId = cfw.acquireLabel(); target.labelId(labelId); } return labelId; } private void visitGoto(Jump node, int type, Node child) { Node target = node.target; if (type == Token.IFEQ || type == Token.IFNE) { if (child == null) throw Codegen.badTree(); int targetLabel = getTargetLabel(target); int fallThruLabel = cfw.acquireLabel(); if (type == Token.IFEQ) generateIfJump(child, node, targetLabel, fallThruLabel); else generateIfJump(child, node, fallThruLabel, targetLabel); cfw.markLabel(fallThruLabel); } else { if (type == Token.JSR) { if (isGenerator) { addGotoWithReturn(target); } else { addGoto(target, ByteCode.JSR); } } else { addGoto(target, ByteCode.GOTO); } } } private void addGotoWithReturn(Node target) { FinallyReturnPoint ret = finallys.get(target); cfw.addLoadConstant(ret.jsrPoints.size()); addGoto(target, ByteCode.GOTO); int retLabel = cfw.acquireLabel(); cfw.markLabel(retLabel); ret.jsrPoints.add(Integer.valueOf(retLabel)); } private void visitArrayLiteral(Node node, Node child) { int count = 0; for (Node cursor = child; cursor != null; cursor = cursor.getNext()) { ++count; } // load array to store array literal objects addNewObjectArray(count); for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); generateExpression(child, node); cfw.add(ByteCode.AASTORE); child = child.getNext(); } int[] skipIndexes = (int[])node.getProp(Node.SKIP_INDEXES_PROP); if (skipIndexes == null) { cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.ICONST_0); } else { cfw.addPush(OptRuntime.encodeIntArray(skipIndexes)); cfw.addPush(skipIndexes.length); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addOptRuntimeInvoke("newArrayLiteral", "([Ljava/lang/Object;" +"Ljava/lang/String;" +"I" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); } private void visitObjectLiteral(Node node, Node child) { Object[] properties = (Object[])node.getProp(Node.OBJECT_IDS_PROP); int count = properties.length; // load array with property ids addNewObjectArray(count); for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); Object id = properties[i]; if (id instanceof String) { cfw.addPush((String)id); } else { cfw.addPush(((Integer)id).intValue()); addScriptRuntimeInvoke("wrapInt", "(I)Ljava/lang/Integer;"); } cfw.add(ByteCode.AASTORE); } // load array with property values addNewObjectArray(count); Node child2 = child; for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); int childType = child.getType(); if (childType == Token.GET) { generateExpression(child.getFirstChild(), node); } else if (childType == Token.SET) { generateExpression(child.getFirstChild(), node); } else { generateExpression(child, node); } cfw.add(ByteCode.AASTORE); child = child.getNext(); } // load array with getterSetter values cfw.addPush(count); cfw.add(ByteCode.NEWARRAY, ByteCode.T_INT); for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); int childType = child2.getType(); if (childType == Token.GET) { cfw.add(ByteCode.ICONST_M1); } else if (childType == Token.SET) { cfw.add(ByteCode.ICONST_1); } else { cfw.add(ByteCode.ICONST_0); } cfw.add(ByteCode.IASTORE); child2 = child2.getNext(); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("newObjectLiteral", "([Ljava/lang/Object;" +"[Ljava/lang/Object;" +"[I" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); } private void visitSpecialCall(Node node, int type, int specialType, Node child) { cfw.addALoad(contextLocal); if (type == Token.NEW) { generateExpression(child, node); // stack: ... cx functionObj } else { generateFunctionAndThisObj(child, node); // stack: ... cx functionObj thisObj } child = child.getNext(); generateCallArgArray(node, child, false); String methodName; String callSignature; if (type == Token.NEW) { methodName = "newObjectSpecial"; callSignature = "(Lorg/mozilla/javascript/Context;" +"Ljava/lang/Object;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"I" // call type +")Ljava/lang/Object;"; cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addPush(specialType); } else { methodName = "callSpecial"; callSignature = "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"I" // call type +"Ljava/lang/String;I" // filename, linenumber +")Ljava/lang/Object;"; cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addPush(specialType); String sourceName = scriptOrFn.getSourceName(); cfw.addPush(sourceName == null ? "" : sourceName); cfw.addPush(itsLineNumber); } addOptRuntimeInvoke(methodName, callSignature); } private void visitStandardCall(Node node, Node child) { if (node.getType() != Token.CALL) throw Codegen.badTree(); Node firstArgChild = child.getNext(); int childType = child.getType(); String methodName; String signature; if (firstArgChild == null) { if (childType == Token.NAME) { // name() call String name = child.getString(); cfw.addPush(name); methodName = "callName0"; signature = "(Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else if (childType == Token.GETPROP) { // x.name() call Node propTarget = child.getFirstChild(); generateExpression(propTarget, node); Node id = propTarget.getNext(); String property = id.getString(); cfw.addPush(property); methodName = "callProp0"; signature = "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else if (childType == Token.GETPROPNOWARN) { throw Kit.codeBug(); } else { generateFunctionAndThisObj(child, node); methodName = "call0"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } } else if (childType == Token.NAME) { // XXX: this optimization is only possible if name // resolution // is not affected by arguments evaluation and currently // there are no checks for it String name = child.getString(); generateCallArgArray(node, firstArgChild, false); cfw.addPush(name); methodName = "callName"; signature = "([Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else { int argCount = 0; for (Node arg = firstArgChild; arg != null; arg = arg.getNext()) { ++argCount; } generateFunctionAndThisObj(child, node); // stack: ... functionObj thisObj if (argCount == 1) { generateExpression(firstArgChild, node); methodName = "call1"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else if (argCount == 2) { generateExpression(firstArgChild, node); generateExpression(firstArgChild.getNext(), node); methodName = "call2"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else { generateCallArgArray(node, firstArgChild, false); methodName = "callN"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addOptRuntimeInvoke(methodName, signature); } private void visitStandardNew(Node node, Node child) { if (node.getType() != Token.NEW) throw Codegen.badTree(); Node firstArgChild = child.getNext(); generateExpression(child, node); // stack: ... functionObj cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); // stack: ... functionObj cx scope generateCallArgArray(node, firstArgChild, false); addScriptRuntimeInvoke( "newObject", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); } private void visitOptimizedCall(Node node, OptFunctionNode target, int type, Node child) { Node firstArgChild = child.getNext(); short thisObjLocal = 0; if (type == Token.NEW) { generateExpression(child, node); } else { generateFunctionAndThisObj(child, node); thisObjLocal = getNewWordLocal(); cfw.addAStore(thisObjLocal); } // stack: ... functionObj int beyond = cfw.acquireLabel(); int directTargetIndex = target.getDirectTargetIndex(); if (isTopLevel) { cfw.add(ByteCode.ALOAD_0); } else { cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); } cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.getDirectTargetFieldName(directTargetIndex), codegen.mainClassSignature); cfw.add(ByteCode.DUP2); // stack: ... functionObj directFunct functionObj directFunct int regularCall = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPNE, regularCall); // stack: ... functionObj directFunct short stackHeight = cfw.getStackTop(); cfw.add(ByteCode.SWAP); cfw.add(ByteCode.POP); // stack: ... directFunct if (compilerEnv.isUseDynamicScope()) { cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); } else { cfw.add(ByteCode.DUP); // stack: ... directFunct directFunct cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); // stack: ... directFunct scope cfw.addALoad(contextLocal); // stack: ... directFunct scope cx cfw.add(ByteCode.SWAP); } // stack: ... directFunc cx scope if (type == Token.NEW) { cfw.add(ByteCode.ACONST_NULL); } else { cfw.addALoad(thisObjLocal); } // stack: ... directFunc cx scope thisObj /* Remember that directCall parameters are paired in 1 aReg and 1 dReg If the argument is an incoming arg, just pass the orginal pair thru. Else, if the argument is known to be typed 'Number', pass Void.TYPE in the aReg and the number is the dReg Else pass the JS object in the aReg and 0.0 in the dReg. */ Node argChild = firstArgChild; while (argChild != null) { int dcp_register = nodeIsDirectCallParameter(argChild); if (dcp_register >= 0) { cfw.addALoad(dcp_register); cfw.addDLoad(dcp_register + 1); } else if (argChild.getIntProp(Node.ISNUMBER_PROP, -1) == Node.BOTH) { cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); generateExpression(argChild, node); } else { generateExpression(argChild, node); cfw.addPush(0.0); } argChild = argChild.getNext(); } cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "emptyArgs", "[Ljava/lang/Object;"); cfw.addInvoke(ByteCode.INVOKESTATIC, codegen.mainClassName, (type == Token.NEW) ? codegen.getDirectCtorName(target.fnode) : codegen.getBodyMethodName(target.fnode), codegen.getBodyMethodSignature(target.fnode)); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(regularCall, stackHeight); // stack: ... functionObj directFunct cfw.add(ByteCode.POP); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); // stack: ... functionObj cx scope if (type != Token.NEW) { cfw.addALoad(thisObjLocal); releaseWordLocal(thisObjLocal); // stack: ... functionObj cx scope thisObj } // XXX: this will generate code for the child array the second time, // so expression code generation better not to alter tree structure... generateCallArgArray(node, firstArgChild, true); if (type == Token.NEW) { addScriptRuntimeInvoke( "newObject", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); } else { cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Callable", "call", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); } cfw.markLabel(beyond); } private void generateCallArgArray(Node node, Node argChild, boolean directCall) { int argCount = 0; for (Node child = argChild; child != null; child = child.getNext()) { ++argCount; } // load array object to set arguments if (argCount == 1 && itsOneArgArray >= 0) { cfw.addALoad(itsOneArgArray); } else { addNewObjectArray(argCount); } // Copy arguments into it for (int i = 0; i != argCount; ++i) { // If we are compiling a generator an argument could be the result // of a yield. In that case we will have an immediate on the stack // which we need to avoid if (!isGenerator) { cfw.add(ByteCode.DUP); cfw.addPush(i); } if (!directCall) { generateExpression(argChild, node); } else { // If this has also been a directCall sequence, the Number // flag will have remained set for any parameter so that // the values could be copied directly into the outgoing // args. Here we want to force it to be treated as not in // a Number context, so we set the flag off. int dcp_register = nodeIsDirectCallParameter(argChild); if (dcp_register >= 0) { dcpLoadAsObject(dcp_register); } else { generateExpression(argChild, node); int childNumberFlag = argChild.getIntProp(Node.ISNUMBER_PROP, -1); if (childNumberFlag == Node.BOTH) { addDoubleWrap(); } } } // When compiling generators, any argument to a method may be a // yield expression. Hence we compile the argument first and then // load the argument index and assign the value to the args array. if (isGenerator) { short tempLocal = getNewWordLocal(); cfw.addAStore(tempLocal); cfw.add(ByteCode.CHECKCAST, "[Ljava/lang/Object;"); cfw.add(ByteCode.DUP); cfw.addPush(i); cfw.addALoad(tempLocal); releaseWordLocal(tempLocal); } cfw.add(ByteCode.AASTORE); argChild = argChild.getNext(); } } private void generateFunctionAndThisObj(Node node, Node parent) { // Place on stack (function object, function this) pair int type = node.getType(); switch (node.getType()) { case Token.GETPROPNOWARN: throw Kit.codeBug(); case Token.GETPROP: case Token.GETELEM: { Node target = node.getFirstChild(); generateExpression(target, node); Node id = target.getNext(); if (type == Token.GETPROP) { String property = id.getString(); cfw.addPush(property); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getPropFunctionAndThis", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Callable;"); } else { // Optimizer do not optimize this case for now if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) throw Codegen.badTree(); generateExpression(id, node); // id cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getElemFunctionAndThis", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Callable;"); } break; } case Token.NAME: { String name = node.getString(); cfw.addPush(name); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getNameFunctionAndThis", "(Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Callable;"); break; } default: // including GETVAR generateExpression(node, parent); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getValueFunctionAndThis", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Callable;"); break; } // Get thisObj prepared by get(Name|Prop|Elem|Value)FunctionAndThis cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "lastStoredScriptable", "(Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Scriptable;"); } private void updateLineNumber(Node node) { itsLineNumber = node.getLineno(); if (itsLineNumber == -1) return; cfw.addLineNumberEntry((short)itsLineNumber); } private void visitTryCatchFinally(Jump node, Node child) { /* Save the variable object, in case there are with statements * enclosed by the try block and we catch some exception. * We'll restore it for the catch block so that catch block * statements get the right scope. */ // OPT we only need to do this if there are enclosed WITH // statements; could statically check and omit this if there aren't any. // XXX OPT Maybe instead do syntactic transforms to associate // each 'with' with a try/finally block that does the exitwith. short savedVariableObject = getNewWordLocal(); cfw.addALoad(variableObjectLocal); cfw.addAStore(savedVariableObject); /* * Generate the code for the tree; most of the work is done in IRFactory * and NodeTransformer; Codegen just adds the java handlers for the * javascript catch and finally clauses. */ int startLabel = cfw.acquireLabel(); cfw.markLabel(startLabel, (short)0); Node catchTarget = node.target; Node finallyTarget = node.getFinally(); // create a table for the equivalent of JSR returns if (isGenerator && finallyTarget != null) { FinallyReturnPoint ret = new FinallyReturnPoint(); if (finallys == null) { finallys = new HashMap<Node,FinallyReturnPoint>(); } // add the finally target to hashtable finallys.put(finallyTarget, ret); // add the finally node as well to the hash table finallys.put(finallyTarget.getNext(), ret); } while (child != null) { generateStatement(child); child = child.getNext(); } // control flow skips the handlers int realEnd = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, realEnd); int exceptionLocal = getLocalBlockRegister(node); // javascript handler; unwrap exception and GOTO to javascript // catch area. if (catchTarget != null) { // get the label to goto int catchLabel = catchTarget.labelId(); generateCatchBlock(JAVASCRIPT_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); /* * catch WrappedExceptions, see if they are wrapped * JavaScriptExceptions. Otherwise, rethrow. */ generateCatchBlock(EVALUATOR_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); /* we also need to catch EcmaErrors and feed the associated error object to the handler */ generateCatchBlock(ECMAERROR_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); Context cx = Context.getCurrentContext(); if (cx != null && cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) { generateCatchBlock(THROWABLE_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); } } // finally handler; catch all exceptions, store to a local; JSR to // the finally, then re-throw. if (finallyTarget != null) { int finallyHandler = cfw.acquireLabel(); cfw.markHandler(finallyHandler); cfw.addAStore(exceptionLocal); // reset the variable object local cfw.addALoad(savedVariableObject); cfw.addAStore(variableObjectLocal); // get the label to JSR to int finallyLabel = finallyTarget.labelId(); if (isGenerator) addGotoWithReturn(finallyTarget); else cfw.add(ByteCode.JSR, finallyLabel); // rethrow cfw.addALoad(exceptionLocal); if (isGenerator) cfw.add(ByteCode.CHECKCAST, "java/lang/Throwable"); cfw.add(ByteCode.ATHROW); // mark the handler cfw.addExceptionHandler(startLabel, finallyLabel, finallyHandler, null); // catch any } releaseWordLocal(savedVariableObject); cfw.markLabel(realEnd); } private static final int JAVASCRIPT_EXCEPTION = 0; private static final int EVALUATOR_EXCEPTION = 1; private static final int ECMAERROR_EXCEPTION = 2; private static final int THROWABLE_EXCEPTION = 3; private void generateCatchBlock(int exceptionType, short savedVariableObject, int catchLabel, int startLabel, int exceptionLocal) { int handler = cfw.acquireLabel(); cfw.markHandler(handler); // MS JVM gets cranky if the exception object is left on the stack cfw.addAStore(exceptionLocal); // reset the variable object local cfw.addALoad(savedVariableObject); cfw.addAStore(variableObjectLocal); String exceptionName; if (exceptionType == JAVASCRIPT_EXCEPTION) { exceptionName = "org/mozilla/javascript/JavaScriptException"; } else if (exceptionType == EVALUATOR_EXCEPTION) { exceptionName = "org/mozilla/javascript/EvaluatorException"; } else if (exceptionType == ECMAERROR_EXCEPTION) { exceptionName = "org/mozilla/javascript/EcmaError"; } else if (exceptionType == THROWABLE_EXCEPTION) { exceptionName = "java/lang/Throwable"; } else { throw Kit.codeBug(); } // mark the handler cfw.addExceptionHandler(startLabel, catchLabel, handler, exceptionName); cfw.add(ByteCode.GOTO, catchLabel); } private boolean generateSaveLocals(Node node) { int count = 0; for (int i = 0; i < firstFreeLocal; i++) { if (locals[i] != 0) count++; } if (count == 0) { ((FunctionNode)scriptOrFn).addLiveLocals(node, null); return false; } // calculate the max locals maxLocals = maxLocals > count ? maxLocals : count; // create a locals list int[] ls = new int[count]; int s = 0; for (int i = 0; i < firstFreeLocal; i++) { if (locals[i] != 0) { ls[s] = i; s++; } } // save the locals ((FunctionNode)scriptOrFn).addLiveLocals(node, ls); // save locals generateGetGeneratorLocalsState(); for (int i = 0; i < count; i++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(i); cfw.addALoad(ls[i]); cfw.add(ByteCode.AASTORE); } // pop the array off the stack cfw.add(ByteCode.POP); return true; } private void visitSwitch(Jump switchNode, Node child) { // See comments in IRFactory.createSwitch() for description // of SWITCH node generateExpression(child, switchNode); // save selector value short selector = getNewWordLocal(); cfw.addAStore(selector); for (Jump caseNode = (Jump)child.getNext(); caseNode != null; caseNode = (Jump)caseNode.getNext()) { if (caseNode.getType() != Token.CASE) throw Codegen.badTree(); Node test = caseNode.getFirstChild(); generateExpression(test, caseNode); cfw.addALoad(selector); addScriptRuntimeInvoke("shallowEq", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +")Z"); addGoto(caseNode.target, ByteCode.IFNE); } releaseWordLocal(selector); } private void visitTypeofname(Node node) { if (hasVarsInRegs) { int varIndex = fnCurrent.fnode.getIndexForNameNode(node); if (varIndex >= 0) { if (fnCurrent.isNumberVar(varIndex)) { cfw.addPush("number"); } else if (varIsDirectCallParameter(varIndex)) { int dcp_register = varRegisters[varIndex]; cfw.addALoad(dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); cfw.addALoad(dcp_register); addScriptRuntimeInvoke("typeof", "(Ljava/lang/Object;" +")Ljava/lang/String;"); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addPush("number"); cfw.markLabel(beyond); } else { cfw.addALoad(varRegisters[varIndex]); addScriptRuntimeInvoke("typeof", "(Ljava/lang/Object;" +")Ljava/lang/String;"); } return; } } cfw.addALoad(variableObjectLocal); cfw.addPush(node.getString()); addScriptRuntimeInvoke("typeofName", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/String;"); } /** * Save the current code offset. This saved code offset is used to * compute instruction counts in subsequent calls to * {@link #addInstructionCount()}. */ private void saveCurrentCodeOffset() { savedCodeOffset = cfw.getCurrentCodeOffset(); } /** * Generate calls to ScriptRuntime.addInstructionCount to keep track of * executed instructions and call <code>observeInstructionCount()</code> * if a threshold is exceeded.<br> * Calculates the count from getCurrentCodeOffset - savedCodeOffset */ private void addInstructionCount() { int count = cfw.getCurrentCodeOffset() - savedCodeOffset; // TODO we used to return for count == 0 but that broke the following: // while(true) continue; (see bug 531600) // To be safe, we now always count at least 1 instruction when invoked. addInstructionCount(Math.max(count, 1)); } /** * Generate calls to ScriptRuntime.addInstructionCount to keep track of * executed instructions and call <code>observeInstructionCount()</code> * if a threshold is exceeded.<br> * Takes the count as a parameter - used to add monitoring to loops and * other blocks that don't have any ops - this allows * for monitoring/killing of while(true) loops and such. */ private void addInstructionCount(int count) { cfw.addALoad(contextLocal); cfw.addPush(count); addScriptRuntimeInvoke("addInstructionCount", "(Lorg/mozilla/javascript/Context;" +"I)V"); } private void visitIncDec(Node node) { int incrDecrMask = node.getExistingIntProp(Node.INCRDECR_PROP); Node child = node.getFirstChild(); switch (child.getType()) { case Token.GETVAR: if (!hasVarsInRegs) Kit.codeBug(); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { boolean post = ((incrDecrMask & Node.POST_FLAG) != 0); int varIndex = fnCurrent.getVarIndex(child); short reg = varRegisters[varIndex]; int offset = varIsDirectCallParameter(varIndex) ? 1 : 0; cfw.addDLoad(reg + offset); if (post) { cfw.add(ByteCode.DUP2); } cfw.addPush(1.0); if ((incrDecrMask & Node.DECR_FLAG) == 0) { cfw.add(ByteCode.DADD); } else { cfw.add(ByteCode.DSUB); } if (!post) { cfw.add(ByteCode.DUP2); } cfw.addDStore(reg + offset); } else { boolean post = ((incrDecrMask & Node.POST_FLAG) != 0); int varIndex = fnCurrent.getVarIndex(child); short reg = varRegisters[varIndex]; cfw.addALoad(reg); if (post) { cfw.add(ByteCode.DUP); } addObjectToDouble(); cfw.addPush(1.0); if ((incrDecrMask & Node.DECR_FLAG) == 0) { cfw.add(ByteCode.DADD); } else { cfw.add(ByteCode.DSUB); } addDoubleWrap(); if (!post) { cfw.add(ByteCode.DUP); } cfw.addAStore(reg); break; } break; case Token.NAME: cfw.addALoad(variableObjectLocal); cfw.addPush(child.getString()); // push name cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); addScriptRuntimeInvoke("nameIncrDecr", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"I)Ljava/lang/Object;"); break; case Token.GETPROPNOWARN: throw Kit.codeBug(); case Token.GETPROP: { Node getPropChild = child.getFirstChild(); generateExpression(getPropChild, node); generateExpression(getPropChild.getNext(), node); cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); addScriptRuntimeInvoke("propIncrDecr", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"I)Ljava/lang/Object;"); break; } case Token.GETELEM: { Node elemChild = child.getFirstChild(); generateExpression(elemChild, node); generateExpression(elemChild.getNext(), node); cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); if (elemChild.getNext().getIntProp(Node.ISNUMBER_PROP, -1) != -1) { addOptRuntimeInvoke("elemIncrDecr", "(Ljava/lang/Object;" +"D" +"Lorg/mozilla/javascript/Context;" +"I" +")Ljava/lang/Object;"); } else { addScriptRuntimeInvoke("elemIncrDecr", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Ljava/lang/Object;"); } break; } case Token.GET_REF: { Node refChild = child.getFirstChild(); generateExpression(refChild, node); cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); addScriptRuntimeInvoke( "refIncrDecr", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +"I)Ljava/lang/Object;"); break; } default: Codegen.badTree(); } } private static boolean isArithmeticNode(Node node) { int type = node.getType(); return (type == Token.SUB) || (type == Token.MOD) || (type == Token.DIV) || (type == Token.MUL); } private void visitArithmetic(Node node, int opCode, Node child, Node parent) { int childNumberFlag = node.getIntProp(Node.ISNUMBER_PROP, -1); if (childNumberFlag != -1) { generateExpression(child, node); generateExpression(child.getNext(), node); cfw.add(opCode); } else { boolean childOfArithmetic = isArithmeticNode(parent); generateExpression(child, node); if (!isArithmeticNode(child)) addObjectToDouble(); generateExpression(child.getNext(), node); if (!isArithmeticNode(child.getNext())) addObjectToDouble(); cfw.add(opCode); if (!childOfArithmetic) { addDoubleWrap(); } } } private void visitBitOp(Node node, int type, Node child) { int childNumberFlag = node.getIntProp(Node.ISNUMBER_PROP, -1); generateExpression(child, node); // special-case URSH; work with the target arg as a long, so // that we can return a 32-bit unsigned value, and call // toUint32 instead of toInt32. if (type == Token.URSH) { addScriptRuntimeInvoke("toUint32", "(Ljava/lang/Object;)J"); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); // Looks like we need to explicitly mask the shift to 5 bits - // LUSHR takes 6 bits. cfw.addPush(31); cfw.add(ByteCode.IAND); cfw.add(ByteCode.LUSHR); cfw.add(ByteCode.L2D); addDoubleWrap(); return; } if (childNumberFlag == -1) { addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); } else { addScriptRuntimeInvoke("toInt32", "(D)I"); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toInt32", "(D)I"); } switch (type) { case Token.BITOR: cfw.add(ByteCode.IOR); break; case Token.BITXOR: cfw.add(ByteCode.IXOR); break; case Token.BITAND: cfw.add(ByteCode.IAND); break; case Token.RSH: cfw.add(ByteCode.ISHR); break; case Token.LSH: cfw.add(ByteCode.ISHL); break; default: throw Codegen.badTree(); } cfw.add(ByteCode.I2D); if (childNumberFlag == -1) { addDoubleWrap(); } } private int nodeIsDirectCallParameter(Node node) { if (node.getType() == Token.GETVAR && inDirectCallFunction && !itsForcedObjectParameters) { int varIndex = fnCurrent.getVarIndex(node); if (fnCurrent.isParameter(varIndex)) { return varRegisters[varIndex]; } } return -1; } private boolean varIsDirectCallParameter(int varIndex) { return fnCurrent.isParameter(varIndex) && inDirectCallFunction && !itsForcedObjectParameters; } private void genSimpleCompare(int type, int trueGOTO, int falseGOTO) { if (trueGOTO == -1) throw Codegen.badTree(); switch (type) { case Token.LE : cfw.add(ByteCode.DCMPG); cfw.add(ByteCode.IFLE, trueGOTO); break; case Token.GE : cfw.add(ByteCode.DCMPL); cfw.add(ByteCode.IFGE, trueGOTO); break; case Token.LT : cfw.add(ByteCode.DCMPG); cfw.add(ByteCode.IFLT, trueGOTO); break; case Token.GT : cfw.add(ByteCode.DCMPL); cfw.add(ByteCode.IFGT, trueGOTO); break; default : throw Codegen.badTree(); } if (falseGOTO != -1) cfw.add(ByteCode.GOTO, falseGOTO); } private void visitIfJumpRelOp(Node node, Node child, int trueGOTO, int falseGOTO) { if (trueGOTO == -1 || falseGOTO == -1) throw Codegen.badTree(); int type = node.getType(); Node rChild = child.getNext(); if (type == Token.INSTANCEOF || type == Token.IN) { generateExpression(child, node); generateExpression(rChild, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( (type == Token.INSTANCEOF) ? "instanceOf" : "in", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Z"); cfw.add(ByteCode.IFNE, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); return; } int childNumberFlag = node.getIntProp(Node.ISNUMBER_PROP, -1); int left_dcp_register = nodeIsDirectCallParameter(child); int right_dcp_register = nodeIsDirectCallParameter(rChild); if (childNumberFlag != -1) { // Force numeric context on both parameters and optimize // direct call case as Optimizer currently does not handle it if (childNumberFlag != Node.RIGHT) { // Left already has number content generateExpression(child, node); } else if (left_dcp_register != -1) { dcpLoadAsNumber(left_dcp_register); } else { generateExpression(child, node); addObjectToDouble(); } if (childNumberFlag != Node.LEFT) { // Right already has number content generateExpression(rChild, node); } else if (right_dcp_register != -1) { dcpLoadAsNumber(right_dcp_register); } else { generateExpression(rChild, node); addObjectToDouble(); } genSimpleCompare(type, trueGOTO, falseGOTO); } else { if (left_dcp_register != -1 && right_dcp_register != -1) { // Generate code to dynamically check for number content // if both operands are dcp short stack = cfw.getStackTop(); int leftIsNotNumber = cfw.acquireLabel(); cfw.addALoad(left_dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); cfw.add(ByteCode.IF_ACMPNE, leftIsNotNumber); cfw.addDLoad(left_dcp_register + 1); dcpLoadAsNumber(right_dcp_register); genSimpleCompare(type, trueGOTO, falseGOTO); if (stack != cfw.getStackTop()) throw Codegen.badTree(); cfw.markLabel(leftIsNotNumber); int rightIsNotNumber = cfw.acquireLabel(); cfw.addALoad(right_dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); cfw.add(ByteCode.IF_ACMPNE, rightIsNotNumber); cfw.addALoad(left_dcp_register); addObjectToDouble(); cfw.addDLoad(right_dcp_register + 1); genSimpleCompare(type, trueGOTO, falseGOTO); if (stack != cfw.getStackTop()) throw Codegen.badTree(); cfw.markLabel(rightIsNotNumber); // Load both register as objects to call generic cmp_* cfw.addALoad(left_dcp_register); cfw.addALoad(right_dcp_register); } else { generateExpression(child, node); generateExpression(rChild, node); } if (type == Token.GE || type == Token.GT) { cfw.add(ByteCode.SWAP); } String routine = ((type == Token.LT) || (type == Token.GT)) ? "cmp_LT" : "cmp_LE"; addScriptRuntimeInvoke(routine, "(Ljava/lang/Object;" +"Ljava/lang/Object;" +")Z"); cfw.add(ByteCode.IFNE, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); } } private void visitIfJumpEqOp(Node node, Node child, int trueGOTO, int falseGOTO) { if (trueGOTO == -1 || falseGOTO == -1) throw Codegen.badTree(); short stackInitial = cfw.getStackTop(); int type = node.getType(); Node rChild = child.getNext(); // Optimize if one of operands is null if (child.getType() == Token.NULL || rChild.getType() == Token.NULL) { // eq is symmetric in this case if (child.getType() == Token.NULL) { child = rChild; } generateExpression(child, node); if (type == Token.SHEQ || type == Token.SHNE) { int testCode = (type == Token.SHEQ) ? ByteCode.IFNULL : ByteCode.IFNONNULL; cfw.add(testCode, trueGOTO); } else { if (type != Token.EQ) { // swap false/true targets for != if (type != Token.NE) throw Codegen.badTree(); int tmp = trueGOTO; trueGOTO = falseGOTO; falseGOTO = tmp; } cfw.add(ByteCode.DUP); int undefCheckLabel = cfw.acquireLabel(); cfw.add(ByteCode.IFNONNULL, undefCheckLabel); short stack = cfw.getStackTop(); cfw.add(ByteCode.POP); cfw.add(ByteCode.GOTO, trueGOTO); cfw.markLabel(undefCheckLabel, stack); Codegen.pushUndefined(cfw); cfw.add(ByteCode.IF_ACMPEQ, trueGOTO); } cfw.add(ByteCode.GOTO, falseGOTO); } else { int child_dcp_register = nodeIsDirectCallParameter(child); if (child_dcp_register != -1 && rChild.getType() == Token.TO_OBJECT) { Node convertChild = rChild.getFirstChild(); if (convertChild.getType() == Token.NUMBER) { cfw.addALoad(child_dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int notNumbersLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPNE, notNumbersLabel); cfw.addDLoad(child_dcp_register + 1); cfw.addPush(convertChild.getDouble()); cfw.add(ByteCode.DCMPL); if (type == Token.EQ) cfw.add(ByteCode.IFEQ, trueGOTO); else cfw.add(ByteCode.IFNE, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); cfw.markLabel(notNumbersLabel); // fall thru into generic handling } } generateExpression(child, node); generateExpression(rChild, node); String name; int testCode; switch (type) { case Token.EQ: name = "eq"; testCode = ByteCode.IFNE; break; case Token.NE: name = "eq"; testCode = ByteCode.IFEQ; break; case Token.SHEQ: name = "shallowEq"; testCode = ByteCode.IFNE; break; case Token.SHNE: name = "shallowEq"; testCode = ByteCode.IFEQ; break; default: throw Codegen.badTree(); } addScriptRuntimeInvoke(name, "(Ljava/lang/Object;" +"Ljava/lang/Object;" +")Z"); cfw.add(testCode, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); } if (stackInitial != cfw.getStackTop()) throw Codegen.badTree(); } private void visitSetName(Node node, Node child) { String name = node.getFirstChild().getString(); while (child != null) { generateExpression(child, node); child = child.getNext(); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(name); addScriptRuntimeInvoke( "setName", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } private void visitStrictSetName(Node node, Node child) { String name = node.getFirstChild().getString(); while (child != null) { generateExpression(child, node); child = child.getNext(); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(name); addScriptRuntimeInvoke( "strictSetName", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } private void visitSetConst(Node node, Node child) { String name = node.getFirstChild().getString(); while (child != null) { generateExpression(child, node); child = child.getNext(); } cfw.addALoad(contextLocal); cfw.addPush(name); addScriptRuntimeInvoke( "setConst", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } private void visitGetVar(Node node) { if (!hasVarsInRegs) Kit.codeBug(); int varIndex = fnCurrent.getVarIndex(node); short reg = varRegisters[varIndex]; if (varIsDirectCallParameter(varIndex)) { // Remember that here the isNumber flag means that we // want to use the incoming parameter in a Number // context, so test the object type and convert the // value as necessary. if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { dcpLoadAsNumber(reg); } else { dcpLoadAsObject(reg); } } else if (fnCurrent.isNumberVar(varIndex)) { cfw.addDLoad(reg); } else { cfw.addALoad(reg); } } private void visitSetVar(Node node, Node child, boolean needValue) { if (!hasVarsInRegs) Kit.codeBug(); int varIndex = fnCurrent.getVarIndex(node); generateExpression(child.getNext(), node); boolean isNumber = (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1); short reg = varRegisters[varIndex]; boolean [] constDeclarations = fnCurrent.fnode.getParamAndVarConst(); if (constDeclarations[varIndex]) { if (!needValue) { if (isNumber) cfw.add(ByteCode.POP2); else cfw.add(ByteCode.POP); } } else if (varIsDirectCallParameter(varIndex)) { if (isNumber) { if (needValue) cfw.add(ByteCode.DUP2); cfw.addALoad(reg); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); addDoubleWrap(); cfw.addAStore(reg); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addDStore(reg + 1); cfw.markLabel(beyond); } else { if (needValue) cfw.add(ByteCode.DUP); cfw.addAStore(reg); } } else { boolean isNumberVar = fnCurrent.isNumberVar(varIndex); if (isNumber) { if (isNumberVar) { cfw.addDStore(reg); if (needValue) cfw.addDLoad(reg); } else { if (needValue) cfw.add(ByteCode.DUP2); // Cannot save number in variable since !isNumberVar, // so convert to object addDoubleWrap(); cfw.addAStore(reg); } } else { if (isNumberVar) Kit.codeBug(); cfw.addAStore(reg); if (needValue) cfw.addALoad(reg); } } } private void visitSetConstVar(Node node, Node child, boolean needValue) { if (!hasVarsInRegs) Kit.codeBug(); int varIndex = fnCurrent.getVarIndex(node); generateExpression(child.getNext(), node); boolean isNumber = (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1); short reg = varRegisters[varIndex]; int beyond = cfw.acquireLabel(); int noAssign = cfw.acquireLabel(); if (isNumber) { cfw.addILoad(reg + 2); cfw.add(ByteCode.IFNE, noAssign); short stack = cfw.getStackTop(); cfw.addPush(1); cfw.addIStore(reg + 2); cfw.addDStore(reg); if (needValue) { cfw.addDLoad(reg); cfw.markLabel(noAssign, stack); } else { cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(noAssign, stack); cfw.add(ByteCode.POP2); } } else { cfw.addILoad(reg + 1); cfw.add(ByteCode.IFNE, noAssign); short stack = cfw.getStackTop(); cfw.addPush(1); cfw.addIStore(reg + 1); cfw.addAStore(reg); if (needValue) { cfw.addALoad(reg); cfw.markLabel(noAssign, stack); } else { cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(noAssign, stack); cfw.add(ByteCode.POP); } } cfw.markLabel(beyond); } private void visitGetProp(Node node, Node child) { generateExpression(child, node); // object Node nameChild = child.getNext(); generateExpression(nameChild, node); // the name if (node.getType() == Token.GETPROPNOWARN) { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectPropNoWarn", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); return; } /* for 'this.foo' we call getObjectProp(Scriptable...) which can skip some casting overhead. */ int childType = child.getType(); if (childType == Token.THIS && nameChild.getType() == Token.STRING) { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectProp", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getObjectProp", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"); } } private void visitSetProp(int type, Node node, Node child) { Node objectChild = child; generateExpression(child, node); child = child.getNext(); if (type == Token.SETPROP_OP) { cfw.add(ByteCode.DUP); } Node nameChild = child; generateExpression(child, node); child = child.getNext(); if (type == Token.SETPROP_OP) { // stack: ... object object name -> ... object name object name cfw.add(ByteCode.DUP_X1); //for 'this.foo += ...' we call thisGet which can skip some //casting overhead. if (objectChild.getType() == Token.THIS && nameChild.getType() == Token.STRING) { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectProp", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectProp", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "setObjectProp", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } private void visitSetElem(int type, Node node, Node child) { generateExpression(child, node); child = child.getNext(); if (type == Token.SETELEM_OP) { cfw.add(ByteCode.DUP); } generateExpression(child, node); child = child.getNext(); boolean indexIsNumber = (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1); if (type == Token.SETELEM_OP) { if (indexIsNumber) { // stack: ... object object number // -> ... object number object number cfw.add(ByteCode.DUP2_X1); cfw.addALoad(contextLocal); addOptRuntimeInvoke( "getObjectIndex", "(Ljava/lang/Object;D" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { // stack: ... object object indexObject // -> ... object indexObject object indexObject cfw.add(ByteCode.DUP_X1); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectElem", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } generateExpression(child, node); cfw.addALoad(contextLocal); if (indexIsNumber) { addScriptRuntimeInvoke( "setObjectIndex", "(Ljava/lang/Object;" +"D" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { addScriptRuntimeInvoke( "setObjectElem", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } private void visitDotQuery(Node node, Node child) { updateLineNumber(node); generateExpression(child, node); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("enterDotQuery", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // add push null/pop with label in between to simplify code for loop // continue when it is necessary to pop the null result from // updateDotQuery cfw.add(ByteCode.ACONST_NULL); int queryLoopStart = cfw.acquireLabel(); cfw.markLabel(queryLoopStart); // loop continue jumps here cfw.add(ByteCode.POP); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("updateDotQuery", "(Z" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"); cfw.add(ByteCode.DUP); cfw.add(ByteCode.IFNULL, queryLoopStart); // stack: ... non_null_result_of_updateDotQuery cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("leaveDotQuery", "(Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } private int getLocalBlockRegister(Node node) { Node localBlock = (Node)node.getProp(Node.LOCAL_BLOCK_PROP); int localSlot = localBlock.getExistingIntProp(Node.LOCAL_PROP); return localSlot; } private void dcpLoadAsNumber(int dcp_register) { cfw.addALoad(dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); cfw.addALoad(dcp_register); addObjectToDouble(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addDLoad(dcp_register + 1); cfw.markLabel(beyond); } private void dcpLoadAsObject(int dcp_register) { cfw.addALoad(dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); cfw.addALoad(dcp_register); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addDLoad(dcp_register + 1); addDoubleWrap(); cfw.markLabel(beyond); } private void addGoto(Node target, int jumpcode) { int targetLabel = getTargetLabel(target); cfw.add(jumpcode, targetLabel); } private void addObjectToDouble() { addScriptRuntimeInvoke("toNumber", "(Ljava/lang/Object;)D"); } private void addNewObjectArray(int size) { if (size == 0) { if (itsZeroArgArray >= 0) { cfw.addALoad(itsZeroArgArray); } else { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "emptyArgs", "[Ljava/lang/Object;"); } } else { cfw.addPush(size); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); } } private void addScriptRuntimeInvoke(String methodName, String methodSignature) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org.mozilla.javascript.ScriptRuntime", methodName, methodSignature); } private void addOptRuntimeInvoke(String methodName, String methodSignature) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/optimizer/OptRuntime", methodName, methodSignature); } private void addJumpedBooleanWrap(int trueLabel, int falseLabel) { cfw.markLabel(falseLabel); int skip = cfw.acquireLabel(); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cfw.add(ByteCode.GOTO, skip); cfw.markLabel(trueLabel); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); cfw.markLabel(skip); cfw.adjustStackTop(-1); // only have 1 of true/false } private void addDoubleWrap() { addOptRuntimeInvoke("wrapDouble", "(D)Ljava/lang/Double;"); } /** * Const locals use an extra slot to hold the has-been-assigned-once flag at * runtime. * @param isConst true iff the variable is const * @return the register for the word pair (double/long) */ private short getNewWordPairLocal(boolean isConst) { short result = getConsecutiveSlots(2, isConst); if (result < (MAX_LOCALS - 1)) { locals[result] = 1; locals[result + 1] = 1; if (isConst) locals[result + 2] = 1; if (result == firstFreeLocal) { for (int i = firstFreeLocal + 2; i < MAX_LOCALS; i++) { if (locals[i] == 0) { firstFreeLocal = (short) i; if (localsMax < firstFreeLocal) localsMax = firstFreeLocal; return result; } } } else { return result; } } throw Context.reportRuntimeError("Program too complex " + "(out of locals)"); } private short getNewWordLocal(boolean isConst) { short result = getConsecutiveSlots(1, isConst); if (result < (MAX_LOCALS - 1)) { locals[result] = 1; if (isConst) locals[result + 1] = 1; if (result == firstFreeLocal) { for (int i = firstFreeLocal + 2; i < MAX_LOCALS; i++) { if (locals[i] == 0) { firstFreeLocal = (short) i; if (localsMax < firstFreeLocal) localsMax = firstFreeLocal; return result; } } } else { return result; } } throw Context.reportRuntimeError("Program too complex " + "(out of locals)"); } private short getNewWordLocal() { short result = firstFreeLocal; locals[result] = 1; for (int i = firstFreeLocal + 1; i < MAX_LOCALS; i++) { if (locals[i] == 0) { firstFreeLocal = (short) i; if (localsMax < firstFreeLocal) localsMax = firstFreeLocal; return result; } } throw Context.reportRuntimeError("Program too complex " + "(out of locals)"); } private short getConsecutiveSlots(int count, boolean isConst) { if (isConst) count++; short result = firstFreeLocal; while (true) { if (result >= (MAX_LOCALS - 1)) break; int i; for (i = 0; i < count; i++) if (locals[result + i] != 0) break; if (i >= count) break; result++; } return result; } // This is a valid call only for a local that is allocated by default. private void incReferenceWordLocal(short local) { locals[local]++; } // This is a valid call only for a local that is allocated by default. private void decReferenceWordLocal(short local) { locals[local]--; } private void releaseWordLocal(short local) { if (local < firstFreeLocal) firstFreeLocal = local; locals[local] = 0; } static final int GENERATOR_TERMINATE = -1; static final int GENERATOR_START = 0; static final int GENERATOR_YIELD_START = 1; ClassFileWriter cfw; Codegen codegen; CompilerEnvirons compilerEnv; ScriptNode scriptOrFn; public int scriptOrFnIndex; private int savedCodeOffset; private OptFunctionNode fnCurrent; private boolean isTopLevel; private static final int MAX_LOCALS = 256; private int[] locals; private short firstFreeLocal; private short localsMax; private int itsLineNumber; private boolean hasVarsInRegs; private short[] varRegisters; private boolean inDirectCallFunction; private boolean itsForcedObjectParameters; private int enterAreaStartLabel; private int epilogueLabel; // special known locals. If you add a new local here, be sure // to initialize it to -1 in initBodyGeneration private short variableObjectLocal; private short popvLocal; private short contextLocal; private short argsLocal; private short operationLocal; private short thisObjLocal; private short funObjLocal; private short itsZeroArgArray; private short itsOneArgArray; private short scriptRegexpLocal; private short generatorStateLocal; private boolean isGenerator; private int generatorSwitch; private int maxLocals = 0; private int maxStack = 0; private Map<Node,FinallyReturnPoint> finallys; static class FinallyReturnPoint { public List<Integer> jsrPoints = new ArrayList<Integer>(); public int tableLabel = 0; } }
src/org/mozilla/javascript/optimizer/Codegen.java
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Kemal Bayram * Igor Bukanov * Bob Jervis * Roger Lawrence * Andi Vajda * Hannes Wallnoefer * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.optimizer; import org.mozilla.javascript.*; import org.mozilla.javascript.ast.FunctionNode; import org.mozilla.javascript.ast.Jump; import org.mozilla.javascript.ast.Name; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.classfile.*; import java.util.*; import java.lang.reflect.Constructor; /** * This class generates code for a given IR tree. * * @author Norris Boyd * @author Roger Lawrence */ public class Codegen implements Evaluator { public void captureStackInfo(RhinoException ex) { throw new UnsupportedOperationException(); } public String getSourcePositionFromStack(Context cx, int[] linep) { throw new UnsupportedOperationException(); } public String getPatchedStack(RhinoException ex, String nativeStackTrace) { throw new UnsupportedOperationException(); } public List<String> getScriptStack(RhinoException ex) { throw new UnsupportedOperationException(); } public void setEvalScriptFlag(Script script) { throw new UnsupportedOperationException(); } public Object compile(CompilerEnvirons compilerEnv, ScriptNode tree, String encodedSource, boolean returnFunction) { int serial; synchronized (globalLock) { serial = ++globalSerialClassCounter; } String baseName = "c"; if (tree.getSourceName().length() > 0) { baseName = tree.getSourceName().replaceAll("\\W", "_"); if (!Character.isJavaIdentifierStart(baseName.charAt(0))) { baseName = "_" + baseName; } } String mainClassName = "org.mozilla.javascript.gen." + baseName + "_" + serial; byte[] mainClassBytes = compileToClassFile(compilerEnv, mainClassName, tree, encodedSource, returnFunction); return new Object[] { mainClassName, mainClassBytes }; } public Script createScriptObject(Object bytecode, Object staticSecurityDomain) { Class<?> cl = defineClass(bytecode, staticSecurityDomain); Script script; try { script = (Script)cl.newInstance(); } catch (Exception ex) { throw new RuntimeException ("Unable to instantiate compiled class:" + ex.toString()); } return script; } public Function createFunctionObject(Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain) { Class<?> cl = defineClass(bytecode, staticSecurityDomain); NativeFunction f; try { Constructor<?>ctor = cl.getConstructors()[0]; Object[] initArgs = { scope, cx, Integer.valueOf(0) }; f = (NativeFunction)ctor.newInstance(initArgs); } catch (Exception ex) { throw new RuntimeException ("Unable to instantiate compiled class:"+ex.toString()); } return f; } private Class<?> defineClass(Object bytecode, Object staticSecurityDomain) { Object[] nameBytesPair = (Object[])bytecode; String className = (String)nameBytesPair[0]; byte[] classBytes = (byte[])nameBytesPair[1]; // The generated classes in this case refer only to Rhino classes // which must be accessible through this class loader ClassLoader rhinoLoader = getClass().getClassLoader(); GeneratedClassLoader loader; loader = SecurityController.createLoader(rhinoLoader, staticSecurityDomain); Exception e; try { Class<?> cl = loader.defineClass(className, classBytes); loader.linkClass(cl); return cl; } catch (SecurityException x) { e = x; } catch (IllegalArgumentException x) { e = x; } throw new RuntimeException("Malformed optimizer package " + e); } byte[] compileToClassFile(CompilerEnvirons compilerEnv, String mainClassName, ScriptNode scriptOrFn, String encodedSource, boolean returnFunction) { this.compilerEnv = compilerEnv; transform(scriptOrFn); if (Token.printTrees) { System.out.println(scriptOrFn.toStringTree(scriptOrFn)); } if (returnFunction) { scriptOrFn = scriptOrFn.getFunctionNode(0); } initScriptNodesData(scriptOrFn); this.mainClassName = mainClassName; this.mainClassSignature = ClassFileWriter.classNameToSignature(mainClassName); try { return generateCode(encodedSource); } catch (ClassFileWriter.ClassFileFormatException e) { throw reportClassFileFormatException(scriptOrFn, e.getMessage()); } } private RuntimeException reportClassFileFormatException( ScriptNode scriptOrFn, String message) { String msg = scriptOrFn instanceof FunctionNode ? ScriptRuntime.getMessage2("msg.while.compiling.fn", ((FunctionNode)scriptOrFn).getFunctionName(), message) : ScriptRuntime.getMessage1("msg.while.compiling.script", message); return Context.reportRuntimeError(msg, scriptOrFn.getSourceName(), scriptOrFn.getLineno(), null, 0); } private void transform(ScriptNode tree) { initOptFunctions_r(tree); int optLevel = compilerEnv.getOptimizationLevel(); Map<String,OptFunctionNode> possibleDirectCalls = null; if (optLevel > 0) { /* * Collect all of the contained functions into a hashtable * so that the call optimizer can access the class name & parameter * count for any call it encounters */ if (tree.getType() == Token.SCRIPT) { int functionCount = tree.getFunctionCount(); for (int i = 0; i != functionCount; ++i) { OptFunctionNode ofn = OptFunctionNode.get(tree, i); if (ofn.fnode.getFunctionType() == FunctionNode.FUNCTION_STATEMENT) { String name = ofn.fnode.getName(); if (name.length() != 0) { if (possibleDirectCalls == null) { possibleDirectCalls = new HashMap<String,OptFunctionNode>(); } possibleDirectCalls.put(name, ofn); } } } } } if (possibleDirectCalls != null) { directCallTargets = new ObjArray(); } OptTransformer ot = new OptTransformer(possibleDirectCalls, directCallTargets); ot.transform(tree); if (optLevel > 0) { (new Optimizer()).optimize(tree); } } private static void initOptFunctions_r(ScriptNode scriptOrFn) { for (int i = 0, N = scriptOrFn.getFunctionCount(); i != N; ++i) { FunctionNode fn = scriptOrFn.getFunctionNode(i); new OptFunctionNode(fn); initOptFunctions_r(fn); } } private void initScriptNodesData(ScriptNode scriptOrFn) { ObjArray x = new ObjArray(); collectScriptNodes_r(scriptOrFn, x); int count = x.size(); scriptOrFnNodes = new ScriptNode[count]; x.toArray(scriptOrFnNodes); scriptOrFnIndexes = new ObjToIntMap(count); for (int i = 0; i != count; ++i) { scriptOrFnIndexes.put(scriptOrFnNodes[i], i); } } private static void collectScriptNodes_r(ScriptNode n, ObjArray x) { x.add(n); int nestedCount = n.getFunctionCount(); for (int i = 0; i != nestedCount; ++i) { collectScriptNodes_r(n.getFunctionNode(i), x); } } private byte[] generateCode(String encodedSource) { boolean hasScript = (scriptOrFnNodes[0].getType() == Token.SCRIPT); boolean hasFunctions = (scriptOrFnNodes.length > 1 || !hasScript); String sourceFile = null; if (compilerEnv.isGenerateDebugInfo()) { sourceFile = scriptOrFnNodes[0].getSourceName(); } ClassFileWriter cfw = new ClassFileWriter(mainClassName, SUPER_CLASS_NAME, sourceFile); cfw.addField(ID_FIELD_NAME, "I", ClassFileWriter.ACC_PRIVATE); cfw.addField(DIRECT_CALL_PARENT_FIELD, mainClassSignature, ClassFileWriter.ACC_PRIVATE); cfw.addField(REGEXP_ARRAY_FIELD_NAME, REGEXP_ARRAY_FIELD_TYPE, ClassFileWriter.ACC_PRIVATE); if (hasFunctions) { generateFunctionConstructor(cfw); } if (hasScript) { cfw.addInterface("org/mozilla/javascript/Script"); generateScriptCtor(cfw); generateMain(cfw); generateExecute(cfw); } generateCallMethod(cfw); generateResumeGenerator(cfw); generateNativeFunctionOverrides(cfw, encodedSource); int count = scriptOrFnNodes.length; for (int i = 0; i != count; ++i) { ScriptNode n = scriptOrFnNodes[i]; BodyCodegen bodygen = new BodyCodegen(); bodygen.cfw = cfw; bodygen.codegen = this; bodygen.compilerEnv = compilerEnv; bodygen.scriptOrFn = n; bodygen.scriptOrFnIndex = i; try { bodygen.generateBodyCode(); } catch (ClassFileWriter.ClassFileFormatException e) { throw reportClassFileFormatException(n, e.getMessage()); } if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); generateFunctionInit(cfw, ofn); if (ofn.isTargetOfDirectCall()) { emitDirectConstructor(cfw, ofn); } } } if (directCallTargets != null) { int N = directCallTargets.size(); for (int j = 0; j != N; ++j) { cfw.addField(getDirectTargetFieldName(j), mainClassSignature, ClassFileWriter.ACC_PRIVATE); } } emitRegExpInit(cfw); emitConstantDudeInitializers(cfw); return cfw.toByteArray(); } private void emitDirectConstructor(ClassFileWriter cfw, OptFunctionNode ofn) { /* we generate .. Scriptable directConstruct(<directCallArgs>) { Scriptable newInstance = createObject(cx, scope); Object val = <body-name>(cx, scope, newInstance, <directCallArgs>); if (val instanceof Scriptable) { return (Scriptable) val; } return newInstance; } */ cfw.startMethod(getDirectCtorName(ofn.fnode), getBodyMethodSignature(ofn.fnode), (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); int argCount = ofn.fnode.getParamCount(); int firstLocal = (4 + argCount * 3) + 1; cfw.addALoad(0); // this cfw.addALoad(1); // cx cfw.addALoad(2); // scope cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "org/mozilla/javascript/BaseFunction", "createObject", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(firstLocal); cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(firstLocal); for (int i = 0; i < argCount; i++) { cfw.addALoad(4 + (i * 3)); cfw.addDLoad(5 + (i * 3)); } cfw.addALoad(4 + argCount * 3); cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(ofn.fnode), getBodyMethodSignature(ofn.fnode)); int exitLabel = cfw.acquireLabel(); cfw.add(ByteCode.DUP); // make a copy of direct call result cfw.add(ByteCode.INSTANCEOF, "org/mozilla/javascript/Scriptable"); cfw.add(ByteCode.IFEQ, exitLabel); // cast direct call result cfw.add(ByteCode.CHECKCAST, "org/mozilla/javascript/Scriptable"); cfw.add(ByteCode.ARETURN); cfw.markLabel(exitLabel); cfw.addALoad(firstLocal); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)(firstLocal + 1)); } static boolean isGenerator(ScriptNode node) { return (node.getType() == Token.FUNCTION ) && ((FunctionNode)node).isGenerator(); } // How dispatch to generators works: // Two methods are generated corresponding to a user-written generator. // One of these creates a generator object (NativeGenerator), which is // returned to the user. The other method contains all of the body code // of the generator. // When a user calls a generator, the call() method dispatches control to // to the method that creates the NativeGenerator object. Subsequently when // the user invokes .next(), .send() or any such method on the generator // object, the resumeGenerator() below dispatches the call to the // method corresponding to the generator body. As a matter of convention // the generator body is given the name of the generator activation function // appended by "_gen". private void generateResumeGenerator(ClassFileWriter cfw) { boolean hasGenerators = false; for (int i=0; i < scriptOrFnNodes.length; i++) { if (isGenerator(scriptOrFnNodes[i])) hasGenerators = true; } // if there are no generators defined, we don't implement a // resumeGenerator(). The base class provides a default implementation. if (!hasGenerators) return; cfw.startMethod("resumeGenerator", "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "ILjava/lang/Object;" + "Ljava/lang/Object;)Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // load arguments for dispatch to the corresponding *_gen method cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(4); cfw.addALoad(5); cfw.addILoad(3); cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); int startSwitch = cfw.addTableSwitch(0, scriptOrFnNodes.length - 1); cfw.markTableSwitchDefault(startSwitch); int endlabel = cfw.acquireLabel(); for (int i = 0; i < scriptOrFnNodes.length; i++) { ScriptNode n = scriptOrFnNodes[i]; cfw.markTableSwitchCase(startSwitch, i, (short)6); if (isGenerator(n)) { String type = "(" + mainClassSignature + "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Ljava/lang/Object;" + "Ljava/lang/Object;I)Ljava/lang/Object;"; cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(n) + "_gen", type); cfw.add(ByteCode.ARETURN); } else { cfw.add(ByteCode.GOTO, endlabel); } } cfw.markLabel(endlabel); pushUndefined(cfw); cfw.add(ByteCode.ARETURN); // this method uses as many locals as there are arguments (hence 6) cfw.stopMethod((short)6); } private void generateCallMethod(ClassFileWriter cfw) { cfw.startMethod("call", "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Lorg/mozilla/javascript/Scriptable;" + "[Ljava/lang/Object;)Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // Generate code for: // if (!ScriptRuntime.hasTopCall(cx)) { // return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args); // } int nonTopCallLabel = cfw.acquireLabel(); cfw.addALoad(1); //cx cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "hasTopCall", "(Lorg/mozilla/javascript/Context;" +")Z"); cfw.add(ByteCode.IFNE, nonTopCallLabel); cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(3); cfw.addALoad(4); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "doTopCall", "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); cfw.add(ByteCode.ARETURN); cfw.markLabel(nonTopCallLabel); // Now generate switch to call the real methods cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(3); cfw.addALoad(4); int end = scriptOrFnNodes.length; boolean generateSwitch = (2 <= end); int switchStart = 0; int switchStackTop = 0; if (generateSwitch) { cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); // do switch from (1, end - 1) mapping 0 to // the default case switchStart = cfw.addTableSwitch(1, end - 1); } for (int i = 0; i != end; ++i) { ScriptNode n = scriptOrFnNodes[i]; if (generateSwitch) { if (i == 0) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } else { cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop); } } if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); if (ofn.isTargetOfDirectCall()) { int pcount = ofn.fnode.getParamCount(); if (pcount != 0) { // loop invariant: // stack top == arguments array from addALoad4() for (int p = 0; p != pcount; ++p) { cfw.add(ByteCode.ARRAYLENGTH); cfw.addPush(p); int undefArg = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.IF_ICMPLE, undefArg); // get array[p] cfw.addALoad(4); cfw.addPush(p); cfw.add(ByteCode.AALOAD); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(undefArg); pushUndefined(cfw); cfw.markLabel(beyond); // Only one push cfw.adjustStackTop(-1); cfw.addPush(0.0); // restore invariant cfw.addALoad(4); } } } } cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(n), getBodyMethodSignature(n)); cfw.add(ByteCode.ARETURN); } cfw.stopMethod((short)5); // 5: this, cx, scope, js this, args[] } private void generateMain(ClassFileWriter cfw) { cfw.startMethod("main", "([Ljava/lang/String;)V", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_STATIC)); // load new ScriptImpl() cfw.add(ByteCode.NEW, cfw.getClassName()); cfw.add(ByteCode.DUP); cfw.addInvoke(ByteCode.INVOKESPECIAL, cfw.getClassName(), "<init>", "()V"); // load 'args' cfw.add(ByteCode.ALOAD_0); // Call mainMethodClass.main(Script script, String[] args) cfw.addInvoke(ByteCode.INVOKESTATIC, mainMethodClass, "main", "(Lorg/mozilla/javascript/Script;[Ljava/lang/String;)V"); cfw.add(ByteCode.RETURN); // 1 = String[] args cfw.stopMethod((short)1); } private void generateExecute(ClassFileWriter cfw) { cfw.startMethod("exec", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); final int CONTEXT_ARG = 1; final int SCOPE_ARG = 2; cfw.addLoadThis(); cfw.addALoad(CONTEXT_ARG); cfw.addALoad(SCOPE_ARG); cfw.add(ByteCode.DUP); cfw.add(ByteCode.ACONST_NULL); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, cfw.getClassName(), "call", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); cfw.add(ByteCode.ARETURN); // 3 = this + context + scope cfw.stopMethod((short)3); } private void generateScriptCtor(ClassFileWriter cfw) { cfw.startMethod("<init>", "()V", ClassFileWriter.ACC_PUBLIC); cfw.addLoadThis(); cfw.addInvoke(ByteCode.INVOKESPECIAL, SUPER_CLASS_NAME, "<init>", "()V"); // set id to 0 cfw.addLoadThis(); cfw.addPush(0); cfw.add(ByteCode.PUTFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); cfw.add(ByteCode.RETURN); // 1 parameter = this cfw.stopMethod((short)1); } private void generateFunctionConstructor(ClassFileWriter cfw) { final int SCOPE_ARG = 1; final int CONTEXT_ARG = 2; final int ID_ARG = 3; cfw.startMethod("<init>", FUNCTION_CONSTRUCTOR_SIGNATURE, ClassFileWriter.ACC_PUBLIC); cfw.addALoad(0); cfw.addInvoke(ByteCode.INVOKESPECIAL, SUPER_CLASS_NAME, "<init>", "()V"); cfw.addLoadThis(); cfw.addILoad(ID_ARG); cfw.add(ByteCode.PUTFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); cfw.addLoadThis(); cfw.addALoad(CONTEXT_ARG); cfw.addALoad(SCOPE_ARG); int start = (scriptOrFnNodes[0].getType() == Token.SCRIPT) ? 1 : 0; int end = scriptOrFnNodes.length; if (start == end) throw badTree(); boolean generateSwitch = (2 <= end - start); int switchStart = 0; int switchStackTop = 0; if (generateSwitch) { cfw.addILoad(ID_ARG); // do switch from (start + 1, end - 1) mapping start to // the default case switchStart = cfw.addTableSwitch(start + 1, end - 1); } for (int i = start; i != end; ++i) { if (generateSwitch) { if (i == start) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } else { cfw.markTableSwitchCase(switchStart, i - 1 - start, switchStackTop); } } OptFunctionNode ofn = OptFunctionNode.get(scriptOrFnNodes[i]); cfw.addInvoke(ByteCode.INVOKESPECIAL, mainClassName, getFunctionInitMethodName(ofn), FUNCTION_INIT_SIGNATURE); cfw.add(ByteCode.RETURN); } // 4 = this + scope + context + id cfw.stopMethod((short)4); } private void generateFunctionInit(ClassFileWriter cfw, OptFunctionNode ofn) { final int CONTEXT_ARG = 1; final int SCOPE_ARG = 2; cfw.startMethod(getFunctionInitMethodName(ofn), FUNCTION_INIT_SIGNATURE, (short)(ClassFileWriter.ACC_PRIVATE | ClassFileWriter.ACC_FINAL)); // Call NativeFunction.initScriptFunction cfw.addLoadThis(); cfw.addALoad(CONTEXT_ARG); cfw.addALoad(SCOPE_ARG); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "org/mozilla/javascript/NativeFunction", "initScriptFunction", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")V"); // precompile all regexp literals int regexpCount = ofn.fnode.getRegexpCount(); if (regexpCount != 0) { cfw.addLoadThis(); pushRegExpArray(cfw, ofn.fnode, CONTEXT_ARG, SCOPE_ARG); cfw.add(ByteCode.PUTFIELD, mainClassName, REGEXP_ARRAY_FIELD_NAME, REGEXP_ARRAY_FIELD_TYPE); } cfw.add(ByteCode.RETURN); // 3 = (scriptThis/functionRef) + scope + context cfw.stopMethod((short)3); } private void generateNativeFunctionOverrides(ClassFileWriter cfw, String encodedSource) { // Override NativeFunction.getLanguageVersion() with // public int getLanguageVersion() { return <version-constant>; } cfw.startMethod("getLanguageVersion", "()I", ClassFileWriter.ACC_PUBLIC); cfw.addPush(compilerEnv.getLanguageVersion()); cfw.add(ByteCode.IRETURN); // 1: this and no argument or locals cfw.stopMethod((short)1); // The rest of NativeFunction overrides require specific code for each // script/function id final int Do_getFunctionName = 0; final int Do_getParamCount = 1; final int Do_getParamAndVarCount = 2; final int Do_getParamOrVarName = 3; final int Do_getEncodedSource = 4; final int Do_getParamOrVarConst = 5; final int SWITCH_COUNT = 6; for (int methodIndex = 0; methodIndex != SWITCH_COUNT; ++methodIndex) { if (methodIndex == Do_getEncodedSource && encodedSource == null) { continue; } // Generate: // prologue; // switch over function id to implement function-specific action // epilogue short methodLocals; switch (methodIndex) { case Do_getFunctionName: methodLocals = 1; // Only this cfw.startMethod("getFunctionName", "()Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamCount: methodLocals = 1; // Only this cfw.startMethod("getParamCount", "()I", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamAndVarCount: methodLocals = 1; // Only this cfw.startMethod("getParamAndVarCount", "()I", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamOrVarName: methodLocals = 1 + 1; // this + paramOrVarIndex cfw.startMethod("getParamOrVarName", "(I)Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC); break; case Do_getParamOrVarConst: methodLocals = 1 + 1 + 1; // this + paramOrVarName cfw.startMethod("getParamOrVarConst", "(I)Z", ClassFileWriter.ACC_PUBLIC); break; case Do_getEncodedSource: methodLocals = 1; // Only this cfw.startMethod("getEncodedSource", "()Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC); cfw.addPush(encodedSource); break; default: throw Kit.codeBug(); } int count = scriptOrFnNodes.length; int switchStart = 0; int switchStackTop = 0; if (count > 1) { // Generate switch but only if there is more then one // script/function cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); // do switch from 1 .. count - 1 mapping 0 to the default case switchStart = cfw.addTableSwitch(1, count - 1); } for (int i = 0; i != count; ++i) { ScriptNode n = scriptOrFnNodes[i]; if (i == 0) { if (count > 1) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } } else { cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop); } // Impelemnet method-specific switch code switch (methodIndex) { case Do_getFunctionName: // Push function name if (n.getType() == Token.SCRIPT) { cfw.addPush(""); } else { String name = ((FunctionNode)n).getName(); cfw.addPush(name); } cfw.add(ByteCode.ARETURN); break; case Do_getParamCount: // Push number of defined parameters cfw.addPush(n.getParamCount()); cfw.add(ByteCode.IRETURN); break; case Do_getParamAndVarCount: // Push number of defined parameters and declared variables cfw.addPush(n.getParamAndVarCount()); cfw.add(ByteCode.IRETURN); break; case Do_getParamOrVarName: // Push name of parameter using another switch // over paramAndVarCount int paramAndVarCount = n.getParamAndVarCount(); if (paramAndVarCount == 0) { // The runtime should never call the method in this // case but to make bytecode verifier happy return null // as throwing execption takes more code cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.ARETURN); } else if (paramAndVarCount == 1) { // As above do not check for valid index but always // return the name of the first param cfw.addPush(n.getParamOrVarName(0)); cfw.add(ByteCode.ARETURN); } else { // Do switch over getParamOrVarName cfw.addILoad(1); // param or var index // do switch from 1 .. paramAndVarCount - 1 mapping 0 // to the default case int paramSwitchStart = cfw.addTableSwitch( 1, paramAndVarCount - 1); for (int j = 0; j != paramAndVarCount; ++j) { if (cfw.getStackTop() != 0) Kit.codeBug(); String s = n.getParamOrVarName(j); if (j == 0) { cfw.markTableSwitchDefault(paramSwitchStart); } else { cfw.markTableSwitchCase(paramSwitchStart, j - 1, 0); } cfw.addPush(s); cfw.add(ByteCode.ARETURN); } } break; case Do_getParamOrVarConst: // Push name of parameter using another switch // over paramAndVarCount paramAndVarCount = n.getParamAndVarCount(); boolean [] constness = n.getParamAndVarConst(); if (paramAndVarCount == 0) { // The runtime should never call the method in this // case but to make bytecode verifier happy return null // as throwing execption takes more code cfw.add(ByteCode.ICONST_0); cfw.add(ByteCode.IRETURN); } else if (paramAndVarCount == 1) { // As above do not check for valid index but always // return the name of the first param cfw.addPush(constness[0]); cfw.add(ByteCode.IRETURN); } else { // Do switch over getParamOrVarName cfw.addILoad(1); // param or var index // do switch from 1 .. paramAndVarCount - 1 mapping 0 // to the default case int paramSwitchStart = cfw.addTableSwitch( 1, paramAndVarCount - 1); for (int j = 0; j != paramAndVarCount; ++j) { if (cfw.getStackTop() != 0) Kit.codeBug(); if (j == 0) { cfw.markTableSwitchDefault(paramSwitchStart); } else { cfw.markTableSwitchCase(paramSwitchStart, j - 1, 0); } cfw.addPush(constness[j]); cfw.add(ByteCode.IRETURN); } } break; case Do_getEncodedSource: // Push number encoded source start and end // to prepare for encodedSource.substring(start, end) cfw.addPush(n.getEncodedSourceStart()); cfw.addPush(n.getEncodedSourceEnd()); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "substring", "(II)Ljava/lang/String;"); cfw.add(ByteCode.ARETURN); break; default: throw Kit.codeBug(); } } cfw.stopMethod(methodLocals); } } private void emitRegExpInit(ClassFileWriter cfw) { // precompile all regexp literals int totalRegCount = 0; for (int i = 0; i != scriptOrFnNodes.length; ++i) { totalRegCount += scriptOrFnNodes[i].getRegexpCount(); } if (totalRegCount == 0) { return; } cfw.startMethod(REGEXP_INIT_METHOD_NAME, REGEXP_INIT_METHOD_SIGNATURE, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE | ClassFileWriter.ACC_SYNCHRONIZED)); cfw.addField("_reInitDone", "Z", (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); cfw.add(ByteCode.GETSTATIC, mainClassName, "_reInitDone", "Z"); int doInit = cfw.acquireLabel(); cfw.add(ByteCode.IFEQ, doInit); cfw.add(ByteCode.RETURN); cfw.markLabel(doInit); for (int i = 0; i != scriptOrFnNodes.length; ++i) { ScriptNode n = scriptOrFnNodes[i]; int regCount = n.getRegexpCount(); for (int j = 0; j != regCount; ++j) { String reFieldName = getCompiledRegexpName(n, j); String reFieldType = "Ljava/lang/Object;"; String reString = n.getRegexpString(j); String reFlags = n.getRegexpFlags(j); cfw.addField(reFieldName, reFieldType, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); cfw.addALoad(0); // proxy cfw.addALoad(1); // context cfw.addPush(reString); if (reFlags == null) { cfw.add(ByteCode.ACONST_NULL); } else { cfw.addPush(reFlags); } cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/RegExpProxy", "compileRegExp", "(Lorg/mozilla/javascript/Context;" +"Ljava/lang/String;Ljava/lang/String;" +")Ljava/lang/Object;"); cfw.add(ByteCode.PUTSTATIC, mainClassName, reFieldName, reFieldType); } } cfw.addPush(1); cfw.add(ByteCode.PUTSTATIC, mainClassName, "_reInitDone", "Z"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)2); } private void emitConstantDudeInitializers(ClassFileWriter cfw) { int N = itsConstantListSize; if (N == 0) return; cfw.startMethod("<clinit>", "()V", (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_FINAL)); double[] array = itsConstantList; for (int i = 0; i != N; ++i) { double num = array[i]; String constantName = "_k" + i; String constantType = getStaticConstantWrapperType(num); cfw.addField(constantName, constantType, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); int inum = (int)num; if (inum == num) { cfw.add(ByteCode.NEW, "java/lang/Integer"); cfw.add(ByteCode.DUP); cfw.addPush(inum); cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Integer", "<init>", "(I)V"); } else { cfw.addPush(num); addDoubleWrap(cfw); } cfw.add(ByteCode.PUTSTATIC, mainClassName, constantName, constantType); } cfw.add(ByteCode.RETURN); cfw.stopMethod((short)0); } void pushRegExpArray(ClassFileWriter cfw, ScriptNode n, int contextArg, int scopeArg) { int regexpCount = n.getRegexpCount(); if (regexpCount == 0) throw badTree(); cfw.addPush(regexpCount); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); cfw.addALoad(contextArg); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "checkRegExpProxy", "(Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/RegExpProxy;"); // Stack: proxy, array cfw.add(ByteCode.DUP); cfw.addALoad(contextArg); cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, REGEXP_INIT_METHOD_NAME, REGEXP_INIT_METHOD_SIGNATURE); for (int i = 0; i != regexpCount; ++i) { // Stack: proxy, array cfw.add(ByteCode.DUP2); cfw.addALoad(contextArg); cfw.addALoad(scopeArg); cfw.add(ByteCode.GETSTATIC, mainClassName, getCompiledRegexpName(n, i), "Ljava/lang/Object;"); // Stack: compiledRegExp, scope, cx, proxy, array, proxy, array cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/RegExpProxy", "wrapRegExp", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); // Stack: wrappedRegExp, array, proxy, array cfw.addPush(i); cfw.add(ByteCode.SWAP); cfw.add(ByteCode.AASTORE); // Stack: proxy, array } // remove proxy cfw.add(ByteCode.POP); } void pushNumberAsObject(ClassFileWriter cfw, double num) { if (num == 0.0) { if (1 / num > 0) { // +0.0 cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "zeroObj", "Ljava/lang/Double;"); } else { cfw.addPush(num); addDoubleWrap(cfw); } } else if (num == 1.0) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "oneObj", "Ljava/lang/Double;"); return; } else if (num == -1.0) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "minusOneObj", "Ljava/lang/Double;"); } else if (num != num) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "NaNobj", "Ljava/lang/Double;"); } else if (itsConstantListSize >= 2000) { // There appears to be a limit in the JVM on either the number // of static fields in a class or the size of the class // initializer. Either way, we can't have any more than 2000 // statically init'd constants. cfw.addPush(num); addDoubleWrap(cfw); } else { int N = itsConstantListSize; int index = 0; if (N == 0) { itsConstantList = new double[64]; } else { double[] array = itsConstantList; while (index != N && array[index] != num) { ++index; } if (N == array.length) { array = new double[N * 2]; System.arraycopy(itsConstantList, 0, array, 0, N); itsConstantList = array; } } if (index == N) { itsConstantList[N] = num; itsConstantListSize = N + 1; } String constantName = "_k" + index; String constantType = getStaticConstantWrapperType(num); cfw.add(ByteCode.GETSTATIC, mainClassName, constantName, constantType); } } private static void addDoubleWrap(ClassFileWriter cfw) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/optimizer/OptRuntime", "wrapDouble", "(D)Ljava/lang/Double;"); } private static String getStaticConstantWrapperType(double num) { int inum = (int)num; if (inum == num) { return "Ljava/lang/Integer;"; } else { return "Ljava/lang/Double;"; } } static void pushUndefined(ClassFileWriter cfw) { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/Undefined", "instance", "Ljava/lang/Object;"); } int getIndex(ScriptNode n) { return scriptOrFnIndexes.getExisting(n); } static String getDirectTargetFieldName(int i) { return "_dt" + i; } String getDirectCtorName(ScriptNode n) { return "_n" + getIndex(n); } String getBodyMethodName(ScriptNode n) { return "_c_" + cleanName(n) + "_" + getIndex(n); } /** * Gets a Java-compatible "informative" name for the the ScriptOrFnNode */ String cleanName(final ScriptNode n) { String result = ""; if (n instanceof FunctionNode) { Name name = ((FunctionNode) n).getFunctionName(); if (name == null) { result = "anonymous"; } else { result = name.getIdentifier(); } } else { result = "script"; } return result; } String getBodyMethodSignature(ScriptNode n) { StringBuffer sb = new StringBuffer(); sb.append('('); sb.append(mainClassSignature); sb.append("Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;"); if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); if (ofn.isTargetOfDirectCall()) { int pCount = ofn.fnode.getParamCount(); for (int i = 0; i != pCount; i++) { sb.append("Ljava/lang/Object;D"); } } } sb.append("[Ljava/lang/Object;)Ljava/lang/Object;"); return sb.toString(); } String getFunctionInitMethodName(OptFunctionNode ofn) { return "_i"+getIndex(ofn.fnode); } String getCompiledRegexpName(ScriptNode n, int regexpIndex) { return "_re"+getIndex(n)+"_"+regexpIndex; } static RuntimeException badTree() { throw new RuntimeException("Bad tree in codegen"); } void setMainMethodClass(String className) { mainMethodClass = className; } static final String DEFAULT_MAIN_METHOD_CLASS = "org.mozilla.javascript.optimizer.OptRuntime"; private static final String SUPER_CLASS_NAME = "org.mozilla.javascript.NativeFunction"; static final String DIRECT_CALL_PARENT_FIELD = "_dcp"; private static final String ID_FIELD_NAME = "_id"; private static final String REGEXP_INIT_METHOD_NAME = "_reInit"; private static final String REGEXP_INIT_METHOD_SIGNATURE = "(Lorg/mozilla/javascript/RegExpProxy;" +"Lorg/mozilla/javascript/Context;" +")V"; static final String REGEXP_ARRAY_FIELD_NAME = "_re"; static final String REGEXP_ARRAY_FIELD_TYPE = "[Ljava/lang/Object;"; static final String FUNCTION_INIT_SIGNATURE = "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")V"; static final String FUNCTION_CONSTRUCTOR_SIGNATURE = "(Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;I)V"; private static final Object globalLock = new Object(); private static int globalSerialClassCounter; private CompilerEnvirons compilerEnv; private ObjArray directCallTargets; ScriptNode[] scriptOrFnNodes; private ObjToIntMap scriptOrFnIndexes; private String mainMethodClass = DEFAULT_MAIN_METHOD_CLASS; String mainClassName; String mainClassSignature; private double[] itsConstantList; private int itsConstantListSize; } class BodyCodegen { void generateBodyCode() { isGenerator = Codegen.isGenerator(scriptOrFn); // generate the body of the current function or script object initBodyGeneration(); if (isGenerator) { // All functions in the generated bytecode have a unique name. Every // generator has a unique prefix followed by _gen String type = "(" + codegen.mainClassSignature + "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Ljava/lang/Object;" + "Ljava/lang/Object;I)Ljava/lang/Object;"; cfw.startMethod(codegen.getBodyMethodName(scriptOrFn) + "_gen", type, (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); } else { cfw.startMethod(codegen.getBodyMethodName(scriptOrFn), codegen.getBodyMethodSignature(scriptOrFn), (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); } generatePrologue(); Node treeTop; if (fnCurrent != null) { treeTop = scriptOrFn.getLastChild(); } else { treeTop = scriptOrFn; } generateStatement(treeTop); generateEpilogue(); cfw.stopMethod((short)(localsMax + 1)); if (isGenerator) { // generate the user visible method which when invoked will // return a generator object generateGenerator(); } } // This creates a the user-facing function that returns a NativeGenerator // object. private void generateGenerator() { cfw.startMethod(codegen.getBodyMethodName(scriptOrFn), codegen.getBodyMethodSignature(scriptOrFn), (short)(ClassFileWriter.ACC_STATIC | ClassFileWriter.ACC_PRIVATE)); initBodyGeneration(); argsLocal = firstFreeLocal++; localsMax = firstFreeLocal; // get top level scope if (fnCurrent != null && !inDirectCallFunction && (!compilerEnv.isUseDynamicScope() || fnCurrent.fnode.getIgnoreDynamicScope())) { // Unless we're either in a direct call or using dynamic scope, // use the enclosing scope of the function as our variable object. cfw.addALoad(funObjLocal); cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } // generators are forced to have an activation record cfw.addALoad(funObjLocal); cfw.addALoad(variableObjectLocal); cfw.addALoad(argsLocal); addScriptRuntimeInvoke("createFunctionActivation", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // create a function object cfw.add(ByteCode.NEW, codegen.mainClassName); // Call function constructor cfw.add(ByteCode.DUP); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' cfw.addPush(scriptOrFnIndex); cfw.addInvoke(ByteCode.INVOKESPECIAL, codegen.mainClassName, "<init>", Codegen.FUNCTION_CONSTRUCTOR_SIGNATURE); // Init mainScript field cfw.add(ByteCode.DUP); if (isTopLevel) Kit.codeBug(); // Only functions can be generators cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); cfw.add(ByteCode.PUTFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); generateNestedFunctionInits(); // create the NativeGenerator object that we return cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addLoadConstant(maxLocals); cfw.addLoadConstant(maxStack); addOptRuntimeInvoke("createNativeGenerator", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;II" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)(localsMax + 1)); } private void generateNestedFunctionInits() { int functionCount = scriptOrFn.getFunctionCount(); for (int i = 0; i != functionCount; i++) { OptFunctionNode ofn = OptFunctionNode.get(scriptOrFn, i); if (ofn.fnode.getFunctionType() == FunctionNode.FUNCTION_STATEMENT) { visitFunction(ofn, FunctionNode.FUNCTION_STATEMENT); } } } private void initBodyGeneration() { isTopLevel = (scriptOrFn == codegen.scriptOrFnNodes[0]); varRegisters = null; if (scriptOrFn.getType() == Token.FUNCTION) { fnCurrent = OptFunctionNode.get(scriptOrFn); hasVarsInRegs = !fnCurrent.fnode.requiresActivation(); if (hasVarsInRegs) { int n = fnCurrent.fnode.getParamAndVarCount(); if (n != 0) { varRegisters = new short[n]; } } inDirectCallFunction = fnCurrent.isTargetOfDirectCall(); if (inDirectCallFunction && !hasVarsInRegs) Codegen.badTree(); } else { fnCurrent = null; hasVarsInRegs = false; inDirectCallFunction = false; } locals = new int[MAX_LOCALS]; funObjLocal = 0; contextLocal = 1; variableObjectLocal = 2; thisObjLocal = 3; localsMax = (short) 4; // number of parms + "this" firstFreeLocal = 4; popvLocal = -1; argsLocal = -1; itsZeroArgArray = -1; itsOneArgArray = -1; scriptRegexpLocal = -1; epilogueLabel = -1; enterAreaStartLabel = -1; generatorStateLocal = -1; } /** * Generate the prologue for a function or script. */ private void generatePrologue() { if (inDirectCallFunction) { int directParameterCount = scriptOrFn.getParamCount(); // 0 is reserved for function Object 'this' // 1 is reserved for context // 2 is reserved for parentScope // 3 is reserved for script 'this' if (firstFreeLocal != 4) Kit.codeBug(); for (int i = 0; i != directParameterCount; ++i) { varRegisters[i] = firstFreeLocal; // 3 is 1 for Object parm and 2 for double parm firstFreeLocal += 3; } if (!fnCurrent.getParameterNumberContext()) { // make sure that all parameters are objects itsForcedObjectParameters = true; for (int i = 0; i != directParameterCount; ++i) { short reg = varRegisters[i]; cfw.addALoad(reg); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isObjectLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPNE, isObjectLabel); cfw.addDLoad(reg + 1); addDoubleWrap(); cfw.addAStore(reg); cfw.markLabel(isObjectLabel); } } } if (fnCurrent != null && !inDirectCallFunction && (!compilerEnv.isUseDynamicScope() || fnCurrent.fnode.getIgnoreDynamicScope())) { // Unless we're either in a direct call or using dynamic scope, // use the enclosing scope of the function as our variable object. cfw.addALoad(funObjLocal); cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } // reserve 'args[]' argsLocal = firstFreeLocal++; localsMax = firstFreeLocal; // Generate Generator specific prelude if (isGenerator) { // reserve 'args[]' operationLocal = firstFreeLocal++; localsMax = firstFreeLocal; // Local 3 is a reference to a GeneratorState object. The rest // of codegen expects local 3 to be a reference to the thisObj. // So move the value in local 3 to generatorStateLocal, and load // the saved thisObj from the GeneratorState object. cfw.addALoad(thisObjLocal); generatorStateLocal = firstFreeLocal++; localsMax = firstFreeLocal; cfw.add(ByteCode.CHECKCAST, OptRuntime.GeneratorState.CLASS_NAME); cfw.add(ByteCode.DUP); cfw.addAStore(generatorStateLocal); cfw.add(ByteCode.GETFIELD, OptRuntime.GeneratorState.CLASS_NAME, OptRuntime.GeneratorState.thisObj_NAME, OptRuntime.GeneratorState.thisObj_TYPE); cfw.addAStore(thisObjLocal); if (epilogueLabel == -1) { epilogueLabel = cfw.acquireLabel(); } List<Node> targets = ((FunctionNode)scriptOrFn).getResumptionPoints(); if (targets != null) { // get resumption point generateGetGeneratorResumptionPoint(); // generate dispatch table generatorSwitch = cfw.addTableSwitch(0, targets.size() + GENERATOR_START); generateCheckForThrowOrClose(-1, false, GENERATOR_START); } } if (fnCurrent == null) { // See comments in case Token.REGEXP if (scriptOrFn.getRegexpCount() != 0) { scriptRegexpLocal = getNewWordLocal(); codegen.pushRegExpArray(cfw, scriptOrFn, contextLocal, variableObjectLocal); cfw.addAStore(scriptRegexpLocal); } } if (compilerEnv.isGenerateObserverCount()) saveCurrentCodeOffset(); if (hasVarsInRegs) { // No need to create activation. Pad arguments if need be. int parmCount = scriptOrFn.getParamCount(); if (parmCount > 0 && !inDirectCallFunction) { // Set up args array // check length of arguments, pad if need be cfw.addALoad(argsLocal); cfw.add(ByteCode.ARRAYLENGTH); cfw.addPush(parmCount); int label = cfw.acquireLabel(); cfw.add(ByteCode.IF_ICMPGE, label); cfw.addALoad(argsLocal); cfw.addPush(parmCount); addScriptRuntimeInvoke("padArguments", "([Ljava/lang/Object;I" +")[Ljava/lang/Object;"); cfw.addAStore(argsLocal); cfw.markLabel(label); } int paramCount = fnCurrent.fnode.getParamCount(); int varCount = fnCurrent.fnode.getParamAndVarCount(); boolean [] constDeclarations = fnCurrent.fnode.getParamAndVarConst(); // REMIND - only need to initialize the vars that don't get a value // before the next call and are used in the function short firstUndefVar = -1; for (int i = 0; i != varCount; ++i) { short reg = -1; if (i < paramCount) { if (!inDirectCallFunction) { reg = getNewWordLocal(); cfw.addALoad(argsLocal); cfw.addPush(i); cfw.add(ByteCode.AALOAD); cfw.addAStore(reg); } } else if (fnCurrent.isNumberVar(i)) { reg = getNewWordPairLocal(constDeclarations[i]); cfw.addPush(0.0); cfw.addDStore(reg); } else { reg = getNewWordLocal(constDeclarations[i]); if (firstUndefVar == -1) { Codegen.pushUndefined(cfw); firstUndefVar = reg; } else { cfw.addALoad(firstUndefVar); } cfw.addAStore(reg); } if (reg >= 0) { if (constDeclarations[i]) { cfw.addPush(0); cfw.addIStore(reg + (fnCurrent.isNumberVar(i) ? 2 : 1)); } varRegisters[i] = reg; } // Add debug table entry if we're generating debug info if (compilerEnv.isGenerateDebugInfo()) { String name = fnCurrent.fnode.getParamOrVarName(i); String type = fnCurrent.isNumberVar(i) ? "D" : "Ljava/lang/Object;"; int startPC = cfw.getCurrentCodeOffset(); if (reg < 0) { reg = varRegisters[i]; } cfw.addVariableDescriptor(name, type, startPC, reg); } } // Skip creating activation object. return; } // skip creating activation object for the body of a generator. The // activation record required by a generator has already been created // in generateGenerator(). if (isGenerator) return; String debugVariableName; if (fnCurrent != null) { debugVariableName = "activation"; cfw.addALoad(funObjLocal); cfw.addALoad(variableObjectLocal); cfw.addALoad(argsLocal); addScriptRuntimeInvoke("createFunctionActivation", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("enterActivationFunction", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")V"); } else { debugVariableName = "global"; cfw.addALoad(funObjLocal); cfw.addALoad(thisObjLocal); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(0); // false to indicate it is not eval script addScriptRuntimeInvoke("initScript", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Z" +")V"); } enterAreaStartLabel = cfw.acquireLabel(); epilogueLabel = cfw.acquireLabel(); cfw.markLabel(enterAreaStartLabel); generateNestedFunctionInits(); // default is to generate debug info if (compilerEnv.isGenerateDebugInfo()) { cfw.addVariableDescriptor(debugVariableName, "Lorg/mozilla/javascript/Scriptable;", cfw.getCurrentCodeOffset(), variableObjectLocal); } if (fnCurrent == null) { // OPT: use dataflow to prove that this assignment is dead popvLocal = getNewWordLocal(); Codegen.pushUndefined(cfw); cfw.addAStore(popvLocal); int linenum = scriptOrFn.getEndLineno(); if (linenum != -1) cfw.addLineNumberEntry((short)linenum); } else { if (fnCurrent.itsContainsCalls0) { itsZeroArgArray = getNewWordLocal(); cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "emptyArgs", "[Ljava/lang/Object;"); cfw.addAStore(itsZeroArgArray); } if (fnCurrent.itsContainsCalls1) { itsOneArgArray = getNewWordLocal(); cfw.addPush(1); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); cfw.addAStore(itsOneArgArray); } } } private void generateGetGeneratorResumptionPoint() { cfw.addALoad(generatorStateLocal); cfw.add(ByteCode.GETFIELD, OptRuntime.GeneratorState.CLASS_NAME, OptRuntime.GeneratorState.resumptionPoint_NAME, OptRuntime.GeneratorState.resumptionPoint_TYPE); } private void generateSetGeneratorResumptionPoint(int nextState) { cfw.addALoad(generatorStateLocal); cfw.addLoadConstant(nextState); cfw.add(ByteCode.PUTFIELD, OptRuntime.GeneratorState.CLASS_NAME, OptRuntime.GeneratorState.resumptionPoint_NAME, OptRuntime.GeneratorState.resumptionPoint_TYPE); } private void generateGetGeneratorStackState() { cfw.addALoad(generatorStateLocal); addOptRuntimeInvoke("getGeneratorStackState", "(Ljava/lang/Object;)[Ljava/lang/Object;"); } private void generateEpilogue() { if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); if (isGenerator) { // generate locals initialization Map<Node,int[]> liveLocals = ((FunctionNode)scriptOrFn).getLiveLocals(); if (liveLocals != null) { List<Node> nodes = ((FunctionNode)scriptOrFn).getResumptionPoints(); for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); int[] live = liveLocals.get(node); if (live != null) { cfw.markTableSwitchCase(generatorSwitch, getNextGeneratorState(node)); generateGetGeneratorLocalsState(); for (int j = 0; j < live.length; j++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(j); cfw.add(ByteCode.AALOAD); cfw.addAStore(live[j]); } cfw.add(ByteCode.POP); cfw.add(ByteCode.GOTO, getTargetLabel(node)); } } } // generate dispatch tables for finally if (finallys != null) { for (Node n: finallys.keySet()) { if (n.getType() == Token.FINALLY) { FinallyReturnPoint ret = finallys.get(n); // the finally will jump here cfw.markLabel(ret.tableLabel, (short)1); // start generating a dispatch table int startSwitch = cfw.addTableSwitch(0, ret.jsrPoints.size() - 1); int c = 0; cfw.markTableSwitchDefault(startSwitch); for (int i = 0; i < ret.jsrPoints.size(); i++) { // generate gotos back to the JSR location cfw.markTableSwitchCase(startSwitch, c); cfw.add(ByteCode.GOTO, ret.jsrPoints.get(i).intValue()); c++; } } } } } if (epilogueLabel != -1) { cfw.markLabel(epilogueLabel); } if (hasVarsInRegs) { cfw.add(ByteCode.ARETURN); return; } else if (isGenerator) { if (((FunctionNode)scriptOrFn).getResumptionPoints() != null) { cfw.markTableSwitchDefault(generatorSwitch); } // change state for re-entry generateSetGeneratorResumptionPoint(GENERATOR_TERMINATE); // throw StopIteration cfw.addALoad(variableObjectLocal); addOptRuntimeInvoke("throwStopIteration", "(Ljava/lang/Object;)V"); Codegen.pushUndefined(cfw); cfw.add(ByteCode.ARETURN); } else if (fnCurrent == null) { cfw.addALoad(popvLocal); cfw.add(ByteCode.ARETURN); } else { generateActivationExit(); cfw.add(ByteCode.ARETURN); // Generate catch block to catch all and rethrow to call exit code // under exception propagation as well. int finallyHandler = cfw.acquireLabel(); cfw.markHandler(finallyHandler); short exceptionObject = getNewWordLocal(); cfw.addAStore(exceptionObject); // Duplicate generateActivationExit() in the catch block since it // takes less space then full-featured ByteCode.JSR/ByteCode.RET generateActivationExit(); cfw.addALoad(exceptionObject); releaseWordLocal(exceptionObject); // rethrow cfw.add(ByteCode.ATHROW); // mark the handler cfw.addExceptionHandler(enterAreaStartLabel, epilogueLabel, finallyHandler, null); // catch any } } private void generateGetGeneratorLocalsState() { cfw.addALoad(generatorStateLocal); addOptRuntimeInvoke("getGeneratorLocalsState", "(Ljava/lang/Object;)[Ljava/lang/Object;"); } private void generateActivationExit() { if (fnCurrent == null || hasVarsInRegs) throw Kit.codeBug(); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("exitActivationFunction", "(Lorg/mozilla/javascript/Context;)V"); } private void generateStatement(Node node) { updateLineNumber(node); int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.LOOP: case Token.LABEL: case Token.WITH: case Token.SCRIPT: case Token.BLOCK: case Token.EMPTY: // no-ops. if (compilerEnv.isGenerateObserverCount()) { // Need to add instruction count even for no-ops to catch // cases like while (1) {} addInstructionCount(1); } while (child != null) { generateStatement(child); child = child.getNext(); } break; case Token.LOCAL_BLOCK: { int local = getNewWordLocal(); if (isGenerator) { cfw.add(ByteCode.ACONST_NULL); cfw.addAStore(local); } node.putIntProp(Node.LOCAL_PROP, local); while (child != null) { generateStatement(child); child = child.getNext(); } releaseWordLocal((short)local); node.removeProp(Node.LOCAL_PROP); break; } case Token.FUNCTION: { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); OptFunctionNode ofn = OptFunctionNode.get(scriptOrFn, fnIndex); int t = ofn.fnode.getFunctionType(); if (t == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) { visitFunction(ofn, t); } else { if (t != FunctionNode.FUNCTION_STATEMENT) { throw Codegen.badTree(); } } break; } case Token.TRY: visitTryCatchFinally((Jump)node, child); break; case Token.CATCH_SCOPE: { // nothing stays on the stack on entry into a catch scope cfw.setStackTop((short) 0); int local = getLocalBlockRegister(node); int scopeIndex = node.getExistingIntProp(Node.CATCH_SCOPE_PROP); String name = child.getString(); // name of exception child = child.getNext(); generateExpression(child, node); // load expression object if (scopeIndex == 0) { cfw.add(ByteCode.ACONST_NULL); } else { // Load previous catch scope object cfw.addALoad(local); } cfw.addPush(name); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "newCatchScope", "(Ljava/lang/Throwable;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(local); } break; case Token.THROW: generateExpression(child, node); if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); generateThrowJavaScriptException(); break; case Token.RETHROW: if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); cfw.addALoad(getLocalBlockRegister(node)); cfw.add(ByteCode.ATHROW); break; case Token.RETURN_RESULT: case Token.RETURN: if (!isGenerator) { if (child != null) { generateExpression(child, node); } else if (type == Token.RETURN) { Codegen.pushUndefined(cfw); } else { if (popvLocal < 0) throw Codegen.badTree(); cfw.addALoad(popvLocal); } } if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); if (epilogueLabel == -1) { if (!hasVarsInRegs) throw Codegen.badTree(); epilogueLabel = cfw.acquireLabel(); } cfw.add(ByteCode.GOTO, epilogueLabel); break; case Token.SWITCH: if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); visitSwitch((Jump)node, child); break; case Token.ENTERWITH: generateExpression(child, node); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "enterWith", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); incReferenceWordLocal(variableObjectLocal); break; case Token.LEAVEWITH: cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "leaveWith", "(Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); decReferenceWordLocal(variableObjectLocal); break; case Token.ENUM_INIT_KEYS: case Token.ENUM_INIT_VALUES: case Token.ENUM_INIT_ARRAY: generateExpression(child, node); cfw.addALoad(contextLocal); int enumType = type == Token.ENUM_INIT_KEYS ? ScriptRuntime.ENUMERATE_KEYS : type == Token.ENUM_INIT_VALUES ? ScriptRuntime.ENUMERATE_VALUES : ScriptRuntime.ENUMERATE_ARRAY; cfw.addPush(enumType); addScriptRuntimeInvoke("enumInit", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Ljava/lang/Object;"); cfw.addAStore(getLocalBlockRegister(node)); break; case Token.EXPR_VOID: if (child.getType() == Token.SETVAR) { /* special case this so as to avoid unnecessary load's & pop's */ visitSetVar(child, child.getFirstChild(), false); } else if (child.getType() == Token.SETCONSTVAR) { /* special case this so as to avoid unnecessary load's & pop's */ visitSetConstVar(child, child.getFirstChild(), false); } else if (child.getType() == Token.YIELD) { generateYieldPoint(child, false); } else { generateExpression(child, node); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) cfw.add(ByteCode.POP2); else cfw.add(ByteCode.POP); } break; case Token.EXPR_RESULT: generateExpression(child, node); if (popvLocal < 0) { popvLocal = getNewWordLocal(); } cfw.addAStore(popvLocal); break; case Token.TARGET: { if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); int label = getTargetLabel(node); cfw.markLabel(label); if (compilerEnv.isGenerateObserverCount()) saveCurrentCodeOffset(); } break; case Token.JSR: case Token.GOTO: case Token.IFEQ: case Token.IFNE: if (compilerEnv.isGenerateObserverCount()) addInstructionCount(); visitGoto((Jump)node, type, child); break; case Token.FINALLY: { if (compilerEnv.isGenerateObserverCount()) saveCurrentCodeOffset(); // there is exactly one value on the stack when enterring // finally blocks: the return address (or its int encoding) cfw.setStackTop((short)1); // Save return address in a new local int finallyRegister = getNewWordLocal(); if (isGenerator) generateIntegerWrap(); cfw.addAStore(finallyRegister); while (child != null) { generateStatement(child); child = child.getNext(); } if (isGenerator) { cfw.addALoad(finallyRegister); cfw.add(ByteCode.CHECKCAST, "java/lang/Integer"); generateIntegerUnwrap(); FinallyReturnPoint ret = finallys.get(node); ret.tableLabel = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, ret.tableLabel); } else { cfw.add(ByteCode.RET, finallyRegister); } releaseWordLocal((short)finallyRegister); } break; case Token.DEBUGGER: break; default: throw Codegen.badTree(); } } private void generateIntegerWrap() { cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } private void generateIntegerUnwrap() { cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"); } private void generateThrowJavaScriptException() { cfw.add(ByteCode.NEW, "org/mozilla/javascript/JavaScriptException"); cfw.add(ByteCode.DUP_X1); cfw.add(ByteCode.SWAP); cfw.addPush(scriptOrFn.getSourceName()); cfw.addPush(itsLineNumber); cfw.addInvoke( ByteCode.INVOKESPECIAL, "org/mozilla/javascript/JavaScriptException", "<init>", "(Ljava/lang/Object;Ljava/lang/String;I)V"); cfw.add(ByteCode.ATHROW); } private int getNextGeneratorState(Node node) { int nodeIndex = ((FunctionNode)scriptOrFn).getResumptionPoints() .indexOf(node); return nodeIndex + GENERATOR_YIELD_START; } private void generateExpression(Node node, Node parent) { int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.USE_STACK: break; case Token.FUNCTION: if (fnCurrent != null || parent.getType() != Token.SCRIPT) { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); OptFunctionNode ofn = OptFunctionNode.get(scriptOrFn, fnIndex); int t = ofn.fnode.getFunctionType(); if (t != FunctionNode.FUNCTION_EXPRESSION) { throw Codegen.badTree(); } visitFunction(ofn, t); } break; case Token.NAME: { cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(node.getString()); addScriptRuntimeInvoke( "name", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } break; case Token.CALL: case Token.NEW: { int specialType = node.getIntProp(Node.SPECIALCALL_PROP, Node.NON_SPECIALCALL); if (specialType == Node.NON_SPECIALCALL) { OptFunctionNode target; target = (OptFunctionNode)node.getProp( Node.DIRECTCALL_PROP); if (target != null) { visitOptimizedCall(node, target, type, child); } else if (type == Token.CALL) { visitStandardCall(node, child); } else { visitStandardNew(node, child); } } else { visitSpecialCall(node, type, specialType, child); } } break; case Token.REF_CALL: generateFunctionAndThisObj(child, node); // stack: ... functionObj thisObj child = child.getNext(); generateCallArgArray(node, child, false); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "callRef", "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Ref;"); break; case Token.NUMBER: { double num = node.getDouble(); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { cfw.addPush(num); } else { codegen.pushNumberAsObject(cfw, num); } } break; case Token.STRING: cfw.addPush(node.getString()); break; case Token.THIS: cfw.addALoad(thisObjLocal); break; case Token.THISFN: cfw.add(ByteCode.ALOAD_0); break; case Token.NULL: cfw.add(ByteCode.ACONST_NULL); break; case Token.TRUE: cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); break; case Token.FALSE: cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); break; case Token.REGEXP: { int i = node.getExistingIntProp(Node.REGEXP_PROP); // Scripts can not use REGEXP_ARRAY_FIELD_NAME since // it it will make script.exec non-reentrant so they // store regexp array in a local variable while // functions always access precomputed // REGEXP_ARRAY_FIELD_NAME not to consume locals if (fnCurrent == null) { cfw.addALoad(scriptRegexpLocal); } else { cfw.addALoad(funObjLocal); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.REGEXP_ARRAY_FIELD_NAME, Codegen.REGEXP_ARRAY_FIELD_TYPE); } cfw.addPush(i); cfw.add(ByteCode.AALOAD); } break; case Token.COMMA: { Node next = child.getNext(); while (next != null) { generateExpression(child, node); cfw.add(ByteCode.POP); child = next; next = next.getNext(); } generateExpression(child, node); break; } case Token.ENUM_NEXT: case Token.ENUM_ID: { int local = getLocalBlockRegister(node); cfw.addALoad(local); if (type == Token.ENUM_NEXT) { addScriptRuntimeInvoke( "enumNext", "(Ljava/lang/Object;)Ljava/lang/Boolean;"); } else { cfw.addALoad(contextLocal); addScriptRuntimeInvoke("enumId", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } break; } case Token.ARRAYLIT: visitArrayLiteral(node, child); break; case Token.OBJECTLIT: visitObjectLiteral(node, child); break; case Token.NOT: { int trueTarget = cfw.acquireLabel(); int falseTarget = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); generateIfJump(child, node, trueTarget, falseTarget); cfw.markLabel(trueTarget); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(falseTarget); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); cfw.markLabel(beyond); cfw.adjustStackTop(-1); break; } case Token.BITNOT: generateExpression(child, node); addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); cfw.addPush(-1); // implement ~a as (a ^ -1) cfw.add(ByteCode.IXOR); cfw.add(ByteCode.I2D); addDoubleWrap(); break; case Token.VOID: generateExpression(child, node); cfw.add(ByteCode.POP); Codegen.pushUndefined(cfw); break; case Token.TYPEOF: generateExpression(child, node); addScriptRuntimeInvoke("typeof", "(Ljava/lang/Object;" +")Ljava/lang/String;"); break; case Token.TYPEOFNAME: visitTypeofname(node); break; case Token.INC: case Token.DEC: visitIncDec(node); break; case Token.OR: case Token.AND: { generateExpression(child, node); cfw.add(ByteCode.DUP); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); int falseTarget = cfw.acquireLabel(); if (type == Token.AND) cfw.add(ByteCode.IFEQ, falseTarget); else cfw.add(ByteCode.IFNE, falseTarget); cfw.add(ByteCode.POP); generateExpression(child.getNext(), node); cfw.markLabel(falseTarget); } break; case Token.HOOK : { Node ifThen = child.getNext(); Node ifElse = ifThen.getNext(); generateExpression(child, node); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); int elseTarget = cfw.acquireLabel(); cfw.add(ByteCode.IFEQ, elseTarget); short stack = cfw.getStackTop(); generateExpression(ifThen, node); int afterHook = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, afterHook); cfw.markLabel(elseTarget, stack); generateExpression(ifElse, node); cfw.markLabel(afterHook); } break; case Token.ADD: { generateExpression(child, node); generateExpression(child.getNext(), node); switch (node.getIntProp(Node.ISNUMBER_PROP, -1)) { case Node.BOTH: cfw.add(ByteCode.DADD); break; case Node.LEFT: addOptRuntimeInvoke("add", "(DLjava/lang/Object;)Ljava/lang/Object;"); break; case Node.RIGHT: addOptRuntimeInvoke("add", "(Ljava/lang/Object;D)Ljava/lang/Object;"); break; default: if (child.getType() == Token.STRING) { addScriptRuntimeInvoke("add", "(Ljava/lang/String;" +"Ljava/lang/Object;" +")Ljava/lang/String;"); } else if (child.getNext().getType() == Token.STRING) { addScriptRuntimeInvoke("add", "(Ljava/lang/Object;" +"Ljava/lang/String;" +")Ljava/lang/String;"); } else { cfw.addALoad(contextLocal); addScriptRuntimeInvoke("add", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } } break; case Token.MUL: visitArithmetic(node, ByteCode.DMUL, child, parent); break; case Token.SUB: visitArithmetic(node, ByteCode.DSUB, child, parent); break; case Token.DIV: case Token.MOD: visitArithmetic(node, type == Token.DIV ? ByteCode.DDIV : ByteCode.DREM, child, parent); break; case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.LSH: case Token.RSH: case Token.URSH: visitBitOp(node, type, child); break; case Token.POS: case Token.NEG: generateExpression(child, node); addObjectToDouble(); if (type == Token.NEG) { cfw.add(ByteCode.DNEG); } addDoubleWrap(); break; case Token.TO_DOUBLE: // cnvt to double (not Double) generateExpression(child, node); addObjectToDouble(); break; case Token.TO_OBJECT: { // convert from double int prop = -1; if (child.getType() == Token.NUMBER) { prop = child.getIntProp(Node.ISNUMBER_PROP, -1); } if (prop != -1) { child.removeProp(Node.ISNUMBER_PROP); generateExpression(child, node); child.putIntProp(Node.ISNUMBER_PROP, prop); } else { generateExpression(child, node); addDoubleWrap(); } break; } case Token.IN: case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: { int trueGOTO = cfw.acquireLabel(); int falseGOTO = cfw.acquireLabel(); visitIfJumpRelOp(node, child, trueGOTO, falseGOTO); addJumpedBooleanWrap(trueGOTO, falseGOTO); break; } case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: { int trueGOTO = cfw.acquireLabel(); int falseGOTO = cfw.acquireLabel(); visitIfJumpEqOp(node, child, trueGOTO, falseGOTO); addJumpedBooleanWrap(trueGOTO, falseGOTO); break; } case Token.GETPROP: case Token.GETPROPNOWARN: visitGetProp(node, child); break; case Token.GETELEM: generateExpression(child, node); // object generateExpression(child.getNext(), node); // id cfw.addALoad(contextLocal); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { addScriptRuntimeInvoke( "getObjectIndex", "(Ljava/lang/Object;D" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getObjectElem", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"); } break; case Token.GET_REF: generateExpression(child, node); // reference cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "refGet", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.GETVAR: visitGetVar(node); break; case Token.SETVAR: visitSetVar(node, child, true); break; case Token.SETNAME: visitSetName(node, child); break; case Token.STRICT_SETNAME: visitStrictSetName(node, child); break; case Token.SETCONST: visitSetConst(node, child); break; case Token.SETCONSTVAR: visitSetConstVar(node, child, true); break; case Token.SETPROP: case Token.SETPROP_OP: visitSetProp(type, node, child); break; case Token.SETELEM: case Token.SETELEM_OP: visitSetElem(type, node, child); break; case Token.SET_REF: case Token.SET_REF_OP: { generateExpression(child, node); child = child.getNext(); if (type == Token.SET_REF_OP) { cfw.add(ByteCode.DUP); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "refGet", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "refSet", "(Lorg/mozilla/javascript/Ref;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } break; case Token.DEL_REF: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("refDel", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.DELPROP: generateExpression(child, node); child = child.getNext(); generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("delete", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.BINDNAME: { while (child != null) { generateExpression(child, node); child = child.getNext(); } // Generate code for "ScriptRuntime.bind(varObj, "s")" cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(node.getString()); addScriptRuntimeInvoke( "bind", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Lorg/mozilla/javascript/Scriptable;"); } break; case Token.LOCAL_LOAD: cfw.addALoad(getLocalBlockRegister(node)); break; case Token.REF_SPECIAL: { String special = (String)node.getProp(Node.NAME_PROP); generateExpression(child, node); cfw.addPush(special); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "specialRef", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Ref;"); } break; case Token.REF_MEMBER: case Token.REF_NS_MEMBER: case Token.REF_NAME: case Token.REF_NS_NAME: { int memberTypeFlags = node.getIntProp(Node.MEMBER_TYPE_PROP, 0); // generate possible target, possible namespace and member do { generateExpression(child, node); child = child.getNext(); } while (child != null); cfw.addALoad(contextLocal); String methodName, signature; switch (type) { case Token.REF_MEMBER: methodName = "memberRef"; signature = "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Lorg/mozilla/javascript/Ref;"; break; case Token.REF_NS_MEMBER: methodName = "memberRef"; signature = "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Lorg/mozilla/javascript/Ref;"; break; case Token.REF_NAME: methodName = "nameRef"; signature = "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"I" +")Lorg/mozilla/javascript/Ref;"; cfw.addALoad(variableObjectLocal); break; case Token.REF_NS_NAME: methodName = "nameRef"; signature = "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"I" +")Lorg/mozilla/javascript/Ref;"; cfw.addALoad(variableObjectLocal); break; default: throw Kit.codeBug(); } cfw.addPush(memberTypeFlags); addScriptRuntimeInvoke(methodName, signature); } break; case Token.DOTQUERY: visitDotQuery(node, child); break; case Token.ESCXMLATTR: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("escapeAttributeValue", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/String;"); break; case Token.ESCXMLTEXT: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("escapeTextValue", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/String;"); break; case Token.DEFAULTNAMESPACE: generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke("setDefaultNamespace", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); break; case Token.YIELD: generateYieldPoint(node, true); break; case Token.WITHEXPR: { Node enterWith = child; Node with = enterWith.getNext(); Node leaveWith = with.getNext(); generateStatement(enterWith); generateExpression(with.getFirstChild(), with); generateStatement(leaveWith); break; } case Token.ARRAYCOMP: { Node initStmt = child; Node expr = child.getNext(); generateStatement(initStmt); generateExpression(expr, node); break; } default: throw new RuntimeException("Unexpected node type "+type); } } private void generateYieldPoint(Node node, boolean exprContext) { // save stack state int top = cfw.getStackTop(); maxStack = maxStack > top ? maxStack : top; if (cfw.getStackTop() != 0) { generateGetGeneratorStackState(); for (int i = 0; i < top; i++) { cfw.add(ByteCode.DUP_X1); cfw.add(ByteCode.SWAP); cfw.addLoadConstant(i); cfw.add(ByteCode.SWAP); cfw.add(ByteCode.AASTORE); } // pop the array object cfw.add(ByteCode.POP); } // generate the yield argument Node child = node.getFirstChild(); if (child != null) generateExpression(child, node); else Codegen.pushUndefined(cfw); // change the resumption state int nextState = getNextGeneratorState(node); generateSetGeneratorResumptionPoint(nextState); boolean hasLocals = generateSaveLocals(node); cfw.add(ByteCode.ARETURN); generateCheckForThrowOrClose(getTargetLabel(node), hasLocals, nextState); // reconstruct the stack if (top != 0) { generateGetGeneratorStackState(); for (int i = 0; i < top; i++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(top - i - 1); cfw.add(ByteCode.AALOAD); cfw.add(ByteCode.SWAP); } cfw.add(ByteCode.POP); } // load return value from yield if (exprContext) { cfw.addALoad(argsLocal); } } private void generateCheckForThrowOrClose(int label, boolean hasLocals, int nextState) { int throwLabel = cfw.acquireLabel(); int closeLabel = cfw.acquireLabel(); // throw the user provided object, if the operation is .throw() cfw.markLabel(throwLabel); cfw.addALoad(argsLocal); generateThrowJavaScriptException(); // throw our special internal exception if the generator is being closed cfw.markLabel(closeLabel); cfw.addALoad(argsLocal); cfw.add(ByteCode.CHECKCAST, "java/lang/Throwable"); cfw.add(ByteCode.ATHROW); // mark the re-entry point // jump here after initializing the locals if (label != -1) cfw.markLabel(label); if (!hasLocals) { // jump here directly if there are no locals cfw.markTableSwitchCase(generatorSwitch, nextState); } // see if we need to dispatch for .close() or .throw() cfw.addILoad(operationLocal); cfw.addLoadConstant(NativeGenerator.GENERATOR_CLOSE); cfw.add(ByteCode.IF_ICMPEQ, closeLabel); cfw.addILoad(operationLocal); cfw.addLoadConstant(NativeGenerator.GENERATOR_THROW); cfw.add(ByteCode.IF_ICMPEQ, throwLabel); } private void generateIfJump(Node node, Node parent, int trueLabel, int falseLabel) { // System.out.println("gen code for " + node.toString()); int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.NOT: generateIfJump(child, node, falseLabel, trueLabel); break; case Token.OR: case Token.AND: { int interLabel = cfw.acquireLabel(); if (type == Token.AND) { generateIfJump(child, node, interLabel, falseLabel); } else { generateIfJump(child, node, trueLabel, interLabel); } cfw.markLabel(interLabel); child = child.getNext(); generateIfJump(child, node, trueLabel, falseLabel); break; } case Token.IN: case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: visitIfJumpRelOp(node, child, trueLabel, falseLabel); break; case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: visitIfJumpEqOp(node, child, trueLabel, falseLabel); break; default: // Generate generic code for non-optimized jump generateExpression(node, parent); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); cfw.add(ByteCode.IFNE, trueLabel); cfw.add(ByteCode.GOTO, falseLabel); } } private void visitFunction(OptFunctionNode ofn, int functionType) { int fnIndex = codegen.getIndex(ofn.fnode); cfw.add(ByteCode.NEW, codegen.mainClassName); // Call function constructor cfw.add(ByteCode.DUP); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' cfw.addPush(fnIndex); cfw.addInvoke(ByteCode.INVOKESPECIAL, codegen.mainClassName, "<init>", Codegen.FUNCTION_CONSTRUCTOR_SIGNATURE); // Init mainScript field; cfw.add(ByteCode.DUP); if (isTopLevel) { cfw.add(ByteCode.ALOAD_0); } else { cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); } cfw.add(ByteCode.PUTFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); int directTargetIndex = ofn.getDirectTargetIndex(); if (directTargetIndex >= 0) { cfw.add(ByteCode.DUP); if (isTopLevel) { cfw.add(ByteCode.ALOAD_0); } else { cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); } cfw.add(ByteCode.SWAP); cfw.add(ByteCode.PUTFIELD, codegen.mainClassName, Codegen.getDirectTargetFieldName(directTargetIndex), codegen.mainClassSignature); } if (functionType == FunctionNode.FUNCTION_EXPRESSION) { // Leave closure object on stack and do not pass it to // initFunction which suppose to connect statements to scope return; } cfw.addPush(functionType); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' addOptRuntimeInvoke("initFunction", "(Lorg/mozilla/javascript/NativeFunction;" +"I" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;" +")V"); } private int getTargetLabel(Node target) { int labelId = target.labelId(); if (labelId == -1) { labelId = cfw.acquireLabel(); target.labelId(labelId); } return labelId; } private void visitGoto(Jump node, int type, Node child) { Node target = node.target; if (type == Token.IFEQ || type == Token.IFNE) { if (child == null) throw Codegen.badTree(); int targetLabel = getTargetLabel(target); int fallThruLabel = cfw.acquireLabel(); if (type == Token.IFEQ) generateIfJump(child, node, targetLabel, fallThruLabel); else generateIfJump(child, node, fallThruLabel, targetLabel); cfw.markLabel(fallThruLabel); } else { if (type == Token.JSR) { if (isGenerator) { addGotoWithReturn(target); } else { addGoto(target, ByteCode.JSR); } } else { addGoto(target, ByteCode.GOTO); } } } private void addGotoWithReturn(Node target) { FinallyReturnPoint ret = finallys.get(target); cfw.addLoadConstant(ret.jsrPoints.size()); addGoto(target, ByteCode.GOTO); int retLabel = cfw.acquireLabel(); cfw.markLabel(retLabel); ret.jsrPoints.add(Integer.valueOf(retLabel)); } private void visitArrayLiteral(Node node, Node child) { int count = 0; for (Node cursor = child; cursor != null; cursor = cursor.getNext()) { ++count; } // load array to store array literal objects addNewObjectArray(count); for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); generateExpression(child, node); cfw.add(ByteCode.AASTORE); child = child.getNext(); } int[] skipIndexes = (int[])node.getProp(Node.SKIP_INDEXES_PROP); if (skipIndexes == null) { cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.ICONST_0); } else { cfw.addPush(OptRuntime.encodeIntArray(skipIndexes)); cfw.addPush(skipIndexes.length); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addOptRuntimeInvoke("newArrayLiteral", "([Ljava/lang/Object;" +"Ljava/lang/String;" +"I" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); } private void visitObjectLiteral(Node node, Node child) { Object[] properties = (Object[])node.getProp(Node.OBJECT_IDS_PROP); int count = properties.length; // load array with property ids addNewObjectArray(count); for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); Object id = properties[i]; if (id instanceof String) { cfw.addPush((String)id); } else { cfw.addPush(((Integer)id).intValue()); addScriptRuntimeInvoke("wrapInt", "(I)Ljava/lang/Integer;"); } cfw.add(ByteCode.AASTORE); } // load array with property values addNewObjectArray(count); Node child2 = child; for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); int childType = child.getType(); if (childType == Token.GET) { generateExpression(child.getFirstChild(), node); } else if (childType == Token.SET) { generateExpression(child.getFirstChild(), node); } else { generateExpression(child, node); } cfw.add(ByteCode.AASTORE); child = child.getNext(); } // load array with getterSetter values cfw.addPush(count); cfw.add(ByteCode.NEWARRAY, ByteCode.T_INT); for (int i = 0; i != count; ++i) { cfw.add(ByteCode.DUP); cfw.addPush(i); int childType = child2.getType(); if (childType == Token.GET) { cfw.add(ByteCode.ICONST_M1); } else if (childType == Token.SET) { cfw.add(ByteCode.ICONST_1); } else { cfw.add(ByteCode.ICONST_0); } cfw.add(ByteCode.IASTORE); child2 = child2.getNext(); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("newObjectLiteral", "([Ljava/lang/Object;" +"[Ljava/lang/Object;" +"[I" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); } private void visitSpecialCall(Node node, int type, int specialType, Node child) { cfw.addALoad(contextLocal); if (type == Token.NEW) { generateExpression(child, node); // stack: ... cx functionObj } else { generateFunctionAndThisObj(child, node); // stack: ... cx functionObj thisObj } child = child.getNext(); generateCallArgArray(node, child, false); String methodName; String callSignature; if (type == Token.NEW) { methodName = "newObjectSpecial"; callSignature = "(Lorg/mozilla/javascript/Context;" +"Ljava/lang/Object;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"I" // call type +")Ljava/lang/Object;"; cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addPush(specialType); } else { methodName = "callSpecial"; callSignature = "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"I" // call type +"Ljava/lang/String;I" // filename, linenumber +")Ljava/lang/Object;"; cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addPush(specialType); String sourceName = scriptOrFn.getSourceName(); cfw.addPush(sourceName == null ? "" : sourceName); cfw.addPush(itsLineNumber); } addOptRuntimeInvoke(methodName, callSignature); } private void visitStandardCall(Node node, Node child) { if (node.getType() != Token.CALL) throw Codegen.badTree(); Node firstArgChild = child.getNext(); int childType = child.getType(); String methodName; String signature; if (firstArgChild == null) { if (childType == Token.NAME) { // name() call String name = child.getString(); cfw.addPush(name); methodName = "callName0"; signature = "(Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else if (childType == Token.GETPROP) { // x.name() call Node propTarget = child.getFirstChild(); generateExpression(propTarget, node); Node id = propTarget.getNext(); String property = id.getString(); cfw.addPush(property); methodName = "callProp0"; signature = "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else if (childType == Token.GETPROPNOWARN) { throw Kit.codeBug(); } else { generateFunctionAndThisObj(child, node); methodName = "call0"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } } else if (childType == Token.NAME) { // XXX: this optimization is only possible if name // resolution // is not affected by arguments evaluation and currently // there are no checks for it String name = child.getString(); generateCallArgArray(node, firstArgChild, false); cfw.addPush(name); methodName = "callName"; signature = "([Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else { int argCount = 0; for (Node arg = firstArgChild; arg != null; arg = arg.getNext()) { ++argCount; } generateFunctionAndThisObj(child, node); // stack: ... functionObj thisObj if (argCount == 1) { generateExpression(firstArgChild, node); methodName = "call1"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else if (argCount == 2) { generateExpression(firstArgChild, node); generateExpression(firstArgChild.getNext(), node); methodName = "call2"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } else { generateCallArgArray(node, firstArgChild, false); methodName = "callN"; signature = "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"; } } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addOptRuntimeInvoke(methodName, signature); } private void visitStandardNew(Node node, Node child) { if (node.getType() != Token.NEW) throw Codegen.badTree(); Node firstArgChild = child.getNext(); generateExpression(child, node); // stack: ... functionObj cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); // stack: ... functionObj cx scope generateCallArgArray(node, firstArgChild, false); addScriptRuntimeInvoke( "newObject", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); } private void visitOptimizedCall(Node node, OptFunctionNode target, int type, Node child) { Node firstArgChild = child.getNext(); short thisObjLocal = 0; if (type == Token.NEW) { generateExpression(child, node); } else { generateFunctionAndThisObj(child, node); thisObjLocal = getNewWordLocal(); cfw.addAStore(thisObjLocal); } // stack: ... functionObj int beyond = cfw.acquireLabel(); int directTargetIndex = target.getDirectTargetIndex(); if (isTopLevel) { cfw.add(ByteCode.ALOAD_0); } else { cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.DIRECT_CALL_PARENT_FIELD, codegen.mainClassSignature); } cfw.add(ByteCode.GETFIELD, codegen.mainClassName, Codegen.getDirectTargetFieldName(directTargetIndex), codegen.mainClassSignature); cfw.add(ByteCode.DUP2); // stack: ... functionObj directFunct functionObj directFunct int regularCall = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPNE, regularCall); // stack: ... functionObj directFunct short stackHeight = cfw.getStackTop(); cfw.add(ByteCode.SWAP); cfw.add(ByteCode.POP); // stack: ... directFunct if (compilerEnv.isUseDynamicScope()) { cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); } else { cfw.add(ByteCode.DUP); // stack: ... directFunct directFunct cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); // stack: ... directFunct scope cfw.addALoad(contextLocal); // stack: ... directFunct scope cx cfw.add(ByteCode.SWAP); } // stack: ... directFunc cx scope if (type == Token.NEW) { cfw.add(ByteCode.ACONST_NULL); } else { cfw.addALoad(thisObjLocal); } // stack: ... directFunc cx scope thisObj /* Remember that directCall parameters are paired in 1 aReg and 1 dReg If the argument is an incoming arg, just pass the orginal pair thru. Else, if the argument is known to be typed 'Number', pass Void.TYPE in the aReg and the number is the dReg Else pass the JS object in the aReg and 0.0 in the dReg. */ Node argChild = firstArgChild; while (argChild != null) { int dcp_register = nodeIsDirectCallParameter(argChild); if (dcp_register >= 0) { cfw.addALoad(dcp_register); cfw.addDLoad(dcp_register + 1); } else if (argChild.getIntProp(Node.ISNUMBER_PROP, -1) == Node.BOTH) { cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); generateExpression(argChild, node); } else { generateExpression(argChild, node); cfw.addPush(0.0); } argChild = argChild.getNext(); } cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "emptyArgs", "[Ljava/lang/Object;"); cfw.addInvoke(ByteCode.INVOKESTATIC, codegen.mainClassName, (type == Token.NEW) ? codegen.getDirectCtorName(target.fnode) : codegen.getBodyMethodName(target.fnode), codegen.getBodyMethodSignature(target.fnode)); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(regularCall, stackHeight); // stack: ... functionObj directFunct cfw.add(ByteCode.POP); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); // stack: ... functionObj cx scope if (type != Token.NEW) { cfw.addALoad(thisObjLocal); releaseWordLocal(thisObjLocal); // stack: ... functionObj cx scope thisObj } // XXX: this will generate code for the child array the second time, // so expression code generation better not to alter tree structure... generateCallArgArray(node, firstArgChild, true); if (type == Token.NEW) { addScriptRuntimeInvoke( "newObject", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); } else { cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Callable", "call", "(Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); } cfw.markLabel(beyond); } private void generateCallArgArray(Node node, Node argChild, boolean directCall) { int argCount = 0; for (Node child = argChild; child != null; child = child.getNext()) { ++argCount; } // load array object to set arguments if (argCount == 1 && itsOneArgArray >= 0) { cfw.addALoad(itsOneArgArray); } else { addNewObjectArray(argCount); } // Copy arguments into it for (int i = 0; i != argCount; ++i) { // If we are compiling a generator an argument could be the result // of a yield. In that case we will have an immediate on the stack // which we need to avoid if (!isGenerator) { cfw.add(ByteCode.DUP); cfw.addPush(i); } if (!directCall) { generateExpression(argChild, node); } else { // If this has also been a directCall sequence, the Number // flag will have remained set for any parameter so that // the values could be copied directly into the outgoing // args. Here we want to force it to be treated as not in // a Number context, so we set the flag off. int dcp_register = nodeIsDirectCallParameter(argChild); if (dcp_register >= 0) { dcpLoadAsObject(dcp_register); } else { generateExpression(argChild, node); int childNumberFlag = argChild.getIntProp(Node.ISNUMBER_PROP, -1); if (childNumberFlag == Node.BOTH) { addDoubleWrap(); } } } // When compiling generators, any argument to a method may be a // yield expression. Hence we compile the argument first and then // load the argument index and assign the value to the args array. if (isGenerator) { short tempLocal = getNewWordLocal(); cfw.addAStore(tempLocal); cfw.add(ByteCode.CHECKCAST, "[Ljava/lang/Object;"); cfw.add(ByteCode.DUP); cfw.addPush(i); cfw.addALoad(tempLocal); releaseWordLocal(tempLocal); } cfw.add(ByteCode.AASTORE); argChild = argChild.getNext(); } } private void generateFunctionAndThisObj(Node node, Node parent) { // Place on stack (function object, function this) pair int type = node.getType(); switch (node.getType()) { case Token.GETPROPNOWARN: throw Kit.codeBug(); case Token.GETPROP: case Token.GETELEM: { Node target = node.getFirstChild(); generateExpression(target, node); Node id = target.getNext(); if (type == Token.GETPROP) { String property = id.getString(); cfw.addPush(property); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getPropFunctionAndThis", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Callable;"); } else { // Optimizer do not optimize this case for now if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) throw Codegen.badTree(); generateExpression(id, node); // id cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getElemFunctionAndThis", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Callable;"); } break; } case Token.NAME: { String name = node.getString(); cfw.addPush(name); cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getNameFunctionAndThis", "(Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Callable;"); break; } default: // including GETVAR generateExpression(node, parent); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getValueFunctionAndThis", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Callable;"); break; } // Get thisObj prepared by get(Name|Prop|Elem|Value)FunctionAndThis cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "lastStoredScriptable", "(Lorg/mozilla/javascript/Context;" +")Lorg/mozilla/javascript/Scriptable;"); } private void updateLineNumber(Node node) { itsLineNumber = node.getLineno(); if (itsLineNumber == -1) return; cfw.addLineNumberEntry((short)itsLineNumber); } private void visitTryCatchFinally(Jump node, Node child) { /* Save the variable object, in case there are with statements * enclosed by the try block and we catch some exception. * We'll restore it for the catch block so that catch block * statements get the right scope. */ // OPT we only need to do this if there are enclosed WITH // statements; could statically check and omit this if there aren't any. // XXX OPT Maybe instead do syntactic transforms to associate // each 'with' with a try/finally block that does the exitwith. short savedVariableObject = getNewWordLocal(); cfw.addALoad(variableObjectLocal); cfw.addAStore(savedVariableObject); /* * Generate the code for the tree; most of the work is done in IRFactory * and NodeTransformer; Codegen just adds the java handlers for the * javascript catch and finally clauses. */ int startLabel = cfw.acquireLabel(); cfw.markLabel(startLabel, (short)0); Node catchTarget = node.target; Node finallyTarget = node.getFinally(); // create a table for the equivalent of JSR returns if (isGenerator && finallyTarget != null) { FinallyReturnPoint ret = new FinallyReturnPoint(); if (finallys == null) { finallys = new HashMap<Node,FinallyReturnPoint>(); } // add the finally target to hashtable finallys.put(finallyTarget, ret); // add the finally node as well to the hash table finallys.put(finallyTarget.getNext(), ret); } while (child != null) { generateStatement(child); child = child.getNext(); } // control flow skips the handlers int realEnd = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, realEnd); int exceptionLocal = getLocalBlockRegister(node); // javascript handler; unwrap exception and GOTO to javascript // catch area. if (catchTarget != null) { // get the label to goto int catchLabel = catchTarget.labelId(); generateCatchBlock(JAVASCRIPT_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); /* * catch WrappedExceptions, see if they are wrapped * JavaScriptExceptions. Otherwise, rethrow. */ generateCatchBlock(EVALUATOR_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); /* we also need to catch EcmaErrors and feed the associated error object to the handler */ generateCatchBlock(ECMAERROR_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); Context cx = Context.getCurrentContext(); if (cx != null && cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) { generateCatchBlock(THROWABLE_EXCEPTION, savedVariableObject, catchLabel, startLabel, exceptionLocal); } } // finally handler; catch all exceptions, store to a local; JSR to // the finally, then re-throw. if (finallyTarget != null) { int finallyHandler = cfw.acquireLabel(); cfw.markHandler(finallyHandler); cfw.addAStore(exceptionLocal); // reset the variable object local cfw.addALoad(savedVariableObject); cfw.addAStore(variableObjectLocal); // get the label to JSR to int finallyLabel = finallyTarget.labelId(); if (isGenerator) addGotoWithReturn(finallyTarget); else cfw.add(ByteCode.JSR, finallyLabel); // rethrow cfw.addALoad(exceptionLocal); if (isGenerator) cfw.add(ByteCode.CHECKCAST, "java/lang/Throwable"); cfw.add(ByteCode.ATHROW); // mark the handler cfw.addExceptionHandler(startLabel, finallyLabel, finallyHandler, null); // catch any } releaseWordLocal(savedVariableObject); cfw.markLabel(realEnd); } private static final int JAVASCRIPT_EXCEPTION = 0; private static final int EVALUATOR_EXCEPTION = 1; private static final int ECMAERROR_EXCEPTION = 2; private static final int THROWABLE_EXCEPTION = 3; private void generateCatchBlock(int exceptionType, short savedVariableObject, int catchLabel, int startLabel, int exceptionLocal) { int handler = cfw.acquireLabel(); cfw.markHandler(handler); // MS JVM gets cranky if the exception object is left on the stack cfw.addAStore(exceptionLocal); // reset the variable object local cfw.addALoad(savedVariableObject); cfw.addAStore(variableObjectLocal); String exceptionName; if (exceptionType == JAVASCRIPT_EXCEPTION) { exceptionName = "org/mozilla/javascript/JavaScriptException"; } else if (exceptionType == EVALUATOR_EXCEPTION) { exceptionName = "org/mozilla/javascript/EvaluatorException"; } else if (exceptionType == ECMAERROR_EXCEPTION) { exceptionName = "org/mozilla/javascript/EcmaError"; } else if (exceptionType == THROWABLE_EXCEPTION) { exceptionName = "java/lang/Throwable"; } else { throw Kit.codeBug(); } // mark the handler cfw.addExceptionHandler(startLabel, catchLabel, handler, exceptionName); cfw.add(ByteCode.GOTO, catchLabel); } private boolean generateSaveLocals(Node node) { int count = 0; for (int i = 0; i < firstFreeLocal; i++) { if (locals[i] != 0) count++; } if (count == 0) { ((FunctionNode)scriptOrFn).addLiveLocals(node, null); return false; } // calculate the max locals maxLocals = maxLocals > count ? maxLocals : count; // create a locals list int[] ls = new int[count]; int s = 0; for (int i = 0; i < firstFreeLocal; i++) { if (locals[i] != 0) { ls[s] = i; s++; } } // save the locals ((FunctionNode)scriptOrFn).addLiveLocals(node, ls); // save locals generateGetGeneratorLocalsState(); for (int i = 0; i < count; i++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(i); cfw.addALoad(ls[i]); cfw.add(ByteCode.AASTORE); } // pop the array off the stack cfw.add(ByteCode.POP); return true; } private void visitSwitch(Jump switchNode, Node child) { // See comments in IRFactory.createSwitch() for description // of SWITCH node generateExpression(child, switchNode); // save selector value short selector = getNewWordLocal(); cfw.addAStore(selector); for (Jump caseNode = (Jump)child.getNext(); caseNode != null; caseNode = (Jump)caseNode.getNext()) { if (caseNode.getType() != Token.CASE) throw Codegen.badTree(); Node test = caseNode.getFirstChild(); generateExpression(test, caseNode); cfw.addALoad(selector); addScriptRuntimeInvoke("shallowEq", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +")Z"); addGoto(caseNode.target, ByteCode.IFNE); } releaseWordLocal(selector); } private void visitTypeofname(Node node) { if (hasVarsInRegs) { int varIndex = fnCurrent.fnode.getIndexForNameNode(node); if (varIndex >= 0) { if (fnCurrent.isNumberVar(varIndex)) { cfw.addPush("number"); } else if (varIsDirectCallParameter(varIndex)) { int dcp_register = varRegisters[varIndex]; cfw.addALoad(dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); cfw.addALoad(dcp_register); addScriptRuntimeInvoke("typeof", "(Ljava/lang/Object;" +")Ljava/lang/String;"); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addPush("number"); cfw.markLabel(beyond); } else { cfw.addALoad(varRegisters[varIndex]); addScriptRuntimeInvoke("typeof", "(Ljava/lang/Object;" +")Ljava/lang/String;"); } return; } } cfw.addALoad(variableObjectLocal); cfw.addPush(node.getString()); addScriptRuntimeInvoke("typeofName", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/String;"); } /** * Save the current code offset. This saved code offset is used to * compute instruction counts in subsequent calls to * {@link #addInstructionCount()}. */ private void saveCurrentCodeOffset() { savedCodeOffset = cfw.getCurrentCodeOffset(); } /** * Generate calls to ScriptRuntime.addInstructionCount to keep track of * executed instructions and call <code>observeInstructionCount()</code> * if a threshold is exceeded.<br> * Calculates the count from getCurrentCodeOffset - savedCodeOffset */ private void addInstructionCount() { int count = cfw.getCurrentCodeOffset() - savedCodeOffset; if (count == 0) return; addInstructionCount(count); } /** * Generate calls to ScriptRuntime.addInstructionCount to keep track of * executed instructions and call <code>observeInstructionCount()</code> * if a threshold is exceeded.<br> * Takes the count as a parameter - used to add monitoring to loops and * other blocks that don't have any ops - this allows * for monitoring/killing of while(true) loops and such. */ private void addInstructionCount(int count) { cfw.addALoad(contextLocal); cfw.addPush(count); addScriptRuntimeInvoke("addInstructionCount", "(Lorg/mozilla/javascript/Context;" +"I)V"); } private void visitIncDec(Node node) { int incrDecrMask = node.getExistingIntProp(Node.INCRDECR_PROP); Node child = node.getFirstChild(); switch (child.getType()) { case Token.GETVAR: if (!hasVarsInRegs) Kit.codeBug(); if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { boolean post = ((incrDecrMask & Node.POST_FLAG) != 0); int varIndex = fnCurrent.getVarIndex(child); short reg = varRegisters[varIndex]; int offset = varIsDirectCallParameter(varIndex) ? 1 : 0; cfw.addDLoad(reg + offset); if (post) { cfw.add(ByteCode.DUP2); } cfw.addPush(1.0); if ((incrDecrMask & Node.DECR_FLAG) == 0) { cfw.add(ByteCode.DADD); } else { cfw.add(ByteCode.DSUB); } if (!post) { cfw.add(ByteCode.DUP2); } cfw.addDStore(reg + offset); } else { boolean post = ((incrDecrMask & Node.POST_FLAG) != 0); int varIndex = fnCurrent.getVarIndex(child); short reg = varRegisters[varIndex]; cfw.addALoad(reg); if (post) { cfw.add(ByteCode.DUP); } addObjectToDouble(); cfw.addPush(1.0); if ((incrDecrMask & Node.DECR_FLAG) == 0) { cfw.add(ByteCode.DADD); } else { cfw.add(ByteCode.DSUB); } addDoubleWrap(); if (!post) { cfw.add(ByteCode.DUP); } cfw.addAStore(reg); break; } break; case Token.NAME: cfw.addALoad(variableObjectLocal); cfw.addPush(child.getString()); // push name cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); addScriptRuntimeInvoke("nameIncrDecr", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"I)Ljava/lang/Object;"); break; case Token.GETPROPNOWARN: throw Kit.codeBug(); case Token.GETPROP: { Node getPropChild = child.getFirstChild(); generateExpression(getPropChild, node); generateExpression(getPropChild.getNext(), node); cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); addScriptRuntimeInvoke("propIncrDecr", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"I)Ljava/lang/Object;"); break; } case Token.GETELEM: { Node elemChild = child.getFirstChild(); generateExpression(elemChild, node); generateExpression(elemChild.getNext(), node); cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); if (elemChild.getNext().getIntProp(Node.ISNUMBER_PROP, -1) != -1) { addOptRuntimeInvoke("elemIncrDecr", "(Ljava/lang/Object;" +"D" +"Lorg/mozilla/javascript/Context;" +"I" +")Ljava/lang/Object;"); } else { addScriptRuntimeInvoke("elemIncrDecr", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"I" +")Ljava/lang/Object;"); } break; } case Token.GET_REF: { Node refChild = child.getFirstChild(); generateExpression(refChild, node); cfw.addALoad(contextLocal); cfw.addPush(incrDecrMask); addScriptRuntimeInvoke( "refIncrDecr", "(Lorg/mozilla/javascript/Ref;" +"Lorg/mozilla/javascript/Context;" +"I)Ljava/lang/Object;"); break; } default: Codegen.badTree(); } } private static boolean isArithmeticNode(Node node) { int type = node.getType(); return (type == Token.SUB) || (type == Token.MOD) || (type == Token.DIV) || (type == Token.MUL); } private void visitArithmetic(Node node, int opCode, Node child, Node parent) { int childNumberFlag = node.getIntProp(Node.ISNUMBER_PROP, -1); if (childNumberFlag != -1) { generateExpression(child, node); generateExpression(child.getNext(), node); cfw.add(opCode); } else { boolean childOfArithmetic = isArithmeticNode(parent); generateExpression(child, node); if (!isArithmeticNode(child)) addObjectToDouble(); generateExpression(child.getNext(), node); if (!isArithmeticNode(child.getNext())) addObjectToDouble(); cfw.add(opCode); if (!childOfArithmetic) { addDoubleWrap(); } } } private void visitBitOp(Node node, int type, Node child) { int childNumberFlag = node.getIntProp(Node.ISNUMBER_PROP, -1); generateExpression(child, node); // special-case URSH; work with the target arg as a long, so // that we can return a 32-bit unsigned value, and call // toUint32 instead of toInt32. if (type == Token.URSH) { addScriptRuntimeInvoke("toUint32", "(Ljava/lang/Object;)J"); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); // Looks like we need to explicitly mask the shift to 5 bits - // LUSHR takes 6 bits. cfw.addPush(31); cfw.add(ByteCode.IAND); cfw.add(ByteCode.LUSHR); cfw.add(ByteCode.L2D); addDoubleWrap(); return; } if (childNumberFlag == -1) { addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toInt32", "(Ljava/lang/Object;)I"); } else { addScriptRuntimeInvoke("toInt32", "(D)I"); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toInt32", "(D)I"); } switch (type) { case Token.BITOR: cfw.add(ByteCode.IOR); break; case Token.BITXOR: cfw.add(ByteCode.IXOR); break; case Token.BITAND: cfw.add(ByteCode.IAND); break; case Token.RSH: cfw.add(ByteCode.ISHR); break; case Token.LSH: cfw.add(ByteCode.ISHL); break; default: throw Codegen.badTree(); } cfw.add(ByteCode.I2D); if (childNumberFlag == -1) { addDoubleWrap(); } } private int nodeIsDirectCallParameter(Node node) { if (node.getType() == Token.GETVAR && inDirectCallFunction && !itsForcedObjectParameters) { int varIndex = fnCurrent.getVarIndex(node); if (fnCurrent.isParameter(varIndex)) { return varRegisters[varIndex]; } } return -1; } private boolean varIsDirectCallParameter(int varIndex) { return fnCurrent.isParameter(varIndex) && inDirectCallFunction && !itsForcedObjectParameters; } private void genSimpleCompare(int type, int trueGOTO, int falseGOTO) { if (trueGOTO == -1) throw Codegen.badTree(); switch (type) { case Token.LE : cfw.add(ByteCode.DCMPG); cfw.add(ByteCode.IFLE, trueGOTO); break; case Token.GE : cfw.add(ByteCode.DCMPL); cfw.add(ByteCode.IFGE, trueGOTO); break; case Token.LT : cfw.add(ByteCode.DCMPG); cfw.add(ByteCode.IFLT, trueGOTO); break; case Token.GT : cfw.add(ByteCode.DCMPL); cfw.add(ByteCode.IFGT, trueGOTO); break; default : throw Codegen.badTree(); } if (falseGOTO != -1) cfw.add(ByteCode.GOTO, falseGOTO); } private void visitIfJumpRelOp(Node node, Node child, int trueGOTO, int falseGOTO) { if (trueGOTO == -1 || falseGOTO == -1) throw Codegen.badTree(); int type = node.getType(); Node rChild = child.getNext(); if (type == Token.INSTANCEOF || type == Token.IN) { generateExpression(child, node); generateExpression(rChild, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( (type == Token.INSTANCEOF) ? "instanceOf" : "in", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Z"); cfw.add(ByteCode.IFNE, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); return; } int childNumberFlag = node.getIntProp(Node.ISNUMBER_PROP, -1); int left_dcp_register = nodeIsDirectCallParameter(child); int right_dcp_register = nodeIsDirectCallParameter(rChild); if (childNumberFlag != -1) { // Force numeric context on both parameters and optimize // direct call case as Optimizer currently does not handle it if (childNumberFlag != Node.RIGHT) { // Left already has number content generateExpression(child, node); } else if (left_dcp_register != -1) { dcpLoadAsNumber(left_dcp_register); } else { generateExpression(child, node); addObjectToDouble(); } if (childNumberFlag != Node.LEFT) { // Right already has number content generateExpression(rChild, node); } else if (right_dcp_register != -1) { dcpLoadAsNumber(right_dcp_register); } else { generateExpression(rChild, node); addObjectToDouble(); } genSimpleCompare(type, trueGOTO, falseGOTO); } else { if (left_dcp_register != -1 && right_dcp_register != -1) { // Generate code to dynamically check for number content // if both operands are dcp short stack = cfw.getStackTop(); int leftIsNotNumber = cfw.acquireLabel(); cfw.addALoad(left_dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); cfw.add(ByteCode.IF_ACMPNE, leftIsNotNumber); cfw.addDLoad(left_dcp_register + 1); dcpLoadAsNumber(right_dcp_register); genSimpleCompare(type, trueGOTO, falseGOTO); if (stack != cfw.getStackTop()) throw Codegen.badTree(); cfw.markLabel(leftIsNotNumber); int rightIsNotNumber = cfw.acquireLabel(); cfw.addALoad(right_dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); cfw.add(ByteCode.IF_ACMPNE, rightIsNotNumber); cfw.addALoad(left_dcp_register); addObjectToDouble(); cfw.addDLoad(right_dcp_register + 1); genSimpleCompare(type, trueGOTO, falseGOTO); if (stack != cfw.getStackTop()) throw Codegen.badTree(); cfw.markLabel(rightIsNotNumber); // Load both register as objects to call generic cmp_* cfw.addALoad(left_dcp_register); cfw.addALoad(right_dcp_register); } else { generateExpression(child, node); generateExpression(rChild, node); } if (type == Token.GE || type == Token.GT) { cfw.add(ByteCode.SWAP); } String routine = ((type == Token.LT) || (type == Token.GT)) ? "cmp_LT" : "cmp_LE"; addScriptRuntimeInvoke(routine, "(Ljava/lang/Object;" +"Ljava/lang/Object;" +")Z"); cfw.add(ByteCode.IFNE, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); } } private void visitIfJumpEqOp(Node node, Node child, int trueGOTO, int falseGOTO) { if (trueGOTO == -1 || falseGOTO == -1) throw Codegen.badTree(); short stackInitial = cfw.getStackTop(); int type = node.getType(); Node rChild = child.getNext(); // Optimize if one of operands is null if (child.getType() == Token.NULL || rChild.getType() == Token.NULL) { // eq is symmetric in this case if (child.getType() == Token.NULL) { child = rChild; } generateExpression(child, node); if (type == Token.SHEQ || type == Token.SHNE) { int testCode = (type == Token.SHEQ) ? ByteCode.IFNULL : ByteCode.IFNONNULL; cfw.add(testCode, trueGOTO); } else { if (type != Token.EQ) { // swap false/true targets for != if (type != Token.NE) throw Codegen.badTree(); int tmp = trueGOTO; trueGOTO = falseGOTO; falseGOTO = tmp; } cfw.add(ByteCode.DUP); int undefCheckLabel = cfw.acquireLabel(); cfw.add(ByteCode.IFNONNULL, undefCheckLabel); short stack = cfw.getStackTop(); cfw.add(ByteCode.POP); cfw.add(ByteCode.GOTO, trueGOTO); cfw.markLabel(undefCheckLabel, stack); Codegen.pushUndefined(cfw); cfw.add(ByteCode.IF_ACMPEQ, trueGOTO); } cfw.add(ByteCode.GOTO, falseGOTO); } else { int child_dcp_register = nodeIsDirectCallParameter(child); if (child_dcp_register != -1 && rChild.getType() == Token.TO_OBJECT) { Node convertChild = rChild.getFirstChild(); if (convertChild.getType() == Token.NUMBER) { cfw.addALoad(child_dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int notNumbersLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPNE, notNumbersLabel); cfw.addDLoad(child_dcp_register + 1); cfw.addPush(convertChild.getDouble()); cfw.add(ByteCode.DCMPL); if (type == Token.EQ) cfw.add(ByteCode.IFEQ, trueGOTO); else cfw.add(ByteCode.IFNE, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); cfw.markLabel(notNumbersLabel); // fall thru into generic handling } } generateExpression(child, node); generateExpression(rChild, node); String name; int testCode; switch (type) { case Token.EQ: name = "eq"; testCode = ByteCode.IFNE; break; case Token.NE: name = "eq"; testCode = ByteCode.IFEQ; break; case Token.SHEQ: name = "shallowEq"; testCode = ByteCode.IFNE; break; case Token.SHNE: name = "shallowEq"; testCode = ByteCode.IFEQ; break; default: throw Codegen.badTree(); } addScriptRuntimeInvoke(name, "(Ljava/lang/Object;" +"Ljava/lang/Object;" +")Z"); cfw.add(testCode, trueGOTO); cfw.add(ByteCode.GOTO, falseGOTO); } if (stackInitial != cfw.getStackTop()) throw Codegen.badTree(); } private void visitSetName(Node node, Node child) { String name = node.getFirstChild().getString(); while (child != null) { generateExpression(child, node); child = child.getNext(); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(name); addScriptRuntimeInvoke( "setName", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } private void visitStrictSetName(Node node, Node child) { String name = node.getFirstChild().getString(); while (child != null) { generateExpression(child, node); child = child.getNext(); } cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); cfw.addPush(name); addScriptRuntimeInvoke( "strictSetName", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } private void visitSetConst(Node node, Node child) { String name = node.getFirstChild().getString(); while (child != null) { generateExpression(child, node); child = child.getNext(); } cfw.addALoad(contextLocal); cfw.addPush(name); addScriptRuntimeInvoke( "setConst", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +"Ljava/lang/String;" +")Ljava/lang/Object;"); } private void visitGetVar(Node node) { if (!hasVarsInRegs) Kit.codeBug(); int varIndex = fnCurrent.getVarIndex(node); short reg = varRegisters[varIndex]; if (varIsDirectCallParameter(varIndex)) { // Remember that here the isNumber flag means that we // want to use the incoming parameter in a Number // context, so test the object type and convert the // value as necessary. if (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1) { dcpLoadAsNumber(reg); } else { dcpLoadAsObject(reg); } } else if (fnCurrent.isNumberVar(varIndex)) { cfw.addDLoad(reg); } else { cfw.addALoad(reg); } } private void visitSetVar(Node node, Node child, boolean needValue) { if (!hasVarsInRegs) Kit.codeBug(); int varIndex = fnCurrent.getVarIndex(node); generateExpression(child.getNext(), node); boolean isNumber = (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1); short reg = varRegisters[varIndex]; boolean [] constDeclarations = fnCurrent.fnode.getParamAndVarConst(); if (constDeclarations[varIndex]) { if (!needValue) { if (isNumber) cfw.add(ByteCode.POP2); else cfw.add(ByteCode.POP); } } else if (varIsDirectCallParameter(varIndex)) { if (isNumber) { if (needValue) cfw.add(ByteCode.DUP2); cfw.addALoad(reg); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); addDoubleWrap(); cfw.addAStore(reg); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addDStore(reg + 1); cfw.markLabel(beyond); } else { if (needValue) cfw.add(ByteCode.DUP); cfw.addAStore(reg); } } else { boolean isNumberVar = fnCurrent.isNumberVar(varIndex); if (isNumber) { if (isNumberVar) { cfw.addDStore(reg); if (needValue) cfw.addDLoad(reg); } else { if (needValue) cfw.add(ByteCode.DUP2); // Cannot save number in variable since !isNumberVar, // so convert to object addDoubleWrap(); cfw.addAStore(reg); } } else { if (isNumberVar) Kit.codeBug(); cfw.addAStore(reg); if (needValue) cfw.addALoad(reg); } } } private void visitSetConstVar(Node node, Node child, boolean needValue) { if (!hasVarsInRegs) Kit.codeBug(); int varIndex = fnCurrent.getVarIndex(node); generateExpression(child.getNext(), node); boolean isNumber = (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1); short reg = varRegisters[varIndex]; int beyond = cfw.acquireLabel(); int noAssign = cfw.acquireLabel(); if (isNumber) { cfw.addILoad(reg + 2); cfw.add(ByteCode.IFNE, noAssign); short stack = cfw.getStackTop(); cfw.addPush(1); cfw.addIStore(reg + 2); cfw.addDStore(reg); if (needValue) { cfw.addDLoad(reg); cfw.markLabel(noAssign, stack); } else { cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(noAssign, stack); cfw.add(ByteCode.POP2); } } else { cfw.addILoad(reg + 1); cfw.add(ByteCode.IFNE, noAssign); short stack = cfw.getStackTop(); cfw.addPush(1); cfw.addIStore(reg + 1); cfw.addAStore(reg); if (needValue) { cfw.addALoad(reg); cfw.markLabel(noAssign, stack); } else { cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(noAssign, stack); cfw.add(ByteCode.POP); } } cfw.markLabel(beyond); } private void visitGetProp(Node node, Node child) { generateExpression(child, node); // object Node nameChild = child.getNext(); generateExpression(nameChild, node); // the name if (node.getType() == Token.GETPROPNOWARN) { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectPropNoWarn", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); return; } /* for 'this.foo' we call getObjectProp(Scriptable...) which can skip some casting overhead. */ int childType = child.getType(); if (childType == Token.THIS && nameChild.getType() == Token.STRING) { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectProp", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { cfw.addALoad(contextLocal); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke( "getObjectProp", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"); } } private void visitSetProp(int type, Node node, Node child) { Node objectChild = child; generateExpression(child, node); child = child.getNext(); if (type == Token.SETPROP_OP) { cfw.add(ByteCode.DUP); } Node nameChild = child; generateExpression(child, node); child = child.getNext(); if (type == Token.SETPROP_OP) { // stack: ... object object name -> ... object name object name cfw.add(ByteCode.DUP_X1); //for 'this.foo += ...' we call thisGet which can skip some //casting overhead. if (objectChild.getType() == Token.THIS && nameChild.getType() == Token.STRING) { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectProp", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectProp", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } generateExpression(child, node); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "setObjectProp", "(Ljava/lang/Object;" +"Ljava/lang/String;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } private void visitSetElem(int type, Node node, Node child) { generateExpression(child, node); child = child.getNext(); if (type == Token.SETELEM_OP) { cfw.add(ByteCode.DUP); } generateExpression(child, node); child = child.getNext(); boolean indexIsNumber = (node.getIntProp(Node.ISNUMBER_PROP, -1) != -1); if (type == Token.SETELEM_OP) { if (indexIsNumber) { // stack: ... object object number // -> ... object number object number cfw.add(ByteCode.DUP2_X1); cfw.addALoad(contextLocal); addOptRuntimeInvoke( "getObjectIndex", "(Ljava/lang/Object;D" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { // stack: ... object object indexObject // -> ... object indexObject object indexObject cfw.add(ByteCode.DUP_X1); cfw.addALoad(contextLocal); addScriptRuntimeInvoke( "getObjectElem", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } generateExpression(child, node); cfw.addALoad(contextLocal); if (indexIsNumber) { addScriptRuntimeInvoke( "setObjectIndex", "(Ljava/lang/Object;" +"D" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } else { addScriptRuntimeInvoke( "setObjectElem", "(Ljava/lang/Object;" +"Ljava/lang/Object;" +"Ljava/lang/Object;" +"Lorg/mozilla/javascript/Context;" +")Ljava/lang/Object;"); } } private void visitDotQuery(Node node, Node child) { updateLineNumber(node); generateExpression(child, node); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("enterDotQuery", "(Ljava/lang/Object;" +"Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // add push null/pop with label in between to simplify code for loop // continue when it is necessary to pop the null result from // updateDotQuery cfw.add(ByteCode.ACONST_NULL); int queryLoopStart = cfw.acquireLabel(); cfw.markLabel(queryLoopStart); // loop continue jumps here cfw.add(ByteCode.POP); generateExpression(child.getNext(), node); addScriptRuntimeInvoke("toBoolean", "(Ljava/lang/Object;)Z"); cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("updateDotQuery", "(Z" +"Lorg/mozilla/javascript/Scriptable;" +")Ljava/lang/Object;"); cfw.add(ByteCode.DUP); cfw.add(ByteCode.IFNULL, queryLoopStart); // stack: ... non_null_result_of_updateDotQuery cfw.addALoad(variableObjectLocal); addScriptRuntimeInvoke("leaveDotQuery", "(Lorg/mozilla/javascript/Scriptable;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } private int getLocalBlockRegister(Node node) { Node localBlock = (Node)node.getProp(Node.LOCAL_BLOCK_PROP); int localSlot = localBlock.getExistingIntProp(Node.LOCAL_PROP); return localSlot; } private void dcpLoadAsNumber(int dcp_register) { cfw.addALoad(dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); cfw.addALoad(dcp_register); addObjectToDouble(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addDLoad(dcp_register + 1); cfw.markLabel(beyond); } private void dcpLoadAsObject(int dcp_register) { cfw.addALoad(dcp_register); cfw.add(ByteCode.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;"); int isNumberLabel = cfw.acquireLabel(); cfw.add(ByteCode.IF_ACMPEQ, isNumberLabel); short stack = cfw.getStackTop(); cfw.addALoad(dcp_register); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(isNumberLabel, stack); cfw.addDLoad(dcp_register + 1); addDoubleWrap(); cfw.markLabel(beyond); } private void addGoto(Node target, int jumpcode) { int targetLabel = getTargetLabel(target); cfw.add(jumpcode, targetLabel); } private void addObjectToDouble() { addScriptRuntimeInvoke("toNumber", "(Ljava/lang/Object;)D"); } private void addNewObjectArray(int size) { if (size == 0) { if (itsZeroArgArray >= 0) { cfw.addALoad(itsZeroArgArray); } else { cfw.add(ByteCode.GETSTATIC, "org/mozilla/javascript/ScriptRuntime", "emptyArgs", "[Ljava/lang/Object;"); } } else { cfw.addPush(size); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); } } private void addScriptRuntimeInvoke(String methodName, String methodSignature) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org.mozilla.javascript.ScriptRuntime", methodName, methodSignature); } private void addOptRuntimeInvoke(String methodName, String methodSignature) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/optimizer/OptRuntime", methodName, methodSignature); } private void addJumpedBooleanWrap(int trueLabel, int falseLabel) { cfw.markLabel(falseLabel); int skip = cfw.acquireLabel(); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cfw.add(ByteCode.GOTO, skip); cfw.markLabel(trueLabel); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); cfw.markLabel(skip); cfw.adjustStackTop(-1); // only have 1 of true/false } private void addDoubleWrap() { addOptRuntimeInvoke("wrapDouble", "(D)Ljava/lang/Double;"); } /** * Const locals use an extra slot to hold the has-been-assigned-once flag at * runtime. * @param isConst true iff the variable is const * @return the register for the word pair (double/long) */ private short getNewWordPairLocal(boolean isConst) { short result = getConsecutiveSlots(2, isConst); if (result < (MAX_LOCALS - 1)) { locals[result] = 1; locals[result + 1] = 1; if (isConst) locals[result + 2] = 1; if (result == firstFreeLocal) { for (int i = firstFreeLocal + 2; i < MAX_LOCALS; i++) { if (locals[i] == 0) { firstFreeLocal = (short) i; if (localsMax < firstFreeLocal) localsMax = firstFreeLocal; return result; } } } else { return result; } } throw Context.reportRuntimeError("Program too complex " + "(out of locals)"); } private short getNewWordLocal(boolean isConst) { short result = getConsecutiveSlots(1, isConst); if (result < (MAX_LOCALS - 1)) { locals[result] = 1; if (isConst) locals[result + 1] = 1; if (result == firstFreeLocal) { for (int i = firstFreeLocal + 2; i < MAX_LOCALS; i++) { if (locals[i] == 0) { firstFreeLocal = (short) i; if (localsMax < firstFreeLocal) localsMax = firstFreeLocal; return result; } } } else { return result; } } throw Context.reportRuntimeError("Program too complex " + "(out of locals)"); } private short getNewWordLocal() { short result = firstFreeLocal; locals[result] = 1; for (int i = firstFreeLocal + 1; i < MAX_LOCALS; i++) { if (locals[i] == 0) { firstFreeLocal = (short) i; if (localsMax < firstFreeLocal) localsMax = firstFreeLocal; return result; } } throw Context.reportRuntimeError("Program too complex " + "(out of locals)"); } private short getConsecutiveSlots(int count, boolean isConst) { if (isConst) count++; short result = firstFreeLocal; while (true) { if (result >= (MAX_LOCALS - 1)) break; int i; for (i = 0; i < count; i++) if (locals[result + i] != 0) break; if (i >= count) break; result++; } return result; } // This is a valid call only for a local that is allocated by default. private void incReferenceWordLocal(short local) { locals[local]++; } // This is a valid call only for a local that is allocated by default. private void decReferenceWordLocal(short local) { locals[local]--; } private void releaseWordLocal(short local) { if (local < firstFreeLocal) firstFreeLocal = local; locals[local] = 0; } static final int GENERATOR_TERMINATE = -1; static final int GENERATOR_START = 0; static final int GENERATOR_YIELD_START = 1; ClassFileWriter cfw; Codegen codegen; CompilerEnvirons compilerEnv; ScriptNode scriptOrFn; public int scriptOrFnIndex; private int savedCodeOffset; private OptFunctionNode fnCurrent; private boolean isTopLevel; private static final int MAX_LOCALS = 256; private int[] locals; private short firstFreeLocal; private short localsMax; private int itsLineNumber; private boolean hasVarsInRegs; private short[] varRegisters; private boolean inDirectCallFunction; private boolean itsForcedObjectParameters; private int enterAreaStartLabel; private int epilogueLabel; // special known locals. If you add a new local here, be sure // to initialize it to -1 in initBodyGeneration private short variableObjectLocal; private short popvLocal; private short contextLocal; private short argsLocal; private short operationLocal; private short thisObjLocal; private short funObjLocal; private short itsZeroArgArray; private short itsOneArgArray; private short scriptRegexpLocal; private short generatorStateLocal; private boolean isGenerator; private int generatorSwitch; private int maxLocals = 0; private int maxStack = 0; private Map<Node,FinallyReturnPoint> finallys; static class FinallyReturnPoint { public List<Integer> jsrPoints = new ArrayList<Integer>(); public int tableLabel = 0; } }
Fix Bug 531600 - "while(true) continue;" will never trigger observeInstructionCount
src/org/mozilla/javascript/optimizer/Codegen.java
Fix Bug 531600 - "while(true) continue;" will never trigger observeInstructionCount
<ide><path>rc/org/mozilla/javascript/optimizer/Codegen.java <ide> */ <ide> private void addInstructionCount() { <ide> int count = cfw.getCurrentCodeOffset() - savedCodeOffset; <del> if (count == 0) <del> return; <del> addInstructionCount(count); <add> // TODO we used to return for count == 0 but that broke the following: <add> // while(true) continue; (see bug 531600) <add> // To be safe, we now always count at least 1 instruction when invoked. <add> addInstructionCount(Math.max(count, 1)); <ide> } <ide> <ide> /**
Java
apache-2.0
e73e7d96d157c490bc3200b00b7e844d80ecfc76
0
632840804/foursquared.eclair,donka-s27/foursquared,hejie/foursquared.eclair,tahainfocreator/foursquared.eclair,Bishwajet/foursquared,edwinsnao/foursquared.eclair,ming0627/foursquared,ramaraokotu/foursquared.eclair,ksrpraneeth/foursquared,martinx/martinxus-foursquared,kolawoletech/foursquared.eclair,tamzi/foursquared,lxz2014/foursquared,sibendu/foursquared.eclair,stonyyi/foursquared,ekospinach/foursquared,dreamapps786/foursquared,harajuko/foursquared.eclair,dreamapps786/foursquared,smakeit/foursquared,tianyong2/foursquared,sonyraj/foursquared.eclair,varunprathap/foursquared,rahulnagar8/foursquared.eclair,itzmesayooj/foursquared,gtostock/foursquared,hardikamal/foursquared.eclair,RameshBhupathi/foursquared,summerzhao/foursquared,Archenemy-xiatian/foursquared,Zebronaft/foursquared,nara-l/foursquared.eclair,hejie/foursquared.eclair,sakethkaparthi/foursquared,nehalok/foursquared,sathiamour/foursquared,shrikantzarekar/foursquared,rahulnagar8/foursquared.eclair,jamesmartins/foursquared.eclair,hejie/foursquared,foobarprime/foursquared,itrobertson/foursquared,haithemhamzaoui/foursquared.eclair,cairenjie1985/foursquared.eclair,kvnh/foursquared.eclair,mikehowson/foursquared.eclair,jotish/foursquared,waasilzamri/foursquared,harajuko/foursquared,Archenemy-xiatian/foursquared.eclair,smallperson/foursquared,sandeip-yadav/foursquared,ckarademir/foursquared,sbagadi/foursquared.eclair,akhilesh9205/foursquared.eclair,tahainfocreator/foursquared,xuyunhong/foursquared,sonyraj/foursquared.eclair,shrikantzarekar/foursquared,mayankz/foursquared,abedmaatalla/foursquared.eclair,sbolisetty/foursquared.eclair,MarginC/foursquared,akhilesh9205/foursquared.eclair,tyzhaoqi/foursquared.eclair,aasaandinesh/foursquared.eclair,hunanlike/foursquared.eclair,ckarademir/foursquared.eclair,nara-l/foursquared,abdallahynajar/foursquared,wenkeyang/foursquared,zhoujianhanyu/foursquared.eclair,sandeip-yadav/foursquared.eclair,zhoujianhanyu/foursquared.eclair,RameshBhupathi/foursquared.eclair,PriteshJain/foursquared,savelees/foursquared,bancool/foursquared,nextzy/foursquared,mikehowson/foursquared,appoll/foursquared,bancool/foursquared.eclair,tahainfocreator/foursquared,foobarprime/foursquared.eclair,fatihcelik/foursquared,xytrams/foursquared,davideuler/foursquared,hardikamal/foursquared,suman4674/foursquared,fatihcelik/foursquared.eclair,santoshmehta82/foursquared.eclair,EphraimKigamba/foursquared,kolawoletech/foursquared,sbagadi/foursquared,PriteshJain/foursquared,ckarademir/foursquared,dhysf/foursquared,coersum01/foursquared,ramaraokotu/foursquared.eclair,jamesmartins/foursquared,kvnh/foursquared,nluetkemeyer/foursquared,thenewnewbie/foursquared.eclair,tianyong2/foursquared.eclair,vsvankhede/foursquared.eclair,ekospinach/foursquared.eclair,sonyraj/foursquared,gtostock/foursquared,waasilzamri/foursquared,kiruthikak/foursquared,lepinay/foursquared.eclair,donka-s27/foursquared,shivasrinath/foursquared.eclair,lepinay/foursquared.eclair,4DvAnCeBoY/foursquared,pratikjk/foursquared,omondiy/foursquared.eclair,RahulRavindren/foursquared,izBasit/foursquared,sbagadi/foursquared,sakethkaparthi/foursquared,hunanlike/foursquared,ACCTFORGH/foursquared,Zebronaft/foursquared,BinodAryal/foursquared.eclair,kolawoletech/foursquared,mikehowson/foursquared,xuyunhong/foursquared,suripaleru/foursquared,suman4674/foursquared,prashantkumar0509/foursquared.eclair,nluetkemeyer/foursquared.eclair,RameshBhupathi/foursquared,kvnh/foursquared.eclair,aasaandinesh/foursquared,sathiamour/foursquared.eclair,isaiasmercadom/foursquared,votinhaooo/foursquared,RahulRavindren/foursquared.eclair,smallperson/foursquared.eclair,rguindon/raymondeguindon-foursquared,sbolisetty/foursquared,dreamapps786/foursquared.eclair,lxz2014/foursquared.eclair,rihtak/foursquared.eclair,RameshBhupathi/foursquared,suripaleru/foursquared.eclair,pratikjk/foursquared,yusuf-shalahuddin/foursquared,artificiallight92/foursquared.eclair,summerzhao/foursquared,suman4674/foursquared.eclair,hardikamal/foursquared,nasvil/foursquared,srikanthguduru/foursquared,nextzy/foursquared.eclair,jamesmartins/foursquared.eclair,daya-shankar/foursquared,kiruthikak/foursquared,santoshmehta82/foursquared,nara-l/foursquared.eclair,vsvankhede/foursquared,4DvAnCeBoY/foursquared.eclair,xuyunhong/foursquared.eclair,haithemhamzaoui/foursquared,weizp/foursquared.eclair,karanVkgp/foursquared.eclair,karthikkumar12/foursquared.eclair,nasvil/foursquared,smakeit/foursquared.eclair,4DvAnCeBoY/foursquared,since2014/foursquared.eclair,navesdad/foursquared,sakethkaparthi/foursquared,waasilzamri/foursquared.eclair,idmouh/foursquared,malathicode/foursquared.eclair,ACCTFORGH/foursquared,Zebronaft/foursquared.eclair,zhoujianhanyu/foursquared,shivasrinath/foursquared,psvijayk/foursquared,karanVkgp/foursquared,since2014/foursquared,abdallahynajar/foursquared.eclair,nehalok/foursquared,osiloke/foursquared.eclair,ming0627/foursquared,sovaa/foursquared.eclair,starspace/foursquared.eclair,rahulnagar8/foursquared,artificiallight92/foursquared.eclair,hejie/foursquared,stonyyi/foursquared.eclair,tyzhaoqi/foursquared,ming0627/foursquared.eclair,vsvankhede/foursquared,xytrams/foursquared.eclair,daya-shankar/foursquared,tianyong2/foursquared,navesdad/foursquared.eclair,navesdad/foursquared,manisoni28/foursquared.eclair,sovaa/foursquared,psvijayk/foursquared.eclair,Bishwajet/foursquared,MarginC/foursquared,akhilesh9205/foursquared,sbagadi/foursquared,Bishwajet/foursquared.eclair,tyzhaoqi/foursquared,shrikantzarekar/foursquared.eclair,stonyyi/foursquared,ksrpraneeth/foursquared.eclair,azizjonm/foursquared,solubrew/foursquared,psvijayk/foursquared,rihtak/foursquared.eclair,suripaleru/foursquared.eclair,varunprathap/foursquared,Mutai/foursquared,sibendu/foursquared,rguindon/raymondeguindon-foursquared,fuzhou0099/foursquared.eclair,codingz/foursquared.eclair,sathiamour/foursquared.eclair,BinodAryal/foursquared,ekospinach/foursquared.eclair,martinx/martinxus-foursquared,rihtak/foursquared,idmouh/foursquared.eclair,632840804/foursquared.eclair,karanVkgp/foursquared,sevenOneHero/foursquared.eclair,sandeip-yadav/foursquared.eclair,sevenOneHero/foursquared.eclair,starspace/foursquared,vsvankhede/foursquared,idmouh/foursquared,bubao/foursquared.eclair,ACCTFORGH/foursquared.eclair,akhilesh9205/foursquared,sathiamour/foursquared,abdallahynajar/foursquared,ACCTFORGH/foursquared,yusuf-shalahuddin/foursquared,ewugreensignal/foursquared.eclair,forevervhuo/foursquared.eclair,thtak/foursquared,nluetkemeyer/foursquared.eclair,jamesmartins/foursquared,kiruthikak/foursquared.eclair,navesdad/foursquared.eclair,artificiallight92/foursquared,dhysf/foursquared.eclair,jotish/foursquared.eclair,murat8505/foursquared,EphraimKigamba/foursquared.eclair,smallperson/foursquared,pratikjk/foursquared,zhoujianhanyu/foursquared,mansourifatimaezzahraa/foursquared,edwinsnao/foursquared.eclair,nehalok/foursquared.eclair,cairenjie1985/foursquared,rahul18cool/foursquared.eclair,foobarprime/foursquared.eclair,RameshBhupathi/foursquared.eclair,coersum01/foursquared,sonyraj/foursquared,coersum01/foursquared,rahul18cool/foursquared,mansourifatimaezzahraa/foursquared.eclair,xuyunhong/foursquared.eclair,MarginC/foursquared,weizp/foursquared,abedmaatalla/foursquared,starspace/foursquared.eclair,bubao/foursquared,martadewi/foursquared.eclair,nextzy/foursquared.eclair,weizp/foursquared,AnthonyCAS/foursquared.eclair,rahulnagar8/foursquared,CoderJackyHuang/foursquared.eclair,BinodAryal/foursquared,CoderJackyHuang/foursquared.eclair,sibendu/foursquared,paulodiogo/foursquared.eclair,aasaandinesh/foursquared,pratikjk/foursquared.eclair,davideuler/foursquared,lxz2014/foursquared.eclair,savelees/foursquared.eclair,codingz/foursquared.eclair,mayankz/foursquared,prashantkumar0509/foursquared.eclair,since2014/foursquared,thtak/foursquared,gokultaka/foursquared,Bishwajet/foursquared.eclair,akhilesh9205/foursquared,manisoni28/foursquared,rihtak/foursquared,kitencx/foursquared,kitencx/foursquared,abedmaatalla/foursquared.eclair,hunanlike/foursquared.eclair,mansourifatimaezzahraa/foursquared,PriteshJain/foursquared.eclair,murat8505/foursquared.eclair,fatihcelik/foursquared.eclair,sibendu/foursquared.eclair,srikanthguduru/foursquared.eclair,yusuf-shalahuddin/foursquared,EphraimKigamba/foursquared,prashantkumar0509/foursquared,weizp/foursquared,smallperson/foursquared.eclair,dhysf/foursquared,kvnh/foursquared,Zebronaft/foursquared,NarikSmouke228/foursquared,andrewjsauer/foursquared,azai91/foursquared.eclair,aasaandinesh/foursquared,codingz/foursquared,yusuf-shalahuddin/foursquared.eclair,savelees/foursquared,murat8505/foursquared,davideuler/foursquared,zhmkof/foursquared.eclair,gokultaka/foursquared.eclair,rguindon/raymondeguindon-foursquared,nasvil/foursquared.eclair,ragesh91/foursquared.eclair,varunprathap/foursquared.eclair,lepinay/foursquared,AnthonyCAS/foursquared.eclair,ramaraokotu/foursquared,abou78180/foursquared.eclair,hejie/foursquared,gabtni/foursquared,NarikSmouke228/foursquared.eclair,tamzi/foursquared,nara-l/foursquared,rihtak/foursquared,lxz2014/foursquared,itzmesayooj/foursquared.eclair,tahainfocreator/foursquared.eclair,ramaraokotu/foursquared,kolawoletech/foursquared,coersum01/foursquared.eclair,malathicode/foursquared,ewugreensignal/foursquared,jiveshwar/foursquared.eclair,hardikamal/foursquared,since2014/foursquared,itrobertson/foursquared,ayndev/foursquared,jotish/foursquared,isaiasmercadom/foursquared,navesdad/foursquared,nluetkemeyer/foursquared,Bishwajet/foursquared,artificiallight92/foursquared,abedmaatalla/foursquared,4DvAnCeBoY/foursquared.eclair,murat8505/foursquared,abou78180/foursquared,xuyunhong/foursquared,karthikkumar12/foursquared,Archenemy-xiatian/foursquared,manisoni28/foursquared,ekospinach/foursquared,izBasit/foursquared,davideuler/foursquared.eclair,santoshmehta82/foursquared,azizjonm/foursquared,sevenOneHero/foursquared.eclair,sbolisetty/foursquared.eclair,abou78180/foursquared,fatihcelik/foursquared,yusuf-shalahuddin/foursquared.eclair,NarikSmouke228/foursquared.eclair,starspace/foursquared,tamzi/foursquared.eclair,abdallahynajar/foursquared,nasvil/foursquared.eclair,BinodAryal/foursquared.eclair,azai91/foursquared,omondiy/foursquared,nehalok/foursquared,sovaa/foursquared.eclair,Archenemy-xiatian/foursquared.eclair,xzamirx/foursquared.eclair,foobarprime/foursquared,Mutai/foursquared,hardikamal/foursquared.eclair,tianyong2/foursquared.eclair,itzmesayooj/foursquared,andrewjsauer/foursquared,gtostock/foursquared.eclair,kvnh/foursquared,summerzhao/foursquared.eclair,shrikantzarekar/foursquared,edwinsnao/foursquared,azai91/foursquared.eclair,rahulnagar8/foursquared,suripaleru/foursquared,cairenjie1985/foursquared.eclair,kiruthikak/foursquared.eclair,thtak/foursquared,votinhaooo/foursquared,votinhaooo/foursquared.eclair,andrewjsauer/foursquared,rahul18cool/foursquared,RahulRavindren/foursquared.eclair,harajuko/foursquared,smakeit/foursquared,isaiasmercadom/foursquared.eclair,tyzhaoqi/foursquared,waasilzamri/foursquared,lxz2014/foursquared,appoll/foursquared,martadewi/foursquared,jamesmartins/foursquared,malathicode/foursquared,martadewi/foursquared.eclair,summerzhao/foursquared.eclair,ACCTFORGH/foursquared.eclair,osiloke/foursquared.eclair,savelees/foursquared,codingz/foursquared,sbolisetty/foursquared,Zebronaft/foursquared.eclair,omondiy/foursquared,tyzhaoqi/foursquared.eclair,codingz/foursquared,rahul18cool/foursquared.eclair,bancool/foursquared,varunprathap/foursquared,waasilzamri/foursquared.eclair,summerzhao/foursquared,solubrew/foursquared.eclair,kolawoletech/foursquared.eclair,izBasit/foursquared.eclair,karanVkgp/foursquared,EphraimKigamba/foursquared,pratikjk/foursquared.eclair,martadewi/foursquared,ckarademir/foursquared,xzamirx/foursquared.eclair,lepinay/foursquared,forevervhuo/foursquared.eclair,lenkyun/foursquared,srikanthguduru/foursquared,sonyraj/foursquared,azizjonm/foursquared,nehalok/foursquared.eclair,murat8505/foursquared.eclair,manisoni28/foursquared,sbolisetty/foursquared,stonyyi/foursquared,votinhaooo/foursquared.eclair,hunanlike/foursquared,bubao/foursquared,ewugreensignal/foursquared.eclair,gokultaka/foursquared,haithemhamzaoui/foursquared.eclair,thenewnewbie/foursquared,idmouh/foursquared,dhysf/foursquared.eclair,martadewi/foursquared,izBasit/foursquared,abdallahynajar/foursquared.eclair,gokultaka/foursquared,NarikSmouke228/foursquared,suripaleru/foursquared,abou78180/foursquared.eclair,artificiallight92/foursquared,Archenemy-xiatian/foursquared,RahulRavindren/foursquared,idmouh/foursquared.eclair,itzmesayooj/foursquared,azai91/foursquared,fuzhou0099/foursquared.eclair,Mutai/foursquared,abou78180/foursquared,shivasrinath/foursquared.eclair,ayndev/foursquared.eclair,omondiy/foursquared.eclair,thenewnewbie/foursquared,foobarprime/foursquared,prashantkumar0509/foursquared,NarikSmouke228/foursquared,PriteshJain/foursquared,BinodAryal/foursquared,karthikkumar12/foursquared,mansourifatimaezzahraa/foursquared,sandeip-yadav/foursquared,ksrpraneeth/foursquared,vsvankhede/foursquared.eclair,haithemhamzaoui/foursquared,ekospinach/foursquared,dhysf/foursquared,ming0627/foursquared,bancool/foursquared,osiloke/foursquared,sovaa/foursquared,sbagadi/foursquared.eclair,edwinsnao/foursquared,mypapit/foursquared,mansourifatimaezzahraa/foursquared.eclair,wenkeyang/foursquared.eclair,ksrpraneeth/foursquared,bancool/foursquared.eclair,gabtni/foursquared.eclair,votinhaooo/foursquared,thtak/foursquared.eclair,wenkeyang/foursquared,dreamapps786/foursquared,martinx/martinxus-foursquared,donka-s27/foursquared.eclair,bubao/foursquared.eclair,donka-s27/foursquared.eclair,sandeip-yadav/foursquared,nara-l/foursquared,santoshmehta82/foursquared.eclair,PriteshJain/foursquared.eclair,shrikantzarekar/foursquared.eclair,solubrew/foursquared,since2014/foursquared.eclair,zhoujianhanyu/foursquared,tianyong2/foursquared,daya-shankar/foursquared,shivasrinath/foursquared,ewugreensignal/foursquared,karanVkgp/foursquared.eclair,mypapit/foursquared,karthikkumar12/foursquared.eclair,gokultaka/foursquared.eclair,nextzy/foursquared,harajuko/foursquared,srikanthguduru/foursquared,EphraimKigamba/foursquared.eclair,sathiamour/foursquared,gtostock/foursquared.eclair,cairenjie1985/foursquared,ewugreensignal/foursquared,coersum01/foursquared.eclair,lenkyun/foursquared,paulodiogo/foursquared.eclair,daya-shankar/foursquared.eclair,thenewnewbie/foursquared,zhmkof/foursquared.eclair,nasvil/foursquared,bubao/foursquared,loganj/foursquared,ming0627/foursquared.eclair,loganj/foursquared,haithemhamzaoui/foursquared,ragesh91/foursquared,dreamapps786/foursquared.eclair,nextzy/foursquared,malathicode/foursquared.eclair,sovaa/foursquared,santoshmehta82/foursquared,edwinsnao/foursquared,ayndev/foursquared.eclair,harajuko/foursquared.eclair,smakeit/foursquared.eclair,tamzi/foursquared.eclair,thtak/foursquared.eclair,ayndev/foursquared,stonyyi/foursquared.eclair,daya-shankar/foursquared.eclair,xytrams/foursquared,psvijayk/foursquared.eclair,rahul18cool/foursquared,malathicode/foursquared,donka-s27/foursquared,solubrew/foursquared,ckarademir/foursquared.eclair,mikehowson/foursquared,smakeit/foursquared,4DvAnCeBoY/foursquared,gabtni/foursquared,shivasrinath/foursquared,prashantkumar0509/foursquared,srikanthguduru/foursquared.eclair,weizp/foursquared.eclair,kitencx/foursquared,aasaandinesh/foursquared.eclair,mayankz/foursquared,ragesh91/foursquared,itzmesayooj/foursquared.eclair,xytrams/foursquared.eclair,jiveshwar/foursquared.eclair,davideuler/foursquared.eclair,ksrpraneeth/foursquared.eclair,isaiasmercadom/foursquared,isaiasmercadom/foursquared.eclair,ragesh91/foursquared,Mutai/foursquared.eclair,xytrams/foursquared,kiruthikak/foursquared,izBasit/foursquared.eclair,suman4674/foursquared.eclair,jotish/foursquared.eclair,manisoni28/foursquared.eclair,nluetkemeyer/foursquared,gabtni/foursquared,karthikkumar12/foursquared,osiloke/foursquared,savelees/foursquared.eclair,fatihcelik/foursquared,ayndev/foursquared,gabtni/foursquared.eclair,Mutai/foursquared.eclair,thenewnewbie/foursquared.eclair,solubrew/foursquared.eclair,appoll/foursquared,mikehowson/foursquared.eclair,itrobertson/foursquared,ragesh91/foursquared.eclair,smallperson/foursquared,lenkyun/foursquared,psvijayk/foursquared,tahainfocreator/foursquared,tamzi/foursquared,hunanlike/foursquared,ramaraokotu/foursquared,cairenjie1985/foursquared,suman4674/foursquared,jotish/foursquared,wenkeyang/foursquared,azai91/foursquared,varunprathap/foursquared.eclair,abedmaatalla/foursquared,osiloke/foursquared,starspace/foursquared,sibendu/foursquared,omondiy/foursquared,wenkeyang/foursquared.eclair,gtostock/foursquared,mypapit/foursquared,RahulRavindren/foursquared,lepinay/foursquared
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.filters.VenueFilterable; import android.os.Parcel; import android.os.Parcelable; /** * Auto-generated: 2009-05-03 01:14:11.342959 * @author Joe LaPenna ([email protected]) */ public class Checkin implements Parcelable, FoursquareType, VenueFilterable { private String mAddress; private String mAlert; private String mAliasid; private String mCheckinid; private String mCityName; private String mCityid; private String mCrossstreet; private boolean mDballDefault; private String mDisplay; private String mEmail; private String mFirstname; private String mGender; private String mGeolat; private String mGeolong; private String mLastname; private String mMessage; private String mPhone; private String mPhoto; private String mRelativeTime; private String mShout; private boolean mShowDball; private boolean mShowTwitter; private String mStats; private boolean mStatus; private boolean mTwitterDefault; private String mUrl; private String mUserid; private String mVenueid; private String mVenuename; private String mXdatetime; public Checkin() { } public String getAddress() { return mAddress; } public void setAddress(String address) { mAddress = address; } public String getAlert() { return mAlert; } public void setAlert(String alert) { mAlert = alert; } public String getAliasid() { return mAliasid; } public void setAliasid(String aliasid) { mAliasid = aliasid; } public String getCheckinid() { return mCheckinid; } public void setCheckinid(String checkinid) { mCheckinid = checkinid; } public String getCityName() { return mCityName; } public void setCityName(String cityName) { mCityName = cityName; } public String getCityid() { return mCityid; } public void setCityid(String cityid) { mCityid = cityid; } public String getCrossstreet() { return mCrossstreet; } public void setCrossstreet(String crossstreet) { mCrossstreet = crossstreet; } public boolean dballDefault() { return mDballDefault; } public void setDballDefault(boolean dballDefault) { mDballDefault = dballDefault; } public String getDisplay() { return mDisplay; } public void setDisplay(String display) { mDisplay = display; } public String getEmail() { return mEmail; } public void setEmail(String email) { mEmail = email; } public String getFirstname() { return mFirstname; } public void setFirstname(String firstname) { mFirstname = firstname; } public String getGender() { return mGender; } public void setGender(String gender) { mGender = gender; } public String getGeolat() { return mGeolat; } public void setGeolat(String geolat) { mGeolat = geolat; } public String getGeolong() { return mGeolong; } public void setGeolong(String geolong) { mGeolong = geolong; } public String getLastname() { return mLastname; } public void setLastname(String lastname) { mLastname = lastname; } public String getMessage() { return mMessage; } public void setMessage(String message) { mMessage = message; } public String getPhone() { return mPhone; } public void setPhone(String phone) { mPhone = phone; } public String getPhoto() { return mPhoto; } public void setPhoto(String photo) { mPhoto = photo; } public String getRelativeTime() { return mRelativeTime; } public void setRelativeTime(String relativeTime) { mRelativeTime = relativeTime; } public String getShout() { return mShout; } public void setShout(String shout) { mShout = shout; } public boolean showDball() { return mShowDball; } public void setShowDball(boolean showDball) { mShowDball = showDball; } public boolean showTwitter() { return mShowTwitter; } public void setShowTwitter(boolean showTwitter) { mShowTwitter = showTwitter; } public String getStats() { return mStats; } public void setStats(String stats) { mStats = stats; } public boolean status() { return mStatus; } public void setStatus(boolean status) { mStatus = status; } public boolean twitterDefault() { return mTwitterDefault; } public void setTwitterDefault(boolean twitterDefault) { mTwitterDefault = twitterDefault; } public String getUrl() { return mUrl; } public void setUrl(String url) { mUrl = url; } public String getUserid() { return mUserid; } public void setUserid(String userid) { mUserid = userid; } public String getVenueid() { return mVenueid; } public void setVenueid(String venueid) { mVenueid = venueid; } public String getVenuename() { return mVenuename; } public void setVenuename(String venuename) { mVenuename = venuename; } public String getXdatetime() { return mXdatetime; } public void setXdatetime(String xdatetime) { mXdatetime = xdatetime; } /* For Parcelable */ @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { boolean[] booleanArray = { mDballDefault, mShowDball, mShowTwitter, mStatus, mTwitterDefault, }; dest.writeBooleanArray(booleanArray); dest.writeString(this.mAddress); dest.writeString(this.mAlert); dest.writeString(this.mAliasid); dest.writeString(this.mCheckinid); dest.writeString(this.mCityName); dest.writeString(this.mCityid); dest.writeString(this.mCrossstreet); dest.writeString(this.mDisplay); dest.writeString(this.mEmail); dest.writeString(this.mFirstname); dest.writeString(this.mGender); dest.writeString(this.mGeolat); dest.writeString(this.mGeolong); dest.writeString(this.mLastname); dest.writeString(this.mMessage); dest.writeString(this.mPhone); dest.writeString(this.mPhoto); dest.writeString(this.mRelativeTime); dest.writeString(this.mShout); dest.writeString(this.mStats); dest.writeString(this.mUrl); dest.writeString(this.mUserid); dest.writeString(this.mVenueid); dest.writeString(this.mVenuename); dest.writeString(this.mXdatetime); } private void readFromParcel(Parcel source) { boolean[] booleanArray = new boolean[5]; source.readBooleanArray(booleanArray); this.mDballDefault = booleanArray[0]; this.mShowDball = booleanArray[1]; this.mShowTwitter = booleanArray[2]; this.mStatus = booleanArray[3]; this.mTwitterDefault = booleanArray[4]; this.mAddress = source.readString(); this.mAlert = source.readString(); this.mAliasid = source.readString(); this.mCheckinid = source.readString(); this.mCityName = source.readString(); this.mCityid = source.readString(); this.mCrossstreet = source.readString(); this.mDisplay = source.readString(); this.mEmail = source.readString(); this.mFirstname = source.readString(); this.mGender = source.readString(); this.mGeolat = source.readString(); this.mGeolong = source.readString(); this.mLastname = source.readString(); this.mMessage = source.readString(); this.mPhone = source.readString(); this.mPhoto = source.readString(); this.mRelativeTime = source.readString(); this.mShout = source.readString(); this.mStats = source.readString(); this.mUrl = source.readString(); this.mUserid = source.readString(); this.mVenueid = source.readString(); this.mVenuename = source.readString(); this.mXdatetime = source.readString(); } public static final Parcelable.Creator<Checkin> CREATOR = new Parcelable.Creator<Checkin>() { @Override public Checkin createFromParcel(Parcel source) { Checkin instance = new Checkin(); instance.readFromParcel(source); return instance; } @Override public Checkin[] newArray(int size) { return new Checkin[size]; } }; }
src/com/joelapenna/foursquare/types/Checkin.java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import android.os.Parcel; import android.os.Parcelable; /** * Auto-generated: 2009-05-03 01:14:11.342959 * @author Joe LaPenna ([email protected]) */ public class Checkin implements Parcelable, FoursquareType, VenueFilterable { private String mAddress; private String mAlert; private String mAliasid; private String mCheckinid; private String mCityName; private String mCityid; private String mCrossstreet; private boolean mDballDefault; private String mDisplay; private String mEmail; private String mFirstname; private String mGender; private String mGeolat; private String mGeolong; private String mLastname; private String mMessage; private String mPhone; private String mPhoto; private String mRelativeTime; private String mShout; private boolean mShowDball; private boolean mShowTwitter; private String mStats; private boolean mStatus; private boolean mTwitterDefault; private String mUrl; private String mUserid; private String mVenueid; private String mVenuename; private String mXdatetime; public Checkin() { } public String getAddress() { return mAddress; } public void setAddress(String address) { mAddress = address; } public String getAlert() { return mAlert; } public void setAlert(String alert) { mAlert = alert; } public String getAliasid() { return mAliasid; } public void setAliasid(String aliasid) { mAliasid = aliasid; } public String getCheckinid() { return mCheckinid; } public void setCheckinid(String checkinid) { mCheckinid = checkinid; } public String getCityName() { return mCityName; } public void setCityName(String cityName) { mCityName = cityName; } public String getCityid() { return mCityid; } public void setCityid(String cityid) { mCityid = cityid; } public String getCrossstreet() { return mCrossstreet; } public void setCrossstreet(String crossstreet) { mCrossstreet = crossstreet; } public boolean dballDefault() { return mDballDefault; } public void setDballDefault(boolean dballDefault) { mDballDefault = dballDefault; } public String getDisplay() { return mDisplay; } public void setDisplay(String display) { mDisplay = display; } public String getEmail() { return mEmail; } public void setEmail(String email) { mEmail = email; } public String getFirstname() { return mFirstname; } public void setFirstname(String firstname) { mFirstname = firstname; } public String getGender() { return mGender; } public void setGender(String gender) { mGender = gender; } public String getGeolat() { return mGeolat; } public void setGeolat(String geolat) { mGeolat = geolat; } public String getGeolong() { return mGeolong; } public void setGeolong(String geolong) { mGeolong = geolong; } public String getLastname() { return mLastname; } public void setLastname(String lastname) { mLastname = lastname; } public String getMessage() { return mMessage; } public void setMessage(String message) { mMessage = message; } public String getPhone() { return mPhone; } public void setPhone(String phone) { mPhone = phone; } public String getPhoto() { return mPhoto; } public void setPhoto(String photo) { mPhoto = photo; } public String getRelativeTime() { return mRelativeTime; } public void setRelativeTime(String relativeTime) { mRelativeTime = relativeTime; } public String getShout() { return mShout; } public void setShout(String shout) { mShout = shout; } public boolean showDball() { return mShowDball; } public void setShowDball(boolean showDball) { mShowDball = showDball; } public boolean showTwitter() { return mShowTwitter; } public void setShowTwitter(boolean showTwitter) { mShowTwitter = showTwitter; } public String getStats() { return mStats; } public void setStats(String stats) { mStats = stats; } public boolean status() { return mStatus; } public void setStatus(boolean status) { mStatus = status; } public boolean twitterDefault() { return mTwitterDefault; } public void setTwitterDefault(boolean twitterDefault) { mTwitterDefault = twitterDefault; } public String getUrl() { return mUrl; } public void setUrl(String url) { mUrl = url; } public String getUserid() { return mUserid; } public void setUserid(String userid) { mUserid = userid; } public String getVenueid() { return mVenueid; } public void setVenueid(String venueid) { mVenueid = venueid; } public String getVenuename() { return mVenuename; } public void setVenuename(String venuename) { mVenuename = venuename; } public String getXdatetime() { return mXdatetime; } public void setXdatetime(String xdatetime) { mXdatetime = xdatetime; } /* For Parcelable */ @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { boolean[] booleanArray = { mDballDefault, mShowDball, mShowTwitter, mStatus, mTwitterDefault, }; dest.writeBooleanArray(booleanArray); dest.writeString(this.mAddress); dest.writeString(this.mAlert); dest.writeString(this.mAliasid); dest.writeString(this.mCheckinid); dest.writeString(this.mCityName); dest.writeString(this.mCityid); dest.writeString(this.mCrossstreet); dest.writeString(this.mDisplay); dest.writeString(this.mEmail); dest.writeString(this.mFirstname); dest.writeString(this.mGender); dest.writeString(this.mGeolat); dest.writeString(this.mGeolong); dest.writeString(this.mLastname); dest.writeString(this.mMessage); dest.writeString(this.mPhone); dest.writeString(this.mPhoto); dest.writeString(this.mRelativeTime); dest.writeString(this.mShout); dest.writeString(this.mStats); dest.writeString(this.mUrl); dest.writeString(this.mUserid); dest.writeString(this.mVenueid); dest.writeString(this.mVenuename); dest.writeString(this.mXdatetime); } private void readFromParcel(Parcel source) { boolean[] booleanArray = new boolean[5]; source.readBooleanArray(booleanArray); this.mDballDefault = booleanArray[0]; this.mShowDball = booleanArray[1]; this.mShowTwitter = booleanArray[2]; this.mStatus = booleanArray[3]; this.mTwitterDefault = booleanArray[4]; this.mAddress = source.readString(); this.mAlert = source.readString(); this.mAliasid = source.readString(); this.mCheckinid = source.readString(); this.mCityName = source.readString(); this.mCityid = source.readString(); this.mCrossstreet = source.readString(); this.mDisplay = source.readString(); this.mEmail = source.readString(); this.mFirstname = source.readString(); this.mGender = source.readString(); this.mGeolat = source.readString(); this.mGeolong = source.readString(); this.mLastname = source.readString(); this.mMessage = source.readString(); this.mPhone = source.readString(); this.mPhoto = source.readString(); this.mRelativeTime = source.readString(); this.mShout = source.readString(); this.mStats = source.readString(); this.mUrl = source.readString(); this.mUserid = source.readString(); this.mVenueid = source.readString(); this.mVenuename = source.readString(); this.mXdatetime = source.readString(); } public static final Parcelable.Creator<Checkin> CREATOR = new Parcelable.Creator<Checkin>() { @Override public Checkin createFromParcel(Parcel source) { Checkin instance = new Checkin(); instance.readFromParcel(source); return instance; } @Override public Checkin[] newArray(int size) { return new Checkin[size]; } }; }
Restore VenueFilterable on Checkin type committer: Joe LaPenna <[email protected]>
src/com/joelapenna/foursquare/types/Checkin.java
Restore VenueFilterable on Checkin type
<ide><path>rc/com/joelapenna/foursquare/types/Checkin.java <ide> */ <ide> <ide> package com.joelapenna.foursquare.types; <add> <add>import com.joelapenna.foursquare.filters.VenueFilterable; <ide> <ide> import android.os.Parcel; <ide> import android.os.Parcelable; <ide> private String mVenueid; <ide> private String mVenuename; <ide> private String mXdatetime; <del> <add> <ide> public Checkin() { <ide> } <del> <add> <ide> public String getAddress() { <ide> return mAddress; <ide> } <del> <add> <ide> public void setAddress(String address) { <ide> mAddress = address; <ide> } <del> <add> <ide> public String getAlert() { <ide> return mAlert; <ide> } <del> <add> <ide> public void setAlert(String alert) { <ide> mAlert = alert; <ide> } <del> <add> <ide> public String getAliasid() { <ide> return mAliasid; <ide> } <del> <add> <ide> public void setAliasid(String aliasid) { <ide> mAliasid = aliasid; <ide> } <del> <add> <ide> public String getCheckinid() { <ide> return mCheckinid; <ide> } <del> <add> <ide> public void setCheckinid(String checkinid) { <ide> mCheckinid = checkinid; <ide> } <del> <add> <ide> public String getCityName() { <ide> return mCityName; <ide> } <del> <add> <ide> public void setCityName(String cityName) { <ide> mCityName = cityName; <ide> } <del> <add> <ide> public String getCityid() { <ide> return mCityid; <ide> } <del> <add> <ide> public void setCityid(String cityid) { <ide> mCityid = cityid; <ide> } <del> <add> <ide> public String getCrossstreet() { <ide> return mCrossstreet; <ide> } <del> <add> <ide> public void setCrossstreet(String crossstreet) { <ide> mCrossstreet = crossstreet; <ide> } <del> <add> <ide> public boolean dballDefault() { <ide> return mDballDefault; <ide> } <del> <add> <ide> public void setDballDefault(boolean dballDefault) { <ide> mDballDefault = dballDefault; <ide> } <del> <add> <ide> public String getDisplay() { <ide> return mDisplay; <ide> } <del> <add> <ide> public void setDisplay(String display) { <ide> mDisplay = display; <ide> } <del> <add> <ide> public String getEmail() { <ide> return mEmail; <ide> } <del> <add> <ide> public void setEmail(String email) { <ide> mEmail = email; <ide> } <del> <add> <ide> public String getFirstname() { <ide> return mFirstname; <ide> } <del> <add> <ide> public void setFirstname(String firstname) { <ide> mFirstname = firstname; <ide> } <del> <add> <ide> public String getGender() { <ide> return mGender; <ide> } <del> <add> <ide> public void setGender(String gender) { <ide> mGender = gender; <ide> } <del> <add> <ide> public String getGeolat() { <ide> return mGeolat; <ide> } <del> <add> <ide> public void setGeolat(String geolat) { <ide> mGeolat = geolat; <ide> } <del> <add> <ide> public String getGeolong() { <ide> return mGeolong; <ide> } <del> <add> <ide> public void setGeolong(String geolong) { <ide> mGeolong = geolong; <ide> } <del> <add> <ide> public String getLastname() { <ide> return mLastname; <ide> } <del> <add> <ide> public void setLastname(String lastname) { <ide> mLastname = lastname; <ide> } <del> <add> <ide> public String getMessage() { <ide> return mMessage; <ide> } <del> <add> <ide> public void setMessage(String message) { <ide> mMessage = message; <ide> } <del> <add> <ide> public String getPhone() { <ide> return mPhone; <ide> } <del> <add> <ide> public void setPhone(String phone) { <ide> mPhone = phone; <ide> } <del> <add> <ide> public String getPhoto() { <ide> return mPhoto; <ide> } <del> <add> <ide> public void setPhoto(String photo) { <ide> mPhoto = photo; <ide> } <del> <add> <ide> public String getRelativeTime() { <ide> return mRelativeTime; <ide> } <del> <add> <ide> public void setRelativeTime(String relativeTime) { <ide> mRelativeTime = relativeTime; <ide> } <del> <add> <ide> public String getShout() { <ide> return mShout; <ide> } <del> <add> <ide> public void setShout(String shout) { <ide> mShout = shout; <ide> } <del> <add> <ide> public boolean showDball() { <ide> return mShowDball; <ide> } <del> <add> <ide> public void setShowDball(boolean showDball) { <ide> mShowDball = showDball; <ide> } <del> <add> <ide> public boolean showTwitter() { <ide> return mShowTwitter; <ide> } <del> <add> <ide> public void setShowTwitter(boolean showTwitter) { <ide> mShowTwitter = showTwitter; <ide> } <del> <add> <ide> public String getStats() { <ide> return mStats; <ide> } <del> <add> <ide> public void setStats(String stats) { <ide> mStats = stats; <ide> } <del> <add> <ide> public boolean status() { <ide> return mStatus; <ide> } <del> <add> <ide> public void setStatus(boolean status) { <ide> mStatus = status; <ide> } <del> <add> <ide> public boolean twitterDefault() { <ide> return mTwitterDefault; <ide> } <del> <add> <ide> public void setTwitterDefault(boolean twitterDefault) { <ide> mTwitterDefault = twitterDefault; <ide> } <del> <add> <ide> public String getUrl() { <ide> return mUrl; <ide> } <del> <add> <ide> public void setUrl(String url) { <ide> mUrl = url; <ide> } <del> <add> <ide> public String getUserid() { <ide> return mUserid; <ide> } <del> <add> <ide> public void setUserid(String userid) { <ide> mUserid = userid; <ide> } <del> <add> <ide> public String getVenueid() { <ide> return mVenueid; <ide> } <del> <add> <ide> public void setVenueid(String venueid) { <ide> mVenueid = venueid; <ide> } <del> <add> <ide> public String getVenuename() { <ide> return mVenuename; <ide> } <del> <add> <ide> public void setVenuename(String venuename) { <ide> mVenuename = venuename; <ide> } <del> <add> <ide> public String getXdatetime() { <ide> return mXdatetime; <ide> } <del> <add> <ide> public void setXdatetime(String xdatetime) { <ide> mXdatetime = xdatetime; <ide> } <del> <add> <ide> /* For Parcelable */ <del> <add> <ide> @Override <ide> public int describeContents() { <ide> return 0; <ide> } <del> <add> <ide> @Override <ide> public void writeToParcel(Parcel dest, int flags) { <ide> boolean[] booleanArray = { <del> mDballDefault, <del> mShowDball, <del> mShowTwitter, <del> mStatus, <add> mDballDefault, <add> mShowDball, <add> mShowTwitter, <add> mStatus, <ide> mTwitterDefault, <ide> }; <ide> dest.writeBooleanArray(booleanArray); <del> dest.writeString(this.mAddress); <del> dest.writeString(this.mAlert); <del> dest.writeString(this.mAliasid); <del> dest.writeString(this.mCheckinid); <del> dest.writeString(this.mCityName); <del> dest.writeString(this.mCityid); <del> dest.writeString(this.mCrossstreet); <del> dest.writeString(this.mDisplay); <del> dest.writeString(this.mEmail); <del> dest.writeString(this.mFirstname); <del> dest.writeString(this.mGender); <del> dest.writeString(this.mGeolat); <del> dest.writeString(this.mGeolong); <del> dest.writeString(this.mLastname); <del> dest.writeString(this.mMessage); <del> dest.writeString(this.mPhone); <del> dest.writeString(this.mPhoto); <del> dest.writeString(this.mRelativeTime); <del> dest.writeString(this.mShout); <del> dest.writeString(this.mStats); <del> dest.writeString(this.mUrl); <del> dest.writeString(this.mUserid); <del> dest.writeString(this.mVenueid); <del> dest.writeString(this.mVenuename); <add> dest.writeString(this.mAddress); <add> dest.writeString(this.mAlert); <add> dest.writeString(this.mAliasid); <add> dest.writeString(this.mCheckinid); <add> dest.writeString(this.mCityName); <add> dest.writeString(this.mCityid); <add> dest.writeString(this.mCrossstreet); <add> dest.writeString(this.mDisplay); <add> dest.writeString(this.mEmail); <add> dest.writeString(this.mFirstname); <add> dest.writeString(this.mGender); <add> dest.writeString(this.mGeolat); <add> dest.writeString(this.mGeolong); <add> dest.writeString(this.mLastname); <add> dest.writeString(this.mMessage); <add> dest.writeString(this.mPhone); <add> dest.writeString(this.mPhoto); <add> dest.writeString(this.mRelativeTime); <add> dest.writeString(this.mShout); <add> dest.writeString(this.mStats); <add> dest.writeString(this.mUrl); <add> dest.writeString(this.mUserid); <add> dest.writeString(this.mVenueid); <add> dest.writeString(this.mVenuename); <ide> dest.writeString(this.mXdatetime); <ide> } <del> <add> <ide> private void readFromParcel(Parcel source) { <ide> boolean[] booleanArray = new boolean[5]; <ide> source.readBooleanArray(booleanArray); <del> this.mDballDefault = booleanArray[0]; <del> this.mShowDball = booleanArray[1]; <del> this.mShowTwitter = booleanArray[2]; <del> this.mStatus = booleanArray[3]; <del> this.mTwitterDefault = booleanArray[4]; <del> this.mAddress = source.readString(); <del> this.mAlert = source.readString(); <del> this.mAliasid = source.readString(); <del> this.mCheckinid = source.readString(); <del> this.mCityName = source.readString(); <del> this.mCityid = source.readString(); <del> this.mCrossstreet = source.readString(); <del> this.mDisplay = source.readString(); <del> this.mEmail = source.readString(); <del> this.mFirstname = source.readString(); <del> this.mGender = source.readString(); <del> this.mGeolat = source.readString(); <del> this.mGeolong = source.readString(); <del> this.mLastname = source.readString(); <del> this.mMessage = source.readString(); <del> this.mPhone = source.readString(); <del> this.mPhoto = source.readString(); <del> this.mRelativeTime = source.readString(); <del> this.mShout = source.readString(); <del> this.mStats = source.readString(); <del> this.mUrl = source.readString(); <del> this.mUserid = source.readString(); <del> this.mVenueid = source.readString(); <del> this.mVenuename = source.readString(); <add> this.mDballDefault = booleanArray[0]; <add> this.mShowDball = booleanArray[1]; <add> this.mShowTwitter = booleanArray[2]; <add> this.mStatus = booleanArray[3]; <add> this.mTwitterDefault = booleanArray[4]; <add> this.mAddress = source.readString(); <add> this.mAlert = source.readString(); <add> this.mAliasid = source.readString(); <add> this.mCheckinid = source.readString(); <add> this.mCityName = source.readString(); <add> this.mCityid = source.readString(); <add> this.mCrossstreet = source.readString(); <add> this.mDisplay = source.readString(); <add> this.mEmail = source.readString(); <add> this.mFirstname = source.readString(); <add> this.mGender = source.readString(); <add> this.mGeolat = source.readString(); <add> this.mGeolong = source.readString(); <add> this.mLastname = source.readString(); <add> this.mMessage = source.readString(); <add> this.mPhone = source.readString(); <add> this.mPhoto = source.readString(); <add> this.mRelativeTime = source.readString(); <add> this.mShout = source.readString(); <add> this.mStats = source.readString(); <add> this.mUrl = source.readString(); <add> this.mUserid = source.readString(); <add> this.mVenueid = source.readString(); <add> this.mVenuename = source.readString(); <ide> this.mXdatetime = source.readString(); <ide> } <del> <add> <ide> public static final Parcelable.Creator<Checkin> CREATOR = new Parcelable.Creator<Checkin>() { <del> <add> <ide> @Override <ide> public Checkin createFromParcel(Parcel source) { <ide> Checkin instance = new Checkin(); <ide> instance.readFromParcel(source); <ide> return instance; <ide> } <del> <add> <ide> @Override <ide> public Checkin[] newArray(int size) { <ide> return new Checkin[size]; <ide> } <del> <add> <ide> }; <del> <add> <ide> }
Java
apache-2.0
7b6e8a714c5a2dcc9bdeffc85d01bfd4eef1e313
0
kaddiya/grorchestrator
package org.kaddiya.grorchestrator.models.core; /** * Created by Webonise on 29/12/16. */ public enum ACCESSIBILITY { RO, RW }
src/main/groovy/org/kaddiya/grorchestrator/models/core/ACCESSIBILITY.java
package org.kaddiya.grorchestrator.models.core; /** * Created by Webonise on 29/12/16. */ public enum ACCESSIBILITY { RO, WO }
Changes for having the RW as a permission
src/main/groovy/org/kaddiya/grorchestrator/models/core/ACCESSIBILITY.java
Changes for having the RW as a permission
<ide><path>rc/main/groovy/org/kaddiya/grorchestrator/models/core/ACCESSIBILITY.java <ide> */ <ide> public enum ACCESSIBILITY { <ide> RO, <del> WO <add> RW <ide> }
Java
bsd-3-clause
923f21947eced1948fa086fcef28c754b305b45a
0
oci-pronghorn/FogLight,oci-pronghorn/PronghornIoT,oci-pronghorn/FogLight,oci-pronghorn/PronghornIoT,oci-pronghorn/FogLight
package com.ociweb.pronghorn.iot; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.iot.hardware.HardConnection; import com.ociweb.iot.hardware.Hardware; import com.ociweb.iot.maker.AnalogListener; import com.ociweb.iot.maker.DigitalListener; import com.ociweb.iot.maker.I2CListener; import com.ociweb.iot.maker.PayloadReader; import com.ociweb.iot.maker.PubSubListener; import com.ociweb.iot.maker.RestListener; import com.ociweb.iot.maker.RotaryListener; import com.ociweb.iot.maker.StartupListener; import com.ociweb.iot.maker.TimeListener; import com.ociweb.pronghorn.iot.schema.GroveResponseSchema; import com.ociweb.pronghorn.iot.schema.I2CResponseSchema; import com.ociweb.pronghorn.iot.schema.MessageSubscription; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeReader; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.util.ma.MAvgRollerLong; public class ReactiveListenerStage extends PronghornStage { protected final Object listener; protected final Pipe<?>[] inputPipes; protected final Pipe<?>[] outputPipes; protected long timeTrigger; protected long timeRate; protected Hardware hardware; private static final Logger logger = LoggerFactory.getLogger(ReactiveListenerStage.class); private static final int MAX_SENSORS = 32; protected MAvgRollerLong[] rollingMovingAveragesAnalog; protected MAvgRollerLong[] rollingMovingAveragesDigital; protected int[] oversampledAnalogValues; private static final int MAX_CONNECTIONS = 10; //for analog values returns the one with the longest run within the last n samples protected static final int OVERSAMPLE = 3; // (COUNT), SAMPLE1, ... SAMPLEn protected static final int OVERSAMPLE_STEP = OVERSAMPLE+1; protected int[] lastDigitalValues; protected int[] lastAnalogValues; public ReactiveListenerStage(GraphManager graphManager, Object listener, Pipe<?>[] inputPipes, Pipe<?>[] outputPipes, Hardware hardware) { super(graphManager, inputPipes, outputPipes); this.listener = listener; this.inputPipes = inputPipes; this.outputPipes = outputPipes; this.hardware = hardware; //force all commands to happen upon publish and release this.supportsBatchedPublish = false; this.supportsBatchedRelease = false; } private void setupMovingAverages(MAvgRollerLong[] target, HardConnection[] con) { int i = con.length; while (--i >= 0) { int ms = con[i].movingAverageWindowMS; int rate = con[i].responseMS; target[con[i].connection] = new MAvgRollerLong(ms/rate); System.out.println("expecting moving average on connection "+con[i].connection); } } public void setTimeEventSchedule(long rate) { timeRate = rate; long now = hardware.currentTimeMillis(); if (timeTrigger <= now) { timeTrigger = now + timeRate; } } protected int findStableReading(int tempValue, int connector) { int offset = updateRunLenghtOfActiveValue(tempValue, connector); return findMedian(offset); } private int findMedian(int offset) { assert(3 == OVERSAMPLE);//ONLY WORKS FOR 3 int a = oversampledAnalogValues[offset+1]; int b = oversampledAnalogValues[offset+2]; int c = oversampledAnalogValues[offset+3]; //TODO: what if we returned the floor? if (a>b) { if (b>c) { return b; } else { return c; } } else { //b > a if (a>c) { return a; } else { return c; } } } private int updateRunLenghtOfActiveValue(int tempValue, int connector) { //store this value with the oversamples int offset = connector*OVERSAMPLE_STEP; int pos = oversampledAnalogValues[offset]; if (--pos<=0) { pos = OVERSAMPLE; } oversampledAnalogValues[offset] = pos; oversampledAnalogValues[offset+pos] = tempValue; return offset; } @Override public void startup() { if (listener instanceof StartupListener) { ((StartupListener)listener).startup(); } //Init all the moving averages to the right size rollingMovingAveragesAnalog = new MAvgRollerLong[MAX_SENSORS]; rollingMovingAveragesDigital = new MAvgRollerLong[MAX_SENSORS]; System.out.println("setup analogs "+Arrays.toString(hardware.analogInputs)); setupMovingAverages(rollingMovingAveragesAnalog, hardware.analogInputs); System.out.println("setup digitals "+Arrays.toString(hardware.digitalInputs)); setupMovingAverages(rollingMovingAveragesDigital, hardware.digitalInputs); lastDigitalValues = new int[MAX_CONNECTIONS]; lastAnalogValues = new int[MAX_CONNECTIONS]; oversampledAnalogValues = new int[MAX_CONNECTIONS*OVERSAMPLE_STEP]; } @Override public void run() { processTimeEvents(listener); //TODO: replace with linked list of processors?, NOTE each one also needs a length bound so it does not starve the rest. int p = inputPipes.length; while (--p >= 0) { //TODO: this solution works but smells, a "process" lambda added to the Pipe may be a better solution? Still thinking.... Pipe<?> localPipe = inputPipes[p]; if (Pipe.isForSchema(localPipe, GroveResponseSchema.instance)) { consumeResponseMessage(listener, (Pipe<GroveResponseSchema>) localPipe); } else if (Pipe.isForSchema(localPipe, I2CResponseSchema.instance)) { consumeI2CMessage(listener, (Pipe<I2CResponseSchema>) localPipe); } else if (Pipe.isForSchema(localPipe, MessageSubscription.instance)) { consumePubSubMessage(listener, (Pipe<MessageSubscription>) localPipe); } else { logger.error("unrecognized pipe sent to listener of type {} ", Pipe.schemaName(localPipe)); } } } private StringBuilder workspace = new StringBuilder(); private PayloadReader payloadReader; private void consumePubSubMessage(Object listener, Pipe<MessageSubscription> p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); switch (msgIdx) { case MessageSubscription.MSG_PUBLISH_103: workspace.setLength(0); CharSequence topic = PipeReader.readUTF8(p, MessageSubscription.MSG_PUBLISH_103_FIELD_TOPIC_1, workspace); if (null==payloadReader) { payloadReader = new PayloadReader(p); } payloadReader.openHighLevelAPIField(MessageSubscription.MSG_PUBLISH_103_FIELD_PAYLOAD_3); // if (! payloadReader.markSupported() ) { // logger.warn("we need mark to be suppported for payloads in pubsub and http."); //TODO: need to implement mark, urgent. // } ((PubSubListener)listener).message(topic, payloadReader); break; case -1: requestShutdown(); PipeReader.releaseReadLock(p); return; default: throw new UnsupportedOperationException("Unknown id: "+msgIdx); } PipeReader.releaseReadLock(p); } } private void processTimeEvents(Object listener) { //if we do have a clock schedule if (0 != timeRate) { if (listener instanceof TimeListener) { long now = hardware.currentTimeMillis(); if (now >= timeTrigger) { ((TimeListener)listener).timeEvent(now); timeTrigger += timeRate; } } } } private void consumeRestMessage(Object listener2, Pipe<?> p) { if (null!= p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); //no need to check instance of since this was registered and we have a pipe ((RestListener)listener).restRequest(1, null, null); //done reading message off pipe PipeReader.releaseReadLock(p); } } } protected void consumeI2CMessage(Object listener, Pipe<I2CResponseSchema> p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); switch (msgIdx) { case I2CResponseSchema.MSG_RESPONSE_10: if (listener instanceof I2CListener) { int addr = PipeReader.readInt(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_ADDRESS_11); int register = PipeReader.readInt(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_REGISTER_14); int time = PipeReader.readInt(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_TIME_13); byte[] backing = PipeReader.readBytesBackingArray(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); int position = PipeReader.readBytesPosition(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); int length = PipeReader.readBytesLength(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); int mask = PipeReader.readBytesMask(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); ((I2CListener)listener).i2cEvent(addr, register, time, backing, position, length, mask); } break; case -1: requestShutdown(); PipeReader.releaseReadLock(p); return; default: throw new UnsupportedOperationException("Unknown id: "+msgIdx); } //done reading message off pipe PipeReader.releaseReadLock(p); } } protected void consumeResponseMessage(Object listener, Pipe<GroveResponseSchema> p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); switch (msgIdx) { case GroveResponseSchema.MSG_ANALOGSAMPLE_30: if (listener instanceof AnalogListener) { int connector = PipeReader.readInt(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_CONNECTOR_31); long time = PipeReader.readLong(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_TIME_11); int value = PipeReader.readInt(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_VALUE_32); //TODO: remove average. int average = PipeReader.readInt(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_AVERAGE_33); long duration = PipeReader.readLong(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_PREVDURATION_35); int runningValue = findStableReading(value, connector); MAvgRollerLong.roll(rollingMovingAveragesAnalog[connector], runningValue); int mean = 0/*(int)MAvgRollerLong.mean(rollingMovingAveragesAnalog[connector])*/; ((AnalogListener)listener).analogEvent(connector, time, mean, runningValue); } break; case GroveResponseSchema.MSG_DIGITALSAMPLE_20: if (listener instanceof DigitalListener) { int connector = PipeReader.readInt(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_CONNECTOR_21); long time = PipeReader.readLong(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_TIME_11); int value = PipeReader.readInt(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_VALUE_22); long duration = PipeReader.readLong(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_PREVDURATION_25); ((DigitalListener)listener).digitalEvent(connector, time, value); } break; case GroveResponseSchema.MSG_ENCODER_70: if (listener instanceof RotaryListener) { int connector = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_CONNECTOR_71); long time = PipeReader.readLong(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_TIME_11); int value = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_VALUE_72); int delta = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_DELTA_73); int speed = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_SPEED_74); long duration = PipeReader.readLong(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_PREVDURATION_75); ((RotaryListener)listener).rotaryEvent(connector, time, value, delta, speed); } break; case -1: { requestShutdown(); PipeReader.releaseReadLock(p); return; } default: throw new UnsupportedOperationException("Unknown id: "+msgIdx); } //done reading message off pipe PipeReader.releaseReadLock(p); } } }
src/main/java/com/ociweb/pronghorn/iot/ReactiveListenerStage.java
package com.ociweb.pronghorn.iot; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.iot.hardware.HardConnection; import com.ociweb.iot.hardware.Hardware; import com.ociweb.iot.maker.AnalogListener; import com.ociweb.iot.maker.DigitalListener; import com.ociweb.iot.maker.I2CListener; import com.ociweb.iot.maker.PayloadReader; import com.ociweb.iot.maker.PubSubListener; import com.ociweb.iot.maker.RestListener; import com.ociweb.iot.maker.RotaryListener; import com.ociweb.iot.maker.StartupListener; import com.ociweb.iot.maker.TimeListener; import com.ociweb.pronghorn.iot.schema.GroveResponseSchema; import com.ociweb.pronghorn.iot.schema.I2CResponseSchema; import com.ociweb.pronghorn.iot.schema.MessageSubscription; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeReader; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.util.ma.MAvgRollerLong; public class ReactiveListenerStage extends PronghornStage { protected final Object listener; protected final Pipe<?>[] inputPipes; protected final Pipe<?>[] outputPipes; protected long timeTrigger; protected long timeRate; protected Hardware hardware; private static final Logger logger = LoggerFactory.getLogger(ReactiveListenerStage.class); private static final int MAX_SENSORS = 32; protected MAvgRollerLong[] rollingMovingAveragesAnalog; protected MAvgRollerLong[] rollingMovingAveragesDigital; protected int[] oversampledAnalogValues; private static final int MAX_CONNECTIONS = 10; //for analog values returns the one with the longest run within the last n samples protected static final int OVERSAMPLE = 3; // (COUNT), SAMPLE1, ... SAMPLEn protected static final int OVERSAMPLE_STEP = OVERSAMPLE+1; protected int[] lastDigitalValues; protected int[] lastAnalogValues; public ReactiveListenerStage(GraphManager graphManager, Object listener, Pipe<?>[] inputPipes, Pipe<?>[] outputPipes, Hardware hardware) { super(graphManager, inputPipes, outputPipes); this.listener = listener; this.inputPipes = inputPipes; this.outputPipes = outputPipes; this.hardware = hardware; //force all commands to happen upon publish and release this.supportsBatchedPublish = false; this.supportsBatchedRelease = false; } private void setupMovingAverages(MAvgRollerLong[] target, HardConnection[] con) { int i = con.length; while (--i >= 0) { int ms = con[i].movingAverageWindowMS; int rate = con[i].responseMS; target[con[i].connection] = new MAvgRollerLong(ms/rate); System.out.println("expecting moving average on connection "+con[i].connection); } } public void setTimeEventSchedule(long rate) { timeRate = rate; long now = hardware.currentTimeMillis(); if (timeTrigger <= now) { timeTrigger = now + timeRate; } } protected int findStableReading(int tempValue, int connector) { int offset = updateRunLenghtOfActiveValue(tempValue, connector); return findMedian(offset); } private int findMedian(int offset) { assert(3 == OVERSAMPLE);//ONLY WORKS FOR 3 int a = oversampledAnalogValues[offset+1]; int b = oversampledAnalogValues[offset+2]; int c = oversampledAnalogValues[offset+3]; //TODO: what if we returned the floor? if (a>b) { if (b>c) { return b; } else { return c; } } else { //b > a if (a>c) { return a; } else { return c; } } } private int updateRunLenghtOfActiveValue(int tempValue, int connector) { //store this value with the oversamples int offset = connector*OVERSAMPLE_STEP; int pos = oversampledAnalogValues[offset]; if (--pos<=0) { pos = OVERSAMPLE; } oversampledAnalogValues[offset] = pos; oversampledAnalogValues[offset+pos] = tempValue; return offset; } @Override public void startup() { if (listener instanceof StartupListener) { ((StartupListener)listener).startup(); } //Init all the moving averages to the right size rollingMovingAveragesAnalog = new MAvgRollerLong[MAX_SENSORS]; rollingMovingAveragesDigital = new MAvgRollerLong[MAX_SENSORS]; System.out.println("setup analogs "+Arrays.toString(hardware.analogInputs)); setupMovingAverages(rollingMovingAveragesAnalog, hardware.analogInputs); System.out.println("setup digitals "+Arrays.toString(hardware.digitalInputs)); setupMovingAverages(rollingMovingAveragesDigital, hardware.digitalInputs); lastDigitalValues = new int[MAX_CONNECTIONS]; lastAnalogValues = new int[MAX_CONNECTIONS]; oversampledAnalogValues = new int[MAX_CONNECTIONS*OVERSAMPLE_STEP]; oversampledAnalogCounts = new int[MAX_CONNECTIONS*OVERSAMPLE_STEP]; } @Override public void run() { processTimeEvents(listener); //TODO: replace with linked list of processors?, NOTE each one also needs a length bound so it does not starve the rest. int p = inputPipes.length; while (--p >= 0) { //TODO: this solution works but smells, a "process" lambda added to the Pipe may be a better solution? Still thinking.... Pipe<?> localPipe = inputPipes[p]; if (Pipe.isForSchema(localPipe, GroveResponseSchema.instance)) { consumeResponseMessage(listener, (Pipe<GroveResponseSchema>) localPipe); } else if (Pipe.isForSchema(localPipe, I2CResponseSchema.instance)) { consumeI2CMessage(listener, (Pipe<I2CResponseSchema>) localPipe); } else if (Pipe.isForSchema(localPipe, MessageSubscription.instance)) { consumePubSubMessage(listener, (Pipe<MessageSubscription>) localPipe); } else { logger.error("unrecognized pipe sent to listener of type {} ", Pipe.schemaName(localPipe)); } } } private StringBuilder workspace = new StringBuilder(); private PayloadReader payloadReader; private void consumePubSubMessage(Object listener, Pipe<MessageSubscription> p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); switch (msgIdx) { case MessageSubscription.MSG_PUBLISH_103: workspace.setLength(0); CharSequence topic = PipeReader.readUTF8(p, MessageSubscription.MSG_PUBLISH_103_FIELD_TOPIC_1, workspace); if (null==payloadReader) { payloadReader = new PayloadReader(p); } payloadReader.openHighLevelAPIField(MessageSubscription.MSG_PUBLISH_103_FIELD_PAYLOAD_3); // if (! payloadReader.markSupported() ) { // logger.warn("we need mark to be suppported for payloads in pubsub and http."); //TODO: need to implement mark, urgent. // } ((PubSubListener)listener).message(topic, payloadReader); break; case -1: requestShutdown(); PipeReader.releaseReadLock(p); return; default: throw new UnsupportedOperationException("Unknown id: "+msgIdx); } PipeReader.releaseReadLock(p); } } private void processTimeEvents(Object listener) { //if we do have a clock schedule if (0 != timeRate) { if (listener instanceof TimeListener) { long now = hardware.currentTimeMillis(); if (now >= timeTrigger) { ((TimeListener)listener).timeEvent(now); timeTrigger += timeRate; } } } } private void consumeRestMessage(Object listener2, Pipe<?> p) { if (null!= p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); //no need to check instance of since this was registered and we have a pipe ((RestListener)listener).restRequest(1, null, null); //done reading message off pipe PipeReader.releaseReadLock(p); } } } protected void consumeI2CMessage(Object listener, Pipe<I2CResponseSchema> p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); switch (msgIdx) { case I2CResponseSchema.MSG_RESPONSE_10: if (listener instanceof I2CListener) { int addr = PipeReader.readInt(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_ADDRESS_11); int register = PipeReader.readInt(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_REGISTER_14); int time = PipeReader.readInt(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_TIME_13); byte[] backing = PipeReader.readBytesBackingArray(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); int position = PipeReader.readBytesPosition(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); int length = PipeReader.readBytesLength(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); int mask = PipeReader.readBytesMask(p, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12); ((I2CListener)listener).i2cEvent(addr, register, time, backing, position, length, mask); } break; case -1: requestShutdown(); PipeReader.releaseReadLock(p); return; default: throw new UnsupportedOperationException("Unknown id: "+msgIdx); } //done reading message off pipe PipeReader.releaseReadLock(p); } } protected void consumeResponseMessage(Object listener, Pipe<GroveResponseSchema> p) { while (PipeReader.tryReadFragment(p)) { int msgIdx = PipeReader.getMsgIdx(p); switch (msgIdx) { case GroveResponseSchema.MSG_ANALOGSAMPLE_30: if (listener instanceof AnalogListener) { int connector = PipeReader.readInt(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_CONNECTOR_31); long time = PipeReader.readLong(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_TIME_11); int value = PipeReader.readInt(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_VALUE_32); //TODO: remove average. int average = PipeReader.readInt(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_AVERAGE_33); long duration = PipeReader.readLong(p, GroveResponseSchema.MSG_ANALOGSAMPLE_30_FIELD_PREVDURATION_35); int runningValue = findStableReading(value, connector); MAvgRollerLong.roll(rollingMovingAveragesAnalog[connector], runningValue); int mean = 0/*(int)MAvgRollerLong.mean(rollingMovingAveragesAnalog[connector])*/; ((AnalogListener)listener).analogEvent(connector, time, mean, runningValue); } break; case GroveResponseSchema.MSG_DIGITALSAMPLE_20: if (listener instanceof DigitalListener) { int connector = PipeReader.readInt(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_CONNECTOR_21); long time = PipeReader.readLong(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_TIME_11); int value = PipeReader.readInt(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_VALUE_22); long duration = PipeReader.readLong(p, GroveResponseSchema.MSG_DIGITALSAMPLE_20_FIELD_PREVDURATION_25); ((DigitalListener)listener).digitalEvent(connector, time, value); } break; case GroveResponseSchema.MSG_ENCODER_70: if (listener instanceof RotaryListener) { int connector = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_CONNECTOR_71); long time = PipeReader.readLong(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_TIME_11); int value = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_VALUE_72); int delta = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_DELTA_73); int speed = PipeReader.readInt(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_SPEED_74); long duration = PipeReader.readLong(p, GroveResponseSchema.MSG_ENCODER_70_FIELD_PREVDURATION_75); ((RotaryListener)listener).rotaryEvent(connector, time, value, delta, speed); } break; case -1: { requestShutdown(); PipeReader.releaseReadLock(p); return; } default: throw new UnsupportedOperationException("Unknown id: "+msgIdx); } //done reading message off pipe PipeReader.releaseReadLock(p); } } }
removed dead line of code
src/main/java/com/ociweb/pronghorn/iot/ReactiveListenerStage.java
removed dead line of code
<ide><path>rc/main/java/com/ociweb/pronghorn/iot/ReactiveListenerStage.java <ide> lastAnalogValues = new int[MAX_CONNECTIONS]; <ide> <ide> oversampledAnalogValues = new int[MAX_CONNECTIONS*OVERSAMPLE_STEP]; <del> oversampledAnalogCounts = new int[MAX_CONNECTIONS*OVERSAMPLE_STEP]; <ide> <ide> } <ide>
Java
apache-2.0
7b81d84c71642a325b1624c20c1f3724272f0f79
0
surya-janani/sakai,noondaysun/sakai,zqian/sakai,pushyamig/sakai,kwedoff1/sakai,udayg/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,kingmook/sakai,rodriguezdevera/sakai,Fudan-University/sakai,bkirschn/sakai,ktakacs/sakai,whumph/sakai,clhedrick/sakai,introp-software/sakai,bkirschn/sakai,Fudan-University/sakai,rodriguezdevera/sakai,pushyamig/sakai,colczr/sakai,conder/sakai,introp-software/sakai,kwedoff1/sakai,wfuedu/sakai,puramshetty/sakai,ouit0408/sakai,Fudan-University/sakai,surya-janani/sakai,liubo404/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,puramshetty/sakai,bkirschn/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,buckett/sakai-gitflow,Fudan-University/sakai,introp-software/sakai,ouit0408/sakai,rodriguezdevera/sakai,zqian/sakai,OpenCollabZA/sakai,zqian/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,zqian/sakai,wfuedu/sakai,ouit0408/sakai,willkara/sakai,OpenCollabZA/sakai,kwedoff1/sakai,buckett/sakai-gitflow,whumph/sakai,joserabal/sakai,conder/sakai,surya-janani/sakai,rodriguezdevera/sakai,puramshetty/sakai,kwedoff1/sakai,surya-janani/sakai,zqian/sakai,ktakacs/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,puramshetty/sakai,bzhouduke123/sakai,frasese/sakai,introp-software/sakai,conder/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,surya-janani/sakai,kingmook/sakai,clhedrick/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,zqian/sakai,rodriguezdevera/sakai,conder/sakai,kingmook/sakai,frasese/sakai,Fudan-University/sakai,clhedrick/sakai,clhedrick/sakai,ouit0408/sakai,whumph/sakai,noondaysun/sakai,noondaysun/sakai,zqian/sakai,pushyamig/sakai,lorenamgUMU/sakai,wfuedu/sakai,hackbuteer59/sakai,pushyamig/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,puramshetty/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,udayg/sakai,colczr/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,kwedoff1/sakai,ktakacs/sakai,clhedrick/sakai,ouit0408/sakai,liubo404/sakai,udayg/sakai,noondaysun/sakai,clhedrick/sakai,bkirschn/sakai,ktakacs/sakai,noondaysun/sakai,hackbuteer59/sakai,willkara/sakai,joserabal/sakai,liubo404/sakai,pushyamig/sakai,colczr/sakai,kingmook/sakai,bzhouduke123/sakai,liubo404/sakai,pushyamig/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,OpenCollabZA/sakai,udayg/sakai,ktakacs/sakai,liubo404/sakai,willkara/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,kingmook/sakai,udayg/sakai,conder/sakai,wfuedu/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,Fudan-University/sakai,kingmook/sakai,ouit0408/sakai,puramshetty/sakai,bzhouduke123/sakai,lorenamgUMU/sakai,kingmook/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,whumph/sakai,rodriguezdevera/sakai,whumph/sakai,colczr/sakai,Fudan-University/sakai,udayg/sakai,frasese/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,kwedoff1/sakai,wfuedu/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,bkirschn/sakai,joserabal/sakai,bkirschn/sakai,colczr/sakai,joserabal/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,colczr/sakai,willkara/sakai,hackbuteer59/sakai,wfuedu/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,udayg/sakai,willkara/sakai,colczr/sakai,zqian/sakai,ktakacs/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,noondaysun/sakai,udayg/sakai,whumph/sakai,lorenamgUMU/sakai,Fudan-University/sakai,buckett/sakai-gitflow,frasese/sakai,bzhouduke123/sakai,ktakacs/sakai,lorenamgUMU/sakai,joserabal/sakai,frasese/sakai,conder/sakai,ouit0408/sakai,liubo404/sakai,willkara/sakai,frasese/sakai,ktakacs/sakai,rodriguezdevera/sakai,bzhouduke123/sakai,wfuedu/sakai,willkara/sakai,OpenCollabZA/sakai,willkara/sakai,surya-janani/sakai,conder/sakai,whumph/sakai,joserabal/sakai,kwedoff1/sakai,wfuedu/sakai,kingmook/sakai,liubo404/sakai,introp-software/sakai,colczr/sakai,introp-software/sakai,joserabal/sakai,conder/sakai,OpenCollabZA/sakai,whumph/sakai,frasese/sakai,kwedoff1/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,bkirschn/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,joserabal/sakai,bkirschn/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import au.com.bytecode.opencsv.CSVReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.Collator; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.RuleBasedCollator; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessage; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentConstants; import org.sakaiproject.assignment.api.AssignmentContent; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentPeerAssessmentService; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItem; import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItemAccess; import org.sakaiproject.assignment.api.model.AssignmentModelAnswerItem; import org.sakaiproject.assignment.api.model.AssignmentNoteItem; import org.sakaiproject.assignment.api.model.AssignmentSupplementItemAttachment; import org.sakaiproject.assignment.api.model.AssignmentSupplementItemService; import org.sakaiproject.assignment.api.model.AssignmentSupplementItemWithAttachment; import org.sakaiproject.assignment.api.model.PeerAssessmentItem; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarEventEdit; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.contentreview.service.ContentReviewService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.Event; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.event.api.LearningResourceStoreService; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Actor; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Object; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Statement; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb.SAKAI_VERB; import org.sakaiproject.event.api.NotificationService; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.scoringservice.api.ScoringAgent; import org.sakaiproject.scoringservice.api.ScoringComponent; import org.sakaiproject.scoringservice.api.ScoringService; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.CategoryDefinition; import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException; import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException; import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.taggable.api.TaggingHelperInfo; import org.sakaiproject.taggable.api.TaggingManager; import org.sakaiproject.taggable.api.TaggingProvider; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); /** Our logger. */ private static Log M_log = LogFactory.getLog(AssignmentAction.class); private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades"; private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false); private static final Boolean allowPeerAssessment = ServerConfigurationService.getBoolean("assignment.usePeerAssessment", true); /** Is the review service available? */ //Peer Assessment private static final String NEW_ASSIGNMENT_USE_PEER_ASSESSMENT= "new_assignment_use_peer_assessment"; private static final String NEW_ASSIGNMENT_PEERPERIODMONTH = "new_assignment_peerperiodmonth"; private static final String NEW_ASSIGNMENT_PEERPERIODDAY = "new_assignment_peerperiodday"; private static final String NEW_ASSIGNMENT_PEERPERIODYEAR = "new_assignment_peerperiodyear"; private static final String NEW_ASSIGNMENT_PEERPERIODHOUR = "new_assignment_peerperiodhour"; private static final String NEW_ASSIGNMENT_PEERPERIODMIN = "new_assignment_peerperiodmin"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL= "new_assignment_peer_assessment_anon_eval"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS= "new_assignment_peer_assessment_student_view_review"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS= "new_assignment_peer_assessment_num_reviews"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS = "new_assignment_peer_assessment_instructions"; private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service"; private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO = "submit_papers_to"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE = "0"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD = "1"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION = "2"; // When to generate reports // although the service allows for a value of "1" --> Generate report immediately but overwrite until due date, // this doesn't make sense for assignment2. We limit the UI to 0 - Immediately // or 2 - On Due Date private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO = "report_gen_speed"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY = "0"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE = "2"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN = "s_paper_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET = "internet_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB = "journal_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION = "institution_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC = "exclude_biblio"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED = "exclude_quoted"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES = "exclude_smallmatches"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE = "exclude_type"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE = "exclude_value"; /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; private static final String ATTACHMENTS_FOR = "Assignment.attachments_for"; /** The property name associated with Groups that are Sections **/ private static final String GROUP_SECTION_PROPERTY = "sections_category"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** Additional calendar service */ private static final String ADDITIONAL_CALENDAR = "additonal_calendar"; /** The calendar tool */ private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit"; /** Additional calendar tool */ private static final String ADDITIONAL_CALENDAR_TOOL_READY = "additional_calendar_tool_ready"; /** The announcement tool */ private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; /** The submitter */ private static final String STATE_SUBMITTER = "Assignment.submitter"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** default sorting */ private static final String SORTED_BY_DEFAULT = "default"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** state sort submissuib by content review score **/ private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /*********************** Sort by user sort name *****************************************/ private static final String SORTED_USER_BY_SORTNAME = "sorted_user_by_sortname"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; private static final String GRADE_SUBMISSION_DONE = "grade_submission_done"; private static final String GRADE_SUBMISSION_SUBMIT = "grade_submission_submit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; /** * Is review service enabled? */ private static final String ENABLE_REVIEW_SERVICE = "enable_review_service"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // assignment order for default view private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order"; private static final String NEW_ASSIGNMENT_GROUP_SUBMIT = "new_assignment_group_submit"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; // visible date private static final String NEW_ASSIGNMENT_VISIBLEMONTH = "new_assignment_visiblemonth"; private static final String NEW_ASSIGNMENT_VISIBLEDAY = "new_assignment_visibleday"; private static final String NEW_ASSIGNMENT_VISIBLEYEAR = "new_assignment_visibleyear"; private static final String NEW_ASSIGNMENT_VISIBLEHOUR = "new_assignment_visiblehour"; private static final String NEW_ASSIGNMENT_VISIBLEMIN = "new_assignment_visiblemin"; private static final String NEW_ASSIGNMENT_VISIBLETOGGLE = "new_assignment_visibletoggle"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_CATEGORY = "new_assignment_category"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE = "new_assignment_check_hide_due_date"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; private static final String VIEW_SUBMISSION_GROUP = "view_submission_group"; private static final String VIEW_SUBMISSION_ORIGINAL_GROUP = "view_submission_original_group"; private static final String NEW_ASSIGNMENT_PAST_CLOSE_DATE = "new_assignment_past_close_date"; /*************************** assignment model answer attributes *************************/ private static final String NEW_ASSIGNMENT_MODEL_ANSWER = "new_assignment_model_answer"; private static final String NEW_ASSIGNMENT_MODEL_ANSWER_TEXT = "new_assignment_model_answer_text"; private static final String NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT = "new_assignment_model_answer_show_to_student"; private static final String NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT = "new_assignment_model_answer_attachment"; /**************************** assignment year range *************************/ private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from"; private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE_PRIVATE = "Assignment.mode_student_view_grade_private"; /** The student view of a group submission error (user is in multiple groups */ private static final String MODE_STUDENT_VIEW_GROUP_ERROR = "Assignment.mode_student_view_group_error"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to reorder assignments */ private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The instructor view of download all file */ private static final String MODE_INSTRUCTOR_DOWNLOAD_ALL = "downloadAll"; /** The instructor view of uploading all from archive file */ private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll"; /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** The option view */ private static final String MODE_OPTIONS= "options"; // set in velocity template /** Review Edit page for students */ private static final String MODE_STUDENT_REVIEW_EDIT= "Assignment.mode_student_review_edit"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of showing a group assignment grouping error */ private static final String TEMPLATE_STUDENT_VIEW_GROUP_ERROR = "_student_view_group_error"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to reorder the default assignments */ private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The instructor view to upload all information from archive file */ private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll"; /** The student view to edit reviews **/ private static final String TEMPLATE_STUDENT_REVIEW_EDIT = "_student_review_edit"; /** The options page */ private static final String TEMPLATE_OPTIONS = "_options"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The configuration choice of showing or hiding the number of submissions column */ private static final String SHOW_NUMBER_SUBMISSION_COLUMN = "showNumSubmissionColumn"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** the items for storing the comments and grades for peer assessment **/ private static final String PEER_ASSESSMENT_ITEMS = "peer_assessment_items"; private static final String PEER_ASSESSMENT_ASSESSOR_ID = "peer_assessment_assesor_id"; private static final String PEER_ASSESSMENT_REMOVED_STATUS = "peer_assessment_removed_status"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; // name for release grade notification private static final String ASSIGNMENT_RELEASEGRADE_NOTIFICATION = "assignment.releasegrade.notification"; private static final String ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION = "assignment.releasereturn.notification"; /****************************** Upload all screen ***************************/ private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text"; private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment"; private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile"; private static final String UPLOAD_ALL_GRADEFILE_FORMAT = "upload_all_gradefile_format"; private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments"; private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text"; private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment"; private static final String UPLOAD_ALL_WITHOUT_FOLDERS = "upload_all_without_folders"; private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades"; // this is to track whether the site has multiple assignment, hence if true, show the reorder link private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments"; // view all or grouped submission list private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option"; /************************* SAK-17606 - Upload all grades.csv columns ********************/ private static final int IDX_GRADES_CSV_EID = 1; private static final int IDX_GRADES_CSV_GRADE = 5; // search string for submission list private static final String VIEW_SUBMISSION_SEARCH = "view_submission_search"; private ContentHostingService m_contentHostingService = null; private EventTrackingService m_eventTrackingService = null; private NotificationService m_notificationService = null; private SecurityService m_securityService = null; /********************** Supplement item ************************/ private AssignmentSupplementItemService m_assignmentSupplementItemService = null; /******** Model Answer ************/ private static final String MODELANSWER = "modelAnswer"; private static final String MODELANSWER_TEXT = "modelAnswer.text"; private static final String MODELANSWER_SHOWTO = "modelAnswer.showTo"; private static final String MODELANSWER_ATTACHMENTS = "modelanswer_attachments"; private static final String MODELANSWER_TO_DELETE = "modelanswer.toDelete"; /******** Note ***********/ private static final String NOTE = "note"; private static final String NOTE_TEXT = "note.text"; private static final String NOTE_SHAREWITH = "note.shareWith"; private static final String NOTE_TO_DELETE = "note.toDelete"; /******** AllPurpose *******/ private static final String ALLPURPOSE = "allPurpose"; private static final String ALLPURPOSE_TITLE = "allPurpose.title"; private static final String ALLPURPOSE_TEXT = "allPurpose.text"; private static final String ALLPURPOSE_HIDE = "allPurpose.hide"; private static final String ALLPURPOSE_SHOW_FROM = "allPurpose.show.from"; private static final String ALLPURPOSE_SHOW_TO = "allPurpose.show.to"; private static final String ALLPURPOSE_RELEASE_DATE = "allPurpose.releaseDate"; private static final String ALLPURPOSE_RETRACT_DATE= "allPurpose.retractDate"; private static final String ALLPURPOSE_ACCESS = "allPurpose.access"; private static final String ALLPURPOSE_ATTACHMENTS = "allPurpose_attachments"; private static final String ALLPURPOSE_RELEASE_YEAR = "allPurpose_releaseYear"; private static final String ALLPURPOSE_RELEASE_MONTH = "allPurpose_releaseMonth"; private static final String ALLPURPOSE_RELEASE_DAY = "allPurpose_releaseDay"; private static final String ALLPURPOSE_RELEASE_HOUR = "allPurpose_releaseHour"; private static final String ALLPURPOSE_RELEASE_MIN = "allPurpose_releaseMin"; private static final String ALLPURPOSE_RETRACT_YEAR = "allPurpose_retractYear"; private static final String ALLPURPOSE_RETRACT_MONTH = "allPurpose_retractMonth"; private static final String ALLPURPOSE_RETRACT_DAY = "allPurpose_retractDay"; private static final String ALLPURPOSE_RETRACT_HOUR = "allPurpose_retractHour"; private static final String ALLPURPOSE_RETRACT_MIN = "allPurpose_retractMin"; private static final String ALLPURPOSE_TO_DELETE = "allPurpose.toDelete"; private static final String SHOW_ALLOW_RESUBMISSION = "show_allow_resubmission"; private static final String SHOW_SEND_FEEDBACK = "show_send_feedback"; private static final String RETURNED_FEEDBACK = "feedback_returned_to_selected_users"; private static final String OW_FEEDBACK = "feedback_overwritten"; private static final String SAVED_FEEDBACK = "feedback_saved"; private static final int INPUT_BUFFER_SIZE = 102400; private static final String INVOKE = "invoke_via"; private static final String INVOKE_BY_LINK = "link"; private static final String INVOKE_BY_PORTAL = "portal"; private static final String SUBMISSIONS_SEARCH_ONLY = "submissions_search_only"; /*************** search related *******************/ private static final String STATE_SEARCH = "state_search"; private static final String FORM_SEARCH = "form_search"; private static final String STATE_DOWNLOAD_URL = "state_download_url"; /** To know if grade_submission go from view_students_assignment view or not **/ private static final String FROM_VIEW = "from_view"; /** SAK-17606 - Property for whether an assignment user anonymous grading (user settable). */ private static final String NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING = "new_assignment_check_anonymous_grading"; private AssignmentPeerAssessmentService assignmentPeerAssessmentService; public void setAssignmentPeerAssessmentService(AssignmentPeerAssessmentService assignmentPeerAssessmentService){ this.assignmentPeerAssessmentService = assignmentPeerAssessmentService; } public String buildLinkedPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state){ state.setAttribute(INVOKE, INVOKE_BY_LINK); return buildMainPanelContext(portlet, context, data, state); } /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = null; context.put("action", "AssignmentAction"); context.put("tlang", rb); context.put("dateFormat", getDateFormatString()); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? boolean allowUpdateSite = SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("allowUpdateSite", Boolean.valueOf(allowUpdateSite)); //group related settings context.put("siteAccess", Assignment.AssignmentAccess.SITE); context.put("groupAccess", Assignment.AssignmentAccess.GROUPED); // allow all.groups? boolean allowAllGroups = AssignmentService.allowAllGroups(contextString); context.put("allowAllGroups", Boolean.valueOf(allowAllGroups)); //Is the review service allowed? Site s = null; try { s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (IdUnusedException iue) { M_log.warn(this + ":buildMainPanelContext: Site not found!" + iue.getMessage()); } // Check whether content review service is enabled, present and enabled for this site getContentReviewService(); context.put("allowReviewService", allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s)); if (allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s)) { //put the review service stings in context String reviewServiceName = contentReviewService.getServiceName(); String reviewServiceTitle = rb.getFormattedMessage("review.title", new Object[]{reviewServiceName}); String reviewServiceUse = rb.getFormattedMessage("review.use", new Object[]{reviewServiceName}); String reviewServiceNonElectronic1 = rb.getFormattedMessage("review.switch.ne.1", reviewServiceName); String reviewServiceNonElectronic2 = rb.getFormattedMessage("review.switch.ne.2", reviewServiceName); context.put("reviewServiceName", reviewServiceName); context.put("reviewServiceTitle", reviewServiceTitle); context.put("reviewServiceUse", reviewServiceUse); context.put("reviewIndicator", rb.getFormattedMessage("review.contentReviewIndicator", new Object[]{reviewServiceName})); context.put("reviewSwitchNe1", reviewServiceNonElectronic1); context.put("reviewSwitchNe2", reviewServiceNonElectronic2); } //Peer Assessment context.put("allowPeerAssessment", allowPeerAssessment); if(allowPeerAssessment){ context.put("peerAssessmentName", rb.getFormattedMessage("peerAssessmentName")); context.put("peerAssessmentUse", rb.getFormattedMessage("peerAssessmentUse")); } // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); // the grade type table context.put("gradeTypeTable", gradeTypeTable()); // set the allowSubmitByInstructor option context.put("allowSubmitByInstructor", AssignmentService.getAllowSubmitByInstructor()); // get the system setting for whether to show the Option tool link or not context.put("enableViewOption", ServerConfigurationService.getBoolean("assignment.enableViewOption", true)); String mode = (String) state.getAttribute(STATE_MODE); if (!MODE_LIST_ASSIGNMENTS.equals(mode)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (MODE_LIST_ASSIGNMENTS.equals(mode)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_ASSIGNMENT.equals(mode)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_GROUP_ERROR.equals(mode)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing group submission error template = build_student_view_group_error_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION.equals(mode)) { context.put("site",s); // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode)) { context.put("site",s); // disable auto-updates while leaving the list view justDelivered(state); if(MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode)){ context.put("privateView", true); } // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)) { context.put("site",s); if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode)) { context.put("site",s); // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode)) { context.put("site",s); if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_DOWNLOAD_ALL.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_download_upload_all(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_UPLOAD_ALL.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_download_upload_all(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode)) { context.put("site",s); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_reorder_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_OPTIONS)) { if (allowUpdateSite) { // build the options page template = build_options_context(portlet, context, data, state); } } else if (mode.equals(MODE_STUDENT_REVIEW_EDIT)) { template = build_student_review_edit_context(portlet, context, data, state); } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } // this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null) { context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS)); } return template; } // buildNormalContext /** * local function for getting assignment object * @param assignmentId * @param callingFunctionName * @param state * @return */ private Assignment getAssignment(String assignmentId, String callingFunctionName, SessionState state) { Assignment rv = null; try { Session session = SessionManager.getCurrentSession(); SecurityAdvisor secAdv = pushSecurityAdvisor(session, "assignment.security.advisor", false); SecurityAdvisor contentAdvisor = pushSecurityAdvisor(session, "assignment.content.security.advisor", false); rv = AssignmentService.getAssignment(assignmentId); m_securityService.popAdvisor(contentAdvisor); m_securityService.popAdvisor(secAdv); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentId})); } return rv; } /** * local function for getting assignment submission object * @param submissionId * @param callingFunctionName * @param state * @return */ private AssignmentSubmission getSubmission(String submissionId, String callingFunctionName, SessionState state) { AssignmentSubmission rv = null; try { Session session = SessionManager.getCurrentSession(); SecurityAdvisor secAdv = pushSecurityAdvisor(session, "assignment.grade.security.advisor", false); rv = AssignmentService.getSubmission(submissionId); m_securityService.popAdvisor(secAdv); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission", new Object[]{submissionId})); } return rv; } /** * local function for editing assignment submission object * @param submissionId * @param callingFunctionName * @param state * @return */ private AssignmentSubmissionEdit editSubmission(String submissionId, String callingFunctionName, SessionState state) { AssignmentSubmissionEdit rv = null; try { rv = AssignmentService.editSubmission(submissionId); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("youarenot_editSubmission", new Object[]{submissionId})); } catch (InUseException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("somelsis_submission", new Object[]{submissionId})); } return rv; } /** * local function for editing assignment object * @param assignmentId * @param callingFunctionName * @param state * @param allowToAdd * @return */ private AssignmentEdit editAssignment(String assignmentId, String callingFunctionName, SessionState state, boolean allowAdd) { AssignmentEdit rv = null; if (assignmentId.length() == 0 && allowAdd) { // create a new assignment try { rv = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot_addAssignment")); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } } else { try { rv = AssignmentService.editAssignment(assignmentId); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{assignmentId})); } catch (InUseException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("somelsis_assignment", new Object[]{assignmentId})); } } // if-else return rv; } /** * local function for getting assignment submission object * @param submissionId * @param callingFunctionName * @param state * @return */ private AssignmentSubmission getSubmission(String assignmentRef, User user, String callingFunctionName, SessionState state) { AssignmentSubmission rv = null; try { rv = AssignmentService.getSubmission(assignmentRef, user); } catch (IdUnusedException e) { M_log.warn(this + ":build_student_view_submission " + e.getMessage() + " " + assignmentRef + " " + user.getId()); if (state != null) addAlert(state, rb.getFormattedMessage("cannotfin_submission_1", new Object[]{assignmentRef, user.getId()})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentRef + " " + user.getId()); if (state != null) addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission_1", new Object[]{assignmentRef, user.getId()})); } return rv; } /** * local function for getting assignment submission object for a group id (or is that submitter id instead of group id) */ private AssignmentSubmission getSubmission(String assignmentRef, String group_id, String callingFunctionName, SessionState state) { AssignmentSubmission rv = null; try { rv = AssignmentService.getSubmission(assignmentRef, group_id); } catch (IdUnusedException e) { M_log.warn(this + ":build_student_view_submission " + e.getMessage() + " " + assignmentRef + " " + group_id); if (state != null) addAlert(state, rb.getFormattedMessage("cannotfin_submission_1", new Object[]{assignmentRef, group_id})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentRef + " " + group_id); if (state != null) addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission_1", new Object[]{assignmentRef, group_id})); } return rv; } /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String invokedByStatus = (String) state.getAttribute(INVOKE); if(invokedByStatus!=null){ if(invokedByStatus.equalsIgnoreCase(INVOKE_BY_LINK)){ context.put("linkInvoked", Boolean.valueOf(true)); }else{ context.put("linkInvoked", Boolean.valueOf(false)); } }else{ context.put("linkInvoked", Boolean.valueOf(false)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); M_log.debug(this + " BUILD SUBMISSION FORM WITH USER " + user.getId() + " NAME " + user.getDisplayName()); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = getAssignment(currentAssignmentReference, "build_student_view_submission_context", state); AssignmentSubmission s = null; boolean newAttachments = false; if (assignment != null) { context.put("assignment", assignment); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment))); // SAK-26322 --bbailla2 if (assignment.getContent().getAllowReviewService()) { context.put("plagiarismNote", rb.getFormattedMessage("gen.yoursubwill", contentReviewService.getServiceName())); } if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } User submitter = (User)state.getAttribute("student"); if (submitter == null) { submitter = user; } s = getSubmission(assignment.getReference(), submitter, "build_student_view_submission_context", state); List currentAttachments = (List) state.getAttribute(ATTACHMENTS); if (s != null) { M_log.debug(this + " BUILD SUBMISSION FORM HAS SUBMISSION FOR USER " + s.getSubmitterId() + " NAME " + user.getDisplayName()); context.put("submission", s); if (assignment.isGroup()) { context.put("selectedGroup", s.getSubmitterId()); context.put("originalGroup", s.getSubmitterId()); } setScoringAgentProperties(context, assignment, s, false); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if (assignment.isGroup()) { context.put("submitterId", s.getSubmitterId() ); String _grade_override= s.getGradeForUser(UserDirectoryService.getCurrentUser().getId()); if (_grade_override != null) { if (assignment.getContext() != null && assignment.getContent().getTypeOfGrade() == 3) { context.put("override", displayGrade(state, _grade_override)); } else { context.put("override", _grade_override); } } } // figure out if attachments have been modified // the attachments from the previous submission List submittedAttachments = s.getSubmittedAttachments(); newAttachments = areAttachmentsNew(submittedAttachments, currentAttachments); } else { // There is no previous submission, attachments are modified if anything has been uploaded newAttachments = currentAttachments != null && !currentAttachments.isEmpty(); } // put the resubmit information into context assignment_resubmission_option_into_context(context, state); if (assignment.isGroup()) { context.put("assignmentService", AssignmentService.getInstance()); // get current site Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", st); groups = getGroupsWithUser(user.getId(), assignment, st); checkForGroupsInMultipleGroups(assignment, groups, state, rb.getString("group.user.multiple.warning")); context.put("group_size", String.valueOf(groups.size())); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); if (state.getAttribute(VIEW_SUBMISSION_GROUP) != null) { context.put("selectedGroup", (String)state.getAttribute(VIEW_SUBMISSION_GROUP)); if (M_log.isDebugEnabled()) M_log.debug(this + ":buildStudentViewSubmissionContext: VIEW_SUBMISSION_GROUP " + (String)state.getAttribute(VIEW_SUBMISSION_GROUP)); } if (state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP) != null) { context.put("originalGroup", (String)state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP)); if (M_log.isDebugEnabled()) M_log.debug(this + ":buildStudentViewSubmissionContext: VIEW_SUBMISSION_ORIGINAL_GROUP " + (String)state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP)); } } catch (IdUnusedException iue) { M_log.warn(this + ":buildStudentViewSubmissionContext: Site not found!" + iue.getMessage()); } } // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, s); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); context.put("attachments", stripInvisibleAttachments(state.getAttribute(ATTACHMENTS))); context.put("new_attachments", newAttachments); context.put("userDirectoryService", UserDirectoryService.getInstance()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); // SAK-21525 - Groups were not being queried for authz boolean allowSubmit = AssignmentService.allowAddSubmissionCheckGroups((String) state.getAttribute(STATE_CONTEXT_STRING),assignment); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", Boolean.valueOf(allowSubmit)); // put supplement item into context supplementItemIntoContext(state, context, assignment, s); initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); // if the instructor is allowed to submit assignment on behalf of student, add the student list to the page User student = (User) state.getAttribute("student") ; if (AssignmentService.getAllowSubmitByInstructor() && student != null) { List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, currentAssignmentReference, contextString); if (submitterIds != null && !submitterIds.isEmpty() && submitterIds.contains(student.getId())) { // we want to come back to the instructor view page state.setAttribute(FROM_VIEW, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); context.put("student",student); } } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * Determines if there are new attachments * @return true if currentAttachments is not empty and isn't equal to oldAttachments */ private boolean areAttachmentsNew(List oldAttachments, List currentAttachments) { if (currentAttachments == null || currentAttachments.isEmpty()) { //there are no current attachments return false; } if (oldAttachments == null || oldAttachments.isEmpty()) { //there are no old attachments (and there are new ones) return true; } Set<String> ids1 = getIdsFromReferences(oldAttachments); Set<String> ids2 = getIdsFromReferences(currentAttachments); //.equals on Sets of Strings will compare .equals on the contained Strings return !ids1.equals(ids2); } /** * Gets ids from a list of Reference objects. If the List contains any non-reference objects, they are skipped */ private Set<String> getIdsFromReferences(List references) { Set<String> ids = new HashSet<String>(); for (Object reference : references) { if (reference instanceof Reference) { Reference casted = (Reference) reference; ids.add(casted.getId()); } } return ids; } /** * Returns a clone of the passed in List of attachments minus any attachments that should not be displayed in the UI */ private List stripInvisibleAttachments(Object attachments) { List stripped = new ArrayList(); if (attachments == null || !(attachments instanceof List)) { return stripped; } Iterator itAttachments = ((List) attachments).iterator(); while (itAttachments.hasNext()) { Object next = itAttachments.next(); if (next instanceof Reference) { Reference attachment = (Reference) next; // inline submissions should not show up in the UI's lists of attachments if (!"true".equals(attachment.getProperties().getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { stripped.add(attachment); } } } return stripped; } /** * build the student view of showing a group assignment error with eligible groups * a user can only be in one eligible group * * @param portlet * @param context * @param data * @param state * @return the student error message for this context */ protected String build_student_view_group_error_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); if (M_log.isDebugEnabled()) M_log.debug(this + " BUILD SUBMISSION GROUP ERROR WITH USER " + user.getId() + " NAME " + user.getDisplayName()); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = getAssignment(currentAssignmentReference, "build_student_view_submission_context", state); if (assignment != null) { context.put("assignment", assignment); if (assignment.isGroup()) { context.put("assignmentService", AssignmentService.getInstance()); Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", st); groups = getGroupsWithUser(user.getId(), assignment, st); //checkForGroupsInMultipleGroups(assignment, groups, state, rb.getString("group.user.multiple.warning")); context.put("group_size", String.valueOf(groups.size())); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); } catch (IdUnusedException iue) { M_log.warn(this + ":buildStudentViewSubmissionContext: Site not found!" + iue.getMessage()); } } } TaggingManager taggingManager = (TaggingManager) ComponentManager.get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("userDirectoryService", UserDirectoryService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GROUP_ERROR; } // build_student_view_group_error_context /** * Get groups containing a user for this assignment (remove SECTION groups) * @param member * @param assignment * @param site * @return collection of groups with the given member */ private Collection<Group> getGroupsWithUser(String member, Assignment assignment, Site site) { Collection<Group> groups = new ArrayList<Group>(); if (assignment.getAccess().equals(Assignment.AssignmentAccess.SITE)) { Iterator<Group> _groups = site.getGroupsWithMember(member).iterator(); while (_groups.hasNext()) { Group _g = _groups.next(); if (_g.getMember(member) != null)// && _g.getProperties().get(GROUP_SECTION_PROPERTY) == null) groups.add(_g); } } else { Iterator<String> _it = assignment.getGroups().iterator(); while (_it.hasNext()) { String _gRef = _it.next(); Group _g = site.getGroup(_gRef); if (_g != null && _g.getMember(member) != null)// && _g.getProperties().get(GROUP_SECTION_PROPERTY) == null) groups.add(_g); } } return groups; } /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); String invokedByStatus = (String) state.getAttribute(INVOKE); if(invokedByStatus!=null){ if(invokedByStatus.equalsIgnoreCase(INVOKE_BY_LINK)){ context.put("linkInvoked", Boolean.valueOf(true)); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); }else{ context.put("linkInvoked", Boolean.valueOf(false)); } }else{ context.put("linkInvoked", Boolean.valueOf(false)); } context.put("view", MODE_LIST_ASSIGNMENTS); // get user information User user = (User) state.getAttribute(STATE_USER); String submitterId = (String) state.getAttribute(STATE_SUBMITTER); User submitter = user; if (submitterId != null) { try { submitter = UserDirectoryService.getUser(submitterId); } catch (UserNotDefinedException ex) { M_log.warn(this + ":build_student_view_submission cannot find user with id " + submitterId + " " + ex.getMessage()); } } context.put("user_name", submitter.getDisplayName()); context.put("user_id", submitter.getDisplayId()); if (StringUtils.trimToNull(user.getEmail()) != null) context.put("user_email", user.getEmail()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { M_log.warn(this + ":buildStudentViewSubmission " + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment currentAssignment = getAssignment(currentAssignmentReference, "build_student_view_submission_confirmation_context", state); if (currentAssignment != null) { context.put("assignment", currentAssignment); context.put("assignment_title", currentAssignment.getTitle()); // differenciate submission type int submissionType = currentAssignment.getContent().getTypeOfSubmission(); if (submissionType == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION || submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION) { context.put("attachmentSubmissionOnly", Boolean.TRUE); } else { context.put("attachmentSubmissionOnly", Boolean.FALSE); } if (submissionType == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION) { context.put("textSubmissionOnly", Boolean.TRUE); } else { context.put("textSubmissionOnly", Boolean.FALSE); } context.put("submissionType", submissionType); AssignmentSubmission s = getSubmission(currentAssignmentReference, submitter, "build_student_view_submission_confirmation_context",state); if (s != null) { context.put("submission", s); context.put("submitted", Boolean.valueOf(s.getSubmitted())); context.put("submission_id", s.getId()); if (s.getTimeSubmitted() != null) { context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); } List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getVisibleSubmittedAttachments()); } context.put("submit_text", StringUtils.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } state.removeAttribute(STATE_SUBMITTER); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment * * @param portlet * @param context * @param data * @param state * @return */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); String aReference = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); User user = (User) state.getAttribute(STATE_USER); AssignmentSubmission submission = null; Assignment assignment = getAssignment(aReference, "build_student_view_assignment_context", state); if (assignment != null) { context.put("assignment", assignment); // put creator information into context putCreatorIntoContext(context, assignment); submission = getSubmission(aReference, user, "build_student_view_assignment_context", state); context.put("submission", submission); if (assignment.isGroup()) { Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", st); groups = getGroupsWithUser(user.getId(), assignment, st); context.put("group_size", String.valueOf(groups.size())); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); checkForGroupsInMultipleGroups(assignment, groups, state, rb.getString("group.user.multiple.warning")); } catch (IdUnusedException iue) { M_log.warn(this + ":buildStudentViewAssignmentContext: Site not found!" + iue.getMessage()); } } // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, submission); // put resubmit information into context assignment_resubmission_option_into_context(context, state); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); // put supplement item into context supplementItemIntoContext(state, context, assignment, submission); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission * * @param portlet * @param context * @param data * @param state * @return */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = getAssignment(aReference, "build_student_preview_submission_context", state); if (assignment != null) { context.put("assignment", assignment); AssignmentSubmission submission = getSubmission(aReference, user, "build_student_preview_submission_context", state); context.put("submission", submission); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit((String) state.getAttribute(STATE_CONTEXT_STRING), assignment))); setScoringAgentProperties(context, assignment, submission, false); // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, submission); // put the resubmit information into context assignment_resubmission_option_into_context(context, state); if(state.getAttribute(SHOW_SEND_FEEDBACK) != null) { context.put("showSendFeedback", Boolean.TRUE); state.removeAttribute(SHOW_SEND_FEEDBACK); } if (state.getAttribute(SAVED_FEEDBACK) != null) { context.put("savedFeedback", Boolean.TRUE); state.removeAttribute(SAVED_FEEDBACK); } if (state.getAttribute(OW_FEEDBACK) != null) { context.put("overwriteFeedback", Boolean.TRUE); state.removeAttribute(OW_FEEDBACK); } if (state.getAttribute(RETURNED_FEEDBACK) != null) { context.put("returnedFeedback", Boolean.TRUE); state.removeAttribute(RETURNED_FEEDBACK); } } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); context.put("attachments", stripInvisibleAttachments(state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS))); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context private void canViewAssignmentIntoContext(Context context, Assignment assignment, AssignmentSubmission submission) { boolean canViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, submission); context.put("allowViewModelAnswer", Boolean.valueOf(canViewModelAnswer)); if (canViewModelAnswer) { context.put("modelAnswer", m_assignmentSupplementItemService.getModelAnswer(assignment.getId())); } } /** * Look up a security advisor from the session with the given key, and then push it on the security service stack. * @param session * @param sessionKey String key used to look up a SecurityAdvisor stored in the session object * @param removeFromSession boolean flag indicating if the value should be removed from the session once retrieved * @return */ private SecurityAdvisor pushSecurityAdvisor(Session session, String sessionKey, boolean removeFromSession) { SecurityAdvisor asgnAdvisor = (SecurityAdvisor)session.getAttribute(sessionKey); if (asgnAdvisor != null) { m_securityService.pushAdvisor(asgnAdvisor); if (removeFromSession) session.removeAttribute(sessionKey); } return asgnAdvisor; } /** * If necessary, put a "decoratedUrlMap" into the context * @param session * @param context Context object that will have a "decoratedUrlMap" object put into it * @param removeFromSession boolean flag indicating if the value should be removed from the session once retrieved */ private void addDecoUrlMapToContext(Session session, Context context, boolean removeFromSession) { SecurityAdvisor contentAdvisor = (SecurityAdvisor)session.getAttribute("assignment.content.security.advisor"); String decoratedContentWrapper = (String)session.getAttribute("assignment.content.decoration.wrapper"); String[] contentRefs = (String[])session.getAttribute("assignment.content.decoration.wrapper.refs"); if (removeFromSession) { session.removeAttribute("assignment.content.decoration.wrapper"); session.removeAttribute("assignment.content.decoration.wrapper.refs"); } if (contentAdvisor != null && contentRefs != null) { m_securityService.pushAdvisor(contentAdvisor); Map<String, String> urlMap = new HashMap<String, String>(); for (String refStr:contentRefs) { Reference ref = EntityManager.newReference(refStr); String url = ref.getUrl(); urlMap.put(url, url.replaceFirst("access/content", "access/" + decoratedContentWrapper + "/content")); } context.put("decoratedUrlMap", urlMap); m_securityService.popAdvisor(contentAdvisor); } } /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); Session session = SessionManager.getCurrentSession(); addDecoUrlMapToContext(session, context, false); SecurityAdvisor asgnAdvisor = pushSecurityAdvisor(session, "assignment.security.advisor", false); AssignmentSubmission submission = null; Assignment assignment = null; String submissionId = (String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID); submission = getSubmission(submissionId, "build_student_view_grade_context", state); if (submission != null) { assignment = submission.getAssignment(); context.put("assignment", assignment); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } context.put("submission", submission); if (assignment.isGroup()) { String _grade_override= submission.getGradeForUser(UserDirectoryService.getCurrentUser().getId()); if (_grade_override != null) { if (assignment.getContext() != null && assignment.getContent().getTypeOfGrade() == 3) context.put("override", displayGrade(state, _grade_override)); else context.put("override", _grade_override); } } // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, submission); // scoring agent integration setScoringAgentProperties(context, assignment, submission, false); //peer review if(assignment.getAllowPeerAssessment() && assignment.getPeerAssessmentStudentViewReviews() && assignment.isPeerAssessmentClosed()){ List<PeerAssessmentItem> reviews = assignmentPeerAssessmentService.getPeerAssessmentItems(submission.getId()); if(reviews != null){ List<PeerAssessmentItem> completedReviews = new ArrayList<PeerAssessmentItem>(); for(PeerAssessmentItem review : reviews){ if(!review.isRemoved() && (review.getScore() != null || (review.getComment() != null && !"".equals(review.getComment().trim())))){ //only show peer reviews that have either a score or a comment saved if(assignment.getPeerAssessmentAnonEval()){ //annonymous eval review.setAssessorDisplayName(rb.getFormattedMessage("gen.reviewer.countReview", completedReviews.size() + 1)); }else{ //need to set the assessor's display name try { review.setAssessorDisplayName(UserDirectoryService.getUser(review.getAssessorUserId()).getDisplayName()); } catch (UserNotDefinedException e) { //reviewer doesn't exist or userId is wrong M_log.error(e.getMessage(), e); //set a default one: review.setAssessorDisplayName(rb.getFormattedMessage("gen.reviewer.countReview", completedReviews.size() + 1)); } } completedReviews.add(review); } } if(completedReviews.size() > 0){ context.put("peerReviews", completedReviews); } } } } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && submission != null) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getItemHelperInfo( assignmentActivityProducer.getItem( submission, UserDirectoryService.getCurrentUser() .getId()).getReference()); if (helper != null) { itemHelpers.add(helper); } } addItem(context, submission, UserDirectoryService.getCurrentUser().getId()); addActivity(context, submission.getAssignment()); context.put("itemHelpers", itemHelpers); context.put("taggable", Boolean.valueOf(true)); } // put supplement item into context supplementItemIntoContext(state, context, assignment, submission); if (asgnAdvisor != null) { m_securityService.popAdvisor(asgnAdvisor); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); context.put("providers", taggingManager.getProviders()); context.put("taggable", Boolean.valueOf(true)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("AuthzGroupService", AuthzGroupService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", Long.valueOf(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (SORTED_BY_GROUP_TITLE.equals(sortedBy) || SORTED_BY_GROUP_DESCRIPTION.equals(sortedBy)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null && // this is not very elegant, but the view cannot be 'lisofass2' here. !state.getAttribute(STATE_SELECTED_VIEW).equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } List assignments = prepPage(state); context.put("assignments", assignments.iterator()); // allow add assignment? Map<String, List<PeerAssessmentItem>> peerAssessmentItemsMap = new HashMap<String, List<PeerAssessmentItem>>(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if(!allowAddAssignment){ //this is the same requirement for displaying the assignment link for students //now lets create a map for peer reviews for each eligible assignment for(Assignment assignment : (List<Assignment>) assignments){ if(assignment.getAllowPeerAssessment() && (assignment.isPeerAssessmentOpen() || assignment.isPeerAssessmentClosed())){ peerAssessmentItemsMap.put(assignment.getId(), assignmentPeerAssessmentService.getPeerAssessmentItems(assignment.getId(), UserDirectoryService.getCurrentUser().getId())); } } } context.put("peerAssessmentItemsMap", peerAssessmentItemsMap); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.valueOf(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = getAllGroupsInSite(contextString); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { M_log.warn(this + ":build_list_assignments_context " + ignore.getMessage()); M_log.warn(this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", Boolean.valueOf(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // the type int for non-electronic submission context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)); // show or hide the number of submission column context.put(SHOW_NUMBER_SUBMISSION_COLUMN, state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context private HashSet<String> getSubmittersIdSet(List submissions) { HashSet<String> rv = new HashSet<String>(); for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();) { rv.add(((AssignmentSubmission) iSubmissions.next()).getSubmitterId()); } return rv; } private HashSet<String> getAllowAddSubmissionUsersIdSet(List users) { HashSet<String> rv = new HashSet<String>(); for (Iterator iUsers=users.iterator(); iUsers.hasNext();) { rv.add(((User) iUsers.next()).getId()); } return rv; } /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // If the user adds the schedule or alternate calendar tool after using the assignment tool, // we need to remove these state attributes so they are re-initialized with the updated // availability of the tools. state.removeAttribute(CALENDAR_TOOL_EXIST); state.removeAttribute(ADDITIONAL_CALENDAR_TOOL_READY); initState(state, portlet, (JetspeedRunData)data); // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { Assignment a = getAssignment(assignmentId, "build_instructor_new_edit_assignment_context", state); if (a != null) { context.put("assignment", a); if (a.isGroup()) { Collection<String> _dupUsers = usersInMultipleGroups(a); if (_dupUsers.size() > 0) context.put("multipleGroupUsers", _dupUsers); } } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); context.put("group_submissions_enabled", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.group.submission.enabled", true))); context.put("visible_date_enabled", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_UsePeerAssessment", NEW_ASSIGNMENT_USE_PEER_ASSESSMENT); context.put("name_PeerAssessmentAnonEval", NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL); context.put("name_PeerAssessmentStudentViewReviews", NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS); context.put("name_PeerAssessmentNumReviews", NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS); context.put("name_PeerAssessmentInstructions", NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE); context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO", NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY", NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE", NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE); context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_order", NEW_ASSIGNMENT_ORDER); // set open time context variables putTimePropertiesInContext(context, state, "Open", NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // set visible time context variables if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { putTimePropertiesInContext(context, state, "Visible", NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } // set due time context variables putTimePropertiesInContext(context, state, "Due", NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); // set close time context variables putTimePropertiesInContext(context, state, "Close", NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_Category", NEW_ASSIGNMENT_CATEGORY); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null || state.getAttribute(ADDITIONAL_CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); context.put("name_CheckHideDueDate", NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE); //don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // SAK-17606 context.put("name_CheckAnonymousGrading", NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING); context.put("name_CheckIsGroupSubmission", NEW_ASSIGNMENT_GROUP_SUBMIT); String gs = (String) state.getAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT); if (gs == null) gs = "0"; // set the values Assignment a = null; String assignmentRef = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentRef != null) { a = getAssignment(assignmentRef, "setAssignmentFormContext", state); gs = a != null && a.isGroup() ? "1": "0"; } context.put("value_CheckIsGroupSubmission", gs); // put the re-submission info into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); // information related to gradebook categories putGradebookCategoryInfoIntoContext(state, context); context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); //Peer Assessment context.put("value_UsePeerAssessment", state.getAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT)); context.put("value_PeerAssessmentAnonEval", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL)); context.put("value_PeerAssessmentStudentViewReviews", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS)); context.put("value_PeerAssessmentNumReviews", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)); context.put("value_PeerAssessmentInstructions", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS)); putTimePropertiesInContext(context, state, "PeerPeriod", NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); // Keep the use review service setting context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); context.put("turnitin_forceSingleAttachment", ServerConfigurationService.getBoolean("turnitin.forceSingleAttachment", false)); context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.allowStudentView.default", false)) : state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); List<String> subOptions = getSubmissionRepositoryOptions(); String submitRadio = ServerConfigurationService.getString("turnitin.repository.setting.value",null) == null ? NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE : ServerConfigurationService.getString("turnitin.repository.setting.value"); if(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO) != null && subOptions.contains(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO))) submitRadio = state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO).toString(); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO", submitRadio); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT", subOptions); List<String> reportGenOptions = getReportGenOptions(); String reportRadio = ServerConfigurationService.getString("turnitin.report_gen_speed.setting.value", null) == null ? NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY : ServerConfigurationService.getString("turnitin.report_gen_speed.setting.value"); if(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO) != null && reportGenOptions.contains(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO))) reportRadio = state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO).toString(); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO", reportRadio); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT", reportGenOptions); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN", ServerConfigurationService.getBoolean("turnitin.option.s_paper_check", true)); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET", ServerConfigurationService.getBoolean("turnitin.option.internet_check", true)); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB", ServerConfigurationService.getBoolean("turnitin.option.journal_check", true)); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION", ServerConfigurationService.getBoolean("turnitin.option.institution_check", false)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN) == null) ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.s_paper_check.default", ServerConfigurationService.getBoolean("turnitin.option.s_paper_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET", state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.internet_check.default", ServerConfigurationService.getBoolean("turnitin.option.internet_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB", state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.journal_check.default", ServerConfigurationService.getBoolean("turnitin.option.journal_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION", state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.institution_check.default", ServerConfigurationService.getBoolean("turnitin.option.institution_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION)); //exclude bibliographic materials context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC", ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC) == null) ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic.default", ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC)); //exclude quoted materials context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED", ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED) == null) ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted.default", ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED)); //exclude quoted materials boolean displayExcludeType = ServerConfigurationService.getBoolean("turnitin.option.exclude_smallmatches", true); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES", displayExcludeType); if(displayExcludeType){ context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE) == null) ? Integer.toString(ServerConfigurationService.getInt("turnitin.option.exclude_type.default", 0)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE) == null) ? Integer.toString(ServerConfigurationService.getInt("turnitin.option.exclude_value.default", 1)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE)); } // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null || state.getAttribute(ADDITIONAL_CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckHideDueDate", state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); // don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // put resubmission option into context assignment_resubmission_option_into_context(context, state); // get all available assignments from Gradebook tool except for those created fromcategoryTable boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); try { // how many gradebook assignment have been integrated with Assignment tool already currentAssignmentGradebookIntegrationIntoContext(context, state, g, gradebookUid, a != null ? a.getTitle() : null); if (StringUtils.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("withGradebook", Boolean.TRUE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (associateGradebookAssignment != null) { context.put("associateGradebookAssignment", associateGradebookAssignment); if (a != null) { context.put("noAddToGradebookChoice", Boolean.valueOf(associateGradebookAssignment.equals(a.getReference()))); } } } catch (Exception e) { // not able to link to Gradebook M_log.warn(this + "setAssignmentFormContext " + e.getMessage()); } if (StringUtils.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = StringUtils.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE)); context.put("range", range != null?range:"site"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { M_log.warn(this + ":setAssignmentFormContext " + ignore.getMessage()); } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (a != null && a.isGroup()) { List _valid_groups = new ArrayList(); Iterator<Group> _it = groupsAllowAddAssignment.iterator(); while (_it.hasNext()) { Group _group = _it.next(); //if (_group.getProperties().get(GROUP_SECTION_PROPERTY) == null) { _valid_groups.add(_group); //} } groupsAllowAddAssignment = _valid_groups; } if (range == null) { if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } // SAK-26349 - need to add the collection; the iterator added below is only usable once in the velocity template AssignmentComparator comp = new AssignmentComparator(state, sort, asc); Collections.sort((List<Group>) groupsAllowAddAssignment, comp); context.put("groupsList", groupsAllowAddAssignment); context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), comp)); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", Boolean.valueOf(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices // whether the choice of emails instructor submission notification is available in the installation // system installation allowed assignment submission notification boolean allowNotification = ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true); if (allowNotification) { // whether current user can receive notification. If not, don't show the notification choices in the create/edit assignment page allowNotification = AssignmentService.allowReceiveSubmissionNotification(contextString); } if (allowNotification) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default // whether or how the instructor receive submission notification emails, none(default)|each|digest state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } // release grade notification option putReleaseGradeNotificationOptionIntoContext(state, context); // release grade notification option putReleaseResubmissionNotificationOptionIntoContext(state, context, a); // the supplement information // model answers context.put("modelanswer", state.getAttribute(MODELANSWER) != null?Boolean.TRUE:Boolean.FALSE); context.put("modelanswer_text", state.getAttribute(MODELANSWER_TEXT)); context.put("modelanswer_showto", state.getAttribute(MODELANSWER_SHOWTO)); // get attachment for model answer object putSupplementItemAttachmentStateIntoContext(state, context, MODELANSWER_ATTACHMENTS); // private notes context.put("allowReadAssignmentNoteItem", m_assignmentSupplementItemService.canReadNoteItem(a, contextString)); context.put("allowEditAssignmentNoteItem", m_assignmentSupplementItemService.canEditNoteItem(a)); context.put("note", state.getAttribute(NOTE) != null?Boolean.TRUE:Boolean.FALSE); context.put("note_text", state.getAttribute(NOTE_TEXT)); context.put("note_to", state.getAttribute(NOTE_SHAREWITH) != null?state.getAttribute(NOTE_SHAREWITH):String.valueOf(0)); // all purpose item context.put("allPurpose", state.getAttribute(ALLPURPOSE) != null?Boolean.TRUE:Boolean.FALSE); context.put("value_allPurposeTitle", state.getAttribute(ALLPURPOSE_TITLE)); context.put("value_allPurposeText", state.getAttribute(ALLPURPOSE_TEXT)); context.put("value_allPurposeHide", state.getAttribute(ALLPURPOSE_HIDE) != null?state.getAttribute(ALLPURPOSE_HIDE):Boolean.FALSE); context.put("value_allPurposeShowFrom", state.getAttribute(ALLPURPOSE_SHOW_FROM) != null?state.getAttribute(ALLPURPOSE_SHOW_FROM):Boolean.FALSE); context.put("value_allPurposeShowTo", state.getAttribute(ALLPURPOSE_SHOW_TO) != null?state.getAttribute(ALLPURPOSE_SHOW_TO):Boolean.FALSE); context.put("value_allPurposeAccessList", state.getAttribute(ALLPURPOSE_ACCESS)); putTimePropertiesInContext(context, state, "allPurposeRelease", ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN); putTimePropertiesInContext(context, state, "allPurposeRetract", ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN); // get attachment for all purpose object putSupplementItemAttachmentStateIntoContext(state, context, ALLPURPOSE_ATTACHMENTS); // put role information into context HashMap<String, List> roleUsers = new HashMap<String, List>(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); Set<Role> roles = realm.getRoles(); for(Iterator iRoles = roles.iterator(); iRoles.hasNext();) { Role r = (Role) iRoles.next(); Set<String> users = realm.getUsersHasRole(r.getId()); if (users!=null && users.size() > 0) { List<User> usersList = new ArrayList(); for (Iterator<String> iUsers = users.iterator(); iUsers.hasNext();) { String userId = iUsers.next(); try { User u = UserDirectoryService.getUser(userId); usersList.add(u); } catch (Exception e) { M_log.warn(this + ":setAssignmentFormContext cannot get user " + e.getMessage() + " user id=" + userId); } } roleUsers.put(r.getId(), usersList); } } context.put("roleUsers", roleUsers); } catch (Exception e) { M_log.warn(this + ":setAssignmentFormContext role cast problem " + e.getMessage() + " site =" + contextString); } } // setAssignmentFormContext /** * how many gradebook items has been assoicated with assignment * @param context * @param state */ private void currentAssignmentGradebookIntegrationIntoContext(Context context, SessionState state, GradebookService g, String gradebookUid, String aTitle) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get all assignment Iterator iAssignments = AssignmentService.getAssignmentsForContext(contextString); HashMap<String, String> gAssignmentIdTitles = new HashMap<String, String>(); HashMap<String, String> gradebookAssignmentsSelectedDisabled = new HashMap<String, String>(); HashMap<String, String> gradebookAssignmentsLabel = new HashMap<String, String>(); while (iAssignments.hasNext()) { Assignment a = (Assignment) iAssignments.next(); String gradebookItem = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (gradebookItem != null) { String associatedAssignmentTitles=""; if (gAssignmentIdTitles.containsKey(gradebookItem)) { // get the current associated assignment titles first associatedAssignmentTitles=gAssignmentIdTitles.get(gradebookItem) + ", "; } // append the current assignment title associatedAssignmentTitles += a.getTitle(); // put the current associated assignment titles back gAssignmentIdTitles.put(gradebookItem, associatedAssignmentTitles); } } // get all assignments in Gradebook try { List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new ArrayList(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); // gradebook item has been associated or not String gaId = gAssignment.isExternallyMaintained() ? Validator.escapeHtml(gAssignment.getExternalId()) : Validator.escapeHtml(gAssignment.getName()); String status = ""; if (gAssignmentIdTitles.containsKey(gaId)) { String assignmentTitle = gAssignmentIdTitles.get(gaId); if (aTitle != null && aTitle.equals(assignmentTitle)) { // this gradebook item is associated with current assignment, make it selected status = "selected"; } } // check with the state variable if ( state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT) != null) { String associatedAssignment = ((String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (associatedAssignment.equals(gaId)) { status ="selected"; } } gradebookAssignmentsSelectedDisabled.put(gaId, status); // gradebook assignment label String label = gAssignment.getName(); if (gAssignmentIdTitles.containsKey(gaId)) { label += " ( " + rb.getFormattedMessage("usedGradebookAssignment", new Object[]{gAssignmentIdTitles.get(gaId)}) + " )"; } gradebookAssignmentsLabel.put(gaId, label); } } } catch (GradebookNotFoundException e) { // exception M_log.debug(this + ":currentAssignmentGradebookIntegrationIntoContext " + rb.getFormattedMessage("addtogradebook.alertMessage", new Object[]{e.getMessage()})); } context.put("gradebookAssignmentsSelectedDisabled", gradebookAssignmentsSelectedDisabled); context.put("gradebookAssignmentsLabel", gradebookAssignmentsLabel); } private void putGradebookCategoryInfoIntoContext(SessionState state, Context context) { HashMap<Long, String> categoryTable = categoryTable(); if (categoryTable != null) { context.put("value_totalCategories", Integer.valueOf(categoryTable.size())); // selected category context.put("value_Category", state.getAttribute(NEW_ASSIGNMENT_CATEGORY)); List<Long> categoryList = new ArrayList<Long>(); for (Map.Entry<Long, String> entry : categoryTable.entrySet()) { categoryList.add(entry.getKey()); } Collections.sort(categoryList); context.put("categoryKeys", categoryList); context.put("categoryTable", categoryTable()); } else { context.put("value_totalCategories", Integer.valueOf(0)); } } /** * put the release grade notification options into context * @param state * @param context */ private void putReleaseGradeNotificationOptionIntoContext(SessionState state, Context context) { if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) == null) { // set the notification value using site default to be none: no email will be sent to student when the grade is released state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE); } // input fields context.put("name_assignment_releasegrade_notification", ASSIGNMENT_RELEASEGRADE_NOTIFICATION); context.put("value_assignment_releasegrade_notification", state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); // the option values context.put("value_assignment_releasegrade_notification_none", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE); context.put("value_assignment_releasegrade_notification_each", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_EACH); } /** * put the release resubmission grade notification options into context * @param state * @param context */ private void putReleaseResubmissionNotificationOptionIntoContext(SessionState state, Context context, Assignment a) { if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) == null && a != null){ // get the assignment property for notification setting first state.setAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, a.getProperties().getProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); } if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) == null){ // set the notification value using site default to be none: no email will be sent to student when the grade is released state.setAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_NONE); } // input fields context.put("name_assignment_releasereturn_notification", ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION); context.put("value_assignment_releasereturn_notification", state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); // the option values context.put("value_assignment_releasereturn_notification_none", Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_NONE); context.put("value_assignment_releasereturn_notification_each", Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_EACH); } /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("name_order", NEW_ASSIGNMENT_ORDER); context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER)); Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); context.put("value_OpenDate", openTime); if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { Time visibleTime = getTimeFromState(state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); context.put("value_VisibleDate", visibleTime); } // due time Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckHideDueDate", state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // get all available assignments from Gradebook tool except for those created from if (isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // information related to gradebook categories putGradebookCategoryInfoIntoContext(state, context); } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); String assignmentId = StringUtils.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); if (assignmentId != null) { // editing existing assignment context.put("value_assignment_id", assignmentId); Assignment a = getAssignment(assignmentId, "build_instructor_preview_assignment_context", state); if (a != null) { context.put("isDraft", Boolean.valueOf(a.getDraft())); } } else { // new assignment context.put("isDraft", Boolean.TRUE); } context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { List assignments = new ArrayList(); List assignmentIds = (List) state.getAttribute(DELETE_ASSIGNMENT_IDS); HashMap<String, Integer> submissionCountTable = new HashMap<String, Integer>(); for (int i = 0; i < assignmentIds.size(); i++) { String assignmentId = (String) assignmentIds.get(i); Assignment a = getAssignment(assignmentId, "build_instructor_delete_assignment_context", state); if (a != null) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); int submittedCount = 0; while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted() && s.getTimeSubmitted() != null) { submittedCount++; } } if (submittedCount > 0) { // if there is submission to the assignment, show the alert addAlert(state, rb.getFormattedMessage("areyousur_withSubmission", new Object[]{a.getTitle()})); } assignments.add(a); submissionCountTable.put(a.getReference(), Integer.valueOf(submittedCount)); } } context.put("assignments", assignments); context.put("confirmMessage", assignments.size() > 1 ? rb.getString("areyousur_multiple"):rb.getString("areyousur_single")); context.put("currentTime", TimeService.newTime()); context.put("submissionCountTable", submissionCountTable); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String submissionId=""; int gradeType = -1; // need to show the alert for grading drafts? boolean addGradeDraftAlert = false; // assignment String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); Assignment a = getAssignment(assignmentId, "build_instructor_grade_submission_context", state); if (a != null) { context.put("assignment", a); if (a.getContent() != null) { gradeType = a.getContent().getTypeOfGrade(); } // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, a.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); boolean allowToGrade=true; String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (associateGradebookAssignment != null) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g != null && g.isGradebookDefined(gradebookUid)) { if (!g.currentUserHasGradingPerm(gradebookUid)) { context.put("notAllowedToGradeWarning", rb.getString("not_allowed_to_grade_in_gradebook")); allowToGrade=false; } } } context.put("allowToGrade", Boolean.valueOf(allowToGrade)); } // assignment submission AssignmentSubmission s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_grade_submission_context", state); if (s != null) { submissionId = s.getId(); context.put("submission", s); if(a != null) { setScoringAgentProperties(context, a, s, true); } // show alert if student is working on a draft if (!s.getSubmitted() // not submitted && ((s.getSubmittedText() != null && s.getSubmittedText().length()> 0) // has some text || (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0))) // has some attachment { if (s.getCloseTime().after(TimeService.newTime())) { // not pass the close date yet addGradeDraftAlert = true; } else { // passed the close date already addGradeDraftAlert = false; } } ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } // put the re-submission info into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); assignment_resubmission_option_into_context(context, state); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); // try to put in grade overrides if (a.isGroup()) { Map<String,Object> _ugrades = new HashMap(); User[] _users = s.getSubmitters(); for (int i=0; _users != null && i < _users.length; i ++) { if (state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()) != null) { _ugrades.put( _users[i].getId(), gradeType == 3 ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId())): state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()) ); } } context.put("value_grades", _ugrades); } context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); // is this a non-electronic submission type of assignment context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE); if (addGradeDraftAlert) { addAlert(state, rb.getString("grading.alert.draft.beforeclosedate")); } context.put("alertGradeDraft", Boolean.valueOf(addGradeDraftAlert)); if (a != null && a.isGroup()) { checkForUsersInMultipleGroups(a, s.getSubmitterIds(), state, rb.getString("group.user.multiple.warning")); } // for the navigation purpose List<SubmitterSubmission> userSubmissions = state.getAttribute(USER_SUBMISSIONS) != null ? (List<SubmitterSubmission>) state.getAttribute(USER_SUBMISSIONS):null; if (userSubmissions != null) { for (int i = 0; i < userSubmissions.size(); i++) { if (((SubmitterSubmission) userSubmissions.get(i)).getSubmission().getId().equals(submissionId)) { boolean goPT = false; boolean goNT = false; if ((i - 1) >= 0) { goPT = true; } if ((i + 1) < userSubmissions.size()) { goNT = true; } context.put("goPTButton", Boolean.valueOf(goPT)); context.put("goNTButton", Boolean.valueOf(goNT)); if (i>0) { // retrieve the previous submission id context.put("prevSubmissionId", ((SubmitterSubmission) userSubmissions.get(i-1)).getSubmission().getReference()); } if (i < userSubmissions.size() - 1) { // retrieve the next submission id context.put("nextSubmissionId", ((SubmitterSubmission) userSubmissions.get(i+1)).getSubmission().getReference()); } } } } // put supplement item into context supplementItemIntoContext(state, context, a, null); // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_DONE) != null) { context.put("gradingDone", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_DONE); } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_SUBMIT) != null) { context.put("gradingSubmit", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); } // letter grading letterGradeOptionsIntoContext(context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context /** * Checks whether the time is already past. * If yes, return the time of three days from current time; * Otherwise, return the original time * @param originalTime * @return */ private Time getProperFutureTime(Time originalTime) { // check whether the time is past already. // If yes, add three days to the current time Time time = originalTime; if (TimeService.newTime().after(time)) { time = TimeService.newTime(TimeService.newTime().getTime() + 3*24*60*60*1000/*add three days*/); } return time; } public void doPrev_back_next_submission_review(RunData rundata, String option, boolean submit) { SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid()); // save the instructor input boolean hasChange = saveReviewGradeForm(rundata, state, submit ? "submit" : "save"); if (state.getAttribute(STATE_MESSAGE) == null) { ParameterParser params = rundata.getParameters(); List<String> submissionIds = new ArrayList<String>(); if(state.getAttribute(USER_SUBMISSIONS) != null){ submissionIds = (List<String>) state.getAttribute(USER_SUBMISSIONS); } String submissionId = null; String assessorId = null; if ("next".equals(option)) { submissionId = params.get("nextSubmissionId"); assessorId = params.get("nextAssessorId"); } else if ("prev".equals(option)) { submissionId = params.get("prevSubmissionId"); assessorId = params.get("prevAssessorId"); } else if ("back".equals(option)) { String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); List userSubmissionsState = state.getAttribute(STATE_PAGEING_TOTAL_ITEMS) != null ? (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS):null; if(userSubmissionsState != null && userSubmissionsState.size() > 0 && userSubmissionsState.get(0) instanceof SubmitterSubmission && AssignmentService.allowGradeSubmission(assignmentId)){ //coming from instructor view submissions page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); }else{ state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } if(submissionId != null && submissionIds.contains(submissionId)){ state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); } if(assessorId != null){ state.setAttribute(PEER_ASSESSMENT_ASSESSOR_ID, assessorId); } } } /** * Responding to the request of submission navigation * @param rundata * @param option */ public void doPrev_back_next_submission(RunData rundata, String option) { SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid()); // save the instructor input boolean hasChange = readGradeForm(rundata, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null && hasChange) { grade_submission_option(rundata, "save"); } if (state.getAttribute(STATE_MESSAGE) == null) { if ("next".equals(option)) { navigateToSubmission(rundata, "nextSubmissionId"); } else if ("prev".equals(option)) { navigateToSubmission(rundata, "prevSubmissionId"); } else if ("back".equals(option)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } else if ("backListStudent".equals(option)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } } } // doPrev_back_next_submission private void navigateToSubmission(RunData rundata, String paramString) { ParameterParser params = rundata.getParameters(); SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid()); String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); String submissionId = StringUtils.trimToNull(params.getString(paramString)); if (submissionId != null) { // put submission information into state putSubmissionInfoIntoState(state, assignmentId, submissionId); } } /** * Parse time value and put corresponding values into state * @param context * @param state * @param a * @param timeValue * @param timeName * @param month * @param day * @param year * @param hour * @param min */ private void putTimePropertiesInState(SessionState state, Time timeValue, String month, String day, String year, String hour, String min) { try { TimeBreakdown bTime = timeValue.breakdownLocal(); state.setAttribute(month, Integer.valueOf(bTime.getMonth())); state.setAttribute(day, Integer.valueOf(bTime.getDay())); state.setAttribute(year, Integer.valueOf(bTime.getYear())); state.setAttribute(hour, Integer.valueOf(bTime.getHour())); state.setAttribute(min, Integer.valueOf(bTime.getMin())); } catch (NullPointerException _npe) { /* TODO empty exception block */ } } /** * put related time information into context variable * @param context * @param state * @param timeName * @param month * @param day * @param year * @param hour * @param min */ private void putTimePropertiesInContext(Context context, SessionState state, String timeName, String month, String day, String year, String hour, String min) { // get the submission level of close date setting context.put("name_" + timeName + "Month", month); context.put("name_" + timeName + "Day", day); context.put("name_" + timeName + "Year", year); context.put("name_" + timeName + "Hour", hour); context.put("name_" + timeName + "Min", min); context.put("value_" + timeName + "Month", (Integer) state.getAttribute(month)); context.put("value_" + timeName + "Day", (Integer) state.getAttribute(day)); context.put("value_" + timeName + "Year", (Integer) state.getAttribute(year)); context.put("value_" + timeName + "Hour", (Integer) state.getAttribute(hour)); context.put("value_" + timeName + "Min", (Integer) state.getAttribute(min)); } private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); Assignment a = getAssignment(assignmentId, "build_instructor_preview_grade_submission_context", state); if (a != null) { context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } // submission AssignmentSubmission submission = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_preview_grade_submission_context", state); context.put("submission", submission); if(a != null) { setScoringAgentProperties(context, a, submission, false); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW); context.put("userDirectoryService", UserDirectoryService.getInstance()); String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Assignment assignment = getAssignment(assignmentRef, "build_instructor_grade_assignment_context", state); // getContent() early and store it, this call is expensive, always making a db call due to lack of caching in this tool AssignmentContent assignmentContent = assignment == null ? null : assignment.getContent(); if (assignment != null) { context.put("assignment", assignment); state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId()); if (assignmentContent != null) { context.put("assignmentContent", assignmentContent); context.put("value_SubmissionType", Integer.valueOf(assignmentContent.getTypeOfSubmission())); context.put("typeOfGrade", assignmentContent.getTypeOfGrade()); } // put creator information into context putCreatorIntoContext(context, assignment); String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (defaultGrade != null) { context.put("defaultGrade", defaultGrade); } initViewSubmissionListOption(state); String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); context.put("view", view); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH): rb.getString("search_student_instruction")); // access point url for zip file download String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))); if (view != null && !AssignmentConstants.ALL.equals(view)) { // append the group info to the end accessPointUrl = accessPointUrl.concat(view); } context.put("accessPointUrl", accessPointUrl); // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, assignment.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference()); // group list which user can add message to if (groupsAllowGradeAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc))); } } // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); List<SubmitterSubmission> userSubmissions = prepPage(state); // attach the assignment to these submissions now to avoid costly lookup for each submission later in the velocity template for (SubmitterSubmission s : userSubmissions) { s.getSubmission().setAssignment(assignment); } state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); //find peer assessment grades if exist if(assignment.getAllowPeerAssessment()){ List<String> submissionIds = new ArrayList<String>(); //get list of submission ids to look up reviews in db for(SubmitterSubmission s : userSubmissions){ submissionIds.add(s.getSubmission().getId()); } //look up reviews for these submissions List<PeerAssessmentItem> items = assignmentPeerAssessmentService.getPeerAssessmentItems(submissionIds); //create a map for velocity to use in displaying the submission reviews Map<String, List<PeerAssessmentItem>> itemsMap = new HashMap<String, List<PeerAssessmentItem>>(); Map<String, User> reviewersMap = new HashMap<String, User>(); if(items != null){ for(PeerAssessmentItem item : items){ //update items map List<PeerAssessmentItem> sItems = itemsMap.get(item.getSubmissionId()); if(sItems == null){ sItems = new ArrayList<PeerAssessmentItem>(); } sItems.add(item); itemsMap.put(item.getSubmissionId(), sItems); //update users map: User u = reviewersMap.get(item.getAssessorUserId()); if(u == null){ try { u = UserDirectoryService.getUser(item.getAssessorUserId()); reviewersMap.put(item.getAssessorUserId(), u); } catch (UserNotDefinedException e) { M_log.warn(e.getMessage(), e); } } } } //go through all the submissions and make sure there aren't any nulls for(String id : submissionIds){ List<PeerAssessmentItem> sItems = itemsMap.get(id); if(sItems == null){ sItems = new ArrayList<PeerAssessmentItem>(); itemsMap.put(id, sItems); } } context.put("peerAssessmentItems", itemsMap); context.put("reviewersMap", reviewersMap); } // try to put in grade overrides if (assignment.isGroup()) { Map<String,Object> _ugrades = new HashMap<String,Object>(); Iterator<SubmitterSubmission> _ssubmits = userSubmissions.iterator(); while (_ssubmits.hasNext()) { SubmitterSubmission _ss = _ssubmits.next(); if (_ss != null && _ss.getSubmission() != null) { User[] _users = _ss.getSubmission().getSubmitters(); for (int i=0; _users != null && i < _users.length; i ++) { String _agrade = _ss.getSubmission().getGradeForUser(_users[i].getId()); if (_agrade != null) { _ugrades.put( _users[i].getId(), assignmentContent != null && assignmentContent.getTypeOfGrade() == 3 ? displayGrade(state, _agrade): _agrade); } } } } context.put("value_grades", _ugrades); Collection<String> _dups = checkForUsersInMultipleGroups(assignment, null, state, rb.getString("group.user.multiple.warning")); if (_dups.size() > 0) { context.put("usersinmultiplegroups", _dups); } } // whether to show the resubmission choice if (state.getAttribute(SHOW_ALLOW_RESUBMISSION) != null) { context.put("showAllowResubmission", Boolean.TRUE); } // put the re-submission info into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); assignment_resubmission_option_into_context(context, state); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); // put supplement item into context supplementItemIntoContext(state, context, assignment, null); // search context String searchString = (String) state.getAttribute(STATE_SEARCH); if (searchString == null) { searchString = rb.getString("search_student_instruction"); } context.put("searchString", searchString); context.put("form_search", FORM_SEARCH); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); // letter grading letterGradeOptionsIntoContext(context); // ever set the default grade for no-submissions if (assignment != null && assignmentContent != null && assignmentContent.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // non-electronic submissions context.put("form_action", "eventSubmit_doSet_defaultNotGradedNonElectronicScore"); context.put("form_label", rb.getFormattedMessage("not.graded.non.electronic.submission.grade", new Object[]{state.getAttribute(STATE_NUM_MESSAGES)})); } else { // other types of submissions context.put("form_action", "eventSubmit_doSet_defaultNoSubmissionScore"); context.put("form_label", rb.getFormattedMessage("non.submission.grade", new Object[]{state.getAttribute(STATE_NUM_MESSAGES)})); } // show the reminder for download all url String downloadUrl = (String) state.getAttribute(STATE_DOWNLOAD_URL); if (downloadUrl != null) { context.put("download_url_reminder", rb.getString("download_url_reminder")); context.put("download_url_link", downloadUrl); context.put("download_url_link_label", rb.getString("download_url_link_label")); state.removeAttribute(STATE_DOWNLOAD_URL); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * make sure the state variable VIEW_SUBMISSION_LIST_OPTION is not null * @param state */ private void initViewSubmissionListOption(SessionState state) { if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null && (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) == null || !((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)).booleanValue())) { state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, AssignmentConstants.ALL); } } /** * put the supplement item information into context * @param state * @param context * @param assignment * @param s */ private void supplementItemIntoContext(SessionState state, Context context, Assignment assignment, AssignmentSubmission s) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // for model answer boolean allowViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, s); context.put("allowViewModelAnswer", allowViewModelAnswer); if (allowViewModelAnswer) { context.put("assignmentModelAnswerItem", m_assignmentSupplementItemService.getModelAnswer(assignment.getId())); } // for note item boolean allowReadAssignmentNoteItem = m_assignmentSupplementItemService.canReadNoteItem(assignment, contextString); context.put("allowReadAssignmentNoteItem", allowReadAssignmentNoteItem); if (allowReadAssignmentNoteItem) { context.put("assignmentNoteItem", m_assignmentSupplementItemService.getNoteItem(assignment.getId())); } // for all purpose item boolean allowViewAllPurposeItem = m_assignmentSupplementItemService.canViewAllPurposeItem(assignment); context.put("allowViewAllPurposeItem", allowViewAllPurposeItem); if (allowViewAllPurposeItem) { context.put("assignmentAllPurposeItem", m_assignmentSupplementItemService.getAllPurposeItem(assignment.getId())); } } /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); Assignment assignment = getAssignment(assignmentId, "build_instructor_view_assignment_context", state); if (assignment != null) { context.put("assignment", assignment); // put the resubmit information into context assignment_resubmission_option_into_context(context, state); // put creator information into context putCreatorIntoContext(context, assignment); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { Session session = SessionManager.getCurrentSession(); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getActivityHelperInfo( assignmentActivityProducer.getActivity( assignment).getReference()); if (helper != null) { activityHelpers.add(helper); } } addActivity(context, assignment); context.put("activityHelpers", activityHelpers); context.put("taggable", Boolean.valueOf(true)); addDecoUrlMapToContext(session, context, false); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context private void putCreatorIntoContext(Context context, Assignment assignment) { // the creator String creatorId = assignment.getCreator(); try { User creator = UserDirectoryService.getUser(creatorId); context.put("creator", creator.getDisplayName()); } catch (Exception ee) { context.put("creator", creatorId); M_log.warn(this + ":build_instructor_view_assignment_context " + ee.getMessage()); } } /** * build the instructor view of reordering assignments */ protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); context.put("assignmentsize", assignments.size()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT; } // build_instructor_reorder_assignment_context protected String build_student_review_edit_context(VelocityPortlet portlet, Context context, RunData data, SessionState state){ int gradeType = -1; context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state.getAttribute(PEER_ASSESSMENT_ITEMS); String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); User sessionUser = (User) state.getAttribute(STATE_USER); String assessorId = sessionUser.getId(); if(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null){ assessorId = (String) state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID); } Assignment assignment = getAssignment(assignmentId, "build_student_review_edit_context", state); if (assignment != null){ context.put("assignment", assignment); if (assignment.getContent() != null) { gradeType = assignment.getContent().getTypeOfGrade(); } context.put("peerAssessmentInstructions", assignment.getPeerAssessmentInstructions() == null ? "" : assignment.getPeerAssessmentInstructions()); } String submissionId = ""; SecurityAdvisor secAdv = new SecurityAdvisor(){ @Override public SecurityAdvice isAllowed(String userId, String function, String reference) { if("asn.submit".equals(function) || "asn.submit".equals(function) || "asn.grade".equals(function)){ return SecurityAdvice.ALLOWED; } return null; } }; AssignmentSubmission s = null; try{ //surround with a try/catch/finally for the security advisor m_securityService.pushAdvisor(secAdv); s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_student_review_edit_context", state); m_securityService.popAdvisor(secAdv); }catch(Exception e){ M_log.error(e.getMessage(), e); }finally{ if(secAdv != null){ m_securityService.popAdvisor(secAdv); } } if (s != null) { submissionId = s.getId(); context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { context.put("value_feedback_text", s.getSubmittedText()); } else { context.put("value_feedback_text", s.getFeedbackFormattedText()); } context.put("value_feedback_text", s.getSubmittedText()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } context.put("value_feedback_attachment", v); state.setAttribute(ATTACHMENTS, v); } if(peerAssessmentItems != null && submissionId != null){ //find the peerAssessmentItem for this submission: PeerAssessmentItem peerAssessmentItem = null; for(PeerAssessmentItem item : peerAssessmentItems){ if(submissionId.equals(item.getSubmissionId()) && assessorId.equals(item.getAssessorUserId())){ peerAssessmentItem = item; break; } } if(peerAssessmentItem != null){ //check if current user is the peer assessor, if not, only display data (no editing) if(!sessionUser.getId().equals(peerAssessmentItem.getAssessorUserId())){ context.put("view_only", true); try { User reviewer = UserDirectoryService.getUser(peerAssessmentItem.getAssessorUserId()); context.put("reviewer", reviewer); } catch (UserNotDefinedException e) { M_log.warn(e.getMessage(), e); } }else{ context.put("view_only", false); } //scores are saved as whole values //so a score of 1.3 would be stored as 13 //so a DB score of 13 needs to be 1.3: if(peerAssessmentItem.getScore() != null){ double score = peerAssessmentItem.getScore()/10.0; context.put("value_grade", score); }else{ context.put("value_grade", null); } context.put("display_grade", peerAssessmentItem.getScoreDisplay()); context.put("item_removed", peerAssessmentItem.isRemoved()); context.put("value_feedback_comment", peerAssessmentItem.getComment()); //set previous/next values List userSubmissionsState = state.getAttribute(STATE_PAGEING_TOTAL_ITEMS) != null ? (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS):null; List<String> userSubmissions = new ArrayList<String>(); boolean instructorView = false; if(userSubmissionsState != null && userSubmissionsState.size() > 0 && userSubmissionsState.get(0) instanceof SubmitterSubmission){ //from instructor view for(SubmitterSubmission userSubmission : (List<SubmitterSubmission>) userSubmissionsState){ if(!userSubmissions.contains(userSubmission.getSubmission().getId()) && userSubmission.getSubmission().getSubmitted()){ userSubmissions.add(userSubmission.getSubmission().getId()); } } }else{ //student view for(PeerAssessmentItem item : peerAssessmentItems){ if(!userSubmissions.contains(item.getSubmissionId()) && !item.isSubmitted()){ userSubmissions.add(item.getSubmissionId()); } } } if(userSubmissions != null){ context.put("totalReviews", userSubmissions.size()); //first setup map to make the navigation logic easier: Map<String, List<PeerAssessmentItem>> itemMap = new HashMap<String, List<PeerAssessmentItem>>(); for(String userSubmissionId : userSubmissions){ for (PeerAssessmentItem item : peerAssessmentItems){ if(userSubmissionId.equals(item.getSubmissionId())){ List<PeerAssessmentItem> items = itemMap.get(userSubmissionId); if(items == null){ items = new ArrayList<PeerAssessmentItem>(); } items.add(item); itemMap.put(item.getSubmissionId(), items); } } } for(int i = 0; i < userSubmissions.size(); i++){ String userSubmissionId = userSubmissions.get(i); if(userSubmissionId.equals(submissionId)){ //we found the right submission, now find the items context.put("reviewNumber", (i + 1)); List<PeerAssessmentItem> submissionItems = itemMap.get(submissionId); if(submissionItems != null){ for (int j = 0; j < submissionItems.size(); j++){ PeerAssessmentItem item = submissionItems.get(j); if(item.getAssessorUserId().equals(assessorId)){ context.put("anonNumber", i + 1); boolean goPT = false; boolean goNT = false; if ((i - 1) >= 0 || (j - 1) >= 0) { goPT = true; } if ((i + 1) < userSubmissions.size() || (j + 1) < submissionItems.size()) { goNT = true; } context.put("goPTButton", Boolean.valueOf(goPT)); context.put("goNTButton", Boolean.valueOf(goNT)); if (j>0) { // retrieve the previous submission id context.put("prevSubmissionId", (submissionItems.get(j-1).getSubmissionId())); context.put("prevAssessorId", (submissionItems.get(j-1).getAssessorUserId())); }else if(i > 0){ //go to previous submission and grab the last item in that list int k = i - 1; while(k >= 0 && !itemMap.containsKey(userSubmissions.get(k))){ k--; } if(k >= 0 && itemMap.get(userSubmissions.get(k)).size() > 0){ List<PeerAssessmentItem> pItems = itemMap.get(userSubmissions.get(k)); PeerAssessmentItem pItem = pItems.get(pItems.size() - 1); context.put("prevSubmissionId", (pItem.getSubmissionId())); context.put("prevAssessorId", (pItem.getAssessorUserId())); }else{ //no previous option, set to false context.put("goPTButton", Boolean.valueOf(false)); } } if (j < submissionItems.size() - 1) { // retrieve the next submission id context.put("nextSubmissionId", (submissionItems.get(j+1).getSubmissionId())); context.put("nextAssessorId", (submissionItems.get(j+1).getAssessorUserId())); }else if (i < userSubmissions.size() - 1){ //go to previous submission and grab the last item in that list int k = i + 1; while(k < userSubmissions.size() && !itemMap.containsKey(userSubmissions.get(k))){ k++; } if(k < userSubmissions.size() && itemMap.get(userSubmissions.get(k)).size() > 0){ List<PeerAssessmentItem> pItems = itemMap.get(userSubmissions.get(k)); PeerAssessmentItem pItem = pItems.get(0); context.put("nextSubmissionId", (pItem.getSubmissionId())); context.put("nextAssessorId", (pItem.getAssessorUserId())); }else{ //no next option, set to false context.put("goNTButton", Boolean.valueOf(false)); } } } } } } } } } } context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("user", sessionUser); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // put supplement item into context try{ //surround with a try/catch/finally for the security advisor m_securityService.pushAdvisor(secAdv); supplementItemIntoContext(state, context, assignment, null); }catch(Exception e){ M_log.error(e.getMessage(), e); }finally{ if(secAdv != null){ m_securityService.popAdvisor(secAdv); } } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_DONE) != null) { context.put("gradingDone", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_DONE); if(state.getAttribute(PEER_ASSESSMENT_REMOVED_STATUS) != null){ context.put("itemRemoved", state.getAttribute(PEER_ASSESSMENT_REMOVED_STATUS)); state.removeAttribute(PEER_ASSESSMENT_REMOVED_STATUS); } } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_SUBMIT) != null) { context.put("gradingSubmit", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_REVIEW_EDIT; } /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // cleaning from view attribute state.removeAttribute(FROM_VIEW); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); // get the realm and its member List studentMembers = new ArrayList(); Iterator assignments = AssignmentService.getAssignmentsForContext(contextString); //No duplicates Set allowSubmitMembers = new HashSet(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, a.getReference(), contextString); allowSubmitMembers.addAll(submitterIds); } for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage()); } } context.put("studentMembers", new SortedIterator(studentMembers.iterator(), new AssignmentComparator(state, SORTED_USER_BY_SORTNAME, Boolean.TRUE.toString()))); context.put("assignmentService", AssignmentService.getInstance()); context.put("userService", UserDirectoryService.getInstance()); context.put("viewGroup", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH): rb.getString("search_student_instruction")); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); if (AssignmentService.getAllowGroupAssignments()) { Collection groups = getAllGroupsInSite(contextString); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); } HashMap showStudentAssignments = new HashMap(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); // sort the assignments into the default order before adding Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId); // filter to obtain only grade-able assignments List rv = new ArrayList(); while (assignmentSorter.hasNext()) { Assignment a = (Assignment) assignmentSorter.next(); if (AssignmentService.allowGradeSubmission(a.getReference())) { rv.add(a); } } Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString())); showStudentAssignments.put(user, assignmentSortFinal); } catch (Exception ee) { M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_GRADE_SUBMISSION_BY_RELEASED); //context.put("sortedBy_assignment", SORTED_GRADE_SUBMISSION_BY_ASSIGNMENT); //context.put("sortedBy_maxGrade", SORTED_GRADE_SUBMISSION_BY_MAX_GRADE); // get current site String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH): rb.getString("search_student_instruction")); context.put("view", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)); context.put("viewString", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)!=null?state.getAttribute(VIEW_SUBMISSION_LIST_OPTION):""); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH):""); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); if (AssignmentService.getAllowGroupAssignments()) { Collection groups = getAllGroupsInSite(contextString); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); } add2ndToolbarFields(data, context); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); context.put("assignmentService", AssignmentService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions // Is Gradebook defined for the site? protected boolean isGradebookDefined() { boolean rv = false; try { GradebookService g = (GradebookService) ComponentManager .get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid) && (g.currentUserHasEditPerm(gradebookUid) || g.currentUserHasGradingPerm(gradebookUid))) { rv = true; } } catch (Exception e) { M_log.debug(this + "isGradebookDefined " + rb.getFormattedMessage("addtogradebook.alertMessage", new Object[]{e.getMessage()})); } return rv; } // isGradebookDefined() /** * build the instructor view to download/upload information from archive file */ protected String build_instructor_download_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String view = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); boolean download = (((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_DOWNLOAD_ALL)); context.put("download", Boolean.valueOf(download)); context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT)); context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT)); context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE)); String gradeFileFormat = (String) state.getAttribute(UPLOAD_ALL_GRADEFILE_FORMAT); if (gradeFileFormat==null) gradeFileFormat="csv"; context.put("gradeFileFormat", gradeFileFormat); context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS)); context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT)); context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT)); context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES)); // SAK-19147 context.put("withoutFolders", state.getAttribute(UPLOAD_ALL_WITHOUT_FOLDERS)); context.put("enableFlatDownload", ServerConfigurationService.getBoolean("assignment.download.flat", false)); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Assignment a = getAssignment(assignmentRef, "build_instructor_download_upload_all", state); if (a != null) { String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference( contextString, assignmentRef)); context.put("accessPointUrl", accessPointUrl); int submissionType = a.getContent().getTypeOfSubmission(); // if the assignment is of text-only or allow both text and attachment, include option for uploading student submit text context.put("includeSubmissionText", Boolean.valueOf(Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION == submissionType || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == submissionType)); // if the assignment is of attachment-only or allow both text and attachment, include option for uploading student attachment context.put("includeSubmissionAttachment", Boolean.valueOf(Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION == submissionType || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == submissionType || Assignment.SINGLE_ATTACHMENT_SUBMISSION == submissionType)); context.put("viewString", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)!=null?state.getAttribute(VIEW_SUBMISSION_LIST_OPTION):""); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH):""); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL; } // build_instructor_upload_all /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * integration with gradebook * * @param state * @param assignmentRef Assignment reference * @param associateGradebookAssignment The title for the associated GB assignment * @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment * @param oldAssignment_title The original assignment title * @param newAssignment_title The updated assignment title * @param newAssignment_maxPoints The maximum point of the assignment * @param newAssignment_dueTime The due time of the assignment * @param submissionRef Any submission grade need to be updated? Do bulk update if null * @param updateRemoveSubmission "update" for update submission;"remove" for remove submission */ protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission, long category) { associateGradebookAssignment = StringUtils.trimToNull(associateGradebookAssignment); // add or remove external grades to gradebook // a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden // b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The // exception are indication that the assessment is already in the Gradebook or there is nothing // to remove. String assignmentToolTitle = getToolTitle(); GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid) && g.currentUserHasGradingPerm(gradebookUid)) { boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, assignmentRef); boolean isExternalAssociateAssignmentDefined = gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment); if (addUpdateRemoveAssignment != null) { // add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || ("update".equals(addUpdateRemoveAssignment) && !isExternalAssignmentDefined)) && associateGradebookAssignment == null) { // add assignment into gradebook try { // add assignment to gradebook gExternal.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle, false, category != -1?Long.valueOf(category):null); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (ConflictingAssignmentNameException e) { // add alert prompting for change assignment title addAlert(state, rb.getFormattedMessage("addtogradebook.nonUniqueTitle", new Object[]{"\"" + newAssignment_title + "\""})); M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (ConflictingExternalIdException e) { // this shouldn't happen, as we have already checked for assignment reference before. Log the error M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (GradebookNotFoundException e) { // this shouldn't happen, as we have checked for gradebook existence before M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (Exception e) { // ignore M_log.warn(this + ":integrateGradebook " + e.getMessage()); } } else if ("update".equals(addUpdateRemoveAssignment)) { if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined) { // if there is an external entry created in Gradebook based on this assignment, update it try { // update attributes if the GB assignment was created for the assignment gExternal.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), false); } catch(Exception e) { addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef})); M_log.warn(this + ":integrateGradebook " + rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef})); } } } // addUpdateRemove != null else if ("remove".equals(addUpdateRemoveAssignment)) { // remove assignment and all submission grades removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, gExternal, gradebookUid); } } if (updateRemoveSubmission != null) { Assignment a = getAssignment(assignmentRef, "integrateGradebook", state); if (a != null) { if ("update".equals(updateRemoveSubmission) && a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null && !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (submissionRef == null) { // bulk add all grades for assignment into gradebook Iterator submissions = AssignmentService.getSubmissions(a).iterator(); //Assignment scores map Map<String, String> sm = new HashMap<String, String>(); //Assignment comments map, though doesn't look like there's any way to update comments in bulk in the UI yet Map<String, String> cm = new HashMap<String, String>(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); if (aSubmission.getGradeReleased()) { User[] submitters = aSubmission.getSubmitters(); String gradeString = StringUtils.trimToNull(aSubmission.getGrade(false)); String commentString = FormattedText.convertFormattedTextToPlaintext(aSubmission.getFeedbackComment()); String grade = gradeString != null ? displayGrade(state,gradeString) : null; for (int i=0; submitters != null && i < submitters.length; i++) { String submitterId = submitters[i].getId(); if (a.isGroup() && aSubmission.getGradeForUser(submitterId) != null) { grade = displayGrade(state,aSubmission.getGradeForUser(submitterId)); } sm.put(submitterId, grade); cm.put(submitterId, commentString); } } } // need to update only when there is at least one submission if (!sm.isEmpty()) { if (associateGradebookAssignment != null) { if (isExternalAssociateAssignmentDefined) { // the associated assignment is externally maintained gExternal.updateExternalAssessmentScoresString(gradebookUid, associateGradebookAssignment, sm); gExternal.updateExternalAssessmentComments(gradebookUid, associateGradebookAssignment, cm); } else if (isAssignmentDefined) { // the associated assignment is internal one, update records one by one for (Map.Entry<String, String> entry : sm.entrySet()) { String submitterId = (String) entry.getKey(); String grade = StringUtils.trimToNull(displayGrade(state, (String) sm.get(submitterId))); if (grade != null) { g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitterId, grade, ""); } } } } else if (isExternalAssignmentDefined) { gExternal.updateExternalAssessmentScoresString(gradebookUid, assignmentRef, sm); gExternal.updateExternalAssessmentComments(gradebookUid, associateGradebookAssignment, cm); } } } else { // only update one submission AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state); if (aSubmission != null) { User[] submitters = aSubmission.getSubmitters(); String gradeString = displayGrade(state, StringUtils.trimToNull(aSubmission.getGrade(false))); for (int i=0; submitters != null && i < submitters.length; i++) { String gradeStringToUse = (a.isGroup() && aSubmission.getGradeForUser(submitters[i].getId()) != null) ? displayGrade(state,aSubmission.getGradeForUser(submitters[i].getId())): gradeString; if (associateGradebookAssignment != null) { if (gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is externally maintained gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[i].getId(), (gradeStringToUse != null && aSubmission.getGradeReleased()) ? gradeStringToUse : ""); //Gradebook only supports plaintext strings String commentString = FormattedText.convertFormattedTextToPlaintext(aSubmission.getFeedbackComment()); gExternal.updateExternalAssessmentComment(gradebookUid, associateGradebookAssignment, submitters[i].getId(), (commentString != null && aSubmission.getGradeReleased()) ? commentString : ""); } else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is internal one, update records g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[i].getId(), (gradeStringToUse != null && aSubmission.getGradeReleased()) ? gradeStringToUse : "", ""); } } else { gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[i].getId(), (gradeStringToUse != null && aSubmission.getGradeReleased()) ? gradeStringToUse : ""); } } } } } else if ("remove".equals(updateRemoveSubmission)) { if (submissionRef == null) { // remove all submission grades (when changing the associated entry in Gradebook) Iterator submissions = AssignmentService.getSubmissions(a).iterator(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); for (int i=0; submitters != null && i < submitters.length; i++) { if (isExternalAssociateAssignmentDefined) { // if the old associated assignment is an external maintained one gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[i].getId(), null); } else if (isAssignmentDefined) { g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[i].getId(), "0", assignmentToolTitle); } } } } else { // remove only one submission grade AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state); if (aSubmission != null) { User[] submitters = aSubmission.getSubmitters(); for (int i=0; submitters != null && i < submitters.length; i++) { if (isExternalAssociateAssignmentDefined) { // external assignment gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[i].getId(), null); } else if (isAssignmentDefined) { // gb assignment g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[i].getId(), "0", ""); } } } } } } } } } // integrateGradebook /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student public void doView_submission_evap(RunData data){ SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(INVOKE, INVOKE_BY_LINK); doView_submission(data); } /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); String submitterId = params.get("submitterId"); if (submitterId != null) { try { u = UserDirectoryService.getUser(submitterId); state.setAttribute("student", u); } catch (UserNotDefinedException ex) { M_log.warn(this + ":doView_submission cannot find user with id " + submitterId + " " + ex.getMessage()); } } Assignment a = getAssignment(assignmentReference, "doView_submission", state); if (a != null) { AssignmentSubmission submission = getSubmission(assignmentReference, u, "doView_submission", state); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (Boolean.valueOf(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } // put resubmission option into state assignment_resubmission_option_into_state(a, submission, state); // show submission view unless group submission with group error String _mode = MODE_STUDENT_VIEW_SUBMISSION; if (a.isGroup()) { Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); groups = getGroupsWithUser(u.getId(), a, st); Collection<String> _dupUsers = checkForGroupsInMultipleGroups(a, groups, state, rb.getString("group.user.multiple.warning")); if (_dupUsers.size() > 0) { _mode = MODE_STUDENT_VIEW_GROUP_ERROR; } } catch (IdUnusedException iue) { M_log.warn(this + ":doView_submission: Site not found!" + iue.getMessage()); } } state.setAttribute(STATE_MODE, _mode); if (submission != null) { // submission read event Event event = m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submission.getId(), false); m_eventTrackingService.post(event); LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); if (null != lrss) { lrss.registerStatement(getStatementForViewSubmittedAssignment(lrss.getEventActor(event), event, a.getTitle()), "assignment"); } } else { // otherwise, the student just read assignment description and prepare for submission Event event = m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, a.getId(), false); m_eventTrackingService.post(event); LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); if (null != lrss) { lrss.registerStatement(getStatementForViewAssignment(lrss.getEventActor(event), event, a.getTitle()), "assignment"); } } } } // doView_submission /** * Dispatcher for view submission list options */ public void doView_submission_list_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if ("changeView".equals(option)) { doChange_submission_list_option(data); } else if ("search".equals(option)) { state.setAttribute(VIEW_SUBMISSION_SEARCH, params.getString("search")); } else if ("clearSearch".equals(option)) { state.removeAttribute(VIEW_SUBMISSION_SEARCH); } else if ("download".equals(option)) { // go to download all page doPrep_download_all(data); } else if ("upload".equals(option)) { // go to upload all page doPrep_upload_all(data); } else if ("releaseGrades".equals(option)) { // release all grades doRelease_grades(data); } } // doView_submission_list_option /** * Action is to view the content of one specific assignment submission */ public void doChange_submission_list_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String view = params.getString("viewgroup"); //Case where two dropdowns on same page if (view == null) { view = params.getString("view"); } state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view); } // doView_submission_list_option /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, aReference); Assignment a = getAssignment(aReference, "doPreview_submission", state); saveSubmitInputs(state, params); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); // get attachment input and generate alert message according to assignment submission type checkSubmissionTextAttachmentInput(data, state, a, text); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); String fromView = (String) state.getAttribute(FROM_VIEW); if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } else { // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new ArrayList()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { // put submission information into state SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); putSubmissionInfoIntoState(state, assignmentId, sId); String fromView = (String) state.getAttribute(FROM_VIEW); if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } else { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doCancel_grade_submission /** * clean the state variables related to grading page * @param state */ private void resetGradeSubmission(SessionState state) { // reset the grade parameters state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT); state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); // remove all GRADE_SUBMISSION_GRADE states including possible grade overrides // looking like GRADE_SUBMISSION_GRADE_[id of user] Iterator<String> _attribute_names = state.getAttributeNames().iterator(); while (_attribute_names.hasNext()) { String _attribute_name = _attribute_names.next(); if (_attribute_name.startsWith(GRADE_SUBMISSION_GRADE)) { state.removeAttribute(_attribute_name); } } state.removeAttribute(GRADE_SUBMISSION_SUBMISSION_ID); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); state.removeAttribute(GRADE_SUBMISSION_DONE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); resetAllowResubmitParams(state); } /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the reorder process */ public void doCancel_reorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_reorder /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { doCancel_grade_submission(data); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission public void doSave_grade_submission_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); saveReviewGradeForm(data, state, "save"); } public void doSave_toggle_remove_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null){ String peerAssessor = (String) state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID); ParameterParser params = data.getParameters(); String submissionRef = params.getString("submissionId"); String submissionId = null; if(submissionRef != null){ int i = submissionRef.lastIndexOf(Entity.SEPARATOR); if (i == -1){ submissionId = submissionRef; }else{ submissionId = submissionRef.substring(i + 1); } } if(submissionId != null){ //call the DB to make sure this user can edit this assessment, otherwise it wouldn't exist PeerAssessmentItem item = assignmentPeerAssessmentService.getPeerAssessmentItem(submissionId, peerAssessor); if(item != null){ item.setRemoved(!item.isRemoved()); assignmentPeerAssessmentService.savePeerAssessmentItem(item); if(item.getScore() != null){ //item was part of the calculation, re-calculate boolean saved = assignmentPeerAssessmentService.updateScore(submissionId); if(saved){ //we need to make sure the GB is updated correctly (or removed) String assignmentId = item.getAssignmentId(); if(assignmentId != null){ Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if(a != null){ String aReference = a.getReference(); String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, submissionId, "update", -1); } } } } state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); state.setAttribute(PEER_ASSESSMENT_REMOVED_STATUS, item.isRemoved()); //update session state: List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state.getAttribute(PEER_ASSESSMENT_ITEMS); if(peerAssessmentItems != null){ for(int i = 0; i < peerAssessmentItems.size(); i++) { PeerAssessmentItem sItem = peerAssessmentItems.get(i); if(sItem.getSubmissionId().equals(item.getSubmissionId()) && sItem.getAssessorUserId().equals(item.getAssessorUserId())){ //found it, just update it peerAssessmentItems.set(i, item); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); break; } } } } } } } /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = editSubmission(sId, "grade_submission_option", state); if (sEdit != null) { //This logic could be done in one line, but would be harder to read, so break it out to make it easier to follow boolean gradeChanged = false; if((sEdit.getGrade() == null || "".equals(sEdit.getGrade().trim())) && (grade == null || "".equals(grade.trim()))){ //both are null, keep grade changed = false }else if((sEdit.getGrade() == null || "".equals(sEdit.getGrade().trim()) || (grade == null || "".equals(grade.trim())))){ //one is null the other isn't gradeChanged = true; }else if(!grade.trim().equals(sEdit.getGrade().trim())){ gradeChanged = true; } Assignment a = sEdit.getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } if ("return".equals(gradeOption) || "release".equals(gradeOption)) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); if(gradeChanged){ sEdit.setGradedBy(null); } sEdit.setGradeReleased(false); } else { sEdit.setGrade(grade); if (grade.length() != 0) { sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } } else { sEdit.setGraded(false); if(gradeChanged){ sEdit.setGradedBy(null); } } } // iterate through submitters and look for grade overrides... if (withGrade && a.isGroup()) { User[] _users = sEdit.getSubmitters(); for (int i=0; _users != null && i < _users.length; i++) { String _gr = (String)state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); sEdit.addGradeForUser(_users[i].getId(), _gr); } } if ("release".equals(gradeOption)) { sEdit.setGradeReleased(true); sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if ("return".equals(gradeOption)) { sEdit.setGradeReleased(true); sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } else if ("save".equals(gradeOption)) { sEdit.setGradeReleased(false); sEdit.setReturned(false); sEdit.setTimeReturned(null); } ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } else { // clean resubmission property pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } // the instructor comment String feedbackCommentString = StringUtils .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } else { sEdit.setFeedbackComment(""); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); // save a timestamp for this grading process sEdit.getPropertiesEdit().addProperty(AssignmentConstants.PROP_LAST_GRADED_DATE, TimeService.newTime().toStringLocalFull()); AssignmentService.commitEdit(sEdit); // update grades in gradebook String aReference = a.getReference(); String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (!"remove".equals(gradeOption)) { // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1); } else { //remove grade from gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove", -1); } } if (state.getAttribute(STATE_MESSAGE) == null) { // put submission information into state putSubmissionInfoIntoState(state, assignmentId, sId); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); } else { state.removeAttribute(GRADE_SUBMISSION_DONE); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { // save submission post_save_submission(data, false); } // doSave_submission /** * set the resubmission related properties in AssignmentSubmission object * @param a * @param edit */ private void setResubmissionProperties(Assignment a, AssignmentSubmissionEdit edit) { // get the assignment setting for resubmitting ResourceProperties assignmentProperties = a.getProperties(); String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (assignmentAllowResubmitNumber != null) { edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, assignmentAllowResubmitNumber); String assignmentAllowResubmitCloseDate = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // if assignment's setting of resubmit close time is null, use assignment close time as the close time for resubmit edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime())); } } /** * Action is to post the submission */ public void doPost_submission(RunData data) { // post submission post_save_submission(data, true); } // doPost_submission /** * Inner method used for post or save submission * @param data * @param post */ private void post_save_submission(RunData data, boolean post) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = getAssignment(aReference, "post_save_submission", state); if (a != null && AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // check formatting error whether the student is posting or saving String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); User submitter = null; String studentId = params.get("submit_on_behalf_of"); if (studentId != null && !studentId.equals("-1")) { // SAK-23817: return to the Assignments List by Student state.setAttribute(FROM_VIEW, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); try { u = UserDirectoryService.getUser(studentId); submitter = u; } catch (UserNotDefinedException ex1) { M_log.warn("Unable to find user with ID [" + studentId + "]"); submitter = null; } } String group_id = null; String original_group_id = null; if (a.isGroup()) { original_group_id = (params.getString("originalGroup") == null || params.getString("originalGroup").trim().length() == 0) ? null: params.getString("originalGroup"); ; if (original_group_id != null) { state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, original_group_id); } else { if (state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP) != null) original_group_id = (String)state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP); else state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, null); } String[] groupChoice = params.getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { if (groupChoice.length > 1) { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } else { group_id = groupChoice[0]; state.setAttribute(VIEW_SUBMISSION_GROUP, groupChoice[0]); } } else { // get the submitted group id if (state.getAttribute(VIEW_SUBMISSION_GROUP) != null) { group_id = (String)state.getAttribute(VIEW_SUBMISSION_GROUP); } else { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } } String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // SAK-26322 --bbailla2 List nonInlineAttachments = getNonInlineAttachments(state, a); int typeOfSubmission = a.getContent().getTypeOfSubmission(); if (typeOfSubmission == Assignment.SINGLE_ATTACHMENT_SUBMISSION && nonInlineAttachments.size() >1) { //Single uploaded file and there are multiple attachments adjustAttachmentsToSingleUpload(data, state, a, nonInlineAttachments); } // clear text if submission type does not allow it if (typeOfSubmission == Assignment.SINGLE_ATTACHMENT_SUBMISSION || typeOfSubmission == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION) { text = null; } // get attachment input and generate alert message according to assignment submission type checkSubmissionTextAttachmentInput(data, state, a, text); } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { AssignmentSubmission submission = null; if (a.isGroup()) { submission = getSubmission(a.getReference(), (original_group_id == null ? group_id: original_group_id), "post_save_submission", state); } else { submission = getSubmission(a.getReference(), u, "post_save_submission", state); } if (submission != null) { // the submission already exists, change the text and honor pledge value, post it AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "post_save_submission", state); if (sEdit != null) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); /** * SAK-22150 We will need to know later if there was a previous submission time. DH */ boolean isPreviousSubmissionTime = true; if (sEdit.getTimeSubmitted() == null || "".equals(sEdit.getTimeSubmitted())) { isPreviousSubmissionTime = false; } if (a.isGroup()) { if (original_group_id != null && !original_group_id.equals(group_id)) { // changing group id so we need to check if a submission has already been made for that group AssignmentSubmission submissioncheck = getSubmission(a.getReference(), group_id, "post_save_submission",state); if (submissioncheck != null) { addAlert(state, rb.getString("group.already.submitted")); M_log.warn(this + ":post_save_submission " + group_id + " has already submitted " + submissioncheck.getId() + "!"); } } sEdit.setSubmitterId(group_id); } sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(post); // decrease the allow_resubmit_number, if this submission has been submitted. if (sEdit.getSubmitted() && isPreviousSubmissionTime && sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number, if the number is not -1 (not unlimited) if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } } // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. Time now = TimeService.newTime(); // need this to handle feedback and comments, which we have to do even if ungraded // get the previous graded date String prevGradedDate = sEdit.getProperties().getProperty(AssignmentConstants.PROP_LAST_GRADED_DATE); if (prevGradedDate == null) { // since this is a newly added property, if no value is set, get the default as the submission last modified date prevGradedDate = sEdit.getTimeLastModified().toStringLocalFull(); sEdit.getProperties().addProperty(AssignmentConstants.PROP_LAST_GRADED_DATE, prevGradedDate); } if (sEdit.getGraded() && sEdit.getReturned() && sEdit.getGradeReleased()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtils.split(previousGrades, " "); String newGrades = ""; NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(decSeparator) == -1) { // show the grade with decimal point grade = grade.concat(decSeparator).concat("0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } if (StringUtils.trimToNull(sEdit.getGradeDisplay()) != null) { previousGrades = "<h4>" + prevGradedDate + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getGradeDisplay() + "</div>" +previousGrades; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); } // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGradedBy(null); sEdit.setGrade(""); sEdit.setGradeReleased(false); } // following involves content, not grading, so always do on resubmit, not just if graded // clean the ContentReview attributes sEdit.setReviewIconUrl(null); sEdit.setReviewScore(0); // default to be 0? sEdit.setReviewStatus(null); if (StringUtils.trimToNull(sEdit.getFeedbackFormattedText()) != null) { // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = "<h4>" + prevGradedDate + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackText() + "</div>" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); } if (StringUtils.trimToNull(sEdit.getFeedbackComment()) != null) { // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = "<h4>" + prevGradedDate + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackComment() + "</div>" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); } // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); StringBuffer attBuffer = new StringBuffer(); for (int k = 0; k<feedbackAttachments.size();k++) { // use comma as separator for attachments attBuffer.append(((Reference) feedbackAttachments.get(k)).getReference() + ","); } feedbackAttachmentHistory = attBuffer.toString() + feedbackAttachmentHistory; sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); sEdit.setAssignment(a); // SAK-26322 --bbailla2 List nonInlineAttachments = getNonInlineAttachments(state, a); if (nonInlineAttachments != null && a.getContent().getTypeOfSubmission() == 5) { //clear out inline attachments for content-review //filter the attachment sin the state to exclude inline attachments (nonInlineAttachments, is a subset of what's currently in the state) state.setAttribute(ATTACHMENTS, nonInlineAttachments); } // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { if (a.getContent().getTypeOfSubmission() == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION) { //inline only doesn't accept attachments sEdit.clearSubmittedAttachments(); } else { //Post the attachments before clearing so that we don't sumbit duplicate attachments //Check if we need to post the attachments if (a.getContent().getAllowReviewService()) { if (!attachments.isEmpty()) { sEdit.postAttachment(attachments); } } // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment if (submitter != null) { sPropertiesEdit.addProperty(AssignmentSubmission.SUBMITTER_USER_ID, submitter.getId()); state.setAttribute(STATE_SUBMITTER, u.getId()); } else { sPropertiesEdit.removeProperty(AssignmentSubmission.SUBMITTER_USER_ID); } Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } } // SAK-26322 - add inline as an attachment for the content review service --bbailla2 if (a.getContent().getAllowReviewService() && !isHtmlEmpty(text)) { prepareInlineForContentReview(text, sEdit, state, submitter); } if (submitter != null) { sPropertiesEdit.addProperty(AssignmentSubmission.SUBMITTER_USER_ID, submitter.getId()); state.setAttribute(STATE_SUBMITTER, u.getId()); } else { sPropertiesEdit.removeProperty(AssignmentSubmission.SUBMITTER_USER_ID); } // SAK-17606 StringBuilder log = new StringBuilder(); log.append(new java.util.Date()); log.append(" "); boolean anonymousGrading = Boolean.parseBoolean(a.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); if(!anonymousGrading){ log.append(u.getDisplayName()); log.append(" ("); log.append(u.getEid()); log.append(") "); } log.append(post ? "submitted" : "saved draft"); sEdit.addSubmissionLogEntry(log.toString()); AssignmentService.commitEdit(sEdit); } } else { // new submission try { // if assignment is a group submission... send group id and not user id M_log.debug(this + " NEW SUBMISSION IS GROUP: " + a.isGroup() + " GROUP:" + group_id); AssignmentSubmissionEdit edit = a.isGroup() ? AssignmentService.addSubmission(contextString, assignmentId, group_id): AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId()); if (edit != null) { edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(post); edit.setAssignment(a); ResourcePropertiesEdit sPropertiesEdit = edit.getPropertiesEdit(); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); // SAK-26322 - add inline as an attachment for the content review service --bbailla2 if (a.getContent().getAllowReviewService() && !isHtmlEmpty(text)) { prepareInlineForContentReview(text, edit, state, submitter); } if (attachments != null) { // add each attachment if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService()) edit.postAttachment(attachments); // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } // set the resubmission properties setResubmissionProperties(a, edit); if (submitter != null) { sPropertiesEdit.addProperty(AssignmentSubmission.SUBMITTER_USER_ID, submitter.getId()); state.setAttribute(STATE_SUBMITTER, u.getId()); } else { sPropertiesEdit.removeProperty(AssignmentSubmission.SUBMITTER_USER_ID); } // SAK-17606 StringBuilder log = new StringBuilder(); log.append(new java.util.Date()); log.append(" "); boolean anonymousGrading = Boolean.parseBoolean(a.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); if(!anonymousGrading){ log.append(u.getDisplayName()); log.append(" ("); log.append(u.getEid()); log.append(") "); } log.append(post ? "submitted" : "saved draft"); edit.addSubmissionLogEntry(log.toString()); AssignmentService.commitEdit(edit); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); M_log.warn(this + ":post_save_submission " + e.getMessage()); } } // if-else } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); if (null != lrss) { Event event = m_eventTrackingService.newEvent(AssignmentConstants.EVENT_SUBMIT_ASSIGNMENT_SUBMISSION, assignmentId, false); lrss.registerStatement( getStatementForSubmitAssignment(lrss.getEventActor(event), event, ServerConfigurationService.getAccessUrl(), a.getTitle()), "sakai.assignment"); } } // if } // post_save_submission /** * Takes the inline submission, prepares it as an attachment to the submission and queues the attachment with the content review service * @author bbailla2 */ private void prepareInlineForContentReview(String text, AssignmentSubmissionEdit edit, SessionState state, User submitter) { //We will be replacing the inline submission's attachment //firstly, disconnect any existing attachments with AssignmentSubmission.PROP_INLINE_SUBMISSION set List attachments = edit.getSubmittedAttachments(); List toRemove = new ArrayList(); Iterator itAttachments = attachments.iterator(); while (itAttachments.hasNext()) { Reference attachment = (Reference) itAttachments.next(); ResourceProperties attachProps = attachment.getProperties(); if ("true".equals(attachProps.getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { toRemove.add(attachment); } } Iterator itToRemove = toRemove.iterator(); while (itToRemove.hasNext()) { Reference attachment = (Reference) itToRemove.next(); edit.removeSubmittedAttachment(attachment); } //now prepare the new resource //provide lots of info for forensics - filename=InlineSubmission_siteId_assignmentId_userDisplayId_(on ehalf of)_date.html String currentDisplayName = UserDirectoryService.getCurrentUser().getDisplayId(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); //avoid semicolons in filenames, right? dform.applyPattern("yyyy-MM-dd_HH-mm-ss"); StringBuilder sb_resourceId = new StringBuilder("InlineSub_"); String u = "_"; sb_resourceId.append(edit.getAssignmentId()).append(u).append(currentDisplayName).append(u); if (submitter != null) { sb_resourceId.append("for_").append(submitter.getDisplayId()).append(u); } sb_resourceId.append(dform.format(new Date())); String fileExtension = ".html"; /* * TODO: add and use a method in ContentHostingService to get the length of the ID of an attachment collection * Attachment collections currently look like this: * /attachment/dc126c4a-a48f-42a6-bda0-cf7b9c4c5c16/Assignments/eac7212a-9597-4b7d-b958-89e1c47cdfa7/ * See BaseContentService.addAttachmentResource for more information */ String toolName = "Assignments"; // TODO: add and use a method in IdManager to get the maxUuidLength int maxUuidLength = 36; int esl = Entity.SEPARATOR.length(); int attachmentCollectionLength = ContentHostingService.ATTACHMENTS_COLLECTION.length() + siteId.length() + esl + toolName.length() + esl + maxUuidLength + esl; int maxChars = ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH - attachmentCollectionLength - fileExtension.length() - 1; String resourceId = StringUtils.substring(sb_resourceId.toString(), 0, maxChars) + fileExtension; ResourcePropertiesEdit inlineProps = m_contentHostingService.newResourceProperties(); inlineProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, rb.getString("submission.inline")); inlineProps.addProperty(ResourceProperties.PROP_DESCRIPTION, resourceId); inlineProps.addProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION, "true"); //create a byte array input stream //text is almost in html format, but it's missing the start and ending tags //(Is this always the case? Does the content review service care?) String toHtml = "<html><head></head><body>" + text + "</body></html>"; InputStream contentStream = new ByteArrayInputStream(toHtml.getBytes()); String contentType = "text/html"; //duplicating code from doAttachUpload. TODO: Consider refactoring into a method SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { if(function.equals(m_contentHostingService.AUTH_RESOURCE_ADD)){ return SecurityAdvice.ALLOWED; }else if(function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_ANY)){ return SecurityAdvice.ALLOWED; }else{ return SecurityAdvice.PASS; } } }; try { m_securityService.pushAdvisor(sa); ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, toolName, contentType, contentStream, inlineProps); // TODO: need to put this file in some kind of list to improve performance with web service impls of content-review service --bbailla2 String contentUserId = UserDirectoryService.getCurrentUser().getId(); if(submitter != null){ //this is a submission on behalf of a student, so grab that student's id instead contentUserId = submitter.getId(); } contentReviewService.queueContent(contentUserId, siteId, edit.getAssignment().getReference(), Arrays.asList(attachment)); try { Reference ref = EntityManager.newReference(m_contentHostingService.getReference(attachment.getId())); edit.addSubmittedAttachment(ref); } catch (Exception e) { M_log.warn(this + "prepareInlineForContentReview() cannot find reference for " + attachment.getId() + e.getMessage()); } } catch (PermissionException e) { addAlert(state, rb.getString("notpermis4")); } catch (RuntimeException e) { if (m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) { addAlert(state, rb.getFormattedMessage("alert.toolong", new String[]{resourceId})); } } catch (ServerOverloadException e) { M_log.debug(this + ".prepareInlineForContentReview() ***** DISK IO Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.diskio")); } catch (Exception ignore) { M_log.debug(this + ".prepareInlineForContentReview() ***** Unknown Exception ***** " + ignore.getMessage()); addAlert(state, rb.getString("failed")); } finally { m_securityService.popAdvisor(sa); } } /** * Used when students are selecting from a list of previous attachments for their single uploaded file * @author bbailla2 */ private void adjustAttachmentsToSingleUpload(RunData data, SessionState state, Assignment a, List nonInlineAttachments) { if (a == null || a.getContent() == null || a.getContent().getTypeOfSubmission() != 5) { throw new IllegalArgumentException("adjustAttachmentsToSingleUpload called, but the assignment type is not Single Uploaded File"); } if (nonInlineAttachments == null) { throw new IllegalArgumentException("adjustAttachmentsToSingleUpload called, but nonInlineAttachments is null"); } String selection = data.getParameters().get("attachmentSelection"); if ("newAttachment".equals(selection)) { Reference attachment = (Reference) state.getAttribute("newSingleUploadedFile"); if (attachment != null) { List attachments = EntityManager.newReferenceList(); attachments.add(attachment); state.setAttribute(ATTACHMENTS, attachments); state.removeAttribute("newSingleUploadedFile"); state.removeAttribute(VIEW_SUBMISSION_TEXT); } // ^ if attachment is null, we don't care - checkSubmissionTextAttachmentInput() handles that for us } else { //they selected a previous attachment. selection represents an index in the nonInlineAttachments list boolean error = false; int index = -1; try { //get the selected attachment index = Integer.parseInt(selection); if (nonInlineAttachments.size() <= index) { error = true; } } catch (NumberFormatException nfe) { error = true; } if (error) { M_log.warn("adjustAttachmentsToSingleUpload() - couldn't parse the selected index as an integer, or the selected index wasn't in the range of attachment indices"); //checkSubmissionTextAttachmentInput() handles the alert message for us } else { Reference attachment = (Reference) nonInlineAttachments.get(index); //remove all the attachments from the state and add the selected one back for resubmission List attachments = (List) state.getAttribute(ATTACHMENTS); attachments.clear(); attachments.add(attachment); } } } private void checkSubmissionTextAttachmentInput(RunData data, SessionState state, Assignment a, String text) { // SAK-26329 - determine if the submission has text --bbailla2 boolean textIsEmpty = isHtmlEmpty(text); if (a != null) { // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION) { // for the inline only submission if (textIsEmpty) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION) { // for the attachment only submission List v = getNonInlineAttachments(state, a); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION) { // for the single uploaded file only submission List v = getNonInlineAttachments(state, a); if ((v == null) || (v.size() != 1)) { addAlert(state, rb.getString("youmust8")); } } else { // for the inline and attachment submission / other submission types // There must be at least one thing submitted: inline text or at least one attachment List v = getNonInlineAttachments(state, a); if (textIsEmpty && (v == null || v.size() == 0)) { addAlert(state, rb.getString("youmust2")); } } } } /** * When using content review, inline text gets turned into an attachment. This method returns all the attachments that do not represent inline text * @author bbailla2 */ private List getNonInlineAttachments(SessionState state, Assignment a) { List attachments = (List) state.getAttribute(ATTACHMENTS); List nonInlineAttachments = new ArrayList(); nonInlineAttachments.addAll(attachments); if (a.getContent().getAllowReviewService()) { Iterator itAttachments = attachments.iterator(); while (itAttachments.hasNext()) { Object next = itAttachments.next(); if (next instanceof Reference) { Reference attachment = (Reference) next; if ("true".equals(attachment.getProperties().getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { nonInlineAttachments.remove(attachment); } } } } return nonInlineAttachments; } // SAK-26329 /** * Parses html and determines whether it contains printable characters. * @author bbailla2 */ private boolean isHtmlEmpty(String html) { return html == null ? true : FormattedText.stripHtmlFromText(html, false, true).isEmpty(); } /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // SAK-23817 if the instructor submitted on behalf of the student, go back to Assignment List by Student String fromView = (String) state.getAttribute(FROM_VIEW); if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } else { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { initializeAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot_addAssignment")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doNew_Assignment /** * Action is to show the reorder assignment screen */ public void doReorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // this insures the default order is loaded into the reordering tool state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING))) { state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot19")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doReorder /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentRef = params.getString("assignmentId"); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); String order = params.getString(NEW_ASSIGNMENT_ORDER); state.setAttribute(NEW_ASSIGNMENT_ORDER, order); String groupAssignment = params.getString(NEW_ASSIGNMENT_GROUP_SUBMIT); state.setAttribute( NEW_ASSIGNMENT_GROUP_SUBMIT, (groupAssignment == null ? "0": "1")); if (title == null || title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } else if (sameAssignmentTitleInContext(assignmentRef, title, (String) state.getAttribute(STATE_CONTEXT_STRING))) { // assignment title already exist addAlert(state, rb.getFormattedMessage("same_assignment_title", new Object[]{title})); } // open time Time openTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, "newassig.opedat"); // visible time if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { if (params.get("allowVisibleDateToggle") == null) { state.setAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE, true); } else { Time visibleTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN, "newassig.visdat"); } } // due time Time dueTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, "gen.duedat"); // show alert message when due date is in past. Remove it after user confirms the choice. if (dueTime != null && dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null && validify) { addAlert(state, rb.getString("assig4")); } if (openTime != null && dueTime != null && !dueTime.after(openTime)) { addAlert(state, rb.getString("assig3")); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true)); // close time Time closeTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, "date.closedate"); if (openTime != null && closeTime != null && !closeTime.after(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (dueTime != null && closeTime != null && closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); Integer submissionType = Integer.valueOf(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE)); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, submissionType); // Skip category if it was never set. Long catInt = Long.valueOf(-1); if(params.getString(NEW_ASSIGNMENT_CATEGORY) != null) catInt = Long.valueOf(params.getString(NEW_ASSIGNMENT_CATEGORY)); state.setAttribute(NEW_ASSIGNMENT_CATEGORY, catInt); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(gradeType)); } //Peer Assessment boolean peerAssessment = false; String r = params.getString(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT); String b; if (r == null){ b = Boolean.FALSE.toString(); }else{ b = Boolean.TRUE.toString(); peerAssessment = true; } state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, b); if(peerAssessment){ //not allowed for group assignments: if("1".equals(groupAssignment)){ addAlert(state, rb.getString("peerassessment.invliadGroupAssignment")); } //do not allow non-electronic assignments if(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION == submissionType){ addAlert(state, rb.getString("peerassessment.invliadSubmissionTypeAssignment")); } if (gradeType != Assignment.SCORE_GRADE_TYPE){ addAlert(state, rb.getString("peerassessment.invliadGradeTypeAssignment")); } Time peerPeriodTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN, "newassig.opedat"); GregorianCalendar peerPeriodMinTimeCal = new GregorianCalendar(); peerPeriodMinTimeCal.setTimeInMillis(closeTime.getTime()); peerPeriodMinTimeCal.add(GregorianCalendar.MINUTE, 10); GregorianCalendar peerPeriodTimeCal = new GregorianCalendar(); peerPeriodTimeCal.setTimeInMillis(peerPeriodTime.getTime()); //peer assessment must complete at a minimum of 10 mins after close time if(peerPeriodTimeCal.before(peerPeriodMinTimeCal)){ addAlert(state, rb.getString("peerassessment.invliadPeriodTime")); } } r = params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL, b); r = params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS, b); if(peerAssessment){ if(params.get(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS) != null && !"".equals(params.get(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS))){ try{ int peerAssessmentNumOfReviews = Integer.parseInt(params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)); if(peerAssessmentNumOfReviews > 0){ state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, Integer.valueOf(peerAssessmentNumOfReviews)); }else{ addAlert(state, rb.getString("peerassessment.invalidNumReview")); } }catch(Exception e){ addAlert(state, rb.getString("peerassessment.invalidNumReview")); } }else{ addAlert(state, rb.getString("peerassessment.specifyNumReview")); } } String peerAssessmentInstructions = processFormattedTextFromBrowser(state, params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS), true); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS, peerAssessmentInstructions); //REVIEW SERVICE r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); // set whether we use the review service or not if (r == null) b = Boolean.FALSE.toString(); else { b = Boolean.TRUE.toString(); if (state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE).equals(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)) { //can't use content-review with non-electronic submissions addAlert(state, rb.getFormattedMessage("review.switch.ne.1", contentReviewService.getServiceName())); } } state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b); //set whether students can view the review service results r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b); //set submit options r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); if(r == null || (!NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD.equals(r) && !NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION.equals(r))) r = NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE; state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO, r); //set originality report options r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); if(r == null || !NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE.equals(r)) r = NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY; state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO, r); //set check repository options: r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN, b); r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET, b); r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB, b); r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION, b); //exclude bibliographic materials: r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC, b); //exclude quoted materials: r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED, b); //exclude small matches r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES, b); //exclude type: //only options are 0=none, 1=words, 2=percentages r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE); if(!"0".equals(r) && !"1".equals(r) && !"2".equals(r)){ //this really shouldn't ever happen (unless someone's messing with the parameters) r = "0"; } state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE, r); //exclude value if(!"0".equals(r)){ r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE); try{ int rInt = Integer.parseInt(r); if(rInt < 0 || rInt > 100){ addAlert(state, rb.getString("review.exclude.matches.value_error")); } }catch (Exception e) { addAlert(state, rb.getString("review.exclude.matches.value_error")); } state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE, r); }else{ state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE, "1"); } // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null || state.getAttribute(ADDITIONAL_CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } if (params.getString(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE) != null && params.getString(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, params.getString(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtils.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments == null || attachments.isEmpty()) { // read from vm file String[] attachmentIds = data.getParameters().getStrings("attachments"); if (attachmentIds != null && attachmentIds.length != 0) { attachments = new ArrayList(); for (int i= 0; i<attachmentIds.length;i++) { attachments.add(EntityManager.newReference(attachmentIds[i])); } } } state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); if (validify) { if ((description == null) || (description.length() == 0) || ("<br/>".equals(description)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if ("groups".equals(range)) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } // check groups for duplicate members here if ("1".equals(params.getString(NEW_ASSIGNMENT_GROUP_SUBMIT))) { Collection<String> _dupUsers = usersInMultipleGroups(state, "groups".equals(range),("groups".equals(range) ? data.getParameters().getStrings("selectedGroups") : null), false, null); if (_dupUsers.size() > 0) { StringBuilder _sb = new StringBuilder(rb.getString("group.user.multiple.warning") + " "); Iterator<String> _it = _dupUsers.iterator(); if (_it.hasNext()) _sb.append(_it.next()); while (_it.hasNext()) _sb.append(", " + _it.next()); addAlert(state, _sb.toString()); M_log.warn(this + ":post_save_assignment at least one user in multiple groups."); } } // allow resubmission numbers if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params Time resubmitCloseTime = readAllowResubmitParams(params, state, null); if (resubmitCloseTime != null) { // check the date is valid if (openTime != null && ! resubmitCloseTime.after(openTime)) { addAlert(state, rb.getString("acesubdea6")); } } } else if (!Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION).equals(state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE))) { /* * SAK-26640: If the instructor switches to non-electronic by mistake, the resubmissions settings should persist so they can be easily retrieved. * So we only reset resubmit params for electronic assignments. */ resetAllowResubmitParams(state); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } // release grade notification option String releaseGradeOption = params.getString(ASSIGNMENT_RELEASEGRADE_NOTIFICATION); if (releaseGradeOption != null) { state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, releaseGradeOption); } // release resubmission notification option String releaseResubmissionOption = params.getString(ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION); if (releaseResubmissionOption != null){ state.setAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, releaseResubmissionOption); } // read inputs for supplement items setNewAssignmentParametersSupplementItems(validify, state, params); if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of point grade assignment, user must specify maximum grade point addAlert(state, rb.getString("plespethe3")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } } } // setNewAssignmentParameters /** * check to see whether there is already an assignment with the same title in the site * @param assignmentRef * @param title * @param contextString * @return */ private boolean sameAssignmentTitleInContext(String assignmentRef, String title, String contextString) { boolean rv = false; // in the student list view of assignments Iterator assignments = AssignmentService.getAssignmentsForContext(contextString); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); if (assignmentRef == null || !assignmentRef.equals(a.getReference())) { // don't do self-compare String aTitle = a.getTitle(); if (aTitle != null && aTitle.length() > 0 && title.equals(aTitle)) { //further check whether the assignment is marked as deleted or not String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted != null && !Boolean.TRUE.toString().equalsIgnoreCase(deleted)) { rv = true; } } } } return rv; } /** * read inputs for supplement items * @param validify * @param state * @param params */ private void setNewAssignmentParametersSupplementItems(boolean validify, SessionState state, ParameterParser params) { /********************* MODEL ANSWER ITEM *********************/ String modelAnswer_to_delete = StringUtils.trimToNull(params.getString("modelanswer_to_delete")); if (modelAnswer_to_delete != null) { state.setAttribute(MODELANSWER_TO_DELETE, modelAnswer_to_delete); } String modelAnswer_text = StringUtils.trimToNull(params.getString("modelanswer_text")); if (modelAnswer_text != null) { state.setAttribute(MODELANSWER_TEXT, modelAnswer_text); } String modelAnswer_showto = StringUtils.trimToNull(params.getString("modelanswer_showto")); if (modelAnswer_showto != null) { state.setAttribute(MODELANSWER_SHOWTO, modelAnswer_showto); } if (modelAnswer_text != null || !"0".equals(modelAnswer_showto) || state.getAttribute(MODELANSWER_ATTACHMENTS) != null) { // there is Model Answer input state.setAttribute(MODELANSWER, Boolean.TRUE); if (validify && !"true".equalsIgnoreCase(modelAnswer_to_delete)) { // show alert when there is no model answer input if (modelAnswer_text == null) { addAlert(state, rb.getString("modelAnswer.alert.modelAnswer")); } // show alert when user didn't select show-to option if ("0".equals(modelAnswer_showto)) { addAlert(state, rb.getString("modelAnswer.alert.showto")); } } } else { state.removeAttribute(MODELANSWER); } /**************** NOTE ITEM ********************/ String note_to_delete = StringUtils.trimToNull(params.getString("note_to_delete")); if (note_to_delete != null) { state.setAttribute(NOTE_TO_DELETE, note_to_delete); } String note_text = StringUtils.trimToNull(params.getString("note_text")); if (note_text != null) { state.setAttribute(NOTE_TEXT, note_text); } String note_to = StringUtils.trimToNull(params.getString("note_to")); if (note_to != null) { state.setAttribute(NOTE_SHAREWITH, note_to); } if (note_text != null || !"0".equals(note_to)) { // there is Note Item input state.setAttribute(NOTE, Boolean.TRUE); if (validify && !"true".equalsIgnoreCase(note_to_delete)) { // show alert when there is no note text if (note_text == null) { addAlert(state, rb.getString("note.alert.text")); } // show alert when there is no share option if ("0".equals(note_to)) { addAlert(state, rb.getString("note.alert.to")); } } } else { state.removeAttribute(NOTE); } /****************** ALL PURPOSE ITEM **********************/ String allPurpose_to_delete = StringUtils.trimToNull(params.getString("allPurpose_to_delete")); if ( allPurpose_to_delete != null) { state.setAttribute(ALLPURPOSE_TO_DELETE, allPurpose_to_delete); } String allPurposeTitle = StringUtils.trimToNull(params.getString("allPurposeTitle")); if (allPurposeTitle != null) { state.setAttribute(ALLPURPOSE_TITLE, allPurposeTitle); } String allPurposeText = StringUtils.trimToNull(params.getString("allPurposeText")); if (allPurposeText != null) { state.setAttribute(ALLPURPOSE_TEXT, allPurposeText); } if (StringUtils.trimToNull(params.getString("allPurposeHide")) != null) { state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(params.getString("allPurposeHide"))); } if (StringUtils.trimToNull(params.getString("allPurposeShowFrom")) != null) { state.setAttribute(ALLPURPOSE_SHOW_FROM, Boolean.valueOf(params.getString("allPurposeShowFrom"))); // allpurpose release time putTimeInputInState(params, state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, "date.allpurpose.releasedate"); } else { state.removeAttribute(ALLPURPOSE_SHOW_FROM); } if (StringUtils.trimToNull(params.getString("allPurposeShowTo")) != null) { state.setAttribute(ALLPURPOSE_SHOW_TO, Boolean.valueOf(params.getString("allPurposeShowTo"))); // allpurpose retract time putTimeInputInState(params, state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, "date.allpurpose.retractdate"); } else { state.removeAttribute(ALLPURPOSE_SHOW_TO); } String siteId = (String)state.getAttribute(STATE_CONTEXT_STRING); List<String> accessList = new ArrayList<String>(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId)); Set<Role> roles = realm.getRoles(); for(Iterator iRoles = roles.iterator(); iRoles.hasNext();) { // iterator through roles first Role role = (Role) iRoles.next(); if (params.getString("allPurpose_" + role.getId()) != null) { accessList.add(role.getId()); } else { // if the role is not selected, iterate through the users with this role Set userIds = realm.getUsersHasRole(role.getId()); for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); if (params.getString("allPurpose_" + userId) != null) { accessList.add(userId); } } } } } catch (Exception e) { M_log.warn(this + ":setNewAssignmentParameters" + e.toString() + "error finding authzGroup for = " + siteId); } state.setAttribute(ALLPURPOSE_ACCESS, accessList); if (allPurposeTitle != null || allPurposeText != null || (accessList != null && !accessList.isEmpty()) || state.getAttribute(ALLPURPOSE_ATTACHMENTS) != null) { // there is allpupose item input state.setAttribute(ALLPURPOSE, Boolean.TRUE); if (validify && !"true".equalsIgnoreCase(allPurpose_to_delete)) { if (allPurposeTitle == null) { // missing title addAlert(state, rb.getString("allPurpose.alert.title")); } if (allPurposeText == null) { // missing text addAlert(state, rb.getString("allPurpose.alert.text")); } if (accessList == null || accessList.isEmpty()) { // missing access choice addAlert(state, rb.getString("allPurpose.alert.access")); } } } else { state.removeAttribute(ALLPURPOSE); } } /** * read time input and assign it to state attributes * @param params * @param state * @param monthString * @param dayString * @param yearString * @param hourString * @param minString * @param invalidBundleMessage * @return */ Time putTimeInputInState(ParameterParser params, SessionState state, String monthString, String dayString, String yearString, String hourString, String minString, String invalidBundleMessage) { int month = (Integer.valueOf(params.getString(monthString))).intValue(); state.setAttribute(monthString, Integer.valueOf(month)); int day = (Integer.valueOf(params.getString(dayString))).intValue(); state.setAttribute(dayString, Integer.valueOf(day)); int year = (Integer.valueOf(params.getString(yearString))).intValue(); state.setAttribute(yearString, Integer.valueOf(year)); int hour = (Integer.valueOf(params.getString(hourString))).intValue(); state.setAttribute(hourString, Integer.valueOf(hour)); int min = (Integer.valueOf(params.getString(minString))).intValue(); state.setAttribute(minString, Integer.valueOf(min)); // validate date if (!Validator.checkDate(day, month, year)) { addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString(invalidBundleMessage)})); } return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0); } /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); // save user input saveReviewGradeForm(data, state, "read"); } public void doShow_submission_assignment_instruction_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true)); // save user input saveReviewGradeForm(data, state, "read"); } /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment post_save_assignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Map.Entry<String, ? extends Object> entry : helperParms.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Map.Entry<String, ? extends Object> entry : helperParms.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Map.Entry<String, ? extends Object> entry : helperParms.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } // doHelp_activity /** * post or save assignment */ private void post_save_assignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && "post".equals(postOrSave); // assignment old title String aOldTitle = null; // assignment old access setting String aOldAccessString = null; // assignment old group setting Collection aOldGroups = null; // assignment old open date setting Time oldOpenTime = null; // assignment old due date setting Time oldDueTime = null; // assignment old visible date setting Time oldVisibleTime = null; // assignment old close date setting Time oldCloseTime = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); // whether this is an editing which changes non-point graded assignment to point graded assignment? boolean bool_change_from_non_point = false; // whether there is a change in the assignment resubmission choice boolean bool_change_resubmit_option = false; if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = editAssignmentContent(assignmentContentId, "post_save_assignment", state, true); bool_change_from_non_point = change_from_non_point(state, assignmentId, assignmentContentId, ac); // Assignment AssignmentEdit a = editAssignment(assignmentId, "post_save_assignment", state, true); bool_change_resubmit_option = change_resubmit_option(state, a); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER); // open time Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // visible time Time visibleTime = null; if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { if (state.getAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE) == null) visibleTime = getTimeFromState(state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } // due time Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); } // sections String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); boolean isGroupSubmit = "1".equals((String)state.getAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT)); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; boolean hideDueDate = "true".equals((String) state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; long category = state.getAttribute(NEW_ASSIGNMENT_CATEGORY) != null ? ((Long) state.getAttribute(NEW_ASSIGNMENT_CATEGORY)).longValue() : -1; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; // SAK-17606 String checkAnonymousGrading = state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING) != null? (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING):""; // SAK-26319 - we no longer clear the resubmit number for non electronic submissions; the instructor may switch to another submission type in the future --bbailla2 //Peer Assessment boolean usePeerAssessment = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT)); Time peerPeriodTime = getTimeFromState(state, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); boolean peerAssessmentAnonEval = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL)); boolean peerAssessmentStudentViewReviews = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS)); int peerAssessmentNumReviews = 0; if(state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS) != null){ peerAssessmentNumReviews = ((Integer) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)).intValue(); } String peerAssessmentInstructions = (String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); //Review Service boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); String submitReviewRepo = (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); String generateOriginalityReport = (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); boolean checkTurnitin = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN)); boolean checkInternet = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET)); boolean checkPublications = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB)); boolean checkInstitution = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION)); //exclude bibliographic materials boolean excludeBibliographic = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC)); //exclude quoted materials boolean excludeQuoted = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED)); //exclude small matches boolean excludeSmallMatches = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES)); //exclude type 0=none, 1=words, 2=percentages int excludeType = 0; int excludeValue = 1; if(excludeSmallMatches){ try{ excludeType = Integer.parseInt((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE)); if(excludeType != 0 && excludeType != 1 && excludeType != 2){ excludeType = 0; } }catch (Exception e) { //Numberformatexception } //exclude value try{ excludeValue = Integer.parseInt((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE)); if(excludeValue < 0 || excludeValue > 100){ excludeValue = 1; } }catch (Exception e) { //Numberformatexception } } // the attachments List attachments = (List) state.getAttribute(NEW_ASSIGNMENT_ATTACHMENT); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new ArrayList(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); if (Assignment.AssignmentAccess.GROUPED.toString().equals(range) && (groupChoice == null || groupChoice.size() == 0)) { // show alert if no group is selected for the group access assignment addAlert(state, rb.getString("java.alert.youchoosegroup")); } else if (groupChoice != null) { for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); Group _aGroup = site.getGroup(groupId); if (_aGroup != null) groups.add(_aGroup); } } } catch (Exception e) { M_log.warn(this + ":post_save_assignment " + e.getMessage()); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); aOldAccessString = a.getAccess().toString(); aOldGroups = a.getGroups(); // old open time oldOpenTime = a.getOpenTime(); // old due time oldDueTime = a.getDueTime(); // old visible time oldVisibleTime = a.getVisibleTime(); // old close time oldCloseTime = a.getCloseTime(); //assume creating the assignment with the content review service will be successful state.setAttribute("contentReviewSuccess", Boolean.TRUE); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, a.getReference(), title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments, submitReviewRepo, generateOriginalityReport, checkTurnitin, checkInternet, checkPublications, checkInstitution, excludeBibliographic, excludeQuoted, excludeType, excludeValue, openTime, dueTime, closeTime, hideDueDate); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); Time resubmitCloseTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); // SAK-17606 editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post, resubmitCloseTime, checkAnonymousGrading); //TODO: ADD_DUE_DATE // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // the release grade notification option if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); } if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) != null){ aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, visibleTime, openTime, dueTime, closeTime, enableCloseDate, section, range, groups, isGroupSubmit, usePeerAssessment,peerPeriodTime, peerAssessmentAnonEval, peerAssessmentStudentViewReviews, peerAssessmentNumReviews, peerAssessmentInstructions); if (post) { // we need to update the submission if (bool_change_from_non_point || bool_change_resubmit_option) { List submissions = AssignmentService.getSubmissions(a); if (submissions != null && submissions.size() >0) { // assignment already exist and with submissions for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next(); AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "post_save_assignment", state); if (sEdit != null) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (bool_change_from_non_point) { // set the grade to be empty for now sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradedBy(null); sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (bool_change_resubmit_option) { String aAllowResubmitNumber = a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (aAllowResubmitNumber == null || aAllowResubmitNumber.length() == 0 || "0".equals(aAllowResubmitNumber)) { sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } else { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME)); } } AssignmentService.commitEdit(sEdit); } } } } } //if // save supplement item information saveAssignmentSupplementItem(state, params, siteId, a); // set default sorting setDefaultSort(state); if (state.getAttribute(STATE_MESSAGE) == null) { // set the state navigation variables state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); // integrate with other tools only if the assignment is posted if (post) { // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook try { initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range, category); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); M_log.warn(this + ":post_save_assignment " + e.getMessage()); } // log event if there is a title update if (!aOldTitle.equals(title)) { // title changed m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_TITLE, assignmentId, true)); } if (!aOldAccessString.equals(a.getAccess().toString())) { // site-group access setting changed m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_ACCESS, assignmentId, true)); } else { Collection aGroups = a.getGroups(); if (!(aOldGroups == null && aGroups == null) && !(aOldGroups != null && aGroups != null && aGroups.containsAll(aOldGroups) && aOldGroups.containsAll(aGroups))) { //group changed m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_ACCESS, assignmentId, true)); } } if (oldOpenTime != null && !oldOpenTime.equals(a.getOpenTime())) { // open time change m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_OPENDATE, assignmentId, true)); } if (oldDueTime != null && !oldDueTime.equals(a.getDueTime())) { // due time change m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_DUEDATE, assignmentId, true)); } if (oldCloseTime != null && !oldCloseTime.equals(a.getCloseTime())) { // due time change m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_CLOSEDATE, assignmentId, true)); } } } } // if } // if } // post_save_assignment /** * supplement item related information * @param state * @param params * @param siteId * @param a */ private void saveAssignmentSupplementItem(SessionState state, ParameterParser params, String siteId, AssignmentEdit a) { // assignment supplement items String aId = a.getId(); //model answer if (state.getAttribute(MODELANSWER_TO_DELETE) != null && "true".equals((String) state.getAttribute(MODELANSWER_TO_DELETE))) { // to delete the model answer AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId); if (mAnswer != null) { m_assignmentSupplementItemService.cleanAttachment(mAnswer); m_assignmentSupplementItemService.removeModelAnswer(mAnswer); } } else if (state.getAttribute(MODELANSWER_TEXT) != null) { // edit/add model answer AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId); if (mAnswer == null) { mAnswer = m_assignmentSupplementItemService.newModelAnswer(); m_assignmentSupplementItemService.saveModelAnswer(mAnswer); } mAnswer.setAssignmentId(a.getId()); mAnswer.setText((String) state.getAttribute(MODELANSWER_TEXT)); mAnswer.setShowTo(state.getAttribute(MODELANSWER_SHOWTO) != null ? Integer.parseInt((String) state.getAttribute(MODELANSWER_SHOWTO)) : 0); mAnswer.setAttachmentSet(getAssignmentSupplementItemAttachment(state, mAnswer, MODELANSWER_ATTACHMENTS)); m_assignmentSupplementItemService.saveModelAnswer(mAnswer); } // note if (state.getAttribute(NOTE_TO_DELETE) != null && "true".equals((String) state.getAttribute(NOTE_TO_DELETE))) { // to remove note item AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId); if (nNote != null) m_assignmentSupplementItemService.removeNoteItem(nNote); } else if (state.getAttribute(NOTE_TEXT) != null) { // edit/add private note AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId); if (nNote == null) nNote = m_assignmentSupplementItemService.newNoteItem(); nNote.setAssignmentId(a.getId()); nNote.setNote((String) state.getAttribute(NOTE_TEXT)); nNote.setShareWith(state.getAttribute(NOTE_SHAREWITH) != null ? Integer.parseInt((String) state.getAttribute(NOTE_SHAREWITH)) : 0); nNote.setCreatorId(UserDirectoryService.getCurrentUser().getId()); m_assignmentSupplementItemService.saveNoteItem(nNote); } // all purpose if (state.getAttribute(ALLPURPOSE_TO_DELETE) != null && "true".equals((String) state.getAttribute(ALLPURPOSE_TO_DELETE))) { // to remove allPurpose item AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId); if (nAllPurpose != null) { m_assignmentSupplementItemService.cleanAttachment(nAllPurpose); m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose); m_assignmentSupplementItemService.removeAllPurposeItem(nAllPurpose); } } else if (state.getAttribute(ALLPURPOSE_TITLE) != null) { // edit/add private note AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId); if (nAllPurpose == null) { nAllPurpose = m_assignmentSupplementItemService.newAllPurposeItem(); m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose); } nAllPurpose.setAssignmentId(a.getId()); nAllPurpose.setTitle((String) state.getAttribute(ALLPURPOSE_TITLE)); nAllPurpose.setText((String) state.getAttribute(ALLPURPOSE_TEXT)); boolean allPurposeShowFrom = state.getAttribute(ALLPURPOSE_SHOW_FROM) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_FROM)).booleanValue() : false; boolean allPurposeShowTo = state.getAttribute(ALLPURPOSE_SHOW_TO) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_TO)).booleanValue() : false; boolean allPurposeHide = state.getAttribute(ALLPURPOSE_HIDE) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_HIDE)).booleanValue() : false; nAllPurpose.setHide(allPurposeHide); // save the release and retract dates if (allPurposeShowFrom && !allPurposeHide) { // save release date Time releaseTime = getTimeFromState(state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(releaseTime.getTime()); nAllPurpose.setReleaseDate(cal.getTime()); } else { nAllPurpose.setReleaseDate(null); } if (allPurposeShowTo && !allPurposeHide) { // save retract date Time retractTime = getTimeFromState(state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(retractTime.getTime()); nAllPurpose.setRetractDate(cal.getTime()); } else { nAllPurpose.setRetractDate(null); } nAllPurpose.setAttachmentSet(getAssignmentSupplementItemAttachment(state, nAllPurpose, ALLPURPOSE_ATTACHMENTS)); // clean the access list first if (state.getAttribute(ALLPURPOSE_ACCESS) != null) { // get the access settings List<String> accessList = (List<String>) state.getAttribute(ALLPURPOSE_ACCESS); m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose); Set<AssignmentAllPurposeItemAccess> accessSet = new HashSet<AssignmentAllPurposeItemAccess>(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId)); Set<Role> roles = realm.getRoles(); for(Iterator iRoles = roles.iterator(); iRoles.hasNext();) { // iterator through roles first Role r = (Role) iRoles.next(); if (accessList.contains(r.getId())) { AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess(); access.setAccess(r.getId()); access.setAssignmentAllPurposeItem(nAllPurpose); m_assignmentSupplementItemService.saveAllPurposeItemAccess(access); accessSet.add(access); } else { // if the role is not selected, iterate through the users with this role Set userIds = realm.getUsersHasRole(r.getId()); for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); if (accessList.contains(userId)) { AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess(); access.setAccess(userId); access.setAssignmentAllPurposeItem(nAllPurpose); m_assignmentSupplementItemService.saveAllPurposeItemAccess(access); accessSet.add(access); } } } } } catch (Exception e) { M_log.warn(this + ":post_save_assignment " + e.toString() + "error finding authzGroup for = " + siteId); } nAllPurpose.setAccessSet(accessSet); } m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose); } } private Set<AssignmentSupplementItemAttachment> getAssignmentSupplementItemAttachment(SessionState state, AssignmentSupplementItemWithAttachment mItem, String attachmentString) { Set<AssignmentSupplementItemAttachment> sAttachments = new HashSet<AssignmentSupplementItemAttachment>(); List<String> attIdList = m_assignmentSupplementItemService.getAttachmentListForSupplementItem(mItem); if (state.getAttribute(attachmentString) != null) { List currentAttachments = (List) state.getAttribute(attachmentString); for (Iterator aIterator = currentAttachments.iterator(); aIterator.hasNext();) { Reference attRef = (Reference) aIterator.next(); String attRefId = attRef.getReference(); // if the attachment is not exist, add it into db if (!attIdList.contains(attRefId)) { AssignmentSupplementItemAttachment mAttach = m_assignmentSupplementItemService.newAttachment(); mAttach.setAssignmentSupplementItemWithAttachment(mItem); mAttach.setAttachmentId(attRefId); m_assignmentSupplementItemService.saveAttachment(mAttach); sAttachments.add(mAttach); } } } return sAttachments; } /** * */ private boolean change_from_non_point(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac) { // whether this is an editing which changes non point_grade type to point grade type? if (StringUtils.trimToNull(assignmentId) != null && StringUtils.trimToNull(assignmentContentId) != null) { // editing if (ac.getTypeOfGrade() != Assignment.SCORE_GRADE_TYPE && ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue() == Assignment.SCORE_GRADE_TYPE) { // changing from non-point grade type to point grade type? return true; } } return false; } /** * whether the resubmit option has been changed * @param state * @param a * @return */ private boolean change_resubmit_option(SessionState state, Entity entity) { if (entity != null) { // editing return propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) || propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } return false; } /** * whether there is a change between state variable and object's property value * @param state * @param entity * @param propertyName * @return */ private boolean propertyValueChanged(SessionState state, Entity entity, String propertyName) { String o_property_value = entity.getProperties().getProperty(propertyName); String n_property_value = state.getAttribute(propertyName) != null? (String) state.getAttribute(propertyName):null; if (o_property_value == null && n_property_value != null || o_property_value != null && n_property_value == null || o_property_value != null && n_property_value != null && !o_property_value.equals(n_property_value)) { // there is a change return true; } return false; } /** * default sorting */ private void setDefaultSort(SessionState state) { state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } /** * Add submission objects if necessary for non-electronic type of assignment * @param state * @param a */ private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a) { // create submission object for those user who doesn't have one yet for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId); if (submission != null) { submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } } catch (Exception e) { M_log.warn(this + ":addRemoveSubmissionsForNonElectronicAssignment " + e.toString() + "error adding submission for userId = " + userId); } } // remove submission object for those who no longer in the site for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); String submissionRef = null; // TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;) { AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next(); if (userId.equals(submission.getSubmitterId())) { submissionRef = submission.getReference(); } } if (submissionRef != null) { AssignmentSubmissionEdit submissionEdit = editSubmission(submissionRef, "addRemoveSubmissionsForNonElectronicAssignment", state); if (submissionEdit != null) { try { AssignmentService.removeSubmission(submissionEdit); } catch (PermissionException e) { addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{submissionEdit.getReference()})); M_log.warn(this + ":deleteAssignmentObjects " + e.getMessage() + " " + submissionEdit.getReference()); } } } } } private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range, long category) { GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService"); String context = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean gradebookExists = isGradebookDefined(); // only if the gradebook is defined if (gradebookExists) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); String aReference = a.getReference(); String addUpdateRemoveAssignment = "remove"; if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if integrate with Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && ("groups".equals(range))) { // if grouped assignment is not allowed to add into Gradebook addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = a.getReference(); AssignmentEdit aEdit = editAssignment(a.getReference(), "initINtegrateWithGradebook", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category); } else { if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD; } else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { addUpdateRemoveAssignment = "update"; } if (!"remove".equals(addUpdateRemoveAssignment) && gradeType == 3) { try { integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null, category); // add all existing grades, if any, into Gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", category); // if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook if (StringUtils.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment)) { // if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid); } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); M_log.warn(this + ":initIntegrateWithGradebook " + nE.getMessage()); } } else { integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category); } } } else { // need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid); } } } private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookExternalAssessmentService gExternal, String gradebookUid) { boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); if (isExternalAssignmentDefined) { // iterate through all assignments currently in the site, see if any is associated with this GB entry Iterator i = AssignmentService.getAssignmentsForContext(context); boolean found = false; while (!found && i.hasNext()) { Assignment aI = (Assignment) i.next(); String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference)) { found = true; } } // so if none of the assignment in this site is associated with the entry, remove the entry if (!found) { gExternal.removeExternalAssessment(gradebookUid, associateGradebookAssignment); } } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { // whether the assignment's title or open date has been updated boolean updatedTitle = false; boolean updatedOpenDate = false; boolean updateAccess = false; String openDateAnnounced = StringUtils.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED)); String openDateAnnouncementId = StringUtils.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID)); if (openDateAnnounced != null && openDateAnnouncementId != null) { AnnouncementMessage message = null; try { message = channel.getAnnouncementMessage(openDateAnnouncementId); if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/ { updatedTitle = true; } if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/ { updatedOpenDate = true; } if (!message.getAnnouncementHeader().getAccess().equals(a.getAccess())) { updateAccess = true; } else if (a.getAccess() == Assignment.AssignmentAccess.GROUPED) { Collection<String> assnGroups = a.getGroups(); Collection<String> anncGroups = message.getAnnouncementHeader().getGroups(); if (!assnGroups.equals(anncGroups)) { updateAccess = true; } } } catch (IdUnusedException e) { M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage()); } catch (PermissionException e) { M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage()); } if (updateAccess && message != null) { try { // if the access level has changed in assignment, remove the original announcement channel.removeAnnouncementMessage(message.getId()); } catch (PermissionException e) { M_log.warn(this + ":integrateWithAnnouncement PermissionException for remove message id=" + message.getId() + " for assignment id=" + a.getId() + " " + e.getMessage()); } } } // need to create announcement message if assignment is added or assignment has been updated if (openDateAnnounced == null || updatedTitle || updatedOpenDate || updateAccess) { try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); if (message != null) { AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); // add assignment id into property, to facilitate assignment lookup in Annoucement tool message.getPropertiesEdit().addProperty("assignmentReference", a.getReference()); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getFormattedMessage("assig6", new Object[]{title})); } else { // updated title header.setSubject(/* subject */rb.getFormattedMessage("assig5", new Object[]{title})); } if (updatedOpenDate) { // revised assignment open date message.setBody(/* body */rb.getFormattedMessage("newope", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()})); } else { // assignment open date message.setBody(/* body */rb.getFormattedMessage("opedat", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()})); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new ArrayList(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log M_log.warn(this + ":integrateWithAnnouncement " + exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, m_notificationService.NOTI_NONE); } // commit related properties into Assignment object AssignmentEdit aEdit = editAssignment(a.getReference(), "integrateWithAnnouncement", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } } catch (PermissionException ee) { M_log.warn(this + ":IntegrateWithAnnouncement " + rb.getString("cannotmak")); } } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { // Integrate with Sakai calendar tool Calendar c = (Calendar) state.getAttribute(CALENDAR); integrateWithCalendarTool(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit, c, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); // Integrate with additional calendar tool if deployed. Calendar additionalCal = (Calendar) state.getAttribute(ADDITIONAL_CALENDAR); if (additionalCal != null){ integrateWithCalendarTool(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit, additionalCal, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_ADDITIONAL_CALENDAR_EVENT_ID); } } // Checks to see if due date event in assignment properties exists on the calendar. // If so, remove it and then add a new due date event to the calendar. Then update assignment property // with new event id. private void integrateWithCalendarTool(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit, Calendar c, String dueDateProperty) { if (c == null){ return; } String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(dueDateProperty); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { M_log.warn(this + ":integrateWithCalendarTool The old event has been deleted: event id=" + oldEventId + ". " + c.getClass().getName()); } catch (PermissionException ee) { M_log.warn(this + ":integrateWithCalendarTool You do not have the permission to view the schedule event id= " + oldEventId + ". " + c.getClass().getName()); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found){ removeOldEvent(title, c, e); } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { updateAssignmentWithEventId(state, a, title, dueTime, c, dueDateProperty); } } /** * Add event to calendar and then persist the event id to the assignment properties * @param state * @param a AssignmentEdit * @param title Event title * @param dueTime Assignment due date/time * @param c Calendar * @param dueDateProperty Property name specifies the appropriate calendar */ private void updateAssignmentWithEventId(SessionState state, AssignmentEdit a, String title, Time dueTime, Calendar c, String dueDateProperty) { CalendarEvent e; // commit related properties into Assignment object AssignmentEdit aEdit = editAssignment(a.getReference(), "updateAssignmentWithEventId", state, false); if (aEdit != null) { try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new ArrayList(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); Group _aGroup = site.getGroup(groupRef); if (_aGroup != null) eGroups.add(_aGroup); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("gen.due") + " " + title, /* description */rb.getFormattedMessage("assign_due_event_desc", new Object[]{title, dueTime.toStringLocalFull()}), /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */null /*SAK-27919 do not include assignment attachments.*/); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(dueDateProperty, e.getId()); // edit the calendar object and add an assignment id field addAssignmentIdToCalendar(a, c, e); } // TODO do we care if the event is null? } catch (IdUnusedException ee) { M_log.warn(this + ":updateAssignmentWithEventId " + ee.getMessage()); } catch (PermissionException ee) { M_log.warn(this + ":updateAssignmentWithEventId " + rb.getString("cannotfin1")); } catch (Exception ee) { M_log.warn(this + ":updateAssignmentWithEventId " + ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } } // Persist the assignment id to the calendar private void addAssignmentIdToCalendar(AssignmentEdit a, Calendar c, CalendarEvent e) throws IdUnusedException, PermissionException,InUseException { if (c!= null && e != null && a != null){ CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR); edit.setField(AssignmentConstants.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId()); c.commitEvent(edit); } } // Remove an existing event from the calendar private void removeOldEvent(String title, Calendar c, CalendarEvent e) { // remove the found old event if (c != null && e != null){ try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { M_log.warn(this + ":removeOldEvent " + rb.getFormattedMessage("cannotrem", new Object[]{title})); } catch (InUseException ee) { M_log.warn(this + ":removeOldEvent " + rb.getString("somelsis_calendar")); } catch (IdUnusedException ee) { M_log.warn(this + ":removeOldEvent " + rb.getFormattedMessage("cannotfin6", new Object[]{e.getId()})); } } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time visibleTime, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups, boolean isGroupSubmit, boolean usePeerAssessment, Time peerPeriodTime, boolean peerAssessmentAnonEval, boolean peerAssessmentStudentViewReviews, int peerAssessmentNumReviews, String peerAssessmentInstructions) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setVisibleTime(visibleTime); a.setOpenTime(openTime); a.setDueTime(dueTime); a.setGroup(isGroupSubmit); a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } if (Boolean.TRUE.equals(state.getAttribute("contentReviewSuccess"))) { // post the assignment if appropriate a.setDraft(!post); } else { // setup for content review failed, save as a draft a.setDraft(true); } a.setAllowPeerAssessment(usePeerAssessment); a.setPeerAssessmentPeriod(peerPeriodTime); a.setPeerAssessmentAnonEval(peerAssessmentAnonEval); a.setPeerAssessmentStudentViewReviews(peerAssessmentStudentViewReviews); a.setPeerAssessmentNumReviews(peerAssessmentNumReviews); a.setPeerAssessmentInstructions(peerAssessmentInstructions); try { // SAK-26349 - clear group selection before changing, otherwise it can result in a PermissionException a.clearGroupAccess(); if ("site".equals(range)) { a.setAccess(Assignment.AssignmentAccess.SITE); } else if ("groups".equals(range)) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot_addAssignmentContent")); M_log.warn(this + ":commitAssignmentEdit " + rb.getString("youarenot_addAssignmentContent") + e.getMessage()); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } if (a.isGroup()) { Collection<String> _dupUsers = usersInMultipleGroups(a); if (_dupUsers.size() > 0) { addAlert(state, rb.getString("group.user.multiple.error")); M_log.warn(this + ":post_save_assignment at least one user in multiple groups."); } } } private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit, boolean post, Time closeTime, String checkAnonymousGrading) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); // SAK-17606 aPropertiesEdit.addProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, checkAnonymousGrading); if (post && addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference()); } // allow resubmit number and default assignment resubmit closeTime (dueTime) if (allowResubmitNumber != null && closeTime != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else if (allowResubmitNumber == null || allowResubmitNumber.length() == 0 || "0".equals(allowResubmitNumber)) { aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String assignmentRef, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments, String submitReviewRepo, String generateOriginalityReport, boolean checkTurnitin, boolean checkInternet, boolean checkPublications, boolean checkInstitution, boolean excludeBibliographic, boolean excludeQuoted, int excludeType, int excludeValue, Time openTime, Time dueTime, Time closeTime, boolean hideDueDate) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setHideDueDate(hideDueDate); ac.setTypeOfSubmission(submissionType); ac.setAllowReviewService(useReviewService); ac.setAllowStudentViewReport(allowStudentViewReport); ac.setSubmitReviewRepo(submitReviewRepo); ac.setGenerateOriginalityReport(generateOriginalityReport); ac.setCheckInstitution(checkInstitution); ac.setCheckInternet(checkInternet); ac.setCheckPublications(checkPublications); ac.setCheckTurnitin(checkTurnitin); ac.setExcludeBibliographic(excludeBibliographic); ac.setExcludeQuoted(excludeQuoted); ac.setExcludeType(excludeType); ac.setExcludeValue(excludeValue); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); M_log.warn(this + ":commitAssignmentContentEdit " + e.getMessage()); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); if (attachments != null) { // add each attachment Iterator it = EntityManager.newReferenceList(attachments).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } } state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false)); // commit the changes AssignmentService.commitEdit(ac); if(ac.getAllowReviewService()){ if (!createTIIAssignment(ac, assignmentRef, openTime, dueTime, closeTime, state)) { state.setAttribute("contentReviewSuccess", Boolean.FALSE); } } } public boolean createTIIAssignment(AssignmentContentEdit assign, String assignmentRef, Time openTime, Time dueTime, Time closeTime, SessionState state) { Map opts = new HashMap(); opts.put("submit_papers_to", assign.getSubmitReviewRepo()); opts.put("report_gen_speed", assign.getGenerateOriginalityReport()); opts.put("institution_check", assign.isCheckInstitution() ? "1" : "0"); opts.put("internet_check", assign.isCheckInternet() ? "1" : "0"); opts.put("journal_check", assign.isCheckPublications() ? "1" : "0"); opts.put("s_paper_check", assign.isCheckTurnitin() ? "1" : "0"); opts.put("s_view_report", assign.getAllowStudentViewReport() ? "1" : "0"); if(ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true)){ //we don't want to pass parameters if the user didn't get an option to set it opts.put("exclude_biblio", assign.isExcludeBibliographic() ? "1" : "0"); } if(ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true)){ //we don't want to pass parameters if the user didn't get an option to set it opts.put("exclude_quoted", assign.isExcludeQuoted() ? "1" : "0"); } if((assign.getExcludeType() == 1 || assign.getExcludeType() == 2) && assign.getExcludeValue() >= 0 && assign.getExcludeValue() <= 100){ opts.put("exclude_type", Integer.toString(assign.getExcludeType())); opts.put("exclude_value", Integer.toString(assign.getExcludeValue())); } opts.put("late_accept_flag", "1"); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern("yyyy-MM-dd HH:mm:ss"); opts.put("dtstart", dform.format(openTime.getTime())); opts.put("dtdue", dform.format(dueTime.getTime())); //opts.put("dtpost", dform.format(closeTime.getTime())); opts.put("title", assign.getTitle()); opts.put("instructions", assign.getInstructions()); if(assign.getAttachments() != null && assign.getAttachments().size() > 0){ List<String> attachments = new ArrayList<String>(); for(Reference ref : assign.getAttachments()){ attachments.add(ref.getReference()); } opts.put("attachments", attachments); } try { contentReviewService.createAssignment(assign.getContext(), assignmentRef, opts); return true; } catch (Exception e) { M_log.error(e); String uiService = ServerConfigurationService.getString("ui.service", "Sakai"); String[] args = new String[]{contentReviewService.getServiceName(), uiService}; state.setAttribute("alertMessage", rb.getFormattedMessage("content_review.error.createAssignment", args)); } return false; } /** * reorderAssignments */ private void reorderAssignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List assignments = prepPage(state); Iterator it = assignments.iterator(); while (it.hasNext()) // reads and writes the parameter for default ordering { Assignment a = (Assignment) it.next(); String assignmentid = a.getId(); String assignmentposition = params.getString("position_" + assignmentid); SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return function.equals(AssignmentService.SECURE_UPDATE_ASSIGNMENT)?SecurityAdvice.ALLOWED:SecurityAdvice.PASS; } }; try { // put in a security advisor so we can create citationAdmin site without need // of further permissions m_securityService.pushAdvisor(sa); AssignmentEdit ae = editAssignment(assignmentid, "reorderAssignments", state, true); if (ae != null) { ae.setPosition_order(Long.valueOf(assignmentposition).intValue()); AssignmentService.commitEdit(ae); } } catch (Exception e) { M_log.warn(this + ":reorderAssignments : not able to edit assignment " + assignmentid + e.toString()); } finally { // remove advisor m_securityService.popAdvisor(sa); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // reorderAssignments private AssignmentContentEdit editAssignmentContent(String assignmentContentId, String callingFunctionName, SessionState state, boolean allowAdd) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0 && allowAdd) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot_addAssignmentContent")); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + (String) state.getAttribute(STATE_CONTEXT_STRING)); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getFormattedMessage("somelsis_assignmentContent", new Object[]{assignmentContentId})); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } catch (IdUnusedException e) { addAlert(state, rb.getFormattedMessage("cannotfin_assignmentContent", new Object[]{assignmentContentId})); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } catch (PermissionException e) { addAlert(state, rb.getFormattedMessage("youarenot_viewAssignmentContent", new Object[]{assignmentContentId})); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } } return ac; } /** * construct time object based on various state variables * @param state * @param monthString * @param dayString * @param yearString * @param hourString * @param minString * @return */ private Time getTimeFromState(SessionState state, String monthString, String dayString, String yearString, String hourString, String minString) { if (state.getAttribute(monthString) != null || state.getAttribute(dayString) != null || state.getAttribute(yearString) != null || state.getAttribute(hourString) != null || state.getAttribute(minString) != null) { int month = ((Integer) state.getAttribute(monthString)).intValue(); int day = ((Integer) state.getAttribute(dayString)).intValue(); int year = ((Integer) state.getAttribute(yearString)).intValue(); int hour = ((Integer) state.getAttribute(hourString)).intValue(); int min = ((Integer) state.getAttribute(minString)).intValue(); return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0); } else { return null; } } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { post_save_assignment(data, "save"); } // doSave_assignment /** * Action is to reorder assignments */ public void doReorder_assignment(RunData data) { reorderAssignments(data); } // doReorder_assignments /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, true); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); Assignment a = getAssignment(assignmentId, "doView_assignment", state); // get resubmission option into state assignment_resubmission_option_into_state(a, null, state); // assignment read event m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, assignmentId, false)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student // TODO: investigate if this method can be removed --bbailla2 public void doView_submissionReviews(RunData data){ String submissionId = data.getParameters().getString("submissionId"); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String assessorId = data.getParameters().getString("assessorId"); String assignmentId = StringUtils.trimToNull(data.getParameters().getString("assignmentId")); Assignment a = getAssignment(assignmentId, "doEdit_assignment", state); if (submissionId != null && !"".equals(submissionId) && a != null){ //set the page to go to state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); List<PeerAssessmentItem> peerAssessmentItems = assignmentPeerAssessmentService.getPeerAssessmentItemsByAssignmentId(a.getId()); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); List<String> submissionIds = new ArrayList<String>(); if(peerAssessmentItems != null){ for(PeerAssessmentItem item : peerAssessmentItems){ submissionIds.add(item.getSubmissionId()); } } state.setAttribute(USER_SUBMISSIONS, submissionIds); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); state.setAttribute(PEER_ASSESSMENT_ASSESSOR_ID, assessorId); state.setAttribute(STATE_MODE, MODE_STUDENT_REVIEW_EDIT); }else{ addAlert(state, rb.getString("peerassessment.notavailable")); } } // TODO: investigate if this method can be removed --bbailla2 public void doEdit_review(RunData data){ SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtils.trimToNull(params.getString("assignmentId")); Assignment a = getAssignment(assignmentId, "doEdit_assignment", state); if (a != null && a.isPeerAssessmentOpen()){ //set the page to go to state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); String submissionId = null; List<PeerAssessmentItem> peerAssessmentItems = assignmentPeerAssessmentService.getPeerAssessmentItems(a.getId(), UserDirectoryService.getCurrentUser().getId()); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); List<String> submissionIds = new ArrayList<String>(); if(peerAssessmentItems != null){ for(PeerAssessmentItem item : peerAssessmentItems){ if(!item.isSubmitted()){ submissionIds.add(item.getSubmissionId()); } } } if(params.getString("submissionId") != null && submissionIds.contains(params.getString("submissionId"))){ submissionId = StringUtils.trimToNull(params.getString("submissionId")); }else if(submissionIds.size() > 0){ //submission Id wasn't passed in, let's find one for this user //grab the first one: submissionId = submissionIds.get(0); } if(submissionId != null){ state.setAttribute(USER_SUBMISSIONS, submissionIds); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); state.setAttribute(STATE_MODE, MODE_STUDENT_REVIEW_EDIT); }else{ if(peerAssessmentItems != null && peerAssessmentItems.size() > 0){ //student has submitted all their peer reviews, nothing left to review //(student really shouldn't get to this warning) addAlert(state, rb.getString("peerassessment.allSubmitted")); }else{ //wasn't able to find a submission id, throw error addAlert(state, rb.getString("peerassessment.notavailable")); } } }else{ addAlert(state, rb.getString("peerassessment.notavailable")); } } /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtils.trimToNull(params.getString("assignmentId")); if (AssignmentService.allowUpdateAssignment(assignmentId)) { Assignment a = getAssignment(assignmentId, "doEdit_assignment", state); if (a != null) { // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); // for the non_electronice assignment, submissions are auto-generated by the time that assignment is created; // don't need to go through the following checkings. if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // any submitted? boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted() && s.getTimeSubmitted() != null) { anySubmitted = true; } } // any draft submission boolean anyDraft = false; for (;submissions.hasNext() && !anyDraft;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (!s.getSubmitted()) { anyDraft = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getFormattedMessage("hassum", new Object[]{a.getTitle()})); } if (anyDraft) { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order()); if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { putTimePropertiesInState(state, a.getVisibleTime(), NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } putTimePropertiesInState(state, a.getOpenTime(), NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // generate alert when editing an assignment past open date if (a.getOpenTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot20")); } putTimePropertiesInState(state, a.getDueTime(), NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true)); putTimePropertiesInState(state, a.getCloseTime(), NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(a.getContent().getTypeOfSubmission())); state.setAttribute(NEW_ASSIGNMENT_CATEGORY, getAssignmentCategoryAsInt(a)); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE, Boolean.valueOf(a.getContent().getHideDueDate()).toString()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // submission notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // release grade notification option if (properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, properties.getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // put the resubmission option into state assignment_resubmission_option_into_state(a, null, state); // set whether we use peer assessment or not Time peerAssessmentPeriod = a.getPeerAssessmentPeriod(); //check if peer assessment time exist? if not, this could be an old assignment, so just set it //to 10 min after accept until date if(peerAssessmentPeriod == null && a.getCloseTime() != null){ // set the peer period time to be 10 mins after accept until date GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(a.getCloseTime().getTime()); c.add(GregorianCalendar.MINUTE, 10); peerAssessmentPeriod = TimeService.newTime(c.getTimeInMillis()); } if(peerAssessmentPeriod != null){ state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, Boolean.valueOf(a.getAllowPeerAssessment()).toString()); putTimePropertiesInState(state, peerAssessmentPeriod, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL, Boolean.valueOf(a.getPeerAssessmentAnonEval()).toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS, Boolean.valueOf(a.getPeerAssessmentStudentViewReviews()).toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, a.getPeerAssessmentNumReviews()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS, a.getPeerAssessmentInstructions()); } if(!allowPeerAssessment){ state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, false); } // set whether we use the review service or not state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, Boolean.valueOf(a.getContent().getAllowReviewService()).toString()); //set whether students can view the review service results state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, Boolean.valueOf(a.getContent().getAllowStudentViewReport()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO, a.getContent().getSubmitReviewRepo()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO, a.getContent().getGenerateOriginalityReport()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN, Boolean.valueOf(a.getContent().isCheckTurnitin()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET, Boolean.valueOf(a.getContent().isCheckInternet()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB, Boolean.valueOf(a.getContent().isCheckPublications()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION, Boolean.valueOf(a.getContent().isCheckInstitution()).toString()); //exclude bibliographic state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC, Boolean.valueOf(a.getContent().isExcludeBibliographic()).toString()); //exclude quoted state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED, Boolean.valueOf(a.getContent().isExcludeQuoted()).toString()); //exclude type state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE, a.getContent().getExcludeType()); //exclude value state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE,a.getContent().getExcludeValue()); state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); state.setAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT, a.isGroup() ? "1": "0"); // get all supplement item info into state setAssignmentSupplementItemInState(state, a); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } } else { addAlert(state, rb.getString("youarenot6")); } } // doEdit_Assignment public List<String> getSubmissionRepositoryOptions() { List<String> submissionRepoSettings = new ArrayList<String>(); String[] propertyValues = ServerConfigurationService.getStrings("turnitin.repository.setting"); if (propertyValues != null && propertyValues.length > 0) { for (int i=0; i < propertyValues.length; i++) { String propertyVal = propertyValues[i]; if (propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE) || propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION) || propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD)) { submissionRepoSettings.add(propertyVal); } } } // if there are still no valid settings in the list at this point, use the default if (submissionRepoSettings.isEmpty()) { // add all three submissionRepoSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE); submissionRepoSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD); } return submissionRepoSettings; } public List<String> getReportGenOptions() { List<String> reportGenSettings = new ArrayList<String>(); String[] propertyValues = ServerConfigurationService.getStrings("turnitin.report_gen_speed.setting"); if (propertyValues != null && propertyValues.length > 0) { for (int i=0; i < propertyValues.length; i++) { String propertyVal = propertyValues[i]; if (propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE) || propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY)) { reportGenSettings.add(propertyVal); } } } // if there are still no valid settings in the list at this point, use the default if (reportGenSettings.isEmpty()) { // add all three reportGenSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE); reportGenSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY); } return reportGenSettings; } /** * put all assignment supplement item info into state * @param state * @param a */ private void setAssignmentSupplementItemInState(SessionState state, Assignment a) { String assignmentId = a.getId(); // model answer AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(assignmentId); if (mAnswer != null) { if (state.getAttribute(MODELANSWER_TEXT) == null) { state.setAttribute(MODELANSWER_TEXT, mAnswer.getText()); } if (state.getAttribute(MODELANSWER_SHOWTO) == null) { state.setAttribute(MODELANSWER_SHOWTO, String.valueOf(mAnswer.getShowTo())); } if (state.getAttribute(MODELANSWER) == null) { state.setAttribute(MODELANSWER, Boolean.TRUE); } } // get attachments for model answer object putSupplementItemAttachmentInfoIntoState(state, mAnswer, MODELANSWER_ATTACHMENTS); // private notes AssignmentNoteItem mNote = m_assignmentSupplementItemService.getNoteItem(assignmentId); if (mNote != null) { if (state.getAttribute(NOTE) == null) { state.setAttribute(NOTE, Boolean.TRUE); } if (state.getAttribute(NOTE_TEXT) == null) { state.setAttribute(NOTE_TEXT, mNote.getNote()); } if (state.getAttribute(NOTE_SHAREWITH) == null) { state.setAttribute(NOTE_SHAREWITH, String.valueOf(mNote.getShareWith())); } } // all purpose item AssignmentAllPurposeItem aItem = m_assignmentSupplementItemService.getAllPurposeItem(assignmentId); if (aItem != null) { if (state.getAttribute(ALLPURPOSE) == null) { state.setAttribute(ALLPURPOSE, Boolean.TRUE); } if (state.getAttribute(ALLPURPOSE_TITLE) == null) { state.setAttribute(ALLPURPOSE_TITLE, aItem.getTitle()); } if (state.getAttribute(ALLPURPOSE_TEXT) == null) { state.setAttribute(ALLPURPOSE_TEXT, aItem.getText()); } if (state.getAttribute(ALLPURPOSE_HIDE) == null) { state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(aItem.getHide())); } if (state.getAttribute(ALLPURPOSE_SHOW_FROM) == null) { state.setAttribute(ALLPURPOSE_SHOW_FROM, aItem.getReleaseDate() != null); } if (state.getAttribute(ALLPURPOSE_SHOW_TO) == null) { state.setAttribute(ALLPURPOSE_SHOW_TO, aItem.getRetractDate() != null); } if (state.getAttribute(ALLPURPOSE_ACCESS) == null) { Set<AssignmentAllPurposeItemAccess> aSet = aItem.getAccessSet(); List<String> aList = new ArrayList<String>(); for(Iterator<AssignmentAllPurposeItemAccess> aIterator = aSet.iterator(); aIterator.hasNext();) { AssignmentAllPurposeItemAccess access = aIterator.next(); aList.add(access.getAccess()); } state.setAttribute(ALLPURPOSE_ACCESS, aList); } // get attachments for model answer object putSupplementItemAttachmentInfoIntoState(state, aItem, ALLPURPOSE_ATTACHMENTS); } // get the AllPurposeItem and AllPurposeReleaseTime/AllPurposeRetractTime //default to assignment open time Time releaseTime = a.getOpenTime(); // default to assignment close time Time retractTime = a.getCloseTime(); if (aItem != null) { Date releaseDate = aItem.getReleaseDate(); if (releaseDate != null) { // overwrite if there is a release date releaseTime = TimeService.newTime(releaseDate.getTime()); } Date retractDate = aItem.getRetractDate(); if (retractDate != null) { // overwriteif there is a retract date retractTime = TimeService.newTime(retractDate.getTime()); } } putTimePropertiesInState(state, releaseTime, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN); putTimePropertiesInState(state, retractTime, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN); } /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { List ids = new ArrayList(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getFormattedMessage("youarenot_removeAssignment", new Object[]{id})); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids List ids = (List) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); AssignmentEdit aEdit = editAssignment(assignmentId, "doDelete_assignment", state, false); if (aEdit != null) { ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove related event if there is one removeCalendarEvent(state, aEdit, pEdit, title); // remove related announcement if there is one removeAnnouncement(state, pEdit); // we use to check "assignment.delete.cascade.submission" setting. But the implementation now is always remove submission objects when the assignment is removed. // delete assignment and its submissions altogether deleteAssignmentObjects(state, aEdit, true); // remove from Gradebook integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null, -1); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new ArrayList()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset paging information after the assignment been deleted resetPaging(state); } } // doDelete_Assignment /** * private function to remove assignment related announcement * @param state * @param pEdit */ private void removeAnnouncement(SessionState state, ResourcePropertiesEdit pEdit) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { String openDateAnnounced = StringUtils.trimToNull(pEdit.getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED)); String openDateAnnouncementId = StringUtils.trimToNull(pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID)); if (openDateAnnounced != null && openDateAnnouncementId != null) { try { channel.removeMessage(openDateAnnouncementId); } catch (PermissionException e) { M_log.warn(this + ":removeAnnouncement " + e.getMessage()); } } } } /** * private method to remove assignment and related objects * @param state * @param aEdit * @param removeSubmissions Whether or not to remove the submission objects */ private void deleteAssignmentObjects(SessionState state, AssignmentEdit aEdit, boolean removeSubmissions) { if (removeSubmissions) { // if this is non-electronic submission, remove all the submissions List submissions = AssignmentService.getSubmissions(aEdit); if (submissions != null) { for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); AssignmentSubmissionEdit sEdit = editSubmission((s.getReference()), "deleteAssignmentObjects", state); try { AssignmentService.removeSubmission(sEdit); } catch (Exception eee) { // Trapping for InUseException... go ahead and remove them. if (!(eee instanceof InUseException)) { addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{s.getReference()})); M_log.warn(this + ":deleteAssignmentObjects " + eee.getMessage() + " " + s.getReference()); } } } } } AssignmentContent aContent = aEdit.getContent(); if (aContent != null) { try { // remove the assignment content AssignmentContentEdit acEdit = editAssignmentContent(aContent.getReference(), "deleteAssignmentObjects", state, false); if (acEdit != null) AssignmentService.removeAssignmentContent(acEdit); } catch (Exception ee) { addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". "); M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage()); } } try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(aEdit)); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException ee) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage()); } } private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) { String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { // remove the associated calendar event Calendar c = (Calendar) state.getAttribute(CALENDAR); removeCalendarEventFromCalendar(state, aEdit, pEdit, title, c, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); // remove the associated event from the additional calendar Calendar additionalCalendar = (Calendar) state.getAttribute(ADDITIONAL_CALENDAR); removeCalendarEventFromCalendar(state, aEdit, pEdit, title, additionalCalendar, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_ADDITIONAL_CALENDAR_EVENT_ID); } } // Retrieves the calendar event associated with the due date and removes it from the calendar. private void removeCalendarEventFromCalendar(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title, Calendar c, String dueDateProperty) { if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(dueDateProperty); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition M_log.warn(this + ":removeCalendarEventFromCalendar " + ee.getMessage()); } catch (PermissionException ee) { M_log.warn(this + ":removeCalendarEventFromCalendar " + ee.getMessage()); } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1) { found = true; } } } catch (PermissionException pException) { addAlert(state, rb.getFormattedMessage("cannot_getEvents", new Object[]{c.getReference()})); } } // remove the found old event if (found) { // found the old event delete it removeOldEvent(title, c, e); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(dueDateProperty); } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids List ids = (List) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); AssignmentEdit a = editAssignment(currentId, "doDeep_delete_assignment", state, false); if (a != null) { try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(a)); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{a.getTitle()})); M_log.warn(this + ":doDeep_delete_assignment " + e.getMessage()); } } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new ArrayList()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { if (!"POST".equals(data.getRequest().getMethod())) { return; } SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtils.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_ADDITIONAL_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aPropertiesEdit.removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } catch (IdInvalidException e) { addAlert(state, rb.getFormattedMessage("theassiid_isnotval", new Object[]{assignmentId})); M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } catch (IdUnusedException e) { addAlert(state, rb.getFormattedMessage("theassiid_hasnotbee", new Object[]{assignmentId})); M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } catch (Exception e) { M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); String submissionId = params.getString("submissionId"); // put submission information into state putSubmissionInfoIntoState(state, assignmentId, submissionId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); state.setAttribute(FROM_VIEW, (String)params.getString("option")); // assignment read event m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submissionId, false)); } } // doGrade_submission /** * put all the submission information into state variables * @param state * @param assignmentId * @param submissionId */ private void putSubmissionInfoIntoState(SessionState state, String assignmentId, String submissionId) { // reset grading submission variables resetGradeSubmission(state); // reset the grade assignment id and submission id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, assignmentId); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = getAssignment(assignmentId, "putSubmissionInfoIntoState", state); if (a != null) { AssignmentSubmission s = getSubmission(submissionId, "putSubmissionInfoIntoState", state); if (s != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); /* if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } */ state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT,v); state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); // populate grade overrides if they exist if (a.isGroup()) { User[] _users = s.getSubmitters(); for (int i=0; _users != null && i < _users.length; i++) { if (s.getGradeForUser(_users[i].getId()) != null) { state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), s.getGradeForUser(_users[i].getId())); } } } // put the resubmission info into state assignment_resubmission_option_into_state(a, s, state); } } } /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); // get the assignment Assignment a = getAssignment(assignmentId, "doRelease_grades", state); if (a != null) { String aReference = a.getReference(); Iterator submissions = getFilteredSubmitters(state, aReference).iterator(); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded() || (s.getGrade()!=null && !"".equals(s.getGrade()))) { String sRef = s.getReference(); AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doRelease_grades", state); if (sEdit != null) { String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !"".equals(grade)) { sEdit.setGradeReleased(true); if(!s.getGraded()) { sEdit.setGraded(true); } } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", -1); } } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.removeAttribute(SHOW_ALLOW_RESUBMISSION); state.removeAttribute(SHOW_SEND_FEEDBACK); state.removeAttribute(SAVED_FEEDBACK); state.removeAttribute(OW_FEEDBACK); state.removeAttribute(RETURNED_FEEDBACK); String assignmentId = params.getString("assignmentId"); state.setAttribute(EXPORT_ASSIGNMENT_REF, assignmentId); Assignment a = getAssignment(assignmentId, "doGrade_assignment", state); if (a != null) { state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // initialize the resubmission params assignment_resubmission_option_into_state(a, null, state); // we are changing the view, so start with first page again. resetPaging(state); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); String _mode = MODE_STUDENT_VIEW_GRADE; AssignmentSubmission _s = getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade", state ); // whether the user can access the Submission object if (_s != null) { // show submission view unless group submission with group error Assignment a = _s.getAssignment(); User u = (User) state.getAttribute(STATE_USER); if (a.isGroup()) { Collection groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); groups = getGroupsWithUser(u.getId(), a, st); Collection<String> _dupUsers = checkForGroupsInMultipleGroups(a, groups, state, rb.getString("group.user.multiple.warning")); if (_dupUsers.size() > 0) { _mode = MODE_STUDENT_VIEW_GROUP_ERROR; state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, _s.getAssignmentId()); } } catch (IdUnusedException iue) { M_log.warn(this + ":doView_grade found!" + iue.getMessage()); } } state.setAttribute(STATE_MODE, _mode); } } // doView_grade /** * Action is to show the graded assignment submission while keeping specific information private */ public void doView_grade_private(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); // whether the user can access the Submission object if (getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade_private", state ) != null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE_PRIVATE); } } // doView_grade_private /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); //Added by Branden Visser: Grab the submission id from the query string SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String actualGradeSubmissionId = (String) params.getString("submissionId"); Log.debug("chef", "doAssignment_form(): actualGradeSubmissionId = " + actualGradeSubmissionId); String option = (String) params.getString("option"); String fromView = (String) state.getAttribute(FROM_VIEW); if (option != null) { if ("post".equals(option)) { // post assignment doPost_assignment(data); } else if ("save".equals(option)) { // save assignment doSave_assignment(data); } else if ("reorder".equals(option)) { // reorder assignments doReorder_assignment(data); } else if ("preview".equals(option)) { // preview assignment doPreview_assignment(data); } else if ("cancel".equals(option)) { // cancel creating assignment doCancel_new_assignment(data); } else if ("canceledit".equals(option)) { // cancel editing assignment doCancel_edit_assignment(data); } else if ("attach".equals(option)) { // attachments doAttachmentsFrom(data, null); } else if ("modelAnswerAttach".equals(option)) { doAttachmentsFrom(data, "modelAnswer"); } else if ("allPurposeAttach".equals(option)) { doAttachmentsFrom(data, "allPurpose"); } else if ("view".equals(option)) { // view doView(data); } else if ("permissions".equals(option)) { // permissions doPermissions(data); } else if ("returngrade".equals(option)) { // return grading doReturn_grade_submission(data); } else if ("savegrade".equals(option)) { // save grading doSave_grade_submission(data); } else if ("savegrade_review".equals(option)) { // save review grading doSave_grade_submission_review(data); }else if("submitgrade_review".equals(option)){ //we basically need to submit, save, and move the user to the next review (if available) if(data.getParameters().get("nextSubmissionId") != null){ //go next doPrev_back_next_submission_review(data, "next", true); }else if(data.getParameters().get("prevSubmissionId") != null){ //go previous doPrev_back_next_submission_review(data, "prev", true); }else{ //go back to the list doPrev_back_next_submission_review(data, "back", true); } } else if ("toggleremove_review".equals(option)) { // save review grading doSave_toggle_remove_review(data); } else if ("previewgrade".equals(option)) { // preview grading doPreview_grade_submission(data); } else if ("cancelgrade".equals(option)) { // cancel grading doCancel_grade_submission(data); } else if ("cancelgrade_review".equals(option)) { // cancel grade review // no need to do anything, session will have original values and refresh } else if ("cancelreorder".equals(option)) { // cancel reordering doCancel_reorder(data); } else if ("sortbygrouptitle".equals(option)) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if ("sortbygroupdescription".equals(option)) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if ("hide_instruction".equals(option)) { // hide the assignment instruction doHide_submission_assignment_instruction(data); }else if ("hide_instruction_review".equals(option)) { // hide the assignment instruction doHide_submission_assignment_instruction_review(data); } else if ("show_instruction".equals(option)) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if ("show_instruction_review".equals(option)) { // show the assignment instruction doShow_submission_assignment_instruction_review(data); } else if ("sortbygroupdescription".equals(option)) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if ("revise".equals(option) || "done".equals(option)) { // back from the preview mode doDone_preview_new_assignment(data); } else if ("prevsubmission".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission(data, "prev"); } else if ("nextsubmission".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission(data, "next"); } else if ("prevsubmission_review".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission_review(data, "prev", false); } else if ("nextsubmission_review".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission_review(data, "next", false); } else if ("cancelgradesubmission".equals(option)) { if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { doPrev_back_next_submission(data, "backListStudent"); } else { // save and navigate to previous submission doPrev_back_next_submission(data, "back"); } } else if ("cancelgradesubmission_review".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission_review(data, "back", false); } else if ("reorderNavigation".equals(option)) { // save and do reorder doReorder(data); } else if ("options".equals(option)) { // go to the options view doOptions(data); } } } // added by Branden Visser - Check that the state is consistent boolean checkSubmissionStateConsistency(SessionState state, String actualGradeSubmissionId) { String stateGradeSubmissionId = (String)state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); Log.debug("chef", "checkSubmissionStateConsistency(): stateGradeSubmissionId = " + stateGradeSubmissionId); boolean is_good = stateGradeSubmissionId.equals(actualGradeSubmissionId); if (!is_good) { Log.warn("chef", "checkSubissionStateConsistency(): State is inconsistent! Aborting grade save."); addAlert(state, rb.getString("grading.alert.multiTab")); } return is_good; } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachmentsFrom(RunData data, String from) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); doAttachments(data); // use the real attachment list if (state.getAttribute(STATE_MESSAGE) == null) { if (from != null && "modelAnswer".equals(from)) { state.setAttribute(ATTACHMENTS_FOR, MODELANSWER_ATTACHMENTS); state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(MODELANSWER_ATTACHMENTS)); state.setAttribute(MODELANSWER, Boolean.TRUE); } else if (from != null && "allPurpose".equals(from)) { state.setAttribute(ATTACHMENTS_FOR, ALLPURPOSE_ATTACHMENTS); state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ALLPURPOSE_ATTACHMENTS)); state.setAttribute(ALLPURPOSE, Boolean.TRUE); } } } /** * put supplement item attachment info into state * @param state * @param item * @param attachmentsKind */ private void putSupplementItemAttachmentInfoIntoState(SessionState state, AssignmentSupplementItemWithAttachment item, String attachmentsKind) { List refs = new ArrayList(); if (item != null) { // get reference list Set<AssignmentSupplementItemAttachment> aSet = item.getAttachmentSet(); if (aSet != null && aSet.size() > 0) { for(Iterator<AssignmentSupplementItemAttachment> aIterator = aSet.iterator(); aIterator.hasNext();) { AssignmentSupplementItemAttachment att = aIterator.next(); // add reference refs.add(EntityManager.newReference(att.getAttachmentId())); } state.setAttribute(attachmentsKind, refs); } } } /** * put supplement item attachment state attribute value into context * @param state * @param context * @param attachmentsKind */ private void putSupplementItemAttachmentStateIntoContext(SessionState state, Context context, String attachmentsKind) { List refs = new ArrayList(); String attachmentsFor = (String) state.getAttribute(ATTACHMENTS_FOR); if (attachmentsFor != null && attachmentsFor.equals(attachmentsKind)) { ToolSession session = SessionManager.getCurrentToolSession(); if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null && session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); // set the correct state variable state.setAttribute(attachmentsKind, refs); } session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); state.removeAttribute(ATTACHMENTS_FOR); } // show attachments content if (state.getAttribute(attachmentsKind) != null) { context.put(attachmentsKind, state.getAttribute(attachmentsKind)); } // this is to keep the proper node div open context.put("attachments_for", attachmentsKind); } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // determines if the file picker can only add a single attachment boolean singleAttachment = false; // when content-review is enabled, the inline text will have an associated attachment. It should be omitted from the file picker Assignment assignment = null; boolean omitInlineAttachments = false; String mode = (String) state.getAttribute(STATE_MODE); if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode)) { // save the current input before leaving the page saveSubmitInputs(state, params); // Restrict file picker configuration if using content-review (Turnitin): String assignmentRef = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { assignment = AssignmentService.getAssignment(assignmentRef); if (assignment.getContent().getAllowReviewService()) { state.setAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS, FilePickerHelper.CARDINALITY_MULTIPLE); state.setAttribute(FilePickerHelper.FILE_PICKER_SHOW_URL, Boolean.FALSE); } if (assignment.getContent().getTypeOfSubmission() == Assignment.SINGLE_ATTACHMENT_SUBMISSION) { singleAttachment = true; } } catch ( IdUnusedException e ) { addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef})); } catch ( PermissionException e ) { addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentRef})); } // need also to upload local file if any doAttachUpload(data, false); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); // Always omit inline attachments. Even if content-review is not enabled, // this could be a resubmission to an assignment that was previously content-review enabled, // in which case the file will be present and should be omitted. omitInlineAttachments = true; } else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)) { setNewAssignmentParameters(data, false); } else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); if (singleAttachment) { // SAK-27595 - added a resources file picker for single uploaded file only assignments; we limit it here to accept a maximum of 1 file --bbailla2 state.setAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS, Integer.valueOf(1)); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig.singular")); } else { state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); } state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list // but omit the inlie submission under conditions determined in the logic above List attachments = (List) state.getAttribute(ATTACHMENTS); if (omitInlineAttachments && assignment != null) { attachments = getNonInlineAttachments(state, assignment); state.setAttribute(ATTACHMENTS, attachments); } state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, attachments); } } /** * saves the current input before navigating off to other pages * @param state * @param params */ private void saveSubmitInputs(SessionState state, ParameterParser params) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } String assignmentRef = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment assignment = AssignmentService.getAssignment(assignmentRef); if (assignment.isGroup()) { String[] groupChoice = params.getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { if (groupChoice.length > 1) { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } else { state.setAttribute(VIEW_SUBMISSION_GROUP, groupChoice[0]); } } else { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } String original_group_id = params.getString("originalGroup") == null || params.getString("originalGroup").trim().length() == 0 ? null: params.getString("originalGroup"); if (original_group_id != null) { state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, original_group_id); } else { state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, null); } } } catch (PermissionException p) { M_log.debug(this + " :saveSubmitInputs permission error getting assignment. "); } catch ( IdUnusedException e ) {} } /** * read review grade information form and see if any grading information has been changed * @param data * @param state * @param gradeOption * @return */ public boolean saveReviewGradeForm(RunData data, SessionState state, String gradeOption){ String assessorUserId = UserDirectoryService.getCurrentUser().getId(); if(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null && !assessorUserId.equals(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID))){ //this is only set during the read only view, so just return return false; } ParameterParser params = data.getParameters(); String submissionRef = params.getString("submissionId"); String submissionId = null; if(submissionRef != null){ int i = submissionRef.lastIndexOf(Entity.SEPARATOR); if (i == -1){ submissionId = submissionRef; }else{ submissionId = submissionRef.substring(i + 1); } } if(submissionId != null){ //call the DB to make sure this user can edit this assessment, otherwise it wouldn't exist PeerAssessmentItem item = assignmentPeerAssessmentService.getPeerAssessmentItem(submissionId, assessorUserId); if(item != null){ //find the original assessment item and compare to see if it has changed //if so, save it boolean changed = false; if(submissionId.equals(item.getSubmissionId()) && assessorUserId.equals(item.getAssessorUserId())){ //Grade String g = StringUtils.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE)); Integer score = item.getScore(); if(g != null && !"".equals(g)){ try{ Double dScore = Double.parseDouble(g); if(dScore < 0){ addAlert(state, rb.getString("peerassessment.alert.saveinvalidscore")); }else{ String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); if(assignmentId != null){ Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if(a != null){ if(dScore <= a.getContent().getMaxGradePoint()/10.0){ //scores are saved as whole values //so a score of 1.3 would be stored as 13 score = (int) Math.round(dScore * 10); }else{ addAlert(state, rb.getFormattedMessage("plesuse4", new Object[]{g, a.getContent().getMaxGradePoint()/10.0})); } }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } } }catch(Exception e){ addAlert(state, rb.getString("peerassessment.alert.saveinvalidscore")); } } boolean scoreChanged = false; if(score != null && item.getScore() == null || score == null && item.getScore() != null || (score != null && item.getScore() != null && !score.equals(item.getScore()))){ //Score changed changed = true; scoreChanged = true; item.setScore(score); } //Comment: boolean checkForFormattingErrors = true; String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if(feedbackComment != null && item.getComment() == null || feedbackComment == null && item.getComment() != null || (feedbackComment != null && item.getComment() != null && !feedbackComment.equals(item.getComment()))){ //comment changed changed = true; item.setComment(feedbackComment); } //Submitted if("submit".equals(gradeOption)){ if(item.getScore() != null || (item.getComment() != null && !"".equals(item.getComment().trim()))){ item.setSubmitted(true); changed = true; }else{ addAlert(state, rb.getString("peerassessment.alert.savenoscorecomment")); } } if(("submit".equals(gradeOption) || "save".equals(gradeOption)) && state.getAttribute(STATE_MESSAGE) == null){ if(changed){ //save this in the DB assignmentPeerAssessmentService.savePeerAssessmentItem(item); if(scoreChanged){ //need to re-calcuate the overall score: boolean saved = assignmentPeerAssessmentService.updateScore(submissionId); if(saved){ //we need to make sure the GB is updated correctly (or removed) String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); if(assignmentId != null){ Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if(a != null){ String aReference = a.getReference(); String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, submissionId, "update", -1); } } } } state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); if("submit".equals(gradeOption)){ state.setAttribute(GRADE_SUBMISSION_SUBMIT, Boolean.TRUE); } } } //update session state: List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state.getAttribute(PEER_ASSESSMENT_ITEMS); if(peerAssessmentItems != null){ for(int i = 0; i < peerAssessmentItems.size(); i++) { PeerAssessmentItem sItem = peerAssessmentItems.get(i); if(sItem.getSubmissionId().equals(item.getSubmissionId()) && sItem.getAssessorUserId().equals(item.getAssessorUserId())){ //found it, just update it peerAssessmentItems.set(i, item); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); break; } } } } return changed; }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } return false; } /** * read grade information form and see if any grading information has been changed * @param data * @param state * @param gradeOption * @return */ public boolean readGradeForm(RunData data, SessionState state, String gradeOption) { // whether user has changed anything from previous grading information boolean hasChange = false; ParameterParser params = data.getParameters(); String sId = params.getString("submissionId"); //Added by Branden Visser - Check that the state is consistent if (!checkSubmissionStateConsistency(state, sId)) { return false; } AssignmentSubmission submission = getSubmission(sId, "readGradeForm", state); // security check for allowing grading submission or not if (AssignmentService.allowGradeSubmission(sId)) { int typeOfGrade = -1; boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = true; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); // comment value changed? hasChange = !hasChange && submission != null ? valueDiffFromStateAttribute(state, feedbackComment, submission.getFeedbackComment()):hasChange; if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); // feedbackText value changed? hasChange = !hasChange && submission != null ? valueDiffFromStateAttribute(state, feedbackText, submission.getFeedbackText()):hasChange; if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } // any change inside attachment list? if (!hasChange && submission != null) { List stateAttachments = submission.getFeedbackAttachments(); List inputAttachments = (List) state.getAttribute(ATTACHMENTS); if (stateAttachments == null && inputAttachments != null || stateAttachments != null && inputAttachments == null || stateAttachments != null && inputAttachments != null && !(stateAttachments.containsAll(inputAttachments) && inputAttachments.containsAll(stateAttachments))) { hasChange = true; } } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = StringUtils.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE)); if (submission != null) { Assignment a = submission.getAssignment(); typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // any change in grade. Do not check for ungraded assignment type if (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) { if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { String currentGrade = submission.getGrade(); NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; if (currentGrade != null && currentGrade.indexOf(decSeparator) != -1) { currentGrade = scalePointGrade(state, submission.getGrade()); } hasChange = valueDiffFromStateAttribute(state, scalePointGrade(state, g), currentGrade); } else { hasChange = valueDiffFromStateAttribute(state, g, submission.getGrade()); } } if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } else { state.removeAttribute(GRADE_SUBMISSION_GRADE); } // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if ((grade != null)) { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); M_log.warn(this + ":readGradeForm " + e.getMessage()); } } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || "ungraded".equals(grade)) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && "release".equals(gradeOption)) { addAlert(state, rb.getString("plespethe2")); } // check for grade overrides if (a.isGroup()) { User[] _users = submission.getSubmitters(); for (int i=0; _users != null && i < _users.length; i++) { String ug = StringUtil.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId())); if ("null".equals(ug)) ug = null; if (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) { if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { hasChange = valueDiffFromStateAttribute(state, scalePointGrade(state, ug), submission.getGradeForUser(_users[i].getId())); } else { hasChange = valueDiffFromStateAttribute(state, ug, submission.getGradeForUser(_users[i].getId())); } } if (ug == null) { state.removeAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); } else { state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), ug); } // for points grading, one have to enter number as the points String ugrade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if (ugrade != null && !(ugrade.equals("null"))) { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, ugrade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, ugrade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{ugrade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, ugrade); M_log.warn(this + ":readGradeForm User " + e.getMessage()); } } state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), scalePointGrade(state,ugrade)); } } } } } } // allow resubmit number and due time if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params readAllowResubmitParams(params, state, submission); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (!"read".equals(gradeOption)) { resetAllowResubmitParams(state); } } // record whether the resubmission options has been changed or not hasChange = hasChange || change_resubmit_option(state, submission); } if (state.getAttribute(STATE_MESSAGE) == null) { String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE)?scalePointGrade(state, grade):grade; state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } else { // generate alert addAlert(state, rb.getFormattedMessage("not_allowed_to_grade_submission", new Object[]{sId})); } return hasChange; } /** * whether the current input value is different from existing oldValue * @param state * @param value * @param oldValue * @return */ private boolean valueDiffFromStateAttribute(SessionState state, String value, String oldValue) { boolean rv = false; value = StringUtils.trimToNull(value); oldValue = StringUtils.trimToNull(oldValue); if (oldValue == null && value != null || oldValue != null && value == null || oldValue != null && value != null && !normalizeAttributeSpaces(oldValue).equals(normalizeAttributeSpaces(value))) { rv = true; } return rv; } /** Remove extraneous spaces between tag attributes, to allow a better equality test in valueDiffFromStateAttribute. @param the input string, to be normalized @return the normalized string. */ String normalizeAttributeSpaces(String s) { if (s == null) return s; Pattern p = Pattern.compile("(=\".*?\")( +)"); Matcher m = p.matcher(s); String c = m.replaceAll("$1 "); return c; } /** * read in the resubmit parameters into state variables * @param params * @param state * @return the time set for the resubmit close OR null if it is not set */ protected Time readAllowResubmitParams(ParameterParser params, SessionState state, Entity entity) { Time resubmitCloseTime = null; String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (allowResubmitNumberString != null && Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(closeMonth)); int closeDay = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(closeDay)); int closeYear = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(closeYear)); int closeHour = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(closeHour)); int closeMin = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(closeMin)); resubmitCloseTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(resubmitCloseTime.getTime())); // no need to show alert if the resubmission setting has not changed if (entity == null || change_resubmit_option(state, entity)) { // validate date if (resubmitCloseTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) != null) { addAlert(state, rb.getString("acesubdea5")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString("date.resubmission.closedate")})); } } } else { // reset the state attributes resetAllowResubmitParams(state); } return resubmitCloseTime; } protected void resetAllowResubmitParams(SessionState state) { state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH,state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY,state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR,state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR,state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN,state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); if (m_contentHostingService == null) { m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); } if (m_assignmentSupplementItemService == null) { m_assignmentSupplementItemService = (AssignmentSupplementItemService) ComponentManager.get("org.sakaiproject.assignment.api.model.AssignmentSupplementItemService"); } if (m_eventTrackingService == null) { m_eventTrackingService = (EventTrackingService) ComponentManager.get("org.sakaiproject.event.api.EventTrackingService"); } if (m_notificationService == null) { m_notificationService = (NotificationService) ComponentManager.get("org.sakaiproject.event.api.NotificationService"); } if (m_securityService == null) { m_securityService = (SecurityService) ComponentManager.get("org.sakaiproject.authz.api.SecurityService"); } if(assignmentPeerAssessmentService == null){ assignmentPeerAssessmentService = (AssignmentPeerAssessmentService) ComponentManager.get("org.sakaiproject.assignment.api.AssignmentPeerAssessmentService"); } String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if if (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) == null) { String propValue = null; // save the option into tool configuration try { Site site = SiteService.getSite(siteId); ToolConfiguration tc=site.getToolForCommonId(ASSIGNMENT_TOOL_ID); propValue = tc.getPlacementConfig().getProperty(SUBMISSIONS_SEARCH_ONLY); } catch (IdUnusedException e) { M_log.warn(this + ":init() Cannot find site with id " + siteId); } state.setAttribute(SUBMISSIONS_SEARCH_ONLY, propValue == null ? Boolean.FALSE:Boolean.valueOf(propValue)); } /** The calendar tool */ if (state.getAttribute(CALENDAR_TOOL_EXIST) == null) { CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); if (cService != null){ if (!siteHasTool(siteId, cService.getToolId())) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(CALENDAR); } else { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(CALENDAR) == null ) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { state.removeAttribute(CALENDAR); M_log.info(this + ":initState No calendar found for site " + siteId + " " + e.getMessage()); } catch (PermissionException e) { state.removeAttribute(CALENDAR); M_log.info(this + ":initState No permission to get the calender. " + e.getMessage()); } catch (Exception ex) { state.removeAttribute(CALENDAR); M_log.info(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage()); } } } } } } /** Additional Calendar tool */ // Setting this attribute to true or false currently makes no difference as it is never checked for true or false. // true: means the additional calendar is ready to be used with assignments. // false: means the tool may not be deployed at all or may be at the site but not ready to be used. if (state.getAttribute(ADDITIONAL_CALENDAR_TOOL_READY) == null) { // Get a handle to the Google calendar service class from the Component Manager. It will be null if not deployed. CalendarService additionalCalendarService = (CalendarService)ComponentManager.get(CalendarService.ADDITIONAL_CALENDAR); if (additionalCalendarService != null){ // If tool is not used/used on this site, we set the appropriate flag in the state. if (!siteHasTool(siteId, additionalCalendarService.getToolId())) { state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.FALSE); state.removeAttribute(ADDITIONAL_CALENDAR); } else { // Also check that this calendar has been fully created (initialized) in the additional calendar service. if (additionalCalendarService.isCalendarToolInitialized(siteId)){ state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.TRUE); // Alternate calendar ready for events. if (state.getAttribute(ADDITIONAL_CALENDAR) == null ) { try { state.setAttribute(ADDITIONAL_CALENDAR, additionalCalendarService.getCalendar(null)); } catch (IdUnusedException e) { M_log.info(this + ":initState No calendar found for site " + siteId + " " + e.getMessage()); } catch (PermissionException e) { M_log.info(this + ":initState No permission to get the calendar. " + e.getMessage()); } } } else{ state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.FALSE); // Tool on site but alternate calendar not yet created. } } } else{ state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.FALSE); // Tool not deployed on the server. } } /** The Announcement tool */ if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null) { if (!siteHasTool(siteId, "sakai.announcements")) { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } else { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null ) { /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { M_log.warn(this + ":initState No announcement channel found. " + e.getMessage()); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } catch (PermissionException e) { M_log.warn(this + ":initState No permission to annoucement channel. " + e.getMessage()); } catch (Exception ex) { M_log.warn(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage()); } } } } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null || ((String) state.getAttribute(STATE_CONTEXT_STRING)).length() == 0) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { setDefaultSort(state); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new ConcurrentSkipListSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, Integer.valueOf(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtils.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, Boolean.valueOf(withGrades)); } // whether to display the number of submission/ungraded submission column // default to show if (state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN) == null) { PortletConfig config = portlet.getPortletConfig(); String value = StringUtils.trimToNull(config.getInitParameter(SHOW_NUMBER_SUBMISSION_COLUMN)); if (value == null) { value = Boolean.TRUE.toString(); } state.setAttribute(SHOW_NUMBER_SUBMISSION_COLUMN, Boolean.valueOf(value)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, Integer.valueOf(GregorianCalendar.getInstance().get(GregorianCalendar.YEAR)-4)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, Integer.valueOf(GregorianCalendar.getInstance().get(GregorianCalendar.YEAR)+4)); } } // initState /** * whether the site has the specified tool * @param siteId * @return */ private boolean siteHasTool(String siteId, String toolId) { boolean rv = false; try { Site s = SiteService.getSite(siteId); if (s.getToolForCommonId(toolId) != null) { rv = true; } } catch (Exception e) { M_log.warn(this + "siteHasTool" + e.getMessage() + siteId); } return rv; } /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * initialize assignment attributes * @param state */ private void initializeAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the visible time to be 12:00 PM if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { state.setAttribute(NEW_ASSIGNMENT_VISIBLEMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEHOUR, Integer.valueOf(12)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEMIN, Integer.valueOf(0)); } // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, Integer.valueOf(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, Integer.valueOf(0)); // set the all purpose item release time state.setAttribute(ALLPURPOSE_RELEASE_MONTH, Integer.valueOf(month)); state.setAttribute(ALLPURPOSE_RELEASE_DAY, Integer.valueOf(day)); state.setAttribute(ALLPURPOSE_RELEASE_YEAR, Integer.valueOf(year)); state.setAttribute(ALLPURPOSE_RELEASE_HOUR, Integer.valueOf(12)); state.setAttribute(ALLPURPOSE_RELEASE_MIN, Integer.valueOf(0)); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, Integer.valueOf(17)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, Integer.valueOf(0)); // set the resubmit time to be the same as due time state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(month)); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(day)); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(year)); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(17)); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(0)); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, Integer.valueOf(1)); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, Integer.valueOf(17)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, Integer.valueOf(0)); // set the all purpose retract time state.setAttribute(ALLPURPOSE_RETRACT_MONTH, Integer.valueOf(month)); state.setAttribute(ALLPURPOSE_RETRACT_DAY, Integer.valueOf(day)); state.setAttribute(ALLPURPOSE_RETRACT_YEAR, Integer.valueOf(year)); state.setAttribute(ALLPURPOSE_RETRACT_HOUR, Integer.valueOf(17)); state.setAttribute(ALLPURPOSE_RETRACT_MIN, Integer.valueOf(0)); // set the peer period time to be 10 mins after accept until date state.setAttribute(NEW_ASSIGNMENT_PEERPERIODMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODHOUR, Integer.valueOf(17)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODMIN, Integer.valueOf(10)); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL, Boolean.TRUE.toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS, Boolean.TRUE.toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, 1); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (Integer.valueOf(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.removeAttribute(NEW_ASSIGNMENT_RANGE); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); // remove the resubmit number state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // remove the supplement attributes state.removeAttribute(MODELANSWER); state.removeAttribute(MODELANSWER_TEXT); state.removeAttribute(MODELANSWER_SHOWTO); state.removeAttribute(MODELANSWER_ATTACHMENTS); state.removeAttribute(NOTE); state.removeAttribute(NOTE_TEXT); state.removeAttribute(NOTE_SHAREWITH); state.removeAttribute(ALLPURPOSE); state.removeAttribute(ALLPURPOSE_TITLE); state.removeAttribute(ALLPURPOSE_TEXT); state.removeAttribute(ALLPURPOSE_HIDE); state.removeAttribute(ALLPURPOSE_SHOW_FROM); state.removeAttribute(ALLPURPOSE_SHOW_TO); state.removeAttribute(ALLPURPOSE_RELEASE_DATE); state.removeAttribute(ALLPURPOSE_RETRACT_DATE); state.removeAttribute(ALLPURPOSE_ACCESS); state.removeAttribute(ALLPURPOSE_ATTACHMENTS); // SAK-17606 state.removeAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING); } // resetNewAssignment /** * reset the attributes for assignment */ private void resetAssignment(SessionState state) { state.removeAttribute(NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_OPENMONTH); state.removeAttribute(NEW_ASSIGNMENT_OPENDAY); state.removeAttribute(NEW_ASSIGNMENT_OPENYEAR); state.removeAttribute(NEW_ASSIGNMENT_OPENHOUR); state.removeAttribute(NEW_ASSIGNMENT_OPENMIN); state.removeAttribute(ALLPURPOSE_RELEASE_MONTH); state.removeAttribute(ALLPURPOSE_RELEASE_DAY); state.removeAttribute(ALLPURPOSE_RELEASE_YEAR); state.removeAttribute(ALLPURPOSE_RELEASE_HOUR); state.removeAttribute(ALLPURPOSE_RELEASE_MIN); state.removeAttribute(NEW_ASSIGNMENT_DUEMONTH); state.removeAttribute(NEW_ASSIGNMENT_DUEDAY); state.removeAttribute(NEW_ASSIGNMENT_DUEYEAR); state.removeAttribute(NEW_ASSIGNMENT_DUEHOUR); state.removeAttribute(NEW_ASSIGNMENT_DUEMIN); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEMONTH); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEDAY); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEYEAR); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEHOUR); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEMIN); state.removeAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE); state.removeAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); state.removeAttribute(NEW_ASSIGNMENT_CLOSEMONTH); state.removeAttribute(NEW_ASSIGNMENT_CLOSEDAY); state.removeAttribute(NEW_ASSIGNMENT_CLOSEYEAR); state.removeAttribute(NEW_ASSIGNMENT_CLOSEHOUR); state.removeAttribute(NEW_ASSIGNMENT_CLOSEMIN); // set the all purpose retract time state.removeAttribute(ALLPURPOSE_RETRACT_MONTH); state.removeAttribute(ALLPURPOSE_RETRACT_DAY); state.removeAttribute(ALLPURPOSE_RETRACT_YEAR); state.removeAttribute(ALLPURPOSE_RETRACT_HOUR); state.removeAttribute(ALLPURPOSE_RETRACT_MIN); state.removeAttribute(NEW_ASSIGNMENT_SECTION); state.removeAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE); state.removeAttribute(NEW_ASSIGNMENT_GRADE_TYPE); state.removeAttribute(NEW_ASSIGNMENT_GRADE_POINTS); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION); state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); state.removeAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); state.removeAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE); state.removeAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.removeAttribute(NEW_ASSIGNMENT_ATTACHMENT); state.removeAttribute(NEW_ASSIGNMENT_FOCUS); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); state.removeAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.removeAttribute(NEW_ASSIGNMENT_RANGE); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); // remove the resubmit number state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // remove the supplement attributes state.removeAttribute(MODELANSWER); state.removeAttribute(MODELANSWER_TEXT); state.removeAttribute(MODELANSWER_SHOWTO); state.removeAttribute(MODELANSWER_ATTACHMENTS); state.removeAttribute(NOTE); state.removeAttribute(NOTE_TEXT); state.removeAttribute(NOTE_SHAREWITH); state.removeAttribute(ALLPURPOSE); state.removeAttribute(ALLPURPOSE_TITLE); state.removeAttribute(ALLPURPOSE_TEXT); state.removeAttribute(ALLPURPOSE_HIDE); state.removeAttribute(ALLPURPOSE_SHOW_FROM); state.removeAttribute(ALLPURPOSE_SHOW_TO); state.removeAttribute(ALLPURPOSE_RELEASE_DATE); state.removeAttribute(ALLPURPOSE_RETRACT_DATE); state.removeAttribute(ALLPURPOSE_ACCESS); state.removeAttribute(ALLPURPOSE_ATTACHMENTS); //revmoew peer assessment settings state.removeAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODMONTH); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODDAY); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODYEAR); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODHOUR); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODMIN); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); // remove content-review setting state.removeAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); state.removeAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE); state.removeAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } // resetNewAssignment /** * construct a HashMap using integer as the key and three character string of the month as the value */ private HashMap monthTable() { HashMap n = new HashMap(); n.put(Integer.valueOf(1), rb.getString("jan")); n.put(Integer.valueOf(2), rb.getString("feb")); n.put(Integer.valueOf(3), rb.getString("mar")); n.put(Integer.valueOf(4), rb.getString("apr")); n.put(Integer.valueOf(5), rb.getString("may")); n.put(Integer.valueOf(6), rb.getString("jun")); n.put(Integer.valueOf(7), rb.getString("jul")); n.put(Integer.valueOf(8), rb.getString("aug")); n.put(Integer.valueOf(9), rb.getString("sep")); n.put(Integer.valueOf(10), rb.getString("oct")); n.put(Integer.valueOf(11), rb.getString("nov")); n.put(Integer.valueOf(12), rb.getString("dec")); return n; } // monthTable /** * construct a HashMap using the integer as the key and grade type String as the value */ private HashMap gradeTypeTable(){ HashMap gradeTypeTable = new HashMap(); gradeTypeTable.put(Integer.valueOf(1), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_NOGRADE_PROP)); gradeTypeTable.put(Integer.valueOf(2), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_LETTER_PROP)); gradeTypeTable.put(Integer.valueOf(3), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_POINTS_PROP)); gradeTypeTable.put(Integer.valueOf(4), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_PASS_FAIL_PROP)); gradeTypeTable.put(Integer.valueOf(5), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_CHECK_PROP)); return gradeTypeTable; } // gradeTypeTable /** * construct a HashMap using the integer as the key and submission type String as the value */ private HashMap submissionTypeTable(){ HashMap submissionTypeTable = new HashMap(); submissionTypeTable.put(Integer.valueOf(1), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_INLINE_PROP)); submissionTypeTable.put(Integer.valueOf(2), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_ATTACHMENTS_ONLY_PROP)); submissionTypeTable.put(Integer.valueOf(3), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_INLINE_AND_ATTACHMENTS_PROP)); submissionTypeTable.put(Integer.valueOf(4), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_NON_ELECTRONIC_PROP)); submissionTypeTable.put(Integer.valueOf(5), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_SINGLE_ATTACHMENT_PROP)); return submissionTypeTable; } // submissionTypeTable /** * Add the list of categories from the gradebook tool * construct a HashMap using the integer as the key and category String as the value * @return */ private HashMap<Long, String> categoryTable() { boolean gradebookExists = isGradebookDefined(); HashMap<Long, String> catTable = new HashMap<Long, String>(); if (gradebookExists) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); List<CategoryDefinition> categoryDefinitions = g.getCategoryDefinitions(gradebookUid); catTable.put(Long.valueOf(-1), rb.getString("grading.unassigned")); for (CategoryDefinition category: categoryDefinitions) { catTable.put(category.getId(), category.getName()); } } return catTable; } // categoryTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); //for content review default is desc if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) asc = Boolean.FALSE.toString(); else asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the SubmitterSubmission clas */ public class SubmitterSubmission { /** * the User object */ User m_user = null; /** * is the Submitter in more than one group */ Boolean m_multi_group = false; /** * the Group */ Group m_group = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; /** * the AssignmentSubmission object */ User m_submittedBy = null; public SubmitterSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } public SubmitterSubmission(Group g, AssignmentSubmission s) { m_group = g; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } public void setSubmittedBy(User submittedBy) { m_submittedBy = submittedBy; } /** * Returns the User object of the submitter, * if null, the user submitted the assignment himself. */ public User getSubmittedBy() { return m_submittedBy; } public Group getGroup() { return m_group; } public void setGroup(Group _group) { m_group = _group; } public Boolean getIsMultiGroup() { return m_multi_group; } public void setMultiGroup(Boolean _multi) { m_multi_group = _multi; } public String getGradeForUser(String id) { String grade = getSubmission() == null ? null: getSubmission().getGradeForUser(id); if (grade != null && getSubmission().getAssignment().getContent() != null && getSubmission().getAssignment().getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (grade.length() > 0 && !"0".equals(grade)) { try { Integer.parseInt(grade); // if point grade, display the grade with one decimal place return grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (Exception e) { return grade; } } else { return StringUtil.trimToZero(grade); } } return grade; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { Collator collator = null; /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; // true if users should be compared by anonymous submitter id rather than other identifiers boolean m_anon = false; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { this(state, criteria, asc, null); } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; try { collator= new RuleBasedCollator(((RuleBasedCollator)Collator.getInstance()).getRules().replaceAll("<'\u005f'", "<' '<'\u005f'")); } catch (ParseException e) { // error with init RuleBasedCollator with rules // use the default Collator collator = Collator.getInstance(); M_log.warn(this + " AssignmentComparator cannot init RuleBasedCollator. Will use the default Collator instead. " + e); } } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group Group _aGroup = site.getGroup((String) k.next()); if (_aGroup != null) rv = rv.concat(_aGroup.getTitle()); } } catch (Exception ignore) { M_log.warn(this + ":getAssignmentRange" + ignore.getMessage()); } } return rv; } // getAssignmentRange public void setAnon(boolean value) { m_anon = value; } /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; if (m_criteria == null) { m_criteria = SORTED_BY_DEFAULT; } /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else { if (t1.equals(t2)) { t1 = ((Assignment) o1).getTimeCreated(); t2 = ((Assignment) o2).getTimeCreated(); } else if (t1.before(t2)) { result = 1; } else { result = -1; } } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { if (AssignmentService.allowAddAssignment(((Assignment) o1).getContext())) { // comparing assignment status result = compareString(((Assignment) o1).getStatus(), ((Assignment) o2).getStatus()); } else { // comparing submission status AssignmentSubmission s1 = findAssignmentSubmission((Assignment) o1); AssignmentSubmission s2 = findAssignmentSubmission((Assignment) o2); result = s1==null ? 1 : s2==null? -1:compareString(s1.getStatus(), s2.getStatus()); } } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Time t1,t2; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); t1 = submission1.getTimeSubmitted(); if (t1!=null) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); t2 = submission2.getTimeSubmitted(); if (t2!=null) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Time t1,t2; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); t1 = submission1.getTimeSubmitted(); if (t1!=null && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); t2 = submission2.getTimeSubmitted(); if (t2!=null && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_GRADE) || m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { AssignmentSubmission submission1 = getSubmission(((Assignment) o1).getId(), m_user, "compare", null); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = getSubmission(((Assignment) o2).getId(), m_user, "compare", null); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = compareString(grade1, grade2); } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = compareString(maxGrade1, maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = compareString(factor1, factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (Integer.valueOf(score1)).intValue() > (Integer.valueOf(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null || (u1.getUser() == null && u1.getGroup() == null) || (u2.getUser() == null && u2.getGroup() == null) ) { result = 1; } else if (m_anon) { String anon1 = u1.getSubmission().getAnonymousSubmissionId(); String anon2 = u2.getSubmission().getAnonymousSubmissionId(); result = compareString(anon1, anon2); } else { String lName1 = u1.getUser() == null ? u1.getGroup().getTitle(): u1.getUser().getSortName(); String lName2 = u2.getUser() == null ? u2.getGroup().getTitle(): u2.getUser().getSortName(); result = compareString(lName1, lName2); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = s1.getStatus(); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = s2.getStatus(); } } result = compareString(status1, status2); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if ("".equals(grade1)) { result = -1; } else if ("".equals(grade2)) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (Boolean.valueOf(s1.getGradeReleased())).toString(); String released2 = (Boolean.valueOf(s2.getGradeReleased())).toString(); result = compareString(released1, released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name AssignmentSubmission _a1 = (AssignmentSubmission)o1; AssignmentSubmission _a2 = (AssignmentSubmission)o2; String _s1 = ""; String _s2 = ""; if (_a1.getAssignment().isGroup()) { try { Site site = SiteService.getSite(_a1.getAssignment().getContext()); _s1 = site.getGroup(_a1.getSubmitterId()).getTitle(); } catch (Throwable _dfef) { } } else { try { _s1 = UserDirectoryService.getUser(_a1.getSubmitterId()).getSortName(); } catch (UserNotDefinedException e) { M_log.warn(this + ": cannot find user id=" + _a1.getSubmitterId() + e.getMessage() + ""); } } if (_a2.getAssignment().isGroup()) { try { Site site = SiteService.getSite(_a2.getAssignment().getContext()); _s2 = site.getGroup(_a2.getSubmitterId()).getTitle(); } catch (Throwable _dfef) { // TODO empty exception block } } else { try { _s2 = UserDirectoryService.getUser(_a2.getSubmitterId()).getSortName(); } catch (UserNotDefinedException e) { M_log.warn(this + ": cannot find user id=" + _a2.getSubmitterId() + e.getMessage() + ""); } } result = _s1.compareTo(_s2); //compareString(submitters1, submitters2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status result = compareString(((AssignmentSubmission) o1).getStatus(), ((AssignmentSubmission) o2).getStatus()); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if ("".equals(grade1)) { result = -1; } else if ("".equals(grade2)) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if ("".equals(grade1)) { result = -1; } else if ("".equals(grade2)) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { M_log.warn(this + ":AssignmentComparator compare" + e.getMessage()); // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (Boolean.valueOf(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (Boolean.valueOf(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = compareString(released1, released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = compareString(title1, title2); } /*************** sort user by sort name ***************/ else if (m_criteria.equals(SORTED_USER_BY_SORTNAME)) { // sort by user's sort name String name1 = ((User) o1).getSortName(); String name2 = ((User) o2).getSortName(); result = compareString(name1, name2); } // sort ascending or descending if (!Boolean.valueOf(m_asc)) { result = -result; } return result; } /** * returns AssignmentSubmission object for given assignment by current user * @param a * @return */ protected AssignmentSubmission findAssignmentSubmission (Assignment a) { AssignmentSubmission rv = null; try { rv = AssignmentService.getSubmission(a.getReference(), UserDirectoryService.getCurrentUser()); } catch (IdUnusedException e) { M_log.warn(this + "compare: " + rb.getFormattedMessage("cannotfin_assignment", new Object[]{a.getReference()})); } catch (PermissionException e) { } return rv; } /** * Compare two strings as double values. Deal with the case when either of the strings cannot be parsed as double value. * @param grade1 * @param grade2 * @return */ private int compareDouble(String grade1, String grade2) { int result; try { result = (Double.valueOf(grade1)).doubleValue() > (Double.valueOf(grade2)).doubleValue() ? 1 : -1; } catch (Exception formatException) { // in case either grade1 or grade2 cannot be parsed as Double result = compareString(grade1, grade2); M_log.warn(this + ":AssignmentComparator compareDouble " + formatException.getMessage()); } return result; } // compareDouble private int compareString(String s1, String s2) { int result; if (s1 == null && s2 == null) { result = 0; } else if (s2 == null) { result = 1; } else if (s1 == null) { result = -1; } else { result = collator.compare(s1.toLowerCase(), s2.toLowerCase()); } return result; } /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("gen.nograd"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // ... pass the resource loader object ResourceLoader pRb = new ResourceLoader("permissions"); HashMap<String, String> pRbValues = new HashMap<String, String>(); for (Iterator<Map.Entry<String, Object>> iEntries = pRb.entrySet().iterator();iEntries.hasNext();) { Map.Entry<String, Object> entry = iEntries.next(); pRbValues.put(entry.getKey(), (String) entry.getValue()); } state.setAttribute("permissionDescriptions", pRbValues); String groupAware = ToolManager.getCurrentTool().getRegisteredConfig().getProperty("groupAware"); state.setAttribute("groupAware", groupAware != null?Boolean.valueOf(groupAware):Boolean.FALSE); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to List */ private List iterator_to_list(Iterator l) { List v = new ArrayList(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_list /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new ArrayList(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (MODE_LIST_ASSIGNMENTS.equals(mode)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || (!allowAddAssignment && AssignmentService.allowAddSubmission((String) state .getAttribute(STATE_CONTEXT_STRING)))) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || "".equals(deleted)) { // show not deleted assignments Time openTime = a.getOpenTime(); Time visibleTime = a.getVisibleTime(); if ( ( (openTime != null && currentTime.after(openTime))|| (visibleTime != null && currentTime.after(visibleTime)) ) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) && getSubmission(a.getReference(), (User) state.getAttribute(STATE_USER), "sizeResources", state) != null) { // and those deleted but not non-electronic assignments but the user has made submissions to them returnResources.add(a); } } } else { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1)); } else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode)) { returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode)) { initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); Boolean has_multiple_groups_for_user = false; List submissions = new ArrayList(); List assignments = iterator_to_list(AssignmentService.getAssignmentsForContext(contextString)); if (assignments.size() > 0) { try { // get the site object first Site site = SiteService.getSite(contextString); for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, a.getReference(), contextString); Collection<String> _dupUsers = new ArrayList<String>(); if (a.isGroup()) { _dupUsers = usersInMultipleGroups(a, true); } //get the list of users which are allowed to grade this assignment List allowGradeAssignmentUsers = AssignmentService.allowGradeAssignmentUsers(a.getReference()); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || "".equals(deleted)) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference())) { try { List assignmentSubmissions = AssignmentService.getSubmissions(a); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s.getTimeReturned()))))) { //If the group search is null or if it contains the group if (submitterIds.contains(s.getSubmitterId())){ if (a.isGroup()) { User[] _users = s.getSubmitters(); for (int m=0; _users != null && m < _users.length; m++) { Member member = site.getMember(_users[m].getId()); if (member != null && member.isActive()) { // only include the active student submission // conder TODO create temporary submissions SubmitterSubmission _new_sub = new SubmitterSubmission(_users[m], s); _new_sub.setGroup(site.getGroup(s.getSubmitterId())); if (_dupUsers.size() > 0 && _dupUsers.contains(_users[m].getId())) { _new_sub.setMultiGroup(true); has_multiple_groups_for_user = true; } submissions.add(_new_sub); } } } else { if (s.getSubmitterId() != null && !allowGradeAssignmentUsers.contains(s.getSubmitterId())) { // find whether the submitter is still an active member of the site Member member = site.getMember(s.getSubmitterId()); if(member != null && member.isActive()) { // only include the active student submission try { SubmitterSubmission _new_sub = new SubmitterSubmission(UserDirectoryService.getUser(s.getSubmitterId()), s); submissions.add(_new_sub); } catch (UserNotDefinedException e) { M_log.warn(this + ":sizeResources cannot find user id=" + s.getSubmitterId() + e.getMessage() + ""); } } } } } } // if-else } } catch (Exception e) { M_log.warn(this + ":sizeResources " + e.getMessage()); } } } if (has_multiple_groups_for_user) { addAlert(state, rb.getString("group.user.multiple.error")); } } catch (IdUnusedException idUnusedException) { M_log.warn(this + ":sizeResources " + idUnusedException.getMessage() + " site id=" + contextString); } } // end if returnResources = submissions; } else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode)) { initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); String aRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); try { if (AssignmentService.getAssignment(aRef).isGroup()) { Collection<Group> submitterGroups = AssignmentService.getSubmitterGroupList("false", allOrOneGroup, "", aRef, contextString); // construct the group-submission list if (submitterGroups != null && !submitterGroups.isEmpty()) { for (Iterator<Group> iSubmitterGroupsIterator = submitterGroups.iterator(); iSubmitterGroupsIterator.hasNext();) { Group gId = iSubmitterGroupsIterator.next(); // Allow sections to be used for group assigments - https://jira.sakaiproject.org/browse/SAK-22425 //if (gId.getProperties().get(GROUP_SECTION_PROPERTY) == null) { try { AssignmentSubmission sub = AssignmentService.getSubmission(aRef, gId.getId()); returnResources.add(new SubmitterSubmission(gId, sub)); // UserSubmission accepts either User or Group } catch (IdUnusedException subIdException) { M_log.warn(this + ".sizeResources: looking for submission for unused assignment id " + aRef + subIdException.getMessage()); } catch (PermissionException subPerException) { M_log.warn(this + ".sizeResources: cannot have permission to access submission of assignment " + aRef + " of group " + gId.getId()); } //} } } } else { //List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); Map<User, AssignmentSubmission> submitters = AssignmentService.getSubmitterMap(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); // construct the user-submission list for (User u : submitters.keySet()) { String uId = u.getId(); AssignmentSubmission sub = submitters.get(u); SubmitterSubmission us = new SubmitterSubmission(u, sub); String submittedById = (String)sub.getProperties().get(AssignmentSubmission.SUBMITTER_USER_ID); if ( submittedById != null) { try { us.setSubmittedBy(UserDirectoryService.getUser(submittedById)); } catch (UserNotDefinedException ex1) { M_log.warn(this + ":sizeResources cannot find submitter id=" + uId + ex1.getMessage()); } } returnResources.add(us); } } } catch (PermissionException aPerException) { M_log.warn(":getSubmitterGroupList: Not allowed to get assignment " + aRef + " " + aPerException.getMessage()); } catch (org.sakaiproject.exception.IdUnusedException e) { M_log.warn(this + ":sizeResources cannot find assignment " + e.getMessage() + ""); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode) && (sort == null || !sort.startsWith("sorted_grade_submission_by"))) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode) && (sort == null || sort.startsWith("sorted_submission_by"))) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode)) { AssignmentComparator ac = new AssignmentComparator(state, sort, ascending); // figure out if we have to sort by anonymous id if (SORTED_GRADE_SUBMISSION_BY_LASTNAME.equals(sort) && (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))) { String aRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { Assignment assignment = AssignmentService.getAssignment(aRef); if (assignment != null) { ResourceProperties props = assignment.getProperties(); if (props != null) { ac.setAnon(props.getBooleanProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); } } } catch (IdUnusedException iue) { // ignore, continue with default sort } catch (PermissionException pe) { // ignore, continue with default sort } catch (EntityPropertyNotDefinedException epnde) { // ignore, continue with default sort } catch (EntityPropertyTypeException epte) { // ignore, continue with default sort } } try { Collections.sort(returnResources, ac); } catch (Exception e) { // log exception during sorting for helping debugging M_log.warn(this + ":sizeResources mode=" + mode + " sort=" + sort + " ascending=" + ascending + " " + e.getStackTrace()); } } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (MODE_LIST_ASSIGNMENTS.equals(viewMode)) { doList_assignments(data); } else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(viewMode)) { doView_students_assignment(data); } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(viewMode)) { doReport_submissions(data); } else if (MODE_STUDENT_VIEW.equals(viewMode)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade for point based type * returns a double value in a string from the localized input */ private String validPointGrade(SessionState state, String grade) { if (grade != null && !"".equals(grade)) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; // only the right decimal separator is allowed and no other grouping separator if ((",".equals(decSeparator) && grade.indexOf(".") != -1) || (".".equals(decSeparator) && grade.indexOf(",") != -1) || grade.indexOf(" ") != -1) { addAlert(state, rb.getString("plesuse1")); return grade; } // parse grade from localized number format int index = grade.indexOf(decSeparator); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!decSeparator.equals(grade)) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = grade.endsWith(decSeparator) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { nbFormat.parse(gradeString); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); alertInvalidPoint(state, gradeString); } } catch (ParseException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); addAlert(state, rb.getString("plesuse1")); } } } else { // grade is decSeparator addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { nbFormat.parse(gradeString); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); alertInvalidPoint(state, gradeString); } } catch (ParseException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); addAlert(state, rb.getString("plesuse1")); } } } } return grade; } /** * get the right number format based on local * @return */ private NumberFormat getNumberFormat() { // get localized number format NumberFormat nbFormat = NumberFormat.getInstance(); try { Locale locale = null; ResourceLoader rb = new ResourceLoader(); locale = rb.getLocale(); nbFormat = NumberFormat.getNumberInstance(locale); } catch (Exception e) { M_log.warn("Error while retrieving local number format, using default ", e); } return nbFormat; } // validPointGrade /** * valid grade for point based type */ private void validLetterGrade(SessionState state, String grade) { String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-"; boolean invalid = false; if (grade != null) { grade = grade.toUpperCase(); for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1) { invalid = true; } } if (invalid) { // -------- SAK-24199 (SAKU-274) by Shoji Kajita addAlert(state, rb.getFormattedMessage("plesuse0", new Object []{grade})); // -------- } } } private void alertInvalidPoint(SessionState state, String grade) { NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, rb.getFormattedMessage("plesuse4", new Object[]{grade.substring(0, grade.length()-1) + decSeparator + grade.substring(grade.length()-1), maxInt + decSeparator + maxDec})); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { NumberFormat nbFormat = getNumberFormat(); nbFormat.setMaximumFractionDigits(1); nbFormat.setMinimumFractionDigits(1); nbFormat.setGroupingUsed(false); DecimalFormat dcformat = (DecimalFormat) nbFormat; String decSeparator = dcformat.getDecimalFormatSymbols().getDecimalSeparator() + ""; if (grade.indexOf(decSeparator) != -1) { if (grade.startsWith(decSeparator)) { grade = "0".concat(grade); } else if (grade.endsWith(decSeparator)) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + decSeparator + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { // alert alertInvalidPoint(state, grade); M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage()); } } try { // show grade in localized number format Double dblGrade = dcformat.parse(grade).doubleValue(); grade = nbFormat.format(dblGrade); } catch (Exception e) { // alert alertInvalidPoint(state, grade); M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage()); } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; point = validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf(decSeparator); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if ("00".equals(point)) { point = "0"; } } } if (StringUtils.trimToNull(point) != null) { try { point = Integer.valueOf(point).toString(); } catch (Exception e) { M_log.warn(this + " scalePointGrade: cannot parse " + point + " into integer. " + e.getMessage()); } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuilder alertMsg = new StringBuilder(); boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuilder buf = new StringBuilder(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = true; // so that grading isn't held up by formatting errors buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuilder buf = new StringBuilder(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode) || MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode) || MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode) || MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode)|| MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode)) { // save submit inputs saveSubmitInputs(state, params); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)) { setNewAssignmentParameters(data, false); } else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if ("cancel".equals(option)) { // cancel doCancel_show_submission(data); } else if ("preview".equals(option)) { // preview doPreview_submission(data); } else if ("save".equals(option)) { // save draft doSave_submission(data); } else if ("post".equals(option)) { // post doPost_submission(data); } else if ("revise".equals(option)) { // done preview doDone_preview_submission(data); } else if ("attach".equals(option)) { // attach ToolSession toolSession = SessionManager.getCurrentToolSession(); String userId = SessionManager.getCurrentSessionUserId(); String siteId = SiteService.getUserSiteId(userId); String collectionId = m_contentHostingService.getSiteCollection(siteId); toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId); doAttachments(data); } else if ("removeAttachment".equals(option)) { // remove selected attachment doRemove_attachment(data); } else if ("removeNewSingleUploadedFile".equals(option)) { doRemove_newSingleUploadedFile(data); } else if ("upload".equals(option)) { // upload local file doAttachUpload(data, true); } else if ("uploadSingleFile".equals(option)) { // upload single local file doAttachUpload(data, false); } } public void doRemove_attachment(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); // save submit inputs before refresh the page saveSubmitInputs(state, params); String removeAttachmentId = params.getString("currentAttachment"); List attachments = state.getAttribute(ATTACHMENTS) == null?null:((List) state.getAttribute(ATTACHMENTS)).isEmpty()?null:(List) state.getAttribute(ATTACHMENTS); if (attachments != null) { Reference found = null; for(Object attachment : attachments) { if (((Reference) attachment).getId().equals(removeAttachmentId)) { found = (Reference) attachment; break; } } if (found != null) { attachments.remove(found); // refresh state variable state.setAttribute(ATTACHMENTS, attachments); } } } public void doRemove_newSingleUploadedFile(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid()); state.removeAttribute("newSingleUploadedFile"); } /** * return returns all groups in a site * @param contextString * @param aRef * @return */ protected Collection getAllGroupsInSite(String contextString) { Collection groups = new ArrayList(); try { Site site = SiteService.getSite(contextString); // any group in the site? groups = site.getGroups(); } catch (IdUnusedException e) { // TODO Auto-generated catch block M_log.info("Problem getting groups for site:"+e.getMessage()); } return groups; } /** * return list of submission object based on the group filter/search result * @param state * @param aRef * @return */ protected List<AssignmentSubmission> getFilteredSubmitters(SessionState state, String aRef) { List<AssignmentSubmission> rv = new ArrayList<AssignmentSubmission>(); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); //List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); Map<User, AssignmentSubmission> submitters = AssignmentService.getSubmitterMap(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); // construct the user-submission list for (AssignmentSubmission sub : submitters.values()) { if (!rv.contains(sub)) rv.add(sub); } return rv; } /** * Set default score for all ungraded non electronic submissions * @param data */ public void doSet_defaultNotGradedNonElectronicScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtils.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); // record the default grade setting for no-submission AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); } Assignment a = getAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state); if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { M_log.warn(this + ":setDefaultNotGradedNonElectronicScore " + e.getMessage()); alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List submissions = getFilteredSubmitters(state, a.getReference()); for (int i = 0; i<submissions.size(); i++) { // get the submission object AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i); if (submission.getSubmitted() && !submission.getGraded()) { String sRef = submission.getReference(); // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doSet_defaultNotGradedNonElectronicScore", state); if (sEdit != null) { sEdit.setGrade(grade); sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); AssignmentService.commitEdit(sEdit); } } } } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtils.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); // record the default grade setting for no-submission AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); } Assignment a = getAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state); if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); M_log.warn(this + ":setDefaultNoSubmissionScore " + e.getMessage()); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the submission list List submissions = getFilteredSubmitters(state, a.getReference()); for (int i = 0; i<submissions.size(); i++) { // get the submission object AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i); if (StringUtils.trimToNull(submission.getGrade()) == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state); if (sEdit != null) { sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); AssignmentService.commitEdit(sEdit); } } else if (StringUtils.trimToNull(submission.getGrade()) != null && !submission.getGraded()) { // correct the grade status if there is a grade but the graded is false AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state); if (sEdit != null) { sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); AssignmentService.commitEdit(sEdit); } } } } } /** * A utility method to determine users listed in multiple groups * eligible to submit an assignment. This is a bad situation. * Current mechanism is to error out assignments with this situation * to prevent affected groups from submitting and viewing feedback * and prevent instructors from grading or sending feedback to * affected groups until the conflict is resolved (by altering * membership or perhaps by designating a resolution). * * @param assignmentorstate * @param specify_groups * @param ingroups * @param populate_ids * @param users * @return */ public Collection<String> usersInMultipleGroups( Object assignmentorstate, // an assignment object or state object to find data boolean specify_groups, // don't use all site groups String[] ingroups, // limit to looking at specific groups boolean populate_ids, // return collection of user ids instead of message strings Collection<String> users // optional list of users to check instead of ALL site users ) { List retVal = new ArrayList(); try { Site s = null; Collection<String> _assignmentGroups = new ArrayList<String>(); for (int i=0; ingroups != null && i < ingroups.length; i++) { _assignmentGroups.add(ingroups[i]); } if (assignmentorstate instanceof SessionState) { s = SiteService.getSite((String)((SessionState)assignmentorstate).getAttribute(STATE_CONTEXT_STRING)); } else { Assignment _a = (Assignment)assignmentorstate; s = SiteService.getSite(_a.getContext()); if (_a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { specify_groups = false; } else { _assignmentGroups = _a.getGroups(); specify_groups = true; } } Iterator<String> _it = users == null ? s.getUsers().iterator(): users.iterator(); while (_it.hasNext()) { String _userRef = _it.next(); Collection<Group> _userGroups = s.getGroupsWithMember(_userRef); int _count = 0; StringBuilder _sb = new StringBuilder(); Iterator<Group> _checkGroups = _userGroups.iterator(); while (_checkGroups.hasNext()) { Group _checkGroup = _checkGroups.next(); // exclude Sections from eligible groups //if (_checkGroup.getProperties().get(GROUP_SECTION_PROPERTY) == null) { if (!specify_groups) { _count++; if (_count > 1) { _sb.append(", "); } _sb.append(_checkGroup.getTitle()); } else { if (_assignmentGroups != null) { Iterator<String> _assgnRefs = _assignmentGroups.iterator(); while (_assgnRefs.hasNext()) { String _ref = _assgnRefs.next(); Group _group = s.getGroup(_ref); if (_group != null && _group.getId().equals(_checkGroup.getId())) { _count++; if (_count > 1) { _sb.append(", "); } _sb.append(_checkGroup.getTitle()); } } } } //} } if (_count > 1) { try { User _the_user = UserDirectoryService.getUser(_userRef); /* * SAK-23697 Allow user to be in multiple groups if * no SECURE_ADD_ASSIGNMENT_SUBMISSION permission or * if user has both SECURE_ADD_ASSIGNMENT_SUBMISSION * and SECURE_GRADE_ASSIGNMENT_SUBMISSION permission (TAs and Instructors) */ if (m_securityService.unlock(_the_user,AssignmentService.SECURE_ADD_ASSIGNMENT_SUBMISSION,s.getReference()) && !m_securityService.unlock(_the_user,AssignmentService.SECURE_GRADE_ASSIGNMENT_SUBMISSION,s.getReference())) { retVal.add(populate_ids ? _the_user.getId(): _the_user.getDisplayName() + " (" + _sb.toString() + ")"); }; } catch (UserNotDefinedException _unde) { retVal.add("UNKNOWN USER (" + _sb.toString() + ")"); } } } } catch (IdUnusedException _te) { throw new IllegalStateException("Could not find the site for assignment/state "+assignmentorstate+": "+_te, _te); } return retVal; } public Collection<String> usersInMultipleGroups(Assignment _a, boolean populate_ids) { return usersInMultipleGroups(_a,false,null,populate_ids,null); } public Collection<String> usersInMultipleGroups(Assignment _a) { return usersInMultipleGroups(_a,false,null,false,null); } public Collection<String> checkForUsersInMultipleGroups( Assignment a, Collection<String> ids, SessionState state, String base_message) { Collection<String> _dupUsers = usersInMultipleGroups(a,false,null,false,ids); if (_dupUsers.size() > 0) { StringBuilder _sb = new StringBuilder(base_message + " "); Iterator<String> _it = _dupUsers.iterator(); if (_it.hasNext()) { _sb.append(_it.next()); } while (_it.hasNext()) { _sb.append(", " + _it.next()); } addAlert(state, _sb.toString()); } return _dupUsers; } public Collection<String> checkForGroupsInMultipleGroups( Assignment a, Collection<Group> groups, SessionState state, String base_message) { Collection<String> retVal = new ArrayList<String>(); if (groups != null && groups.size() > 0) { ArrayList<String> check_users = new ArrayList<String>(); Iterator<Group> it_groups = groups.iterator(); while (it_groups.hasNext()) { Group _group = it_groups.next(); Iterator<String> it_strings = _group.getUsers().iterator(); while (it_strings.hasNext()) { String _id = it_strings.next(); if (!check_users.contains(_id)) { check_users.add(_id); } } } retVal = checkForUsersInMultipleGroups(a, check_users, state, rb.getString("group.user.multiple.warning")); } return retVal; } /** * * @return */ public void doDownload_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String flow = params.getString("flow"); if ("upload".equals(flow)) { // upload doUpload_all(data); } else if ("download".equals(flow)) { // upload doDownload_all(data); } else if ("cancel".equals(flow)) { // cancel doCancel_download_upload_all(data); } } public void doDownload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } public void doUpload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = params.getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); if(fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{max_file_size_mb})); } else { String fname = StringUtils.lowerCase(fileFromUpload.getFileName()); if (!StringUtils.endsWithAny(fname, new String[] {".zip", ".sit"})) { // no file addAlert(state, rb.getString("uploadall.alert.zipFile")); } else { String contextString = ToolManager.getCurrentPlacement().getContext(); String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle(); String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); String associateGradebookAssignment = null; List<String> choices = params.getStrings("choices") != null?new ArrayList(Arrays.asList(params.getStrings("choices"))):null; if (choices == null || choices.size() == 0) { // has to choose one upload feature addAlert(state, rb.getString("uploadall.alert.choose.element")); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_GRADEFILE_FORMAT); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_WITHOUT_FOLDERS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } else { // should contain student submission text information boolean hasSubmissionText = uploadAll_readChoice(choices, "studentSubmissionText"); // should contain student submission attachment information boolean hasSubmissionAttachment = uploadAll_readChoice(choices, "studentSubmissionAttachment"); // should contain grade file boolean hasGradeFile = uploadAll_readChoice(choices, "gradeFile"); String gradeFileFormat = params.getString("gradeFileFormat"); if ("excel".equals(gradeFileFormat)) {gradeFileFormat="excel";} else {gradeFileFormat="csv";}; // inline text boolean hasFeedbackText = uploadAll_readChoice(choices, "feedbackTexts"); // comments.txt should be available boolean hasComment = uploadAll_readChoice(choices, "feedbackComments"); // feedback attachment boolean hasFeedbackAttachment = uploadAll_readChoice(choices, "feedbackAttachments"); // folders //boolean withoutFolders = params.getString("withoutFolders") != null ? params.getBoolean("withoutFolders") : false; boolean withoutFolders = uploadAll_readChoice(choices, "withoutFolders"); // SAK-19147 // release boolean releaseGrades = params.getString("release") != null ? params.getBoolean("release") : false; state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText)); state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment)); state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile)); state.setAttribute(UPLOAD_ALL_GRADEFILE_FORMAT, gradeFileFormat); state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment)); state.setAttribute(UPLOAD_ALL_WITHOUT_FOLDERS, Boolean.valueOf(withoutFolders)); state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades)); // SAK-17606 HashMap anonymousSubmissionAndEidTable = new HashMap(); // constructor the hashmap for all submission objects HashMap submissionTable = new HashMap(); List submissions = null; Assignment assignment = getAssignment(aReference, "doUpload_all", state); if (assignment != null) { associateGradebookAssignment = StringUtils.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); submissions = AssignmentService.getSubmissions(assignment); if (submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { try { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); String _eid = s.getSubmitterId(); submissionTable.put(_eid, new UploadGradeWrapper(s.getGrade(), s.getSubmittedText(), s.getFeedbackComment(), hasSubmissionAttachment?new ArrayList():s.getSubmittedAttachments(), hasFeedbackAttachment?new ArrayList():s.getFeedbackAttachments(), (s.getSubmitted() && s.getTimeSubmitted() != null)?s.getTimeSubmitted().toString():"", s.getFeedbackText())); // SAK-17606 anonymousSubmissionAndEidTable.put(s.getAnonymousSubmissionId(), _eid); } catch (Throwable _eidprob) {} } } } InputStream fileContentStream = fileFromUpload.getInputStream(); if(fileContentStream != null) { submissionTable = uploadAll_parseZipFile(state, hasSubmissionText, hasSubmissionAttachment, hasGradeFile, hasFeedbackText, hasComment, hasFeedbackAttachment, submissionTable, assignment, fileContentStream,gradeFileFormat, anonymousSubmissionAndEidTable); } if (state.getAttribute(STATE_MESSAGE) == null) { // update related submissions uploadAll_updateSubmissions(state, aReference, associateGradebookAssignment, hasSubmissionText, hasSubmissionAttachment, hasGradeFile, hasFeedbackText, hasComment, hasFeedbackAttachment, releaseGrades, submissionTable, submissions, assignment); } } } } if (state.getAttribute(STATE_MESSAGE) == null) { // go back to the list of submissions view cleanUploadAllContext(state); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } } private boolean uploadAll_readChoice(List<String> choices, String text) { return choices != null && text != null && choices.contains(text) ? true:false; } /** * parse content inside uploaded zip file * @param state * @param hasSubmissionText * @param hasSubmissionAttachment * @param hasGradeFile * @param hasFeedbackText * @param hasComment * @param hasFeedbackAttachment * @param submissionTable * @param assignment * @param fileContentStream * @return */ private HashMap uploadAll_parseZipFile(SessionState state, boolean hasSubmissionText, boolean hasSubmissionAttachment, boolean hasGradeFile, boolean hasFeedbackText, boolean hasComment, boolean hasFeedbackAttachment, HashMap submissionTable, Assignment assignment, InputStream fileContentStream,String gradeFileFormat, HashMap anonymousSubmissionAndEidTable) { // a flag value for checking whether the zip file is of proper format: // should have a grades.csv file or grades.xls if there is no user folders boolean zipHasGradeFile = false; // and if have any folder structures, those folders should be named after at least one site user (zip file could contain user names who is no longer inside the site) boolean zipHasFolder = false; boolean zipHasFolderValidUserId = false; FileOutputStream tmpFileOut = null; File tempFile = null; // as stated from UI, we expected the zip file to have structure as follows // assignment_name/user_eid/files // or assignment_name/grades.csv or assignment_name/grades.xls boolean validZipFormat = true; try { tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),""); tmpFileOut = new FileOutputStream(tempFile); writeToStream(fileContentStream, tmpFileOut); tmpFileOut.flush(); tmpFileOut.close(); ZipFile zipFile = new ZipFile(tempFile, "UTF-8"); Enumeration<ZipEntry> zipEntries = zipFile.getEntries(); ZipEntry entry; while (zipEntries.hasMoreElements() && validZipFormat) { entry = zipEntries.nextElement(); String entryName = entry.getName(); if (!entry.isDirectory() && entryName.indexOf("/.") == -1) { // SAK-17606 String anonTitle = rb.getString("grading.anonymous.title"); if (entryName.endsWith("grades.csv") || entryName.endsWith("grades.xls")) { if (hasGradeFile && entryName.endsWith("grades.csv") && "csv".equals(gradeFileFormat)) { // at least the zip file has a grade.csv zipHasGradeFile = true; // read grades.cvs from zip CSVReader reader = new CSVReader(new InputStreamReader(zipFile.getInputStream(entry))); List <String[]> lines = reader.readAll(); if (lines != null ) { for (int i = 3; i<lines.size(); i++) { String[] items = lines.get(i); if ((assignment.isGroup() && items.length > 3) || items.length > 4) { // has grade information try { String _the_eid = items[1]; if (!assignment.isGroup()) { // SAK-17606 User u = null; // check for anonymous grading if (!items[IDX_GRADES_CSV_EID].contains(anonTitle)) { u = UserDirectoryService.getUserByEid(items[IDX_GRADES_CSV_EID]); } else { // anonymous so pull the real eid out of our hash table String anonId = items[IDX_GRADES_CSV_EID]; String eid = (String) anonymousSubmissionAndEidTable.get(anonId); u = UserDirectoryService.getUserByEid(eid); } if (u == null) throw new Exception("User not found!"); _the_eid = u.getId(); } UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(_the_eid); if (w != null) { String itemString = assignment.isGroup() ? items[3]: items[4]; int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { validPointGrade(state, itemString); } // SAK-24199 - Applied patch provided with a few additional modifications. else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) { itemString = validatePassFailGradeValue(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString); submissionTable.put(_the_eid, w); } } } catch (Exception e ) { M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } } } } } //end of csv grades import //Excel file import if (hasGradeFile && entryName.endsWith("grades.xls") && "excel".equals(gradeFileFormat)) { // at least the zip file has a grade.csv zipHasGradeFile = true; // read grades.xls from zip POIFSFileSystem fsFileSystem = new POIFSFileSystem(zipFile.getInputStream(entry)); HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem); HSSFSheet hssfSheet = workBook.getSheetAt(0); //Iterate the rows Iterator rowIterator = hssfSheet.rowIterator(); int count = 0; while (rowIterator.hasNext()) { HSSFRow hssfRow = (HSSFRow) rowIterator.next(); //We skip first row (= header row) if (count > 0) { double gradeXls = -1; String itemString = null; // has grade information try { String _the_eid = hssfRow.getCell(1).getStringCellValue(); if (!assignment.isGroup()) { User u = UserDirectoryService.getUserByEid(hssfRow.getCell(1).getStringCellValue()/*user eid*/); if (u == null) throw new Exception("User not found!"); _the_eid = u.getId(); } UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(_the_eid); if (w != null) { itemString = assignment.isGroup() ? hssfRow.getCell(3).toString() : hssfRow.getCell(4).toString(); int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { //Parse the string to double using the locale format try { itemString = assignment.isGroup() ? hssfRow.getCell(3).getStringCellValue() : hssfRow.getCell(4).getStringCellValue(); if ((itemString != null) && (itemString.trim().length() > 0)) { NumberFormat nbFormat = NumberFormat.getInstance(new ResourceLoader().getLocale()); gradeXls = nbFormat.parse(itemString).doubleValue(); } } catch (Exception e) { try { gradeXls = assignment.isGroup() ? hssfRow.getCell(3).getNumericCellValue() : hssfRow.getCell(4).getNumericCellValue(); } catch (Exception e2) { gradeXls = -1; } } if (gradeXls != -1) { // get localized number format NumberFormat nbFormat = NumberFormat.getInstance(); try { Locale locale = null; ResourceLoader rb = new ResourceLoader(); locale = rb.getLocale(); nbFormat = NumberFormat.getNumberInstance(locale); itemString = nbFormat.format(gradeXls); } catch (Exception e) { M_log.warn("Error while retrieving local number format, using default ", e); } } else { itemString = ""; } validPointGrade(state, itemString); } else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) { itemString = validatePassFailGradeValue(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE ? scalePointGrade(state, itemString) : itemString); submissionTable.put(_the_eid, w); } } } catch (Exception e) { M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } } count++; } } //end of Excel grades import } else { String[] pathParts = entryName.split("/"); if (pathParts.length <=2) { validZipFormat=false; } else { // get user eid part String userEid = ""; if (entryName.indexOf("/") != -1) { // there is folder structure inside zip if (!zipHasFolder) zipHasFolder = true; // remove the part of zip name userEid = entryName.substring(entryName.indexOf("/")+1); // get out the user name part if (userEid.indexOf("/") != -1) { userEid = userEid.substring(0, userEid.indexOf("/")); } // SAK-17606 - get the eid part if ((userEid.indexOf("(") != -1) && !userEid.contains(anonTitle)) { userEid = userEid.substring(userEid.indexOf("(")+1, userEid.indexOf(")")); } if (userEid.contains(anonTitle)) { // anonymous grading so we have to figure out the eid //get eid out of this slick table we made earlier userEid = (String) anonymousSubmissionAndEidTable.get(userEid); } userEid=StringUtils.trimToNull(userEid); if (!assignment.isGroup()) { try { User u = UserDirectoryService.getUserByEid(userEid/*user eid*/); if (u != null) userEid = u.getId(); } catch (Throwable _t) { } } } if (submissionTable.containsKey(userEid)) { if (!zipHasFolderValidUserId) zipHasFolderValidUserId = true; if (hasComment && entryName.indexOf("comments") != -1) { // read the comments file String comment = getBodyTextFromZipHtml(zipFile.getInputStream(entry)); if (comment != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setComment(comment); submissionTable.put(userEid, r); } } if (hasFeedbackText && entryName.indexOf("feedbackText") != -1) { // upload the feedback text String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry)); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackText(text); submissionTable.put(userEid, r); } } if (hasSubmissionText && entryName.indexOf("_submissionText") != -1) { // upload the student submission text String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry)); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setText(text); submissionTable.put(userEid, r); } } if (hasSubmissionAttachment) { // upload the submission attachment String submissionFolder = "/" + rb.getString("stuviewsubm.submissatt") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); submissionTable.put(userEid, r); submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "submission"); } } if (hasFeedbackAttachment) { // upload the feedback attachment String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the feedback attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); submissionTable.put(userEid, r); submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "feedback"); } } // if this is a timestamp file if (entryName.indexOf("timestamp") != -1) { byte[] timeStamp = readIntoBytes(zipFile.getInputStream(entry), entryName, entry.getSize()); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionTimestamp(new String(timeStamp)); submissionTable.put(userEid, r); } } } } } } } catch (IOException e) { // uploaded file is not a valid archive addAlert(state, rb.getString("uploadall.alert.zipFile")); M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } finally { if (tmpFileOut != null) { try { tmpFileOut.close(); } catch (IOException e) { M_log.warn(this + ":uploadAll_parseZipFile: Error closing temp file output stream: " + e.toString()); } } if (fileContentStream != null) { try { fileContentStream.close(); } catch (IOException e) { M_log.warn(this + ":uploadAll_parseZipFile: Error closing file upload stream: " + e.toString()); } } //clean up the zip file if (tempFile != null && tempFile.exists()) { if (!tempFile.delete()) { M_log.warn("Failed to clean up temp file"); } } } //This is used so that the "Zip Error" message is only printed once boolean zipError = false; // generate error when there is no grade file and no folder structure if (!zipHasGradeFile && !zipHasFolder) { addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); addAlert(state, rb.getString("uploadall.alert.noGradeFile")); zipError = true; } // generate error when there is folder structure but not matching one user id if(zipHasFolder && !zipHasFolderValidUserId) { if (zipError == false) addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); addAlert(state, rb.getString("uploadall.alert.invalidUserId")); zipError = true; } // should have right structure of zip file if (!validZipFormat) { if (zipError == false) addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); // alert if the zip is of wrong format addAlert(state, rb.getString("uploadall.alert.wrongZipFormat")); zipError = true; } return submissionTable; } /** * Update all submission objects based on uploaded zip file * @param state * @param aReference * @param associateGradebookAssignment * @param hasSubmissionText * @param hasSubmissionAttachment * @param hasGradeFile * @param hasFeedbackText * @param hasComment * @param hasFeedbackAttachment * @param releaseGrades * @param submissionTable * @param submissions * @param assignment */ private void uploadAll_updateSubmissions(SessionState state, String aReference, String associateGradebookAssignment, boolean hasSubmissionText, boolean hasSubmissionAttachment, boolean hasGradeFile, boolean hasFeedbackText, boolean hasComment, boolean hasFeedbackAttachment, boolean releaseGrades, HashMap submissionTable, List submissions, Assignment assignment) { if (assignment != null && submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); if (submissionTable.containsKey(s.getSubmitterId())) { // update the AssignmetnSubmission record AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "doUpload_all", state); if (sEdit != null) { UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(s.getSubmitterId()); // the submission text if (hasSubmissionText) { sEdit.setSubmittedText(w.getText()); } // the feedback text if (hasFeedbackText) { sEdit.setFeedbackText(w.getFeedbackText()); } // the submission attachment if (hasSubmissionAttachment) { // update the submission attachments with newly added ones from zip file List submittedAttachments = sEdit.getSubmittedAttachments(); for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();) { Reference a = (Reference) attachments.next(); if (!submittedAttachments.contains(a)) { sEdit.addSubmittedAttachment(a); } } } // the feedback attachment if (hasFeedbackAttachment) { List feedbackAttachments = sEdit.getFeedbackAttachments(); for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();) { // update the feedback attachments with newly added ones from zip file Reference a = (Reference) attachments.next(); if (!feedbackAttachments.contains(a)) { sEdit.addFeedbackAttachment(a); } } } // the feedback comment if (hasComment) { sEdit.setFeedbackComment(w.getComment()); } // the grade file if (hasGradeFile) { // set grade String grade = StringUtils.trimToNull(w.getGrade()); sEdit.setGrade(grade); if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !"ungraded".equals(grade)){ sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } } // release or not if (sEdit.getGraded()) { sEdit.setGradeReleased(releaseGrades); sEdit.setReturned(releaseGrades); } else { sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (releaseGrades && sEdit.getGraded()) { sEdit.setTimeReturned(TimeService.newTime()); } // if the current submission lacks timestamp while the timestamp exists inside the zip file if (StringUtils.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null) { sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp())); sEdit.setSubmitted(true); } // for further information boolean graded = sEdit.getGraded(); String sReference = sEdit.getReference(); // commit AssignmentService.commitEdit(sEdit); if (releaseGrades && graded) { // update grade in gradebook if (associateGradebookAssignment != null) { integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1); } } } } } } } /** * This is to get the submission or feedback attachment from the upload zip file into the submission object * @param state * @param submissionTable * @param zin * @param entry * @param entryName * @param userEid * @param submissionOrFeedback */ private HashMap uploadZipAttachments(SessionState state, HashMap submissionTable, InputStream zin, ZipEntry entry, String entryName, String userEid, String submissionOrFeedback) { // upload all the files as instructor attachments to the submission for grading purpose String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length()); ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); try { // get file extension for detecting content type // ignore those hidden files String extension = ""; if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0)) { // add the file as attachment ResourceProperties properties = m_contentHostingService.newResourceProperties(); properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName); String[] parts = fName.split("\\."); if(parts.length > 1) { extension = parts[parts.length - 1]; } try { String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension); ContentResourceEdit attachment = m_contentHostingService.addAttachmentResource(fName); attachment.setContent(zin); attachment.setContentType(contentType); attachment.getPropertiesEdit().addAll(properties); m_contentHostingService.commitResource(attachment); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); List attachments = "submission".equals(submissionOrFeedback)?r.getSubmissionAttachments():r.getFeedbackAttachments(); attachments.add(EntityManager.newReference(attachment.getReference())); if ("submission".equals(submissionOrFeedback)) { r.setSubmissionAttachments(attachments); } else { r.setFeedbackAttachments(attachments); } submissionTable.put(userEid, r); } catch (Exception e) { M_log.warn(this + ":doUploadZipAttachments problem commit resource " + e.getMessage()); } } } catch (Exception ee) { M_log.warn(this + ":doUploadZipAttachments " + ee.getMessage()); } return submissionTable; } private String getBodyTextFromZipHtml(InputStream zin) { String rv = ""; try { rv = StringUtils.trimToNull(readIntoString(zin)); } catch (IOException e) { M_log.warn(this + ":getBodyTextFromZipHtml " + e.getMessage()); } if (rv != null) { int start = rv.indexOf("<body>"); int end = rv.indexOf("</body>"); if (start != -1 && end != -1) { // get the text in between rv = rv.substring(start+6, end); } } return rv; } private byte[] readIntoBytes(InputStream zin, String fName, long length) throws IOException { byte[] buffer = new byte[4096]; File f = File.createTempFile("asgnup", "tmp"); FileOutputStream fout = new FileOutputStream(f); try { int len; while ((len = zin.read(buffer)) > 0) { fout.write(buffer, 0, len); } zin.close(); } finally { try { fout.close(); // The file channel needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileOutputStream " + ioException.getMessage()); } } FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); byte[] data = null; try { data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel ByteBuffer bb = ByteBuffer.wrap(data); fc.read(bb); } finally { try { fc.close(); // The file channel needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileChannel " + ioException.getMessage()); } try { fis.close(); // The file inputstream needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileInputStream " + ioException.getMessage()); } } //remove the file f.delete(); return data; } private String readIntoString(InputStream zin) throws IOException { StringBuilder buffer = new StringBuilder(); int size = 2048; byte[] data = new byte[2048]; while (true) { try { size = zin.read(data, 0, data.length); if (size > 0) { buffer.append(new String(data, 0, size)); } else { break; } } catch (IOException e) { M_log.warn(this + ":readIntoString " + e.getMessage()); } } return buffer.toString(); } /** * * @return */ public void doCancel_download_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); ParameterParser params = data.getParameters(); String downloadUrl = params.getString("downloadUrl"); state.setAttribute(STATE_DOWNLOAD_URL, downloadUrl); cleanUploadAllContext(state); } /** * clean the state variabled used by upload all process */ private void cleanUploadAllContext(SessionState state) { state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_GRADEFILE_FORMAT); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_WITHOUT_FOLDERS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } /** * Action is to preparing to go to the download all file */ public void doPrep_download_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String view = params.getString("view"); state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DOWNLOAD_ALL); } // doPrep_download_all /** * Action is to preparing to go to the upload files */ public void doPrep_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL); } // doPrep_upload_all /** * the UploadGradeWrapper class to be used for the "upload all" feature */ public class UploadGradeWrapper { /** * the grade */ String m_grade = null; /** * the text */ String m_text = null; /** * the submission attachment list */ List m_submissionAttachments = EntityManager.newReferenceList(); /** * the comment */ String m_comment = ""; /** * the timestamp */ String m_timeStamp=""; /** * the feedback text */ String m_feedbackText=""; /** * the feedback attachment list */ List m_feedbackAttachments = EntityManager.newReferenceList(); public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText) { m_grade = grade; m_text = text; m_comment = comment; m_submissionAttachments = submissionAttachments; m_feedbackAttachments = feedbackAttachments; m_feedbackText = feedbackText; m_timeStamp = timeStamp; } /** * Returns grade string */ public String getGrade() { return m_grade; } /** * Returns the text */ public String getText() { return m_text; } /** * Returns the comment string */ public String getComment() { return m_comment; } /** * Returns the submission attachment list */ public List getSubmissionAttachments() { return m_submissionAttachments; } /** * Returns the feedback attachment list */ public List getFeedbackAttachments() { return m_feedbackAttachments; } /** * submission timestamp * @return */ public String getSubmissionTimeStamp() { return m_timeStamp; } /** * feedback text/incline comment * @return */ public String getFeedbackText() { return m_feedbackText; } /** * set the grade string */ public void setGrade(String grade) { m_grade = grade; } /** * set the text */ public void setText(String text) { m_text = text; } /** * set the comment string */ public void setComment(String comment) { m_comment = comment; } /** * set the submission attachment list */ public void setSubmissionAttachments(List attachments) { m_submissionAttachments = attachments; } /** * set the attachment list */ public void setFeedbackAttachments(List attachments) { m_feedbackAttachments = attachments; } /** * set the submission timestamp */ public void setSubmissionTimestamp(String timeStamp) { m_timeStamp = timeStamp; } /** * set the feedback text */ public void setFeedbackText(String feedbackText) { m_feedbackText = feedbackText; } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); return providers; } private void addActivity(Context context, Assignment assignment) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("activity", assignmentActivityProducer .getActivity(assignment)); String placement = ToolManager.getCurrentPlacement().getId(); context.put("iframeId", Validator.escapeJavascript("Main" + placement)); } private void addItem(Context context, AssignmentSubmission submission, String userId) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("item", assignmentActivityProducer .getItem(submission, userId)); } private ContentReviewService contentReviewService; public String getReportURL(Long score) { getContentReviewService(); return contentReviewService.getIconUrlforScore(score); } private void getContentReviewService() { if (contentReviewService == null) { contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName()); } } /******************* model answer *********/ /** * add model answer input into state variables */ public void doModel_answer(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String text = StringUtils.trimToNull(params.get("modelanswer_text")); if (text == null) { // no text entered for model answer addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noText")); } int showTo = params.getInt("modelanswer_showto"); if (showTo == 0) { // no show to criteria specifided for model answer addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noShowTo")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER, Boolean.TRUE); state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_TEXT, text); state.setAttribute(NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT, showTo); //state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT); } } private void assignment_resubmission_option_into_context(Context context, SessionState state) { context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) : null; String allowResubmitTimeString = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) : null; // the resubmit number if (allowResubmitNumber != null && !"0".equals(allowResubmitNumber)) { context.put("value_allowResubmitNumber", Integer.valueOf(allowResubmitNumber)); context.put("resubmitNumber", "-1".equals(allowResubmitNumber) ? rb.getString("allow.resubmit.number.unlimited"): allowResubmitNumber); // put allow resubmit time information into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); // resubmit close time Time resubmitCloseTime = null; if (allowResubmitTimeString != null) { resubmitCloseTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString)); } // put into context if (resubmitCloseTime != null) { context.put("resubmitCloseTime", resubmitCloseTime.toStringLocalFull()); } } context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); } private void assignment_resubmission_option_into_state(Assignment a, AssignmentSubmission s, SessionState state) { String allowResubmitNumber = null; String allowResubmitTimeString = null; if (s != null) { // if submission is present, get the resubmission values from submission object first ResourceProperties sProperties = s.getProperties(); allowResubmitNumber = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); allowResubmitTimeString = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } else if (a != null) { // otherwise, if assignment is present, get the resubmission values from assignment object next ResourceProperties aProperties = a.getProperties(); allowResubmitNumber = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); allowResubmitTimeString = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } if (StringUtils.trimToNull(allowResubmitNumber) != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } if (allowResubmitTimeString == null) { // default setting allowResubmitTimeString = String.valueOf(a.getCloseTime().getTime()); } Time allowResubmitTime = null; if (allowResubmitTimeString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, allowResubmitTimeString); // get time object allowResubmitTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString)); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } if (allowResubmitTime != null) { // set up related state variables putTimePropertiesInState(state, allowResubmitTime, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); } } /** * save the resubmit option for selected users * @param data */ public void doSave_resubmission_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // read in user input into state variable if (StringUtils.trimToNull(params.getString("allowResToggle")) != null) { if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params readAllowResubmitParams(params, state, null); } } else { resetAllowResubmitParams(state); } String[] userIds = params.getStrings("selectedAllowResubmit"); if (userIds == null || userIds.length == 0) { addAlert(state, rb.getString("allowResubmission.nouser")); } else { for (int i = 0; i < userIds.length; i++) { String userId = userIds[i]; try { String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Assignment _a = getAssignment(assignmentRef, " resubmit update ", state); AssignmentSubmission submission = null; if (_a.isGroup()) { submission = getSubmission(assignmentRef, userId, "doSave_resubmission_option", state); } else { User u = UserDirectoryService.getUser(userId); submission = getSubmission(assignmentRef, u, "doSave_resubmission_option", state); } if (submission != null) { AssignmentSubmissionEdit submissionEdit = editSubmission(submission.getReference(), "doSave_resubmission_option", state); if (submissionEdit != null) { // get resubmit number ResourcePropertiesEdit pEdit = submissionEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } // save AssignmentService.commitEdit(submissionEdit); } } } catch (Exception userException) { M_log.warn(this + ":doSave_resubmission_option error getting user with id " + userId + " " + userException.getMessage()); } } } // make sure the options are exposed in UI state.setAttribute(SHOW_ALLOW_RESUBMISSION, Boolean.TRUE); } public void doSave_send_feedback(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] userIds = params.getStrings("selectedAllowResubmit"); boolean checkForFormattingErrors = true; String comment = processFormattedTextFromBrowser(state, params.getCleanString("commentFeedback"),checkForFormattingErrors); String overwrite = params.getString("overWrite"); String returnToStudents = params.getString("returnToStudents"); if (userIds == null || userIds.length == 0) { addAlert(state, rb.getString("sendFeedback.nouser")); } else { if (comment.equals("")) { addAlert(state, rb.getString("sendFeedback.nocomment")); } else { int errorUsers = 0; for (int i = 0; i < userIds.length; i++) { String userId = userIds[i]; try { User u = UserDirectoryService.getUser(userId); String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); AssignmentSubmission submission = AssignmentService.getSubmission(assignmentRef, u); if (submission != null) { AssignmentSubmissionEdit submissionEdit = AssignmentService.editSubmission(submission.getReference()); if (submissionEdit != null) { String newFeedbackComment = ""; if (overwrite != null) { newFeedbackComment = comment + "<br/>"; state.setAttribute(OW_FEEDBACK, Boolean.TRUE); } else { newFeedbackComment = submissionEdit.getFeedbackComment() + comment + "<br/>"; } submissionEdit.setFeedbackComment(newFeedbackComment); if (returnToStudents != null) { submissionEdit.setReturned(true); submissionEdit.setTimeReturned(TimeService.newTime()); state.setAttribute(RETURNED_FEEDBACK, Boolean.TRUE); } AssignmentService.commitEdit(submissionEdit); state.setAttribute(SAVED_FEEDBACK, Boolean.TRUE); } } } catch (Exception userException) { M_log.warn(this + ":doSave_send_feedback error getting user with id " + userId + " " + userException.getMessage()); errorUsers++; } } if (errorUsers>0) { addAlert(state, rb.getFormattedMessage("sendFeedback.error", new Object[]{errorUsers})); } } } // make sure the options are exposed in UI state.setAttribute(SHOW_SEND_FEEDBACK, Boolean.TRUE); } /** * multiple file upload * @param data */ public void doAttachUpload(RunData data) { // save the current input before leaving the page SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); saveSubmitInputs(state, data.getParameters ()); doAttachUpload(data, false); } /** * single file upload * @param data */ public void doAttachUploadSingle(RunData data) { doAttachUpload(data, true); } /** * upload local file for attachment * @param data * @param singleFileUpload */ public void doAttachUpload(RunData data, boolean singleFileUpload) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ToolSession toolSession = SessionManager.getCurrentToolSession(); ParameterParser params = data.getParameters (); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); // construct the state variable for attachment list List attachments = state.getAttribute(ATTACHMENTS) != null? (List) state.getAttribute(ATTACHMENTS) : EntityManager.newReferenceList(); FileItem fileitem = null; try { fileitem = params.getFileItem("upload"); } catch(Exception e) { // other exceptions should be caught earlier M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.upload")); } if(fileitem == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_file_size_mb })); //addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2")); } else if (singleFileUpload && (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)) { // only if in the single file upload case, need to warn user to upload a local file addAlert(state, rb.getString("choosefile7")); } else if (fileitem.getFileName().length() > 0) { String filename = Validator.getFileName(fileitem.getFileName()); InputStream fileContentStream = fileitem.getInputStream(); String contentType = fileitem.getContentType(); InputStreamReader reader = new InputStreamReader(fileContentStream); try{ //check the InputStreamReader to see if the file is 0kb aka empty if( reader.ready()==false ) { addAlert(state, rb.getFormattedMessage("attempty", new Object[]{filename} )); } else if(fileContentStream != null) { // we just want the file name part - strip off any drive and path stuff String name = Validator.getFileName(filename); String resourceId = Validator.escapeResourceName(name); // make a set of properties to add for the new resource ResourcePropertiesEdit props = m_contentHostingService.newResourceProperties(); props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name); props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename); // make an attachment resource for this URL SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { //Needed to be able to add or modify their own if (function.equals(m_contentHostingService.AUTH_RESOURCE_ADD) || function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_OWN)) { return SecurityAdvice.ALLOWED; } return SecurityAdvice.PASS; } }; try { String siteId = ToolManager.getCurrentPlacement().getContext(); // add attachment // put in a security advisor so we can create citationAdmin site without need // of further permissions m_securityService.pushAdvisor(sa); ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, "Assignments", contentType, fileContentStream, props); try { Reference ref = EntityManager.newReference(m_contentHostingService.getReference(attachment.getId())); if (singleFileUpload && attachments.size() > 1) { //SAK-26319 - the assignment type is 'single file upload' and the user has existing attachments, so they must be uploading a 'newSingleUploadedFile' --bbailla2 state.setAttribute("newSingleUploadedFile", ref); } else { attachments.add(ref); } } catch(Exception ee) { M_log.warn(this + "doAttachUpload cannot find reference for " + attachment.getId() + ee.getMessage()); } state.setAttribute(ATTACHMENTS, attachments); } catch (PermissionException e) { addAlert(state, rb.getString("notpermis4")); } catch(RuntimeException e) { if(m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) { // couldn't we just truncate the resource-id instead of rejecting the upload? addAlert(state, rb.getFormattedMessage("alert.toolong", new String[]{name})); } else { M_log.debug(this + ".doAttachupload ***** Runtime Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed")); } } catch (ServerOverloadException e) { // disk full or no writing permission to disk M_log.debug(this + ".doAttachupload ***** Disk IO Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.diskio")); } catch(Exception ignore) { // other exceptions should be caught earlier M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + ignore.getMessage()); addAlert(state, rb.getString("failed")); } finally { m_securityService.popAdvisor(sa); } } else { addAlert(state, rb.getString("choosefile7")); } } catch( IOException e){ M_log.debug(this + ".doAttachupload ***** IOException ***** " + e.getMessage()); addAlert(state, rb.getString("failed")); } } } // doAttachupload /** * Simply take as much as possible out of 'in', and write it to 'out'. Don't * close the streams, just transfer the data. * * @param in * The data provider * @param out * The data output * @throws IOException * Thrown if there is an IOException transfering the data */ private void writeToStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[INPUT_BUFFER_SIZE]; try { while (in.read(buffer) > 0) { out.write(buffer); } } catch (IOException e) { throw e; } } /** * Categories are represented as Integers. Right now this feature only will * be active for new assignments, so we'll just always return 0 for the * unassigned category. In the future we may (or not) want to update this * to return categories for existing gradebook items. * @param assignment * @return */ private int getAssignmentCategoryAsInt(Assignment assignment) { int categoryAsInt; categoryAsInt = 0; // zero for unassigned return categoryAsInt; } /* * (non-Javadoc) */ public void doOptions(RunData data, Context context) { doOptions(data); } // doOptions protected void doOptions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = ToolManager.getCurrentPlacement().getContext(); try { Site site = SiteService.getSite(siteId); ToolConfiguration tc=site.getToolForCommonId(ASSIGNMENT_TOOL_ID); String optionValue = tc.getPlacementConfig().getProperty(SUBMISSIONS_SEARCH_ONLY); state.setAttribute(SUBMISSIONS_SEARCH_ONLY, optionValue == null ? Boolean.FALSE:Boolean.valueOf(optionValue)); } catch (IdUnusedException e) { M_log.warn(this + ":doOptions Cannot find site with id " + siteId); } if (!alertGlobalNavigation(state, data)) { if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { state.setAttribute(STATE_MODE, MODE_OPTIONS); } else { addAlert(state, rb.getString("youarenot_options")); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } /** * build the options */ protected String build_options_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); context.put(SUBMISSIONS_SEARCH_ONLY, (Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_OPTIONS; } // build_options_context /** * save the option edits * @param data * @param context */ public void doUpdate_options(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = ToolManager.getCurrentPlacement().getContext(); ParameterParser params = data.getParameters(); // only show those submissions matching search criteria boolean submissionsSearchOnly = params.getBoolean(SUBMISSIONS_SEARCH_ONLY); state.setAttribute(SUBMISSIONS_SEARCH_ONLY, Boolean.valueOf(submissionsSearchOnly)); // save the option into tool configuration try { Site site = SiteService.getSite(siteId); ToolConfiguration tc=site.getToolForCommonId(ASSIGNMENT_TOOL_ID); String currentSetting = tc.getPlacementConfig().getProperty(SUBMISSIONS_SEARCH_ONLY); if (currentSetting == null || !currentSetting.equals(Boolean.toString(submissionsSearchOnly))) { // save the change tc.getPlacementConfig().setProperty(SUBMISSIONS_SEARCH_ONLY, Boolean.toString(submissionsSearchOnly)); SiteService.save(site); } } catch (IdUnusedException e) { M_log.warn(this + ":doUpdate_options Cannot find site with id " + siteId); addAlert(state, rb.getFormattedMessage("options_cannotFindSite", new Object[]{siteId})); } catch (PermissionException e) { M_log.warn(this + ":doUpdate_options Do not have permission to edit site with id " + siteId); addAlert(state, rb.getFormattedMessage("options_cannotEditSite", new Object[]{siteId})); } if (state.getAttribute(STATE_MESSAGE) == null) { // back to list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doUpdate_options /** * cancel the option edits * @param data * @param context */ public void doCancel_options(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_options /** * handle submission options */ public void doSubmission_search_option(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String searchOption = StringUtils.trimToNull(data.getParameters().getString("option")); // set the flag to go to the prev page on the next list if (searchOption != null && "submit".equals(searchOption)) { doSubmission_search(data, context); } else if (searchOption != null && "clear".equals(searchOption)) { doSubmission_search_clear(data, context); } } // doSubmission_search_option /** * Handle the submission search request. */ public void doSubmission_search(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String search = StringUtils.trimToNull(data.getParameters().getString( FORM_SEARCH)); // set the flag to go to the prev page on the next list if (search == null) { state.removeAttribute(STATE_SEARCH); } else { state.setAttribute(STATE_SEARCH, search); } } // doSubmission_search /** * Handle a Search Clear request. */ public void doSubmission_search_clear(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // clear the search state.removeAttribute(STATE_SEARCH); } // doSubmission_search_clear protected void letterGradeOptionsIntoContext(Context context) { String lOptions = ServerConfigurationService.getString("assignment.letterGradeOptions", "A+,A,A-,B+,B,B-,C+,C,C-,D+,D,D-,E,F"); context.put("letterGradeOptions", StringUtils.split(lOptions, ",")); } private LRS_Statement getStatementForViewSubmittedAssignment(LRS_Actor actor, Event event, String assignmentName) { String url = ServerConfigurationService.getPortalUrl(); LRS_Verb verb = new LRS_Verb(SAKAI_VERB.interacted); LRS_Object lrsObject = new LRS_Object(url + event.getResource(), "view-submitted-assignment"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("en-US", "User reviewed a submitted assignment"); lrsObject.setActivityName(nameMap); // Add description HashMap<String, String> descMap = new HashMap<String, String>(); descMap.put("en-US", "User reviewed a submitted assignment: " + assignmentName); lrsObject.setDescription(descMap); return new LRS_Statement(actor, verb, lrsObject); } private LRS_Statement getStatementForViewAssignment(LRS_Actor actor, Event event, String assignmentName) { String url = ServerConfigurationService.getPortalUrl(); LRS_Verb verb = new LRS_Verb(SAKAI_VERB.interacted); LRS_Object lrsObject = new LRS_Object(url + event.getResource(), "view-assignment"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("en-US", "User viewed an assignment"); lrsObject.setActivityName(nameMap); HashMap<String, String> descMap = new HashMap<String, String>(); descMap.put("en-US", "User viewed assignment: " + assignmentName); lrsObject.setDescription(descMap); return new LRS_Statement(actor, verb, lrsObject); } private LRS_Statement getStatementForSubmitAssignment(LRS_Actor actor, Event event, String accessUrl, String assignmentName) { LRS_Verb verb = new LRS_Verb(SAKAI_VERB.attempted); LRS_Object lrsObject = new LRS_Object(accessUrl + event.getResource(), "submit-assignment"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("en-US", "User submitted an assignment"); lrsObject.setActivityName(nameMap); // Add description HashMap<String, String> descMap = new HashMap<String, String>(); descMap.put("en-US", "User submitted an assignment: " + assignmentName); lrsObject.setDescription(descMap); return new LRS_Statement(actor, verb, lrsObject); } /** * Validates the ungraded/pass/fail grade values provided in the upload file are valid. * Values must be present in the appropriate language property file. * @param state * @param itemString * @return one of the valid values or the original value entered by the user */ private String validatePassFailGradeValue(SessionState state, String itemString) { // -------- SAK-24199 (SAKU-274) by Shoji Kajita if (itemString.equalsIgnoreCase(rb.getString("pass"))) { itemString = "Pass"; } else if (itemString.equalsIgnoreCase(rb.getString("fail"))) { itemString = "Fail"; } else if (itemString.equalsIgnoreCase(rb.getString("ungra")) || itemString.isEmpty()) { itemString = "Ungraded"; } else { // Not one of the expected values. Display error message. addAlert(state, rb.getFormattedMessage("plesuse0", new Object []{itemString})); } // -------- return itemString; } /** * Action to determine which view do present to user. * This method is currently called from calendar events in the alternate calendar tool. */ public void doCheck_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean allowReadAssignment = AssignmentService.allowGetAssignment(contextString); boolean allowSubmitAssignment = AssignmentService.allowAddSubmission(contextString); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); // Retrieve the status of the assignment String assignStatus = getAssignmentStatus(assignmentId, state); if (assignStatus != null && !assignStatus.equals(rb.getString("gen.open")) && !allowAddAssignment){ addAlert(state, rb.getFormattedMessage("gen.notavail", new Object[]{assignStatus})); } // Check the permission and call the appropriate view method. if (allowAddAssignment){ doView_assignment(data); } else if (allowSubmitAssignment){ doView_submission(data); } else if (allowReadAssignment){ doView_assignment_as_student(data); } else{ addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentId})); } } // doCheck_view /** * Retrieves the status of a given assignment. * @param assignmentId * @param state * @return */ private String getAssignmentStatus(String assignmentId, SessionState state) { String rv = null; try { Session session = SessionManager.getCurrentSession(); rv = AssignmentService.getAssignmentStatus(assignmentId); } catch (IdUnusedException e) { M_log.warn(this + " " + e.getMessage() + " " + assignmentId); } catch (PermissionException e) { M_log.warn(this + e.getMessage() + " " + assignmentId); } return rv; } /** * Set properties related to grading via an external scoring service. This service may be enabled for the * associated gradebook item. */ protected void setScoringAgentProperties(Context context, Assignment assignment, AssignmentSubmission submission, boolean gradeView) { String associatedGbItem = StringUtils.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (submission != null && associatedGbItem != null && assignment.getContent().getTypeOfGrade() == 3) { ScoringService scoringService = (ScoringService) ComponentManager.get("org.sakaiproject.scoringservice.api.ScoringService"); ScoringAgent scoringAgent = scoringService.getDefaultScoringAgent(); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); boolean scoringAgentEnabled = scoringAgent != null && scoringAgent.isEnabled(gradebookUid, null); String studentId = submission.getSubmitterId(); if (scoringAgentEnabled) { String gbItemName; if (assignment.getReference().equals(associatedGbItem)) { // this gb item is controlled by this tool gbItemName = assignment.getTitle(); } else { // this assignment was associated with an existing gb item gbItemName = associatedGbItem; } GradebookService gbService = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); org.sakaiproject.service.gradebook.shared.Assignment gbItem = null; try { gbItem = gbService.getAssignment(gradebookUid, gbItemName); } catch (SecurityException se) { // the gradebook method above is overzealous about security when retrieving the gb item by name. It doesn't // allow student-role users to access the assignment via this method. So we // have to retrieve all viewable gb items and filter to get the one we want, unfortunately, if we hit an exception. // If gb item isn't released in the gb, scoring agent info will not be available. List<org.sakaiproject.service.gradebook.shared.Assignment> viewableGbItems = gbService.getViewableAssignmentsForCurrentUser(gradebookUid); if (viewableGbItems != null && !viewableGbItems.isEmpty()) { for (org.sakaiproject.service.gradebook.shared.Assignment viewableGbItem : viewableGbItems) { if(gbItemName.equals(viewableGbItem.getName())) { gbItem = viewableGbItem; break; } } } } if (gbItem != null) { String gbItemId = Long.toString(gbItem.getId()); // Determine if a scoring component (like a rubric) has been associated with this gradebook item ScoringComponent component = scoringService.getScoringComponent( scoringAgent.getAgentId(), gradebookUid, gbItemId); boolean scoringComponentEnabled = component != null; context.put("scoringComponentEnabled", scoringComponentEnabled); if (scoringComponentEnabled) { context.put("scoringAgentImage", scoringAgent.getImageReference()); context.put("scoringAgentName", scoringAgent.getName()); // retrieve the appropriate url if (gradeView) { context.put("scoreUrl", scoringAgent.getScoreLaunchUrl(gradebookUid, gbItemId, studentId)); context.put("refreshScoreUrl", scoringService.getDefaultScoringAgent().getScoreUrl(gradebookUid, gbItemId, studentId) + "&t=gb"); context.put("scoreText",rb.getFormattedMessage("scoringAgent.grade", new Object[]{scoringAgent.getName()})); } else { // only retrieve the graded rubric if grade has been released. otherwise, keep it generic String scoreStudent = null; if (submission.getGradeReleased()) { scoreStudent = studentId; } context.put("scoreUrl", scoringAgent.getViewScoreLaunchUrl(gradebookUid, gbItemId, scoreStudent)); context.put("scoreText",rb.getFormattedMessage("scoringAgent.view", new Object[]{scoringAgent.getName()})); } } } } } } }
assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import au.com.bytecode.opencsv.CSVReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.Collator; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.RuleBasedCollator; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessage; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentConstants; import org.sakaiproject.assignment.api.AssignmentContent; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentPeerAssessmentService; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItem; import org.sakaiproject.assignment.api.model.AssignmentAllPurposeItemAccess; import org.sakaiproject.assignment.api.model.AssignmentModelAnswerItem; import org.sakaiproject.assignment.api.model.AssignmentNoteItem; import org.sakaiproject.assignment.api.model.AssignmentSupplementItemAttachment; import org.sakaiproject.assignment.api.model.AssignmentSupplementItemService; import org.sakaiproject.assignment.api.model.AssignmentSupplementItemWithAttachment; import org.sakaiproject.assignment.api.model.PeerAssessmentItem; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarEventEdit; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.contentreview.service.ContentReviewService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.Event; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.event.api.LearningResourceStoreService; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Actor; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Object; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Statement; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb; import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb.SAKAI_VERB; import org.sakaiproject.event.api.NotificationService; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.scoringservice.api.ScoringAgent; import org.sakaiproject.scoringservice.api.ScoringComponent; import org.sakaiproject.scoringservice.api.ScoringService; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.CategoryDefinition; import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException; import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException; import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.taggable.api.TaggingHelperInfo; import org.sakaiproject.taggable.api.TaggingManager; import org.sakaiproject.taggable.api.TaggingProvider; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); /** Our logger. */ private static Log M_log = LogFactory.getLog(AssignmentAction.class); private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades"; private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false); private static final Boolean allowPeerAssessment = ServerConfigurationService.getBoolean("assignment.usePeerAssessment", true); /** Is the review service available? */ //Peer Assessment private static final String NEW_ASSIGNMENT_USE_PEER_ASSESSMENT= "new_assignment_use_peer_assessment"; private static final String NEW_ASSIGNMENT_PEERPERIODMONTH = "new_assignment_peerperiodmonth"; private static final String NEW_ASSIGNMENT_PEERPERIODDAY = "new_assignment_peerperiodday"; private static final String NEW_ASSIGNMENT_PEERPERIODYEAR = "new_assignment_peerperiodyear"; private static final String NEW_ASSIGNMENT_PEERPERIODHOUR = "new_assignment_peerperiodhour"; private static final String NEW_ASSIGNMENT_PEERPERIODMIN = "new_assignment_peerperiodmin"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL= "new_assignment_peer_assessment_anon_eval"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS= "new_assignment_peer_assessment_student_view_review"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS= "new_assignment_peer_assessment_num_reviews"; private static final String NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS = "new_assignment_peer_assessment_instructions"; private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service"; private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO = "submit_papers_to"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE = "0"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD = "1"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION = "2"; // When to generate reports // although the service allows for a value of "1" --> Generate report immediately but overwrite until due date, // this doesn't make sense for assignment2. We limit the UI to 0 - Immediately // or 2 - On Due Date private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO = "report_gen_speed"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY = "0"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE = "2"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN = "s_paper_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET = "internet_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB = "journal_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION = "institution_check"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC = "exclude_biblio"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED = "exclude_quoted"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES = "exclude_smallmatches"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE = "exclude_type"; private static final String NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE = "exclude_value"; /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; private static final String ATTACHMENTS_FOR = "Assignment.attachments_for"; /** The property name associated with Groups that are Sections **/ private static final String GROUP_SECTION_PROPERTY = "sections_category"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** Additional calendar service */ private static final String ADDITIONAL_CALENDAR = "additonal_calendar"; /** The calendar tool */ private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit"; /** Additional calendar tool */ private static final String ADDITIONAL_CALENDAR_TOOL_READY = "additional_calendar_tool_ready"; /** The announcement tool */ private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; /** The submitter */ private static final String STATE_SUBMITTER = "Assignment.submitter"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** default sorting */ private static final String SORTED_BY_DEFAULT = "default"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** state sort submissuib by content review score **/ private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /*********************** Sort by user sort name *****************************************/ private static final String SORTED_USER_BY_SORTNAME = "sorted_user_by_sortname"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; private static final String GRADE_SUBMISSION_DONE = "grade_submission_done"; private static final String GRADE_SUBMISSION_SUBMIT = "grade_submission_submit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; /** * Is review service enabled? */ private static final String ENABLE_REVIEW_SERVICE = "enable_review_service"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // assignment order for default view private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order"; private static final String NEW_ASSIGNMENT_GROUP_SUBMIT = "new_assignment_group_submit"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; // visible date private static final String NEW_ASSIGNMENT_VISIBLEMONTH = "new_assignment_visiblemonth"; private static final String NEW_ASSIGNMENT_VISIBLEDAY = "new_assignment_visibleday"; private static final String NEW_ASSIGNMENT_VISIBLEYEAR = "new_assignment_visibleyear"; private static final String NEW_ASSIGNMENT_VISIBLEHOUR = "new_assignment_visiblehour"; private static final String NEW_ASSIGNMENT_VISIBLEMIN = "new_assignment_visiblemin"; private static final String NEW_ASSIGNMENT_VISIBLETOGGLE = "new_assignment_visibletoggle"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_CATEGORY = "new_assignment_category"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE = "new_assignment_check_hide_due_date"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; private static final String VIEW_SUBMISSION_GROUP = "view_submission_group"; private static final String VIEW_SUBMISSION_ORIGINAL_GROUP = "view_submission_original_group"; private static final String NEW_ASSIGNMENT_PAST_CLOSE_DATE = "new_assignment_past_close_date"; /*************************** assignment model answer attributes *************************/ private static final String NEW_ASSIGNMENT_MODEL_ANSWER = "new_assignment_model_answer"; private static final String NEW_ASSIGNMENT_MODEL_ANSWER_TEXT = "new_assignment_model_answer_text"; private static final String NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT = "new_assignment_model_answer_show_to_student"; private static final String NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT = "new_assignment_model_answer_attachment"; /**************************** assignment year range *************************/ private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from"; private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE_PRIVATE = "Assignment.mode_student_view_grade_private"; /** The student view of a group submission error (user is in multiple groups */ private static final String MODE_STUDENT_VIEW_GROUP_ERROR = "Assignment.mode_student_view_group_error"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to reorder assignments */ private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The instructor view of download all file */ private static final String MODE_INSTRUCTOR_DOWNLOAD_ALL = "downloadAll"; /** The instructor view of uploading all from archive file */ private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll"; /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** The option view */ private static final String MODE_OPTIONS= "options"; // set in velocity template /** Review Edit page for students */ private static final String MODE_STUDENT_REVIEW_EDIT= "Assignment.mode_student_review_edit"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of showing a group assignment grouping error */ private static final String TEMPLATE_STUDENT_VIEW_GROUP_ERROR = "_student_view_group_error"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to reorder the default assignments */ private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The instructor view to upload all information from archive file */ private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll"; /** The student view to edit reviews **/ private static final String TEMPLATE_STUDENT_REVIEW_EDIT = "_student_review_edit"; /** The options page */ private static final String TEMPLATE_OPTIONS = "_options"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The configuration choice of showing or hiding the number of submissions column */ private static final String SHOW_NUMBER_SUBMISSION_COLUMN = "showNumSubmissionColumn"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** the items for storing the comments and grades for peer assessment **/ private static final String PEER_ASSESSMENT_ITEMS = "peer_assessment_items"; private static final String PEER_ASSESSMENT_ASSESSOR_ID = "peer_assessment_assesor_id"; private static final String PEER_ASSESSMENT_REMOVED_STATUS = "peer_assessment_removed_status"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; // name for release grade notification private static final String ASSIGNMENT_RELEASEGRADE_NOTIFICATION = "assignment.releasegrade.notification"; private static final String ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION = "assignment.releasereturn.notification"; /****************************** Upload all screen ***************************/ private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text"; private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment"; private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile"; private static final String UPLOAD_ALL_GRADEFILE_FORMAT = "upload_all_gradefile_format"; private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments"; private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text"; private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment"; private static final String UPLOAD_ALL_WITHOUT_FOLDERS = "upload_all_without_folders"; private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades"; // this is to track whether the site has multiple assignment, hence if true, show the reorder link private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments"; // view all or grouped submission list private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option"; /************************* SAK-17606 - Upload all grades.csv columns ********************/ private static final int IDX_GRADES_CSV_EID = 1; private static final int IDX_GRADES_CSV_GRADE = 5; // search string for submission list private static final String VIEW_SUBMISSION_SEARCH = "view_submission_search"; private ContentHostingService m_contentHostingService = null; private EventTrackingService m_eventTrackingService = null; private NotificationService m_notificationService = null; private SecurityService m_securityService = null; /********************** Supplement item ************************/ private AssignmentSupplementItemService m_assignmentSupplementItemService = null; /******** Model Answer ************/ private static final String MODELANSWER = "modelAnswer"; private static final String MODELANSWER_TEXT = "modelAnswer.text"; private static final String MODELANSWER_SHOWTO = "modelAnswer.showTo"; private static final String MODELANSWER_ATTACHMENTS = "modelanswer_attachments"; private static final String MODELANSWER_TO_DELETE = "modelanswer.toDelete"; /******** Note ***********/ private static final String NOTE = "note"; private static final String NOTE_TEXT = "note.text"; private static final String NOTE_SHAREWITH = "note.shareWith"; private static final String NOTE_TO_DELETE = "note.toDelete"; /******** AllPurpose *******/ private static final String ALLPURPOSE = "allPurpose"; private static final String ALLPURPOSE_TITLE = "allPurpose.title"; private static final String ALLPURPOSE_TEXT = "allPurpose.text"; private static final String ALLPURPOSE_HIDE = "allPurpose.hide"; private static final String ALLPURPOSE_SHOW_FROM = "allPurpose.show.from"; private static final String ALLPURPOSE_SHOW_TO = "allPurpose.show.to"; private static final String ALLPURPOSE_RELEASE_DATE = "allPurpose.releaseDate"; private static final String ALLPURPOSE_RETRACT_DATE= "allPurpose.retractDate"; private static final String ALLPURPOSE_ACCESS = "allPurpose.access"; private static final String ALLPURPOSE_ATTACHMENTS = "allPurpose_attachments"; private static final String ALLPURPOSE_RELEASE_YEAR = "allPurpose_releaseYear"; private static final String ALLPURPOSE_RELEASE_MONTH = "allPurpose_releaseMonth"; private static final String ALLPURPOSE_RELEASE_DAY = "allPurpose_releaseDay"; private static final String ALLPURPOSE_RELEASE_HOUR = "allPurpose_releaseHour"; private static final String ALLPURPOSE_RELEASE_MIN = "allPurpose_releaseMin"; private static final String ALLPURPOSE_RETRACT_YEAR = "allPurpose_retractYear"; private static final String ALLPURPOSE_RETRACT_MONTH = "allPurpose_retractMonth"; private static final String ALLPURPOSE_RETRACT_DAY = "allPurpose_retractDay"; private static final String ALLPURPOSE_RETRACT_HOUR = "allPurpose_retractHour"; private static final String ALLPURPOSE_RETRACT_MIN = "allPurpose_retractMin"; private static final String ALLPURPOSE_TO_DELETE = "allPurpose.toDelete"; private static final String SHOW_ALLOW_RESUBMISSION = "show_allow_resubmission"; private static final String SHOW_SEND_FEEDBACK = "show_send_feedback"; private static final String RETURNED_FEEDBACK = "feedback_returned_to_selected_users"; private static final String OW_FEEDBACK = "feedback_overwritten"; private static final String SAVED_FEEDBACK = "feedback_saved"; private static final int INPUT_BUFFER_SIZE = 102400; private static final String INVOKE = "invoke_via"; private static final String INVOKE_BY_LINK = "link"; private static final String INVOKE_BY_PORTAL = "portal"; private static final String SUBMISSIONS_SEARCH_ONLY = "submissions_search_only"; /*************** search related *******************/ private static final String STATE_SEARCH = "state_search"; private static final String FORM_SEARCH = "form_search"; private static final String STATE_DOWNLOAD_URL = "state_download_url"; /** To know if grade_submission go from view_students_assignment view or not **/ private static final String FROM_VIEW = "from_view"; /** SAK-17606 - Property for whether an assignment user anonymous grading (user settable). */ private static final String NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING = "new_assignment_check_anonymous_grading"; private AssignmentPeerAssessmentService assignmentPeerAssessmentService; public void setAssignmentPeerAssessmentService(AssignmentPeerAssessmentService assignmentPeerAssessmentService){ this.assignmentPeerAssessmentService = assignmentPeerAssessmentService; } public String buildLinkedPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state){ state.setAttribute(INVOKE, INVOKE_BY_LINK); return buildMainPanelContext(portlet, context, data, state); } /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = null; context.put("action", "AssignmentAction"); context.put("tlang", rb); context.put("dateFormat", getDateFormatString()); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? boolean allowUpdateSite = SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("allowUpdateSite", Boolean.valueOf(allowUpdateSite)); //group related settings context.put("siteAccess", Assignment.AssignmentAccess.SITE); context.put("groupAccess", Assignment.AssignmentAccess.GROUPED); // allow all.groups? boolean allowAllGroups = AssignmentService.allowAllGroups(contextString); context.put("allowAllGroups", Boolean.valueOf(allowAllGroups)); //Is the review service allowed? Site s = null; try { s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (IdUnusedException iue) { M_log.warn(this + ":buildMainPanelContext: Site not found!" + iue.getMessage()); } // Check whether content review service is enabled, present and enabled for this site getContentReviewService(); context.put("allowReviewService", allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s)); if (allowReviewService && contentReviewService != null && contentReviewService.isSiteAcceptable(s)) { //put the review service stings in context String reviewServiceName = contentReviewService.getServiceName(); String reviewServiceTitle = rb.getFormattedMessage("review.title", new Object[]{reviewServiceName}); String reviewServiceUse = rb.getFormattedMessage("review.use", new Object[]{reviewServiceName}); String reviewServiceNonElectronic1 = rb.getFormattedMessage("review.switch.ne.1", reviewServiceName); String reviewServiceNonElectronic2 = rb.getFormattedMessage("review.switch.ne.2", reviewServiceName); context.put("reviewServiceName", reviewServiceName); context.put("reviewServiceTitle", reviewServiceTitle); context.put("reviewServiceUse", reviewServiceUse); context.put("reviewIndicator", rb.getFormattedMessage("review.contentReviewIndicator", new Object[]{reviewServiceName})); context.put("reviewSwitchNe1", reviewServiceNonElectronic1); context.put("reviewSwitchNe2", reviewServiceNonElectronic2); } //Peer Assessment context.put("allowPeerAssessment", allowPeerAssessment); if(allowPeerAssessment){ context.put("peerAssessmentName", rb.getFormattedMessage("peerAssessmentName")); context.put("peerAssessmentUse", rb.getFormattedMessage("peerAssessmentUse")); } // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); // the grade type table context.put("gradeTypeTable", gradeTypeTable()); // set the allowSubmitByInstructor option context.put("allowSubmitByInstructor", AssignmentService.getAllowSubmitByInstructor()); // get the system setting for whether to show the Option tool link or not context.put("enableViewOption", ServerConfigurationService.getBoolean("assignment.enableViewOption", true)); String mode = (String) state.getAttribute(STATE_MODE); if (!MODE_LIST_ASSIGNMENTS.equals(mode)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (MODE_LIST_ASSIGNMENTS.equals(mode)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_ASSIGNMENT.equals(mode)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_GROUP_ERROR.equals(mode)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing group submission error template = build_student_view_group_error_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION.equals(mode)) { context.put("site",s); // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode)) { context.put("site",s); // disable auto-updates while leaving the list view justDelivered(state); if(MODE_STUDENT_VIEW_GRADE_PRIVATE.equals(mode)){ context.put("privateView", true); } // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)) { context.put("site",s); if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode)) { context.put("site",s); // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode)) { context.put("site",s); if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_DOWNLOAD_ALL.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_download_upload_all(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_UPLOAD_ALL.equals(mode)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_download_upload_all(portlet, context, data, state); } } else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode)) { context.put("site",s); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_reorder_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_OPTIONS)) { if (allowUpdateSite) { // build the options page template = build_options_context(portlet, context, data, state); } } else if (mode.equals(MODE_STUDENT_REVIEW_EDIT)) { template = build_student_review_edit_context(portlet, context, data, state); } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } // this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null) { context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS)); } return template; } // buildNormalContext /** * local function for getting assignment object * @param assignmentId * @param callingFunctionName * @param state * @return */ private Assignment getAssignment(String assignmentId, String callingFunctionName, SessionState state) { Assignment rv = null; try { Session session = SessionManager.getCurrentSession(); SecurityAdvisor secAdv = pushSecurityAdvisor(session, "assignment.security.advisor", false); SecurityAdvisor contentAdvisor = pushSecurityAdvisor(session, "assignment.content.security.advisor", false); rv = AssignmentService.getAssignment(assignmentId); m_securityService.popAdvisor(contentAdvisor); m_securityService.popAdvisor(secAdv); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentId})); } return rv; } /** * local function for getting assignment submission object * @param submissionId * @param callingFunctionName * @param state * @return */ private AssignmentSubmission getSubmission(String submissionId, String callingFunctionName, SessionState state) { AssignmentSubmission rv = null; try { Session session = SessionManager.getCurrentSession(); SecurityAdvisor secAdv = pushSecurityAdvisor(session, "assignment.grade.security.advisor", false); rv = AssignmentService.getSubmission(submissionId); m_securityService.popAdvisor(secAdv); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission", new Object[]{submissionId})); } return rv; } /** * local function for editing assignment submission object * @param submissionId * @param callingFunctionName * @param state * @return */ private AssignmentSubmissionEdit editSubmission(String submissionId, String callingFunctionName, SessionState state) { AssignmentSubmissionEdit rv = null; try { rv = AssignmentService.editSubmission(submissionId); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("cannotfin_submission", new Object[]{submissionId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("youarenot_editSubmission", new Object[]{submissionId})); } catch (InUseException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + submissionId); addAlert(state, rb.getFormattedMessage("somelsis_submission", new Object[]{submissionId})); } return rv; } /** * local function for editing assignment object * @param assignmentId * @param callingFunctionName * @param state * @param allowToAdd * @return */ private AssignmentEdit editAssignment(String assignmentId, String callingFunctionName, SessionState state, boolean allowAdd) { AssignmentEdit rv = null; if (assignmentId.length() == 0 && allowAdd) { // create a new assignment try { rv = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot_addAssignment")); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } } else { try { rv = AssignmentService.editAssignment(assignmentId); } catch (IdUnusedException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentId})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{assignmentId})); } catch (InUseException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentId); addAlert(state, rb.getFormattedMessage("somelsis_assignment", new Object[]{assignmentId})); } } // if-else return rv; } /** * local function for getting assignment submission object * @param submissionId * @param callingFunctionName * @param state * @return */ private AssignmentSubmission getSubmission(String assignmentRef, User user, String callingFunctionName, SessionState state) { AssignmentSubmission rv = null; try { rv = AssignmentService.getSubmission(assignmentRef, user); } catch (IdUnusedException e) { M_log.warn(this + ":build_student_view_submission " + e.getMessage() + " " + assignmentRef + " " + user.getId()); if (state != null) addAlert(state, rb.getFormattedMessage("cannotfin_submission_1", new Object[]{assignmentRef, user.getId()})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentRef + " " + user.getId()); if (state != null) addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission_1", new Object[]{assignmentRef, user.getId()})); } return rv; } /** * local function for getting assignment submission object for a group id (or is that submitter id instead of group id) */ private AssignmentSubmission getSubmission(String assignmentRef, String group_id, String callingFunctionName, SessionState state) { AssignmentSubmission rv = null; try { rv = AssignmentService.getSubmission(assignmentRef, group_id); } catch (IdUnusedException e) { M_log.warn(this + ":build_student_view_submission " + e.getMessage() + " " + assignmentRef + " " + group_id); if (state != null) addAlert(state, rb.getFormattedMessage("cannotfin_submission_1", new Object[]{assignmentRef, group_id})); } catch (PermissionException e) { M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + " " + assignmentRef + " " + group_id); if (state != null) addAlert(state, rb.getFormattedMessage("youarenot_viewSubmission_1", new Object[]{assignmentRef, group_id})); } return rv; } /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String invokedByStatus = (String) state.getAttribute(INVOKE); if(invokedByStatus!=null){ if(invokedByStatus.equalsIgnoreCase(INVOKE_BY_LINK)){ context.put("linkInvoked", Boolean.valueOf(true)); }else{ context.put("linkInvoked", Boolean.valueOf(false)); } }else{ context.put("linkInvoked", Boolean.valueOf(false)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); M_log.debug(this + " BUILD SUBMISSION FORM WITH USER " + user.getId() + " NAME " + user.getDisplayName()); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = getAssignment(currentAssignmentReference, "build_student_view_submission_context", state); AssignmentSubmission s = null; boolean newAttachments = false; if (assignment != null) { context.put("assignment", assignment); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment))); // SAK-26322 --bbailla2 if (assignment.getContent().getAllowReviewService()) { context.put("plagiarismNote", rb.getFormattedMessage("gen.yoursubwill", contentReviewService.getServiceName())); } if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } User submitter = (User)state.getAttribute("student"); if (submitter == null) { submitter = user; } s = getSubmission(assignment.getReference(), submitter, "build_student_view_submission_context", state); List currentAttachments = (List) state.getAttribute(ATTACHMENTS); if (s != null) { M_log.debug(this + " BUILD SUBMISSION FORM HAS SUBMISSION FOR USER " + s.getSubmitterId() + " NAME " + user.getDisplayName()); context.put("submission", s); if (assignment.isGroup()) { context.put("selectedGroup", s.getSubmitterId()); context.put("originalGroup", s.getSubmitterId()); } setScoringAgentProperties(context, assignment, s, false); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if (assignment.isGroup()) { context.put("submitterId", s.getSubmitterId() ); String _grade_override= s.getGradeForUser(UserDirectoryService.getCurrentUser().getId()); if (_grade_override != null) { if (assignment.getContext() != null && assignment.getContent().getTypeOfGrade() == 3) { context.put("override", displayGrade(state, _grade_override)); } else { context.put("override", _grade_override); } } } // figure out if attachments have been modified // the attachments from the previous submission List submittedAttachments = s.getSubmittedAttachments(); newAttachments = areAttachmentsNew(submittedAttachments, currentAttachments); } else { // There is no previous submission, attachments are modified if anything has been uploaded newAttachments = currentAttachments != null && !currentAttachments.isEmpty(); } // put the resubmit information into context assignment_resubmission_option_into_context(context, state); if (assignment.isGroup()) { context.put("assignmentService", AssignmentService.getInstance()); // get current site Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", st); groups = getGroupsWithUser(user.getId(), assignment, st); checkForGroupsInMultipleGroups(assignment, groups, state, rb.getString("group.user.multiple.warning")); context.put("group_size", String.valueOf(groups.size())); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); if (state.getAttribute(VIEW_SUBMISSION_GROUP) != null) { context.put("selectedGroup", (String)state.getAttribute(VIEW_SUBMISSION_GROUP)); if (M_log.isDebugEnabled()) M_log.debug(this + ":buildStudentViewSubmissionContext: VIEW_SUBMISSION_GROUP " + (String)state.getAttribute(VIEW_SUBMISSION_GROUP)); } if (state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP) != null) { context.put("originalGroup", (String)state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP)); if (M_log.isDebugEnabled()) M_log.debug(this + ":buildStudentViewSubmissionContext: VIEW_SUBMISSION_ORIGINAL_GROUP " + (String)state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP)); } } catch (IdUnusedException iue) { M_log.warn(this + ":buildStudentViewSubmissionContext: Site not found!" + iue.getMessage()); } } // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, s); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); context.put("attachments", stripInvisibleAttachments(state.getAttribute(ATTACHMENTS))); context.put("new_attachments", newAttachments); context.put("userDirectoryService", UserDirectoryService.getInstance()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); // SAK-21525 - Groups were not being queried for authz boolean allowSubmit = AssignmentService.allowAddSubmissionCheckGroups((String) state.getAttribute(STATE_CONTEXT_STRING),assignment); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", Boolean.valueOf(allowSubmit)); // put supplement item into context supplementItemIntoContext(state, context, assignment, s); initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); // if the instructor is allowed to submit assignment on behalf of student, add the student list to the page User student = (User) state.getAttribute("student") ; if (AssignmentService.getAllowSubmitByInstructor() && student != null) { List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, currentAssignmentReference, contextString); if (submitterIds != null && !submitterIds.isEmpty() && submitterIds.contains(student.getId())) { // we want to come back to the instructor view page state.setAttribute(FROM_VIEW, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); context.put("student",student); } } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * Determines if there are new attachments * @return true if currentAttachments is not empty and isn't equal to oldAttachments */ private boolean areAttachmentsNew(List oldAttachments, List currentAttachments) { if (currentAttachments == null || currentAttachments.isEmpty()) { //there are no current attachments return false; } if (oldAttachments == null || oldAttachments.isEmpty()) { //there are no old attachments (and there are new ones) return true; } Set<String> ids1 = getIdsFromReferences(oldAttachments); Set<String> ids2 = getIdsFromReferences(currentAttachments); //.equals on Sets of Strings will compare .equals on the contained Strings return !ids1.equals(ids2); } /** * Gets ids from a list of Reference objects. If the List contains any non-reference objects, they are skipped */ private Set<String> getIdsFromReferences(List references) { Set<String> ids = new HashSet<String>(); for (Object reference : references) { if (reference instanceof Reference) { Reference casted = (Reference) reference; ids.add(casted.getId()); } } return ids; } /** * Returns a clone of the passed in List of attachments minus any attachments that should not be displayed in the UI */ private List stripInvisibleAttachments(Object attachments) { List stripped = new ArrayList(); if (attachments == null || !(attachments instanceof List)) { return stripped; } Iterator itAttachments = ((List) attachments).iterator(); while (itAttachments.hasNext()) { Object next = itAttachments.next(); if (next instanceof Reference) { Reference attachment = (Reference) next; // inline submissions should not show up in the UI's lists of attachments if (!"true".equals(attachment.getProperties().getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { stripped.add(attachment); } } } return stripped; } /** * build the student view of showing a group assignment error with eligible groups * a user can only be in one eligible group * * @param portlet * @param context * @param data * @param state * @return the student error message for this context */ protected String build_student_view_group_error_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); if (M_log.isDebugEnabled()) M_log.debug(this + " BUILD SUBMISSION GROUP ERROR WITH USER " + user.getId() + " NAME " + user.getDisplayName()); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = getAssignment(currentAssignmentReference, "build_student_view_submission_context", state); if (assignment != null) { context.put("assignment", assignment); if (assignment.isGroup()) { context.put("assignmentService", AssignmentService.getInstance()); Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", st); groups = getGroupsWithUser(user.getId(), assignment, st); //checkForGroupsInMultipleGroups(assignment, groups, state, rb.getString("group.user.multiple.warning")); context.put("group_size", String.valueOf(groups.size())); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); } catch (IdUnusedException iue) { M_log.warn(this + ":buildStudentViewSubmissionContext: Site not found!" + iue.getMessage()); } } } TaggingManager taggingManager = (TaggingManager) ComponentManager.get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("userDirectoryService", UserDirectoryService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GROUP_ERROR; } // build_student_view_group_error_context /** * Get groups containing a user for this assignment (remove SECTION groups) * @param member * @param assignment * @param site * @return collection of groups with the given member */ private Collection<Group> getGroupsWithUser(String member, Assignment assignment, Site site) { Collection<Group> groups = new ArrayList<Group>(); if (assignment.getAccess().equals(Assignment.AssignmentAccess.SITE)) { Iterator<Group> _groups = site.getGroupsWithMember(member).iterator(); while (_groups.hasNext()) { Group _g = _groups.next(); if (_g.getMember(member) != null)// && _g.getProperties().get(GROUP_SECTION_PROPERTY) == null) groups.add(_g); } } else { Iterator<String> _it = assignment.getGroups().iterator(); while (_it.hasNext()) { String _gRef = _it.next(); Group _g = site.getGroup(_gRef); if (_g != null && _g.getMember(member) != null)// && _g.getProperties().get(GROUP_SECTION_PROPERTY) == null) groups.add(_g); } } return groups; } /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); String invokedByStatus = (String) state.getAttribute(INVOKE); if(invokedByStatus!=null){ if(invokedByStatus.equalsIgnoreCase(INVOKE_BY_LINK)){ context.put("linkInvoked", Boolean.valueOf(true)); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); }else{ context.put("linkInvoked", Boolean.valueOf(false)); } }else{ context.put("linkInvoked", Boolean.valueOf(false)); } context.put("view", MODE_LIST_ASSIGNMENTS); // get user information User user = (User) state.getAttribute(STATE_USER); String submitterId = (String) state.getAttribute(STATE_SUBMITTER); User submitter = user; if (submitterId != null) { try { submitter = UserDirectoryService.getUser(submitterId); } catch (UserNotDefinedException ex) { M_log.warn(this + ":build_student_view_submission cannot find user with id " + submitterId + " " + ex.getMessage()); } } context.put("user_name", submitter.getDisplayName()); context.put("user_id", submitter.getDisplayId()); if (StringUtils.trimToNull(user.getEmail()) != null) context.put("user_email", user.getEmail()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { M_log.warn(this + ":buildStudentViewSubmission " + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment currentAssignment = getAssignment(currentAssignmentReference, "build_student_view_submission_confirmation_context", state); if (currentAssignment != null) { context.put("assignment", currentAssignment); context.put("assignment_title", currentAssignment.getTitle()); // differenciate submission type int submissionType = currentAssignment.getContent().getTypeOfSubmission(); if (submissionType == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION || submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION) { context.put("attachmentSubmissionOnly", Boolean.TRUE); } else { context.put("attachmentSubmissionOnly", Boolean.FALSE); } if (submissionType == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION) { context.put("textSubmissionOnly", Boolean.TRUE); } else { context.put("textSubmissionOnly", Boolean.FALSE); } context.put("submissionType", submissionType); AssignmentSubmission s = getSubmission(currentAssignmentReference, submitter, "build_student_view_submission_confirmation_context",state); if (s != null) { context.put("submission", s); context.put("submitted", Boolean.valueOf(s.getSubmitted())); context.put("submission_id", s.getId()); if (s.getTimeSubmitted() != null) { context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); } List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getVisibleSubmittedAttachments()); } context.put("submit_text", StringUtils.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } state.removeAttribute(STATE_SUBMITTER); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment * * @param portlet * @param context * @param data * @param state * @return */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); String aReference = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); User user = (User) state.getAttribute(STATE_USER); AssignmentSubmission submission = null; Assignment assignment = getAssignment(aReference, "build_student_view_assignment_context", state); if (assignment != null) { context.put("assignment", assignment); // put creator information into context putCreatorIntoContext(context, assignment); submission = getSubmission(aReference, user, "build_student_view_assignment_context", state); context.put("submission", submission); if (assignment.isGroup()) { Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", st); groups = getGroupsWithUser(user.getId(), assignment, st); context.put("group_size", String.valueOf(groups.size())); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); checkForGroupsInMultipleGroups(assignment, groups, state, rb.getString("group.user.multiple.warning")); } catch (IdUnusedException iue) { M_log.warn(this + ":buildStudentViewAssignmentContext: Site not found!" + iue.getMessage()); } } // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, submission); // put resubmit information into context assignment_resubmission_option_into_context(context, state); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); // put supplement item into context supplementItemIntoContext(state, context, assignment, submission); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission * * @param portlet * @param context * @param data * @param state * @return */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = getAssignment(aReference, "build_student_preview_submission_context", state); if (assignment != null) { context.put("assignment", assignment); AssignmentSubmission submission = getSubmission(aReference, user, "build_student_preview_submission_context", state); context.put("submission", submission); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit((String) state.getAttribute(STATE_CONTEXT_STRING), assignment))); setScoringAgentProperties(context, assignment, submission, false); // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, submission); // put the resubmit information into context assignment_resubmission_option_into_context(context, state); if(state.getAttribute(SHOW_SEND_FEEDBACK) != null) { context.put("showSendFeedback", Boolean.TRUE); state.removeAttribute(SHOW_SEND_FEEDBACK); } if (state.getAttribute(SAVED_FEEDBACK) != null) { context.put("savedFeedback", Boolean.TRUE); state.removeAttribute(SAVED_FEEDBACK); } if (state.getAttribute(OW_FEEDBACK) != null) { context.put("overwriteFeedback", Boolean.TRUE); state.removeAttribute(OW_FEEDBACK); } if (state.getAttribute(RETURNED_FEEDBACK) != null) { context.put("returnedFeedback", Boolean.TRUE); state.removeAttribute(RETURNED_FEEDBACK); } } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); context.put("attachments", stripInvisibleAttachments(state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS))); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context private void canViewAssignmentIntoContext(Context context, Assignment assignment, AssignmentSubmission submission) { boolean canViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, submission); context.put("allowViewModelAnswer", Boolean.valueOf(canViewModelAnswer)); if (canViewModelAnswer) { context.put("modelAnswer", m_assignmentSupplementItemService.getModelAnswer(assignment.getId())); } } /** * Look up a security advisor from the session with the given key, and then push it on the security service stack. * @param session * @param sessionKey String key used to look up a SecurityAdvisor stored in the session object * @param removeFromSession boolean flag indicating if the value should be removed from the session once retrieved * @return */ private SecurityAdvisor pushSecurityAdvisor(Session session, String sessionKey, boolean removeFromSession) { SecurityAdvisor asgnAdvisor = (SecurityAdvisor)session.getAttribute(sessionKey); if (asgnAdvisor != null) { m_securityService.pushAdvisor(asgnAdvisor); if (removeFromSession) session.removeAttribute(sessionKey); } return asgnAdvisor; } /** * If necessary, put a "decoratedUrlMap" into the context * @param session * @param context Context object that will have a "decoratedUrlMap" object put into it * @param removeFromSession boolean flag indicating if the value should be removed from the session once retrieved */ private void addDecoUrlMapToContext(Session session, Context context, boolean removeFromSession) { SecurityAdvisor contentAdvisor = (SecurityAdvisor)session.getAttribute("assignment.content.security.advisor"); String decoratedContentWrapper = (String)session.getAttribute("assignment.content.decoration.wrapper"); String[] contentRefs = (String[])session.getAttribute("assignment.content.decoration.wrapper.refs"); if (removeFromSession) { session.removeAttribute("assignment.content.decoration.wrapper"); session.removeAttribute("assignment.content.decoration.wrapper.refs"); } if (contentAdvisor != null && contentRefs != null) { m_securityService.pushAdvisor(contentAdvisor); Map<String, String> urlMap = new HashMap<String, String>(); for (String refStr:contentRefs) { Reference ref = EntityManager.newReference(refStr); String url = ref.getUrl(); urlMap.put(url, url.replaceFirst("access/content", "access/" + decoratedContentWrapper + "/content")); } context.put("decoratedUrlMap", urlMap); m_securityService.popAdvisor(contentAdvisor); } } /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); Session session = SessionManager.getCurrentSession(); addDecoUrlMapToContext(session, context, false); SecurityAdvisor asgnAdvisor = pushSecurityAdvisor(session, "assignment.security.advisor", false); AssignmentSubmission submission = null; Assignment assignment = null; String submissionId = (String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID); submission = getSubmission(submissionId, "build_student_view_grade_context", state); if (submission != null) { assignment = submission.getAssignment(); context.put("assignment", assignment); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } context.put("submission", submission); if (assignment.isGroup()) { String _grade_override= submission.getGradeForUser(UserDirectoryService.getCurrentUser().getId()); if (_grade_override != null) { if (assignment.getContext() != null && assignment.getContent().getTypeOfGrade() == 3) context.put("override", displayGrade(state, _grade_override)); else context.put("override", _grade_override); } } // can the student view model answer or not canViewAssignmentIntoContext(context, assignment, submission); // scoring agent integration setScoringAgentProperties(context, assignment, submission, false); //peer review if(assignment.getAllowPeerAssessment() && assignment.getPeerAssessmentStudentViewReviews() && assignment.isPeerAssessmentClosed()){ List<PeerAssessmentItem> reviews = assignmentPeerAssessmentService.getPeerAssessmentItems(submission.getId()); if(reviews != null){ List<PeerAssessmentItem> completedReviews = new ArrayList<PeerAssessmentItem>(); for(PeerAssessmentItem review : reviews){ if(!review.isRemoved() && (review.getScore() != null || (review.getComment() != null && !"".equals(review.getComment().trim())))){ //only show peer reviews that have either a score or a comment saved if(assignment.getPeerAssessmentAnonEval()){ //annonymous eval review.setAssessorDisplayName(rb.getFormattedMessage("gen.reviewer.countReview", completedReviews.size() + 1)); }else{ //need to set the assessor's display name try { review.setAssessorDisplayName(UserDirectoryService.getUser(review.getAssessorUserId()).getDisplayName()); } catch (UserNotDefinedException e) { //reviewer doesn't exist or userId is wrong M_log.error(e.getMessage(), e); //set a default one: review.setAssessorDisplayName(rb.getFormattedMessage("gen.reviewer.countReview", completedReviews.size() + 1)); } } completedReviews.add(review); } } if(completedReviews.size() > 0){ context.put("peerReviews", completedReviews); } } } } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && submission != null) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getItemHelperInfo( assignmentActivityProducer.getItem( submission, UserDirectoryService.getCurrentUser() .getId()).getReference()); if (helper != null) { itemHelpers.add(helper); } } addItem(context, submission, UserDirectoryService.getCurrentUser().getId()); addActivity(context, submission.getAssignment()); context.put("itemHelpers", itemHelpers); context.put("taggable", Boolean.valueOf(true)); } // put supplement item into context supplementItemIntoContext(state, context, assignment, submission); if (asgnAdvisor != null) { m_securityService.popAdvisor(asgnAdvisor); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); context.put("providers", taggingManager.getProviders()); context.put("taggable", Boolean.valueOf(true)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("AuthzGroupService", AuthzGroupService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", Long.valueOf(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (SORTED_BY_GROUP_TITLE.equals(sortedBy) || SORTED_BY_GROUP_DESCRIPTION.equals(sortedBy)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null && // this is not very elegant, but the view cannot be 'lisofass2' here. !state.getAttribute(STATE_SELECTED_VIEW).equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } List assignments = prepPage(state); context.put("assignments", assignments.iterator()); // allow add assignment? Map<String, List<PeerAssessmentItem>> peerAssessmentItemsMap = new HashMap<String, List<PeerAssessmentItem>>(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if(!allowAddAssignment){ //this is the same requirement for displaying the assignment link for students //now lets create a map for peer reviews for each eligible assignment for(Assignment assignment : (List<Assignment>) assignments){ if(assignment.getAllowPeerAssessment() && (assignment.isPeerAssessmentOpen() || assignment.isPeerAssessmentClosed())){ peerAssessmentItemsMap.put(assignment.getId(), assignmentPeerAssessmentService.getPeerAssessmentItems(assignment.getId(), UserDirectoryService.getCurrentUser().getId())); } } } context.put("peerAssessmentItemsMap", peerAssessmentItemsMap); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.valueOf(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = getAllGroupsInSite(contextString); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { M_log.warn(this + ":build_list_assignments_context " + ignore.getMessage()); M_log.warn(this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", Boolean.valueOf(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // the type int for non-electronic submission context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)); // show or hide the number of submission column context.put(SHOW_NUMBER_SUBMISSION_COLUMN, state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context private HashSet<String> getSubmittersIdSet(List submissions) { HashSet<String> rv = new HashSet<String>(); for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();) { rv.add(((AssignmentSubmission) iSubmissions.next()).getSubmitterId()); } return rv; } private HashSet<String> getAllowAddSubmissionUsersIdSet(List users) { HashSet<String> rv = new HashSet<String>(); for (Iterator iUsers=users.iterator(); iUsers.hasNext();) { rv.add(((User) iUsers.next()).getId()); } return rv; } /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // If the user adds the schedule or alternate calendar tool after using the assignment tool, // we need to remove these state attributes so they are re-initialized with the updated // availability of the tools. state.removeAttribute(CALENDAR_TOOL_EXIST); state.removeAttribute(ADDITIONAL_CALENDAR_TOOL_READY); initState(state, portlet, (JetspeedRunData)data); // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { Assignment a = getAssignment(assignmentId, "build_instructor_new_edit_assignment_context", state); if (a != null) { context.put("assignment", a); if (a.isGroup()) { Collection<String> _dupUsers = usersInMultipleGroups(a); if (_dupUsers.size() > 0) context.put("multipleGroupUsers", _dupUsers); } } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); context.put("group_submissions_enabled", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.group.submission.enabled", true))); context.put("visible_date_enabled", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_UsePeerAssessment", NEW_ASSIGNMENT_USE_PEER_ASSESSMENT); context.put("name_PeerAssessmentAnonEval", NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL); context.put("name_PeerAssessmentStudentViewReviews", NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS); context.put("name_PeerAssessmentNumReviews", NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS); context.put("name_PeerAssessmentInstructions", NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE); context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION", NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO", NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY", NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE", NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION", NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE); context.put("name_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE", NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE); context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_order", NEW_ASSIGNMENT_ORDER); // set open time context variables putTimePropertiesInContext(context, state, "Open", NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // set visible time context variables if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { putTimePropertiesInContext(context, state, "Visible", NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } // set due time context variables putTimePropertiesInContext(context, state, "Due", NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); // set close time context variables putTimePropertiesInContext(context, state, "Close", NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_Category", NEW_ASSIGNMENT_CATEGORY); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null || state.getAttribute(ADDITIONAL_CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); context.put("name_CheckHideDueDate", NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE); //don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // SAK-17606 context.put("name_CheckAnonymousGrading", NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING); context.put("name_CheckIsGroupSubmission", NEW_ASSIGNMENT_GROUP_SUBMIT); String gs = (String) state.getAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT); if (gs == null) gs = "0"; // set the values Assignment a = null; String assignmentRef = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentRef != null) { a = getAssignment(assignmentRef, "setAssignmentFormContext", state); gs = a != null && a.isGroup() ? "1": "0"; } context.put("value_CheckIsGroupSubmission", gs); // put the re-submission info into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); // information related to gradebook categories putGradebookCategoryInfoIntoContext(state, context); context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); //Peer Assessment context.put("value_UsePeerAssessment", state.getAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT)); context.put("value_PeerAssessmentAnonEval", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL)); context.put("value_PeerAssessmentStudentViewReviews", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS)); context.put("value_PeerAssessmentNumReviews", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)); context.put("value_PeerAssessmentInstructions", state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS)); putTimePropertiesInContext(context, state, "PeerPeriod", NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); // Keep the use review service setting context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); context.put("turnitin_forceSingleAttachment", ServerConfigurationService.getBoolean("turnitin.forceSingleAttachment", false)); context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.allowStudentView.default", false)) : state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); List<String> subOptions = getSubmissionRepositoryOptions(); String submitRadio = ServerConfigurationService.getString("turnitin.repository.setting.value",null) == null ? NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE : ServerConfigurationService.getString("turnitin.repository.setting.value"); if(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO) != null && subOptions.contains(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO))) submitRadio = state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO).toString(); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO", submitRadio); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT", subOptions); List<String> reportGenOptions = getReportGenOptions(); String reportRadio = ServerConfigurationService.getString("turnitin.report_gen_speed.setting.value", null) == null ? NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY : ServerConfigurationService.getString("turnitin.report_gen_speed.setting.value"); if(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO) != null && reportGenOptions.contains(state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO))) reportRadio = state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO).toString(); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO", reportRadio); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT", reportGenOptions); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN", ServerConfigurationService.getBoolean("turnitin.option.s_paper_check", true)); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET", ServerConfigurationService.getBoolean("turnitin.option.internet_check", true)); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB", ServerConfigurationService.getBoolean("turnitin.option.journal_check", true)); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION", ServerConfigurationService.getBoolean("turnitin.option.institution_check", false)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN) == null) ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.s_paper_check.default", ServerConfigurationService.getBoolean("turnitin.option.s_paper_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET", state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.internet_check.default", ServerConfigurationService.getBoolean("turnitin.option.internet_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB", state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.journal_check.default", ServerConfigurationService.getBoolean("turnitin.option.journal_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION", state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION) == null ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.institution_check.default", ServerConfigurationService.getBoolean("turnitin.option.institution_check", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION)); //exclude bibliographic materials context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC", ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC) == null) ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic.default", ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC)); //exclude quoted materials context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED", ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED) == null) ? Boolean.toString(ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted.default", ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true) ? true : false)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED)); //exclude quoted materials boolean displayExcludeType = ServerConfigurationService.getBoolean("turnitin.option.exclude_smallmatches", true); context.put("show_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES", displayExcludeType); if(displayExcludeType){ context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE) == null) ? Integer.toString(ServerConfigurationService.getInt("turnitin.option.exclude_type.default", 0)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE)); context.put("value_NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE", (state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE) == null) ? Integer.toString(ServerConfigurationService.getInt("turnitin.option.exclude_value.default", 1)) : state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE)); } // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null || state.getAttribute(ADDITIONAL_CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckHideDueDate", state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); // don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // put resubmission option into context assignment_resubmission_option_into_context(context, state); // get all available assignments from Gradebook tool except for those created fromcategoryTable boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); try { // how many gradebook assignment have been integrated with Assignment tool already currentAssignmentGradebookIntegrationIntoContext(context, state, g, gradebookUid, a != null ? a.getTitle() : null); if (StringUtils.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("withGradebook", Boolean.TRUE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (associateGradebookAssignment != null) { context.put("associateGradebookAssignment", associateGradebookAssignment); if (a != null) { context.put("noAddToGradebookChoice", Boolean.valueOf(associateGradebookAssignment.equals(a.getReference()))); } } } catch (Exception e) { // not able to link to Gradebook M_log.warn(this + "setAssignmentFormContext " + e.getMessage()); } if (StringUtils.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = StringUtils.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE)); context.put("range", range != null?range:"site"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { M_log.warn(this + ":setAssignmentFormContext " + ignore.getMessage()); } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (a != null && a.isGroup()) { List _valid_groups = new ArrayList(); Iterator<Group> _it = groupsAllowAddAssignment.iterator(); while (_it.hasNext()) { Group _group = _it.next(); //if (_group.getProperties().get(GROUP_SECTION_PROPERTY) == null) { _valid_groups.add(_group); //} } groupsAllowAddAssignment = _valid_groups; } if (range == null) { if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } // SAK-26349 - need to add the collection; the iterator added below is only usable once in the velocity template AssignmentComparator comp = new AssignmentComparator(state, sort, asc); Collections.sort((List<Group>) groupsAllowAddAssignment, comp); context.put("groupsList", groupsAllowAddAssignment); context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), comp)); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", Boolean.valueOf(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices // whether the choice of emails instructor submission notification is available in the installation // system installation allowed assignment submission notification boolean allowNotification = ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true); if (allowNotification) { // whether current user can receive notification. If not, don't show the notification choices in the create/edit assignment page allowNotification = AssignmentService.allowReceiveSubmissionNotification(contextString); } if (allowNotification) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default // whether or how the instructor receive submission notification emails, none(default)|each|digest state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } // release grade notification option putReleaseGradeNotificationOptionIntoContext(state, context); // release grade notification option putReleaseResubmissionNotificationOptionIntoContext(state, context, a); // the supplement information // model answers context.put("modelanswer", state.getAttribute(MODELANSWER) != null?Boolean.TRUE:Boolean.FALSE); context.put("modelanswer_text", state.getAttribute(MODELANSWER_TEXT)); context.put("modelanswer_showto", state.getAttribute(MODELANSWER_SHOWTO)); // get attachment for model answer object putSupplementItemAttachmentStateIntoContext(state, context, MODELANSWER_ATTACHMENTS); // private notes context.put("allowReadAssignmentNoteItem", m_assignmentSupplementItemService.canReadNoteItem(a, contextString)); context.put("allowEditAssignmentNoteItem", m_assignmentSupplementItemService.canEditNoteItem(a)); context.put("note", state.getAttribute(NOTE) != null?Boolean.TRUE:Boolean.FALSE); context.put("note_text", state.getAttribute(NOTE_TEXT)); context.put("note_to", state.getAttribute(NOTE_SHAREWITH) != null?state.getAttribute(NOTE_SHAREWITH):String.valueOf(0)); // all purpose item context.put("allPurpose", state.getAttribute(ALLPURPOSE) != null?Boolean.TRUE:Boolean.FALSE); context.put("value_allPurposeTitle", state.getAttribute(ALLPURPOSE_TITLE)); context.put("value_allPurposeText", state.getAttribute(ALLPURPOSE_TEXT)); context.put("value_allPurposeHide", state.getAttribute(ALLPURPOSE_HIDE) != null?state.getAttribute(ALLPURPOSE_HIDE):Boolean.FALSE); context.put("value_allPurposeShowFrom", state.getAttribute(ALLPURPOSE_SHOW_FROM) != null?state.getAttribute(ALLPURPOSE_SHOW_FROM):Boolean.FALSE); context.put("value_allPurposeShowTo", state.getAttribute(ALLPURPOSE_SHOW_TO) != null?state.getAttribute(ALLPURPOSE_SHOW_TO):Boolean.FALSE); context.put("value_allPurposeAccessList", state.getAttribute(ALLPURPOSE_ACCESS)); putTimePropertiesInContext(context, state, "allPurposeRelease", ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN); putTimePropertiesInContext(context, state, "allPurposeRetract", ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN); // get attachment for all purpose object putSupplementItemAttachmentStateIntoContext(state, context, ALLPURPOSE_ATTACHMENTS); // put role information into context HashMap<String, List> roleUsers = new HashMap<String, List>(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); Set<Role> roles = realm.getRoles(); for(Iterator iRoles = roles.iterator(); iRoles.hasNext();) { Role r = (Role) iRoles.next(); Set<String> users = realm.getUsersHasRole(r.getId()); if (users!=null && users.size() > 0) { List<User> usersList = new ArrayList(); for (Iterator<String> iUsers = users.iterator(); iUsers.hasNext();) { String userId = iUsers.next(); try { User u = UserDirectoryService.getUser(userId); usersList.add(u); } catch (Exception e) { M_log.warn(this + ":setAssignmentFormContext cannot get user " + e.getMessage() + " user id=" + userId); } } roleUsers.put(r.getId(), usersList); } } context.put("roleUsers", roleUsers); } catch (Exception e) { M_log.warn(this + ":setAssignmentFormContext role cast problem " + e.getMessage() + " site =" + contextString); } } // setAssignmentFormContext /** * how many gradebook items has been assoicated with assignment * @param context * @param state */ private void currentAssignmentGradebookIntegrationIntoContext(Context context, SessionState state, GradebookService g, String gradebookUid, String aTitle) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get all assignment Iterator iAssignments = AssignmentService.getAssignmentsForContext(contextString); HashMap<String, String> gAssignmentIdTitles = new HashMap<String, String>(); HashMap<String, String> gradebookAssignmentsSelectedDisabled = new HashMap<String, String>(); HashMap<String, String> gradebookAssignmentsLabel = new HashMap<String, String>(); while (iAssignments.hasNext()) { Assignment a = (Assignment) iAssignments.next(); String gradebookItem = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (gradebookItem != null) { String associatedAssignmentTitles=""; if (gAssignmentIdTitles.containsKey(gradebookItem)) { // get the current associated assignment titles first associatedAssignmentTitles=gAssignmentIdTitles.get(gradebookItem) + ", "; } // append the current assignment title associatedAssignmentTitles += a.getTitle(); // put the current associated assignment titles back gAssignmentIdTitles.put(gradebookItem, associatedAssignmentTitles); } } // get all assignments in Gradebook try { List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new ArrayList(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); // gradebook item has been associated or not String gaId = gAssignment.isExternallyMaintained() ? Validator.escapeHtml(gAssignment.getExternalId()) : Validator.escapeHtml(gAssignment.getName()); String status = ""; if (gAssignmentIdTitles.containsKey(gaId)) { String assignmentTitle = gAssignmentIdTitles.get(gaId); if (aTitle != null && aTitle.equals(assignmentTitle)) { // this gradebook item is associated with current assignment, make it selected status = "selected"; } } // check with the state variable if ( state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT) != null) { String associatedAssignment = ((String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (associatedAssignment.equals(gaId)) { status ="selected"; } } gradebookAssignmentsSelectedDisabled.put(gaId, status); // gradebook assignment label String label = gAssignment.getName(); if (gAssignmentIdTitles.containsKey(gaId)) { label += " ( " + rb.getFormattedMessage("usedGradebookAssignment", new Object[]{gAssignmentIdTitles.get(gaId)}) + " )"; } gradebookAssignmentsLabel.put(gaId, label); } } } catch (GradebookNotFoundException e) { // exception M_log.debug(this + ":currentAssignmentGradebookIntegrationIntoContext " + rb.getFormattedMessage("addtogradebook.alertMessage", new Object[]{e.getMessage()})); } context.put("gradebookAssignmentsSelectedDisabled", gradebookAssignmentsSelectedDisabled); context.put("gradebookAssignmentsLabel", gradebookAssignmentsLabel); } private void putGradebookCategoryInfoIntoContext(SessionState state, Context context) { HashMap<Long, String> categoryTable = categoryTable(); if (categoryTable != null) { context.put("value_totalCategories", Integer.valueOf(categoryTable.size())); // selected category context.put("value_Category", state.getAttribute(NEW_ASSIGNMENT_CATEGORY)); List<Long> categoryList = new ArrayList<Long>(); for (Map.Entry<Long, String> entry : categoryTable.entrySet()) { categoryList.add(entry.getKey()); } Collections.sort(categoryList); context.put("categoryKeys", categoryList); context.put("categoryTable", categoryTable()); } else { context.put("value_totalCategories", Integer.valueOf(0)); } } /** * put the release grade notification options into context * @param state * @param context */ private void putReleaseGradeNotificationOptionIntoContext(SessionState state, Context context) { if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) == null) { // set the notification value using site default to be none: no email will be sent to student when the grade is released state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE); } // input fields context.put("name_assignment_releasegrade_notification", ASSIGNMENT_RELEASEGRADE_NOTIFICATION); context.put("value_assignment_releasegrade_notification", state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); // the option values context.put("value_assignment_releasegrade_notification_none", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_NONE); context.put("value_assignment_releasegrade_notification_each", Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_EACH); } /** * put the release resubmission grade notification options into context * @param state * @param context */ private void putReleaseResubmissionNotificationOptionIntoContext(SessionState state, Context context, Assignment a) { if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) == null && a != null){ // get the assignment property for notification setting first state.setAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, a.getProperties().getProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); } if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) == null){ // set the notification value using site default to be none: no email will be sent to student when the grade is released state.setAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_NONE); } // input fields context.put("name_assignment_releasereturn_notification", ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION); context.put("value_assignment_releasereturn_notification", state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); // the option values context.put("value_assignment_releasereturn_notification_none", Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_NONE); context.put("value_assignment_releasereturn_notification_each", Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_EACH); } /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("name_order", NEW_ASSIGNMENT_ORDER); context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER)); Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); context.put("value_OpenDate", openTime); if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { Time visibleTime = getTimeFromState(state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); context.put("value_VisibleDate", visibleTime); } // due time Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckHideDueDate", state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // get all available assignments from Gradebook tool except for those created from if (isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // information related to gradebook categories putGradebookCategoryInfoIntoContext(state, context); } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); String assignmentId = StringUtils.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); if (assignmentId != null) { // editing existing assignment context.put("value_assignment_id", assignmentId); Assignment a = getAssignment(assignmentId, "build_instructor_preview_assignment_context", state); if (a != null) { context.put("isDraft", Boolean.valueOf(a.getDraft())); } } else { // new assignment context.put("isDraft", Boolean.TRUE); } context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { List assignments = new ArrayList(); List assignmentIds = (List) state.getAttribute(DELETE_ASSIGNMENT_IDS); HashMap<String, Integer> submissionCountTable = new HashMap<String, Integer>(); for (int i = 0; i < assignmentIds.size(); i++) { String assignmentId = (String) assignmentIds.get(i); Assignment a = getAssignment(assignmentId, "build_instructor_delete_assignment_context", state); if (a != null) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); int submittedCount = 0; while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted() && s.getTimeSubmitted() != null) { submittedCount++; } } if (submittedCount > 0) { // if there is submission to the assignment, show the alert addAlert(state, rb.getFormattedMessage("areyousur_withSubmission", new Object[]{a.getTitle()})); } assignments.add(a); submissionCountTable.put(a.getReference(), Integer.valueOf(submittedCount)); } } context.put("assignments", assignments); context.put("confirmMessage", assignments.size() > 1 ? rb.getString("areyousur_multiple"):rb.getString("areyousur_single")); context.put("currentTime", TimeService.newTime()); context.put("submissionCountTable", submissionCountTable); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String submissionId=""; int gradeType = -1; // need to show the alert for grading drafts? boolean addGradeDraftAlert = false; // assignment String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); Assignment a = getAssignment(assignmentId, "build_instructor_grade_submission_context", state); if (a != null) { context.put("assignment", a); if (a.getContent() != null) { gradeType = a.getContent().getTypeOfGrade(); } // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, a.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); boolean allowToGrade=true; String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (associateGradebookAssignment != null) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g != null && g.isGradebookDefined(gradebookUid)) { if (!g.currentUserHasGradingPerm(gradebookUid)) { context.put("notAllowedToGradeWarning", rb.getString("not_allowed_to_grade_in_gradebook")); allowToGrade=false; } } } context.put("allowToGrade", Boolean.valueOf(allowToGrade)); } // assignment submission AssignmentSubmission s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_grade_submission_context", state); if (s != null) { submissionId = s.getId(); context.put("submission", s); if(a != null) { setScoringAgentProperties(context, a, s, true); } // show alert if student is working on a draft if (!s.getSubmitted() // not submitted && ((s.getSubmittedText() != null && s.getSubmittedText().length()> 0) // has some text || (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0))) // has some attachment { if (s.getCloseTime().after(TimeService.newTime())) { // not pass the close date yet addGradeDraftAlert = true; } else { // passed the close date already addGradeDraftAlert = false; } } ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } // put the re-submission info into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); assignment_resubmission_option_into_context(context, state); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); // try to put in grade overrides if (a.isGroup()) { Map<String,Object> _ugrades = new HashMap(); User[] _users = s.getSubmitters(); for (int i=0; _users != null && i < _users.length; i ++) { if (state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()) != null) { _ugrades.put( _users[i].getId(), gradeType == 3 ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId())): state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()) ); } } context.put("value_grades", _ugrades); } context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); // is this a non-electronic submission type of assignment context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE); if (addGradeDraftAlert) { addAlert(state, rb.getString("grading.alert.draft.beforeclosedate")); } context.put("alertGradeDraft", Boolean.valueOf(addGradeDraftAlert)); if (a != null && a.isGroup()) { checkForUsersInMultipleGroups(a, s.getSubmitterIds(), state, rb.getString("group.user.multiple.warning")); } // for the navigation purpose List<SubmitterSubmission> userSubmissions = state.getAttribute(USER_SUBMISSIONS) != null ? (List<SubmitterSubmission>) state.getAttribute(USER_SUBMISSIONS):null; if (userSubmissions != null) { for (int i = 0; i < userSubmissions.size(); i++) { if (((SubmitterSubmission) userSubmissions.get(i)).getSubmission().getId().equals(submissionId)) { boolean goPT = false; boolean goNT = false; if ((i - 1) >= 0) { goPT = true; } if ((i + 1) < userSubmissions.size()) { goNT = true; } context.put("goPTButton", Boolean.valueOf(goPT)); context.put("goNTButton", Boolean.valueOf(goNT)); if (i>0) { // retrieve the previous submission id context.put("prevSubmissionId", ((SubmitterSubmission) userSubmissions.get(i-1)).getSubmission().getReference()); } if (i < userSubmissions.size() - 1) { // retrieve the next submission id context.put("nextSubmissionId", ((SubmitterSubmission) userSubmissions.get(i+1)).getSubmission().getReference()); } } } } // put supplement item into context supplementItemIntoContext(state, context, a, null); // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_DONE) != null) { context.put("gradingDone", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_DONE); } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_SUBMIT) != null) { context.put("gradingSubmit", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); } // letter grading letterGradeOptionsIntoContext(context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context /** * Checks whether the time is already past. * If yes, return the time of three days from current time; * Otherwise, return the original time * @param originalTime * @return */ private Time getProperFutureTime(Time originalTime) { // check whether the time is past already. // If yes, add three days to the current time Time time = originalTime; if (TimeService.newTime().after(time)) { time = TimeService.newTime(TimeService.newTime().getTime() + 3*24*60*60*1000/*add three days*/); } return time; } public void doPrev_back_next_submission_review(RunData rundata, String option, boolean submit) { SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid()); // save the instructor input boolean hasChange = saveReviewGradeForm(rundata, state, submit ? "submit" : "save"); if (state.getAttribute(STATE_MESSAGE) == null) { ParameterParser params = rundata.getParameters(); List<String> submissionIds = new ArrayList<String>(); if(state.getAttribute(USER_SUBMISSIONS) != null){ submissionIds = (List<String>) state.getAttribute(USER_SUBMISSIONS); } String submissionId = null; String assessorId = null; if ("next".equals(option)) { submissionId = params.get("nextSubmissionId"); assessorId = params.get("nextAssessorId"); } else if ("prev".equals(option)) { submissionId = params.get("prevSubmissionId"); assessorId = params.get("prevAssessorId"); } else if ("back".equals(option)) { String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); List userSubmissionsState = state.getAttribute(STATE_PAGEING_TOTAL_ITEMS) != null ? (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS):null; if(userSubmissionsState != null && userSubmissionsState.size() > 0 && userSubmissionsState.get(0) instanceof SubmitterSubmission && AssignmentService.allowGradeSubmission(assignmentId)){ //coming from instructor view submissions page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); }else{ state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } if(submissionId != null && submissionIds.contains(submissionId)){ state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); } if(assessorId != null){ state.setAttribute(PEER_ASSESSMENT_ASSESSOR_ID, assessorId); } } } /** * Responding to the request of submission navigation * @param rundata * @param option */ public void doPrev_back_next_submission(RunData rundata, String option) { SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid()); // save the instructor input boolean hasChange = readGradeForm(rundata, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null && hasChange) { grade_submission_option(rundata, "save"); } if (state.getAttribute(STATE_MESSAGE) == null) { if ("next".equals(option)) { navigateToSubmission(rundata, "nextSubmissionId"); } else if ("prev".equals(option)) { navigateToSubmission(rundata, "prevSubmissionId"); } else if ("back".equals(option)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } else if ("backListStudent".equals(option)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } } } // doPrev_back_next_submission private void navigateToSubmission(RunData rundata, String paramString) { ParameterParser params = rundata.getParameters(); SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid()); String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); String submissionId = StringUtils.trimToNull(params.getString(paramString)); if (submissionId != null) { // put submission information into state putSubmissionInfoIntoState(state, assignmentId, submissionId); } } /** * Parse time value and put corresponding values into state * @param context * @param state * @param a * @param timeValue * @param timeName * @param month * @param day * @param year * @param hour * @param min */ private void putTimePropertiesInState(SessionState state, Time timeValue, String month, String day, String year, String hour, String min) { try { TimeBreakdown bTime = timeValue.breakdownLocal(); state.setAttribute(month, Integer.valueOf(bTime.getMonth())); state.setAttribute(day, Integer.valueOf(bTime.getDay())); state.setAttribute(year, Integer.valueOf(bTime.getYear())); state.setAttribute(hour, Integer.valueOf(bTime.getHour())); state.setAttribute(min, Integer.valueOf(bTime.getMin())); } catch (NullPointerException _npe) { /* TODO empty exception block */ } } /** * put related time information into context variable * @param context * @param state * @param timeName * @param month * @param day * @param year * @param hour * @param min */ private void putTimePropertiesInContext(Context context, SessionState state, String timeName, String month, String day, String year, String hour, String min) { // get the submission level of close date setting context.put("name_" + timeName + "Month", month); context.put("name_" + timeName + "Day", day); context.put("name_" + timeName + "Year", year); context.put("name_" + timeName + "Hour", hour); context.put("name_" + timeName + "Min", min); context.put("value_" + timeName + "Month", (Integer) state.getAttribute(month)); context.put("value_" + timeName + "Day", (Integer) state.getAttribute(day)); context.put("value_" + timeName + "Year", (Integer) state.getAttribute(year)); context.put("value_" + timeName + "Hour", (Integer) state.getAttribute(hour)); context.put("value_" + timeName + "Min", (Integer) state.getAttribute(min)); } private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); Assignment a = getAssignment(assignmentId, "build_instructor_preview_grade_submission_context", state); if (a != null) { context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } // submission AssignmentSubmission submission = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_instructor_preview_grade_submission_context", state); context.put("submission", submission); if(a != null) { setScoringAgentProperties(context, a, submission, false); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW); context.put("userDirectoryService", UserDirectoryService.getInstance()); String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Assignment assignment = getAssignment(assignmentRef, "build_instructor_grade_assignment_context", state); // getContent() early and store it, this call is expensive, always making a db call due to lack of caching in this tool AssignmentContent assignmentContent = assignment == null ? null : assignment.getContent(); if (assignment != null) { context.put("assignment", assignment); state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId()); if (assignmentContent != null) { context.put("assignmentContent", assignmentContent); context.put("value_SubmissionType", Integer.valueOf(assignmentContent.getTypeOfSubmission())); context.put("typeOfGrade", assignmentContent.getTypeOfGrade()); } // put creator information into context putCreatorIntoContext(context, assignment); String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (defaultGrade != null) { context.put("defaultGrade", defaultGrade); } initViewSubmissionListOption(state); String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); context.put("view", view); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH): rb.getString("search_student_instruction")); // access point url for zip file download String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))); if (view != null && !AssignmentConstants.ALL.equals(view)) { // append the group info to the end accessPointUrl = accessPointUrl.concat(view); } context.put("accessPointUrl", accessPointUrl); // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, assignment.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference()); // group list which user can add message to if (groupsAllowGradeAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc))); } } // SAK-17606 context.put("value_CheckAnonymousGrading", state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); List<SubmitterSubmission> userSubmissions = prepPage(state); // attach the assignment to these submissions now to avoid costly lookup for each submission later in the velocity template for (SubmitterSubmission s : userSubmissions) { s.getSubmission().setAssignment(assignment); } state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); //find peer assessment grades if exist if(assignment.getAllowPeerAssessment()){ List<String> submissionIds = new ArrayList<String>(); //get list of submission ids to look up reviews in db for(SubmitterSubmission s : userSubmissions){ submissionIds.add(s.getSubmission().getId()); } //look up reviews for these submissions List<PeerAssessmentItem> items = assignmentPeerAssessmentService.getPeerAssessmentItems(submissionIds); //create a map for velocity to use in displaying the submission reviews Map<String, List<PeerAssessmentItem>> itemsMap = new HashMap<String, List<PeerAssessmentItem>>(); Map<String, User> reviewersMap = new HashMap<String, User>(); if(items != null){ for(PeerAssessmentItem item : items){ //update items map List<PeerAssessmentItem> sItems = itemsMap.get(item.getSubmissionId()); if(sItems == null){ sItems = new ArrayList<PeerAssessmentItem>(); } sItems.add(item); itemsMap.put(item.getSubmissionId(), sItems); //update users map: User u = reviewersMap.get(item.getAssessorUserId()); if(u == null){ try { u = UserDirectoryService.getUser(item.getAssessorUserId()); reviewersMap.put(item.getAssessorUserId(), u); } catch (UserNotDefinedException e) { M_log.warn(e.getMessage(), e); } } } } //go through all the submissions and make sure there aren't any nulls for(String id : submissionIds){ List<PeerAssessmentItem> sItems = itemsMap.get(id); if(sItems == null){ sItems = new ArrayList<PeerAssessmentItem>(); itemsMap.put(id, sItems); } } context.put("peerAssessmentItems", itemsMap); context.put("reviewersMap", reviewersMap); } // try to put in grade overrides if (assignment.isGroup()) { Map<String,Object> _ugrades = new HashMap<String,Object>(); Iterator<SubmitterSubmission> _ssubmits = userSubmissions.iterator(); while (_ssubmits.hasNext()) { SubmitterSubmission _ss = _ssubmits.next(); if (_ss != null && _ss.getSubmission() != null) { User[] _users = _ss.getSubmission().getSubmitters(); for (int i=0; _users != null && i < _users.length; i ++) { String _agrade = _ss.getSubmission().getGradeForUser(_users[i].getId()); if (_agrade != null) { _ugrades.put( _users[i].getId(), assignmentContent != null && assignmentContent.getTypeOfGrade() == 3 ? displayGrade(state, _agrade): _agrade); } } } } context.put("value_grades", _ugrades); Collection<String> _dups = checkForUsersInMultipleGroups(assignment, null, state, rb.getString("group.user.multiple.warning")); if (_dups.size() > 0) { context.put("usersinmultiplegroups", _dups); } } // whether to show the resubmission choice if (state.getAttribute(SHOW_ALLOW_RESUBMISSION) != null) { context.put("showAllowResubmission", Boolean.TRUE); } // put the re-submission info into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); assignment_resubmission_option_into_context(context, state); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); // put supplement item into context supplementItemIntoContext(state, context, assignment, null); // search context String searchString = (String) state.getAttribute(STATE_SEARCH); if (searchString == null) { searchString = rb.getString("search_student_instruction"); } context.put("searchString", searchString); context.put("form_search", FORM_SEARCH); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); // letter grading letterGradeOptionsIntoContext(context); // ever set the default grade for no-submissions if (assignment != null && assignmentContent != null && assignmentContent.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // non-electronic submissions context.put("form_action", "eventSubmit_doSet_defaultNotGradedNonElectronicScore"); context.put("form_label", rb.getFormattedMessage("not.graded.non.electronic.submission.grade", new Object[]{state.getAttribute(STATE_NUM_MESSAGES)})); } else { // other types of submissions context.put("form_action", "eventSubmit_doSet_defaultNoSubmissionScore"); context.put("form_label", rb.getFormattedMessage("non.submission.grade", new Object[]{state.getAttribute(STATE_NUM_MESSAGES)})); } // show the reminder for download all url String downloadUrl = (String) state.getAttribute(STATE_DOWNLOAD_URL); if (downloadUrl != null) { context.put("download_url_reminder", rb.getString("download_url_reminder")); context.put("download_url_link", downloadUrl); context.put("download_url_link_label", rb.getString("download_url_link_label")); state.removeAttribute(STATE_DOWNLOAD_URL); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * make sure the state variable VIEW_SUBMISSION_LIST_OPTION is not null * @param state */ private void initViewSubmissionListOption(SessionState state) { if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null && (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) == null || !((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)).booleanValue())) { state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, AssignmentConstants.ALL); } } /** * put the supplement item information into context * @param state * @param context * @param assignment * @param s */ private void supplementItemIntoContext(SessionState state, Context context, Assignment assignment, AssignmentSubmission s) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // for model answer boolean allowViewModelAnswer = m_assignmentSupplementItemService.canViewModelAnswer(assignment, s); context.put("allowViewModelAnswer", allowViewModelAnswer); if (allowViewModelAnswer) { context.put("assignmentModelAnswerItem", m_assignmentSupplementItemService.getModelAnswer(assignment.getId())); } // for note item boolean allowReadAssignmentNoteItem = m_assignmentSupplementItemService.canReadNoteItem(assignment, contextString); context.put("allowReadAssignmentNoteItem", allowReadAssignmentNoteItem); if (allowReadAssignmentNoteItem) { context.put("assignmentNoteItem", m_assignmentSupplementItemService.getNoteItem(assignment.getId())); } // for all purpose item boolean allowViewAllPurposeItem = m_assignmentSupplementItemService.canViewAllPurposeItem(assignment); context.put("allowViewAllPurposeItem", allowViewAllPurposeItem); if (allowViewAllPurposeItem) { context.put("assignmentAllPurposeItem", m_assignmentSupplementItemService.getAllPurposeItem(assignment.getId())); } } /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); Assignment assignment = getAssignment(assignmentId, "build_instructor_view_assignment_context", state); if (assignment != null) { context.put("assignment", assignment); // put the resubmit information into context assignment_resubmission_option_into_context(context, state); // put creator information into context putCreatorIntoContext(context, assignment); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { Session session = SessionManager.getCurrentSession(); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getActivityHelperInfo( assignmentActivityProducer.getActivity( assignment).getReference()); if (helper != null) { activityHelpers.add(helper); } } addActivity(context, assignment); context.put("activityHelpers", activityHelpers); context.put("taggable", Boolean.valueOf(true)); addDecoUrlMapToContext(session, context, false); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("honor_pledge_text", ServerConfigurationService.getString("assignment.honor.pledge", rb.getString("gen.honple2"))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context private void putCreatorIntoContext(Context context, Assignment assignment) { // the creator String creatorId = assignment.getCreator(); try { User creator = UserDirectoryService.getUser(creatorId); context.put("creator", creator.getDisplayName()); } catch (Exception ee) { context.put("creator", creatorId); M_log.warn(this + ":build_instructor_view_assignment_context " + ee.getMessage()); } } /** * build the instructor view of reordering assignments */ protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); context.put("assignmentsize", assignments.size()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT; } // build_instructor_reorder_assignment_context protected String build_student_review_edit_context(VelocityPortlet portlet, Context context, RunData data, SessionState state){ int gradeType = -1; context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state.getAttribute(PEER_ASSESSMENT_ITEMS); String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); User sessionUser = (User) state.getAttribute(STATE_USER); String assessorId = sessionUser.getId(); if(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null){ assessorId = (String) state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID); } Assignment assignment = getAssignment(assignmentId, "build_student_review_edit_context", state); if (assignment != null){ context.put("assignment", assignment); if (assignment.getContent() != null) { gradeType = assignment.getContent().getTypeOfGrade(); } context.put("peerAssessmentInstructions", assignment.getPeerAssessmentInstructions() == null ? "" : assignment.getPeerAssessmentInstructions()); } String submissionId = ""; SecurityAdvisor secAdv = new SecurityAdvisor(){ @Override public SecurityAdvice isAllowed(String userId, String function, String reference) { if("asn.submit".equals(function) || "asn.submit".equals(function) || "asn.grade".equals(function)){ return SecurityAdvice.ALLOWED; } return null; } }; AssignmentSubmission s = null; try{ //surround with a try/catch/finally for the security advisor m_securityService.pushAdvisor(secAdv); s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_student_review_edit_context", state); m_securityService.popAdvisor(secAdv); }catch(Exception e){ M_log.error(e.getMessage(), e); }finally{ if(secAdv != null){ m_securityService.popAdvisor(secAdv); } } if (s != null) { submissionId = s.getId(); context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { context.put("value_feedback_text", s.getSubmittedText()); } else { context.put("value_feedback_text", s.getFeedbackFormattedText()); } context.put("value_feedback_text", s.getSubmittedText()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } context.put("value_feedback_attachment", v); state.setAttribute(ATTACHMENTS, v); } if(peerAssessmentItems != null && submissionId != null){ //find the peerAssessmentItem for this submission: PeerAssessmentItem peerAssessmentItem = null; for(PeerAssessmentItem item : peerAssessmentItems){ if(submissionId.equals(item.getSubmissionId()) && assessorId.equals(item.getAssessorUserId())){ peerAssessmentItem = item; break; } } if(peerAssessmentItem != null){ //check if current user is the peer assessor, if not, only display data (no editing) if(!sessionUser.getId().equals(peerAssessmentItem.getAssessorUserId())){ context.put("view_only", true); try { User reviewer = UserDirectoryService.getUser(peerAssessmentItem.getAssessorUserId()); context.put("reviewer", reviewer); } catch (UserNotDefinedException e) { M_log.warn(e.getMessage(), e); } }else{ context.put("view_only", false); } //scores are saved as whole values //so a score of 1.3 would be stored as 13 //so a DB score of 13 needs to be 1.3: if(peerAssessmentItem.getScore() != null){ double score = peerAssessmentItem.getScore()/10.0; context.put("value_grade", score); }else{ context.put("value_grade", null); } context.put("display_grade", peerAssessmentItem.getScoreDisplay()); context.put("item_removed", peerAssessmentItem.isRemoved()); context.put("value_feedback_comment", peerAssessmentItem.getComment()); //set previous/next values List userSubmissionsState = state.getAttribute(STATE_PAGEING_TOTAL_ITEMS) != null ? (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS):null; List<String> userSubmissions = new ArrayList<String>(); boolean instructorView = false; if(userSubmissionsState != null && userSubmissionsState.size() > 0 && userSubmissionsState.get(0) instanceof SubmitterSubmission){ //from instructor view for(SubmitterSubmission userSubmission : (List<SubmitterSubmission>) userSubmissionsState){ if(!userSubmissions.contains(userSubmission.getSubmission().getId()) && userSubmission.getSubmission().getSubmitted()){ userSubmissions.add(userSubmission.getSubmission().getId()); } } }else{ //student view for(PeerAssessmentItem item : peerAssessmentItems){ if(!userSubmissions.contains(item.getSubmissionId()) && !item.isSubmitted()){ userSubmissions.add(item.getSubmissionId()); } } } if(userSubmissions != null){ context.put("totalReviews", userSubmissions.size()); //first setup map to make the navigation logic easier: Map<String, List<PeerAssessmentItem>> itemMap = new HashMap<String, List<PeerAssessmentItem>>(); for(String userSubmissionId : userSubmissions){ for (PeerAssessmentItem item : peerAssessmentItems){ if(userSubmissionId.equals(item.getSubmissionId())){ List<PeerAssessmentItem> items = itemMap.get(userSubmissionId); if(items == null){ items = new ArrayList<PeerAssessmentItem>(); } items.add(item); itemMap.put(item.getSubmissionId(), items); } } } for(int i = 0; i < userSubmissions.size(); i++){ String userSubmissionId = userSubmissions.get(i); if(userSubmissionId.equals(submissionId)){ //we found the right submission, now find the items context.put("reviewNumber", (i + 1)); List<PeerAssessmentItem> submissionItems = itemMap.get(submissionId); if(submissionItems != null){ for (int j = 0; j < submissionItems.size(); j++){ PeerAssessmentItem item = submissionItems.get(j); if(item.getAssessorUserId().equals(assessorId)){ context.put("anonNumber", i + 1); boolean goPT = false; boolean goNT = false; if ((i - 1) >= 0 || (j - 1) >= 0) { goPT = true; } if ((i + 1) < userSubmissions.size() || (j + 1) < submissionItems.size()) { goNT = true; } context.put("goPTButton", Boolean.valueOf(goPT)); context.put("goNTButton", Boolean.valueOf(goNT)); if (j>0) { // retrieve the previous submission id context.put("prevSubmissionId", (submissionItems.get(j-1).getSubmissionId())); context.put("prevAssessorId", (submissionItems.get(j-1).getAssessorUserId())); }else if(i > 0){ //go to previous submission and grab the last item in that list int k = i - 1; while(k >= 0 && !itemMap.containsKey(userSubmissions.get(k))){ k--; } if(k >= 0 && itemMap.get(userSubmissions.get(k)).size() > 0){ List<PeerAssessmentItem> pItems = itemMap.get(userSubmissions.get(k)); PeerAssessmentItem pItem = pItems.get(pItems.size() - 1); context.put("prevSubmissionId", (pItem.getSubmissionId())); context.put("prevAssessorId", (pItem.getAssessorUserId())); }else{ //no previous option, set to false context.put("goPTButton", Boolean.valueOf(false)); } } if (j < submissionItems.size() - 1) { // retrieve the next submission id context.put("nextSubmissionId", (submissionItems.get(j+1).getSubmissionId())); context.put("nextAssessorId", (submissionItems.get(j+1).getAssessorUserId())); }else if (i < userSubmissions.size() - 1){ //go to previous submission and grab the last item in that list int k = i + 1; while(k < userSubmissions.size() && !itemMap.containsKey(userSubmissions.get(k))){ k++; } if(k < userSubmissions.size() && itemMap.get(userSubmissions.get(k)).size() > 0){ List<PeerAssessmentItem> pItems = itemMap.get(userSubmissions.get(k)); PeerAssessmentItem pItem = pItems.get(0); context.put("nextSubmissionId", (pItem.getSubmissionId())); context.put("nextAssessorId", (pItem.getAssessorUserId())); }else{ //no next option, set to false context.put("goNTButton", Boolean.valueOf(false)); } } } } } } } } } } context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("user", sessionUser); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // put supplement item into context try{ //surround with a try/catch/finally for the security advisor m_securityService.pushAdvisor(secAdv); supplementItemIntoContext(state, context, assignment, null); }catch(Exception e){ M_log.error(e.getMessage(), e); }finally{ if(secAdv != null){ m_securityService.popAdvisor(secAdv); } } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_DONE) != null) { context.put("gradingDone", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_DONE); if(state.getAttribute(PEER_ASSESSMENT_REMOVED_STATUS) != null){ context.put("itemRemoved", state.getAttribute(PEER_ASSESSMENT_REMOVED_STATUS)); state.removeAttribute(PEER_ASSESSMENT_REMOVED_STATUS); } } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_SUBMIT) != null) { context.put("gradingSubmit", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_REVIEW_EDIT; } /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // cleaning from view attribute state.removeAttribute(FROM_VIEW); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); // get the realm and its member List studentMembers = new ArrayList(); Iterator assignments = AssignmentService.getAssignmentsForContext(contextString); //No duplicates Set allowSubmitMembers = new HashSet(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, a.getReference(), contextString); allowSubmitMembers.addAll(submitterIds); } for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage()); } } context.put("studentMembers", new SortedIterator(studentMembers.iterator(), new AssignmentComparator(state, SORTED_USER_BY_SORTNAME, Boolean.TRUE.toString()))); context.put("assignmentService", AssignmentService.getInstance()); context.put("userService", UserDirectoryService.getInstance()); context.put("viewGroup", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH): rb.getString("search_student_instruction")); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); if (AssignmentService.getAllowGroupAssignments()) { Collection groups = getAllGroupsInSite(contextString); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); } HashMap showStudentAssignments = new HashMap(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); // sort the assignments into the default order before adding Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId); // filter to obtain only grade-able assignments List rv = new ArrayList(); while (assignmentSorter.hasNext()) { Assignment a = (Assignment) assignmentSorter.next(); if (AssignmentService.allowGradeSubmission(a.getReference())) { rv.add(a); } } Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString())); showStudentAssignments.put(user, assignmentSortFinal); } catch (Exception ee) { M_log.warn(this + ":build_instructor_view_student_assignment_context " + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_GRADE_SUBMISSION_BY_RELEASED); //context.put("sortedBy_assignment", SORTED_GRADE_SUBMISSION_BY_ASSIGNMENT); //context.put("sortedBy_maxGrade", SORTED_GRADE_SUBMISSION_BY_MAX_GRADE); // get current site String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH): rb.getString("search_student_instruction")); context.put("view", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)); context.put("viewString", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)!=null?state.getAttribute(VIEW_SUBMISSION_LIST_OPTION):""); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH):""); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); if (AssignmentService.getAllowGroupAssignments()) { Collection groups = getAllGroupsInSite(contextString); context.put("groups", new SortedIterator(groups.iterator(), new AssignmentComparator(state, SORTED_BY_GROUP_TITLE, Boolean.TRUE.toString() ))); } add2ndToolbarFields(data, context); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); context.put("assignmentService", AssignmentService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions // Is Gradebook defined for the site? protected boolean isGradebookDefined() { boolean rv = false; try { GradebookService g = (GradebookService) ComponentManager .get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid) && (g.currentUserHasEditPerm(gradebookUid) || g.currentUserHasGradingPerm(gradebookUid))) { rv = true; } } catch (Exception e) { M_log.debug(this + "isGradebookDefined " + rb.getFormattedMessage("addtogradebook.alertMessage", new Object[]{e.getMessage()})); } return rv; } // isGradebookDefined() /** * build the instructor view to download/upload information from archive file */ protected String build_instructor_download_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String view = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); boolean download = (((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_DOWNLOAD_ALL)); context.put("download", Boolean.valueOf(download)); context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT)); context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT)); context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE)); String gradeFileFormat = (String) state.getAttribute(UPLOAD_ALL_GRADEFILE_FORMAT); if (gradeFileFormat==null) gradeFileFormat="csv"; context.put("gradeFileFormat", gradeFileFormat); context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS)); context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT)); context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT)); context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES)); // SAK-19147 context.put("withoutFolders", state.getAttribute(UPLOAD_ALL_WITHOUT_FOLDERS)); context.put("enableFlatDownload", ServerConfigurationService.getBoolean("assignment.download.flat", false)); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Assignment a = getAssignment(assignmentRef, "build_instructor_download_upload_all", state); if (a != null) { String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference( contextString, assignmentRef)); context.put("accessPointUrl", accessPointUrl); int submissionType = a.getContent().getTypeOfSubmission(); // if the assignment is of text-only or allow both text and attachment, include option for uploading student submit text context.put("includeSubmissionText", Boolean.valueOf(Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION == submissionType || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == submissionType)); // if the assignment is of attachment-only or allow both text and attachment, include option for uploading student attachment context.put("includeSubmissionAttachment", Boolean.valueOf(Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION == submissionType || Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION == submissionType || Assignment.SINGLE_ATTACHMENT_SUBMISSION == submissionType)); context.put("viewString", state.getAttribute(VIEW_SUBMISSION_LIST_OPTION)!=null?state.getAttribute(VIEW_SUBMISSION_LIST_OPTION):""); context.put("searchString", state.getAttribute(VIEW_SUBMISSION_SEARCH)!=null?state.getAttribute(VIEW_SUBMISSION_SEARCH):""); context.put("showSubmissionByFilterSearchOnly", state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL; } // build_instructor_upload_all /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * integration with gradebook * * @param state * @param assignmentRef Assignment reference * @param associateGradebookAssignment The title for the associated GB assignment * @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment * @param oldAssignment_title The original assignment title * @param newAssignment_title The updated assignment title * @param newAssignment_maxPoints The maximum point of the assignment * @param newAssignment_dueTime The due time of the assignment * @param submissionRef Any submission grade need to be updated? Do bulk update if null * @param updateRemoveSubmission "update" for update submission;"remove" for remove submission */ protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission, long category) { associateGradebookAssignment = StringUtils.trimToNull(associateGradebookAssignment); // add or remove external grades to gradebook // a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden // b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The // exception are indication that the assessment is already in the Gradebook or there is nothing // to remove. String assignmentToolTitle = getToolTitle(); GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid) && g.currentUserHasGradingPerm(gradebookUid)) { boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, assignmentRef); boolean isExternalAssociateAssignmentDefined = gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment); if (addUpdateRemoveAssignment != null) { // add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || ("update".equals(addUpdateRemoveAssignment) && !isExternalAssignmentDefined)) && associateGradebookAssignment == null) { // add assignment into gradebook try { // add assignment to gradebook gExternal.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle, false, category != -1?Long.valueOf(category):null); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (ConflictingAssignmentNameException e) { // add alert prompting for change assignment title addAlert(state, rb.getFormattedMessage("addtogradebook.nonUniqueTitle", new Object[]{"\"" + newAssignment_title + "\""})); M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (ConflictingExternalIdException e) { // this shouldn't happen, as we have already checked for assignment reference before. Log the error M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (GradebookNotFoundException e) { // this shouldn't happen, as we have checked for gradebook existence before M_log.warn(this + ":integrateGradebook " + e.getMessage()); } catch (Exception e) { // ignore M_log.warn(this + ":integrateGradebook " + e.getMessage()); } } else if ("update".equals(addUpdateRemoveAssignment)) { if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined) { // if there is an external entry created in Gradebook based on this assignment, update it try { // update attributes if the GB assignment was created for the assignment gExternal.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), false); } catch(Exception e) { addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef})); M_log.warn(this + ":integrateGradebook " + rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef})); } } } // addUpdateRemove != null else if ("remove".equals(addUpdateRemoveAssignment)) { // remove assignment and all submission grades removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, gExternal, gradebookUid); } } if (updateRemoveSubmission != null) { Assignment a = getAssignment(assignmentRef, "integrateGradebook", state); if (a != null) { if ("update".equals(updateRemoveSubmission) && a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null && !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (submissionRef == null) { // bulk add all grades for assignment into gradebook Iterator submissions = AssignmentService.getSubmissions(a).iterator(); //Assignment scores map Map<String, String> sm = new HashMap<String, String>(); //Assignment comments map, though doesn't look like there's any way to update comments in bulk in the UI yet Map<String, String> cm = new HashMap<String, String>(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); if (aSubmission.getGradeReleased()) { User[] submitters = aSubmission.getSubmitters(); String gradeString = StringUtils.trimToNull(aSubmission.getGrade(false)); String commentString = FormattedText.convertFormattedTextToPlaintext(aSubmission.getFeedbackComment()); String grade = gradeString != null ? displayGrade(state,gradeString) : null; for (int i=0; submitters != null && i < submitters.length; i++) { String submitterId = submitters[i].getId(); if (a.isGroup() && aSubmission.getGradeForUser(submitterId) != null) { grade = displayGrade(state,aSubmission.getGradeForUser(submitterId)); } sm.put(submitterId, grade); cm.put(submitterId, commentString); } } } // need to update only when there is at least one submission if (!sm.isEmpty()) { if (associateGradebookAssignment != null) { if (isExternalAssociateAssignmentDefined) { // the associated assignment is externally maintained gExternal.updateExternalAssessmentScoresString(gradebookUid, associateGradebookAssignment, sm); gExternal.updateExternalAssessmentComments(gradebookUid, associateGradebookAssignment, cm); } else if (isAssignmentDefined) { // the associated assignment is internal one, update records one by one for (Map.Entry<String, String> entry : sm.entrySet()) { String submitterId = (String) entry.getKey(); String grade = StringUtils.trimToNull(displayGrade(state, (String) sm.get(submitterId))); if (grade != null) { g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitterId, grade, ""); } } } } else if (isExternalAssignmentDefined) { gExternal.updateExternalAssessmentScoresString(gradebookUid, assignmentRef, sm); gExternal.updateExternalAssessmentComments(gradebookUid, associateGradebookAssignment, cm); } } } else { // only update one submission AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state); if (aSubmission != null) { User[] submitters = aSubmission.getSubmitters(); String gradeString = displayGrade(state, StringUtils.trimToNull(aSubmission.getGrade(false))); for (int i=0; submitters != null && i < submitters.length; i++) { String gradeStringToUse = (a.isGroup() && aSubmission.getGradeForUser(submitters[i].getId()) != null) ? displayGrade(state,aSubmission.getGradeForUser(submitters[i].getId())): gradeString; if (associateGradebookAssignment != null) { if (gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is externally maintained gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[i].getId(), (gradeStringToUse != null && aSubmission.getGradeReleased()) ? gradeStringToUse : ""); //Gradebook only supports plaintext strings String commentString = FormattedText.convertFormattedTextToPlaintext(aSubmission.getFeedbackComment()); gExternal.updateExternalAssessmentComment(gradebookUid, associateGradebookAssignment, submitters[i].getId(), (commentString != null && aSubmission.getGradeReleased()) ? commentString : ""); } else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is internal one, update records g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[i].getId(), (gradeStringToUse != null && aSubmission.getGradeReleased()) ? gradeStringToUse : "", ""); } } else { gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[i].getId(), (gradeStringToUse != null && aSubmission.getGradeReleased()) ? gradeStringToUse : ""); } } } } } else if ("remove".equals(updateRemoveSubmission)) { if (submissionRef == null) { // remove all submission grades (when changing the associated entry in Gradebook) Iterator submissions = AssignmentService.getSubmissions(a).iterator(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); for (int i=0; submitters != null && i < submitters.length; i++) { if (isExternalAssociateAssignmentDefined) { // if the old associated assignment is an external maintained one gExternal.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[i].getId(), null); } else if (isAssignmentDefined) { g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[i].getId(), "0", assignmentToolTitle); } } } } else { // remove only one submission grade AssignmentSubmission aSubmission = getSubmission(submissionRef, "integrateGradebook", state); if (aSubmission != null) { User[] submitters = aSubmission.getSubmitters(); for (int i=0; submitters != null && i < submitters.length; i++) { if (isExternalAssociateAssignmentDefined) { // external assignment gExternal.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[i].getId(), null); } else if (isAssignmentDefined) { // gb assignment g.setAssignmentScoreString(gradebookUid, associateGradebookAssignment, submitters[i].getId(), "0", ""); } } } } } } } } } // integrateGradebook /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student public void doView_submission_evap(RunData data){ SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(INVOKE, INVOKE_BY_LINK); doView_submission(data); } /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); String submitterId = params.get("submitterId"); if (submitterId != null) { try { u = UserDirectoryService.getUser(submitterId); state.setAttribute("student", u); } catch (UserNotDefinedException ex) { M_log.warn(this + ":doView_submission cannot find user with id " + submitterId + " " + ex.getMessage()); } } Assignment a = getAssignment(assignmentReference, "doView_submission", state); if (a != null) { AssignmentSubmission submission = getSubmission(assignmentReference, u, "doView_submission", state); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (Boolean.valueOf(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } // put resubmission option into state assignment_resubmission_option_into_state(a, submission, state); // show submission view unless group submission with group error String _mode = MODE_STUDENT_VIEW_SUBMISSION; if (a.isGroup()) { Collection<Group> groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); groups = getGroupsWithUser(u.getId(), a, st); Collection<String> _dupUsers = checkForGroupsInMultipleGroups(a, groups, state, rb.getString("group.user.multiple.warning")); if (_dupUsers.size() > 0) { _mode = MODE_STUDENT_VIEW_GROUP_ERROR; } } catch (IdUnusedException iue) { M_log.warn(this + ":doView_submission: Site not found!" + iue.getMessage()); } } state.setAttribute(STATE_MODE, _mode); if (submission != null) { // submission read event Event event = m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submission.getId(), false); m_eventTrackingService.post(event); LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); if (null != lrss) { lrss.registerStatement(getStatementForViewSubmittedAssignment(lrss.getEventActor(event), event, a.getTitle()), "assignment"); } } else { // otherwise, the student just read assignment description and prepare for submission Event event = m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, a.getId(), false); m_eventTrackingService.post(event); LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); if (null != lrss) { lrss.registerStatement(getStatementForViewAssignment(lrss.getEventActor(event), event, a.getTitle()), "assignment"); } } } } // doView_submission /** * Dispatcher for view submission list options */ public void doView_submission_list_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if ("changeView".equals(option)) { doChange_submission_list_option(data); } else if ("search".equals(option)) { state.setAttribute(VIEW_SUBMISSION_SEARCH, params.getString("search")); } else if ("clearSearch".equals(option)) { state.removeAttribute(VIEW_SUBMISSION_SEARCH); } else if ("download".equals(option)) { // go to download all page doPrep_download_all(data); } else if ("upload".equals(option)) { // go to upload all page doPrep_upload_all(data); } else if ("releaseGrades".equals(option)) { // release all grades doRelease_grades(data); } } // doView_submission_list_option /** * Action is to view the content of one specific assignment submission */ public void doChange_submission_list_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String view = params.getString("viewgroup"); //Case where two dropdowns on same page if (view == null) { view = params.getString("view"); } state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view); } // doView_submission_list_option /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, aReference); Assignment a = getAssignment(aReference, "doPreview_submission", state); saveSubmitInputs(state, params); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); // get attachment input and generate alert message according to assignment submission type checkSubmissionTextAttachmentInput(data, state, a, text); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); String fromView = (String) state.getAttribute(FROM_VIEW); if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } else { // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new ArrayList()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { // put submission information into state SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); putSubmissionInfoIntoState(state, assignmentId, sId); String fromView = (String) state.getAttribute(FROM_VIEW); if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } else { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doCancel_grade_submission /** * clean the state variables related to grading page * @param state */ private void resetGradeSubmission(SessionState state) { // reset the grade parameters state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT); state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); state.removeAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); // remove all GRADE_SUBMISSION_GRADE states including possible grade overrides // looking like GRADE_SUBMISSION_GRADE_[id of user] Iterator<String> _attribute_names = state.getAttributeNames().iterator(); while (_attribute_names.hasNext()) { String _attribute_name = _attribute_names.next(); if (_attribute_name.startsWith(GRADE_SUBMISSION_GRADE)) { state.removeAttribute(_attribute_name); } } state.removeAttribute(GRADE_SUBMISSION_SUBMISSION_ID); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); state.removeAttribute(GRADE_SUBMISSION_DONE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); resetAllowResubmitParams(state); } /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the reorder process */ public void doCancel_reorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_reorder /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { doCancel_grade_submission(data); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission public void doSave_grade_submission_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); saveReviewGradeForm(data, state, "save"); } public void doSave_toggle_remove_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null){ String peerAssessor = (String) state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID); ParameterParser params = data.getParameters(); String submissionRef = params.getString("submissionId"); String submissionId = null; if(submissionRef != null){ int i = submissionRef.lastIndexOf(Entity.SEPARATOR); if (i == -1){ submissionId = submissionRef; }else{ submissionId = submissionRef.substring(i + 1); } } if(submissionId != null){ //call the DB to make sure this user can edit this assessment, otherwise it wouldn't exist PeerAssessmentItem item = assignmentPeerAssessmentService.getPeerAssessmentItem(submissionId, peerAssessor); if(item != null){ item.setRemoved(!item.isRemoved()); assignmentPeerAssessmentService.savePeerAssessmentItem(item); if(item.getScore() != null){ //item was part of the calculation, re-calculate boolean saved = assignmentPeerAssessmentService.updateScore(submissionId); if(saved){ //we need to make sure the GB is updated correctly (or removed) String assignmentId = item.getAssignmentId(); if(assignmentId != null){ Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if(a != null){ String aReference = a.getReference(); String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, submissionId, "update", -1); } } } } state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); state.setAttribute(PEER_ASSESSMENT_REMOVED_STATUS, item.isRemoved()); //update session state: List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state.getAttribute(PEER_ASSESSMENT_ITEMS); if(peerAssessmentItems != null){ for(int i = 0; i < peerAssessmentItems.size(); i++) { PeerAssessmentItem sItem = peerAssessmentItems.get(i); if(sItem.getSubmissionId().equals(item.getSubmissionId()) && sItem.getAssessorUserId().equals(item.getAssessorUserId())){ //found it, just update it peerAssessmentItems.set(i, item); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); break; } } } } } } } /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); String assignmentId = (String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID); // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = editSubmission(sId, "grade_submission_option", state); if (sEdit != null) { //This logic could be done in one line, but would be harder to read, so break it out to make it easier to follow boolean gradeChanged = false; if((sEdit.getGrade() == null || "".equals(sEdit.getGrade().trim())) && (grade == null || "".equals(grade.trim()))){ //both are null, keep grade changed = false }else if((sEdit.getGrade() == null || "".equals(sEdit.getGrade().trim()) || (grade == null || "".equals(grade.trim())))){ //one is null the other isn't gradeChanged = true; }else if(!grade.trim().equals(sEdit.getGrade().trim())){ gradeChanged = true; } Assignment a = sEdit.getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } if ("return".equals(gradeOption) || "release".equals(gradeOption)) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); if(gradeChanged){ sEdit.setGradedBy(null); } sEdit.setGradeReleased(false); } else { sEdit.setGrade(grade); if (grade.length() != 0) { sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } } else { sEdit.setGraded(false); if(gradeChanged){ sEdit.setGradedBy(null); } } } // iterate through submitters and look for grade overrides... if (withGrade && a.isGroup()) { User[] _users = sEdit.getSubmitters(); for (int i=0; _users != null && i < _users.length; i++) { String _gr = (String)state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); sEdit.addGradeForUser(_users[i].getId(), _gr); } } if ("release".equals(gradeOption)) { sEdit.setGradeReleased(true); sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if ("return".equals(gradeOption)) { sEdit.setGradeReleased(true); sEdit.setGraded(true); if(gradeChanged){ sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } else if ("save".equals(gradeOption)) { sEdit.setGradeReleased(false); sEdit.setReturned(false); sEdit.setTimeReturned(null); } ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } else { // clean resubmission property pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } // the instructor comment String feedbackCommentString = StringUtils .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } else { sEdit.setFeedbackComment(""); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); // save a timestamp for this grading process sEdit.getPropertiesEdit().addProperty(AssignmentConstants.PROP_LAST_GRADED_DATE, TimeService.newTime().toStringLocalFull()); AssignmentService.commitEdit(sEdit); // update grades in gradebook String aReference = a.getReference(); String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (!"remove".equals(gradeOption)) { // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1); } else { //remove grade from gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove", -1); } } if (state.getAttribute(STATE_MESSAGE) == null) { // put submission information into state putSubmissionInfoIntoState(state, assignmentId, sId); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); } else { state.removeAttribute(GRADE_SUBMISSION_DONE); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { // save submission post_save_submission(data, false); } // doSave_submission /** * set the resubmission related properties in AssignmentSubmission object * @param a * @param edit */ private void setResubmissionProperties(Assignment a, AssignmentSubmissionEdit edit) { // get the assignment setting for resubmitting ResourceProperties assignmentProperties = a.getProperties(); String assignmentAllowResubmitNumber = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (assignmentAllowResubmitNumber != null) { edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, assignmentAllowResubmitNumber); String assignmentAllowResubmitCloseDate = assignmentProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // if assignment's setting of resubmit close time is null, use assignment close time as the close time for resubmit edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, assignmentAllowResubmitCloseDate != null?assignmentAllowResubmitCloseDate:String.valueOf(a.getCloseTime().getTime())); } } /** * Action is to post the submission */ public void doPost_submission(RunData data) { // post submission post_save_submission(data, true); } // doPost_submission /** * Inner method used for post or save submission * @param data * @param post */ private void post_save_submission(RunData data, boolean post) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = getAssignment(aReference, "post_save_submission", state); if (a != null && AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // check formatting error whether the student is posting or saving String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); User submitter = null; String studentId = params.get("submit_on_behalf_of"); if (studentId != null && !studentId.equals("-1")) { // SAK-23817: return to the Assignments List by Student state.setAttribute(FROM_VIEW, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); try { u = UserDirectoryService.getUser(studentId); submitter = u; } catch (UserNotDefinedException ex1) { M_log.warn("Unable to find user with ID [" + studentId + "]"); submitter = null; } } String group_id = null; String original_group_id = null; if (a.isGroup()) { original_group_id = (params.getString("originalGroup") == null || params.getString("originalGroup").trim().length() == 0) ? null: params.getString("originalGroup"); ; if (original_group_id != null) { state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, original_group_id); } else { if (state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP) != null) original_group_id = (String)state.getAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP); else state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, null); } String[] groupChoice = params.getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { if (groupChoice.length > 1) { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } else { group_id = groupChoice[0]; state.setAttribute(VIEW_SUBMISSION_GROUP, groupChoice[0]); } } else { // get the submitted group id if (state.getAttribute(VIEW_SUBMISSION_GROUP) != null) { group_id = (String)state.getAttribute(VIEW_SUBMISSION_GROUP); } else { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } } String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // SAK-26322 --bbailla2 List nonInlineAttachments = getNonInlineAttachments(state, a); int typeOfSubmission = a.getContent().getTypeOfSubmission(); if (typeOfSubmission == Assignment.SINGLE_ATTACHMENT_SUBMISSION && nonInlineAttachments.size() >1) { //Single uploaded file and there are multiple attachments adjustAttachmentsToSingleUpload(data, state, a, nonInlineAttachments); } // clear text if submission type does not allow it if (typeOfSubmission == Assignment.SINGLE_ATTACHMENT_SUBMISSION || typeOfSubmission == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION) { text = null; } // get attachment input and generate alert message according to assignment submission type checkSubmissionTextAttachmentInput(data, state, a, text); } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { AssignmentSubmission submission = null; if (a.isGroup()) { submission = getSubmission(a.getReference(), (original_group_id == null ? group_id: original_group_id), "post_save_submission", state); } else { submission = getSubmission(a.getReference(), u, "post_save_submission", state); } if (submission != null) { // the submission already exists, change the text and honor pledge value, post it AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "post_save_submission", state); if (sEdit != null) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); /** * SAK-22150 We will need to know later if there was a previous submission time. DH */ boolean isPreviousSubmissionTime = true; if (sEdit.getTimeSubmitted() == null || "".equals(sEdit.getTimeSubmitted())) { isPreviousSubmissionTime = false; } if (a.isGroup()) { if (original_group_id != null && !original_group_id.equals(group_id)) { // changing group id so we need to check if a submission has already been made for that group AssignmentSubmission submissioncheck = getSubmission(a.getReference(), group_id, "post_save_submission",state); if (submissioncheck != null) { addAlert(state, rb.getString("group.already.submitted")); M_log.warn(this + ":post_save_submission " + group_id + " has already submitted " + submissioncheck.getId() + "!"); } } sEdit.setSubmitterId(group_id); } sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(post); // decrease the allow_resubmit_number, if this submission has been submitted. if (sEdit.getSubmitted() && isPreviousSubmissionTime && sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number, if the number is not -1 (not unlimited) if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } } // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. Time now = TimeService.newTime(); // need this to handle feedback and comments, which we have to do even if ungraded // get the previous graded date String prevGradedDate = sEdit.getProperties().getProperty(AssignmentConstants.PROP_LAST_GRADED_DATE); if (prevGradedDate == null) { // since this is a newly added property, if no value is set, get the default as the submission last modified date prevGradedDate = sEdit.getTimeLastModified().toStringLocalFull(); sEdit.getProperties().addProperty(AssignmentConstants.PROP_LAST_GRADED_DATE, prevGradedDate); } if (sEdit.getGraded() && sEdit.getReturned() && sEdit.getGradeReleased()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtils.split(previousGrades, " "); String newGrades = ""; NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(decSeparator) == -1) { // show the grade with decimal point grade = grade.concat(decSeparator).concat("0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } if (StringUtils.trimToNull(sEdit.getGradeDisplay()) != null) { previousGrades = "<h4>" + prevGradedDate + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getGradeDisplay() + "</div>" +previousGrades; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); } // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGradedBy(null); sEdit.setGrade(""); sEdit.setGradeReleased(false); } // following involves content, not grading, so always do on resubmit, not just if graded // clean the ContentReview attributes sEdit.setReviewIconUrl(null); sEdit.setReviewScore(0); // default to be 0? sEdit.setReviewStatus(null); if (StringUtils.trimToNull(sEdit.getFeedbackFormattedText()) != null) { // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = "<h4>" + prevGradedDate + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackText() + "</div>" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); } if (StringUtils.trimToNull(sEdit.getFeedbackComment()) != null) { // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = "<h4>" + prevGradedDate + "</h4>" + "<div style=\"margin:0;padding:0\">" + sEdit.getFeedbackComment() + "</div>" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); } // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); StringBuffer attBuffer = new StringBuffer(); for (int k = 0; k<feedbackAttachments.size();k++) { // use comma as separator for attachments attBuffer.append(((Reference) feedbackAttachments.get(k)).getReference() + ","); } feedbackAttachmentHistory = attBuffer.toString() + feedbackAttachmentHistory; sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); sEdit.setAssignment(a); // SAK-26322 --bbailla2 List nonInlineAttachments = getNonInlineAttachments(state, a); if (nonInlineAttachments != null && a.getContent().getTypeOfSubmission() == 5) { //clear out inline attachments for content-review //filter the attachment sin the state to exclude inline attachments (nonInlineAttachments, is a subset of what's currently in the state) state.setAttribute(ATTACHMENTS, nonInlineAttachments); } // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { if (a.getContent().getTypeOfSubmission() == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION) { //inline only doesn't accept attachments sEdit.clearSubmittedAttachments(); } else { //Post the attachments before clearing so that we don't sumbit duplicate attachments //Check if we need to post the attachments if (a.getContent().getAllowReviewService()) { if (!attachments.isEmpty()) { sEdit.postAttachment(attachments); } } // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment if (submitter != null) { sPropertiesEdit.addProperty(AssignmentSubmission.SUBMITTER_USER_ID, submitter.getId()); state.setAttribute(STATE_SUBMITTER, u.getId()); } else { sPropertiesEdit.removeProperty(AssignmentSubmission.SUBMITTER_USER_ID); } Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } } // SAK-26322 - add inline as an attachment for the content review service --bbailla2 if (a.getContent().getAllowReviewService() && !isHtmlEmpty(text)) { prepareInlineForContentReview(text, sEdit, state, submitter); } if (submitter != null) { sPropertiesEdit.addProperty(AssignmentSubmission.SUBMITTER_USER_ID, submitter.getId()); state.setAttribute(STATE_SUBMITTER, u.getId()); } else { sPropertiesEdit.removeProperty(AssignmentSubmission.SUBMITTER_USER_ID); } // SAK-17606 StringBuilder log = new StringBuilder(); log.append(new java.util.Date()); log.append(" "); boolean anonymousGrading = Boolean.parseBoolean(a.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); if(!anonymousGrading){ log.append(u.getDisplayName()); log.append(" ("); log.append(u.getEid()); log.append(") "); } log.append(post ? "submitted" : "saved draft"); sEdit.addSubmissionLogEntry(log.toString()); AssignmentService.commitEdit(sEdit); } } else { // new submission try { // if assignment is a group submission... send group id and not user id M_log.debug(this + " NEW SUBMISSION IS GROUP: " + a.isGroup() + " GROUP:" + group_id); AssignmentSubmissionEdit edit = a.isGroup() ? AssignmentService.addSubmission(contextString, assignmentId, group_id): AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId()); if (edit != null) { edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(post); edit.setAssignment(a); ResourcePropertiesEdit sPropertiesEdit = edit.getPropertiesEdit(); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); // SAK-26322 - add inline as an attachment for the content review service --bbailla2 if (a.getContent().getAllowReviewService() && !isHtmlEmpty(text)) { prepareInlineForContentReview(text, edit, state, submitter); } if (attachments != null) { // add each attachment if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService()) edit.postAttachment(attachments); // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } // set the resubmission properties setResubmissionProperties(a, edit); if (submitter != null) { sPropertiesEdit.addProperty(AssignmentSubmission.SUBMITTER_USER_ID, submitter.getId()); state.setAttribute(STATE_SUBMITTER, u.getId()); } else { sPropertiesEdit.removeProperty(AssignmentSubmission.SUBMITTER_USER_ID); } // SAK-17606 StringBuilder log = new StringBuilder(); log.append(new java.util.Date()); log.append(" "); boolean anonymousGrading = Boolean.parseBoolean(a.getProperties().getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); if(!anonymousGrading){ log.append(u.getDisplayName()); log.append(" ("); log.append(u.getEid()); log.append(") "); } log.append(post ? "submitted" : "saved draft"); edit.addSubmissionLogEntry(log.toString()); AssignmentService.commitEdit(edit); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); M_log.warn(this + ":post_save_submission " + e.getMessage()); } } // if-else } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); if (null != lrss) { Event event = m_eventTrackingService.newEvent(AssignmentConstants.EVENT_SUBMIT_ASSIGNMENT_SUBMISSION, assignmentId, false); lrss.registerStatement( getStatementForSubmitAssignment(lrss.getEventActor(event), event, ServerConfigurationService.getAccessUrl(), a.getTitle()), "sakai.assignment"); } } // if } // post_save_submission /** * Takes the inline submission, prepares it as an attachment to the submission and queues the attachment with the content review service * @author bbailla2 */ private void prepareInlineForContentReview(String text, AssignmentSubmissionEdit edit, SessionState state, User submitter) { //We will be replacing the inline submission's attachment //firstly, disconnect any existing attachments with AssignmentSubmission.PROP_INLINE_SUBMISSION set List attachments = edit.getSubmittedAttachments(); List toRemove = new ArrayList(); Iterator itAttachments = attachments.iterator(); while (itAttachments.hasNext()) { Reference attachment = (Reference) itAttachments.next(); ResourceProperties attachProps = attachment.getProperties(); if ("true".equals(attachProps.getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { toRemove.add(attachment); } } Iterator itToRemove = toRemove.iterator(); while (itToRemove.hasNext()) { Reference attachment = (Reference) itToRemove.next(); edit.removeSubmittedAttachment(attachment); } //now prepare the new resource //provide lots of info for forensics - filename=InlineSubmission_siteId_assignmentId_userDisplayId_(on ehalf of)_date.html String currentDisplayName = UserDirectoryService.getCurrentUser().getDisplayId(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); //avoid semicolons in filenames, right? dform.applyPattern("yyyy-MM-dd_HH-mm-ss"); StringBuilder sb_resourceId = new StringBuilder("InlineSub_"); String u = "_"; sb_resourceId.append(edit.getAssignmentId()).append(u).append(currentDisplayName).append(u); if (submitter != null) { sb_resourceId.append("for_").append(submitter.getDisplayId()).append(u); } sb_resourceId.append(dform.format(new Date())); String fileExtension = ".html"; /* * TODO: add and use a method in ContentHostingService to get the length of the ID of an attachment collection * Attachment collections currently look like this: * /attachment/dc126c4a-a48f-42a6-bda0-cf7b9c4c5c16/Assignments/eac7212a-9597-4b7d-b958-89e1c47cdfa7/ * See BaseContentService.addAttachmentResource for more information */ String toolName = "Assignments"; // TODO: add and use a method in IdManager to get the maxUuidLength int maxUuidLength = 36; int esl = Entity.SEPARATOR.length(); int attachmentCollectionLength = ContentHostingService.ATTACHMENTS_COLLECTION.length() + siteId.length() + esl + toolName.length() + esl + maxUuidLength + esl; int maxChars = ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH - attachmentCollectionLength - fileExtension.length() - 1; String resourceId = StringUtils.substring(sb_resourceId.toString(), 0, maxChars) + fileExtension; ResourcePropertiesEdit inlineProps = m_contentHostingService.newResourceProperties(); inlineProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, rb.getString("submission.inline")); inlineProps.addProperty(ResourceProperties.PROP_DESCRIPTION, resourceId); inlineProps.addProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION, "true"); //create a byte array input stream //text is almost in html format, but it's missing the start and ending tags //(Is this always the case? Does the content review service care?) String toHtml = "<html><head></head><body>" + text + "</body></html>"; InputStream contentStream = new ByteArrayInputStream(toHtml.getBytes()); String contentType = "text/html"; //duplicating code from doAttachUpload. TODO: Consider refactoring into a method SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { if(function.equals(m_contentHostingService.AUTH_RESOURCE_ADD)){ return SecurityAdvice.ALLOWED; }else if(function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_ANY)){ return SecurityAdvice.ALLOWED; }else{ return SecurityAdvice.PASS; } } }; try { m_securityService.pushAdvisor(sa); ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, toolName, contentType, contentStream, inlineProps); // TODO: need to put this file in some kind of list to improve performance with web service impls of content-review service --bbailla2 String contentUserId = UserDirectoryService.getCurrentUser().getId(); if(submitter != null){ //this is a submission on behalf of a student, so grab that student's id instead contentUserId = submitter.getId(); } contentReviewService.queueContent(contentUserId, siteId, edit.getAssignment().getReference(), Arrays.asList(attachment)); try { Reference ref = EntityManager.newReference(m_contentHostingService.getReference(attachment.getId())); edit.addSubmittedAttachment(ref); } catch (Exception e) { M_log.warn(this + "prepareInlineForContentReview() cannot find reference for " + attachment.getId() + e.getMessage()); } } catch (PermissionException e) { addAlert(state, rb.getString("notpermis4")); } catch (RuntimeException e) { if (m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) { addAlert(state, rb.getFormattedMessage("alert.toolong", new String[]{resourceId})); } } catch (ServerOverloadException e) { M_log.debug(this + ".prepareInlineForContentReview() ***** DISK IO Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.diskio")); } catch (Exception ignore) { M_log.debug(this + ".prepareInlineForContentReview() ***** Unknown Exception ***** " + ignore.getMessage()); addAlert(state, rb.getString("failed")); } finally { m_securityService.popAdvisor(sa); } } /** * Used when students are selecting from a list of previous attachments for their single uploaded file * @author bbailla2 */ private void adjustAttachmentsToSingleUpload(RunData data, SessionState state, Assignment a, List nonInlineAttachments) { if (a == null || a.getContent() == null || a.getContent().getTypeOfSubmission() != 5) { throw new IllegalArgumentException("adjustAttachmentsToSingleUpload called, but the assignment type is not Single Uploaded File"); } if (nonInlineAttachments == null) { throw new IllegalArgumentException("adjustAttachmentsToSingleUpload called, but nonInlineAttachments is null"); } String selection = data.getParameters().get("attachmentSelection"); if ("newAttachment".equals(selection)) { Reference attachment = (Reference) state.getAttribute("newSingleUploadedFile"); if (attachment != null) { List attachments = EntityManager.newReferenceList(); attachments.add(attachment); state.setAttribute(ATTACHMENTS, attachments); state.removeAttribute("newSingleUploadedFile"); state.removeAttribute(VIEW_SUBMISSION_TEXT); } // ^ if attachment is null, we don't care - checkSubmissionTextAttachmentInput() handles that for us } else { //they selected a previous attachment. selection represents an index in the nonInlineAttachments list boolean error = false; int index = -1; try { //get the selected attachment index = Integer.parseInt(selection); if (nonInlineAttachments.size() <= index) { error = true; } } catch (NumberFormatException nfe) { error = true; } if (error) { M_log.warn("adjustAttachmentsToSingleUpload() - couldn't parse the selected index as an integer, or the selected index wasn't in the range of attachment indices"); //checkSubmissionTextAttachmentInput() handles the alert message for us } else { Reference attachment = (Reference) nonInlineAttachments.get(index); //remove all the attachments from the state and add the selected one back for resubmission List attachments = (List) state.getAttribute(ATTACHMENTS); attachments.clear(); attachments.add(attachment); } } } private void checkSubmissionTextAttachmentInput(RunData data, SessionState state, Assignment a, String text) { // SAK-26329 - determine if the submission has text --bbailla2 boolean textIsEmpty = isHtmlEmpty(text); if (a != null) { // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION) { // for the inline only submission if (textIsEmpty) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION) { // for the attachment only submission List v = getNonInlineAttachments(state, a); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == Assignment.SINGLE_ATTACHMENT_SUBMISSION) { // for the single uploaded file only submission List v = getNonInlineAttachments(state, a); if ((v == null) || (v.size() != 1)) { addAlert(state, rb.getString("youmust8")); } } else { // for the inline and attachment submission / other submission types // There must be at least one thing submitted: inline text or at least one attachment List v = getNonInlineAttachments(state, a); if (textIsEmpty && (v == null || v.size() == 0)) { addAlert(state, rb.getString("youmust2")); } } } } /** * When using content review, inline text gets turned into an attachment. This method returns all the attachments that do not represent inline text * @author bbailla2 */ private List getNonInlineAttachments(SessionState state, Assignment a) { List attachments = (List) state.getAttribute(ATTACHMENTS); List nonInlineAttachments = new ArrayList(); nonInlineAttachments.addAll(attachments); if (a.getContent().getAllowReviewService()) { Iterator itAttachments = attachments.iterator(); while (itAttachments.hasNext()) { Object next = itAttachments.next(); if (next instanceof Reference) { Reference attachment = (Reference) next; if ("true".equals(attachment.getProperties().getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { nonInlineAttachments.remove(attachment); } } } } return nonInlineAttachments; } // SAK-26329 /** * Parses html and determines whether it contains printable characters. * @author bbailla2 */ private boolean isHtmlEmpty(String html) { return html == null ? true : FormattedText.stripHtmlFromText(html, false, true).isEmpty(); } /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // SAK-23817 if the instructor submitted on behalf of the student, go back to Assignment List by Student String fromView = (String) state.getAttribute(FROM_VIEW); if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } else { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { initializeAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot_addAssignment")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doNew_Assignment /** * Action is to show the reorder assignment screen */ public void doReorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // this insures the default order is loaded into the reordering tool state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING))) { state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot19")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doReorder /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentRef = params.getString("assignmentId"); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); String order = params.getString(NEW_ASSIGNMENT_ORDER); state.setAttribute(NEW_ASSIGNMENT_ORDER, order); String groupAssignment = params.getString(NEW_ASSIGNMENT_GROUP_SUBMIT); state.setAttribute( NEW_ASSIGNMENT_GROUP_SUBMIT, (groupAssignment == null ? "0": "1")); if (title == null || title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } else if (sameAssignmentTitleInContext(assignmentRef, title, (String) state.getAttribute(STATE_CONTEXT_STRING))) { // assignment title already exist addAlert(state, rb.getFormattedMessage("same_assignment_title", new Object[]{title})); } // open time Time openTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, "newassig.opedat"); // visible time if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { if (params.get("allowVisibleDateToggle") == null) { state.setAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE, true); } else { Time visibleTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN, "newassig.visdat"); } } // due time Time dueTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, "gen.duedat"); // show alert message when due date is in past. Remove it after user confirms the choice. if (dueTime != null && dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null && validify) { addAlert(state, rb.getString("assig4")); } if (openTime != null && dueTime != null && !dueTime.after(openTime)) { addAlert(state, rb.getString("assig3")); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true)); // close time Time closeTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, "date.closedate"); if (openTime != null && closeTime != null && !closeTime.after(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (dueTime != null && closeTime != null && closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); Integer submissionType = Integer.valueOf(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE)); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, submissionType); // Skip category if it was never set. Long catInt = Long.valueOf(-1); if(params.getString(NEW_ASSIGNMENT_CATEGORY) != null) catInt = Long.valueOf(params.getString(NEW_ASSIGNMENT_CATEGORY)); state.setAttribute(NEW_ASSIGNMENT_CATEGORY, catInt); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(gradeType)); } //Peer Assessment boolean peerAssessment = false; String r = params.getString(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT); String b; if (r == null){ b = Boolean.FALSE.toString(); }else{ b = Boolean.TRUE.toString(); peerAssessment = true; } state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, b); if(peerAssessment){ //not allowed for group assignments: if("1".equals(groupAssignment)){ addAlert(state, rb.getString("peerassessment.invliadGroupAssignment")); } //do not allow non-electronic assignments if(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION == submissionType){ addAlert(state, rb.getString("peerassessment.invliadSubmissionTypeAssignment")); } if (gradeType != Assignment.SCORE_GRADE_TYPE){ addAlert(state, rb.getString("peerassessment.invliadGradeTypeAssignment")); } Time peerPeriodTime = putTimeInputInState(params, state, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN, "newassig.opedat"); GregorianCalendar peerPeriodMinTimeCal = new GregorianCalendar(); peerPeriodMinTimeCal.setTimeInMillis(closeTime.getTime()); peerPeriodMinTimeCal.add(GregorianCalendar.MINUTE, 10); GregorianCalendar peerPeriodTimeCal = new GregorianCalendar(); peerPeriodTimeCal.setTimeInMillis(peerPeriodTime.getTime()); //peer assessment must complete at a minimum of 10 mins after close time if(peerPeriodTimeCal.before(peerPeriodMinTimeCal)){ addAlert(state, rb.getString("peerassessment.invliadPeriodTime")); } } r = params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL, b); r = params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS, b); if(peerAssessment){ if(params.get(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS) != null && !"".equals(params.get(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS))){ try{ int peerAssessmentNumOfReviews = Integer.parseInt(params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)); if(peerAssessmentNumOfReviews > 0){ state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, Integer.valueOf(peerAssessmentNumOfReviews)); }else{ addAlert(state, rb.getString("peerassessment.invalidNumReview")); } }catch(Exception e){ addAlert(state, rb.getString("peerassessment.invalidNumReview")); } }else{ addAlert(state, rb.getString("peerassessment.specifyNumReview")); } } String peerAssessmentInstructions = processFormattedTextFromBrowser(state, params.getString(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS), true); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS, peerAssessmentInstructions); //REVIEW SERVICE r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); // set whether we use the review service or not if (r == null) b = Boolean.FALSE.toString(); else { b = Boolean.TRUE.toString(); if (state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE).equals(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)) { //can't use content-review with non-electronic submissions addAlert(state, rb.getFormattedMessage("review.switch.ne.1", contentReviewService.getServiceName())); } } state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b); //set whether students can view the review service results r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b); //set submit options r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); if(r == null || (!NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD.equals(r) && !NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION.equals(r))) r = NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE; state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO, r); //set originality report options r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); if(r == null || !NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE.equals(r)) r = NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY; state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO, r); //set check repository options: r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN, b); r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET, b); r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB, b); r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION, b); //exclude bibliographic materials: r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC, b); //exclude quoted materials: r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED, b); //exclude small matches r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES, b); //exclude type: //only options are 0=none, 1=words, 2=percentages r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE); if(!"0".equals(r) && !"1".equals(r) && !"2".equals(r)){ //this really shouldn't ever happen (unless someone's messing with the parameters) r = "0"; } state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE, r); //exclude value if(!"0".equals(r)){ r = params.getString(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE); try{ int rInt = Integer.parseInt(r); if(rInt < 0 || rInt > 100){ addAlert(state, rb.getString("review.exclude.matches.value_error")); } }catch (Exception e) { addAlert(state, rb.getString("review.exclude.matches.value_error")); } state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE, r); }else{ state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE, "1"); } // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null || state.getAttribute(ADDITIONAL_CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } if (params.getString(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE) != null && params.getString(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, params.getString(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtils.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments == null || attachments.isEmpty()) { // read from vm file String[] attachmentIds = data.getParameters().getStrings("attachments"); if (attachmentIds != null && attachmentIds.length != 0) { attachments = new ArrayList(); for (int i= 0; i<attachmentIds.length;i++) { attachments.add(EntityManager.newReference(attachmentIds[i])); } } } state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); if (validify) { if ((description == null) || (description.length() == 0) || ("<br/>".equals(description)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if ("groups".equals(range)) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } // check groups for duplicate members here if ("1".equals(params.getString(NEW_ASSIGNMENT_GROUP_SUBMIT))) { Collection<String> _dupUsers = usersInMultipleGroups(state, "groups".equals(range),("groups".equals(range) ? data.getParameters().getStrings("selectedGroups") : null), false, null); if (_dupUsers.size() > 0) { StringBuilder _sb = new StringBuilder(rb.getString("group.user.multiple.warning") + " "); Iterator<String> _it = _dupUsers.iterator(); if (_it.hasNext()) _sb.append(_it.next()); while (_it.hasNext()) _sb.append(", " + _it.next()); addAlert(state, _sb.toString()); M_log.warn(this + ":post_save_assignment at least one user in multiple groups."); } } // allow resubmission numbers if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params Time resubmitCloseTime = readAllowResubmitParams(params, state, null); if (resubmitCloseTime != null) { // check the date is valid if (openTime != null && ! resubmitCloseTime.after(openTime)) { addAlert(state, rb.getString("acesubdea6")); } } } else if (!Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION).equals(state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE))) { /* * SAK-26640: If the instructor switches to non-electronic by mistake, the resubmissions settings should persist so they can be easily retrieved. * So we only reset resubmit params for electronic assignments. */ resetAllowResubmitParams(state); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } // release grade notification option String releaseGradeOption = params.getString(ASSIGNMENT_RELEASEGRADE_NOTIFICATION); if (releaseGradeOption != null) { state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, releaseGradeOption); } // release resubmission notification option String releaseResubmissionOption = params.getString(ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION); if (releaseResubmissionOption != null){ state.setAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, releaseResubmissionOption); } // read inputs for supplement items setNewAssignmentParametersSupplementItems(validify, state, params); if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of point grade assignment, user must specify maximum grade point addAlert(state, rb.getString("plespethe3")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } } } // setNewAssignmentParameters /** * check to see whether there is already an assignment with the same title in the site * @param assignmentRef * @param title * @param contextString * @return */ private boolean sameAssignmentTitleInContext(String assignmentRef, String title, String contextString) { boolean rv = false; // in the student list view of assignments Iterator assignments = AssignmentService.getAssignmentsForContext(contextString); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); if (assignmentRef == null || !assignmentRef.equals(a.getReference())) { // don't do self-compare String aTitle = a.getTitle(); if (aTitle != null && aTitle.length() > 0 && title.equals(aTitle)) { //further check whether the assignment is marked as deleted or not String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted != null && !Boolean.TRUE.toString().equalsIgnoreCase(deleted)) { rv = true; } } } } return rv; } /** * read inputs for supplement items * @param validify * @param state * @param params */ private void setNewAssignmentParametersSupplementItems(boolean validify, SessionState state, ParameterParser params) { /********************* MODEL ANSWER ITEM *********************/ String modelAnswer_to_delete = StringUtils.trimToNull(params.getString("modelanswer_to_delete")); if (modelAnswer_to_delete != null) { state.setAttribute(MODELANSWER_TO_DELETE, modelAnswer_to_delete); } String modelAnswer_text = StringUtils.trimToNull(params.getString("modelanswer_text")); if (modelAnswer_text != null) { state.setAttribute(MODELANSWER_TEXT, modelAnswer_text); } String modelAnswer_showto = StringUtils.trimToNull(params.getString("modelanswer_showto")); if (modelAnswer_showto != null) { state.setAttribute(MODELANSWER_SHOWTO, modelAnswer_showto); } if (modelAnswer_text != null || !"0".equals(modelAnswer_showto) || state.getAttribute(MODELANSWER_ATTACHMENTS) != null) { // there is Model Answer input state.setAttribute(MODELANSWER, Boolean.TRUE); if (validify && !"true".equalsIgnoreCase(modelAnswer_to_delete)) { // show alert when there is no model answer input if (modelAnswer_text == null) { addAlert(state, rb.getString("modelAnswer.alert.modelAnswer")); } // show alert when user didn't select show-to option if ("0".equals(modelAnswer_showto)) { addAlert(state, rb.getString("modelAnswer.alert.showto")); } } } else { state.removeAttribute(MODELANSWER); } /**************** NOTE ITEM ********************/ String note_to_delete = StringUtils.trimToNull(params.getString("note_to_delete")); if (note_to_delete != null) { state.setAttribute(NOTE_TO_DELETE, note_to_delete); } String note_text = StringUtils.trimToNull(params.getString("note_text")); if (note_text != null) { state.setAttribute(NOTE_TEXT, note_text); } String note_to = StringUtils.trimToNull(params.getString("note_to")); if (note_to != null) { state.setAttribute(NOTE_SHAREWITH, note_to); } if (note_text != null || !"0".equals(note_to)) { // there is Note Item input state.setAttribute(NOTE, Boolean.TRUE); if (validify && !"true".equalsIgnoreCase(note_to_delete)) { // show alert when there is no note text if (note_text == null) { addAlert(state, rb.getString("note.alert.text")); } // show alert when there is no share option if ("0".equals(note_to)) { addAlert(state, rb.getString("note.alert.to")); } } } else { state.removeAttribute(NOTE); } /****************** ALL PURPOSE ITEM **********************/ String allPurpose_to_delete = StringUtils.trimToNull(params.getString("allPurpose_to_delete")); if ( allPurpose_to_delete != null) { state.setAttribute(ALLPURPOSE_TO_DELETE, allPurpose_to_delete); } String allPurposeTitle = StringUtils.trimToNull(params.getString("allPurposeTitle")); if (allPurposeTitle != null) { state.setAttribute(ALLPURPOSE_TITLE, allPurposeTitle); } String allPurposeText = StringUtils.trimToNull(params.getString("allPurposeText")); if (allPurposeText != null) { state.setAttribute(ALLPURPOSE_TEXT, allPurposeText); } if (StringUtils.trimToNull(params.getString("allPurposeHide")) != null) { state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(params.getString("allPurposeHide"))); } if (StringUtils.trimToNull(params.getString("allPurposeShowFrom")) != null) { state.setAttribute(ALLPURPOSE_SHOW_FROM, Boolean.valueOf(params.getString("allPurposeShowFrom"))); // allpurpose release time putTimeInputInState(params, state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN, "date.allpurpose.releasedate"); } else { state.removeAttribute(ALLPURPOSE_SHOW_FROM); } if (StringUtils.trimToNull(params.getString("allPurposeShowTo")) != null) { state.setAttribute(ALLPURPOSE_SHOW_TO, Boolean.valueOf(params.getString("allPurposeShowTo"))); // allpurpose retract time putTimeInputInState(params, state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN, "date.allpurpose.retractdate"); } else { state.removeAttribute(ALLPURPOSE_SHOW_TO); } String siteId = (String)state.getAttribute(STATE_CONTEXT_STRING); List<String> accessList = new ArrayList<String>(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId)); Set<Role> roles = realm.getRoles(); for(Iterator iRoles = roles.iterator(); iRoles.hasNext();) { // iterator through roles first Role role = (Role) iRoles.next(); if (params.getString("allPurpose_" + role.getId()) != null) { accessList.add(role.getId()); } else { // if the role is not selected, iterate through the users with this role Set userIds = realm.getUsersHasRole(role.getId()); for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); if (params.getString("allPurpose_" + userId) != null) { accessList.add(userId); } } } } } catch (Exception e) { M_log.warn(this + ":setNewAssignmentParameters" + e.toString() + "error finding authzGroup for = " + siteId); } state.setAttribute(ALLPURPOSE_ACCESS, accessList); if (allPurposeTitle != null || allPurposeText != null || (accessList != null && !accessList.isEmpty()) || state.getAttribute(ALLPURPOSE_ATTACHMENTS) != null) { // there is allpupose item input state.setAttribute(ALLPURPOSE, Boolean.TRUE); if (validify && !"true".equalsIgnoreCase(allPurpose_to_delete)) { if (allPurposeTitle == null) { // missing title addAlert(state, rb.getString("allPurpose.alert.title")); } if (allPurposeText == null) { // missing text addAlert(state, rb.getString("allPurpose.alert.text")); } if (accessList == null || accessList.isEmpty()) { // missing access choice addAlert(state, rb.getString("allPurpose.alert.access")); } } } else { state.removeAttribute(ALLPURPOSE); } } /** * read time input and assign it to state attributes * @param params * @param state * @param monthString * @param dayString * @param yearString * @param hourString * @param minString * @param invalidBundleMessage * @return */ Time putTimeInputInState(ParameterParser params, SessionState state, String monthString, String dayString, String yearString, String hourString, String minString, String invalidBundleMessage) { int month = (Integer.valueOf(params.getString(monthString))).intValue(); state.setAttribute(monthString, Integer.valueOf(month)); int day = (Integer.valueOf(params.getString(dayString))).intValue(); state.setAttribute(dayString, Integer.valueOf(day)); int year = (Integer.valueOf(params.getString(yearString))).intValue(); state.setAttribute(yearString, Integer.valueOf(year)); int hour = (Integer.valueOf(params.getString(hourString))).intValue(); state.setAttribute(hourString, Integer.valueOf(hour)); int min = (Integer.valueOf(params.getString(minString))).intValue(); state.setAttribute(minString, Integer.valueOf(min)); // validate date if (!Validator.checkDate(day, month, year)) { addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString(invalidBundleMessage)})); } return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0); } /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); // save user input saveReviewGradeForm(data, state, "read"); } public void doShow_submission_assignment_instruction_review(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true)); // save user input saveReviewGradeForm(data, state, "read"); } /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment post_save_assignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Map.Entry<String, ? extends Object> entry : helperParms.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Map.Entry<String, ? extends Object> entry : helperParms.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Map.Entry<String, ? extends Object> entry : helperParms.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } // doHelp_activity /** * post or save assignment */ private void post_save_assignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && "post".equals(postOrSave); // assignment old title String aOldTitle = null; // assignment old access setting String aOldAccessString = null; // assignment old group setting Collection aOldGroups = null; // assignment old open date setting Time oldOpenTime = null; // assignment old due date setting Time oldDueTime = null; // assignment old visible date setting Time oldVisibleTime = null; // assignment old close date setting Time oldCloseTime = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); // whether this is an editing which changes non-point graded assignment to point graded assignment? boolean bool_change_from_non_point = false; // whether there is a change in the assignment resubmission choice boolean bool_change_resubmit_option = false; if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = editAssignmentContent(assignmentContentId, "post_save_assignment", state, true); bool_change_from_non_point = change_from_non_point(state, assignmentId, assignmentContentId, ac); // Assignment AssignmentEdit a = editAssignment(assignmentId, "post_save_assignment", state, true); bool_change_resubmit_option = change_resubmit_option(state, a); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER); // open time Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // visible time Time visibleTime = null; if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { if (state.getAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE) == null) visibleTime = getTimeFromState(state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } // due time Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); } // sections String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); boolean isGroupSubmit = "1".equals((String)state.getAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT)); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; boolean hideDueDate = "true".equals((String) state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; long category = state.getAttribute(NEW_ASSIGNMENT_CATEGORY) != null ? ((Long) state.getAttribute(NEW_ASSIGNMENT_CATEGORY)).longValue() : -1; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; // SAK-17606 String checkAnonymousGrading = state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING) != null? (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING):""; // SAK-26319 - we no longer clear the resubmit number for non electronic submissions; the instructor may switch to another submission type in the future --bbailla2 //Peer Assessment boolean usePeerAssessment = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT)); Time peerPeriodTime = getTimeFromState(state, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); boolean peerAssessmentAnonEval = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL)); boolean peerAssessmentStudentViewReviews = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS)); int peerAssessmentNumReviews = 0; if(state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS) != null){ peerAssessmentNumReviews = ((Integer) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)).intValue(); } String peerAssessmentInstructions = (String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); //Review Service boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); String submitReviewRepo = (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); String generateOriginalityReport = (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); boolean checkTurnitin = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN)); boolean checkInternet = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET)); boolean checkPublications = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB)); boolean checkInstitution = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION)); //exclude bibliographic materials boolean excludeBibliographic = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC)); //exclude quoted materials boolean excludeQuoted = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED)); //exclude small matches boolean excludeSmallMatches = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES)); //exclude type 0=none, 1=words, 2=percentages int excludeType = 0; int excludeValue = 1; if(excludeSmallMatches){ try{ excludeType = Integer.parseInt((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE)); if(excludeType != 0 && excludeType != 1 && excludeType != 2){ excludeType = 0; } }catch (Exception e) { //Numberformatexception } //exclude value try{ excludeValue = Integer.parseInt((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE)); if(excludeValue < 0 || excludeValue > 100){ excludeValue = 1; } }catch (Exception e) { //Numberformatexception } } // the attachments List attachments = (List) state.getAttribute(NEW_ASSIGNMENT_ATTACHMENT); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new ArrayList(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); if (Assignment.AssignmentAccess.GROUPED.toString().equals(range) && (groupChoice == null || groupChoice.size() == 0)) { // show alert if no group is selected for the group access assignment addAlert(state, rb.getString("java.alert.youchoosegroup")); } else if (groupChoice != null) { for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); Group _aGroup = site.getGroup(groupId); if (_aGroup != null) groups.add(_aGroup); } } } catch (Exception e) { M_log.warn(this + ":post_save_assignment " + e.getMessage()); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); aOldAccessString = a.getAccess().toString(); aOldGroups = a.getGroups(); // old open time oldOpenTime = a.getOpenTime(); // old due time oldDueTime = a.getDueTime(); // old visible time oldVisibleTime = a.getVisibleTime(); // old close time oldCloseTime = a.getCloseTime(); //assume creating the assignment with the content review service will be successful state.setAttribute("contentReviewSuccess", Boolean.TRUE); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, a.getReference(), title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments, submitReviewRepo, generateOriginalityReport, checkTurnitin, checkInternet, checkPublications, checkInstitution, excludeBibliographic, excludeQuoted, excludeType, excludeValue, openTime, dueTime, closeTime, hideDueDate); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); Time resubmitCloseTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); // SAK-17606 editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post, resubmitCloseTime, checkAnonymousGrading); //TODO: ADD_DUE_DATE // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // the release grade notification option if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); } if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) != null){ aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, visibleTime, openTime, dueTime, closeTime, enableCloseDate, section, range, groups, isGroupSubmit, usePeerAssessment,peerPeriodTime, peerAssessmentAnonEval, peerAssessmentStudentViewReviews, peerAssessmentNumReviews, peerAssessmentInstructions); if (post) { // we need to update the submission if (bool_change_from_non_point || bool_change_resubmit_option) { List submissions = AssignmentService.getSubmissions(a); if (submissions != null && submissions.size() >0) { // assignment already exist and with submissions for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next(); AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "post_save_assignment", state); if (sEdit != null) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (bool_change_from_non_point) { // set the grade to be empty for now sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradedBy(null); sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (bool_change_resubmit_option) { String aAllowResubmitNumber = a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (aAllowResubmitNumber == null || aAllowResubmitNumber.length() == 0 || "0".equals(aAllowResubmitNumber)) { sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); sPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } else { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME)); } } AssignmentService.commitEdit(sEdit); } } } } } //if // save supplement item information saveAssignmentSupplementItem(state, params, siteId, a); // set default sorting setDefaultSort(state); if (state.getAttribute(STATE_MESSAGE) == null) { // set the state navigation variables state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); // integrate with other tools only if the assignment is posted if (post) { // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook try { initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range, category); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); M_log.warn(this + ":post_save_assignment " + e.getMessage()); } // log event if there is a title update if (!aOldTitle.equals(title)) { // title changed m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_TITLE, assignmentId, true)); } if (!aOldAccessString.equals(a.getAccess().toString())) { // site-group access setting changed m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_ACCESS, assignmentId, true)); } else { Collection aGroups = a.getGroups(); if (!(aOldGroups == null && aGroups == null) && !(aOldGroups != null && aGroups != null && aGroups.containsAll(aOldGroups) && aOldGroups.containsAll(aGroups))) { //group changed m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_ACCESS, assignmentId, true)); } } if (oldOpenTime != null && !oldOpenTime.equals(a.getOpenTime())) { // open time change m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_OPENDATE, assignmentId, true)); } if (oldDueTime != null && !oldDueTime.equals(a.getDueTime())) { // due time change m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_DUEDATE, assignmentId, true)); } if (oldCloseTime != null && !oldCloseTime.equals(a.getCloseTime())) { // due time change m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_CLOSEDATE, assignmentId, true)); } } } } // if } // if } // post_save_assignment /** * supplement item related information * @param state * @param params * @param siteId * @param a */ private void saveAssignmentSupplementItem(SessionState state, ParameterParser params, String siteId, AssignmentEdit a) { // assignment supplement items String aId = a.getId(); //model answer if (state.getAttribute(MODELANSWER_TO_DELETE) != null && "true".equals((String) state.getAttribute(MODELANSWER_TO_DELETE))) { // to delete the model answer AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId); if (mAnswer != null) { m_assignmentSupplementItemService.cleanAttachment(mAnswer); m_assignmentSupplementItemService.removeModelAnswer(mAnswer); } } else if (state.getAttribute(MODELANSWER_TEXT) != null) { // edit/add model answer AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId); if (mAnswer == null) { mAnswer = m_assignmentSupplementItemService.newModelAnswer(); m_assignmentSupplementItemService.saveModelAnswer(mAnswer); } mAnswer.setAssignmentId(a.getId()); mAnswer.setText((String) state.getAttribute(MODELANSWER_TEXT)); mAnswer.setShowTo(state.getAttribute(MODELANSWER_SHOWTO) != null ? Integer.parseInt((String) state.getAttribute(MODELANSWER_SHOWTO)) : 0); mAnswer.setAttachmentSet(getAssignmentSupplementItemAttachment(state, mAnswer, MODELANSWER_ATTACHMENTS)); m_assignmentSupplementItemService.saveModelAnswer(mAnswer); } // note if (state.getAttribute(NOTE_TO_DELETE) != null && "true".equals((String) state.getAttribute(NOTE_TO_DELETE))) { // to remove note item AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId); if (nNote != null) m_assignmentSupplementItemService.removeNoteItem(nNote); } else if (state.getAttribute(NOTE_TEXT) != null) { // edit/add private note AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId); if (nNote == null) nNote = m_assignmentSupplementItemService.newNoteItem(); nNote.setAssignmentId(a.getId()); nNote.setNote((String) state.getAttribute(NOTE_TEXT)); nNote.setShareWith(state.getAttribute(NOTE_SHAREWITH) != null ? Integer.parseInt((String) state.getAttribute(NOTE_SHAREWITH)) : 0); nNote.setCreatorId(UserDirectoryService.getCurrentUser().getId()); m_assignmentSupplementItemService.saveNoteItem(nNote); } // all purpose if (state.getAttribute(ALLPURPOSE_TO_DELETE) != null && "true".equals((String) state.getAttribute(ALLPURPOSE_TO_DELETE))) { // to remove allPurpose item AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId); if (nAllPurpose != null) { m_assignmentSupplementItemService.cleanAttachment(nAllPurpose); m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose); m_assignmentSupplementItemService.removeAllPurposeItem(nAllPurpose); } } else if (state.getAttribute(ALLPURPOSE_TITLE) != null) { // edit/add private note AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId); if (nAllPurpose == null) { nAllPurpose = m_assignmentSupplementItemService.newAllPurposeItem(); m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose); } nAllPurpose.setAssignmentId(a.getId()); nAllPurpose.setTitle((String) state.getAttribute(ALLPURPOSE_TITLE)); nAllPurpose.setText((String) state.getAttribute(ALLPURPOSE_TEXT)); boolean allPurposeShowFrom = state.getAttribute(ALLPURPOSE_SHOW_FROM) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_FROM)).booleanValue() : false; boolean allPurposeShowTo = state.getAttribute(ALLPURPOSE_SHOW_TO) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_TO)).booleanValue() : false; boolean allPurposeHide = state.getAttribute(ALLPURPOSE_HIDE) != null ? ((Boolean) state.getAttribute(ALLPURPOSE_HIDE)).booleanValue() : false; nAllPurpose.setHide(allPurposeHide); // save the release and retract dates if (allPurposeShowFrom && !allPurposeHide) { // save release date Time releaseTime = getTimeFromState(state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(releaseTime.getTime()); nAllPurpose.setReleaseDate(cal.getTime()); } else { nAllPurpose.setReleaseDate(null); } if (allPurposeShowTo && !allPurposeHide) { // save retract date Time retractTime = getTimeFromState(state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(retractTime.getTime()); nAllPurpose.setRetractDate(cal.getTime()); } else { nAllPurpose.setRetractDate(null); } nAllPurpose.setAttachmentSet(getAssignmentSupplementItemAttachment(state, nAllPurpose, ALLPURPOSE_ATTACHMENTS)); // clean the access list first if (state.getAttribute(ALLPURPOSE_ACCESS) != null) { // get the access settings List<String> accessList = (List<String>) state.getAttribute(ALLPURPOSE_ACCESS); m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose); Set<AssignmentAllPurposeItemAccess> accessSet = new HashSet<AssignmentAllPurposeItemAccess>(); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(siteId)); Set<Role> roles = realm.getRoles(); for(Iterator iRoles = roles.iterator(); iRoles.hasNext();) { // iterator through roles first Role r = (Role) iRoles.next(); if (accessList.contains(r.getId())) { AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess(); access.setAccess(r.getId()); access.setAssignmentAllPurposeItem(nAllPurpose); m_assignmentSupplementItemService.saveAllPurposeItemAccess(access); accessSet.add(access); } else { // if the role is not selected, iterate through the users with this role Set userIds = realm.getUsersHasRole(r.getId()); for(Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); if (accessList.contains(userId)) { AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService.newAllPurposeItemAccess(); access.setAccess(userId); access.setAssignmentAllPurposeItem(nAllPurpose); m_assignmentSupplementItemService.saveAllPurposeItemAccess(access); accessSet.add(access); } } } } } catch (Exception e) { M_log.warn(this + ":post_save_assignment " + e.toString() + "error finding authzGroup for = " + siteId); } nAllPurpose.setAccessSet(accessSet); } m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose); } } private Set<AssignmentSupplementItemAttachment> getAssignmentSupplementItemAttachment(SessionState state, AssignmentSupplementItemWithAttachment mItem, String attachmentString) { Set<AssignmentSupplementItemAttachment> sAttachments = new HashSet<AssignmentSupplementItemAttachment>(); List<String> attIdList = m_assignmentSupplementItemService.getAttachmentListForSupplementItem(mItem); if (state.getAttribute(attachmentString) != null) { List currentAttachments = (List) state.getAttribute(attachmentString); for (Iterator aIterator = currentAttachments.iterator(); aIterator.hasNext();) { Reference attRef = (Reference) aIterator.next(); String attRefId = attRef.getReference(); // if the attachment is not exist, add it into db if (!attIdList.contains(attRefId)) { AssignmentSupplementItemAttachment mAttach = m_assignmentSupplementItemService.newAttachment(); mAttach.setAssignmentSupplementItemWithAttachment(mItem); mAttach.setAttachmentId(attRefId); m_assignmentSupplementItemService.saveAttachment(mAttach); sAttachments.add(mAttach); } } } return sAttachments; } /** * */ private boolean change_from_non_point(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac) { // whether this is an editing which changes non point_grade type to point grade type? if (StringUtils.trimToNull(assignmentId) != null && StringUtils.trimToNull(assignmentContentId) != null) { // editing if (ac.getTypeOfGrade() != Assignment.SCORE_GRADE_TYPE && ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue() == Assignment.SCORE_GRADE_TYPE) { // changing from non-point grade type to point grade type? return true; } } return false; } /** * whether the resubmit option has been changed * @param state * @param a * @return */ private boolean change_resubmit_option(SessionState state, Entity entity) { if (entity != null) { // editing return propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) || propertyValueChanged(state, entity, AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } return false; } /** * whether there is a change between state variable and object's property value * @param state * @param entity * @param propertyName * @return */ private boolean propertyValueChanged(SessionState state, Entity entity, String propertyName) { String o_property_value = entity.getProperties().getProperty(propertyName); String n_property_value = state.getAttribute(propertyName) != null? (String) state.getAttribute(propertyName):null; if (o_property_value == null && n_property_value != null || o_property_value != null && n_property_value == null || o_property_value != null && n_property_value != null && !o_property_value.equals(n_property_value)) { // there is a change return true; } return false; } /** * default sorting */ private void setDefaultSort(SessionState state) { state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } /** * Add submission objects if necessary for non-electronic type of assignment * @param state * @param a */ private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a) { // create submission object for those user who doesn't have one yet for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId); if (submission != null) { submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } } catch (Exception e) { M_log.warn(this + ":addRemoveSubmissionsForNonElectronicAssignment " + e.toString() + "error adding submission for userId = " + userId); } } // remove submission object for those who no longer in the site for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); String submissionRef = null; // TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;) { AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next(); if (userId.equals(submission.getSubmitterId())) { submissionRef = submission.getReference(); } } if (submissionRef != null) { AssignmentSubmissionEdit submissionEdit = editSubmission(submissionRef, "addRemoveSubmissionsForNonElectronicAssignment", state); if (submissionEdit != null) { try { AssignmentService.removeSubmission(submissionEdit); } catch (PermissionException e) { addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{submissionEdit.getReference()})); M_log.warn(this + ":deleteAssignmentObjects " + e.getMessage() + " " + submissionEdit.getReference()); } } } } } private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range, long category) { GradebookExternalAssessmentService gExternal = (GradebookExternalAssessmentService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService"); String context = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean gradebookExists = isGradebookDefined(); // only if the gradebook is defined if (gradebookExists) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); String aReference = a.getReference(); String addUpdateRemoveAssignment = "remove"; if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if integrate with Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && ("groups".equals(range))) { // if grouped assignment is not allowed to add into Gradebook addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = a.getReference(); AssignmentEdit aEdit = editAssignment(a.getReference(), "initINtegrateWithGradebook", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category); } else { if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD; } else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { addUpdateRemoveAssignment = "update"; } if (!"remove".equals(addUpdateRemoveAssignment) && gradeType == 3) { try { integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null, category); // add all existing grades, if any, into Gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", category); // if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook if (StringUtils.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment)) { // if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid); } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); M_log.warn(this + ":initIntegrateWithGradebook " + nE.getMessage()); } } else { integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null, category); } } } else { // need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,gExternal, gradebookUid); } } } private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookExternalAssessmentService gExternal, String gradebookUid) { boolean isExternalAssignmentDefined=gExternal.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); if (isExternalAssignmentDefined) { // iterate through all assignments currently in the site, see if any is associated with this GB entry Iterator i = AssignmentService.getAssignmentsForContext(context); boolean found = false; while (!found && i.hasNext()) { Assignment aI = (Assignment) i.next(); String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference)) { found = true; } } // so if none of the assignment in this site is associated with the entry, remove the entry if (!found) { gExternal.removeExternalAssessment(gradebookUid, associateGradebookAssignment); } } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { // whether the assignment's title or open date has been updated boolean updatedTitle = false; boolean updatedOpenDate = false; boolean updateAccess = false; String openDateAnnounced = StringUtils.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED)); String openDateAnnouncementId = StringUtils.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID)); if (openDateAnnounced != null && openDateAnnouncementId != null) { AnnouncementMessage message = null; try { message = channel.getAnnouncementMessage(openDateAnnouncementId); if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/ { updatedTitle = true; } if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/ { updatedOpenDate = true; } if (!message.getAnnouncementHeader().getAccess().equals(a.getAccess())) { updateAccess = true; } else if (a.getAccess() == Assignment.AssignmentAccess.GROUPED) { Collection<String> assnGroups = a.getGroups(); Collection<String> anncGroups = message.getAnnouncementHeader().getGroups(); if (!assnGroups.equals(anncGroups)) { updateAccess = true; } } } catch (IdUnusedException e) { M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage()); } catch (PermissionException e) { M_log.warn(this + ":integrateWithAnnouncement " + e.getMessage()); } if (updateAccess && message != null) { try { // if the access level has changed in assignment, remove the original announcement channel.removeAnnouncementMessage(message.getId()); } catch (PermissionException e) { M_log.warn(this + ":integrateWithAnnouncement PermissionException for remove message id=" + message.getId() + " for assignment id=" + a.getId() + " " + e.getMessage()); } } } // need to create announcement message if assignment is added or assignment has been updated if (openDateAnnounced == null || updatedTitle || updatedOpenDate || updateAccess) { try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); if (message != null) { AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); // add assignment id into property, to facilitate assignment lookup in Annoucement tool message.getPropertiesEdit().addProperty("assignmentReference", a.getReference()); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getFormattedMessage("assig6", new Object[]{title})); } else { // updated title header.setSubject(/* subject */rb.getFormattedMessage("assig5", new Object[]{title})); } if (updatedOpenDate) { // revised assignment open date message.setBody(/* body */rb.getFormattedMessage("newope", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()})); } else { // assignment open date message.setBody(/* body */rb.getFormattedMessage("opedat", new Object[]{FormattedText.convertPlaintextToFormattedText(title), openTime.toStringLocalFull()})); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new ArrayList(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log M_log.warn(this + ":integrateWithAnnouncement " + exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, m_notificationService.NOTI_NONE); } // commit related properties into Assignment object AssignmentEdit aEdit = editAssignment(a.getReference(), "integrateWithAnnouncement", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } } catch (PermissionException ee) { M_log.warn(this + ":IntegrateWithAnnouncement " + rb.getString("cannotmak")); } } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { // Integrate with Sakai calendar tool Calendar c = (Calendar) state.getAttribute(CALENDAR); integrateWithCalendarTool(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit, c, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); // Integrate with additional calendar tool if deployed. Calendar additionalCal = (Calendar) state.getAttribute(ADDITIONAL_CALENDAR); if (additionalCal != null){ integrateWithCalendarTool(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit, additionalCal, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_ADDITIONAL_CALENDAR_EVENT_ID); } } // Checks to see if due date event in assignment properties exists on the calendar. // If so, remove it and then add a new due date event to the calendar. Then update assignment property // with new event id. private void integrateWithCalendarTool(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit, Calendar c, String dueDateProperty) { if (c == null){ return; } String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(dueDateProperty); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { M_log.warn(this + ":integrateWithCalendarTool The old event has been deleted: event id=" + oldEventId + ". " + c.getClass().getName()); } catch (PermissionException ee) { M_log.warn(this + ":integrateWithCalendarTool You do not have the permission to view the schedule event id= " + oldEventId + ". " + c.getClass().getName()); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found){ removeOldEvent(title, c, e); } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { updateAssignmentWithEventId(state, a, title, dueTime, c, dueDateProperty); } } /** * Add event to calendar and then persist the event id to the assignment properties * @param state * @param a AssignmentEdit * @param title Event title * @param dueTime Assignment due date/time * @param c Calendar * @param dueDateProperty Property name specifies the appropriate calendar */ private void updateAssignmentWithEventId(SessionState state, AssignmentEdit a, String title, Time dueTime, Calendar c, String dueDateProperty) { CalendarEvent e; // commit related properties into Assignment object AssignmentEdit aEdit = editAssignment(a.getReference(), "updateAssignmentWithEventId", state, false); if (aEdit != null) { try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new ArrayList(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); Group _aGroup = site.getGroup(groupRef); if (_aGroup != null) eGroups.add(_aGroup); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("gen.due") + " " + title, /* description */rb.getFormattedMessage("assign_due_event_desc", new Object[]{title, dueTime.toStringLocalFull()}), /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */null /*SAK-27919 do not include assignment attachments.*/); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(dueDateProperty, e.getId()); // edit the calendar object and add an assignment id field addAssignmentIdToCalendar(a, c, e); } // TODO do we care if the event is null? } catch (IdUnusedException ee) { M_log.warn(this + ":updateAssignmentWithEventId " + ee.getMessage()); } catch (PermissionException ee) { M_log.warn(this + ":updateAssignmentWithEventId " + rb.getString("cannotfin1")); } catch (Exception ee) { M_log.warn(this + ":updateAssignmentWithEventId " + ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } } // Persist the assignment id to the calendar private void addAssignmentIdToCalendar(AssignmentEdit a, Calendar c, CalendarEvent e) throws IdUnusedException, PermissionException,InUseException { if (c!= null && e != null && a != null){ CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR); edit.setField(AssignmentConstants.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId()); c.commitEvent(edit); } } // Remove an existing event from the calendar private void removeOldEvent(String title, Calendar c, CalendarEvent e) { // remove the found old event if (c != null && e != null){ try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { M_log.warn(this + ":removeOldEvent " + rb.getFormattedMessage("cannotrem", new Object[]{title})); } catch (InUseException ee) { M_log.warn(this + ":removeOldEvent " + rb.getString("somelsis_calendar")); } catch (IdUnusedException ee) { M_log.warn(this + ":removeOldEvent " + rb.getFormattedMessage("cannotfin6", new Object[]{e.getId()})); } } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time visibleTime, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups, boolean isGroupSubmit, boolean usePeerAssessment, Time peerPeriodTime, boolean peerAssessmentAnonEval, boolean peerAssessmentStudentViewReviews, int peerAssessmentNumReviews, String peerAssessmentInstructions) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setVisibleTime(visibleTime); a.setOpenTime(openTime); a.setDueTime(dueTime); a.setGroup(isGroupSubmit); a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } if (Boolean.TRUE.equals(state.getAttribute("contentReviewSuccess"))) { // post the assignment if appropriate a.setDraft(!post); } else { // setup for content review failed, save as a draft a.setDraft(true); } a.setAllowPeerAssessment(usePeerAssessment); a.setPeerAssessmentPeriod(peerPeriodTime); a.setPeerAssessmentAnonEval(peerAssessmentAnonEval); a.setPeerAssessmentStudentViewReviews(peerAssessmentStudentViewReviews); a.setPeerAssessmentNumReviews(peerAssessmentNumReviews); a.setPeerAssessmentInstructions(peerAssessmentInstructions); // post the assignment a.setDraft(!post); try { // SAK-26349 - clear group selection before changing, otherwise it can result in a PermissionException a.clearGroupAccess(); if ("site".equals(range)) { a.setAccess(Assignment.AssignmentAccess.SITE); } else if ("groups".equals(range)) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot_addAssignmentContent")); M_log.warn(this + ":commitAssignmentEdit " + rb.getString("youarenot_addAssignmentContent") + e.getMessage()); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } if (a.isGroup()) { Collection<String> _dupUsers = usersInMultipleGroups(a); if (_dupUsers.size() > 0) { addAlert(state, rb.getString("group.user.multiple.error")); M_log.warn(this + ":post_save_assignment at least one user in multiple groups."); } } } private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit, boolean post, Time closeTime, String checkAnonymousGrading) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); // SAK-17606 aPropertiesEdit.addProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, checkAnonymousGrading); if (post && addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference()); } // allow resubmit number and default assignment resubmit closeTime (dueTime) if (allowResubmitNumber != null && closeTime != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else if (allowResubmitNumber == null || allowResubmitNumber.length() == 0 || "0".equals(allowResubmitNumber)) { aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); aPropertiesEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String assignmentRef, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments, String submitReviewRepo, String generateOriginalityReport, boolean checkTurnitin, boolean checkInternet, boolean checkPublications, boolean checkInstitution, boolean excludeBibliographic, boolean excludeQuoted, int excludeType, int excludeValue, Time openTime, Time dueTime, Time closeTime, boolean hideDueDate) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setHideDueDate(hideDueDate); ac.setTypeOfSubmission(submissionType); ac.setAllowReviewService(useReviewService); ac.setAllowStudentViewReport(allowStudentViewReport); ac.setSubmitReviewRepo(submitReviewRepo); ac.setGenerateOriginalityReport(generateOriginalityReport); ac.setCheckInstitution(checkInstitution); ac.setCheckInternet(checkInternet); ac.setCheckPublications(checkPublications); ac.setCheckTurnitin(checkTurnitin); ac.setExcludeBibliographic(excludeBibliographic); ac.setExcludeQuoted(excludeQuoted); ac.setExcludeType(excludeType); ac.setExcludeValue(excludeValue); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); M_log.warn(this + ":commitAssignmentContentEdit " + e.getMessage()); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); if (attachments != null) { // add each attachment Iterator it = EntityManager.newReferenceList(attachments).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } } state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false)); // commit the changes AssignmentService.commitEdit(ac); if(ac.getAllowReviewService()){ if (!createTIIAssignment(ac, assignmentRef, openTime, dueTime, closeTime, state)) { state.setAttribute("contentReviewSuccess", Boolean.FALSE); } } } public boolean createTIIAssignment(AssignmentContentEdit assign, String assignmentRef, Time openTime, Time dueTime, Time closeTime, SessionState state) { Map opts = new HashMap(); opts.put("submit_papers_to", assign.getSubmitReviewRepo()); opts.put("report_gen_speed", assign.getGenerateOriginalityReport()); opts.put("institution_check", assign.isCheckInstitution() ? "1" : "0"); opts.put("internet_check", assign.isCheckInternet() ? "1" : "0"); opts.put("journal_check", assign.isCheckPublications() ? "1" : "0"); opts.put("s_paper_check", assign.isCheckTurnitin() ? "1" : "0"); opts.put("s_view_report", assign.getAllowStudentViewReport() ? "1" : "0"); if(ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true)){ //we don't want to pass parameters if the user didn't get an option to set it opts.put("exclude_biblio", assign.isExcludeBibliographic() ? "1" : "0"); } if(ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true)){ //we don't want to pass parameters if the user didn't get an option to set it opts.put("exclude_quoted", assign.isExcludeQuoted() ? "1" : "0"); } if((assign.getExcludeType() == 1 || assign.getExcludeType() == 2) && assign.getExcludeValue() >= 0 && assign.getExcludeValue() <= 100){ opts.put("exclude_type", Integer.toString(assign.getExcludeType())); opts.put("exclude_value", Integer.toString(assign.getExcludeValue())); } opts.put("late_accept_flag", "1"); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern("yyyy-MM-dd HH:mm:ss"); opts.put("dtstart", dform.format(openTime.getTime())); opts.put("dtdue", dform.format(dueTime.getTime())); //opts.put("dtpost", dform.format(closeTime.getTime())); opts.put("title", assign.getTitle()); opts.put("instructions", assign.getInstructions()); if(assign.getAttachments() != null && assign.getAttachments().size() > 0){ List<String> attachments = new ArrayList<String>(); for(Reference ref : assign.getAttachments()){ attachments.add(ref.getReference()); } opts.put("attachments", attachments); } try { contentReviewService.createAssignment(assign.getContext(), assignmentRef, opts); return true; } catch (Exception e) { M_log.error(e); String uiService = ServerConfigurationService.getString("ui.service", "Sakai"); String[] args = new String[]{contentReviewService.getServiceName(), uiService}; state.setAttribute("alertMessage", rb.getFormattedMessage("content_review.error.createAssignment", args)); } return false; } /** * reorderAssignments */ private void reorderAssignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List assignments = prepPage(state); Iterator it = assignments.iterator(); while (it.hasNext()) // reads and writes the parameter for default ordering { Assignment a = (Assignment) it.next(); String assignmentid = a.getId(); String assignmentposition = params.getString("position_" + assignmentid); SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return function.equals(AssignmentService.SECURE_UPDATE_ASSIGNMENT)?SecurityAdvice.ALLOWED:SecurityAdvice.PASS; } }; try { // put in a security advisor so we can create citationAdmin site without need // of further permissions m_securityService.pushAdvisor(sa); AssignmentEdit ae = editAssignment(assignmentid, "reorderAssignments", state, true); if (ae != null) { ae.setPosition_order(Long.valueOf(assignmentposition).intValue()); AssignmentService.commitEdit(ae); } } catch (Exception e) { M_log.warn(this + ":reorderAssignments : not able to edit assignment " + assignmentid + e.toString()); } finally { // remove advisor m_securityService.popAdvisor(sa); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // reorderAssignments private AssignmentContentEdit editAssignmentContent(String assignmentContentId, String callingFunctionName, SessionState state, boolean allowAdd) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0 && allowAdd) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot_addAssignmentContent")); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage() + (String) state.getAttribute(STATE_CONTEXT_STRING)); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getFormattedMessage("somelsis_assignmentContent", new Object[]{assignmentContentId})); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } catch (IdUnusedException e) { addAlert(state, rb.getFormattedMessage("cannotfin_assignmentContent", new Object[]{assignmentContentId})); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } catch (PermissionException e) { addAlert(state, rb.getFormattedMessage("youarenot_viewAssignmentContent", new Object[]{assignmentContentId})); M_log.warn(this + ":" + callingFunctionName + " " + e.getMessage()); } } return ac; } /** * construct time object based on various state variables * @param state * @param monthString * @param dayString * @param yearString * @param hourString * @param minString * @return */ private Time getTimeFromState(SessionState state, String monthString, String dayString, String yearString, String hourString, String minString) { if (state.getAttribute(monthString) != null || state.getAttribute(dayString) != null || state.getAttribute(yearString) != null || state.getAttribute(hourString) != null || state.getAttribute(minString) != null) { int month = ((Integer) state.getAttribute(monthString)).intValue(); int day = ((Integer) state.getAttribute(dayString)).intValue(); int year = ((Integer) state.getAttribute(yearString)).intValue(); int hour = ((Integer) state.getAttribute(hourString)).intValue(); int min = ((Integer) state.getAttribute(minString)).intValue(); return TimeService.newTimeLocal(year, month, day, hour, min, 0, 0); } else { return null; } } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { post_save_assignment(data, "save"); } // doSave_assignment /** * Action is to reorder assignments */ public void doReorder_assignment(RunData data) { reorderAssignments(data); } // doReorder_assignments /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, true); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, Boolean.valueOf(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, Boolean.valueOf(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, Boolean.valueOf(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); Assignment a = getAssignment(assignmentId, "doView_assignment", state); // get resubmission option into state assignment_resubmission_option_into_state(a, null, state); // assignment read event m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT, assignmentId, false)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student // TODO: investigate if this method can be removed --bbailla2 public void doView_submissionReviews(RunData data){ String submissionId = data.getParameters().getString("submissionId"); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String assessorId = data.getParameters().getString("assessorId"); String assignmentId = StringUtils.trimToNull(data.getParameters().getString("assignmentId")); Assignment a = getAssignment(assignmentId, "doEdit_assignment", state); if (submissionId != null && !"".equals(submissionId) && a != null){ //set the page to go to state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); List<PeerAssessmentItem> peerAssessmentItems = assignmentPeerAssessmentService.getPeerAssessmentItemsByAssignmentId(a.getId()); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); List<String> submissionIds = new ArrayList<String>(); if(peerAssessmentItems != null){ for(PeerAssessmentItem item : peerAssessmentItems){ submissionIds.add(item.getSubmissionId()); } } state.setAttribute(USER_SUBMISSIONS, submissionIds); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); state.setAttribute(PEER_ASSESSMENT_ASSESSOR_ID, assessorId); state.setAttribute(STATE_MODE, MODE_STUDENT_REVIEW_EDIT); }else{ addAlert(state, rb.getString("peerassessment.notavailable")); } } // TODO: investigate if this method can be removed --bbailla2 public void doEdit_review(RunData data){ SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtils.trimToNull(params.getString("assignmentId")); Assignment a = getAssignment(assignmentId, "doEdit_assignment", state); if (a != null && a.isPeerAssessmentOpen()){ //set the page to go to state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); String submissionId = null; List<PeerAssessmentItem> peerAssessmentItems = assignmentPeerAssessmentService.getPeerAssessmentItems(a.getId(), UserDirectoryService.getCurrentUser().getId()); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); List<String> submissionIds = new ArrayList<String>(); if(peerAssessmentItems != null){ for(PeerAssessmentItem item : peerAssessmentItems){ if(!item.isSubmitted()){ submissionIds.add(item.getSubmissionId()); } } } if(params.getString("submissionId") != null && submissionIds.contains(params.getString("submissionId"))){ submissionId = StringUtils.trimToNull(params.getString("submissionId")); }else if(submissionIds.size() > 0){ //submission Id wasn't passed in, let's find one for this user //grab the first one: submissionId = submissionIds.get(0); } if(submissionId != null){ state.setAttribute(USER_SUBMISSIONS, submissionIds); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); state.setAttribute(STATE_MODE, MODE_STUDENT_REVIEW_EDIT); }else{ if(peerAssessmentItems != null && peerAssessmentItems.size() > 0){ //student has submitted all their peer reviews, nothing left to review //(student really shouldn't get to this warning) addAlert(state, rb.getString("peerassessment.allSubmitted")); }else{ //wasn't able to find a submission id, throw error addAlert(state, rb.getString("peerassessment.notavailable")); } } }else{ addAlert(state, rb.getString("peerassessment.notavailable")); } } /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtils.trimToNull(params.getString("assignmentId")); if (AssignmentService.allowUpdateAssignment(assignmentId)) { Assignment a = getAssignment(assignmentId, "doEdit_assignment", state); if (a != null) { // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); // for the non_electronice assignment, submissions are auto-generated by the time that assignment is created; // don't need to go through the following checkings. if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // any submitted? boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted() && s.getTimeSubmitted() != null) { anySubmitted = true; } } // any draft submission boolean anyDraft = false; for (;submissions.hasNext() && !anyDraft;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (!s.getSubmitted()) { anyDraft = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getFormattedMessage("hassum", new Object[]{a.getTitle()})); } if (anyDraft) { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order()); if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { putTimePropertiesInState(state, a.getVisibleTime(), NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } putTimePropertiesInState(state, a.getOpenTime(), NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // generate alert when editing an assignment past open date if (a.getOpenTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot20")); } putTimePropertiesInState(state, a.getDueTime(), NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true)); putTimePropertiesInState(state, a.getCloseTime(), NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(a.getContent().getTypeOfSubmission())); state.setAttribute(NEW_ASSIGNMENT_CATEGORY, getAssignmentCategoryAsInt(a)); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE, Boolean.valueOf(a.getContent().getHideDueDate()).toString()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // submission notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // release grade notification option if (properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } // SAK-17606 state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING, properties.getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); // put the resubmission option into state assignment_resubmission_option_into_state(a, null, state); // set whether we use peer assessment or not Time peerAssessmentPeriod = a.getPeerAssessmentPeriod(); //check if peer assessment time exist? if not, this could be an old assignment, so just set it //to 10 min after accept until date if(peerAssessmentPeriod == null && a.getCloseTime() != null){ // set the peer period time to be 10 mins after accept until date GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(a.getCloseTime().getTime()); c.add(GregorianCalendar.MINUTE, 10); peerAssessmentPeriod = TimeService.newTime(c.getTimeInMillis()); } if(peerAssessmentPeriod != null){ state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, Boolean.valueOf(a.getAllowPeerAssessment()).toString()); putTimePropertiesInState(state, peerAssessmentPeriod, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL, Boolean.valueOf(a.getPeerAssessmentAnonEval()).toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS, Boolean.valueOf(a.getPeerAssessmentStudentViewReviews()).toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, a.getPeerAssessmentNumReviews()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS, a.getPeerAssessmentInstructions()); } if(!allowPeerAssessment){ state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, false); } // set whether we use the review service or not state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, Boolean.valueOf(a.getContent().getAllowReviewService()).toString()); //set whether students can view the review service results state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, Boolean.valueOf(a.getContent().getAllowStudentViewReport()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO, a.getContent().getSubmitReviewRepo()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO, a.getContent().getGenerateOriginalityReport()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN, Boolean.valueOf(a.getContent().isCheckTurnitin()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET, Boolean.valueOf(a.getContent().isCheckInternet()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB, Boolean.valueOf(a.getContent().isCheckPublications()).toString()); state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION, Boolean.valueOf(a.getContent().isCheckInstitution()).toString()); //exclude bibliographic state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC, Boolean.valueOf(a.getContent().isExcludeBibliographic()).toString()); //exclude quoted state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED, Boolean.valueOf(a.getContent().isExcludeQuoted()).toString()); //exclude type state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE, a.getContent().getExcludeType()); //exclude value state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE,a.getContent().getExcludeValue()); state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); state.setAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT, a.isGroup() ? "1": "0"); // get all supplement item info into state setAssignmentSupplementItemInState(state, a); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } } else { addAlert(state, rb.getString("youarenot6")); } } // doEdit_Assignment public List<String> getSubmissionRepositoryOptions() { List<String> submissionRepoSettings = new ArrayList<String>(); String[] propertyValues = ServerConfigurationService.getStrings("turnitin.repository.setting"); if (propertyValues != null && propertyValues.length > 0) { for (int i=0; i < propertyValues.length; i++) { String propertyVal = propertyValues[i]; if (propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE) || propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_INSITUTION) || propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD)) { submissionRepoSettings.add(propertyVal); } } } // if there are still no valid settings in the list at this point, use the default if (submissionRepoSettings.isEmpty()) { // add all three submissionRepoSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_NONE); submissionRepoSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_STANDARD); } return submissionRepoSettings; } public List<String> getReportGenOptions() { List<String> reportGenSettings = new ArrayList<String>(); String[] propertyValues = ServerConfigurationService.getStrings("turnitin.report_gen_speed.setting"); if (propertyValues != null && propertyValues.length > 0) { for (int i=0; i < propertyValues.length; i++) { String propertyVal = propertyValues[i]; if (propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE) || propertyVal.equals(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY)) { reportGenSettings.add(propertyVal); } } } // if there are still no valid settings in the list at this point, use the default if (reportGenSettings.isEmpty()) { // add all three reportGenSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_DUE); reportGenSettings.add(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_IMMEDIATELY); } return reportGenSettings; } /** * put all assignment supplement item info into state * @param state * @param a */ private void setAssignmentSupplementItemInState(SessionState state, Assignment a) { String assignmentId = a.getId(); // model answer AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(assignmentId); if (mAnswer != null) { if (state.getAttribute(MODELANSWER_TEXT) == null) { state.setAttribute(MODELANSWER_TEXT, mAnswer.getText()); } if (state.getAttribute(MODELANSWER_SHOWTO) == null) { state.setAttribute(MODELANSWER_SHOWTO, String.valueOf(mAnswer.getShowTo())); } if (state.getAttribute(MODELANSWER) == null) { state.setAttribute(MODELANSWER, Boolean.TRUE); } } // get attachments for model answer object putSupplementItemAttachmentInfoIntoState(state, mAnswer, MODELANSWER_ATTACHMENTS); // private notes AssignmentNoteItem mNote = m_assignmentSupplementItemService.getNoteItem(assignmentId); if (mNote != null) { if (state.getAttribute(NOTE) == null) { state.setAttribute(NOTE, Boolean.TRUE); } if (state.getAttribute(NOTE_TEXT) == null) { state.setAttribute(NOTE_TEXT, mNote.getNote()); } if (state.getAttribute(NOTE_SHAREWITH) == null) { state.setAttribute(NOTE_SHAREWITH, String.valueOf(mNote.getShareWith())); } } // all purpose item AssignmentAllPurposeItem aItem = m_assignmentSupplementItemService.getAllPurposeItem(assignmentId); if (aItem != null) { if (state.getAttribute(ALLPURPOSE) == null) { state.setAttribute(ALLPURPOSE, Boolean.TRUE); } if (state.getAttribute(ALLPURPOSE_TITLE) == null) { state.setAttribute(ALLPURPOSE_TITLE, aItem.getTitle()); } if (state.getAttribute(ALLPURPOSE_TEXT) == null) { state.setAttribute(ALLPURPOSE_TEXT, aItem.getText()); } if (state.getAttribute(ALLPURPOSE_HIDE) == null) { state.setAttribute(ALLPURPOSE_HIDE, Boolean.valueOf(aItem.getHide())); } if (state.getAttribute(ALLPURPOSE_SHOW_FROM) == null) { state.setAttribute(ALLPURPOSE_SHOW_FROM, aItem.getReleaseDate() != null); } if (state.getAttribute(ALLPURPOSE_SHOW_TO) == null) { state.setAttribute(ALLPURPOSE_SHOW_TO, aItem.getRetractDate() != null); } if (state.getAttribute(ALLPURPOSE_ACCESS) == null) { Set<AssignmentAllPurposeItemAccess> aSet = aItem.getAccessSet(); List<String> aList = new ArrayList<String>(); for(Iterator<AssignmentAllPurposeItemAccess> aIterator = aSet.iterator(); aIterator.hasNext();) { AssignmentAllPurposeItemAccess access = aIterator.next(); aList.add(access.getAccess()); } state.setAttribute(ALLPURPOSE_ACCESS, aList); } // get attachments for model answer object putSupplementItemAttachmentInfoIntoState(state, aItem, ALLPURPOSE_ATTACHMENTS); } // get the AllPurposeItem and AllPurposeReleaseTime/AllPurposeRetractTime //default to assignment open time Time releaseTime = a.getOpenTime(); // default to assignment close time Time retractTime = a.getCloseTime(); if (aItem != null) { Date releaseDate = aItem.getReleaseDate(); if (releaseDate != null) { // overwrite if there is a release date releaseTime = TimeService.newTime(releaseDate.getTime()); } Date retractDate = aItem.getRetractDate(); if (retractDate != null) { // overwriteif there is a retract date retractTime = TimeService.newTime(retractDate.getTime()); } } putTimePropertiesInState(state, releaseTime, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY, ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN); putTimePropertiesInState(state, retractTime, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY, ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN); } /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { List ids = new ArrayList(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getFormattedMessage("youarenot_removeAssignment", new Object[]{id})); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids List ids = (List) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); AssignmentEdit aEdit = editAssignment(assignmentId, "doDelete_assignment", state, false); if (aEdit != null) { ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove related event if there is one removeCalendarEvent(state, aEdit, pEdit, title); // remove related announcement if there is one removeAnnouncement(state, pEdit); // we use to check "assignment.delete.cascade.submission" setting. But the implementation now is always remove submission objects when the assignment is removed. // delete assignment and its submissions altogether deleteAssignmentObjects(state, aEdit, true); // remove from Gradebook integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null, -1); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new ArrayList()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset paging information after the assignment been deleted resetPaging(state); } } // doDelete_Assignment /** * private function to remove assignment related announcement * @param state * @param pEdit */ private void removeAnnouncement(SessionState state, ResourcePropertiesEdit pEdit) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { String openDateAnnounced = StringUtils.trimToNull(pEdit.getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED)); String openDateAnnouncementId = StringUtils.trimToNull(pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID)); if (openDateAnnounced != null && openDateAnnouncementId != null) { try { channel.removeMessage(openDateAnnouncementId); } catch (PermissionException e) { M_log.warn(this + ":removeAnnouncement " + e.getMessage()); } } } } /** * private method to remove assignment and related objects * @param state * @param aEdit * @param removeSubmissions Whether or not to remove the submission objects */ private void deleteAssignmentObjects(SessionState state, AssignmentEdit aEdit, boolean removeSubmissions) { if (removeSubmissions) { // if this is non-electronic submission, remove all the submissions List submissions = AssignmentService.getSubmissions(aEdit); if (submissions != null) { for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); AssignmentSubmissionEdit sEdit = editSubmission((s.getReference()), "deleteAssignmentObjects", state); try { AssignmentService.removeSubmission(sEdit); } catch (Exception eee) { // Trapping for InUseException... go ahead and remove them. if (!(eee instanceof InUseException)) { addAlert(state, rb.getFormattedMessage("youarenot_removeSubmission", new Object[]{s.getReference()})); M_log.warn(this + ":deleteAssignmentObjects " + eee.getMessage() + " " + s.getReference()); } } } } } AssignmentContent aContent = aEdit.getContent(); if (aContent != null) { try { // remove the assignment content AssignmentContentEdit acEdit = editAssignmentContent(aContent.getReference(), "deleteAssignmentObjects", state, false); if (acEdit != null) AssignmentService.removeAssignmentContent(acEdit); } catch (Exception ee) { addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". "); M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage()); } } try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(aEdit)); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException ee) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); M_log.warn(this + ":deleteAssignmentObjects " + ee.getMessage()); } } private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) { String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { // remove the associated calendar event Calendar c = (Calendar) state.getAttribute(CALENDAR); removeCalendarEventFromCalendar(state, aEdit, pEdit, title, c, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); // remove the associated event from the additional calendar Calendar additionalCalendar = (Calendar) state.getAttribute(ADDITIONAL_CALENDAR); removeCalendarEventFromCalendar(state, aEdit, pEdit, title, additionalCalendar, ResourceProperties.PROP_ASSIGNMENT_DUEDATE_ADDITIONAL_CALENDAR_EVENT_ID); } } // Retrieves the calendar event associated with the due date and removes it from the calendar. private void removeCalendarEventFromCalendar(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title, Calendar c, String dueDateProperty) { if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(dueDateProperty); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition M_log.warn(this + ":removeCalendarEventFromCalendar " + ee.getMessage()); } catch (PermissionException ee) { M_log.warn(this + ":removeCalendarEventFromCalendar " + ee.getMessage()); } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("gen.assig") + " " + title) != -1) { found = true; } } } catch (PermissionException pException) { addAlert(state, rb.getFormattedMessage("cannot_getEvents", new Object[]{c.getReference()})); } } // remove the found old event if (found) { // found the old event delete it removeOldEvent(title, c, e); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(dueDateProperty); } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids List ids = (List) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); AssignmentEdit a = editAssignment(currentId, "doDeep_delete_assignment", state, false); if (a != null) { try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(a)); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getFormattedMessage("youarenot_editAssignment", new Object[]{a.getTitle()})); M_log.warn(this + ":doDeep_delete_assignment " + e.getMessage()); } } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new ArrayList()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { if (!"POST".equals(data.getRequest().getMethod())) { return; } SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtils.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_ADDITIONAL_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aPropertiesEdit.removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } catch (IdInvalidException e) { addAlert(state, rb.getFormattedMessage("theassiid_isnotval", new Object[]{assignmentId})); M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } catch (IdUnusedException e) { addAlert(state, rb.getFormattedMessage("theassiid_hasnotbee", new Object[]{assignmentId})); M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } catch (Exception e) { M_log.warn(this + ":doDuplicate_assignment " + e.getMessage()); } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); String submissionId = params.getString("submissionId"); // put submission information into state putSubmissionInfoIntoState(state, assignmentId, submissionId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); state.setAttribute(FROM_VIEW, (String)params.getString("option")); // assignment read event m_eventTrackingService.post(m_eventTrackingService.newEvent(AssignmentConstants.EVENT_ACCESS_ASSIGNMENT_SUBMISSION, submissionId, false)); } } // doGrade_submission /** * put all the submission information into state variables * @param state * @param assignmentId * @param submissionId */ private void putSubmissionInfoIntoState(SessionState state, String assignmentId, String submissionId) { // reset grading submission variables resetGradeSubmission(state); // reset the grade assignment id and submission id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, assignmentId); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, submissionId); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = getAssignment(assignmentId, "putSubmissionInfoIntoState", state); if (a != null) { AssignmentSubmission s = getSubmission(submissionId, "putSubmissionInfoIntoState", state); if (s != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); /* if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } */ state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT,v); state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); // populate grade overrides if they exist if (a.isGroup()) { User[] _users = s.getSubmitters(); for (int i=0; _users != null && i < _users.length; i++) { if (s.getGradeForUser(_users[i].getId()) != null) { state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), s.getGradeForUser(_users[i].getId())); } } } // put the resubmission info into state assignment_resubmission_option_into_state(a, s, state); } } } /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); // get the assignment Assignment a = getAssignment(assignmentId, "doRelease_grades", state); if (a != null) { String aReference = a.getReference(); Iterator submissions = getFilteredSubmitters(state, aReference).iterator(); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded() || (s.getGrade()!=null && !"".equals(s.getGrade()))) { String sRef = s.getReference(); AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doRelease_grades", state); if (sEdit != null) { String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !"".equals(grade)) { sEdit.setGradeReleased(true); if(!s.getGraded()) { sEdit.setGraded(true); } } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update", -1); } } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.removeAttribute(SHOW_ALLOW_RESUBMISSION); state.removeAttribute(SHOW_SEND_FEEDBACK); state.removeAttribute(SAVED_FEEDBACK); state.removeAttribute(OW_FEEDBACK); state.removeAttribute(RETURNED_FEEDBACK); String assignmentId = params.getString("assignmentId"); state.setAttribute(EXPORT_ASSIGNMENT_REF, assignmentId); Assignment a = getAssignment(assignmentId, "doGrade_assignment", state); if (a != null) { state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, Boolean.valueOf(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, Boolean.valueOf(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // initialize the resubmission params assignment_resubmission_option_into_state(a, null, state); // we are changing the view, so start with first page again. resetPaging(state); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); String _mode = MODE_STUDENT_VIEW_GRADE; AssignmentSubmission _s = getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade", state ); // whether the user can access the Submission object if (_s != null) { // show submission view unless group submission with group error Assignment a = _s.getAssignment(); User u = (User) state.getAttribute(STATE_USER); if (a.isGroup()) { Collection groups = null; Site st = null; try { st = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); groups = getGroupsWithUser(u.getId(), a, st); Collection<String> _dupUsers = checkForGroupsInMultipleGroups(a, groups, state, rb.getString("group.user.multiple.warning")); if (_dupUsers.size() > 0) { _mode = MODE_STUDENT_VIEW_GROUP_ERROR; state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, _s.getAssignmentId()); } } catch (IdUnusedException iue) { M_log.warn(this + ":doView_grade found!" + iue.getMessage()); } } state.setAttribute(STATE_MODE, _mode); } } // doView_grade /** * Action is to show the graded assignment submission while keeping specific information private */ public void doView_grade_private(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); // whether the user can access the Submission object if (getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID), "doView_grade_private", state ) != null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE_PRIVATE); } } // doView_grade_private /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); //Added by Branden Visser: Grab the submission id from the query string SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String actualGradeSubmissionId = (String) params.getString("submissionId"); Log.debug("chef", "doAssignment_form(): actualGradeSubmissionId = " + actualGradeSubmissionId); String option = (String) params.getString("option"); String fromView = (String) state.getAttribute(FROM_VIEW); if (option != null) { if ("post".equals(option)) { // post assignment doPost_assignment(data); } else if ("save".equals(option)) { // save assignment doSave_assignment(data); } else if ("reorder".equals(option)) { // reorder assignments doReorder_assignment(data); } else if ("preview".equals(option)) { // preview assignment doPreview_assignment(data); } else if ("cancel".equals(option)) { // cancel creating assignment doCancel_new_assignment(data); } else if ("canceledit".equals(option)) { // cancel editing assignment doCancel_edit_assignment(data); } else if ("attach".equals(option)) { // attachments doAttachmentsFrom(data, null); } else if ("modelAnswerAttach".equals(option)) { doAttachmentsFrom(data, "modelAnswer"); } else if ("allPurposeAttach".equals(option)) { doAttachmentsFrom(data, "allPurpose"); } else if ("view".equals(option)) { // view doView(data); } else if ("permissions".equals(option)) { // permissions doPermissions(data); } else if ("returngrade".equals(option)) { // return grading doReturn_grade_submission(data); } else if ("savegrade".equals(option)) { // save grading doSave_grade_submission(data); } else if ("savegrade_review".equals(option)) { // save review grading doSave_grade_submission_review(data); }else if("submitgrade_review".equals(option)){ //we basically need to submit, save, and move the user to the next review (if available) if(data.getParameters().get("nextSubmissionId") != null){ //go next doPrev_back_next_submission_review(data, "next", true); }else if(data.getParameters().get("prevSubmissionId") != null){ //go previous doPrev_back_next_submission_review(data, "prev", true); }else{ //go back to the list doPrev_back_next_submission_review(data, "back", true); } } else if ("toggleremove_review".equals(option)) { // save review grading doSave_toggle_remove_review(data); } else if ("previewgrade".equals(option)) { // preview grading doPreview_grade_submission(data); } else if ("cancelgrade".equals(option)) { // cancel grading doCancel_grade_submission(data); } else if ("cancelgrade_review".equals(option)) { // cancel grade review // no need to do anything, session will have original values and refresh } else if ("cancelreorder".equals(option)) { // cancel reordering doCancel_reorder(data); } else if ("sortbygrouptitle".equals(option)) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if ("sortbygroupdescription".equals(option)) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if ("hide_instruction".equals(option)) { // hide the assignment instruction doHide_submission_assignment_instruction(data); }else if ("hide_instruction_review".equals(option)) { // hide the assignment instruction doHide_submission_assignment_instruction_review(data); } else if ("show_instruction".equals(option)) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if ("show_instruction_review".equals(option)) { // show the assignment instruction doShow_submission_assignment_instruction_review(data); } else if ("sortbygroupdescription".equals(option)) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if ("revise".equals(option) || "done".equals(option)) { // back from the preview mode doDone_preview_new_assignment(data); } else if ("prevsubmission".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission(data, "prev"); } else if ("nextsubmission".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission(data, "next"); } else if ("prevsubmission_review".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission_review(data, "prev", false); } else if ("nextsubmission_review".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission_review(data, "next", false); } else if ("cancelgradesubmission".equals(option)) { if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(fromView)) { doPrev_back_next_submission(data, "backListStudent"); } else { // save and navigate to previous submission doPrev_back_next_submission(data, "back"); } } else if ("cancelgradesubmission_review".equals(option)) { // save and navigate to previous submission doPrev_back_next_submission_review(data, "back", false); } else if ("reorderNavigation".equals(option)) { // save and do reorder doReorder(data); } else if ("options".equals(option)) { // go to the options view doOptions(data); } } } // added by Branden Visser - Check that the state is consistent boolean checkSubmissionStateConsistency(SessionState state, String actualGradeSubmissionId) { String stateGradeSubmissionId = (String)state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); Log.debug("chef", "checkSubmissionStateConsistency(): stateGradeSubmissionId = " + stateGradeSubmissionId); boolean is_good = stateGradeSubmissionId.equals(actualGradeSubmissionId); if (!is_good) { Log.warn("chef", "checkSubissionStateConsistency(): State is inconsistent! Aborting grade save."); addAlert(state, rb.getString("grading.alert.multiTab")); } return is_good; } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachmentsFrom(RunData data, String from) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); doAttachments(data); // use the real attachment list if (state.getAttribute(STATE_MESSAGE) == null) { if (from != null && "modelAnswer".equals(from)) { state.setAttribute(ATTACHMENTS_FOR, MODELANSWER_ATTACHMENTS); state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(MODELANSWER_ATTACHMENTS)); state.setAttribute(MODELANSWER, Boolean.TRUE); } else if (from != null && "allPurpose".equals(from)) { state.setAttribute(ATTACHMENTS_FOR, ALLPURPOSE_ATTACHMENTS); state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ALLPURPOSE_ATTACHMENTS)); state.setAttribute(ALLPURPOSE, Boolean.TRUE); } } } /** * put supplement item attachment info into state * @param state * @param item * @param attachmentsKind */ private void putSupplementItemAttachmentInfoIntoState(SessionState state, AssignmentSupplementItemWithAttachment item, String attachmentsKind) { List refs = new ArrayList(); if (item != null) { // get reference list Set<AssignmentSupplementItemAttachment> aSet = item.getAttachmentSet(); if (aSet != null && aSet.size() > 0) { for(Iterator<AssignmentSupplementItemAttachment> aIterator = aSet.iterator(); aIterator.hasNext();) { AssignmentSupplementItemAttachment att = aIterator.next(); // add reference refs.add(EntityManager.newReference(att.getAttachmentId())); } state.setAttribute(attachmentsKind, refs); } } } /** * put supplement item attachment state attribute value into context * @param state * @param context * @param attachmentsKind */ private void putSupplementItemAttachmentStateIntoContext(SessionState state, Context context, String attachmentsKind) { List refs = new ArrayList(); String attachmentsFor = (String) state.getAttribute(ATTACHMENTS_FOR); if (attachmentsFor != null && attachmentsFor.equals(attachmentsKind)) { ToolSession session = SessionManager.getCurrentToolSession(); if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null && session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); // set the correct state variable state.setAttribute(attachmentsKind, refs); } session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); state.removeAttribute(ATTACHMENTS_FOR); } // show attachments content if (state.getAttribute(attachmentsKind) != null) { context.put(attachmentsKind, state.getAttribute(attachmentsKind)); } // this is to keep the proper node div open context.put("attachments_for", attachmentsKind); } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // determines if the file picker can only add a single attachment boolean singleAttachment = false; // when content-review is enabled, the inline text will have an associated attachment. It should be omitted from the file picker Assignment assignment = null; boolean omitInlineAttachments = false; String mode = (String) state.getAttribute(STATE_MODE); if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode)) { // save the current input before leaving the page saveSubmitInputs(state, params); // Restrict file picker configuration if using content-review (Turnitin): String assignmentRef = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { assignment = AssignmentService.getAssignment(assignmentRef); if (assignment.getContent().getAllowReviewService()) { state.setAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS, FilePickerHelper.CARDINALITY_MULTIPLE); state.setAttribute(FilePickerHelper.FILE_PICKER_SHOW_URL, Boolean.FALSE); } if (assignment.getContent().getTypeOfSubmission() == Assignment.SINGLE_ATTACHMENT_SUBMISSION) { singleAttachment = true; } } catch ( IdUnusedException e ) { addAlert(state, rb.getFormattedMessage("cannotfin_assignment", new Object[]{assignmentRef})); } catch ( PermissionException e ) { addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentRef})); } // need also to upload local file if any doAttachUpload(data, false); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); // Always omit inline attachments. Even if content-review is not enabled, // this could be a resubmission to an assignment that was previously content-review enabled, // in which case the file will be present and should be omitted. omitInlineAttachments = true; } else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)) { setNewAssignmentParameters(data, false); } else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); if (singleAttachment) { // SAK-27595 - added a resources file picker for single uploaded file only assignments; we limit it here to accept a maximum of 1 file --bbailla2 state.setAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS, Integer.valueOf(1)); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig.singular")); } else { state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); } state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list // but omit the inlie submission under conditions determined in the logic above List attachments = (List) state.getAttribute(ATTACHMENTS); if (omitInlineAttachments && assignment != null) { attachments = getNonInlineAttachments(state, assignment); state.setAttribute(ATTACHMENTS, attachments); } state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, attachments); } } /** * saves the current input before navigating off to other pages * @param state * @param params */ private void saveSubmitInputs(SessionState state, ParameterParser params) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } String assignmentRef = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment assignment = AssignmentService.getAssignment(assignmentRef); if (assignment.isGroup()) { String[] groupChoice = params.getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { if (groupChoice.length > 1) { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } else { state.setAttribute(VIEW_SUBMISSION_GROUP, groupChoice[0]); } } else { state.setAttribute(VIEW_SUBMISSION_GROUP, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } String original_group_id = params.getString("originalGroup") == null || params.getString("originalGroup").trim().length() == 0 ? null: params.getString("originalGroup"); if (original_group_id != null) { state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, original_group_id); } else { state.setAttribute(VIEW_SUBMISSION_ORIGINAL_GROUP, null); } } } catch (PermissionException p) { M_log.debug(this + " :saveSubmitInputs permission error getting assignment. "); } catch ( IdUnusedException e ) {} } /** * read review grade information form and see if any grading information has been changed * @param data * @param state * @param gradeOption * @return */ public boolean saveReviewGradeForm(RunData data, SessionState state, String gradeOption){ String assessorUserId = UserDirectoryService.getCurrentUser().getId(); if(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null && !assessorUserId.equals(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID))){ //this is only set during the read only view, so just return return false; } ParameterParser params = data.getParameters(); String submissionRef = params.getString("submissionId"); String submissionId = null; if(submissionRef != null){ int i = submissionRef.lastIndexOf(Entity.SEPARATOR); if (i == -1){ submissionId = submissionRef; }else{ submissionId = submissionRef.substring(i + 1); } } if(submissionId != null){ //call the DB to make sure this user can edit this assessment, otherwise it wouldn't exist PeerAssessmentItem item = assignmentPeerAssessmentService.getPeerAssessmentItem(submissionId, assessorUserId); if(item != null){ //find the original assessment item and compare to see if it has changed //if so, save it boolean changed = false; if(submissionId.equals(item.getSubmissionId()) && assessorUserId.equals(item.getAssessorUserId())){ //Grade String g = StringUtils.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE)); Integer score = item.getScore(); if(g != null && !"".equals(g)){ try{ Double dScore = Double.parseDouble(g); if(dScore < 0){ addAlert(state, rb.getString("peerassessment.alert.saveinvalidscore")); }else{ String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); if(assignmentId != null){ Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if(a != null){ if(dScore <= a.getContent().getMaxGradePoint()/10.0){ //scores are saved as whole values //so a score of 1.3 would be stored as 13 score = (int) Math.round(dScore * 10); }else{ addAlert(state, rb.getFormattedMessage("plesuse4", new Object[]{g, a.getContent().getMaxGradePoint()/10.0})); } }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } } }catch(Exception e){ addAlert(state, rb.getString("peerassessment.alert.saveinvalidscore")); } } boolean scoreChanged = false; if(score != null && item.getScore() == null || score == null && item.getScore() != null || (score != null && item.getScore() != null && !score.equals(item.getScore()))){ //Score changed changed = true; scoreChanged = true; item.setScore(score); } //Comment: boolean checkForFormattingErrors = true; String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if(feedbackComment != null && item.getComment() == null || feedbackComment == null && item.getComment() != null || (feedbackComment != null && item.getComment() != null && !feedbackComment.equals(item.getComment()))){ //comment changed changed = true; item.setComment(feedbackComment); } //Submitted if("submit".equals(gradeOption)){ if(item.getScore() != null || (item.getComment() != null && !"".equals(item.getComment().trim()))){ item.setSubmitted(true); changed = true; }else{ addAlert(state, rb.getString("peerassessment.alert.savenoscorecomment")); } } if(("submit".equals(gradeOption) || "save".equals(gradeOption)) && state.getAttribute(STATE_MESSAGE) == null){ if(changed){ //save this in the DB assignmentPeerAssessmentService.savePeerAssessmentItem(item); if(scoreChanged){ //need to re-calcuate the overall score: boolean saved = assignmentPeerAssessmentService.updateScore(submissionId); if(saved){ //we need to make sure the GB is updated correctly (or removed) String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); if(assignmentId != null){ Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if(a != null){ String aReference = a.getReference(); String associateGradebookAssignment = StringUtils.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, submissionId, "update", -1); } } } } state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); if("submit".equals(gradeOption)){ state.setAttribute(GRADE_SUBMISSION_SUBMIT, Boolean.TRUE); } } } //update session state: List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state.getAttribute(PEER_ASSESSMENT_ITEMS); if(peerAssessmentItems != null){ for(int i = 0; i < peerAssessmentItems.size(); i++) { PeerAssessmentItem sItem = peerAssessmentItems.get(i); if(sItem.getSubmissionId().equals(item.getSubmissionId()) && sItem.getAssessorUserId().equals(item.getAssessorUserId())){ //found it, just update it peerAssessmentItems.set(i, item); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); break; } } } } return changed; }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } }else{ addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } return false; } /** * read grade information form and see if any grading information has been changed * @param data * @param state * @param gradeOption * @return */ public boolean readGradeForm(RunData data, SessionState state, String gradeOption) { // whether user has changed anything from previous grading information boolean hasChange = false; ParameterParser params = data.getParameters(); String sId = params.getString("submissionId"); //Added by Branden Visser - Check that the state is consistent if (!checkSubmissionStateConsistency(state, sId)) { return false; } AssignmentSubmission submission = getSubmission(sId, "readGradeForm", state); // security check for allowing grading submission or not if (AssignmentService.allowGradeSubmission(sId)) { int typeOfGrade = -1; boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = true; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); // comment value changed? hasChange = !hasChange && submission != null ? valueDiffFromStateAttribute(state, feedbackComment, submission.getFeedbackComment()):hasChange; if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); // feedbackText value changed? hasChange = !hasChange && submission != null ? valueDiffFromStateAttribute(state, feedbackText, submission.getFeedbackText()):hasChange; if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } // any change inside attachment list? if (!hasChange && submission != null) { List stateAttachments = submission.getFeedbackAttachments(); List inputAttachments = (List) state.getAttribute(ATTACHMENTS); if (stateAttachments == null && inputAttachments != null || stateAttachments != null && inputAttachments == null || stateAttachments != null && inputAttachments != null && !(stateAttachments.containsAll(inputAttachments) && inputAttachments.containsAll(stateAttachments))) { hasChange = true; } } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = StringUtils.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE)); if (submission != null) { Assignment a = submission.getAssignment(); typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // any change in grade. Do not check for ungraded assignment type if (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) { if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { String currentGrade = submission.getGrade(); NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; if (currentGrade != null && currentGrade.indexOf(decSeparator) != -1) { currentGrade = scalePointGrade(state, submission.getGrade()); } hasChange = valueDiffFromStateAttribute(state, scalePointGrade(state, g), currentGrade); } else { hasChange = valueDiffFromStateAttribute(state, g, submission.getGrade()); } } if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } else { state.removeAttribute(GRADE_SUBMISSION_GRADE); } // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if ((grade != null)) { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); M_log.warn(this + ":readGradeForm " + e.getMessage()); } } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || "ungraded".equals(grade)) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && "release".equals(gradeOption)) { addAlert(state, rb.getString("plespethe2")); } // check for grade overrides if (a.isGroup()) { User[] _users = submission.getSubmitters(); for (int i=0; _users != null && i < _users.length; i++) { String ug = StringUtil.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId())); if ("null".equals(ug)) ug = null; if (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) { if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { hasChange = valueDiffFromStateAttribute(state, scalePointGrade(state, ug), submission.getGradeForUser(_users[i].getId())); } else { hasChange = valueDiffFromStateAttribute(state, ug, submission.getGradeForUser(_users[i].getId())); } } if (ug == null) { state.removeAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); } else { state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), ug); } // for points grading, one have to enter number as the points String ugrade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if (ugrade != null && !(ugrade.equals("null"))) { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, ugrade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, ugrade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{ugrade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, ugrade); M_log.warn(this + ":readGradeForm User " + e.getMessage()); } } state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), scalePointGrade(state,ugrade)); } } } } } } // allow resubmit number and due time if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params readAllowResubmitParams(params, state, submission); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (!"read".equals(gradeOption)) { resetAllowResubmitParams(state); } } // record whether the resubmission options has been changed or not hasChange = hasChange || change_resubmit_option(state, submission); } if (state.getAttribute(STATE_MESSAGE) == null) { String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE)?scalePointGrade(state, grade):grade; state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } else { // generate alert addAlert(state, rb.getFormattedMessage("not_allowed_to_grade_submission", new Object[]{sId})); } return hasChange; } /** * whether the current input value is different from existing oldValue * @param state * @param value * @param oldValue * @return */ private boolean valueDiffFromStateAttribute(SessionState state, String value, String oldValue) { boolean rv = false; value = StringUtils.trimToNull(value); oldValue = StringUtils.trimToNull(oldValue); if (oldValue == null && value != null || oldValue != null && value == null || oldValue != null && value != null && !normalizeAttributeSpaces(oldValue).equals(normalizeAttributeSpaces(value))) { rv = true; } return rv; } /** Remove extraneous spaces between tag attributes, to allow a better equality test in valueDiffFromStateAttribute. @param the input string, to be normalized @return the normalized string. */ String normalizeAttributeSpaces(String s) { if (s == null) return s; Pattern p = Pattern.compile("(=\".*?\")( +)"); Matcher m = p.matcher(s); String c = m.replaceAll("$1 "); return c; } /** * read in the resubmit parameters into state variables * @param params * @param state * @return the time set for the resubmit close OR null if it is not set */ protected Time readAllowResubmitParams(ParameterParser params, SessionState state, Entity entity) { Time resubmitCloseTime = null; String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (allowResubmitNumberString != null && Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(closeMonth)); int closeDay = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(closeDay)); int closeYear = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(closeYear)); int closeHour = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(closeHour)); int closeMin = (Integer.valueOf(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(closeMin)); resubmitCloseTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(resubmitCloseTime.getTime())); // no need to show alert if the resubmission setting has not changed if (entity == null || change_resubmit_option(state, entity)) { // validate date if (resubmitCloseTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) != null) { addAlert(state, rb.getString("acesubdea5")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getFormattedMessage("date.invalid", new Object[]{rb.getString("date.resubmission.closedate")})); } } } else { // reset the state attributes resetAllowResubmitParams(state); } return resubmitCloseTime; } protected void resetAllowResubmitParams(SessionState state) { state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH,state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY,state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR,state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR,state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN,state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); if (m_contentHostingService == null) { m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); } if (m_assignmentSupplementItemService == null) { m_assignmentSupplementItemService = (AssignmentSupplementItemService) ComponentManager.get("org.sakaiproject.assignment.api.model.AssignmentSupplementItemService"); } if (m_eventTrackingService == null) { m_eventTrackingService = (EventTrackingService) ComponentManager.get("org.sakaiproject.event.api.EventTrackingService"); } if (m_notificationService == null) { m_notificationService = (NotificationService) ComponentManager.get("org.sakaiproject.event.api.NotificationService"); } if (m_securityService == null) { m_securityService = (SecurityService) ComponentManager.get("org.sakaiproject.authz.api.SecurityService"); } if(assignmentPeerAssessmentService == null){ assignmentPeerAssessmentService = (AssignmentPeerAssessmentService) ComponentManager.get("org.sakaiproject.assignment.api.AssignmentPeerAssessmentService"); } String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if if (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) == null) { String propValue = null; // save the option into tool configuration try { Site site = SiteService.getSite(siteId); ToolConfiguration tc=site.getToolForCommonId(ASSIGNMENT_TOOL_ID); propValue = tc.getPlacementConfig().getProperty(SUBMISSIONS_SEARCH_ONLY); } catch (IdUnusedException e) { M_log.warn(this + ":init() Cannot find site with id " + siteId); } state.setAttribute(SUBMISSIONS_SEARCH_ONLY, propValue == null ? Boolean.FALSE:Boolean.valueOf(propValue)); } /** The calendar tool */ if (state.getAttribute(CALENDAR_TOOL_EXIST) == null) { CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); if (cService != null){ if (!siteHasTool(siteId, cService.getToolId())) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(CALENDAR); } else { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(CALENDAR) == null ) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { state.removeAttribute(CALENDAR); M_log.info(this + ":initState No calendar found for site " + siteId + " " + e.getMessage()); } catch (PermissionException e) { state.removeAttribute(CALENDAR); M_log.info(this + ":initState No permission to get the calender. " + e.getMessage()); } catch (Exception ex) { state.removeAttribute(CALENDAR); M_log.info(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage()); } } } } } } /** Additional Calendar tool */ // Setting this attribute to true or false currently makes no difference as it is never checked for true or false. // true: means the additional calendar is ready to be used with assignments. // false: means the tool may not be deployed at all or may be at the site but not ready to be used. if (state.getAttribute(ADDITIONAL_CALENDAR_TOOL_READY) == null) { // Get a handle to the Google calendar service class from the Component Manager. It will be null if not deployed. CalendarService additionalCalendarService = (CalendarService)ComponentManager.get(CalendarService.ADDITIONAL_CALENDAR); if (additionalCalendarService != null){ // If tool is not used/used on this site, we set the appropriate flag in the state. if (!siteHasTool(siteId, additionalCalendarService.getToolId())) { state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.FALSE); state.removeAttribute(ADDITIONAL_CALENDAR); } else { // Also check that this calendar has been fully created (initialized) in the additional calendar service. if (additionalCalendarService.isCalendarToolInitialized(siteId)){ state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.TRUE); // Alternate calendar ready for events. if (state.getAttribute(ADDITIONAL_CALENDAR) == null ) { try { state.setAttribute(ADDITIONAL_CALENDAR, additionalCalendarService.getCalendar(null)); } catch (IdUnusedException e) { M_log.info(this + ":initState No calendar found for site " + siteId + " " + e.getMessage()); } catch (PermissionException e) { M_log.info(this + ":initState No permission to get the calendar. " + e.getMessage()); } } } else{ state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.FALSE); // Tool on site but alternate calendar not yet created. } } } else{ state.setAttribute(ADDITIONAL_CALENDAR_TOOL_READY, Boolean.FALSE); // Tool not deployed on the server. } } /** The Announcement tool */ if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null) { if (!siteHasTool(siteId, "sakai.announcements")) { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } else { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null ) { /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { M_log.warn(this + ":initState No announcement channel found. " + e.getMessage()); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } catch (PermissionException e) { M_log.warn(this + ":initState No permission to annoucement channel. " + e.getMessage()); } catch (Exception ex) { M_log.warn(this + ":initState Assignment : Action : init state : calendar exception : " + ex.getMessage()); } } } } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null || ((String) state.getAttribute(STATE_CONTEXT_STRING)).length() == 0) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { setDefaultSort(state); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new ConcurrentSkipListSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, Boolean.valueOf(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, Integer.valueOf(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtils.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, Boolean.valueOf(withGrades)); } // whether to display the number of submission/ungraded submission column // default to show if (state.getAttribute(SHOW_NUMBER_SUBMISSION_COLUMN) == null) { PortletConfig config = portlet.getPortletConfig(); String value = StringUtils.trimToNull(config.getInitParameter(SHOW_NUMBER_SUBMISSION_COLUMN)); if (value == null) { value = Boolean.TRUE.toString(); } state.setAttribute(SHOW_NUMBER_SUBMISSION_COLUMN, Boolean.valueOf(value)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, Integer.valueOf(GregorianCalendar.getInstance().get(GregorianCalendar.YEAR)-4)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, Integer.valueOf(GregorianCalendar.getInstance().get(GregorianCalendar.YEAR)+4)); } } // initState /** * whether the site has the specified tool * @param siteId * @return */ private boolean siteHasTool(String siteId, String toolId) { boolean rv = false; try { Site s = SiteService.getSite(siteId); if (s.getToolForCommonId(toolId) != null) { rv = true; } } catch (Exception e) { M_log.warn(this + "siteHasTool" + e.getMessage() + siteId); } return rv; } /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * initialize assignment attributes * @param state */ private void initializeAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the visible time to be 12:00 PM if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { state.setAttribute(NEW_ASSIGNMENT_VISIBLEMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEHOUR, Integer.valueOf(12)); state.setAttribute(NEW_ASSIGNMENT_VISIBLEMIN, Integer.valueOf(0)); } // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, Integer.valueOf(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, Integer.valueOf(0)); // set the all purpose item release time state.setAttribute(ALLPURPOSE_RELEASE_MONTH, Integer.valueOf(month)); state.setAttribute(ALLPURPOSE_RELEASE_DAY, Integer.valueOf(day)); state.setAttribute(ALLPURPOSE_RELEASE_YEAR, Integer.valueOf(year)); state.setAttribute(ALLPURPOSE_RELEASE_HOUR, Integer.valueOf(12)); state.setAttribute(ALLPURPOSE_RELEASE_MIN, Integer.valueOf(0)); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, Integer.valueOf(17)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, Integer.valueOf(0)); // set the resubmit time to be the same as due time state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, Integer.valueOf(month)); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, Integer.valueOf(day)); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, Integer.valueOf(year)); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, Integer.valueOf(17)); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, Integer.valueOf(0)); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, Integer.valueOf(1)); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, Integer.valueOf(17)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, Integer.valueOf(0)); // set the all purpose retract time state.setAttribute(ALLPURPOSE_RETRACT_MONTH, Integer.valueOf(month)); state.setAttribute(ALLPURPOSE_RETRACT_DAY, Integer.valueOf(day)); state.setAttribute(ALLPURPOSE_RETRACT_YEAR, Integer.valueOf(year)); state.setAttribute(ALLPURPOSE_RETRACT_HOUR, Integer.valueOf(17)); state.setAttribute(ALLPURPOSE_RETRACT_MIN, Integer.valueOf(0)); // set the peer period time to be 10 mins after accept until date state.setAttribute(NEW_ASSIGNMENT_PEERPERIODMONTH, Integer.valueOf(month)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODDAY, Integer.valueOf(day)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODYEAR, Integer.valueOf(year)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODHOUR, Integer.valueOf(17)); state.setAttribute(NEW_ASSIGNMENT_PEERPERIODMIN, Integer.valueOf(10)); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL, Boolean.TRUE.toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS, Boolean.TRUE.toString()); state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, 1); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, Integer.valueOf(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (Integer.valueOf(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.removeAttribute(NEW_ASSIGNMENT_RANGE); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); // remove the resubmit number state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // remove the supplement attributes state.removeAttribute(MODELANSWER); state.removeAttribute(MODELANSWER_TEXT); state.removeAttribute(MODELANSWER_SHOWTO); state.removeAttribute(MODELANSWER_ATTACHMENTS); state.removeAttribute(NOTE); state.removeAttribute(NOTE_TEXT); state.removeAttribute(NOTE_SHAREWITH); state.removeAttribute(ALLPURPOSE); state.removeAttribute(ALLPURPOSE_TITLE); state.removeAttribute(ALLPURPOSE_TEXT); state.removeAttribute(ALLPURPOSE_HIDE); state.removeAttribute(ALLPURPOSE_SHOW_FROM); state.removeAttribute(ALLPURPOSE_SHOW_TO); state.removeAttribute(ALLPURPOSE_RELEASE_DATE); state.removeAttribute(ALLPURPOSE_RETRACT_DATE); state.removeAttribute(ALLPURPOSE_ACCESS); state.removeAttribute(ALLPURPOSE_ATTACHMENTS); // SAK-17606 state.removeAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING); } // resetNewAssignment /** * reset the attributes for assignment */ private void resetAssignment(SessionState state) { state.removeAttribute(NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_OPENMONTH); state.removeAttribute(NEW_ASSIGNMENT_OPENDAY); state.removeAttribute(NEW_ASSIGNMENT_OPENYEAR); state.removeAttribute(NEW_ASSIGNMENT_OPENHOUR); state.removeAttribute(NEW_ASSIGNMENT_OPENMIN); state.removeAttribute(ALLPURPOSE_RELEASE_MONTH); state.removeAttribute(ALLPURPOSE_RELEASE_DAY); state.removeAttribute(ALLPURPOSE_RELEASE_YEAR); state.removeAttribute(ALLPURPOSE_RELEASE_HOUR); state.removeAttribute(ALLPURPOSE_RELEASE_MIN); state.removeAttribute(NEW_ASSIGNMENT_DUEMONTH); state.removeAttribute(NEW_ASSIGNMENT_DUEDAY); state.removeAttribute(NEW_ASSIGNMENT_DUEYEAR); state.removeAttribute(NEW_ASSIGNMENT_DUEHOUR); state.removeAttribute(NEW_ASSIGNMENT_DUEMIN); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEMONTH); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEDAY); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEYEAR); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEHOUR); state.removeAttribute(NEW_ASSIGNMENT_VISIBLEMIN); state.removeAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE); state.removeAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); state.removeAttribute(NEW_ASSIGNMENT_CLOSEMONTH); state.removeAttribute(NEW_ASSIGNMENT_CLOSEDAY); state.removeAttribute(NEW_ASSIGNMENT_CLOSEYEAR); state.removeAttribute(NEW_ASSIGNMENT_CLOSEHOUR); state.removeAttribute(NEW_ASSIGNMENT_CLOSEMIN); // set the all purpose retract time state.removeAttribute(ALLPURPOSE_RETRACT_MONTH); state.removeAttribute(ALLPURPOSE_RETRACT_DAY); state.removeAttribute(ALLPURPOSE_RETRACT_YEAR); state.removeAttribute(ALLPURPOSE_RETRACT_HOUR); state.removeAttribute(ALLPURPOSE_RETRACT_MIN); state.removeAttribute(NEW_ASSIGNMENT_SECTION); state.removeAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE); state.removeAttribute(NEW_ASSIGNMENT_GRADE_TYPE); state.removeAttribute(NEW_ASSIGNMENT_GRADE_POINTS); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION); state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); state.removeAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); state.removeAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE); state.removeAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.removeAttribute(NEW_ASSIGNMENT_ATTACHMENT); state.removeAttribute(NEW_ASSIGNMENT_FOCUS); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); state.removeAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.removeAttribute(NEW_ASSIGNMENT_RANGE); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); // remove the resubmit number state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // remove the supplement attributes state.removeAttribute(MODELANSWER); state.removeAttribute(MODELANSWER_TEXT); state.removeAttribute(MODELANSWER_SHOWTO); state.removeAttribute(MODELANSWER_ATTACHMENTS); state.removeAttribute(NOTE); state.removeAttribute(NOTE_TEXT); state.removeAttribute(NOTE_SHAREWITH); state.removeAttribute(ALLPURPOSE); state.removeAttribute(ALLPURPOSE_TITLE); state.removeAttribute(ALLPURPOSE_TEXT); state.removeAttribute(ALLPURPOSE_HIDE); state.removeAttribute(ALLPURPOSE_SHOW_FROM); state.removeAttribute(ALLPURPOSE_SHOW_TO); state.removeAttribute(ALLPURPOSE_RELEASE_DATE); state.removeAttribute(ALLPURPOSE_RETRACT_DATE); state.removeAttribute(ALLPURPOSE_ACCESS); state.removeAttribute(ALLPURPOSE_ATTACHMENTS); //revmoew peer assessment settings state.removeAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODMONTH); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODDAY); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODYEAR); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODHOUR); state.removeAttribute(NEW_ASSIGNMENT_PEERPERIODMIN); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS); state.removeAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); // remove content-review setting state.removeAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); state.removeAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE); state.removeAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } // resetNewAssignment /** * construct a HashMap using integer as the key and three character string of the month as the value */ private HashMap monthTable() { HashMap n = new HashMap(); n.put(Integer.valueOf(1), rb.getString("jan")); n.put(Integer.valueOf(2), rb.getString("feb")); n.put(Integer.valueOf(3), rb.getString("mar")); n.put(Integer.valueOf(4), rb.getString("apr")); n.put(Integer.valueOf(5), rb.getString("may")); n.put(Integer.valueOf(6), rb.getString("jun")); n.put(Integer.valueOf(7), rb.getString("jul")); n.put(Integer.valueOf(8), rb.getString("aug")); n.put(Integer.valueOf(9), rb.getString("sep")); n.put(Integer.valueOf(10), rb.getString("oct")); n.put(Integer.valueOf(11), rb.getString("nov")); n.put(Integer.valueOf(12), rb.getString("dec")); return n; } // monthTable /** * construct a HashMap using the integer as the key and grade type String as the value */ private HashMap gradeTypeTable(){ HashMap gradeTypeTable = new HashMap(); gradeTypeTable.put(Integer.valueOf(1), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_NOGRADE_PROP)); gradeTypeTable.put(Integer.valueOf(2), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_LETTER_PROP)); gradeTypeTable.put(Integer.valueOf(3), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_POINTS_PROP)); gradeTypeTable.put(Integer.valueOf(4), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_PASS_FAIL_PROP)); gradeTypeTable.put(Integer.valueOf(5), rb.getString(AssignmentConstants.ASSN_GRADE_TYPE_CHECK_PROP)); return gradeTypeTable; } // gradeTypeTable /** * construct a HashMap using the integer as the key and submission type String as the value */ private HashMap submissionTypeTable(){ HashMap submissionTypeTable = new HashMap(); submissionTypeTable.put(Integer.valueOf(1), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_INLINE_PROP)); submissionTypeTable.put(Integer.valueOf(2), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_ATTACHMENTS_ONLY_PROP)); submissionTypeTable.put(Integer.valueOf(3), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_INLINE_AND_ATTACHMENTS_PROP)); submissionTypeTable.put(Integer.valueOf(4), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_NON_ELECTRONIC_PROP)); submissionTypeTable.put(Integer.valueOf(5), rb.getString(AssignmentConstants.ASSN_SUBMISSION_TYPE_SINGLE_ATTACHMENT_PROP)); return submissionTypeTable; } // submissionTypeTable /** * Add the list of categories from the gradebook tool * construct a HashMap using the integer as the key and category String as the value * @return */ private HashMap<Long, String> categoryTable() { boolean gradebookExists = isGradebookDefined(); HashMap<Long, String> catTable = new HashMap<Long, String>(); if (gradebookExists) { GradebookService g = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); List<CategoryDefinition> categoryDefinitions = g.getCategoryDefinitions(gradebookUid); catTable.put(Long.valueOf(-1), rb.getString("grading.unassigned")); for (CategoryDefinition category: categoryDefinitions) { catTable.put(category.getId(), category.getName()); } } return catTable; } // categoryTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); //for content review default is desc if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) asc = Boolean.FALSE.toString(); else asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the SubmitterSubmission clas */ public class SubmitterSubmission { /** * the User object */ User m_user = null; /** * is the Submitter in more than one group */ Boolean m_multi_group = false; /** * the Group */ Group m_group = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; /** * the AssignmentSubmission object */ User m_submittedBy = null; public SubmitterSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } public SubmitterSubmission(Group g, AssignmentSubmission s) { m_group = g; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } public void setSubmittedBy(User submittedBy) { m_submittedBy = submittedBy; } /** * Returns the User object of the submitter, * if null, the user submitted the assignment himself. */ public User getSubmittedBy() { return m_submittedBy; } public Group getGroup() { return m_group; } public void setGroup(Group _group) { m_group = _group; } public Boolean getIsMultiGroup() { return m_multi_group; } public void setMultiGroup(Boolean _multi) { m_multi_group = _multi; } public String getGradeForUser(String id) { String grade = getSubmission() == null ? null: getSubmission().getGradeForUser(id); if (grade != null && getSubmission().getAssignment().getContent() != null && getSubmission().getAssignment().getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (grade.length() > 0 && !"0".equals(grade)) { try { Integer.parseInt(grade); // if point grade, display the grade with one decimal place return grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (Exception e) { return grade; } } else { return StringUtil.trimToZero(grade); } } return grade; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { Collator collator = null; /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; // true if users should be compared by anonymous submitter id rather than other identifiers boolean m_anon = false; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { this(state, criteria, asc, null); } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; try { collator= new RuleBasedCollator(((RuleBasedCollator)Collator.getInstance()).getRules().replaceAll("<'\u005f'", "<' '<'\u005f'")); } catch (ParseException e) { // error with init RuleBasedCollator with rules // use the default Collator collator = Collator.getInstance(); M_log.warn(this + " AssignmentComparator cannot init RuleBasedCollator. Will use the default Collator instead. " + e); } } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group Group _aGroup = site.getGroup((String) k.next()); if (_aGroup != null) rv = rv.concat(_aGroup.getTitle()); } } catch (Exception ignore) { M_log.warn(this + ":getAssignmentRange" + ignore.getMessage()); } } return rv; } // getAssignmentRange public void setAnon(boolean value) { m_anon = value; } /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; if (m_criteria == null) { m_criteria = SORTED_BY_DEFAULT; } /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else { if (t1.equals(t2)) { t1 = ((Assignment) o1).getTimeCreated(); t2 = ((Assignment) o2).getTimeCreated(); } else if (t1.before(t2)) { result = 1; } else { result = -1; } } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { if (AssignmentService.allowAddAssignment(((Assignment) o1).getContext())) { // comparing assignment status result = compareString(((Assignment) o1).getStatus(), ((Assignment) o2).getStatus()); } else { // comparing submission status AssignmentSubmission s1 = findAssignmentSubmission((Assignment) o1); AssignmentSubmission s2 = findAssignmentSubmission((Assignment) o2); result = s1==null ? 1 : s2==null? -1:compareString(s1.getStatus(), s2.getStatus()); } } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Time t1,t2; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); t1 = submission1.getTimeSubmitted(); if (t1!=null) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); t2 = submission2.getTimeSubmitted(); if (t2!=null) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Time t1,t2; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); t1 = submission1.getTimeSubmitted(); if (t1!=null && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); t2 = submission2.getTimeSubmitted(); if (t2!=null && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_GRADE) || m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { AssignmentSubmission submission1 = getSubmission(((Assignment) o1).getId(), m_user, "compare", null); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = getSubmission(((Assignment) o2).getId(), m_user, "compare", null); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = compareString(grade1, grade2); } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = compareString(maxGrade1, maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = compareString(factor1, factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (Integer.valueOf(score1)).intValue() > (Integer.valueOf(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null || (u1.getUser() == null && u1.getGroup() == null) || (u2.getUser() == null && u2.getGroup() == null) ) { result = 1; } else if (m_anon) { String anon1 = u1.getSubmission().getAnonymousSubmissionId(); String anon2 = u2.getSubmission().getAnonymousSubmissionId(); result = compareString(anon1, anon2); } else { String lName1 = u1.getUser() == null ? u1.getGroup().getTitle(): u1.getUser().getSortName(); String lName2 = u2.getUser() == null ? u2.getGroup().getTitle(): u2.getUser().getSortName(); result = compareString(lName1, lName2); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = s1.getStatus(); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = s2.getStatus(); } } result = compareString(status1, status2); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if ("".equals(grade1)) { result = -1; } else if ("".equals(grade2)) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status SubmitterSubmission u1 = (SubmitterSubmission) o1; SubmitterSubmission u2 = (SubmitterSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (Boolean.valueOf(s1.getGradeReleased())).toString(); String released2 = (Boolean.valueOf(s2.getGradeReleased())).toString(); result = compareString(released1, released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name AssignmentSubmission _a1 = (AssignmentSubmission)o1; AssignmentSubmission _a2 = (AssignmentSubmission)o2; String _s1 = ""; String _s2 = ""; if (_a1.getAssignment().isGroup()) { try { Site site = SiteService.getSite(_a1.getAssignment().getContext()); _s1 = site.getGroup(_a1.getSubmitterId()).getTitle(); } catch (Throwable _dfef) { } } else { try { _s1 = UserDirectoryService.getUser(_a1.getSubmitterId()).getSortName(); } catch (UserNotDefinedException e) { M_log.warn(this + ": cannot find user id=" + _a1.getSubmitterId() + e.getMessage() + ""); } } if (_a2.getAssignment().isGroup()) { try { Site site = SiteService.getSite(_a2.getAssignment().getContext()); _s2 = site.getGroup(_a2.getSubmitterId()).getTitle(); } catch (Throwable _dfef) { // TODO empty exception block } } else { try { _s2 = UserDirectoryService.getUser(_a2.getSubmitterId()).getSortName(); } catch (UserNotDefinedException e) { M_log.warn(this + ": cannot find user id=" + _a2.getSubmitterId() + e.getMessage() + ""); } } result = _s1.compareTo(_s2); //compareString(submitters1, submitters2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status result = compareString(((AssignmentSubmission) o1).getStatus(), ((AssignmentSubmission) o2).getStatus()); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if ("".equals(grade1)) { result = -1; } else if ("".equals(grade2)) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if ("".equals(grade1)) { result = -1; } else if ("".equals(grade2)) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { M_log.warn(this + ":AssignmentComparator compare" + e.getMessage()); // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (Boolean.valueOf(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (Boolean.valueOf(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = compareString(released1, released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = compareString(title1, title2); } /*************** sort user by sort name ***************/ else if (m_criteria.equals(SORTED_USER_BY_SORTNAME)) { // sort by user's sort name String name1 = ((User) o1).getSortName(); String name2 = ((User) o2).getSortName(); result = compareString(name1, name2); } // sort ascending or descending if (!Boolean.valueOf(m_asc)) { result = -result; } return result; } /** * returns AssignmentSubmission object for given assignment by current user * @param a * @return */ protected AssignmentSubmission findAssignmentSubmission (Assignment a) { AssignmentSubmission rv = null; try { rv = AssignmentService.getSubmission(a.getReference(), UserDirectoryService.getCurrentUser()); } catch (IdUnusedException e) { M_log.warn(this + "compare: " + rb.getFormattedMessage("cannotfin_assignment", new Object[]{a.getReference()})); } catch (PermissionException e) { } return rv; } /** * Compare two strings as double values. Deal with the case when either of the strings cannot be parsed as double value. * @param grade1 * @param grade2 * @return */ private int compareDouble(String grade1, String grade2) { int result; try { result = (Double.valueOf(grade1)).doubleValue() > (Double.valueOf(grade2)).doubleValue() ? 1 : -1; } catch (Exception formatException) { // in case either grade1 or grade2 cannot be parsed as Double result = compareString(grade1, grade2); M_log.warn(this + ":AssignmentComparator compareDouble " + formatException.getMessage()); } return result; } // compareDouble private int compareString(String s1, String s2) { int result; if (s1 == null && s2 == null) { result = 0; } else if (s2 == null) { result = 1; } else if (s1 == null) { result = -1; } else { result = collator.compare(s1.toLowerCase(), s2.toLowerCase()); } return result; } /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("gen.nograd"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // ... pass the resource loader object ResourceLoader pRb = new ResourceLoader("permissions"); HashMap<String, String> pRbValues = new HashMap<String, String>(); for (Iterator<Map.Entry<String, Object>> iEntries = pRb.entrySet().iterator();iEntries.hasNext();) { Map.Entry<String, Object> entry = iEntries.next(); pRbValues.put(entry.getKey(), (String) entry.getValue()); } state.setAttribute("permissionDescriptions", pRbValues); String groupAware = ToolManager.getCurrentTool().getRegisteredConfig().getProperty("groupAware"); state.setAttribute("groupAware", groupAware != null?Boolean.valueOf(groupAware):Boolean.FALSE); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to List */ private List iterator_to_list(Iterator l) { List v = new ArrayList(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_list /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new ArrayList(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (MODE_LIST_ASSIGNMENTS.equals(mode)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || (!allowAddAssignment && AssignmentService.allowAddSubmission((String) state .getAttribute(STATE_CONTEXT_STRING)))) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || "".equals(deleted)) { // show not deleted assignments Time openTime = a.getOpenTime(); Time visibleTime = a.getVisibleTime(); if ( ( (openTime != null && currentTime.after(openTime))|| (visibleTime != null && currentTime.after(visibleTime)) ) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) && getSubmission(a.getReference(), (User) state.getAttribute(STATE_USER), "sizeResources", state) != null) { // and those deleted but not non-electronic assignments but the user has made submissions to them returnResources.add(a); } } } else { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1)); } else if (MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode)) { returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode)) { initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); Boolean has_multiple_groups_for_user = false; List submissions = new ArrayList(); List assignments = iterator_to_list(AssignmentService.getAssignmentsForContext(contextString)); if (assignments.size() > 0) { try { // get the site object first Site site = SiteService.getSite(contextString); for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, a.getReference(), contextString); Collection<String> _dupUsers = new ArrayList<String>(); if (a.isGroup()) { _dupUsers = usersInMultipleGroups(a, true); } //get the list of users which are allowed to grade this assignment List allowGradeAssignmentUsers = AssignmentService.allowGradeAssignmentUsers(a.getReference()); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || "".equals(deleted)) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference())) { try { List assignmentSubmissions = AssignmentService.getSubmissions(a); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s.getTimeReturned()))))) { //If the group search is null or if it contains the group if (submitterIds.contains(s.getSubmitterId())){ if (a.isGroup()) { User[] _users = s.getSubmitters(); for (int m=0; _users != null && m < _users.length; m++) { Member member = site.getMember(_users[m].getId()); if (member != null && member.isActive()) { // only include the active student submission // conder TODO create temporary submissions SubmitterSubmission _new_sub = new SubmitterSubmission(_users[m], s); _new_sub.setGroup(site.getGroup(s.getSubmitterId())); if (_dupUsers.size() > 0 && _dupUsers.contains(_users[m].getId())) { _new_sub.setMultiGroup(true); has_multiple_groups_for_user = true; } submissions.add(_new_sub); } } } else { if (s.getSubmitterId() != null && !allowGradeAssignmentUsers.contains(s.getSubmitterId())) { // find whether the submitter is still an active member of the site Member member = site.getMember(s.getSubmitterId()); if(member != null && member.isActive()) { // only include the active student submission try { SubmitterSubmission _new_sub = new SubmitterSubmission(UserDirectoryService.getUser(s.getSubmitterId()), s); submissions.add(_new_sub); } catch (UserNotDefinedException e) { M_log.warn(this + ":sizeResources cannot find user id=" + s.getSubmitterId() + e.getMessage() + ""); } } } } } } // if-else } } catch (Exception e) { M_log.warn(this + ":sizeResources " + e.getMessage()); } } } if (has_multiple_groups_for_user) { addAlert(state, rb.getString("group.user.multiple.error")); } } catch (IdUnusedException idUnusedException) { M_log.warn(this + ":sizeResources " + idUnusedException.getMessage() + " site id=" + contextString); } } // end if returnResources = submissions; } else if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode)) { initViewSubmissionListOption(state); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); String aRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); try { if (AssignmentService.getAssignment(aRef).isGroup()) { Collection<Group> submitterGroups = AssignmentService.getSubmitterGroupList("false", allOrOneGroup, "", aRef, contextString); // construct the group-submission list if (submitterGroups != null && !submitterGroups.isEmpty()) { for (Iterator<Group> iSubmitterGroupsIterator = submitterGroups.iterator(); iSubmitterGroupsIterator.hasNext();) { Group gId = iSubmitterGroupsIterator.next(); // Allow sections to be used for group assigments - https://jira.sakaiproject.org/browse/SAK-22425 //if (gId.getProperties().get(GROUP_SECTION_PROPERTY) == null) { try { AssignmentSubmission sub = AssignmentService.getSubmission(aRef, gId.getId()); returnResources.add(new SubmitterSubmission(gId, sub)); // UserSubmission accepts either User or Group } catch (IdUnusedException subIdException) { M_log.warn(this + ".sizeResources: looking for submission for unused assignment id " + aRef + subIdException.getMessage()); } catch (PermissionException subPerException) { M_log.warn(this + ".sizeResources: cannot have permission to access submission of assignment " + aRef + " of group " + gId.getId()); } //} } } } else { //List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); Map<User, AssignmentSubmission> submitters = AssignmentService.getSubmitterMap(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); // construct the user-submission list for (User u : submitters.keySet()) { String uId = u.getId(); AssignmentSubmission sub = submitters.get(u); SubmitterSubmission us = new SubmitterSubmission(u, sub); String submittedById = (String)sub.getProperties().get(AssignmentSubmission.SUBMITTER_USER_ID); if ( submittedById != null) { try { us.setSubmittedBy(UserDirectoryService.getUser(submittedById)); } catch (UserNotDefinedException ex1) { M_log.warn(this + ":sizeResources cannot find submitter id=" + uId + ex1.getMessage()); } } returnResources.add(us); } } } catch (PermissionException aPerException) { M_log.warn(":getSubmitterGroupList: Not allowed to get assignment " + aRef + " " + aPerException.getMessage()); } catch (org.sakaiproject.exception.IdUnusedException e) { M_log.warn(this + ":sizeResources cannot find assignment " + e.getMessage() + ""); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode) && (sort == null || !sort.startsWith("sorted_grade_submission_by"))) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(mode) && (sort == null || sort.startsWith("sorted_submission_by"))) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(mode)) { AssignmentComparator ac = new AssignmentComparator(state, sort, ascending); // figure out if we have to sort by anonymous id if (SORTED_GRADE_SUBMISSION_BY_LASTNAME.equals(sort) && (MODE_INSTRUCTOR_GRADE_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode))) { String aRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { Assignment assignment = AssignmentService.getAssignment(aRef); if (assignment != null) { ResourceProperties props = assignment.getProperties(); if (props != null) { ac.setAnon(props.getBooleanProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING)); } } } catch (IdUnusedException iue) { // ignore, continue with default sort } catch (PermissionException pe) { // ignore, continue with default sort } catch (EntityPropertyNotDefinedException epnde) { // ignore, continue with default sort } catch (EntityPropertyTypeException epte) { // ignore, continue with default sort } } try { Collections.sort(returnResources, ac); } catch (Exception e) { // log exception during sorting for helping debugging M_log.warn(this + ":sizeResources mode=" + mode + " sort=" + sort + " ascending=" + ascending + " " + e.getStackTrace()); } } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (MODE_LIST_ASSIGNMENTS.equals(viewMode)) { doList_assignments(data); } else if (MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT.equals(viewMode)) { doView_students_assignment(data); } else if (MODE_INSTRUCTOR_REPORT_SUBMISSIONS.equals(viewMode)) { doReport_submissions(data); } else if (MODE_STUDENT_VIEW.equals(viewMode)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade for point based type * returns a double value in a string from the localized input */ private String validPointGrade(SessionState state, String grade) { if (grade != null && !"".equals(grade)) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; // only the right decimal separator is allowed and no other grouping separator if ((",".equals(decSeparator) && grade.indexOf(".") != -1) || (".".equals(decSeparator) && grade.indexOf(",") != -1) || grade.indexOf(" ") != -1) { addAlert(state, rb.getString("plesuse1")); return grade; } // parse grade from localized number format int index = grade.indexOf(decSeparator); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!decSeparator.equals(grade)) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = grade.endsWith(decSeparator) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { nbFormat.parse(gradeString); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); alertInvalidPoint(state, gradeString); } } catch (ParseException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); addAlert(state, rb.getString("plesuse1")); } } } else { // grade is decSeparator addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { nbFormat.parse(gradeString); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); alertInvalidPoint(state, gradeString); } } catch (ParseException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); addAlert(state, rb.getString("plesuse1")); } } } } return grade; } /** * get the right number format based on local * @return */ private NumberFormat getNumberFormat() { // get localized number format NumberFormat nbFormat = NumberFormat.getInstance(); try { Locale locale = null; ResourceLoader rb = new ResourceLoader(); locale = rb.getLocale(); nbFormat = NumberFormat.getNumberInstance(locale); } catch (Exception e) { M_log.warn("Error while retrieving local number format, using default ", e); } return nbFormat; } // validPointGrade /** * valid grade for point based type */ private void validLetterGrade(SessionState state, String grade) { String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-"; boolean invalid = false; if (grade != null) { grade = grade.toUpperCase(); for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1) { invalid = true; } } if (invalid) { // -------- SAK-24199 (SAKU-274) by Shoji Kajita addAlert(state, rb.getFormattedMessage("plesuse0", new Object []{grade})); // -------- } } } private void alertInvalidPoint(SessionState state, String grade) { NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, rb.getFormattedMessage("plesuse4", new Object[]{grade.substring(0, grade.length()-1) + decSeparator + grade.substring(grade.length()-1), maxInt + decSeparator + maxDec})); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { NumberFormat nbFormat = getNumberFormat(); nbFormat.setMaximumFractionDigits(1); nbFormat.setMinimumFractionDigits(1); nbFormat.setGroupingUsed(false); DecimalFormat dcformat = (DecimalFormat) nbFormat; String decSeparator = dcformat.getDecimalFormatSymbols().getDecimalSeparator() + ""; if (grade.indexOf(decSeparator) != -1) { if (grade.startsWith(decSeparator)) { grade = "0".concat(grade); } else if (grade.endsWith(decSeparator)) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + decSeparator + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { // alert alertInvalidPoint(state, grade); M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage()); } } try { // show grade in localized number format Double dblGrade = dcformat.parse(grade).doubleValue(); grade = nbFormat.format(dblGrade); } catch (Exception e) { // alert alertInvalidPoint(state, grade); M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage()); } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { NumberFormat nbFormat = (DecimalFormat) getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = dcFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""; point = validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf(decSeparator); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if ("00".equals(point)) { point = "0"; } } } if (StringUtils.trimToNull(point) != null) { try { point = Integer.valueOf(point).toString(); } catch (Exception e) { M_log.warn(this + " scalePointGrade: cannot parse " + point + " into integer. " + e.getMessage()); } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuilder alertMsg = new StringBuilder(); boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuilder buf = new StringBuilder(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = true; // so that grading isn't held up by formatting errors buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuilder buf = new StringBuilder(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode) || MODE_STUDENT_PREVIEW_SUBMISSION.equals(mode) || MODE_STUDENT_VIEW_GRADE.equals(mode) || MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_DELETE_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode) || MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION.equals(mode)|| MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_VIEW_ASSIGNMENT.equals(mode) || MODE_INSTRUCTOR_REORDER_ASSIGNMENT.equals(mode)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (MODE_STUDENT_VIEW_SUBMISSION.equals(mode)) { // save submit inputs saveSubmitInputs(state, params); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT.equals(mode)) { setNewAssignmentParameters(data, false); } else if (MODE_INSTRUCTOR_GRADE_SUBMISSION.equals(mode)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if ("cancel".equals(option)) { // cancel doCancel_show_submission(data); } else if ("preview".equals(option)) { // preview doPreview_submission(data); } else if ("save".equals(option)) { // save draft doSave_submission(data); } else if ("post".equals(option)) { // post doPost_submission(data); } else if ("revise".equals(option)) { // done preview doDone_preview_submission(data); } else if ("attach".equals(option)) { // attach ToolSession toolSession = SessionManager.getCurrentToolSession(); String userId = SessionManager.getCurrentSessionUserId(); String siteId = SiteService.getUserSiteId(userId); String collectionId = m_contentHostingService.getSiteCollection(siteId); toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId); doAttachments(data); } else if ("removeAttachment".equals(option)) { // remove selected attachment doRemove_attachment(data); } else if ("removeNewSingleUploadedFile".equals(option)) { doRemove_newSingleUploadedFile(data); } else if ("upload".equals(option)) { // upload local file doAttachUpload(data, true); } else if ("uploadSingleFile".equals(option)) { // upload single local file doAttachUpload(data, false); } } public void doRemove_attachment(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); // save submit inputs before refresh the page saveSubmitInputs(state, params); String removeAttachmentId = params.getString("currentAttachment"); List attachments = state.getAttribute(ATTACHMENTS) == null?null:((List) state.getAttribute(ATTACHMENTS)).isEmpty()?null:(List) state.getAttribute(ATTACHMENTS); if (attachments != null) { Reference found = null; for(Object attachment : attachments) { if (((Reference) attachment).getId().equals(removeAttachmentId)) { found = (Reference) attachment; break; } } if (found != null) { attachments.remove(found); // refresh state variable state.setAttribute(ATTACHMENTS, attachments); } } } public void doRemove_newSingleUploadedFile(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid()); state.removeAttribute("newSingleUploadedFile"); } /** * return returns all groups in a site * @param contextString * @param aRef * @return */ protected Collection getAllGroupsInSite(String contextString) { Collection groups = new ArrayList(); try { Site site = SiteService.getSite(contextString); // any group in the site? groups = site.getGroups(); } catch (IdUnusedException e) { // TODO Auto-generated catch block M_log.info("Problem getting groups for site:"+e.getMessage()); } return groups; } /** * return list of submission object based on the group filter/search result * @param state * @param aRef * @return */ protected List<AssignmentSubmission> getFilteredSubmitters(SessionState state, String aRef) { List<AssignmentSubmission> rv = new ArrayList<AssignmentSubmission>(); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); String search = (String) state.getAttribute(VIEW_SUBMISSION_SEARCH); Boolean searchFilterOnly = (state.getAttribute(SUBMISSIONS_SEARCH_ONLY) != null && ((Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)) ? Boolean.TRUE:Boolean.FALSE); //List<String> submitterIds = AssignmentService.getSubmitterIdList(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); Map<User, AssignmentSubmission> submitters = AssignmentService.getSubmitterMap(searchFilterOnly.toString(), allOrOneGroup, search, aRef, contextString); // construct the user-submission list for (AssignmentSubmission sub : submitters.values()) { if (!rv.contains(sub)) rv.add(sub); } return rv; } /** * Set default score for all ungraded non electronic submissions * @param data */ public void doSet_defaultNotGradedNonElectronicScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtils.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); // record the default grade setting for no-submission AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); } Assignment a = getAssignment(assignmentId, "doSet_defaultNotGradedNonElectronicScore", state); if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { M_log.warn(this + ":setDefaultNotGradedNonElectronicScore " + e.getMessage()); alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List submissions = getFilteredSubmitters(state, a.getReference()); for (int i = 0; i<submissions.size(); i++) { // get the submission object AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i); if (submission.getSubmitted() && !submission.getGraded()) { String sRef = submission.getReference(); // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = editSubmission(sRef, "doSet_defaultNotGradedNonElectronicScore", state); if (sEdit != null) { sEdit.setGrade(grade); sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); AssignmentService.commitEdit(sEdit); } } } } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtils.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); // record the default grade setting for no-submission AssignmentEdit aEdit = editAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state, false); if (aEdit != null) { aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); } Assignment a = getAssignment(assignmentId, "doSet_defaultNoSubmissionScore", state); if (a != null && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[]{grade, displayGrade(state, String.valueOf(maxGrade))})); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); M_log.warn(this + ":setDefaultNoSubmissionScore " + e.getMessage()); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the submission list List submissions = getFilteredSubmitters(state, a.getReference()); for (int i = 0; i<submissions.size(); i++) { // get the submission object AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i); if (StringUtils.trimToNull(submission.getGrade()) == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state); if (sEdit != null) { sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); AssignmentService.commitEdit(sEdit); } } else if (StringUtils.trimToNull(submission.getGrade()) != null && !submission.getGraded()) { // correct the grade status if there is a grade but the graded is false AssignmentSubmissionEdit sEdit = editSubmission(submission.getReference(), "doSet_defaultNoSubmissionScore", state); if (sEdit != null) { sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); AssignmentService.commitEdit(sEdit); } } } } } /** * A utility method to determine users listed in multiple groups * eligible to submit an assignment. This is a bad situation. * Current mechanism is to error out assignments with this situation * to prevent affected groups from submitting and viewing feedback * and prevent instructors from grading or sending feedback to * affected groups until the conflict is resolved (by altering * membership or perhaps by designating a resolution). * * @param assignmentorstate * @param specify_groups * @param ingroups * @param populate_ids * @param users * @return */ public Collection<String> usersInMultipleGroups( Object assignmentorstate, // an assignment object or state object to find data boolean specify_groups, // don't use all site groups String[] ingroups, // limit to looking at specific groups boolean populate_ids, // return collection of user ids instead of message strings Collection<String> users // optional list of users to check instead of ALL site users ) { List retVal = new ArrayList(); try { Site s = null; Collection<String> _assignmentGroups = new ArrayList<String>(); for (int i=0; ingroups != null && i < ingroups.length; i++) { _assignmentGroups.add(ingroups[i]); } if (assignmentorstate instanceof SessionState) { s = SiteService.getSite((String)((SessionState)assignmentorstate).getAttribute(STATE_CONTEXT_STRING)); } else { Assignment _a = (Assignment)assignmentorstate; s = SiteService.getSite(_a.getContext()); if (_a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { specify_groups = false; } else { _assignmentGroups = _a.getGroups(); specify_groups = true; } } Iterator<String> _it = users == null ? s.getUsers().iterator(): users.iterator(); while (_it.hasNext()) { String _userRef = _it.next(); Collection<Group> _userGroups = s.getGroupsWithMember(_userRef); int _count = 0; StringBuilder _sb = new StringBuilder(); Iterator<Group> _checkGroups = _userGroups.iterator(); while (_checkGroups.hasNext()) { Group _checkGroup = _checkGroups.next(); // exclude Sections from eligible groups //if (_checkGroup.getProperties().get(GROUP_SECTION_PROPERTY) == null) { if (!specify_groups) { _count++; if (_count > 1) { _sb.append(", "); } _sb.append(_checkGroup.getTitle()); } else { if (_assignmentGroups != null) { Iterator<String> _assgnRefs = _assignmentGroups.iterator(); while (_assgnRefs.hasNext()) { String _ref = _assgnRefs.next(); Group _group = s.getGroup(_ref); if (_group != null && _group.getId().equals(_checkGroup.getId())) { _count++; if (_count > 1) { _sb.append(", "); } _sb.append(_checkGroup.getTitle()); } } } } //} } if (_count > 1) { try { User _the_user = UserDirectoryService.getUser(_userRef); /* * SAK-23697 Allow user to be in multiple groups if * no SECURE_ADD_ASSIGNMENT_SUBMISSION permission or * if user has both SECURE_ADD_ASSIGNMENT_SUBMISSION * and SECURE_GRADE_ASSIGNMENT_SUBMISSION permission (TAs and Instructors) */ if (m_securityService.unlock(_the_user,AssignmentService.SECURE_ADD_ASSIGNMENT_SUBMISSION,s.getReference()) && !m_securityService.unlock(_the_user,AssignmentService.SECURE_GRADE_ASSIGNMENT_SUBMISSION,s.getReference())) { retVal.add(populate_ids ? _the_user.getId(): _the_user.getDisplayName() + " (" + _sb.toString() + ")"); }; } catch (UserNotDefinedException _unde) { retVal.add("UNKNOWN USER (" + _sb.toString() + ")"); } } } } catch (IdUnusedException _te) { throw new IllegalStateException("Could not find the site for assignment/state "+assignmentorstate+": "+_te, _te); } return retVal; } public Collection<String> usersInMultipleGroups(Assignment _a, boolean populate_ids) { return usersInMultipleGroups(_a,false,null,populate_ids,null); } public Collection<String> usersInMultipleGroups(Assignment _a) { return usersInMultipleGroups(_a,false,null,false,null); } public Collection<String> checkForUsersInMultipleGroups( Assignment a, Collection<String> ids, SessionState state, String base_message) { Collection<String> _dupUsers = usersInMultipleGroups(a,false,null,false,ids); if (_dupUsers.size() > 0) { StringBuilder _sb = new StringBuilder(base_message + " "); Iterator<String> _it = _dupUsers.iterator(); if (_it.hasNext()) { _sb.append(_it.next()); } while (_it.hasNext()) { _sb.append(", " + _it.next()); } addAlert(state, _sb.toString()); } return _dupUsers; } public Collection<String> checkForGroupsInMultipleGroups( Assignment a, Collection<Group> groups, SessionState state, String base_message) { Collection<String> retVal = new ArrayList<String>(); if (groups != null && groups.size() > 0) { ArrayList<String> check_users = new ArrayList<String>(); Iterator<Group> it_groups = groups.iterator(); while (it_groups.hasNext()) { Group _group = it_groups.next(); Iterator<String> it_strings = _group.getUsers().iterator(); while (it_strings.hasNext()) { String _id = it_strings.next(); if (!check_users.contains(_id)) { check_users.add(_id); } } } retVal = checkForUsersInMultipleGroups(a, check_users, state, rb.getString("group.user.multiple.warning")); } return retVal; } /** * * @return */ public void doDownload_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String flow = params.getString("flow"); if ("upload".equals(flow)) { // upload doUpload_all(data); } else if ("download".equals(flow)) { // upload doDownload_all(data); } else if ("cancel".equals(flow)) { // cancel doCancel_download_upload_all(data); } } public void doDownload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } public void doUpload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = params.getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); if(fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{max_file_size_mb})); } else { String fname = StringUtils.lowerCase(fileFromUpload.getFileName()); if (!StringUtils.endsWithAny(fname, new String[] {".zip", ".sit"})) { // no file addAlert(state, rb.getString("uploadall.alert.zipFile")); } else { String contextString = ToolManager.getCurrentPlacement().getContext(); String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle(); String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); String associateGradebookAssignment = null; List<String> choices = params.getStrings("choices") != null?new ArrayList(Arrays.asList(params.getStrings("choices"))):null; if (choices == null || choices.size() == 0) { // has to choose one upload feature addAlert(state, rb.getString("uploadall.alert.choose.element")); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_GRADEFILE_FORMAT); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_WITHOUT_FOLDERS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } else { // should contain student submission text information boolean hasSubmissionText = uploadAll_readChoice(choices, "studentSubmissionText"); // should contain student submission attachment information boolean hasSubmissionAttachment = uploadAll_readChoice(choices, "studentSubmissionAttachment"); // should contain grade file boolean hasGradeFile = uploadAll_readChoice(choices, "gradeFile"); String gradeFileFormat = params.getString("gradeFileFormat"); if ("excel".equals(gradeFileFormat)) {gradeFileFormat="excel";} else {gradeFileFormat="csv";}; // inline text boolean hasFeedbackText = uploadAll_readChoice(choices, "feedbackTexts"); // comments.txt should be available boolean hasComment = uploadAll_readChoice(choices, "feedbackComments"); // feedback attachment boolean hasFeedbackAttachment = uploadAll_readChoice(choices, "feedbackAttachments"); // folders //boolean withoutFolders = params.getString("withoutFolders") != null ? params.getBoolean("withoutFolders") : false; boolean withoutFolders = uploadAll_readChoice(choices, "withoutFolders"); // SAK-19147 // release boolean releaseGrades = params.getString("release") != null ? params.getBoolean("release") : false; state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText)); state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment)); state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile)); state.setAttribute(UPLOAD_ALL_GRADEFILE_FORMAT, gradeFileFormat); state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment)); state.setAttribute(UPLOAD_ALL_WITHOUT_FOLDERS, Boolean.valueOf(withoutFolders)); state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades)); // SAK-17606 HashMap anonymousSubmissionAndEidTable = new HashMap(); // constructor the hashmap for all submission objects HashMap submissionTable = new HashMap(); List submissions = null; Assignment assignment = getAssignment(aReference, "doUpload_all", state); if (assignment != null) { associateGradebookAssignment = StringUtils.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); submissions = AssignmentService.getSubmissions(assignment); if (submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { try { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); String _eid = s.getSubmitterId(); submissionTable.put(_eid, new UploadGradeWrapper(s.getGrade(), s.getSubmittedText(), s.getFeedbackComment(), hasSubmissionAttachment?new ArrayList():s.getSubmittedAttachments(), hasFeedbackAttachment?new ArrayList():s.getFeedbackAttachments(), (s.getSubmitted() && s.getTimeSubmitted() != null)?s.getTimeSubmitted().toString():"", s.getFeedbackText())); // SAK-17606 anonymousSubmissionAndEidTable.put(s.getAnonymousSubmissionId(), _eid); } catch (Throwable _eidprob) {} } } } InputStream fileContentStream = fileFromUpload.getInputStream(); if(fileContentStream != null) { submissionTable = uploadAll_parseZipFile(state, hasSubmissionText, hasSubmissionAttachment, hasGradeFile, hasFeedbackText, hasComment, hasFeedbackAttachment, submissionTable, assignment, fileContentStream,gradeFileFormat, anonymousSubmissionAndEidTable); } if (state.getAttribute(STATE_MESSAGE) == null) { // update related submissions uploadAll_updateSubmissions(state, aReference, associateGradebookAssignment, hasSubmissionText, hasSubmissionAttachment, hasGradeFile, hasFeedbackText, hasComment, hasFeedbackAttachment, releaseGrades, submissionTable, submissions, assignment); } } } } if (state.getAttribute(STATE_MESSAGE) == null) { // go back to the list of submissions view cleanUploadAllContext(state); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } } private boolean uploadAll_readChoice(List<String> choices, String text) { return choices != null && text != null && choices.contains(text) ? true:false; } /** * parse content inside uploaded zip file * @param state * @param hasSubmissionText * @param hasSubmissionAttachment * @param hasGradeFile * @param hasFeedbackText * @param hasComment * @param hasFeedbackAttachment * @param submissionTable * @param assignment * @param fileContentStream * @return */ private HashMap uploadAll_parseZipFile(SessionState state, boolean hasSubmissionText, boolean hasSubmissionAttachment, boolean hasGradeFile, boolean hasFeedbackText, boolean hasComment, boolean hasFeedbackAttachment, HashMap submissionTable, Assignment assignment, InputStream fileContentStream,String gradeFileFormat, HashMap anonymousSubmissionAndEidTable) { // a flag value for checking whether the zip file is of proper format: // should have a grades.csv file or grades.xls if there is no user folders boolean zipHasGradeFile = false; // and if have any folder structures, those folders should be named after at least one site user (zip file could contain user names who is no longer inside the site) boolean zipHasFolder = false; boolean zipHasFolderValidUserId = false; FileOutputStream tmpFileOut = null; File tempFile = null; // as stated from UI, we expected the zip file to have structure as follows // assignment_name/user_eid/files // or assignment_name/grades.csv or assignment_name/grades.xls boolean validZipFormat = true; try { tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),""); tmpFileOut = new FileOutputStream(tempFile); writeToStream(fileContentStream, tmpFileOut); tmpFileOut.flush(); tmpFileOut.close(); ZipFile zipFile = new ZipFile(tempFile, "UTF-8"); Enumeration<ZipEntry> zipEntries = zipFile.getEntries(); ZipEntry entry; while (zipEntries.hasMoreElements() && validZipFormat) { entry = zipEntries.nextElement(); String entryName = entry.getName(); if (!entry.isDirectory() && entryName.indexOf("/.") == -1) { // SAK-17606 String anonTitle = rb.getString("grading.anonymous.title"); if (entryName.endsWith("grades.csv") || entryName.endsWith("grades.xls")) { if (hasGradeFile && entryName.endsWith("grades.csv") && "csv".equals(gradeFileFormat)) { // at least the zip file has a grade.csv zipHasGradeFile = true; // read grades.cvs from zip CSVReader reader = new CSVReader(new InputStreamReader(zipFile.getInputStream(entry))); List <String[]> lines = reader.readAll(); if (lines != null ) { for (int i = 3; i<lines.size(); i++) { String[] items = lines.get(i); if ((assignment.isGroup() && items.length > 3) || items.length > 4) { // has grade information try { String _the_eid = items[1]; if (!assignment.isGroup()) { // SAK-17606 User u = null; // check for anonymous grading if (!items[IDX_GRADES_CSV_EID].contains(anonTitle)) { u = UserDirectoryService.getUserByEid(items[IDX_GRADES_CSV_EID]); } else { // anonymous so pull the real eid out of our hash table String anonId = items[IDX_GRADES_CSV_EID]; String eid = (String) anonymousSubmissionAndEidTable.get(anonId); u = UserDirectoryService.getUserByEid(eid); } if (u == null) throw new Exception("User not found!"); _the_eid = u.getId(); } UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(_the_eid); if (w != null) { String itemString = assignment.isGroup() ? items[3]: items[4]; int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { validPointGrade(state, itemString); } // SAK-24199 - Applied patch provided with a few additional modifications. else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) { itemString = validatePassFailGradeValue(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString); submissionTable.put(_the_eid, w); } } } catch (Exception e ) { M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } } } } } //end of csv grades import //Excel file import if (hasGradeFile && entryName.endsWith("grades.xls") && "excel".equals(gradeFileFormat)) { // at least the zip file has a grade.csv zipHasGradeFile = true; // read grades.xls from zip POIFSFileSystem fsFileSystem = new POIFSFileSystem(zipFile.getInputStream(entry)); HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem); HSSFSheet hssfSheet = workBook.getSheetAt(0); //Iterate the rows Iterator rowIterator = hssfSheet.rowIterator(); int count = 0; while (rowIterator.hasNext()) { HSSFRow hssfRow = (HSSFRow) rowIterator.next(); //We skip first row (= header row) if (count > 0) { double gradeXls = -1; String itemString = null; // has grade information try { String _the_eid = hssfRow.getCell(1).getStringCellValue(); if (!assignment.isGroup()) { User u = UserDirectoryService.getUserByEid(hssfRow.getCell(1).getStringCellValue()/*user eid*/); if (u == null) throw new Exception("User not found!"); _the_eid = u.getId(); } UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(_the_eid); if (w != null) { itemString = assignment.isGroup() ? hssfRow.getCell(3).toString() : hssfRow.getCell(4).toString(); int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { //Parse the string to double using the locale format try { itemString = assignment.isGroup() ? hssfRow.getCell(3).getStringCellValue() : hssfRow.getCell(4).getStringCellValue(); if ((itemString != null) && (itemString.trim().length() > 0)) { NumberFormat nbFormat = NumberFormat.getInstance(new ResourceLoader().getLocale()); gradeXls = nbFormat.parse(itemString).doubleValue(); } } catch (Exception e) { try { gradeXls = assignment.isGroup() ? hssfRow.getCell(3).getNumericCellValue() : hssfRow.getCell(4).getNumericCellValue(); } catch (Exception e2) { gradeXls = -1; } } if (gradeXls != -1) { // get localized number format NumberFormat nbFormat = NumberFormat.getInstance(); try { Locale locale = null; ResourceLoader rb = new ResourceLoader(); locale = rb.getLocale(); nbFormat = NumberFormat.getNumberInstance(locale); itemString = nbFormat.format(gradeXls); } catch (Exception e) { M_log.warn("Error while retrieving local number format, using default ", e); } } else { itemString = ""; } validPointGrade(state, itemString); } else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) { itemString = validatePassFailGradeValue(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE ? scalePointGrade(state, itemString) : itemString); submissionTable.put(_the_eid, w); } } } catch (Exception e) { M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } } count++; } } //end of Excel grades import } else { String[] pathParts = entryName.split("/"); if (pathParts.length <=2) { validZipFormat=false; } else { // get user eid part String userEid = ""; if (entryName.indexOf("/") != -1) { // there is folder structure inside zip if (!zipHasFolder) zipHasFolder = true; // remove the part of zip name userEid = entryName.substring(entryName.indexOf("/")+1); // get out the user name part if (userEid.indexOf("/") != -1) { userEid = userEid.substring(0, userEid.indexOf("/")); } // SAK-17606 - get the eid part if ((userEid.indexOf("(") != -1) && !userEid.contains(anonTitle)) { userEid = userEid.substring(userEid.indexOf("(")+1, userEid.indexOf(")")); } if (userEid.contains(anonTitle)) { // anonymous grading so we have to figure out the eid //get eid out of this slick table we made earlier userEid = (String) anonymousSubmissionAndEidTable.get(userEid); } userEid=StringUtils.trimToNull(userEid); if (!assignment.isGroup()) { try { User u = UserDirectoryService.getUserByEid(userEid/*user eid*/); if (u != null) userEid = u.getId(); } catch (Throwable _t) { } } } if (submissionTable.containsKey(userEid)) { if (!zipHasFolderValidUserId) zipHasFolderValidUserId = true; if (hasComment && entryName.indexOf("comments") != -1) { // read the comments file String comment = getBodyTextFromZipHtml(zipFile.getInputStream(entry)); if (comment != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setComment(comment); submissionTable.put(userEid, r); } } if (hasFeedbackText && entryName.indexOf("feedbackText") != -1) { // upload the feedback text String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry)); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackText(text); submissionTable.put(userEid, r); } } if (hasSubmissionText && entryName.indexOf("_submissionText") != -1) { // upload the student submission text String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry)); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setText(text); submissionTable.put(userEid, r); } } if (hasSubmissionAttachment) { // upload the submission attachment String submissionFolder = "/" + rb.getString("stuviewsubm.submissatt") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); submissionTable.put(userEid, r); submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "submission"); } } if (hasFeedbackAttachment) { // upload the feedback attachment String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the feedback attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); submissionTable.put(userEid, r); submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "feedback"); } } // if this is a timestamp file if (entryName.indexOf("timestamp") != -1) { byte[] timeStamp = readIntoBytes(zipFile.getInputStream(entry), entryName, entry.getSize()); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionTimestamp(new String(timeStamp)); submissionTable.put(userEid, r); } } } } } } } catch (IOException e) { // uploaded file is not a valid archive addAlert(state, rb.getString("uploadall.alert.zipFile")); M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } finally { if (tmpFileOut != null) { try { tmpFileOut.close(); } catch (IOException e) { M_log.warn(this + ":uploadAll_parseZipFile: Error closing temp file output stream: " + e.toString()); } } if (fileContentStream != null) { try { fileContentStream.close(); } catch (IOException e) { M_log.warn(this + ":uploadAll_parseZipFile: Error closing file upload stream: " + e.toString()); } } //clean up the zip file if (tempFile != null && tempFile.exists()) { if (!tempFile.delete()) { M_log.warn("Failed to clean up temp file"); } } } //This is used so that the "Zip Error" message is only printed once boolean zipError = false; // generate error when there is no grade file and no folder structure if (!zipHasGradeFile && !zipHasFolder) { addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); addAlert(state, rb.getString("uploadall.alert.noGradeFile")); zipError = true; } // generate error when there is folder structure but not matching one user id if(zipHasFolder && !zipHasFolderValidUserId) { if (zipError == false) addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); addAlert(state, rb.getString("uploadall.alert.invalidUserId")); zipError = true; } // should have right structure of zip file if (!validZipFormat) { if (zipError == false) addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); // alert if the zip is of wrong format addAlert(state, rb.getString("uploadall.alert.wrongZipFormat")); zipError = true; } return submissionTable; } /** * Update all submission objects based on uploaded zip file * @param state * @param aReference * @param associateGradebookAssignment * @param hasSubmissionText * @param hasSubmissionAttachment * @param hasGradeFile * @param hasFeedbackText * @param hasComment * @param hasFeedbackAttachment * @param releaseGrades * @param submissionTable * @param submissions * @param assignment */ private void uploadAll_updateSubmissions(SessionState state, String aReference, String associateGradebookAssignment, boolean hasSubmissionText, boolean hasSubmissionAttachment, boolean hasGradeFile, boolean hasFeedbackText, boolean hasComment, boolean hasFeedbackAttachment, boolean releaseGrades, HashMap submissionTable, List submissions, Assignment assignment) { if (assignment != null && submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); if (submissionTable.containsKey(s.getSubmitterId())) { // update the AssignmetnSubmission record AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "doUpload_all", state); if (sEdit != null) { UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(s.getSubmitterId()); // the submission text if (hasSubmissionText) { sEdit.setSubmittedText(w.getText()); } // the feedback text if (hasFeedbackText) { sEdit.setFeedbackText(w.getFeedbackText()); } // the submission attachment if (hasSubmissionAttachment) { // update the submission attachments with newly added ones from zip file List submittedAttachments = sEdit.getSubmittedAttachments(); for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();) { Reference a = (Reference) attachments.next(); if (!submittedAttachments.contains(a)) { sEdit.addSubmittedAttachment(a); } } } // the feedback attachment if (hasFeedbackAttachment) { List feedbackAttachments = sEdit.getFeedbackAttachments(); for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();) { // update the feedback attachments with newly added ones from zip file Reference a = (Reference) attachments.next(); if (!feedbackAttachments.contains(a)) { sEdit.addFeedbackAttachment(a); } } } // the feedback comment if (hasComment) { sEdit.setFeedbackComment(w.getComment()); } // the grade file if (hasGradeFile) { // set grade String grade = StringUtils.trimToNull(w.getGrade()); sEdit.setGrade(grade); if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !"ungraded".equals(grade)){ sEdit.setGraded(true); sEdit.setGradedBy(UserDirectoryService.getCurrentUser() == null ? null : UserDirectoryService.getCurrentUser().getId()); } } // release or not if (sEdit.getGraded()) { sEdit.setGradeReleased(releaseGrades); sEdit.setReturned(releaseGrades); } else { sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (releaseGrades && sEdit.getGraded()) { sEdit.setTimeReturned(TimeService.newTime()); } // if the current submission lacks timestamp while the timestamp exists inside the zip file if (StringUtils.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null) { sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp())); sEdit.setSubmitted(true); } // for further information boolean graded = sEdit.getGraded(); String sReference = sEdit.getReference(); // commit AssignmentService.commitEdit(sEdit); if (releaseGrades && graded) { // update grade in gradebook if (associateGradebookAssignment != null) { integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update", -1); } } } } } } } /** * This is to get the submission or feedback attachment from the upload zip file into the submission object * @param state * @param submissionTable * @param zin * @param entry * @param entryName * @param userEid * @param submissionOrFeedback */ private HashMap uploadZipAttachments(SessionState state, HashMap submissionTable, InputStream zin, ZipEntry entry, String entryName, String userEid, String submissionOrFeedback) { // upload all the files as instructor attachments to the submission for grading purpose String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length()); ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); try { // get file extension for detecting content type // ignore those hidden files String extension = ""; if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0)) { // add the file as attachment ResourceProperties properties = m_contentHostingService.newResourceProperties(); properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName); String[] parts = fName.split("\\."); if(parts.length > 1) { extension = parts[parts.length - 1]; } try { String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension); ContentResourceEdit attachment = m_contentHostingService.addAttachmentResource(fName); attachment.setContent(zin); attachment.setContentType(contentType); attachment.getPropertiesEdit().addAll(properties); m_contentHostingService.commitResource(attachment); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); List attachments = "submission".equals(submissionOrFeedback)?r.getSubmissionAttachments():r.getFeedbackAttachments(); attachments.add(EntityManager.newReference(attachment.getReference())); if ("submission".equals(submissionOrFeedback)) { r.setSubmissionAttachments(attachments); } else { r.setFeedbackAttachments(attachments); } submissionTable.put(userEid, r); } catch (Exception e) { M_log.warn(this + ":doUploadZipAttachments problem commit resource " + e.getMessage()); } } } catch (Exception ee) { M_log.warn(this + ":doUploadZipAttachments " + ee.getMessage()); } return submissionTable; } private String getBodyTextFromZipHtml(InputStream zin) { String rv = ""; try { rv = StringUtils.trimToNull(readIntoString(zin)); } catch (IOException e) { M_log.warn(this + ":getBodyTextFromZipHtml " + e.getMessage()); } if (rv != null) { int start = rv.indexOf("<body>"); int end = rv.indexOf("</body>"); if (start != -1 && end != -1) { // get the text in between rv = rv.substring(start+6, end); } } return rv; } private byte[] readIntoBytes(InputStream zin, String fName, long length) throws IOException { byte[] buffer = new byte[4096]; File f = File.createTempFile("asgnup", "tmp"); FileOutputStream fout = new FileOutputStream(f); try { int len; while ((len = zin.read(buffer)) > 0) { fout.write(buffer, 0, len); } zin.close(); } finally { try { fout.close(); // The file channel needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileOutputStream " + ioException.getMessage()); } } FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); byte[] data = null; try { data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel ByteBuffer bb = ByteBuffer.wrap(data); fc.read(bb); } finally { try { fc.close(); // The file channel needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileChannel " + ioException.getMessage()); } try { fis.close(); // The file inputstream needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileInputStream " + ioException.getMessage()); } } //remove the file f.delete(); return data; } private String readIntoString(InputStream zin) throws IOException { StringBuilder buffer = new StringBuilder(); int size = 2048; byte[] data = new byte[2048]; while (true) { try { size = zin.read(data, 0, data.length); if (size > 0) { buffer.append(new String(data, 0, size)); } else { break; } } catch (IOException e) { M_log.warn(this + ":readIntoString " + e.getMessage()); } } return buffer.toString(); } /** * * @return */ public void doCancel_download_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); ParameterParser params = data.getParameters(); String downloadUrl = params.getString("downloadUrl"); state.setAttribute(STATE_DOWNLOAD_URL, downloadUrl); cleanUploadAllContext(state); } /** * clean the state variabled used by upload all process */ private void cleanUploadAllContext(SessionState state) { state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_GRADEFILE_FORMAT); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_WITHOUT_FOLDERS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } /** * Action is to preparing to go to the download all file */ public void doPrep_download_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String view = params.getString("view"); state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DOWNLOAD_ALL); } // doPrep_download_all /** * Action is to preparing to go to the upload files */ public void doPrep_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL); } // doPrep_upload_all /** * the UploadGradeWrapper class to be used for the "upload all" feature */ public class UploadGradeWrapper { /** * the grade */ String m_grade = null; /** * the text */ String m_text = null; /** * the submission attachment list */ List m_submissionAttachments = EntityManager.newReferenceList(); /** * the comment */ String m_comment = ""; /** * the timestamp */ String m_timeStamp=""; /** * the feedback text */ String m_feedbackText=""; /** * the feedback attachment list */ List m_feedbackAttachments = EntityManager.newReferenceList(); public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText) { m_grade = grade; m_text = text; m_comment = comment; m_submissionAttachments = submissionAttachments; m_feedbackAttachments = feedbackAttachments; m_feedbackText = feedbackText; m_timeStamp = timeStamp; } /** * Returns grade string */ public String getGrade() { return m_grade; } /** * Returns the text */ public String getText() { return m_text; } /** * Returns the comment string */ public String getComment() { return m_comment; } /** * Returns the submission attachment list */ public List getSubmissionAttachments() { return m_submissionAttachments; } /** * Returns the feedback attachment list */ public List getFeedbackAttachments() { return m_feedbackAttachments; } /** * submission timestamp * @return */ public String getSubmissionTimeStamp() { return m_timeStamp; } /** * feedback text/incline comment * @return */ public String getFeedbackText() { return m_feedbackText; } /** * set the grade string */ public void setGrade(String grade) { m_grade = grade; } /** * set the text */ public void setText(String text) { m_text = text; } /** * set the comment string */ public void setComment(String comment) { m_comment = comment; } /** * set the submission attachment list */ public void setSubmissionAttachments(List attachments) { m_submissionAttachments = attachments; } /** * set the attachment list */ public void setFeedbackAttachments(List attachments) { m_feedbackAttachments = attachments; } /** * set the submission timestamp */ public void setSubmissionTimestamp(String timeStamp) { m_timeStamp = timeStamp; } /** * set the feedback text */ public void setFeedbackText(String feedbackText) { m_feedbackText = feedbackText; } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); return providers; } private void addActivity(Context context, Assignment assignment) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("activity", assignmentActivityProducer .getActivity(assignment)); String placement = ToolManager.getCurrentPlacement().getId(); context.put("iframeId", Validator.escapeJavascript("Main" + placement)); } private void addItem(Context context, AssignmentSubmission submission, String userId) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("item", assignmentActivityProducer .getItem(submission, userId)); } private ContentReviewService contentReviewService; public String getReportURL(Long score) { getContentReviewService(); return contentReviewService.getIconUrlforScore(score); } private void getContentReviewService() { if (contentReviewService == null) { contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName()); } } /******************* model answer *********/ /** * add model answer input into state variables */ public void doModel_answer(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String text = StringUtils.trimToNull(params.get("modelanswer_text")); if (text == null) { // no text entered for model answer addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noText")); } int showTo = params.getInt("modelanswer_showto"); if (showTo == 0) { // no show to criteria specifided for model answer addAlert(state, rb.getString("modelAnswer.show_to_student.alert.noShowTo")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER, Boolean.TRUE); state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_TEXT, text); state.setAttribute(NEW_ASSIGNMENT_MODEL_SHOW_TO_STUDENT, showTo); //state.setAttribute(NEW_ASSIGNMENT_MODEL_ANSWER_ATTACHMENT); } } private void assignment_resubmission_option_into_context(Context context, SessionState state) { context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) : null; String allowResubmitTimeString = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME) : null; // the resubmit number if (allowResubmitNumber != null && !"0".equals(allowResubmitNumber)) { context.put("value_allowResubmitNumber", Integer.valueOf(allowResubmitNumber)); context.put("resubmitNumber", "-1".equals(allowResubmitNumber) ? rb.getString("allow.resubmit.number.unlimited"): allowResubmitNumber); // put allow resubmit time information into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); // resubmit close time Time resubmitCloseTime = null; if (allowResubmitTimeString != null) { resubmitCloseTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString)); } // put into context if (resubmitCloseTime != null) { context.put("resubmitCloseTime", resubmitCloseTime.toStringLocalFull()); } } context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); } private void assignment_resubmission_option_into_state(Assignment a, AssignmentSubmission s, SessionState state) { String allowResubmitNumber = null; String allowResubmitTimeString = null; if (s != null) { // if submission is present, get the resubmission values from submission object first ResourceProperties sProperties = s.getProperties(); allowResubmitNumber = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); allowResubmitTimeString = sProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } else if (a != null) { // otherwise, if assignment is present, get the resubmission values from assignment object next ResourceProperties aProperties = a.getProperties(); allowResubmitNumber = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); allowResubmitTimeString = aProperties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } if (StringUtils.trimToNull(allowResubmitNumber) != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } if (allowResubmitTimeString == null) { // default setting allowResubmitTimeString = String.valueOf(a.getCloseTime().getTime()); } Time allowResubmitTime = null; if (allowResubmitTimeString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, allowResubmitTimeString); // get time object allowResubmitTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString)); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } if (allowResubmitTime != null) { // set up related state variables putTimePropertiesInState(state, allowResubmitTime, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); } } /** * save the resubmit option for selected users * @param data */ public void doSave_resubmission_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // read in user input into state variable if (StringUtils.trimToNull(params.getString("allowResToggle")) != null) { if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params readAllowResubmitParams(params, state, null); } } else { resetAllowResubmitParams(state); } String[] userIds = params.getStrings("selectedAllowResubmit"); if (userIds == null || userIds.length == 0) { addAlert(state, rb.getString("allowResubmission.nouser")); } else { for (int i = 0; i < userIds.length; i++) { String userId = userIds[i]; try { String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); Assignment _a = getAssignment(assignmentRef, " resubmit update ", state); AssignmentSubmission submission = null; if (_a.isGroup()) { submission = getSubmission(assignmentRef, userId, "doSave_resubmission_option", state); } else { User u = UserDirectoryService.getUser(userId); submission = getSubmission(assignmentRef, u, "doSave_resubmission_option", state); } if (submission != null) { AssignmentSubmissionEdit submissionEdit = editSubmission(submission.getReference(), "doSave_resubmission_option", state); if (submissionEdit != null) { // get resubmit number ResourcePropertiesEdit pEdit = submissionEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } // save AssignmentService.commitEdit(submissionEdit); } } } catch (Exception userException) { M_log.warn(this + ":doSave_resubmission_option error getting user with id " + userId + " " + userException.getMessage()); } } } // make sure the options are exposed in UI state.setAttribute(SHOW_ALLOW_RESUBMISSION, Boolean.TRUE); } public void doSave_send_feedback(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] userIds = params.getStrings("selectedAllowResubmit"); boolean checkForFormattingErrors = true; String comment = processFormattedTextFromBrowser(state, params.getCleanString("commentFeedback"),checkForFormattingErrors); String overwrite = params.getString("overWrite"); String returnToStudents = params.getString("returnToStudents"); if (userIds == null || userIds.length == 0) { addAlert(state, rb.getString("sendFeedback.nouser")); } else { if (comment.equals("")) { addAlert(state, rb.getString("sendFeedback.nocomment")); } else { int errorUsers = 0; for (int i = 0; i < userIds.length; i++) { String userId = userIds[i]; try { User u = UserDirectoryService.getUser(userId); String assignmentRef = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); AssignmentSubmission submission = AssignmentService.getSubmission(assignmentRef, u); if (submission != null) { AssignmentSubmissionEdit submissionEdit = AssignmentService.editSubmission(submission.getReference()); if (submissionEdit != null) { String newFeedbackComment = ""; if (overwrite != null) { newFeedbackComment = comment + "<br/>"; state.setAttribute(OW_FEEDBACK, Boolean.TRUE); } else { newFeedbackComment = submissionEdit.getFeedbackComment() + comment + "<br/>"; } submissionEdit.setFeedbackComment(newFeedbackComment); if (returnToStudents != null) { submissionEdit.setReturned(true); submissionEdit.setTimeReturned(TimeService.newTime()); state.setAttribute(RETURNED_FEEDBACK, Boolean.TRUE); } AssignmentService.commitEdit(submissionEdit); state.setAttribute(SAVED_FEEDBACK, Boolean.TRUE); } } } catch (Exception userException) { M_log.warn(this + ":doSave_send_feedback error getting user with id " + userId + " " + userException.getMessage()); errorUsers++; } } if (errorUsers>0) { addAlert(state, rb.getFormattedMessage("sendFeedback.error", new Object[]{errorUsers})); } } } // make sure the options are exposed in UI state.setAttribute(SHOW_SEND_FEEDBACK, Boolean.TRUE); } /** * multiple file upload * @param data */ public void doAttachUpload(RunData data) { // save the current input before leaving the page SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); saveSubmitInputs(state, data.getParameters ()); doAttachUpload(data, false); } /** * single file upload * @param data */ public void doAttachUploadSingle(RunData data) { doAttachUpload(data, true); } /** * upload local file for attachment * @param data * @param singleFileUpload */ public void doAttachUpload(RunData data, boolean singleFileUpload) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ToolSession toolSession = SessionManager.getCurrentToolSession(); ParameterParser params = data.getParameters (); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); // construct the state variable for attachment list List attachments = state.getAttribute(ATTACHMENTS) != null? (List) state.getAttribute(ATTACHMENTS) : EntityManager.newReferenceList(); FileItem fileitem = null; try { fileitem = params.getFileItem("upload"); } catch(Exception e) { // other exceptions should be caught earlier M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.upload")); } if(fileitem == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_file_size_mb })); //addAlert(state, hrb.getString("size") + " " + max_file_size_mb + "MB " + hrb.getString("exceeded2")); } else if (singleFileUpload && (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)) { // only if in the single file upload case, need to warn user to upload a local file addAlert(state, rb.getString("choosefile7")); } else if (fileitem.getFileName().length() > 0) { String filename = Validator.getFileName(fileitem.getFileName()); InputStream fileContentStream = fileitem.getInputStream(); String contentType = fileitem.getContentType(); InputStreamReader reader = new InputStreamReader(fileContentStream); try{ //check the InputStreamReader to see if the file is 0kb aka empty if( reader.ready()==false ) { addAlert(state, rb.getFormattedMessage("attempty", new Object[]{filename} )); } else if(fileContentStream != null) { // we just want the file name part - strip off any drive and path stuff String name = Validator.getFileName(filename); String resourceId = Validator.escapeResourceName(name); // make a set of properties to add for the new resource ResourcePropertiesEdit props = m_contentHostingService.newResourceProperties(); props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name); props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename); // make an attachment resource for this URL SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { //Needed to be able to add or modify their own if (function.equals(m_contentHostingService.AUTH_RESOURCE_ADD) || function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_OWN)) { return SecurityAdvice.ALLOWED; } return SecurityAdvice.PASS; } }; try { String siteId = ToolManager.getCurrentPlacement().getContext(); // add attachment // put in a security advisor so we can create citationAdmin site without need // of further permissions m_securityService.pushAdvisor(sa); ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, "Assignments", contentType, fileContentStream, props); try { Reference ref = EntityManager.newReference(m_contentHostingService.getReference(attachment.getId())); if (singleFileUpload && attachments.size() > 1) { //SAK-26319 - the assignment type is 'single file upload' and the user has existing attachments, so they must be uploading a 'newSingleUploadedFile' --bbailla2 state.setAttribute("newSingleUploadedFile", ref); } else { attachments.add(ref); } } catch(Exception ee) { M_log.warn(this + "doAttachUpload cannot find reference for " + attachment.getId() + ee.getMessage()); } state.setAttribute(ATTACHMENTS, attachments); } catch (PermissionException e) { addAlert(state, rb.getString("notpermis4")); } catch(RuntimeException e) { if(m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) { // couldn't we just truncate the resource-id instead of rejecting the upload? addAlert(state, rb.getFormattedMessage("alert.toolong", new String[]{name})); } else { M_log.debug(this + ".doAttachupload ***** Runtime Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed")); } } catch (ServerOverloadException e) { // disk full or no writing permission to disk M_log.debug(this + ".doAttachupload ***** Disk IO Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.diskio")); } catch(Exception ignore) { // other exceptions should be caught earlier M_log.debug(this + ".doAttachupload ***** Unknown Exception ***** " + ignore.getMessage()); addAlert(state, rb.getString("failed")); } finally { m_securityService.popAdvisor(sa); } } else { addAlert(state, rb.getString("choosefile7")); } } catch( IOException e){ M_log.debug(this + ".doAttachupload ***** IOException ***** " + e.getMessage()); addAlert(state, rb.getString("failed")); } } } // doAttachupload /** * Simply take as much as possible out of 'in', and write it to 'out'. Don't * close the streams, just transfer the data. * * @param in * The data provider * @param out * The data output * @throws IOException * Thrown if there is an IOException transfering the data */ private void writeToStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[INPUT_BUFFER_SIZE]; try { while (in.read(buffer) > 0) { out.write(buffer); } } catch (IOException e) { throw e; } } /** * Categories are represented as Integers. Right now this feature only will * be active for new assignments, so we'll just always return 0 for the * unassigned category. In the future we may (or not) want to update this * to return categories for existing gradebook items. * @param assignment * @return */ private int getAssignmentCategoryAsInt(Assignment assignment) { int categoryAsInt; categoryAsInt = 0; // zero for unassigned return categoryAsInt; } /* * (non-Javadoc) */ public void doOptions(RunData data, Context context) { doOptions(data); } // doOptions protected void doOptions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = ToolManager.getCurrentPlacement().getContext(); try { Site site = SiteService.getSite(siteId); ToolConfiguration tc=site.getToolForCommonId(ASSIGNMENT_TOOL_ID); String optionValue = tc.getPlacementConfig().getProperty(SUBMISSIONS_SEARCH_ONLY); state.setAttribute(SUBMISSIONS_SEARCH_ONLY, optionValue == null ? Boolean.FALSE:Boolean.valueOf(optionValue)); } catch (IdUnusedException e) { M_log.warn(this + ":doOptions Cannot find site with id " + siteId); } if (!alertGlobalNavigation(state, data)) { if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { state.setAttribute(STATE_MODE, MODE_OPTIONS); } else { addAlert(state, rb.getString("youarenot_options")); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } /** * build the options */ protected String build_options_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); context.put(SUBMISSIONS_SEARCH_ONLY, (Boolean) state.getAttribute(SUBMISSIONS_SEARCH_ONLY)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_OPTIONS; } // build_options_context /** * save the option edits * @param data * @param context */ public void doUpdate_options(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = ToolManager.getCurrentPlacement().getContext(); ParameterParser params = data.getParameters(); // only show those submissions matching search criteria boolean submissionsSearchOnly = params.getBoolean(SUBMISSIONS_SEARCH_ONLY); state.setAttribute(SUBMISSIONS_SEARCH_ONLY, Boolean.valueOf(submissionsSearchOnly)); // save the option into tool configuration try { Site site = SiteService.getSite(siteId); ToolConfiguration tc=site.getToolForCommonId(ASSIGNMENT_TOOL_ID); String currentSetting = tc.getPlacementConfig().getProperty(SUBMISSIONS_SEARCH_ONLY); if (currentSetting == null || !currentSetting.equals(Boolean.toString(submissionsSearchOnly))) { // save the change tc.getPlacementConfig().setProperty(SUBMISSIONS_SEARCH_ONLY, Boolean.toString(submissionsSearchOnly)); SiteService.save(site); } } catch (IdUnusedException e) { M_log.warn(this + ":doUpdate_options Cannot find site with id " + siteId); addAlert(state, rb.getFormattedMessage("options_cannotFindSite", new Object[]{siteId})); } catch (PermissionException e) { M_log.warn(this + ":doUpdate_options Do not have permission to edit site with id " + siteId); addAlert(state, rb.getFormattedMessage("options_cannotEditSite", new Object[]{siteId})); } if (state.getAttribute(STATE_MESSAGE) == null) { // back to list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doUpdate_options /** * cancel the option edits * @param data * @param context */ public void doCancel_options(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_options /** * handle submission options */ public void doSubmission_search_option(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String searchOption = StringUtils.trimToNull(data.getParameters().getString("option")); // set the flag to go to the prev page on the next list if (searchOption != null && "submit".equals(searchOption)) { doSubmission_search(data, context); } else if (searchOption != null && "clear".equals(searchOption)) { doSubmission_search_clear(data, context); } } // doSubmission_search_option /** * Handle the submission search request. */ public void doSubmission_search(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String search = StringUtils.trimToNull(data.getParameters().getString( FORM_SEARCH)); // set the flag to go to the prev page on the next list if (search == null) { state.removeAttribute(STATE_SEARCH); } else { state.setAttribute(STATE_SEARCH, search); } } // doSubmission_search /** * Handle a Search Clear request. */ public void doSubmission_search_clear(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // clear the search state.removeAttribute(STATE_SEARCH); } // doSubmission_search_clear protected void letterGradeOptionsIntoContext(Context context) { String lOptions = ServerConfigurationService.getString("assignment.letterGradeOptions", "A+,A,A-,B+,B,B-,C+,C,C-,D+,D,D-,E,F"); context.put("letterGradeOptions", StringUtils.split(lOptions, ",")); } private LRS_Statement getStatementForViewSubmittedAssignment(LRS_Actor actor, Event event, String assignmentName) { String url = ServerConfigurationService.getPortalUrl(); LRS_Verb verb = new LRS_Verb(SAKAI_VERB.interacted); LRS_Object lrsObject = new LRS_Object(url + event.getResource(), "view-submitted-assignment"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("en-US", "User reviewed a submitted assignment"); lrsObject.setActivityName(nameMap); // Add description HashMap<String, String> descMap = new HashMap<String, String>(); descMap.put("en-US", "User reviewed a submitted assignment: " + assignmentName); lrsObject.setDescription(descMap); return new LRS_Statement(actor, verb, lrsObject); } private LRS_Statement getStatementForViewAssignment(LRS_Actor actor, Event event, String assignmentName) { String url = ServerConfigurationService.getPortalUrl(); LRS_Verb verb = new LRS_Verb(SAKAI_VERB.interacted); LRS_Object lrsObject = new LRS_Object(url + event.getResource(), "view-assignment"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("en-US", "User viewed an assignment"); lrsObject.setActivityName(nameMap); HashMap<String, String> descMap = new HashMap<String, String>(); descMap.put("en-US", "User viewed assignment: " + assignmentName); lrsObject.setDescription(descMap); return new LRS_Statement(actor, verb, lrsObject); } private LRS_Statement getStatementForSubmitAssignment(LRS_Actor actor, Event event, String accessUrl, String assignmentName) { LRS_Verb verb = new LRS_Verb(SAKAI_VERB.attempted); LRS_Object lrsObject = new LRS_Object(accessUrl + event.getResource(), "submit-assignment"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("en-US", "User submitted an assignment"); lrsObject.setActivityName(nameMap); // Add description HashMap<String, String> descMap = new HashMap<String, String>(); descMap.put("en-US", "User submitted an assignment: " + assignmentName); lrsObject.setDescription(descMap); return new LRS_Statement(actor, verb, lrsObject); } /** * Validates the ungraded/pass/fail grade values provided in the upload file are valid. * Values must be present in the appropriate language property file. * @param state * @param itemString * @return one of the valid values or the original value entered by the user */ private String validatePassFailGradeValue(SessionState state, String itemString) { // -------- SAK-24199 (SAKU-274) by Shoji Kajita if (itemString.equalsIgnoreCase(rb.getString("pass"))) { itemString = "Pass"; } else if (itemString.equalsIgnoreCase(rb.getString("fail"))) { itemString = "Fail"; } else if (itemString.equalsIgnoreCase(rb.getString("ungra")) || itemString.isEmpty()) { itemString = "Ungraded"; } else { // Not one of the expected values. Display error message. addAlert(state, rb.getFormattedMessage("plesuse0", new Object []{itemString})); } // -------- return itemString; } /** * Action to determine which view do present to user. * This method is currently called from calendar events in the alternate calendar tool. */ public void doCheck_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean allowReadAssignment = AssignmentService.allowGetAssignment(contextString); boolean allowSubmitAssignment = AssignmentService.allowAddSubmission(contextString); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); // Retrieve the status of the assignment String assignStatus = getAssignmentStatus(assignmentId, state); if (assignStatus != null && !assignStatus.equals(rb.getString("gen.open")) && !allowAddAssignment){ addAlert(state, rb.getFormattedMessage("gen.notavail", new Object[]{assignStatus})); } // Check the permission and call the appropriate view method. if (allowAddAssignment){ doView_assignment(data); } else if (allowSubmitAssignment){ doView_submission(data); } else if (allowReadAssignment){ doView_assignment_as_student(data); } else{ addAlert(state, rb.getFormattedMessage("youarenot_viewAssignment", new Object[]{assignmentId})); } } // doCheck_view /** * Retrieves the status of a given assignment. * @param assignmentId * @param state * @return */ private String getAssignmentStatus(String assignmentId, SessionState state) { String rv = null; try { Session session = SessionManager.getCurrentSession(); rv = AssignmentService.getAssignmentStatus(assignmentId); } catch (IdUnusedException e) { M_log.warn(this + " " + e.getMessage() + " " + assignmentId); } catch (PermissionException e) { M_log.warn(this + e.getMessage() + " " + assignmentId); } return rv; } /** * Set properties related to grading via an external scoring service. This service may be enabled for the * associated gradebook item. */ protected void setScoringAgentProperties(Context context, Assignment assignment, AssignmentSubmission submission, boolean gradeView) { String associatedGbItem = StringUtils.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (submission != null && associatedGbItem != null && assignment.getContent().getTypeOfGrade() == 3) { ScoringService scoringService = (ScoringService) ComponentManager.get("org.sakaiproject.scoringservice.api.ScoringService"); ScoringAgent scoringAgent = scoringService.getDefaultScoringAgent(); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); boolean scoringAgentEnabled = scoringAgent != null && scoringAgent.isEnabled(gradebookUid, null); String studentId = submission.getSubmitterId(); if (scoringAgentEnabled) { String gbItemName; if (assignment.getReference().equals(associatedGbItem)) { // this gb item is controlled by this tool gbItemName = assignment.getTitle(); } else { // this assignment was associated with an existing gb item gbItemName = associatedGbItem; } GradebookService gbService = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); org.sakaiproject.service.gradebook.shared.Assignment gbItem = null; try { gbItem = gbService.getAssignment(gradebookUid, gbItemName); } catch (SecurityException se) { // the gradebook method above is overzealous about security when retrieving the gb item by name. It doesn't // allow student-role users to access the assignment via this method. So we // have to retrieve all viewable gb items and filter to get the one we want, unfortunately, if we hit an exception. // If gb item isn't released in the gb, scoring agent info will not be available. List<org.sakaiproject.service.gradebook.shared.Assignment> viewableGbItems = gbService.getViewableAssignmentsForCurrentUser(gradebookUid); if (viewableGbItems != null && !viewableGbItems.isEmpty()) { for (org.sakaiproject.service.gradebook.shared.Assignment viewableGbItem : viewableGbItems) { if(gbItemName.equals(viewableGbItem.getName())) { gbItem = viewableGbItem; break; } } } } if (gbItem != null) { String gbItemId = Long.toString(gbItem.getId()); // Determine if a scoring component (like a rubric) has been associated with this gradebook item ScoringComponent component = scoringService.getScoringComponent( scoringAgent.getAgentId(), gradebookUid, gbItemId); boolean scoringComponentEnabled = component != null; context.put("scoringComponentEnabled", scoringComponentEnabled); if (scoringComponentEnabled) { context.put("scoringAgentImage", scoringAgent.getImageReference()); context.put("scoringAgentName", scoringAgent.getName()); // retrieve the appropriate url if (gradeView) { context.put("scoreUrl", scoringAgent.getScoreLaunchUrl(gradebookUid, gbItemId, studentId)); context.put("refreshScoreUrl", scoringService.getDefaultScoringAgent().getScoreUrl(gradebookUid, gbItemId, studentId) + "&t=gb"); context.put("scoreText",rb.getFormattedMessage("scoringAgent.grade", new Object[]{scoringAgent.getName()})); } else { // only retrieve the graded rubric if grade has been released. otherwise, keep it generic String scoreStudent = null; if (submission.getGradeReleased()) { scoreStudent = studentId; } context.put("scoreUrl", scoringAgent.getViewScoreLaunchUrl(gradebookUid, gbItemId, scoreStudent)); context.put("scoreText",rb.getFormattedMessage("scoringAgent.view", new Object[]{scoringAgent.getName()})); } } } } } } }
SAK-27933 false message to instructors about draft mode when creating an assignment with content review fails; patch from Brian B. git-svn-id: d213257099f21e50eb3b4c197ffbeb2264dc0174@314597 66ffb92e-73f9-0310-93c1-f5514f145a0a
assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
SAK-27933 false message to instructors about draft mode when creating an assignment with content review fails; patch from Brian B.
<ide><path>ssignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java <ide> a.setPeerAssessmentStudentViewReviews(peerAssessmentStudentViewReviews); <ide> a.setPeerAssessmentNumReviews(peerAssessmentNumReviews); <ide> a.setPeerAssessmentInstructions(peerAssessmentInstructions); <del> <del> // post the assignment <del> a.setDraft(!post); <ide> <ide> try <ide> {
JavaScript
mpl-2.0
8e3ebb487753a4e1f8bed9e88c24ca6d88c8b554
0
joyent/sdc-cnapi,joyent/sdc-cnapi
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * * This file contains all the Compute Server logic, used to interface with the * server as well as it's stored representation in the backend datastores. */ var async = require('async'); var assert = require('assert-plus'); var dns = require('dns'); var qs = require('querystring'); var restify = require('restify'); var sprintf = require('sprintf').sprintf; var util = require('util'); var verror = require('verror'); var once = require('once'); var buckets = require('../apis/moray').BUCKETS; var common = require('../common'); var ModelBase = require('./base'); var ModelVM = require('./vm'); var ModelWaitlist = require('./waitlist'); var ModelPlatform = require('./platform'); var PROVISIONER = 'provisioner'; var MEMORY_USAGE_KEYS = [ 'memory_available_bytes', 'memory_arc_bytes', 'memory_total_bytes', 'memory_provisionable_bytes' ]; var DISK_USAGE_KEYS = [ 'disk_cores_quota_bytes', 'disk_cores_quota_used_bytes', 'disk_installed_images_used_bytes', 'disk_kvm_quota_bytes', 'disk_kvm_quota_used_bytes', 'disk_kvm_zvol_used_bytes', 'disk_kvm_zvol_volsize_bytes', 'disk_pool_alloc_bytes', 'disk_pool_size_bytes', 'disk_system_used_bytes', 'disk_zone_quota_bytes', 'disk_zone_quota_used_bytes' ]; /** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ModelServer encapsulates the logic for manipulating and interacting * servers and their back-end storage representation. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ function ModelServer(uuid) { if (!uuid) { throw new Error('ModelServer missing uuid parameter'); } this.value = null; this.uuid = uuid; this.log = ModelServer.getLog(); } ModelServer.prototype.getValue = function () { return clone(this.value); }; /** * * One-time initialization for some things like logs and caching. */ ModelServer.init = function (app) { this.app = app; Object.keys(ModelBase.staticFn).forEach(function (p) { ModelServer[p] = ModelBase.staticFn[p]; }); ModelServer.tasks = {}; ModelServer.log = app.getLog(); ModelServer.heartbeatByServerUuid = {}; }; ModelServer.createProvisionerEventHandler = function (app, jobuuid) { var self = this; var workflow = ModelServer.getWorkflow(); return function (task, event) { var taskid = task.id; if (!jobuuid) { return; } self.log.info( 'Posting task info (task %s) to workflow jobs endpoint (job %s)', taskid, jobuuid); workflow.getClient().client.post( '/jobs/' + jobuuid + '/info', event, function (error, req, res, obj) { if (error) { self.log.error( error, 'Error posting info to jobs endpoint'); return; } self.log.info( 'Posted task info (task %s, job %s)', taskid, jobuuid); }); }; }; /** * Return a list of servers matching given criteria. */ ModelServer.list = function (params, callback) { var self = this; var uuid = params.uuid; callback = once(callback); var extras = params.extras || { status: true, last_heartbeat: true }; this.log.debug(params, 'Listing servers'); var wantFinal = params.wantFinal; var filterParams = [ 'datacenter', 'setup', 'reservoir', 'headnode', 'reserved', 'hostname' ]; var filter = ''; if (Array.isArray(uuid)) { var uuidFilter = uuid.map(function (u) { return '(uuid=' + u + ')'; }).join(''); filter += '(|' + uuidFilter + ')'; } else if (uuid) { filter += '(uuid=' + uuid + ')'; } else { filter += '(uuid=*)'; } var paramsFilter = []; filterParams.forEach(function (p) { if (!params.hasOwnProperty(p) || typeof (params[p]) === 'undefined') { return; } if (!buckets.servers.bucket.index[p]) { return; } if (buckets.servers.bucket.index[p].type === 'string') { paramsFilter.push( sprintf('(%s=%s)', p, common.filterEscape(params[p]))); } else if (buckets.servers.bucket.index[p].type === 'number') { paramsFilter.push( sprintf('(%s=%s)', p, common.filterEscape(params[p]))); } else if (buckets.servers.bucket.index[p].type === 'boolean') { paramsFilter.push( sprintf('(%s=%s)', p, common.filterEscape(params[p]))); } }); paramsFilter.push('!(uuid=default)'); if (paramsFilter.length > 1) { filter = sprintf('(&%s(&%s))', filter, paramsFilter.join('')); } else if (paramsFilter.length === 1) { filter = sprintf('(&%s%s)', filter, paramsFilter[0]); } var moray = ModelServer.getMoray(); var findOpts = { sort: { attribute: 'uuid', order: 'ASC' } }; ['limit', 'offset'].forEach(function (f) { if (params.hasOwnProperty(f)) { findOpts[f] = params[f]; } }); var servers = []; var serverStatus = {}; async.parallel([ // Get all server records function (next) { var req = moray.findObjects( buckets.servers.name, filter, findOpts); req.on('error', onError); req.on('record', onRecord); req.on('end', next); function onError(error) { self.log.error(error, 'error retriving servers'); next(error); } function onRecord(server) { servers.push(server.value); } }, // Get all server record last_heartbeat data function (next) { // XXX write me a getAllServerStatuses function that can return > // 1000 results if (extras.last_heartbeat === false) { next(); return; } var req = moray.findObjects( buckets.status.name, '(server_uuid=*)', {}); req.on('error', onError); req.on('record', onRecord); req.on('end', next); function onError(error) { self.log.error(error, 'error retriving last_heartbeats'); next(error); } function onRecord(status) { serverStatus[status.value.server_uuid] = status.value; } } ], function (err) { processResults(err); }); function processResults(err) { if (err) { callback(err); return; } if (!wantFinal) { callback(null, servers); return; } async.map( servers, function (server, cb) { var serverModel = new ModelServer(server.uuid); if (serverStatus.hasOwnProperty(server.uuid)) { server.last_heartbeat = serverStatus[server.uuid].last_heartbeat; } serverModel.setRaw(server); serverModel.getFinal(extras, function (error, s) { cb(null, s); }); }, function (error, results) { callback(null, results); }); } }; /** * Initiate a workflow, which can may be can be added to which is run whenever * a new server starts up and sends its sysinfo payload via Ur. */ ModelServer.beginSysinfoWorkflow = function (sysinfo, callback) { var self = this; if (!ModelServer.app.workflow.connected) { self.log.warn( 'Cannot start sysinfo workflow: cannot reach workflow API'); } var uuid = sysinfo.UUID; var params = { sysinfo: sysinfo, server_uuid: uuid, target: uuid, admin_uuid: ModelServer.getConfig().adminUuid }; self.log.info('Instantiating server-sysinfo workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-sysinfo', params, function (error, job) { if (error) { self.log.error('Error in workflow: %s', error.message); if (callback) { callback(error); } return; } if (callback) { callback(); } }); }; /** * Creates an object that will contain default values for new servers. */ ModelServer.setDefaultServer = function (values, callback) { var self = this; var defaultServer; if (arguments.length === 2) { defaultServer = { uuid: 'default' }; for (var k in values) { defaultServer[k] = values[k]; } storeDefault(); } else { defaultServer = { uuid: 'default', default_console: 'serial', serial: 'ttyb', boot_params: {}, kernel_flags: {}, boot_modules: [], boot_platform: ModelServer.getApp().liveimage }; callback = arguments[0]; storeDefault(); } function storeDefault() { var moray = ModelServer.getMoray(); moray.putObject( buckets.servers.name, 'default', defaultServer, function (putError) { if (putError) { self.log.error('Could not store default server'); callback( verror.VError(putError, 'failed to store default server')); return; } callback(); }); } }; ModelServer.updateDefaultServer = function (values, callback) { var self = this; var moray = ModelServer.getMoray(); moray.getObject( buckets.servers.name, 'default', function (error, obj) { if (error) { self.log.error(error, 'Could not store default server'); callback(new verror.VError( error, 'failed to store default server')); return; } var server = obj.value; if (!server.boot_params) { server.boot_params = {}; } if (values.boot_modules) { server.boot_modules = values.boot_modules; } if (values.boot_platform) { server.boot_platform = values.boot_platform; } if (values.boot_modules) { server.boot_modules = values.boot_modules; } var boot_params = values.boot_params || {}; var kernel_flags = values.kernel_flags || {}; var k; for (k in kernel_flags) { if (kernel_flags[k] === null) { delete server.kernel_flags[k]; continue; } server.kernel_flags = server.kernel_flags || {}; server.kernel_flags[k] = kernel_flags[k]; } for (k in boot_params) { if (boot_params[k] === null) { delete server.boot_params[k]; continue; } server.boot_params = server.boot_params || {}; server.boot_params[k] = boot_params[k]; } var names = ['default_console', 'serial']; names.forEach(function (n) { if (values[n] === null) { delete server[n]; return; } server[n] = values[n] || server[n]; }); moray.putObject( buckets.servers.name, 'default', server, function (putError) { if (putError) { self.log.error('Could not store default server'); callback(verror.VError( putError, 'failed to store default server')); return; } callback(); }); }); }; /** * Execute a command on a particular server via Ur. */ ModelServer.prototype.invokeUrScript = function (script, params, callback) { var self = this; var uuid = this.uuid; var opts = { uuid: uuid, message: { type: 'script', script: script, args: params.args || [], env: params.env || {} } }; self.log.info('Sending compute node %s script', uuid); ModelServer.getUr().execute(opts, function (err, stdout, stderr) { if (err) { self.log.error('Error raised by ur when ' + 'running script: ' + err.message); return callback(err); } return callback(err, stdout, stderr); }); }; /** * Reboot a server. */ ModelServer.prototype.reboot = function (params, callback) { var self = this; if (!callback) { callback = params; } var uuid = this.uuid; var wfParams; self.getRaw(function (geterror, raw) { wfParams = { cnapi_url: ModelServer.getConfig().cnapi.url, server_uuid: uuid, target: uuid, origin: params.origin, creator_uuid: params.creator_uuid }; self.log.info('Instantiating server-reboot workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-reboot', wfParams, function (error, job) { if (error) { self.log.error('Error in workflow: %s', error.message); callback(error); return; } callback(null, job.uuid); return; }); }); }; /** * Format an error message with */ ModelServer.prototype.errorFmt = function (str) { return sprintf('Error (server=%s): %s', this.uuid, str); }; /** * Logs an error message along with the relevant error object. */ ModelServer.prototype.logerror = function (error, str) { var self = this; this.log.error(error, self.errorFmt(str)); }; /** * Fetches and returns the server's values and merges * them with the raw internal values. */ ModelServer.prototype.filterFields = function (fields, callback) { var self = this; var server = clone(self.value); function isBoolean(a) { return !!a === a; } function skip(f, fo) { var ret = ( !isBoolean(fo[f]) || !fo[f]); return ret; } async.parallel([ function (cb) { if (skip('last_heartbeat', fields)) { delete server.last_heartbeat; cb(); return; } cb(); }, function (cb) { if (skip('status', fields)) { delete server.status; cb(); return; } server.status = server.status || 'unknown'; self.log.debug( 'Status for %s was %s', self.uuid, server.status); cb(); }, function (cb) { if (skip('memory', fields)) { for (var k in MEMORY_USAGE_KEYS) { delete server[MEMORY_USAGE_KEYS[k]]; } cb(); return; } cb(); }, function (cb) { if (skip('disk', fields)) { for (var k in DISK_USAGE_KEYS) { delete server[DISK_USAGE_KEYS[k]]; } cb(); return; } cb(); }, function (cb) { if (skip('vms', fields)) { delete server.vms; cb(); return; } cb(); }, function (cb) { if (skip('agents', fields)) { delete server.agents; cb(); return; } cb(); } ], function (error) { if (error) { callback(error); return; } callback(null, server); }); }; ModelServer.prototype.updateFromVmsUpdate = function (heartbeat, callback) { var self = this; var serverobj = {}; async.waterfall([ // Get the server object getServer, // Initialize the server object initializeServer, // Update the server's memory updateMemory, // Update the server's disk updateDisk, // Update the server status updateStatus, // Write the change to moray writeServerRecord ], function (error) { callback(error); }); function getServer(cb) { self.getRaw(function (err, so, s) { if (err) { cb(new verror.VError(err, 'retrieving server on heartbeat')); return; } serverobj = so; cb(); }); } function initializeServer(cb) { if (!serverobj) { self.log.info( 'heartbeat server %s was not found in moray, ' + 'initializing new server record', self.uuid); // Initialize new server record from default params ModelServer.initialValues({}, function (error, so) { if (error) { cb(error); return; } serverobj = so; serverobj.uuid = self.uuid; serverobj.vms = {}; cb(); }); return; } else { if (!serverobj.sysinfo) { ModelServer.getApp().needSysinfoFromServer(self.uuid); } ModelServer.carryForwardVMChanges(heartbeat, serverobj); } cb(); } function updateMemory(cb) { if (!serverobj.sysinfo) { cb(); return; } var memoryKeys = [ ['availrmem_bytes', 'memory_available_bytes'], ['arcsize_bytes', 'memory_arc_bytes'], ['total_bytes', 'memory_total_bytes'] ]; memoryKeys.forEach(function (keys) { serverobj[keys[1]] = heartbeat.meminfo[keys[0]]; }); /** * Compute the memory_provisionable_bytes value based on the total * memory, the reservation ratio and the max_physical_memory values * of all vms. */ var reservation_ratio = serverobj.reservation_ratio; var total_memory_bytes = serverobj.sysinfo['MiB of Memory'] * 1024 * 1024; serverobj.memory_provisionable_bytes = total_memory_bytes - (total_memory_bytes * reservation_ratio); serverobj.memory_provisionable_bytes -= 1024 * 1024 * Object.keys(heartbeat.vms) .map(function (uuid) { return heartbeat.vms[uuid]; }) .reduce(function (prev, curr) { return prev + curr.max_physical_memory; }, 0); serverobj.memory_provisionable_bytes = Math.floor(serverobj.memory_provisionable_bytes); cb(); } function updateDisk(cb) { var diskKeys = [ ['cores_quota_bytes', 'disk_cores_quota_bytes'], ['cores_quota_used_bytes', 'disk_cores_quota_used_bytes'], ['installed_images_used_bytes', 'disk_installed_images_used_bytes'], ['kvm_quota_bytes', 'disk_kvm_quota_bytes'], ['kvm_quota_used_bytes', 'disk_kvm_quota_used_bytes'], ['kvm_zvol_used_bytes', 'disk_kvm_zvol_used_bytes'], ['kvm_zvol_volsize_bytes', 'disk_kvm_zvol_volsize_bytes'], ['pool_alloc_bytes', 'disk_pool_alloc_bytes'], ['pool_size_bytes', 'disk_pool_size_bytes'], ['system_used_bytes', 'disk_system_used_bytes'], ['zone_quota_bytes', 'disk_zone_quota_bytes'], ['zone_quota_used_bytes', 'disk_zone_quota_used_bytes'] ]; diskKeys.forEach(function (keys) { if (heartbeat.diskinfo.hasOwnProperty(keys[0])) { serverobj[keys[1]] = heartbeat.diskinfo[keys[0]]; } }); cb(); } function updateStatus(cb) { serverobj.transport = heartbeat.transport; serverobj.status = 'running'; serverobj.last_heartbeat = (new Date()).toISOString(); cb(); } function writeServerRecord(cb) { self.modify(serverobj, function (err) { if (err) { self.log.error(err); } cb(err); }); } }; /** * Returns a copy of the server model's internal representation retried from * the backend store, or from memory if this object has been previously * fetched. */ ModelServer.prototype.getRaw = function (callback) { var self = this; var uuid = self.uuid; var server; if (self.exists === false) { this.log.warn( '%s was not found previously, returning negative result', uuid); callback(); return; } if (self.value) { server = clone(self.value); callback(null, server); } else { this.log.trace('Fetching server %s from moray', uuid); ModelServer.getMoray().getObject( buckets.servers.name, uuid, function (error, obj) { if (error && error.name === 'ObjectNotFoundError') { self.exists = false; self.log.error('Server %s not found in moray', uuid); callback(); return; } else if (error) { self.log.error(error, 'Error fetching server from moray'); callback(error); return; } self.found = true; self.exists = true; server = clone(obj.value); self.value = obj.value; callback(null, server); }); } }; ModelServer.updateServerPropertiesFromSysinfo = function (opts) { var server = opts.server; var sysinfo = opts.sysinfo; server.sysinfo = sysinfo; server.ram = Number(sysinfo['MiB of Memory']); server.current_platform = sysinfo['Live Image']; server.headnode = sysinfo['Boot Parameters']['headnode'] === 'true'; server.boot_platform = server.boot_platform || sysinfo['Live Image']; server.hostname = server.hostname || sysinfo['Hostname']; server.agents = server.agents || sysinfo['SDC Agents']; if (sysinfo['SDC Version'] === '7.0' && !sysinfo.hasOwnProperty('Setup')) { if (sysinfo.hasOwnProperty('Zpool')) { server.setup = true; } else { server.setup = false; } } else if (sysinfo.hasOwnProperty('Setup')) { if (sysinfo['Setup'] === 'true' || sysinfo['Setup'] === true) { server.setup = true; } else if (sysinfo['Setup'] === 'false' || sysinfo['Setup'] === false) { server.setup = false; } } return server; }; /** * Create a server object suitable for insertion into Moray */ ModelServer.initialValues = function (opts, callback) { var self = this; var boot_params; async.waterfall([ function (cb) { ModelServer.getBootParamsDefault( function (error, params) { boot_params = params; if (boot_params.kernel_args.rabbitmq_dns) { boot_params.kernel_args.rabbitmq = boot_params.kernel_args.rabbitmq_dns; delete boot_params.kernel_args.rabbitmq_dns; } cb(); }); } ], function (error) { if (error) { callback(error); return; } var server = {}; server.agents = []; server.datacenter = ModelServer.getConfig().datacenter_name; server.overprovision_ratio = 1.0; server.reservation_ratio = 0.15; server.reservoir = false; server.traits = {}; server.rack_identifier = ''; server.comments = ''; server.uuid = self.uuid; server.reserved = false; server.vms = {}; server.boot_platform = boot_params.platform; server.boot_params = boot_params.kernel_args || {}; server.kernel_flags = boot_params.kernel_flags || {}; server.default_console = boot_params.default_console || 'serial'; server.serial = boot_params.serial || 'ttyb'; server.created = (new Date()).toISOString(); callback(null, server); }); }; /** * Create a server object in Moray. Use the sysinfo values if they are given in * the opts argument. If no sysinfo values are given, do a sysinfo lookup on * the server via Ur, and then create the server using those values. */ ModelServer.prototype.create = function (opts, callback) { var self = this; var server = {}; self.log.info({ opts: opts }, 'server creation opts'); async.waterfall([ function (cb) { ModelServer.initialValues({}, function (err, s) { server = s; server.uuid = opts.sysinfo.UUID; server.created = opts.created; server.sysinfo = opts.sysinfo; server.ram = opts.sysinfo['MiB of Memory']; server.hostname = opts.sysinfo.Hostname; server.status = opts.status; server.headnode = opts.sysinfo['Boot Parameters']['headnode'] === 'true'; server.current_platform = opts.sysinfo['Live Image']; server.setup = opts.setup; server.last_boot = opts.last_boot; cb(); }); } ], function (error) { self.store( server, function (createError, createdServer) { if (createError) { self.log.error( createError, 'Error creating server in moray'); callback(createError); return; } self.log.info('Stored server record in moray'); callback(null, server); }); }); }; /** * Create a server record in moray. */ ModelServer.prototype.store = function (server, callback) { var self = this; var uuid = server['uuid']; delete server.memory; ModelServer.getMoray().putObject( buckets.servers.name, uuid, server, function (error) { if (error) { self.log.error(error, 'Error adding server to moray'); callback(error); return; } callback(); }); }; /** * Modify a server record. */ ModelServer.prototype.modify = function (server, callback) { var self = this; self.value = self.value || {}; self.value = clone(server, self.value); // Remove obsolete attributes delete self.value.serial_speed; delete self.value.images; self.log.trace({ server: self.value.uuid }, 'Writing server %s to moray', self.value.uuid); ModelServer.getMoray().putObject( buckets.servers.name, self.uuid, self.value, function (error) { if (error) { self.logerror(error, 'modifying server'); } callback(error); }); }; /** * Modify a server record. */ ModelServer.prototype.onHeartbeat = function (heartbeat, callback) { if (!callback) { callback = heartbeat; heartbeat = null; } assert.func(callback, 'callback'); var self = this; var uuid = self.uuid; ModelServer.getApp().refreshServerHeartbeatTimeout(self.uuid); if (!ModelServer.getApp().collectedGlobalSysinfo) { callback(); return; } if (!ModelServer.getMoray().connected) { self.log.warn( 'cannot refresh server from heartbeat: cannot reach moray'); return; } if (!ModelServer.heartbeatByServerUuid) { ModelServer.heartbeatByServerUuid = {}; } if (!ModelServer.heartbeatByServerUuid[uuid]) { ModelServer.heartbeatByServerUuid[uuid] = {}; } if (!heartbeat) { heartbeat = { server_uuid: self.uuid, last_heartbeat: (new Date()).toISOString() }; } // Check if we are still processing a heartbeat for this server. When we // begin processing a heartbeat we check if this value is set. If it is, we // update it and return. If it is not set, we set a timeout to clear it. // The reason for the timeout is do not end up stuck in this state. if (ModelServer.heartbeatByServerUuid[uuid].current) { ModelServer.heartbeatByServerUuid[uuid].next = heartbeat; self.log.warn('already writing heartbeat from %s', uuid); return; } clearTimeout(ModelServer.heartbeatByServerUuid[uuid].timeout); ModelServer.heartbeatByServerUuid[uuid].timeout = setTimeout(function () { ModelServer.heartbeatByServerUuid[uuid] = {}; }, common.HEARTBEATER_PERIOD * 2 * 1000); ModelServer.heartbeatByServerUuid[uuid].current = heartbeat; ModelServer.getMoray().putObject( buckets.status.name, self.uuid, heartbeat, function (error) { if (error) { self.log.error(error, 'modifying server last_heartbeat'); } if (ModelServer.heartbeatByServerUuid[uuid].next) { var nextHb = ModelServer.heartbeatByServerUuid[uuid].next; delete ModelServer.heartbeatByServerUuid[uuid].next; ModelServer.heartbeatByServerUuid[uuid].current = nextHb; self.onHeartbeat(nextHb, callback); return; } else { ModelServer.heartbeatByServerUuid[uuid] = {}; } callback(error); }); }; ModelServer.prototype.getLastHeartbeat = function Server$getLastHeartbeat(callback) { var self = this; var uuid = this.uuid; ModelServer.getMoray().getObject( buckets.status.name, uuid, function (error, obj) { if (error && error.name === 'ObjectNotFoundError') { self.log.error('last_heartbeat for %s not found in moray', uuid); callback(); return; } else if (error) { self.log.error(error, 'error fetching last_heartbeat from moray'); callback(error); return; } callback(null, obj.value.last_heartbeat); }); }; /** * This is called when we have determined that the sime since last heartbeat * for a given compute has exceeded the threshold for us to consider it * reachable. */ ModelServer.prototype.onHeartbeatTimeoutExpired = function () { var self = this; self.log.warn('server %s heartbeat timeout', self.uuid); var uuid = self.uuid; var lasthb; var server, serverobj; clearTimeout(ModelServer.getApp().statusTimeouts[uuid]); ModelServer.getApp().statusTimeouts[uuid] = null; // Get server // Get last_heartbeat // modify server status if last_heartbeat is not within range async.waterfall([ getLastHeartbeat, getServer, function (next) { if (!serverobj) { self.log.info( { uuid: uuid }, 'could not find server'); return next(); } var now = Date.now(); var then = new Date(lasthb).valueOf(); var timeout = common.HEARTBEATER_PERIOD; if ((now - then) > timeout * 1000) { server.modify({ status: 'unknown' }, function (err) { if (err) { self.log.error(err); } self.log.warn( { uuid: uuid }, 'no heartbeat from server in %d ' + 'seconds, status => unknown', common.HEARTBEATER_PERIOD); }); } else { // It we got here it me means we didn't receive a heartbeat // from that server before our timeout, but when we checked // the server the last_heartbeat timestamp appears to have // been updated by another cnapi instance. Everything is // okay. self.log.info( { uuid: uuid }, 'no heartbeat from server but last_heartbeat looks ' + 'ok (now=%d then=%d d=%d)', now, then, now-then); } } ], function (err) { if (err) { self.log.error(err, 'writing status after server heartbeat timeout exceeeded'); } }); function getLastHeartbeat(next) { self.getLastHeartbeat(function (err, hb) { if (err) { return next(err); } lasthb = hb; next(); }); } function getServer(next) { ModelServer.get(uuid, function (err, s, so) { if (err) { self.log.error( err, 'error looking up server with expired heartbeat timer'); } server = s; serverobj = so; next(); }); } }; function clone(obj, dest) { var target = dest ? dest : ((obj instanceof Array) ? [] : {}); for (var i in obj) { if (obj[i] && typeof (obj[i]) == 'object') { target[i] = clone(obj[i]); } else { target[i] = obj[i]; } } return target; } ModelServer.get = function (uuid, callback) { var server = new ModelServer(uuid); server.getRaw(function (err, serverobj) { callback(err, server, serverobj); }); }; /** * Delete all references to a server. */ ModelServer.prototype.del = function (callback) { var self = this; self.log.info('Deleting server %s from moray', self.uuid); ModelServer.getMoray().delObject( buckets.servers.name, self.uuid, function (error) { callback(error); }); }; /** * Initialize the internal server representation. */ ModelServer.prototype.setRaw = function (raw, callback) { this.value = clone(raw); }; /** * Filter the server attributes based on fields passed in. */ ModelServer.prototype.getFinal = function (callback) { var self = this; var extras = { vms: true, memory: true, disk: true, status: true, sysinfo: true, last_heartbeat: true, agents: true }; if (arguments.length === 2) { extras = arguments[0]; callback = arguments[1]; if (extras.all) { extras = { vms: true, memory: true, disk: true, sysinfo: true, status: true, last_heartbeat: true, agents: true }; } } var server; async.waterfall([ function (cb) { self.getRaw(function (getError, s) { if (!s) { process.nextTick(function () { try { cb(); } catch (e) { self.log.error(e, 'Error raised: '); cb(e); } }); return; } cb(); }); }, function (cb) { self.filterFields(extras, function (filterError, s) { server = s; cb(filterError); }); }, function (cb) { if (server.overprovision_ratios) { var v = qs.parse(server.overprovision_ratios); // Convert number values to strings Object.keys(v).forEach(function (k) { v[k] = +v[k]; }); server.overprovision_ratios = v; } else { delete server.overprovision_ratios; } cb(); }, function (cb) { if (server.status === 'unknown' && server.transitional_status) { server.status = server.transitional_status; delete server.transitional_status; } cb(); } ], function (error) { callback(error, server); }); }; /** * Compare the VMs given in a heartbeat with those stored in moray for a * particular server. */ ModelServer.carryForwardVMChanges = function (heartbeat, serverobj) { var self = this; var vms = {}; var vmuuid; if (!serverobj.vms) { self.log.warn('server vms member empty'); serverobj.vms = {}; } if (!heartbeat.vms) { self.log.warn({ server: this.uuid }, 'heartbeat vms member empty'); serverobj.vms = {}; return; } for (vmuuid in heartbeat.vms) { if (!serverobj.vms[vmuuid]) { self.log.trace({ vm_uuid: vmuuid }, 'heartbeat shows vm changed (now exists)'); } vms[vmuuid] = heartbeat.vms[vmuuid]; if (serverobj.vms[vmuuid] && serverobj.vms[vmuuid].last_modified !== heartbeat.vms[vmuuid].last_modified) { self.log.trace({ vm_uuid: vmuuid }, 'changed because last modified changed'); } } serverobj.vms = vms; }; /** * Initiate a workflow which orchestrates and executes the steps required to * set up new server. */ ModelServer.prototype.setup = function (params, callback) { var self = this; var job_uuid; var uuid = this.uuid; var wfParams; self.getRaw(function (geterror, raw) { wfParams = { // Set nic action to update, so that we add the nic tags // rather than replace or delete nic_action: 'update', amqp_host: ModelServer.getConfig().amqp.host, cnapi_url: ModelServer.getConfig().cnapi.url, assets_url: ModelServer.getConfig().assets.url, server_uuid: uuid, target: uuid, overprovision_ratio: raw.overprovision_ratio }; if (params.hasOwnProperty('nics')) { wfParams.nics = params.nics; } if (params.hasOwnProperty('postsetup_script')) { wfParams.postsetup_script = params.postsetup_script; } if (params.hasOwnProperty('hostname') && params.hostname) { wfParams.hostname = params.hostname; } if (params.hasOwnProperty('origin') && params.origin) { wfParams.origin = params.origin; } if (params.hasOwnProperty('creator_uuid') && params.creator_uuid) { wfParams.creator_uuid = params.creator_uuid; } async.waterfall([ function (cb) { if (params.hasOwnProperty('hostname') && params.hostname) { raw.hostname = params.hostname; self.modify(raw, function (modifyError) { cb(modifyError); }); } else { cb(); } }, function (cb) { self.log.info('Instantiating server-setup workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-setup', wfParams, function (error, job) { if (error) { self.log.error( 'Error in workflow: %s', error.message); cb(error); return; } job_uuid = job.uuid; cb(); return; }); } ], function (err) { callback(err, job_uuid); }); }); }; /** * Factory reset a server. */ ModelServer.prototype.factoryReset = function (opts, callback) { var self = this; var uuid = this.uuid; var params = { cnapi_url: ModelServer.getConfig().cnapi.url, napi_url: ModelServer.getConfig().napi.url, assets_url: ModelServer.getConfig().assets.url, server_uuid: uuid, target: uuid, origin: opts.origin, creator_uuid: opts.creator_uuid }; self.log.info('Instantiating server-factory-reset workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-factory-reset', params, function (error, job) { if (error) { self.log.error('Error in workflow: %s', error.message); callback(error); return; } callback(null, job.uuid); return; }); }; /** * Return the default boot parameters to be used when booting a server. */ ModelServer.getBootParamsDefault = function (callback) { var params = { platform: 'latest', kernel_args: {}, kernel_flags: {} }; params.kernel_args.rabbitmq = [ ModelServer.getConfig().amqp.username || 'guest', ModelServer.getConfig().amqp.password || 'guest', ModelServer.getConfig().amqp.host, ModelServer.getConfig().amqp.port || 5672 ].join(':'); ModelServer.getMoray().getObject( buckets.servers.name, 'default', function (getError, obj) { if (getError) { callback( new verror.VError(getError, 'getting default object')); return; } var server = obj.value; params.platform = server.boot_platform; var k; for (k in server.boot_params) { params.kernel_args[k] = server.boot_params[k]; } for (k in server.kernel_flags) { params.kernel_flags[k] = server.kernel_flags[k]; } params.boot_modules = server.boot_modules; params.default_console = server.default_console; params.serial = server.serial; var parts = params.kernel_args.rabbitmq.split(':'); var host = parts[2]; if (host === 'localhost') { params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; callback(null, params); return; } if (host && host.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/)) { callback(null, params); return; } else { dns.resolve(host, function (error, addrs) { if (error) { callback(error); return; } host = addrs[Math.floor(Math.random() * addrs.length)]; parts[2] = host; params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; params.kernel_args.rabbitmq = parts.join(':'); callback(null, params); return; }); } }); }; /** * Return the boot parameters to be used when booting a particular server. */ ModelServer.prototype.getBootParams = function (callback) { var self = this; self.getRaw(function (error, server) { if (error) { callback(error); return; } if (!server) { callback(null, null); return; } var params = { platform: server.boot_platform, kernel_args: { hostname: server.hostname }, kernel_flags: {} }; params.kernel_args.rabbitmq = [ ModelServer.getConfig().amqp.username || 'guest', ModelServer.getConfig().amqp.password || 'guest', ModelServer.getConfig().amqp.host, ModelServer.getConfig().amqp.port || 5672 ].join(':'); // Mix in the parameters from Moray. var bootParams = server.boot_params || {}; var kernelFlags = server.kernel_flags || {}; var bootModules = server.boot_modules || []; var i; for (i in bootParams) { if (!bootParams.hasOwnProperty(i)) { continue; } params.kernel_args[i] = bootParams[i]; } for (i in kernelFlags) { if (!kernelFlags.hasOwnProperty(i)) { continue; } params.kernel_flags[i] = kernelFlags[i]; } params.boot_modules = bootModules; params.default_console = server.default_console; params.serial = server.serial; var parts = params.kernel_args.rabbitmq.split(':'); var host = parts[2]; if (host === 'localhost') { params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; callback(null, params); return; } dns.resolve(host, function (dnserror, addrs) { if (dnserror) { callback(dnserror); return; } host = addrs[Math.floor(Math.random() * addrs.length)]; parts[2] = host; params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; params.kernel_args.rabbitmq = parts.join(':'); callback(null, params); return; }); }); }; /** * Set the boot parameters on a server object. */ ModelServer.prototype.setBootParams = function (bootParams, callback) { var self = this; self.getRaw(function (error, server) { if (error) { self.logerror('server to be modified did not exist'); callback(error); return; } server.default_console = bootParams.default_console; server.serial = bootParams.serial; server.boot_params = bootParams.boot_params; server.boot_platform = bootParams.boot_platform; server.kernel_flags = bootParams.kernel_flags || {}; server.boot_modules = bootParams.boot_modules || []; self.modify(server, function (modifyError) { callback(modifyError); return; }); }); }; ModelServer.prototype.updateBootParams = function (bootParams, callback) { var self = this; self.getRaw(function (error, server) { if (error) { self.logerror('server to be modified did not exist'); callback(error); return; } if (bootParams.boot_platform) { server.boot_platform = bootParams.boot_platform; } if (bootParams.boot_modules) { server.boot_modules = bootParams.boot_modules; } var k; if (bootParams.boot_params) { if (!server.boot_params) { server.boot_params = {}; } for (k in bootParams.boot_params) { if (bootParams.boot_params[k] === null) { delete server.boot_params[k]; continue; } server.boot_params[k] = bootParams.boot_params[k]; } } if (bootParams.kernel_flags) { if (!server.kernel_flags) { server.kernel_flags = {}; } for (k in bootParams.kernel_flags) { if (bootParams.kernel_flags[k] === null) { delete server.kernel_flags[k]; continue; } server.kernel_flags[k] = bootParams.kernel_flags[k]; } } var names = ['default_console', 'serial']; names.forEach(function (n) { if (bootParams[n] === null) { server[n] = ''; return; } server[n] = bootParams[n] || server[n]; }); self.modify(server, function (modifyError) { if (error) { callback(new verror.VError( modifyError, 'modifying server boot param')); return; } callback(); return; }); }); }; /** * Returns a function which acts as a handler for provisioner tasks. * * createTaskHandler takes three arguments: * - self: a reference to an instance of Model * - eventCallback: which will be called whenever an event is received from * the running task. It gets as arguments the task id and the event object. * - callback: the function to be called when the returned function sets up * the task handle handler. */ ModelServer.createTaskHandler = function (self, params, handlerOpts, eventCallback, callback, synccb) { var persist = handlerOpts.persist !== false ? true : false; var taskqueue = async.queue(function (qobj, cb) { var task = qobj; if (!persist) { checkFinished(); cb(); return; } var moray = ModelServer.getMoray(); moray.putObject( buckets.tasks.name, task.id, task, function (putError) { if (putError) { self.log.error({ err: putError, task_id: task.id }, 'error doing putObject'); } checkFinished(); cb(); }); function checkFinished() { var lastHist = task.history[task.history.length-1]; if (['complete', 'failure'].indexOf(task.status) !== -1) { var error; if (lastHist && lastHist.event.msg && lastHist.event.msg.error) { error = lastHist.event.msg.error; } ModelServer.getApp().alertWaitingTasks( error && new Error(error), task.id, task); if (synccb) { synccb(null, error ? error: lastHist.event); } } else { // On the first push to async.queue, history won't have // anything in it so do not try to pull anything out of it. if (task.history.length) { var event = lastHist.event; eventCallback(task, event); } } } }, 1); if (synccb) { synccb = once(synccb); } return function (taskHandle) { var task = {}; self.log.info('Task id = %s', taskHandle.id); task.id = taskHandle.id; task.task = params.task; task.progress = 0; task.server_uuid = self.uuid; task.status = 'active'; task.history = []; task.timestamp = (new Date()).toISOString(); if (persist) { var moray = ModelServer.getMoray(); moray.putObject(buckets.tasks.name, taskHandle.id, task, function (putError) { if (putError) { self.log.error({ err: putError }, 'writing initial task details to moray'); return; } taskqueue.push(JSON.parse(JSON.stringify(task))); callback(null, taskHandle); }); } else { taskqueue.push(JSON.parse(JSON.stringify(task))); callback(null, taskHandle); } taskHandle.on('event', function (eventName, msg) { var event = { name: eventName, event: msg }; self.log.debug(event, 'Event details'); if (!event.timestamp) { event.timestamp = (new Date()).toISOString(); } task.history.push(event); switch (eventName) { case 'progress': task.progress = msg.value; break; case 'error': if (task.status === 'active') { task.status = 'failure'; taskqueue.push(JSON.parse(JSON.stringify(task))); } break; case 'finish': if (task.status === 'active') { task.status = 'complete'; taskqueue.push(JSON.parse(JSON.stringify(task))); } break; default: break; } }); }; }; ModelServer.prototype.sendTaskRequest = function () { var self = this; var transport; if (ModelServer.getConfig().useCnAgent === true) { transport = 'http'; } else { transport = 'amqp'; } self.log.info('sending task to %s via %s', self.uuid, transport); if (transport === 'http') { self.sendHttpTaskRequest.apply(self, arguments); } else { self.sendAmqpTaskRequest.apply(self, arguments); } }; ModelServer.prototype.sendAmqpTaskRequest = function (opts) { var self = this; var task, params, evcb, cb, req_id, synccb, persist; task = opts.task; persist = opts.persist !== false ? true : false; params = opts.params; params.task = task; evcb = opts.evcb || function () {}; cb = opts.cb; synccb = opts.synccb; req_id = opts.req_id || (opts.req && opts.req.getId()); self.log.debug({server: self.uuid, task: task, params: params}, 'sendTaskRequest'); var createHandlerOpts = { persist: true }; createHandlerOpts.persist = persist !== false ? true : false; params = JSON.parse(JSON.stringify(params)); params.req_id = req_id; ModelServer.getTaskClient().getAgentHandle( PROVISIONER, self.uuid, function (handle) { handle.sendTask( task, params, ModelServer.createTaskHandler( self, params, createHandlerOpts, evcb, cb, synccb)); }); }; /* * Initiates a cn-agent task http request. */ ModelServer.prototype.sendHttpTaskRequest = function (opts) { var self = this; var task, params, callback, origreq, persist; var synccb; var serverAdminIp; var client; var taskstatus = { id: common.genId(), req_id: opts.req_id, task: opts.task, server_uuid: self.uuid, status: 'active', timestamp: (new Date()).toISOString() }; task = opts.task; persist = opts.persist !== false ? true : false; params = opts.params; origreq = opts.req; callback = opts.cb; synccb = opts.synccb; var payload = { task: task, params: params }; self.log.info('Task id = %s', taskstatus.id); /** * Pull sysinfo for server out of moray * Get IP address of server from sysinfo * Create task payload */ async.waterfall([ function (wfcb) { self.getRaw(function (err, server) { if (err) { wfcb(new verror.VError(err, err)); return; } if (!server) { wfcb(new verror.VError('server not found')); return; } try { serverAdminIp = firstAdminIp(server.sysinfo); } catch (e) { callback( new verror.VError(e, 'parsing server ip address')); return; } self.log.info( 'sysinfo for %s before task %s', self.uuid, task); wfcb(); }); }, function (wfcb) { if (persist) { updateTask(wfcb); return; } wfcb(); }, function (wfcb) { var cOpts = { url: 'http://' + serverAdminIp + ':' + 5309, requestTimeout: 3600 * 1000, connectTimeout: 3600 * 1000 }; var rOpts = { path: '/tasks' }; if (origreq) { rOpts.headers = { 'x-server-uuid': self.uuid, 'x-request-id': origreq.getId() }; } client = restify.createJsonClient(cOpts); self.log.info( 'posting task to %s%s', cOpts.url, rOpts.path); // write initial task to moray // post http request // on response from post, write to moray again // call evcb(); // TODO get taskstatus.history from the response from cn-agent client.post(rOpts, payload, function (err, req, res, obj) { client.close(); if (err) { taskstatus.status = 'failure'; var message = obj && obj.error ? obj.error : (err.message ? err.message : 'no error given'); taskstatus.history = [ { name: 'error', timestamp: (new Date()).toISOString(), event: { error: { message: message } } }, { name: 'finish', timestamp: (new Date()).toISOString(), event: {} } ]; updateTask(function () { ModelServer.getApp().alertWaitingTasks( err, taskstatus.id, taskstatus); }); var e = new verror.VError(err, 'posting task to cn-agent'); self.log.error(e, 'posting task to cn-agent'); if (obj) { e.orig = obj; } if (synccb) { synccb(e); } return; } taskstatus.status = 'complete'; taskstatus.history = [ { name: 'finish', timestamp: (new Date()).toISOString(), event: obj } ]; if (persist) { updateTask(function () { ModelServer.getApp().alertWaitingTasks( err, taskstatus.id); }); } self.log.info({ obj: obj }, 'post came back with'); if (synccb) { synccb(null, obj); } }); wfcb(); } ], function (error) { self.log.info('done posting task to client'); callback(null, taskstatus); }); function updateTask(cb) { var moray = ModelServer.getMoray(); moray.putObject(buckets.tasks.name, taskstatus.id, taskstatus, function (putError) { if (putError) { self.log.error({ err: putError }, 'writing initial task details to moray'); cb(putError); return; } if (cb) { cb(); } }); } }; ModelServer.prototype.zfsTask = function (task, options, callback) { var self = this; var request = { task: task, cb: function (error, taskstatus) { }, evcb: function () {}, synccb: function (error, result) { callback(error, result); }, req_id: options.req_id, params: options }; self.sendTaskRequest(request); }; /** * Return a VM model. */ ModelServer.prototype.getVM = function (uuid) { return new ModelVM({ serverUuid: this.uuid, uuid: uuid }); }; ModelServer.prototype.getWaitlist = function () { return new ModelWaitlist({ uuid: this.uuid }); }; function firstAdminIp(sysinfo) { var interfaces; var addr; // first see if we have an override in the sysinfo addr = sysinfo['Admin IP']; if (addr) { return addr; } interfaces = sysinfo['Network Interfaces']; for (var iface in interfaces) { if (!interfaces.hasOwnProperty(iface)) { continue; } var nic = interfaces[iface]['NIC Names']; var isAdmin = nic.indexOf('admin') !== -1; if (isAdmin) { addr = interfaces[iface]['ip4addr']; return addr; } } throw new Error('No NICs with name "admin" detected.'); } module.exports = ModelServer;
lib/models/server.js
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * * This file contains all the Compute Server logic, used to interface with the * server as well as it's stored representation in the backend datastores. */ var async = require('async'); var assert = require('assert-plus'); var dns = require('dns'); var qs = require('querystring'); var restify = require('restify'); var sprintf = require('sprintf').sprintf; var util = require('util'); var verror = require('verror'); var once = require('once'); var buckets = require('../apis/moray').BUCKETS; var common = require('../common'); var ModelBase = require('./base'); var ModelVM = require('./vm'); var ModelWaitlist = require('./waitlist'); var ModelPlatform = require('./platform'); var PROVISIONER = 'provisioner'; var MEMORY_USAGE_KEYS = [ 'memory_available_bytes', 'memory_arc_bytes', 'memory_total_bytes', 'memory_provisionable_bytes' ]; var DISK_USAGE_KEYS = [ 'disk_cores_quota_bytes', 'disk_cores_quota_used_bytes', 'disk_installed_images_used_bytes', 'disk_kvm_quota_bytes', 'disk_kvm_quota_used_bytes', 'disk_kvm_zvol_used_bytes', 'disk_kvm_zvol_volsize_bytes', 'disk_pool_alloc_bytes', 'disk_pool_size_bytes', 'disk_system_used_bytes', 'disk_zone_quota_bytes', 'disk_zone_quota_used_bytes' ]; /** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ModelServer encapsulates the logic for manipulating and interacting * servers and their back-end storage representation. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ function ModelServer(uuid) { if (!uuid) { throw new Error('ModelServer missing uuid parameter'); } this.value = null; this.uuid = uuid; this.log = ModelServer.getLog(); } ModelServer.prototype.getValue = function () { return clone(this.value); }; /** * * One-time initialization for some things like logs and caching. */ ModelServer.init = function (app) { this.app = app; Object.keys(ModelBase.staticFn).forEach(function (p) { ModelServer[p] = ModelBase.staticFn[p]; }); ModelServer.tasks = {}; ModelServer.log = app.getLog(); ModelServer.heartbeatByServerUuid = {}; }; ModelServer.createProvisionerEventHandler = function (app, jobuuid) { var self = this; var workflow = ModelServer.getWorkflow(); return function (task, event) { var taskid = task.id; if (!jobuuid) { return; } self.log.info( 'Posting task info (task %s) to workflow jobs endpoint (job %s)', taskid, jobuuid); workflow.getClient().client.post( '/jobs/' + jobuuid + '/info', event, function (error, req, res, obj) { if (error) { self.log.error( error, 'Error posting info to jobs endpoint'); return; } self.log.info( 'Posted task info (task %s, job %s)', taskid, jobuuid); }); }; }; /** * Return a list of servers matching given criteria. */ ModelServer.list = function (params, callback) { var self = this; var uuid = params.uuid; callback = once(callback); var extras = params.extras || { status: true, last_heartbeat: true }; this.log.debug(params, 'Listing servers'); var wantFinal = params.wantFinal; var filterParams = [ 'datacenter', 'setup', 'reservoir', 'headnode', 'reserved', 'hostname' ]; var filter = ''; if (Array.isArray(uuid)) { var uuidFilter = uuid.map(function (u) { return '(uuid=' + u + ')'; }).join(''); filter += '(|' + uuidFilter + ')'; } else if (uuid) { filter += '(uuid=' + uuid + ')'; } else { filter += '(uuid=*)'; } var paramsFilter = []; filterParams.forEach(function (p) { if (!params.hasOwnProperty(p) || typeof (params[p]) === 'undefined') { return; } if (!buckets.servers.bucket.index[p]) { return; } if (buckets.servers.bucket.index[p].type === 'string') { paramsFilter.push( sprintf('(%s=%s)', p, common.filterEscape(params[p]))); } else if (buckets.servers.bucket.index[p].type === 'number') { paramsFilter.push( sprintf('(%s=%s)', p, common.filterEscape(params[p]))); } else if (buckets.servers.bucket.index[p].type === 'boolean') { paramsFilter.push( sprintf('(%s=%s)', p, common.filterEscape(params[p]))); } }); paramsFilter.push('!(uuid=default)'); if (paramsFilter.length > 1) { filter = sprintf('(&%s(&%s))', filter, paramsFilter.join('')); } else if (paramsFilter.length === 1) { filter = sprintf('(&%s%s)', filter, paramsFilter[0]); } var moray = ModelServer.getMoray(); var findOpts = { sort: { attribute: 'uuid', order: 'ASC' } }; ['limit', 'offset'].forEach(function (f) { if (params.hasOwnProperty(f)) { findOpts[f] = params[f]; } }); var servers = []; var serverStatus = {}; async.parallel([ // Get all server records function (next) { var req = moray.findObjects( buckets.servers.name, filter, findOpts); req.on('error', onError); req.on('record', onRecord); req.on('end', next); function onError(error) { self.log.error(error, 'error retriving servers'); next(error); } function onRecord(server) { servers.push(server.value); } }, // Get all server record last_heartbeat data function (next) { // XXX write me a getAllServerStatuses function that can return > // 1000 results if (extras.last_heartbeat === false) { next(); return; } var req = moray.findObjects( buckets.status.name, '(server_uuid=*)', {}); req.on('error', onError); req.on('record', onRecord); req.on('end', next); function onError(error) { self.log.error(error, 'error retriving last_heartbeats'); next(error); } function onRecord(status) { serverStatus[status.value.server_uuid] = status.value; } } ], function (err) { processResults(err); }); function processResults(err) { if (err) { callback(err); return; } if (!wantFinal) { callback(null, servers); return; } async.map( servers, function (server, cb) { var serverModel = new ModelServer(server.uuid); if (serverStatus.hasOwnProperty(server.uuid)) { server.last_heartbeat = serverStatus[server.uuid].last_heartbeat; } serverModel.setRaw(server); serverModel.getFinal(extras, function (error, s) { cb(null, s); }); }, function (error, results) { callback(null, results); }); } }; /** * Initiate a workflow, which can may be can be added to which is run whenever * a new server starts up and sends its sysinfo payload via Ur. */ ModelServer.beginSysinfoWorkflow = function (sysinfo, callback) { var self = this; if (!ModelServer.app.workflow.connected) { self.log.warn( 'Cannot start sysinfo workflow: cannot reach workflow API'); } var uuid = sysinfo.UUID; var params = { sysinfo: sysinfo, server_uuid: uuid, target: uuid, admin_uuid: ModelServer.getConfig().adminUuid }; self.log.info('Instantiating server-sysinfo workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-sysinfo', params, function (error, job) { if (error) { self.log.error('Error in workflow: %s', error.message); if (callback) { callback(error); } return; } if (callback) { callback(); } }); }; /** * Creates an object that will contain default values for new servers. */ ModelServer.setDefaultServer = function (values, callback) { var self = this; var defaultServer; if (arguments.length === 2) { defaultServer = { uuid: 'default' }; for (var k in values) { defaultServer[k] = values[k]; } storeDefault(); } else { defaultServer = { uuid: 'default', default_console: 'serial', serial: 'ttyb', boot_params: {}, kernel_flags: {}, boot_modules: [], boot_platform: ModelServer.getApp().liveimage }; callback = arguments[0]; storeDefault(); } function storeDefault() { var moray = ModelServer.getMoray(); moray.putObject( buckets.servers.name, 'default', defaultServer, function (putError) { if (putError) { self.log.error('Could not store default server'); callback( verror.VError(putError, 'failed to store default server')); return; } callback(); }); } }; ModelServer.updateDefaultServer = function (values, callback) { var self = this; var moray = ModelServer.getMoray(); moray.getObject( buckets.servers.name, 'default', function (error, obj) { if (error) { self.log.error(error, 'Could not store default server'); callback(new verror.VError( error, 'failed to store default server')); return; } var server = obj.value; if (!server.boot_params) { server.boot_params = {}; } if (values.boot_modules) { server.boot_modules = values.boot_modules; } if (values.boot_platform) { server.boot_platform = values.boot_platform; } if (values.boot_modules) { server.boot_modules = values.boot_modules; } var boot_params = values.boot_params || {}; var kernel_flags = values.kernel_flags || {}; var k; for (k in kernel_flags) { if (kernel_flags[k] === null) { delete server.kernel_flags[k]; continue; } server.kernel_flags = server.kernel_flags || {}; server.kernel_flags[k] = kernel_flags[k]; } for (k in boot_params) { if (boot_params[k] === null) { delete server.boot_params[k]; continue; } server.boot_params = server.boot_params || {}; server.boot_params[k] = boot_params[k]; } var names = ['default_console', 'serial']; names.forEach(function (n) { if (values[n] === null) { delete server[n]; return; } server[n] = values[n] || server[n]; }); moray.putObject( buckets.servers.name, 'default', server, function (putError) { if (putError) { self.log.error('Could not store default server'); callback(verror.VError( putError, 'failed to store default server')); return; } callback(); }); }); }; /** * Execute a command on a particular server via Ur. */ ModelServer.prototype.invokeUrScript = function (script, params, callback) { var self = this; var uuid = this.uuid; var opts = { uuid: uuid, message: { type: 'script', script: script, args: params.args || [], env: params.env || {} } }; self.log.info('Sending compute node %s script', uuid); ModelServer.getUr().execute(opts, function (err, stdout, stderr) { if (err) { self.log.error('Error raised by ur when ' + 'running script: ' + err.message); return callback(err); } return callback(err, stdout, stderr); }); }; /** * Reboot a server. */ ModelServer.prototype.reboot = function (params, callback) { var self = this; if (!callback) { callback = params; } var uuid = this.uuid; var wfParams; self.getRaw(function (geterror, raw) { wfParams = { cnapi_url: ModelServer.getConfig().cnapi.url, server_uuid: uuid, target: uuid, origin: params.origin, creator_uuid: params.creator_uuid }; self.log.info('Instantiating server-reboot workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-reboot', wfParams, function (error, job) { if (error) { self.log.error('Error in workflow: %s', error.message); callback(error); return; } callback(null, job.uuid); return; }); }); }; /** * Format an error message with */ ModelServer.prototype.errorFmt = function (str) { return sprintf('Error (server=%s): %s', this.uuid, str); }; /** * Logs an error message along with the relevant error object. */ ModelServer.prototype.logerror = function (error, str) { var self = this; this.log.error(error, self.errorFmt(str)); }; /** * Fetches and returns the server's values and merges * them with the raw internal values. */ ModelServer.prototype.filterFields = function (fields, callback) { var self = this; var server = clone(self.value); function isBoolean(a) { return !!a === a; } function skip(f, fo) { var ret = ( !isBoolean(fo[f]) || !fo[f]); return ret; } async.parallel([ function (cb) { if (skip('last_heartbeat', fields)) { delete server.last_heartbeat; cb(); return; } cb(); }, function (cb) { if (skip('status', fields)) { delete server.status; cb(); return; } server.status = server.status || 'unknown'; self.log.debug( 'Status for %s was %s', self.uuid, server.status); cb(); }, function (cb) { if (skip('memory', fields)) { for (var k in MEMORY_USAGE_KEYS) { delete server[MEMORY_USAGE_KEYS[k]]; } cb(); return; } cb(); }, function (cb) { if (skip('disk', fields)) { for (var k in DISK_USAGE_KEYS) { delete server[DISK_USAGE_KEYS[k]]; } cb(); return; } cb(); }, function (cb) { if (skip('vms', fields)) { delete server.vms; cb(); return; } cb(); }, function (cb) { if (skip('agents', fields)) { delete server.agents; cb(); return; } cb(); } ], function (error) { if (error) { callback(error); return; } callback(null, server); }); }; ModelServer.prototype.updateFromVmsUpdate = function (heartbeat, callback) { var self = this; var serverobj = {}; async.waterfall([ // Get the server object getServer, // Initialize the server object initializeServer, // Update the server's memory updateMemory, // Update the server's disk updateDisk, // Update the server status updateStatus, // Write the change to moray writeServerRecord ], function (error) { callback(error); }); function getServer(cb) { self.getRaw(function (err, so, s) { if (err) { cb(new verror.VError(err, 'retrieving server on heartbeat')); return; } serverobj = so; cb(); }); } function initializeServer(cb) { if (!serverobj) { self.log.info( 'heartbeat server %s was not found in moray, ' + 'initializing new server record', self.uuid); // Initialize new server record from default params ModelServer.initialValues({}, function (error, so) { if (error) { cb(error); return; } serverobj = so; serverobj.uuid = self.uuid; serverobj.vms = {}; cb(); }); return; } else { if (!serverobj.sysinfo) { ModelServer.getApp().needSysinfoFromServer(self.uuid); } ModelServer.carryForwardVMChanges(heartbeat, serverobj); } cb(); } function updateMemory(cb) { if (!serverobj.sysinfo) { cb(); return; } var memoryKeys = [ ['availrmem_bytes', 'memory_available_bytes'], ['arcsize_bytes', 'memory_arc_bytes'], ['total_bytes', 'memory_total_bytes'] ]; memoryKeys.forEach(function (keys) { serverobj[keys[1]] = heartbeat.meminfo[keys[0]]; }); /** * Compute the memory_provisionable_bytes value based on the total * memory, the reservation ratio and the max_physical_memory values * of all vms. */ var reservation_ratio = serverobj.reservation_ratio; var total_memory_bytes = serverobj.sysinfo['MiB of Memory'] * 1024 * 1024; serverobj.memory_provisionable_bytes = total_memory_bytes - (total_memory_bytes * reservation_ratio); serverobj.memory_provisionable_bytes -= 1024 * 1024 * Object.keys(heartbeat.vms) .map(function (uuid) { return heartbeat.vms[uuid]; }) .reduce(function (prev, curr) { return prev + curr.max_physical_memory; }, 0); serverobj.memory_provisionable_bytes = Math.floor(serverobj.memory_provisionable_bytes); cb(); } function updateDisk(cb) { var diskKeys = [ ['cores_quota_bytes', 'disk_cores_quota_bytes'], ['cores_quota_used_bytes', 'disk_cores_quota_used_bytes'], ['installed_images_used_bytes', 'disk_installed_images_used_bytes'], ['kvm_quota_bytes', 'disk_kvm_quota_bytes'], ['kvm_quota_used_bytes', 'disk_kvm_quota_used_bytes'], ['kvm_zvol_used_bytes', 'disk_kvm_zvol_used_bytes'], ['kvm_zvol_volsize_bytes', 'disk_kvm_zvol_volsize_bytes'], ['pool_alloc_bytes', 'disk_pool_alloc_bytes'], ['pool_size_bytes', 'disk_pool_size_bytes'], ['system_used_bytes', 'disk_system_used_bytes'], ['zone_quota_bytes', 'disk_zone_quota_bytes'], ['zone_quota_used_bytes', 'disk_zone_quota_used_bytes'] ]; diskKeys.forEach(function (keys) { if (heartbeat.diskinfo.hasOwnProperty(keys[0])) { serverobj[keys[1]] = heartbeat.diskinfo[keys[0]]; } }); cb(); } function updateStatus(cb) { serverobj.transport = heartbeat.transport; serverobj.status = 'running'; serverobj.last_heartbeat = (new Date()).toISOString(); cb(); } function writeServerRecord(cb) { self.modify(serverobj, function (err) { if (err) { self.log.error(err); } cb(err); }); } }; /** * Returns a copy of the server model's internal representation retried from * the backend store, or from memory if this object has been previously * fetched. */ ModelServer.prototype.getRaw = function (callback) { var self = this; var uuid = self.uuid; var server; if (self.exists === false) { this.log.warn( '%s was not found previously, returning negative result', uuid); callback(); return; } if (self.value) { server = clone(self.value); callback(null, server); } else { this.log.trace('Fetching server %s from moray', uuid); ModelServer.getMoray().getObject( buckets.servers.name, uuid, function (error, obj) { if (error && error.name === 'ObjectNotFoundError') { self.exists = false; self.log.error('Server %s not found in moray', uuid); callback(); return; } else if (error) { self.log.error(error, 'Error fetching server from moray'); callback(error); return; } self.found = true; self.exists = true; server = clone(obj.value); self.value = obj.value; callback(null, server); }); } }; ModelServer.updateServerPropertiesFromSysinfo = function (opts) { var server = opts.server; var sysinfo = opts.sysinfo; server.sysinfo = sysinfo; server.ram = Number(sysinfo['MiB of Memory']); server.current_platform = sysinfo['Live Image']; server.headnode = sysinfo['Boot Parameters']['headnode'] === 'true'; server.boot_platform = server.boot_platform || sysinfo['Live Image']; server.hostname = server.hostname || sysinfo['Hostname']; server.agents = server.agents || sysinfo['SDC Agents']; if (sysinfo['SDC Version'] === '7.0' && !sysinfo.hasOwnProperty('Setup')) { if (sysinfo.hasOwnProperty('Zpool')) { server.setup = true; } else { server.setup = false; } } else if (sysinfo.hasOwnProperty('Setup')) { if (sysinfo['Setup'] === 'true' || sysinfo['Setup'] === true) { server.setup = true; } else if (sysinfo['Setup'] === 'false' || sysinfo['Setup'] === false) { server.setup = false; } } return server; }; /** * Create a server object suitable for insertion into Moray */ ModelServer.initialValues = function (opts, callback) { var self = this; var boot_params; async.waterfall([ function (cb) { ModelServer.getBootParamsDefault( function (error, params) { boot_params = params; if (boot_params.kernel_args.rabbitmq_dns) { boot_params.kernel_args.rabbitmq = boot_params.kernel_args.rabbitmq_dns; delete boot_params.kernel_args.rabbitmq_dns; } cb(); }); } ], function (error) { if (error) { callback(error); return; } var server = {}; server.agents = []; server.datacenter = ModelServer.getConfig().datacenter_name; server.overprovision_ratio = 1.0; server.reservation_ratio = 0.15; server.reservoir = false; server.traits = {}; server.rack_identifier = ''; server.comments = ''; server.uuid = self.uuid; server.reserved = false; server.vms = {}; server.boot_platform = boot_params.platform; server.boot_params = boot_params.kernel_args || {}; server.kernel_flags = boot_params.kernel_flags || {}; server.default_console = boot_params.default_console || 'serial'; server.serial = boot_params.serial || 'ttyb'; server.created = (new Date()).toISOString(); callback(null, server); }); }; /** * Create a server object in Moray. Use the sysinfo values if they are given in * the opts argument. If no sysinfo values are given, do a sysinfo lookup on * the server via Ur, and then create the server using those values. */ ModelServer.prototype.create = function (opts, callback) { var self = this; var server = {}; self.log.info({ opts: opts }, 'server creation opts'); async.waterfall([ function (cb) { ModelServer.initialValues({}, function (err, s) { server = s; server.uuid = opts.sysinfo.UUID; server.created = opts.created; server.sysinfo = opts.sysinfo; server.ram = opts.sysinfo['MiB of Memory']; server.hostname = opts.sysinfo.Hostname; server.status = opts.status; server.headnode = opts.sysinfo['Boot Parameters']['headnode'] === 'true'; server.current_platform = opts.sysinfo['Live Image']; server.setup = opts.setup; server.last_boot = opts.last_boot; cb(); }); } ], function (error) { self.store( server, function (createError, createdServer) { if (createError) { self.log.error( createError, 'Error creating server in moray'); callback(createError); return; } self.log.info('Stored server record in moray'); callback(null, server); }); }); }; /** * Create a server record in moray. */ ModelServer.prototype.store = function (server, callback) { var self = this; var uuid = server['uuid']; delete server.memory; ModelServer.getMoray().putObject( buckets.servers.name, uuid, server, function (error) { if (error) { self.log.error(error, 'Error adding server to moray'); callback(error); return; } callback(); }); }; /** * Modify a server record. */ ModelServer.prototype.modify = function (server, callback) { var self = this; self.value = self.value || {}; self.value = clone(server, self.value); // Remove obsolete attributes delete self.value.serial_speed; delete self.value.images; self.log.trace({ server: self.value.uuid }, 'Writing server %s to moray', self.value.uuid); ModelServer.getMoray().putObject( buckets.servers.name, self.uuid, self.value, function (error) { if (error) { self.logerror(error, 'modifying server'); } callback(error); }); }; /** * Modify a server record. */ ModelServer.prototype.onHeartbeat = function (heartbeat, callback) { if (!callback) { callback = heartbeat; heartbeat = null; } assert.func(callback, 'callback'); var self = this; var uuid = self.uuid; ModelServer.getApp().refreshServerHeartbeatTimeout(self.uuid); if (!ModelServer.getApp().collectedGlobalSysinfo) { callback(); return; } if (!ModelServer.getMoray().connected) { self.log.warn( 'cannot refresh server from heartbeat: cannot reach moray'); return; } if (!ModelServer.heartbeatByServerUuid) { ModelServer.heartbeatByServerUuid = {}; } if (!ModelServer.heartbeatByServerUuid[uuid]) { ModelServer.heartbeatByServerUuid[uuid] = {}; } if (!heartbeat) { heartbeat = { server_uuid: self.uuid, last_heartbeat: (new Date()).toISOString() }; } // Check if we are still processing a heartbeat for this server. When we // begin processing a heartbeat we check if this value is set. If it is, we // update it and return. If it is not set, we set a timeout to clear it. // The reason for the timeout is do not end up stuck in this state. if (ModelServer.heartbeatByServerUuid[uuid].current) { ModelServer.heartbeatByServerUuid[uuid].next = heartbeat; self.log.warn('already writing heartbeat from %s', uuid); return; } clearTimeout(ModelServer.heartbeatByServerUuid[uuid].timeout); ModelServer.heartbeatByServerUuid[uuid].timeout = setTimeout(function () { ModelServer.heartbeatByServerUuid[uuid] = {}; }, common.HEARTBEATER_PERIOD * 2 * 1000); ModelServer.heartbeatByServerUuid[uuid].current = heartbeat; ModelServer.getMoray().putObject( buckets.status.name, self.uuid, heartbeat, function (error) { if (error) { self.log.error(error, 'modifying server last_heartbeat'); } if (ModelServer.heartbeatByServerUuid[uuid].next) { var nextHb = ModelServer.heartbeatByServerUuid[uuid].next; delete ModelServer.heartbeatByServerUuid[uuid].next; ModelServer.heartbeatByServerUuid[uuid].current = nextHb; self.onHeartbeat(nextHb, callback); return; } else { ModelServer.heartbeatByServerUuid[uuid] = {}; } callback(error); }); }; ModelServer.prototype.getLastHeartbeat = function Server$getLastHeartbeat(callback) { var self = this; var uuid = this.uuid; ModelServer.getMoray().getObject( buckets.status.name, uuid, function (error, obj) { if (error && error.name === 'ObjectNotFoundError') { self.log.error('last_heartbeat for %s not found in moray', uuid); callback(); return; } else if (error) { self.log.error(error, 'error fetching last_heartbeat from moray'); callback(error); return; } callback(null, obj.value.last_heartbeat); }); }; /** * This is called when we have determined that the sime since last heartbeat * for a given compute has exceeded the threshold for us to consider it * reachable. */ ModelServer.prototype.onHeartbeatTimeoutExpired = function () { var self = this; self.log.warn('server %s heartbeat timeout', self.uuid); var uuid = self.uuid; var lasthb; var server, serverobj; clearTimeout(ModelServer.getApp().statusTimeouts[uuid]); ModelServer.getApp().statusTimeouts[uuid] = null; // Get server // Get last_heartbeat // modify server status if last_heartbeat is not within range async.waterfall([ getLastHeartbeat, getServer, function (next) { if (!serverobj) { self.log.info( { uuid: uuid }, 'could not find server'); return next(); } var now = Date.now(); var then = new Date(lasthb).valueOf(); var timeout = common.HEARTBEATER_PERIOD; if ((now - then) > timeout * 1000) { server.modify({ status: 'unknown' }, function (err) { if (err) { self.log.error(err); } self.log.warn( { uuid: uuid }, 'no heartbeat from server in %d ' + 'seconds, status => unknown', common.HEARTBEATER_PERIOD); }); } else { // It we got here it me means we didn't receive a heartbeat // from that server before our timeout, but when we checked // the server the last_heartbeat timestamp appears to have // been updated by another cnapi instance. Everything is // okay. self.log.info( { uuid: uuid }, 'no heartbeat from server but last_heartbeat looks ' + 'ok (now=%d then=%d d=%d)', now, then, now-then); } } ], function (err) { if (err) { self.log.error(err, 'writing status after server heartbeat timeout exceeeded'); } }); function getLastHeartbeat(next) { self.getLastHeartbeat(function (err, hb) { if (err) { return next(err); } lasthb = hb; next(); }); } function getServer(next) { ModelServer.get(uuid, function (err, s, so) { if (err) { self.log.error( err, 'error looking up server with expired heartbeat timer'); } server = s; serverobj = so; next(); }); } }; function clone(obj, dest) { var target = dest ? dest : ((obj instanceof Array) ? [] : {}); for (var i in obj) { if (obj[i] && typeof (obj[i]) == 'object') { target[i] = clone(obj[i]); } else { target[i] = obj[i]; } } return target; } ModelServer.get = function (uuid, callback) { var server = new ModelServer(uuid); server.getRaw(function (err, serverobj) { callback(err, server, serverobj); }); }; /** * Delete all references to a server. */ ModelServer.prototype.del = function (callback) { var self = this; self.log.info('Deleting server %s from moray', self.uuid); ModelServer.getMoray().delObject( buckets.servers.name, self.uuid, function (error) { callback(error); }); }; /** * Initialize the internal server representation. */ ModelServer.prototype.setRaw = function (raw, callback) { this.value = clone(raw); }; /** * Filter the server attributes based on fields passed in. */ ModelServer.prototype.getFinal = function (callback) { var self = this; var extras = { vms: true, memory: true, disk: true, status: true, sysinfo: true, last_heartbeat: true, agents: true }; if (arguments.length === 2) { extras = arguments[0]; callback = arguments[1]; if (extras.all) { extras = { vms: true, memory: true, disk: true, sysinfo: true, status: true, last_heartbeat: true, agents: true }; } } var server; async.waterfall([ function (cb) { self.getRaw(function (getError, s) { if (!s) { process.nextTick(function () { try { callback(); } catch (e) { self.log.error(e, 'Error raised: '); callback(e); } }); return; } cb(); }); }, function (cb) { self.filterFields(extras, function (filterError, s) { server = s; cb(filterError); }); }, function (cb) { if (server.overprovision_ratios) { var v = qs.parse(server.overprovision_ratios); // Convert number values to strings Object.keys(v).forEach(function (k) { v[k] = +v[k]; }); server.overprovision_ratios = v; } else { delete server.overprovision_ratios; } cb(); }, function (cb) { if (server.status === 'unknown' && server.transitional_status) { server.status = server.transitional_status; delete server.transitional_status; } cb(); } ], function (error) { callback(error, server); }); }; /** * Compare the VMs given in a heartbeat with those stored in moray for a * particular server. */ ModelServer.carryForwardVMChanges = function (heartbeat, serverobj) { var self = this; var vms = {}; var vmuuid; if (!serverobj.vms) { self.log.warn('server vms member empty'); serverobj.vms = {}; } if (!heartbeat.vms) { self.log.warn({ server: this.uuid }, 'heartbeat vms member empty'); serverobj.vms = {}; return; } for (vmuuid in heartbeat.vms) { if (!serverobj.vms[vmuuid]) { self.log.trace({ vm_uuid: vmuuid }, 'heartbeat shows vm changed (now exists)'); } vms[vmuuid] = heartbeat.vms[vmuuid]; if (serverobj.vms[vmuuid] && serverobj.vms[vmuuid].last_modified !== heartbeat.vms[vmuuid].last_modified) { self.log.trace({ vm_uuid: vmuuid }, 'changed because last modified changed'); } } serverobj.vms = vms; }; /** * Initiate a workflow which orchestrates and executes the steps required to * set up new server. */ ModelServer.prototype.setup = function (params, callback) { var self = this; var job_uuid; var uuid = this.uuid; var wfParams; self.getRaw(function (geterror, raw) { wfParams = { // Set nic action to update, so that we add the nic tags // rather than replace or delete nic_action: 'update', amqp_host: ModelServer.getConfig().amqp.host, cnapi_url: ModelServer.getConfig().cnapi.url, assets_url: ModelServer.getConfig().assets.url, server_uuid: uuid, target: uuid, overprovision_ratio: raw.overprovision_ratio }; if (params.hasOwnProperty('nics')) { wfParams.nics = params.nics; } if (params.hasOwnProperty('postsetup_script')) { wfParams.postsetup_script = params.postsetup_script; } if (params.hasOwnProperty('hostname') && params.hostname) { wfParams.hostname = params.hostname; } if (params.hasOwnProperty('origin') && params.origin) { wfParams.origin = params.origin; } if (params.hasOwnProperty('creator_uuid') && params.creator_uuid) { wfParams.creator_uuid = params.creator_uuid; } async.waterfall([ function (cb) { if (params.hasOwnProperty('hostname') && params.hostname) { raw.hostname = params.hostname; self.modify(raw, function (modifyError) { cb(modifyError); }); } else { cb(); } }, function (cb) { self.log.info('Instantiating server-setup workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-setup', wfParams, function (error, job) { if (error) { self.log.error( 'Error in workflow: %s', error.message); cb(error); return; } job_uuid = job.uuid; cb(); return; }); } ], function (err) { callback(err, job_uuid); }); }); }; /** * Factory reset a server. */ ModelServer.prototype.factoryReset = function (opts, callback) { var self = this; var uuid = this.uuid; var params = { cnapi_url: ModelServer.getConfig().cnapi.url, napi_url: ModelServer.getConfig().napi.url, assets_url: ModelServer.getConfig().assets.url, server_uuid: uuid, target: uuid, origin: opts.origin, creator_uuid: opts.creator_uuid }; self.log.info('Instantiating server-factory-reset workflow'); ModelServer.getWorkflow().getClient().createJob( 'server-factory-reset', params, function (error, job) { if (error) { self.log.error('Error in workflow: %s', error.message); callback(error); return; } callback(null, job.uuid); return; }); }; /** * Return the default boot parameters to be used when booting a server. */ ModelServer.getBootParamsDefault = function (callback) { var params = { platform: 'latest', kernel_args: {}, kernel_flags: {} }; params.kernel_args.rabbitmq = [ ModelServer.getConfig().amqp.username || 'guest', ModelServer.getConfig().amqp.password || 'guest', ModelServer.getConfig().amqp.host, ModelServer.getConfig().amqp.port || 5672 ].join(':'); ModelServer.getMoray().getObject( buckets.servers.name, 'default', function (getError, obj) { if (getError) { callback( new verror.VError(getError, 'getting default object')); return; } var server = obj.value; params.platform = server.boot_platform; var k; for (k in server.boot_params) { params.kernel_args[k] = server.boot_params[k]; } for (k in server.kernel_flags) { params.kernel_flags[k] = server.kernel_flags[k]; } params.boot_modules = server.boot_modules; params.default_console = server.default_console; params.serial = server.serial; var parts = params.kernel_args.rabbitmq.split(':'); var host = parts[2]; if (host === 'localhost') { params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; callback(null, params); return; } if (host && host.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/)) { callback(null, params); return; } else { dns.resolve(host, function (error, addrs) { if (error) { callback(error); return; } host = addrs[Math.floor(Math.random() * addrs.length)]; parts[2] = host; params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; params.kernel_args.rabbitmq = parts.join(':'); callback(null, params); return; }); } }); }; /** * Return the boot parameters to be used when booting a particular server. */ ModelServer.prototype.getBootParams = function (callback) { var self = this; self.getRaw(function (error, server) { if (error) { callback(error); return; } if (!server) { callback(null, null); return; } var params = { platform: server.boot_platform, kernel_args: { hostname: server.hostname }, kernel_flags: {} }; params.kernel_args.rabbitmq = [ ModelServer.getConfig().amqp.username || 'guest', ModelServer.getConfig().amqp.password || 'guest', ModelServer.getConfig().amqp.host, ModelServer.getConfig().amqp.port || 5672 ].join(':'); // Mix in the parameters from Moray. var bootParams = server.boot_params || {}; var kernelFlags = server.kernel_flags || {}; var bootModules = server.boot_modules || []; var i; for (i in bootParams) { if (!bootParams.hasOwnProperty(i)) { continue; } params.kernel_args[i] = bootParams[i]; } for (i in kernelFlags) { if (!kernelFlags.hasOwnProperty(i)) { continue; } params.kernel_flags[i] = kernelFlags[i]; } params.boot_modules = bootModules; params.default_console = server.default_console; params.serial = server.serial; var parts = params.kernel_args.rabbitmq.split(':'); var host = parts[2]; if (host === 'localhost') { params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; callback(null, params); return; } dns.resolve(host, function (dnserror, addrs) { if (dnserror) { callback(dnserror); return; } host = addrs[Math.floor(Math.random() * addrs.length)]; parts[2] = host; params.kernel_args.rabbitmq_dns = params.kernel_args.rabbitmq; params.kernel_args.rabbitmq = parts.join(':'); callback(null, params); return; }); }); }; /** * Set the boot parameters on a server object. */ ModelServer.prototype.setBootParams = function (bootParams, callback) { var self = this; self.getRaw(function (error, server) { if (error) { self.logerror('server to be modified did not exist'); callback(error); return; } server.default_console = bootParams.default_console; server.serial = bootParams.serial; server.boot_params = bootParams.boot_params; server.boot_platform = bootParams.boot_platform; server.kernel_flags = bootParams.kernel_flags || {}; server.boot_modules = bootParams.boot_modules || []; self.modify(server, function (modifyError) { callback(modifyError); return; }); }); }; ModelServer.prototype.updateBootParams = function (bootParams, callback) { var self = this; self.getRaw(function (error, server) { if (error) { self.logerror('server to be modified did not exist'); callback(error); return; } if (bootParams.boot_platform) { server.boot_platform = bootParams.boot_platform; } if (bootParams.boot_modules) { server.boot_modules = bootParams.boot_modules; } var k; if (bootParams.boot_params) { if (!server.boot_params) { server.boot_params = {}; } for (k in bootParams.boot_params) { if (bootParams.boot_params[k] === null) { delete server.boot_params[k]; continue; } server.boot_params[k] = bootParams.boot_params[k]; } } if (bootParams.kernel_flags) { if (!server.kernel_flags) { server.kernel_flags = {}; } for (k in bootParams.kernel_flags) { if (bootParams.kernel_flags[k] === null) { delete server.kernel_flags[k]; continue; } server.kernel_flags[k] = bootParams.kernel_flags[k]; } } var names = ['default_console', 'serial']; names.forEach(function (n) { if (bootParams[n] === null) { server[n] = ''; return; } server[n] = bootParams[n] || server[n]; }); self.modify(server, function (modifyError) { if (error) { callback(new verror.VError( modifyError, 'modifying server boot param')); return; } callback(); return; }); }); }; /** * Returns a function which acts as a handler for provisioner tasks. * * createTaskHandler takes three arguments: * - self: a reference to an instance of Model * - eventCallback: which will be called whenever an event is received from * the running task. It gets as arguments the task id and the event object. * - callback: the function to be called when the returned function sets up * the task handle handler. */ ModelServer.createTaskHandler = function (self, params, handlerOpts, eventCallback, callback, synccb) { var persist = handlerOpts.persist !== false ? true : false; var taskqueue = async.queue(function (qobj, cb) { var task = qobj; if (!persist) { checkFinished(); cb(); return; } var moray = ModelServer.getMoray(); moray.putObject( buckets.tasks.name, task.id, task, function (putError) { if (putError) { self.log.error({ err: putError, task_id: task.id }, 'error doing putObject'); } checkFinished(); cb(); }); function checkFinished() { var lastHist = task.history[task.history.length-1]; if (['complete', 'failure'].indexOf(task.status) !== -1) { var error; if (lastHist && lastHist.event.msg && lastHist.event.msg.error) { error = lastHist.event.msg.error; } ModelServer.getApp().alertWaitingTasks( error && new Error(error), task.id, task); if (synccb) { synccb(null, error ? error: lastHist.event); } } else { // On the first push to async.queue, history won't have // anything in it so do not try to pull anything out of it. if (task.history.length) { var event = lastHist.event; eventCallback(task, event); } } } }, 1); if (synccb) { synccb = once(synccb); } return function (taskHandle) { var task = {}; self.log.info('Task id = %s', taskHandle.id); task.id = taskHandle.id; task.task = params.task; task.progress = 0; task.server_uuid = self.uuid; task.status = 'active'; task.history = []; task.timestamp = (new Date()).toISOString(); if (persist) { var moray = ModelServer.getMoray(); moray.putObject(buckets.tasks.name, taskHandle.id, task, function (putError) { if (putError) { self.log.error({ err: putError }, 'writing initial task details to moray'); return; } taskqueue.push(JSON.parse(JSON.stringify(task))); callback(null, taskHandle); }); } else { taskqueue.push(JSON.parse(JSON.stringify(task))); callback(null, taskHandle); } taskHandle.on('event', function (eventName, msg) { var event = { name: eventName, event: msg }; self.log.debug(event, 'Event details'); if (!event.timestamp) { event.timestamp = (new Date()).toISOString(); } task.history.push(event); switch (eventName) { case 'progress': task.progress = msg.value; break; case 'error': if (task.status === 'active') { task.status = 'failure'; taskqueue.push(JSON.parse(JSON.stringify(task))); } break; case 'finish': if (task.status === 'active') { task.status = 'complete'; taskqueue.push(JSON.parse(JSON.stringify(task))); } break; default: break; } }); }; }; ModelServer.prototype.sendTaskRequest = function () { var self = this; var transport; if (ModelServer.getConfig().useCnAgent === true) { transport = 'http'; } else { transport = 'amqp'; } self.log.info('sending task to %s via %s', self.uuid, transport); if (transport === 'http') { self.sendHttpTaskRequest.apply(self, arguments); } else { self.sendAmqpTaskRequest.apply(self, arguments); } }; ModelServer.prototype.sendAmqpTaskRequest = function (opts) { var self = this; var task, params, evcb, cb, req_id, synccb, persist; task = opts.task; persist = opts.persist !== false ? true : false; params = opts.params; params.task = task; evcb = opts.evcb || function () {}; cb = opts.cb; synccb = opts.synccb; req_id = opts.req_id || (opts.req && opts.req.getId()); self.log.debug({server: self.uuid, task: task, params: params}, 'sendTaskRequest'); var createHandlerOpts = { persist: true }; createHandlerOpts.persist = persist !== false ? true : false; params = JSON.parse(JSON.stringify(params)); params.req_id = req_id; ModelServer.getTaskClient().getAgentHandle( PROVISIONER, self.uuid, function (handle) { handle.sendTask( task, params, ModelServer.createTaskHandler( self, params, createHandlerOpts, evcb, cb, synccb)); }); }; /* * Initiates a cn-agent task http request. */ ModelServer.prototype.sendHttpTaskRequest = function (opts) { var self = this; var task, params, callback, origreq, persist; var synccb; var serverAdminIp; var client; var taskstatus = { id: common.genId(), req_id: opts.req_id, task: opts.task, server_uuid: self.uuid, status: 'active', timestamp: (new Date()).toISOString() }; task = opts.task; persist = opts.persist !== false ? true : false; params = opts.params; origreq = opts.req; callback = opts.cb; synccb = opts.synccb; var payload = { task: task, params: params }; self.log.info('Task id = %s', taskstatus.id); /** * Pull sysinfo for server out of moray * Get IP address of server from sysinfo * Create task payload */ async.waterfall([ function (wfcb) { self.getRaw(function (err, server) { if (err) { wfcb(new verror.VError(err, err)); return; } if (!server) { wfcb(new verror.VError('server not found')); return; } try { serverAdminIp = firstAdminIp(server.sysinfo); } catch (e) { callback( new verror.VError(e, 'parsing server ip address')); return; } self.log.info( 'sysinfo for %s before task %s', self.uuid, task); wfcb(); }); }, function (wfcb) { if (persist) { updateTask(wfcb); return; } wfcb(); }, function (wfcb) { var cOpts = { url: 'http://' + serverAdminIp + ':' + 5309, requestTimeout: 3600 * 1000, connectTimeout: 3600 * 1000 }; var rOpts = { path: '/tasks' }; if (origreq) { rOpts.headers = { 'x-server-uuid': self.uuid, 'x-request-id': origreq.getId() }; } client = restify.createJsonClient(cOpts); self.log.info( 'posting task to %s%s', cOpts.url, rOpts.path); // write initial task to moray // post http request // on response from post, write to moray again // call evcb(); // TODO get taskstatus.history from the response from cn-agent client.post(rOpts, payload, function (err, req, res, obj) { client.close(); if (err) { taskstatus.status = 'failure'; var message = obj && obj.error ? obj.error : (err.message ? err.message : 'no error given'); taskstatus.history = [ { name: 'error', timestamp: (new Date()).toISOString(), event: { error: { message: message } } }, { name: 'finish', timestamp: (new Date()).toISOString(), event: {} } ]; updateTask(function () { ModelServer.getApp().alertWaitingTasks( err, taskstatus.id, taskstatus); }); var e = new verror.VError(err, 'posting task to cn-agent'); self.log.error(e, 'posting task to cn-agent'); if (obj) { e.orig = obj; } if (synccb) { synccb(e); } return; } taskstatus.status = 'complete'; taskstatus.history = [ { name: 'finish', timestamp: (new Date()).toISOString(), event: obj } ]; if (persist) { updateTask(function () { ModelServer.getApp().alertWaitingTasks( err, taskstatus.id); }); } self.log.info({ obj: obj }, 'post came back with'); if (synccb) { synccb(null, obj); } }); wfcb(); } ], function (error) { self.log.info('done posting task to client'); callback(null, taskstatus); }); function updateTask(cb) { var moray = ModelServer.getMoray(); moray.putObject(buckets.tasks.name, taskstatus.id, taskstatus, function (putError) { if (putError) { self.log.error({ err: putError }, 'writing initial task details to moray'); cb(putError); return; } if (cb) { cb(); } }); } }; ModelServer.prototype.zfsTask = function (task, options, callback) { var self = this; var request = { task: task, cb: function (error, taskstatus) { }, evcb: function () {}, synccb: function (error, result) { callback(error, result); }, req_id: options.req_id, params: options }; self.sendTaskRequest(request); }; /** * Return a VM model. */ ModelServer.prototype.getVM = function (uuid) { return new ModelVM({ serverUuid: this.uuid, uuid: uuid }); }; ModelServer.prototype.getWaitlist = function () { return new ModelWaitlist({ uuid: this.uuid }); }; function firstAdminIp(sysinfo) { var interfaces; var addr; // first see if we have an override in the sysinfo addr = sysinfo['Admin IP']; if (addr) { return addr; } interfaces = sysinfo['Network Interfaces']; for (var iface in interfaces) { if (!interfaces.hasOwnProperty(iface)) { continue; } var nic = interfaces[iface]['NIC Names']; var isAdmin = nic.indexOf('admin') !== -1; if (isAdmin) { addr = interfaces[iface]['ip4addr']; return addr; } } throw new Error('No NICs with name "admin" detected.'); } module.exports = ModelServer;
CNAPI-587: fix leak
lib/models/server.js
CNAPI-587: fix leak
<ide><path>ib/models/server.js <ide> if (!s) { <ide> process.nextTick(function () { <ide> try { <del> callback(); <add> cb(); <ide> } <ide> catch (e) { <ide> self.log.error(e, 'Error raised: '); <del> callback(e); <add> cb(e); <ide> } <ide> }); <ide> return;
Java
mit
0f83842530e08de381868dc16b83ae8c1584fd7f
0
samphippen/spe,samphippen/spe,samphippen/spe,samphippen/spe
package uk.me.graphe.shared.messages.factories; import uk.me.graphe.shared.Edge; import uk.me.graphe.shared.Vertex; import uk.me.graphe.shared.VertexDirection; import uk.me.graphe.shared.jsonwrapper.JSONException; import uk.me.graphe.shared.jsonwrapper.JSONObject; import uk.me.graphe.shared.messages.Message; import uk.me.graphe.shared.messages.operations.AddEdgeOperation; public class AddEdgeFactory implements ConversionFactory { @Override public Message make(JSONObject o) { try { Vertex v1 = new Vertex(o.getString("from")); Vertex v2 = new Vertex(o.getString("to")); VertexDirection dir = VertexDirection.valueOf(o.getString("dir")); System.err.println(dir); return new AddEdgeOperation(new Edge(v1, v2, dir)); } catch (JSONException e) { e.printStackTrace(); throw new Error(e); } } }
src/uk/me/graphe/shared/messages/factories/AddEdgeFactory.java
package uk.me.graphe.shared.messages.factories; import uk.me.graphe.shared.Edge; import uk.me.graphe.shared.Vertex; import uk.me.graphe.shared.jsonwrapper.JSONException; import uk.me.graphe.shared.jsonwrapper.JSONObject; import uk.me.graphe.shared.messages.Message; import uk.me.graphe.shared.messages.operations.AddEdgeOperation; public class AddEdgeFactory implements ConversionFactory { @Override public Message make(JSONObject o) { try { Vertex v1 = new Vertex(o.getString("from")); Vertex v2 = new Vertex(o.getString("to")); return new AddEdgeOperation(new Edge(v1, v2)); } catch (JSONException e) { throw new Error(e); } } }
make addEdgeFactory direction aware this should remove the problem where edges get the wrong idea about which direction they are rendered in Signed-off-by: Sam Phippen <[email protected]>
src/uk/me/graphe/shared/messages/factories/AddEdgeFactory.java
make addEdgeFactory direction aware
<ide><path>rc/uk/me/graphe/shared/messages/factories/AddEdgeFactory.java <ide> <ide> import uk.me.graphe.shared.Edge; <ide> import uk.me.graphe.shared.Vertex; <add>import uk.me.graphe.shared.VertexDirection; <ide> import uk.me.graphe.shared.jsonwrapper.JSONException; <ide> import uk.me.graphe.shared.jsonwrapper.JSONObject; <ide> import uk.me.graphe.shared.messages.Message; <ide> try { <ide> Vertex v1 = new Vertex(o.getString("from")); <ide> Vertex v2 = new Vertex(o.getString("to")); <del> return new AddEdgeOperation(new Edge(v1, v2)); <add> VertexDirection dir = VertexDirection.valueOf(o.getString("dir")); <add> System.err.println(dir); <add> return new AddEdgeOperation(new Edge(v1, v2, dir)); <ide> } catch (JSONException e) { <add> e.printStackTrace(); <ide> throw new Error(e); <ide> } <ide> }
Java
mit
6df47a29d0ed8ef640aade9f78bae2393b59d2d3
0
cobr123/VirtaMarketAnalyzer,cobr123/VirtaMarketAnalyzer
package ru.VirtaMarketAnalyzer.parser; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.VirtaMarketAnalyzer.data.City; import ru.VirtaMarketAnalyzer.data.Product; import ru.VirtaMarketAnalyzer.data.Shop; import ru.VirtaMarketAnalyzer.data.ShopProduct; import ru.VirtaMarketAnalyzer.main.Utils; import ru.VirtaMarketAnalyzer.main.Wizard; import ru.VirtaMarketAnalyzer.scrapper.Downloader; import java.util.*; import java.util.stream.Collectors; /** * Created by cobr123 on 16.01.16. */ public final class ShopParser { private static final Logger logger = LoggerFactory.getLogger(ShopParser.class); private static final Set<String> oneTryErrorUrl = new HashSet<>(); public static void main(String[] args) throws Exception { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%r %d{ISO8601} [%t] %p %c %x - %m%n"))); // final String url = Wizard.host + "olga/main/unit/view/5788675"; final String host = Wizard.host; // final String realm = "mary"; // final String url = host + realm + "/main/unit/view/3943258"; final String realm = "olga"; final String url = host + realm + "/main/unit/view/6519771"; // Downloader.invalidateCache(url); final List<City> cities = new ArrayList<>(); cities.add(new City("422653", "422655", "422682", "Вашингтон", 0.0, 0.0, 0.0, 0)); final List<Product> products = new ArrayList<>(); products.add(ProductInitParser.getTradingProduct(host, realm, "422547")); products.add(ProductInitParser.getTradingProduct(host, realm, "3838")); final Map<String, List<Product>> productsByImgSrc = products.stream().collect(Collectors.groupingBy(Product::getImgUrl)); System.out.println(Utils.getPrettyGson(parse(realm, url, cities, productsByImgSrc, "Вашингтон"))); } public static Shop parse(final String realm, final String url, final List<City> cities, final Map<String, List<Product>> productsByImgSrc, final String cityCaption) throws Exception { final Document doc = Downloader.getDoc(url); final String countryId = Utils.getLastFromUrl(doc.select("div.officePlace > a:nth-child(2)").attr("href")); final String regionId = Utils.getLastFromUrl(doc.select("div.officePlace > a:nth-child(3)").attr("href")); String townId = ""; if (!cityCaption.isEmpty()) { final Optional<City> city = cities.stream() .filter(c -> countryId.isEmpty() || c.getCountryId().equals(countryId)) .filter(c -> regionId.isEmpty() || c.getRegionId().equals(regionId)) .filter(c -> c.getCaption().equals(cityCaption)) .findFirst(); if (city.isPresent()) { townId = city.get().getId(); } } if (townId.isEmpty()) { String dyrtyCaption = doc.select("#mainContent > div.unit_box-container > div > div:nth-child(1) > table > tbody > tr:nth-child(1) > td:nth-child(2) > a").text(); if(dyrtyCaption == null || dyrtyCaption.isEmpty()) { final Element tmpFirst = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").first(); if (tmpFirst != null && tmpFirst.children() != null) { tmpFirst.children().remove(); } dyrtyCaption = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").text(); } final String dyrtyCaptionReplaced = dyrtyCaption.replaceFirst("\\([^\\)]*\\)$", "").trim() .replace("San Diego", "Сан-Диего") .replace("Indianapolis", "Индианаполис") .replace("San Luis Potosí", "Сан-Луис-Потоси") .replace("San Luis Potosi", "Сан-Луис-Потоси") .replace("León", "Леон") .replace("Filadelfia", "Филадельфия") .replace("Tartu", "Тарту") .replace("Belfast", "Белфаст") .replace("Lisburn", "Лисберн") .replace("Leeds", "Лидс") .replace("Coventry", "Ковентри") .replace("Bamako", "Бамако") .replace("Los Angeles", "Лос-Анджелес") .replace("Hartford", "Хартфорд") .replace("Rotterdam", "Роттердам") .replace("Andijon", "Андижан") .replace("Almere", "Алмере") .replace("Moscow", "Москва") .replace("Lipetsk", "Липецк") .replace("Perm", "Пермь") .replace("Ufa", "Уфа") .replace("Omsk", "Омск") .replace("Vladivostok", "Владивосток") .replace("Nizhni Novgorod", "Нижний Новгород") .replace("Харків", "Харьков") .replace("Львів", "Львов") .replace("Novosibirsk", "Новосибирск") .replace("Khabarovsk", "Хабаровск") .replace("Hongkong", "Гонконг") .replace("Nankin", "Нанкин") .replace("Amsterdam", "Амстердам") .replace("Beijing", "Пекин") .replace("Singapore", "Сингапур") .replace("Chengdu", "Чэнду") .replace("Shimkent", "Шымкент") .replace("Guangzhou", "Гуанчжоу") .replace("Shanghai", "Шанхай") .replace("Seoul", "Сеул") .replace("Hanoi", "Ханой") .replace("Bangkok", "Бангкок") .replace("Hoshimin", "Хошимин") .replace("San Antonio", "Сан-Антонио") .replace("Santiago de Cuba", "Сантьяго-де-Куба") .replace("Pretoria", "Претория") .replace("Aguascalientes", "Агуаскальентес") .replace("Phoenix", "Финикс") .replace("Vilnius", "Вильнюс") .replace("Camaguey", "Камагуэй") .replace("Klaipeda", "Клайпеда") .replace("Buenos Aires", "Буэнос Айрес") .replace("Bergen", "Берген") .replace("Ecatepec de Morelos", "Экатепек-де-Морелос") .replace("Narva", "Нарва") .replace("Madrid", "Мадрид") .replace("Liepaja", "Лиепая") .replace("Київ", "Киев") .replace("San Miguel de Tucuman", "Сан-Мигель-де-Тукуман") .replace("Kuala-Lumpur", "Куала-Лумпур") .replace("Davao", "Давао") .replace("Saltillo", "Сальтильо") .replace("Guadalajara", "Гвадалахара") .replace("Kuala-Lumpur", "Куала-Лумпур") .replace("Surabaya", "Сурабая") .replace("Jakarta", "Джакарта") .replace("Xi'an", "Сиань") .replace("Manila", "Манила") .replace("ChiangMai", "Чиенгмай") .replace("Jacksonville", "Джексонвиль") .replace("Memphis", "Мемфис") .replace("Washington", "Вашингтон") .replace("Charlotte", "Шарлотт") .replace("Bristol", "Бристоль") .replace("Guadalupe", "Гуадалупе") .replace("New York", "Нью-Йорк") .replace("Tijuana", "Тихуана") .replace("Saint-Étienne", "Сент-Этьен") .replace("Dortmund", "Дортмунд") .replace("Montpellier", "Монпелье") .replace("Las Palmas de Gran Canaria", "Лас-Пальмас-де-Гран-Канария") .replace("Sevilla", "Севилья") .replace("Gao", "Гао") .replace("Samarqand", "Самарканд") .replace("Abu Dhabi", "Абу-Даби") .replace("Stuttgart", "Штутгарт") .replace("La Plata", "Ла-Плата") .replace("Gaziantep", "Газиантеп") .replace("Houston", "Хьюстон") .replace("Haikou", "Хайкоу") .replace("Pinar del Rio", "Пинар-дель-Рио") .replace("Oslo", "Осло") .replace("Erevan", "Ереван") .replace("Havana", "Гавана") .replace("Cape Town", "Кейптаун") .replace("Abidjan", "Абиджан") .replace("Abiyán", "Абиджан") .replace("Mexico City", "Мехико") .replace("Bonn", "Бонн") .replace("Colonia", "Кёльн") .replace("Caracas", "Каракас") .replace("Valencia (Ve)", "Валенсия (Ve)") .replace("Groningen", "Гронинген") .replace("Bouake", "Буаке") .replace("Iokogama", "Иокогама") .replace("Inchon", "Инчхон") .replace("Fukuoka", "Фукуока") .replace("Medan", "Медан") .replace("Asahikawa", "Асахикава") .replace("Kano", "Кано") .replace("Riad", "Эр-Рияд") .replace("Cologne", "Кёльн") .replace("Francfort-sur-le-Main", "Франкфурт") .replace("Berlin", "Берлин") .replace("Leipzig", "Лейпциг") .replace("Konya", "Конья") .replace("Stavanger", "Ставангер") .replace("Larissa", "Ларисса") .replace("Istanbul", "Стамбул") .replace("Jeddah", "Джидда") .replace("Dammam", "Даммам") .replace("Medina", "Медина") .replace("Dubai", "Дубай") .replace("Kuwait City", "Эль-Кувейт") .replace("Mecca", "Мекка") .replace("Sapporo", "Саппоро") .replace("Bloemfontein", "Блумфонтейн") .replace("Johannesburg", "Йоханнесбург") .replace("Strasbourg", "Страсбург") .replace("Лієпая", "Лиепая") .replace("Запоріжжя", "Запорожье") .replace("Rhodes", "Родос"); try { townId = cities.stream() .filter(c -> c.getCountryId().equals(countryId)) // .filter(c -> c.getRegionId().equals(regionId)) .filter(c -> c.getCaption().equals(dyrtyCaptionReplaced)) .findFirst().get().getId(); } catch (final Exception e) { logger.info(url); cities.stream() .filter(c -> c.getCountryId().equals(countryId)) // .filter(c -> c.getRegionId().equals(regionId)) .forEach(c -> logger.info(".replace(\"{}\", \"{}\")", dyrtyCaptionReplaced, c.getCaption())); logger.info("'dyrtyCaption = {}'", dyrtyCaptionReplaced); throw e; } } return parse(realm, "", countryId, regionId, townId, url, productsByImgSrc); } public static Shop parse(final String realm, final String productId , final String countryId, final String regionId, final String townId , final String url , final Map<String, List<Product>> productsByImgSrc ) throws Exception { Document doc = null; if (oneTryErrorUrl.contains(url)) { return null; } try { final int maxTriesCnt = 1; doc = Downloader.getDoc(url, maxTriesCnt); } catch (final Exception e) { oneTryErrorUrl.add(url); logger.error("url = https://virtonomica.ru/{}/main/globalreport/marketing/by_trade_at_cities/{}/{}/{}/{}", realm, productId, countryId, regionId, townId); logger.error(e.getLocalizedMessage()); return null; } try { final List<ShopProduct> shopProducts = new ArrayList<>(); final Elements rows = doc.select("table[class=\"grid\"] > tbody > tr[class]"); for (final Element row : rows) { try { if ("не изв.".equalsIgnoreCase(row.select("> td:nth-child(3)").first().text())) { continue; } if (row.select("> td:nth-child(1) > img").first().attr("src").contains("/brand/")) { continue; } final String prodId = productsByImgSrc.get(row.select("> td:eq(0) > img").first().attr("src")).get(0).getId(); final String sellVolume = row.select("> td:nth-child(2)").text().trim(); final double quality = Utils.toDouble(row.select("> td:nth-child(3)").text()); final double brand = Utils.toDouble(row.select("> td:nth-child(4)").text()); final double price = Utils.toDouble(row.select("> td:nth-child(5)").text()); final double marketShare = Utils.toDouble(row.select("> td:nth-child(6)").text()); final ShopProduct shopProduct = new ShopProduct(prodId, sellVolume, price, quality, brand, marketShare); shopProducts.add(shopProduct); } catch (final Exception e) { logger.info("url = {}", url); logger.info("rows.size() = {}", rows.size()); logger.error(row.outerHtml()); logger.error(e.getLocalizedMessage(), e); } } final String unitImage = doc.select("#unitImage > img").attr("src"); if (unitImage.startsWith("/img/v2/units/fuel_")) { //заправки int shopSize = Utils.toInt(unitImage.substring("/img/v2/units/fuel_".length(), "/img/v2/units/fuel_".length() + 1)); final String townDistrict = ""; final int departmentCount = 1; final double notoriety = Utils.toDouble(doc.select("table.infoblock > tbody > tr:nth-child(3) > td:nth-child(2)").text()); final String visitorsCount = doc.select("table.infoblock > tbody > tr:nth-child(4) > td:nth-child(2)").text().trim(); final String serviceLevel = doc.select("table.infoblock > tbody > tr:nth-child(5) > td:nth-child(2)").text(); return new Shop(countryId, regionId, townId, shopSize, townDistrict, departmentCount, notoriety, visitorsCount, serviceLevel, shopProducts); } else if (unitImage.startsWith("/img/v2/units/shop_")) { //магазины doc.select("table.unit_table > tbody > tr:nth-child(1) > td:nth-child(2)").first().children().remove(); final String townDistrict = doc.select("table.unit_table > tbody > tr:nth-child(1) > td:nth-child(2)").text().replaceAll("^\\s*,","").trim(); doc.select("table.unit_table > tbody > tr:nth-child(2) > td:nth-child(2)").first().children().remove(); final int shopSize = Utils.toInt(doc.select("table.unit_table > tbody > tr:nth-child(2) > td:nth-child(2)").text()); final int departmentCount = Utils.doubleToInt(Utils.toDouble(doc.select("table.unit_table > tbody > tr:nth-child(3) > td:nth-child(2)").text())); final double notoriety = Utils.toDouble(doc.select("table.unit_table > tbody > tr:nth-child(4) > td:nth-child(2)").text()); final String visitorsCount = doc.select("table.unit_table > tbody > tr:nth-child(5) > td:nth-child(2)").text().trim(); final String serviceLevel = doc.select("table.unit_table > tbody > tr:nth-child(6) > td:nth-child(2)").text(); return new Shop(countryId, regionId, townId, shopSize, townDistrict, departmentCount, notoriety, visitorsCount, serviceLevel, shopProducts); } else { logger.error("Неизвестный тип юнита, unitImage = {}, url = {}. Возможно еще идет пересчет.", unitImage, url); return null; } } catch (final Exception e) { logger.error("url = {}", url); throw e; } } }
src/main/java/ru/VirtaMarketAnalyzer/parser/ShopParser.java
package ru.VirtaMarketAnalyzer.parser; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.VirtaMarketAnalyzer.data.City; import ru.VirtaMarketAnalyzer.data.Product; import ru.VirtaMarketAnalyzer.data.Shop; import ru.VirtaMarketAnalyzer.data.ShopProduct; import ru.VirtaMarketAnalyzer.main.Utils; import ru.VirtaMarketAnalyzer.main.Wizard; import ru.VirtaMarketAnalyzer.scrapper.Downloader; import java.util.*; import java.util.stream.Collectors; /** * Created by cobr123 on 16.01.16. */ public final class ShopParser { private static final Logger logger = LoggerFactory.getLogger(ShopParser.class); private static final Set<String> oneTryErrorUrl = new HashSet<>(); public static void main(String[] args) throws Exception { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%r %d{ISO8601} [%t] %p %c %x - %m%n"))); // final String url = Wizard.host + "olga/main/unit/view/5788675"; final String host = Wizard.host; final String realm = "mary"; final String url = host + realm + "/main/unit/view/3943258"; // Downloader.invalidateCache(url); final List<City> cities = new ArrayList<>(); cities.add(new City("422653", "422655", "422682", "Вашингтон", 0.0, 0.0, 0.0, 0)); final List<Product> products = new ArrayList<>(); products.add(ProductInitParser.getTradingProduct(host, realm, "422547")); products.add(ProductInitParser.getTradingProduct(host, realm, "3838")); final Map<String, List<Product>> productsByImgSrc = products.stream().collect(Collectors.groupingBy(Product::getImgUrl)); System.out.println(Utils.getPrettyGson(parse(realm, url, cities, productsByImgSrc, "Вашингтон"))); } public static Shop parse(final String realm, final String url, final List<City> cities, final Map<String, List<Product>> productsByImgSrc, final String cityCaption) throws Exception { final Document doc = Downloader.getDoc(url); final String countryId = Utils.getLastFromUrl(doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2) > a:nth-child(1)").attr("href")); final String regionId = Utils.getLastFromUrl(doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2) > a:nth-child(2)").attr("href")); String townId = ""; if (!cityCaption.isEmpty()) { final Optional<City> city = cities.stream() .filter(c -> c.getCountryId().equals(countryId)) .filter(c -> c.getCaption().equals(cityCaption)) .findFirst(); if (city.isPresent()) { townId = city.get().getId(); } } if (townId.isEmpty()) { final Element tmpFirst = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").first(); if (tmpFirst != null && tmpFirst.children() != null) { tmpFirst.children().remove(); } final String dyrtyCaption = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").text(); final String dyrtyCaptionReplaced = dyrtyCaption.replaceFirst("\\([^\\)]*\\)$", "").trim() .replace("San Diego", "Сан-Диего") .replace("Indianapolis", "Индианаполис") .replace("San Luis Potosí", "Сан-Луис-Потоси") .replace("San Luis Potosi", "Сан-Луис-Потоси") .replace("León", "Леон") .replace("Filadelfia", "Филадельфия") .replace("Tartu", "Тарту") .replace("Belfast", "Белфаст") .replace("Lisburn", "Лисберн") .replace("Leeds", "Лидс") .replace("Coventry", "Ковентри") .replace("Bamako", "Бамако") .replace("Los Angeles", "Лос-Анджелес") .replace("Hartford", "Хартфорд") .replace("Rotterdam", "Роттердам") .replace("Andijon", "Андижан") .replace("Almere", "Алмере") .replace("Moscow", "Москва") .replace("Lipetsk", "Липецк") .replace("Perm", "Пермь") .replace("Ufa", "Уфа") .replace("Omsk", "Омск") .replace("Vladivostok", "Владивосток") .replace("Nizhni Novgorod", "Нижний Новгород") .replace("Харків", "Харьков") .replace("Львів", "Львов") .replace("Novosibirsk", "Новосибирск") .replace("Khabarovsk", "Хабаровск") .replace("Hongkong", "Гонконг") .replace("Nankin", "Нанкин") .replace("Amsterdam", "Амстердам") .replace("Beijing", "Пекин") .replace("Singapore", "Сингапур") .replace("Chengdu", "Чэнду") .replace("Shimkent", "Шымкент") .replace("Guangzhou", "Гуанчжоу") .replace("Shanghai", "Шанхай") .replace("Seoul", "Сеул") .replace("Hanoi", "Ханой") .replace("Bangkok", "Бангкок") .replace("Hoshimin", "Хошимин") .replace("San Antonio", "Сан-Антонио") .replace("Santiago de Cuba", "Сантьяго-де-Куба") .replace("Pretoria", "Претория") .replace("Aguascalientes", "Агуаскальентес") .replace("Phoenix", "Финикс") .replace("Vilnius", "Вильнюс") .replace("Camaguey", "Камагуэй") .replace("Klaipeda", "Клайпеда") .replace("Buenos Aires", "Буэнос Айрес") .replace("Bergen", "Берген") .replace("Ecatepec de Morelos", "Экатепек-де-Морелос") .replace("Narva", "Нарва") .replace("Madrid", "Мадрид") .replace("Liepaja", "Лиепая") .replace("Київ", "Киев") .replace("San Miguel de Tucuman", "Сан-Мигель-де-Тукуман") .replace("Kuala-Lumpur", "Куала-Лумпур") .replace("Davao", "Давао") .replace("Saltillo", "Сальтильо") .replace("Guadalajara", "Гвадалахара") .replace("Kuala-Lumpur", "Куала-Лумпур") .replace("Surabaya", "Сурабая") .replace("Jakarta", "Джакарта") .replace("Xi'an", "Сиань") .replace("Manila", "Манила") .replace("ChiangMai", "Чиенгмай") .replace("Jacksonville", "Джексонвиль") .replace("Memphis", "Мемфис") .replace("Washington", "Вашингтон") .replace("Charlotte", "Шарлотт") .replace("Bristol", "Бристоль") .replace("Guadalupe", "Гуадалупе") .replace("New York", "Нью-Йорк") .replace("Tijuana", "Тихуана") .replace("Saint-Étienne", "Сент-Этьен") .replace("Dortmund", "Дортмунд") .replace("Montpellier", "Монпелье") .replace("Las Palmas de Gran Canaria", "Лас-Пальмас-де-Гран-Канария") .replace("Sevilla", "Севилья") .replace("Gao", "Гао") .replace("Samarqand", "Самарканд") .replace("Abu Dhabi", "Абу-Даби") .replace("Stuttgart", "Штутгарт") .replace("La Plata", "Ла-Плата") .replace("Gaziantep", "Газиантеп") .replace("Houston", "Хьюстон") .replace("Haikou", "Хайкоу") .replace("Pinar del Rio", "Пинар-дель-Рио") .replace("Oslo", "Осло") .replace("Erevan", "Ереван") .replace("Havana", "Гавана") .replace("Cape Town", "Кейптаун") .replace("Abidjan", "Абиджан") .replace("Abiyán", "Абиджан") .replace("Mexico City", "Мехико") .replace("Bonn", "Бонн") .replace("Colonia", "Кёльн") .replace("Caracas", "Каракас") .replace("Valencia (Ve)", "Валенсия (Ve)") .replace("Groningen", "Гронинген") .replace("Bouake", "Буаке") .replace("Iokogama", "Иокогама") .replace("Inchon", "Инчхон") .replace("Fukuoka", "Фукуока") .replace("Medan", "Медан") .replace("Asahikawa", "Асахикава") .replace("Kano", "Кано") .replace("Riad", "Эр-Рияд") .replace("Cologne", "Кёльн") .replace("Francfort-sur-le-Main", "Франкфурт") .replace("Berlin", "Берлин") .replace("Leipzig", "Лейпциг") .replace("Konya", "Конья") .replace("Stavanger", "Ставангер") .replace("Larissa", "Ларисса") .replace("Istanbul", "Стамбул") .replace("Jeddah", "Джидда") .replace("Dammam", "Даммам") .replace("Medina", "Медина") .replace("Dubai", "Дубай") .replace("Kuwait City", "Эль-Кувейт") .replace("Mecca", "Мекка") .replace("Sapporo", "Саппоро") .replace("Bloemfontein", "Блумфонтейн") .replace("Johannesburg", "Йоханнесбург") .replace("Strasbourg", "Страсбург") .replace("Лієпая", "Лиепая") .replace("Запоріжжя", "Запорожье") .replace("Rhodes", "Родос"); try { townId = cities.stream() .filter(c -> c.getCountryId().equals(countryId)) // .filter(c -> c.getRegionId().equals(regionId)) .filter(c -> c.getCaption().equals(dyrtyCaptionReplaced)) .findFirst().get().getId(); } catch (final Exception e) { logger.info(url); cities.stream() .filter(c -> c.getCountryId().equals(countryId)) // .filter(c -> c.getRegionId().equals(regionId)) .forEach(c -> logger.info(".replace(\"{}\", \"{}\")", dyrtyCaptionReplaced, c.getCaption())); logger.info("'dyrtyCaption = {}'", dyrtyCaptionReplaced); throw e; } } return parse(realm, "", countryId, regionId, townId, url, productsByImgSrc); } public static Shop parse(final String realm, final String productId , final String countryId, final String regionId, final String townId , final String url , final Map<String, List<Product>> productsByImgSrc ) throws Exception { Document doc = null; if (oneTryErrorUrl.contains(url)) { return null; } try { final int maxTriesCnt = 1; doc = Downloader.getDoc(url, maxTriesCnt); } catch (final Exception e) { oneTryErrorUrl.add(url); logger.error("url = https://virtonomica.ru/{}/main/globalreport/marketing/by_trade_at_cities/{}/{}/{}/{}", realm, productId, countryId, regionId, townId); logger.error(e.getLocalizedMessage()); return null; } try { final List<ShopProduct> shopProducts = new ArrayList<>(); final Elements rows = doc.select("table[class=\"grid\"] > tbody > tr[class]"); for (final Element row : rows) { try { if ("не изв.".equalsIgnoreCase(row.select("> td:nth-child(3)").first().text())) { continue; } if (row.select("> td:nth-child(1) > img").first().attr("src").contains("/brand/")) { continue; } final String prodId = productsByImgSrc.get(row.select("> td:eq(0) > img").first().attr("src")).get(0).getId(); final String sellVolume = row.select("> td").eq(1).text().trim(); final double quality = Utils.toDouble(row.select("> td").eq(2).text()); final double brand = Utils.toDouble(row.select("> td").eq(3).text()); final double price = Utils.toDouble(row.select("> td").eq(4).text()); final double marketShare = Utils.toDouble(row.select("> td").eq(5).text()); final ShopProduct shopProduct = new ShopProduct(prodId, sellVolume, price, quality, brand, marketShare); shopProducts.add(shopProduct); } catch (final Exception e) { logger.info("url = {}", url); logger.info("rows.size() = {}", rows.size()); logger.error(row.outerHtml()); logger.error(e.getLocalizedMessage(), e); } } final String unitImage = doc.select("#unitImage > img").attr("src"); if (unitImage.startsWith("/img/v2/units/fuel_")) { //заправки int shopSize = Utils.toInt(unitImage.substring("/img/v2/units/fuel_".length(), "/img/v2/units/fuel_".length() + 1)); final String townDistrict = ""; final int departmentCount = 1; final double notoriety = Utils.toDouble(doc.select("table.infoblock > tbody > tr:nth-child(3) > td:nth-child(2)").text()); final String visitorsCount = doc.select("table.infoblock > tbody > tr:nth-child(4) > td:nth-child(2)").text().trim(); final String serviceLevel = doc.select("table.infoblock > tbody > tr:nth-child(5) > td:nth-child(2)").text(); return new Shop(countryId, regionId, townId, shopSize, townDistrict, departmentCount, notoriety, visitorsCount, serviceLevel, shopProducts); } else if (unitImage.startsWith("/img/v2/units/shop_")) { //магазины final int shopSize = Utils.toInt(doc.select("table.infoblock > tbody > tr:nth-child(3) > td:nth-child(2)").text()); final String townDistrict = doc.select("table.infoblock > tbody > tr:nth-child(2) > td:nth-child(2)").text(); final int departmentCount = Utils.doubleToInt(Utils.toDouble(doc.select("table.infoblock > tbody > tr:nth-child(4) > td:nth-child(2)").text())); final double notoriety = Utils.toDouble(doc.select("table.infoblock > tbody > tr:nth-child(5) > td:nth-child(2)").text()); final String visitorsCount = doc.select("table.infoblock > tbody > tr:nth-child(6) > td:nth-child(2)").text().trim(); final String serviceLevel = doc.select("table.infoblock > tbody > tr:nth-child(7) > td:nth-child(2)").text(); return new Shop(countryId, regionId, townId, shopSize, townDistrict, departmentCount, notoriety, visitorsCount, serviceLevel, shopProducts); } else { logger.error("Неизвестный тип юнита, unitImage = {}, url = {}. Возможно еще идет пересчет.", unitImage, url); return null; } } catch (final Exception e) { logger.error("url = {}", url); throw e; } } }
shop ui update
src/main/java/ru/VirtaMarketAnalyzer/parser/ShopParser.java
shop ui update
<ide><path>rc/main/java/ru/VirtaMarketAnalyzer/parser/ShopParser.java <ide> BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%r %d{ISO8601} [%t] %p %c %x - %m%n"))); <ide> // final String url = Wizard.host + "olga/main/unit/view/5788675"; <ide> final String host = Wizard.host; <del> final String realm = "mary"; <del> final String url = host + realm + "/main/unit/view/3943258"; <add>// final String realm = "mary"; <add>// final String url = host + realm + "/main/unit/view/3943258"; <add> final String realm = "olga"; <add> final String url = host + realm + "/main/unit/view/6519771"; <ide> // Downloader.invalidateCache(url); <ide> final List<City> cities = new ArrayList<>(); <ide> cities.add(new City("422653", "422655", "422682", "Вашингтон", 0.0, 0.0, 0.0, 0)); <ide> public static Shop parse(final String realm, final String url, final List<City> cities, final Map<String, List<Product>> productsByImgSrc, final String cityCaption) throws Exception { <ide> final Document doc = Downloader.getDoc(url); <ide> <del> final String countryId = Utils.getLastFromUrl(doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2) > a:nth-child(1)").attr("href")); <del> final String regionId = Utils.getLastFromUrl(doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2) > a:nth-child(2)").attr("href")); <add> final String countryId = Utils.getLastFromUrl(doc.select("div.officePlace > a:nth-child(2)").attr("href")); <add> final String regionId = Utils.getLastFromUrl(doc.select("div.officePlace > a:nth-child(3)").attr("href")); <ide> <ide> String townId = ""; <ide> if (!cityCaption.isEmpty()) { <ide> final Optional<City> city = cities.stream() <del> .filter(c -> c.getCountryId().equals(countryId)) <add> .filter(c -> countryId.isEmpty() || c.getCountryId().equals(countryId)) <add> .filter(c -> regionId.isEmpty() || c.getRegionId().equals(regionId)) <ide> .filter(c -> c.getCaption().equals(cityCaption)) <ide> .findFirst(); <ide> <ide> } <ide> } <ide> if (townId.isEmpty()) { <del> final Element tmpFirst = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").first(); <del> if (tmpFirst != null && tmpFirst.children() != null) { <del> tmpFirst.children().remove(); <del> } <del> final String dyrtyCaption = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").text(); <add> String dyrtyCaption = doc.select("#mainContent > div.unit_box-container > div > div:nth-child(1) > table > tbody > tr:nth-child(1) > td:nth-child(2) > a").text(); <add> if(dyrtyCaption == null || dyrtyCaption.isEmpty()) { <add> final Element tmpFirst = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").first(); <add> if (tmpFirst != null && tmpFirst.children() != null) { <add> tmpFirst.children().remove(); <add> } <add> dyrtyCaption = doc.select("table.infoblock > tbody > tr:nth-child(1) > td:nth-child(2)").text(); <add> } <ide> final String dyrtyCaptionReplaced = dyrtyCaption.replaceFirst("\\([^\\)]*\\)$", "").trim() <ide> .replace("San Diego", "Сан-Диего") <ide> .replace("Indianapolis", "Индианаполис") <ide> continue; <ide> } <ide> final String prodId = productsByImgSrc.get(row.select("> td:eq(0) > img").first().attr("src")).get(0).getId(); <del> final String sellVolume = row.select("> td").eq(1).text().trim(); <del> final double quality = Utils.toDouble(row.select("> td").eq(2).text()); <del> final double brand = Utils.toDouble(row.select("> td").eq(3).text()); <del> final double price = Utils.toDouble(row.select("> td").eq(4).text()); <del> final double marketShare = Utils.toDouble(row.select("> td").eq(5).text()); <add> final String sellVolume = row.select("> td:nth-child(2)").text().trim(); <add> final double quality = Utils.toDouble(row.select("> td:nth-child(3)").text()); <add> final double brand = Utils.toDouble(row.select("> td:nth-child(4)").text()); <add> final double price = Utils.toDouble(row.select("> td:nth-child(5)").text()); <add> final double marketShare = Utils.toDouble(row.select("> td:nth-child(6)").text()); <ide> <ide> final ShopProduct shopProduct = new ShopProduct(prodId, sellVolume, price, quality, brand, marketShare); <ide> shopProducts.add(shopProduct); <ide> visitorsCount, serviceLevel, shopProducts); <ide> } else if (unitImage.startsWith("/img/v2/units/shop_")) { <ide> //магазины <del> final int shopSize = Utils.toInt(doc.select("table.infoblock > tbody > tr:nth-child(3) > td:nth-child(2)").text()); <del> final String townDistrict = doc.select("table.infoblock > tbody > tr:nth-child(2) > td:nth-child(2)").text(); <del> final int departmentCount = Utils.doubleToInt(Utils.toDouble(doc.select("table.infoblock > tbody > tr:nth-child(4) > td:nth-child(2)").text())); <del> final double notoriety = Utils.toDouble(doc.select("table.infoblock > tbody > tr:nth-child(5) > td:nth-child(2)").text()); <del> final String visitorsCount = doc.select("table.infoblock > tbody > tr:nth-child(6) > td:nth-child(2)").text().trim(); <del> final String serviceLevel = doc.select("table.infoblock > tbody > tr:nth-child(7) > td:nth-child(2)").text(); <add> doc.select("table.unit_table > tbody > tr:nth-child(1) > td:nth-child(2)").first().children().remove(); <add> final String townDistrict = doc.select("table.unit_table > tbody > tr:nth-child(1) > td:nth-child(2)").text().replaceAll("^\\s*,","").trim(); <add> doc.select("table.unit_table > tbody > tr:nth-child(2) > td:nth-child(2)").first().children().remove(); <add> final int shopSize = Utils.toInt(doc.select("table.unit_table > tbody > tr:nth-child(2) > td:nth-child(2)").text()); <add> final int departmentCount = Utils.doubleToInt(Utils.toDouble(doc.select("table.unit_table > tbody > tr:nth-child(3) > td:nth-child(2)").text())); <add> final double notoriety = Utils.toDouble(doc.select("table.unit_table > tbody > tr:nth-child(4) > td:nth-child(2)").text()); <add> final String visitorsCount = doc.select("table.unit_table > tbody > tr:nth-child(5) > td:nth-child(2)").text().trim(); <add> final String serviceLevel = doc.select("table.unit_table > tbody > tr:nth-child(6) > td:nth-child(2)").text(); <ide> <ide> return new Shop(countryId, regionId, townId, shopSize, townDistrict, departmentCount, notoriety, <ide> visitorsCount, serviceLevel, shopProducts);
JavaScript
apache-2.0
8a337640e1a3909f56e9eeff3f44d88bcee1d0e8
0
ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile
/** * Android build command. * * @module cli/_build * * @copyright * Copyright (c) 2009-2015 by Appcelerator, Inc. All Rights Reserved. * * Copyright (c) 2012-2013 Chris Talkington, contributors. * {@link https://github.com/ctalkington/node-archiver} * * @license * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ var ADB = require('titanium-sdk/lib/adb'), AdmZip = require('adm-zip'), android = require('titanium-sdk/lib/android'), androidDetect = require('../lib/detect').detect, AndroidManifest = require('../lib/AndroidManifest'), appc = require('node-appc'), archiver = require('archiver'), async = require('async'), Builder = require('titanium-sdk/lib/builder'), CleanCSS = require('clean-css'), DOMParser = require('xmldom').DOMParser, ejs = require('ejs'), EmulatorManager = require('titanium-sdk/lib/emulator'), fields = require('fields'), fs = require('fs'), i18n = require('titanium-sdk/lib/i18n'), jsanalyze = require('titanium-sdk/lib/jsanalyze'), path = require('path'), temp = require('temp'), ti = require('titanium-sdk'), tiappxml = require('titanium-sdk/lib/tiappxml'), util = require('util'), wrench = require('wrench'), afs = appc.fs, i18nLib = appc.i18n(__dirname), __ = i18nLib.__, __n = i18nLib.__n, version = appc.version, xml = appc.xml; function AndroidBuilder() { Builder.apply(this, arguments); this.devices = null; // set by findTargetDevices() during 'config' phase this.devicesToAutoSelectFrom = []; this.keystoreAliases = []; this.tiSymbols = {}; this.dexAgent = false; this.minSupportedApiLevel = parseInt(this.packageJson.minSDKVersion); this.minTargetApiLevel = parseInt(version.parseMin(this.packageJson.vendorDependencies['android sdk'])); this.maxSupportedApiLevel = parseInt(version.parseMax(this.packageJson.vendorDependencies['android sdk'])); this.deployTypes = { 'emulator': 'development', 'device': 'test', 'dist-playstore': 'production' }; this.targets = ['emulator', 'device', 'dist-playstore']; this.validABIs = ['armeabi-v7a', 'x86']; this.xmlMergeRegExp = /^(strings|attrs|styles|bools|colors|dimens|ids|integers|arrays)\.xml$/; this.uncompressedTypes = [ 'jpg', 'jpeg', 'png', 'gif', 'wav', 'mp2', 'mp3', 'ogg', 'aac', 'mpg', 'mpeg', 'mid', 'midi', 'smf', 'jet', 'rtttl', 'imy', 'xmf', 'mp4', 'm4a', 'm4v', '3gp', '3gpp', '3g2', '3gpp2', 'amr', 'awb', 'wma', 'wmv' ]; } util.inherits(AndroidBuilder, Builder); AndroidBuilder.prototype.config = function config(logger, config, cli) { Builder.prototype.config.apply(this, arguments); var _t = this; function assertIssue(logger, issues, name) { var i = 0, len = issues.length; for (; i < len; i++) { if ((typeof name == 'string' && issues[i].id == name) || (typeof name == 'object' && name.test(issues[i].id))) { issues[i].message.split('\n').forEach(function (line) { logger[issues[i].type === 'error' ? 'error' : 'warn'](line.replace(/(__(.+?)__)/g, '$2'.bold)); }); logger.log(); if (issues[i].type === 'error') {process.exit(1);} } } } // we hook into the pre-validate event so that we can stop the build before // prompting if we know the build is going to fail. // // this is also where we can detect android and jdk environments before // prompting occurs. because detection is expensive we also do it here instead // of during config() because there's no sense detecting if config() is being // called because of the help command. cli.on('cli:pre-validate', function (obj, callback) { if (cli.argv.platform && cli.argv.platform != 'android') { return callback(); } async.series([ function (next) { // detect android environment androidDetect(config, { packageJson: _t.packageJson }, function (androidInfo) { _t.androidInfo = androidInfo; assertIssue(logger, androidInfo.issues, 'ANDROID_JDK_NOT_FOUND'); assertIssue(logger, androidInfo.issues, 'ANDROID_JDK_PATH_CONTAINS_AMPERSANDS'); assertIssue(logger, androidInfo.issues, 'ANDROID_BUILD_TOOLS_TOO_NEW'); if (!cli.argv.prompt) { // check that the Android SDK is found and sane // note: if we're prompting, then we'll do this check in the --android-sdk validate() callback assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_NOT_FOUND'); assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_MISSING_PROGRAMS'); // make sure we have an Android SDK and some Android targets if (!Object.keys(androidInfo.targets).filter(function (id) { var t = androidInfo.targets[id]; return t.type == 'platform' && t['api-level'] >= _t.minTargetApiLevel; }).length) { if (Object.keys(androidInfo.targets).length) { logger.error(__('No valid Android SDK targets found.')); } else { logger.error(__('No Android SDK targets found.')); } logger.error(__('Please download an Android SDK target API level %s or newer from the Android SDK Manager and try again.', _t.minTargetApiLevel) + '\n'); process.exit(1); } } // if --android-sdk was not specified, then we simply try to set a default android sdk if (!cli.argv['android-sdk']) { var androidSdkPath = config.android && config.android.sdkPath; if (!androidSdkPath && androidInfo.sdk) { androidSdkPath = androidInfo.sdk.path; } androidSdkPath && (cli.argv['android-sdk'] = afs.resolvePath(androidSdkPath)); } next(); }); }, function (next) { // detect java development kit appc.jdk.detect(config, null, function (jdkInfo) { assertIssue(logger, jdkInfo.issues, 'JDK_NOT_INSTALLED'); assertIssue(logger, jdkInfo.issues, 'JDK_MISSING_PROGRAMS'); assertIssue(logger, jdkInfo.issues, 'JDK_INVALID_JAVA_HOME'); if (!jdkInfo.version) { logger.error(__('Unable to locate the Java Development Kit') + '\n'); logger.log(__('You can specify the location by setting the %s environment variable.', 'JAVA_HOME'.cyan) + '\n'); process.exit(1); } if (!version.satisfies(jdkInfo.version, _t.packageJson.vendorDependencies.java)) { logger.error(__('JDK version %s detected, but only version %s is supported', jdkInfo.version, _t.packageJson.vendorDependencies.java) + '\n'); process.exit(1); } _t.jdkInfo = jdkInfo; next(); }); } ], callback); }); var targetDeviceCache = {}, findTargetDevices = function findTargetDevices(target, callback) { if (targetDeviceCache[target]) { return callback(null, targetDeviceCache[target]); } if (target == 'device') { new ADB(config).devices(function (err, devices) { if (err) { callback(err); } else { this.devices = devices.filter(function (d) { return !d.emulator && d.state == 'device'; }); if (this.devices.length > 1) { // we have more than 1 device, so we should show 'all' this.devices.push({ id: 'all', model: 'All Devices' }); } callback(null, targetDeviceCache[target] = this.devices.map(function (d) { return { name: d.model || d.manufacturer, id: d.id, version: d.release, abi: Array.isArray(d.abi) ? d.abi.join(',') : d.abi, type: 'device' }; })); } }.bind(this)); } else if (target == 'emulator') { new EmulatorManager(config).detect(function (err, emus) { if (err) { callback(err); } else { this.devices = emus; callback(null, targetDeviceCache[target] = emus.map(function (emu) { // normalize the emulator info if (emu.type == 'avd') { return { name: emu.name, id: emu.name, api: emu['api-level'], version: emu['sdk-version'], abi: emu.abi, type: emu.type, googleApis: emu.googleApis, sdcard: emu.sdcard }; } else if (emu.type == 'genymotion') { return { name: emu.name, id: emu.name, api: emu['api-level'], version: emu['sdk-version'], abi: emu.abi, type: emu.type, googleApis: emu.googleApis, sdcard: true }; } return emu; // not good })); } }.bind(this)); } else { callback(); } }.bind(this); return function (finished) { cli.createHook('build.android.config', this, function (callback) { var conf = { flags: { 'launch': { desc: __('disable launching the app after installing'), default: true, hideDefault: true, negate: true } }, options: { 'alias': { abbr: 'L', desc: __('the alias for the keystore'), hint: 'alias', order: 155, prompt: function (callback) { callback(fields.select({ title: __("What is the name of the keystore's certificate alias?"), promptLabel: __('Select a certificate alias by number or name'), margin: '', optionLabel: 'name', optionValue: 'name', numbered: true, relistOnError: true, complete: true, suggest: false, options: _t.keystoreAliases, validate: conf.options.alias.validate })); }, validate: function (value, callback) { // if there's a value, then they entered something, otherwise let the cli prompt if (value) { var selectedAlias = value.toLowerCase(), alias = _t.keystoreAlias = _t.keystoreAliases.filter(function (a) { return a.name && a.name.toLowerCase() == selectedAlias; }).shift(); if (!alias) { return callback(new Error(__('Invalid "--alias" value "%s"', value))); } if (alias.sigalg && alias.sigalg.toLowerCase() == 'sha256withrsa') { logger.warn(__('The selected alias %s uses the %s signature algorithm which will likely have issues with Android 4.3 and older.', ('"' + value + '"').cyan, ('"' + alias.sigalg + '"').cyan)); logger.warn(__('Certificates that use the %s or %s signature algorithm will provide better compatibility.', '"SHA1withRSA"'.cyan, '"MD5withRSA"'.cyan)); } } callback(null, value); } }, 'android-sdk': { abbr: 'A', default: config.android && config.android.sdkPath && afs.resolvePath(config.android.sdkPath), desc: __('the path to the Android SDK'), hint: __('path'), order: 100, prompt: function (callback) { var androidSdkPath = config.android && config.android.sdkPath; if (!androidSdkPath && _t.androidInfo.sdk) { androidSdkPath = _t.androidInfo.sdk.path; } if (androidSdkPath) { androidSdkPath = afs.resolvePath(androidSdkPath); if (process.platform == 'win32' || androidSdkPath.indexOf('&') != -1) { androidSdkPath = undefined; } } callback(fields.file({ promptLabel: __('Where is the Android SDK?'), default: androidSdkPath, complete: true, showHidden: true, ignoreDirs: _t.ignoreDirs, ignoreFiles: _t.ignoreFiles, validate: _t.conf.options['android-sdk'].validate.bind(_t) })); }, required: true, validate: function (value, callback) { if (!value) { callback(new Error(__('Invalid Android SDK path'))); } else if (process.platform == 'win32' && value.indexOf('&') != -1) { callback(new Error(__('The Android SDK path cannot contain ampersands (&) on Windows'))); } else if (_t.androidInfo.sdk && _t.androidInfo.sdk.path == afs.resolvePath(value)) { // no sense doing the detection again, just make sure we found the sdk assertIssue(logger, _t.androidInfo.issues, 'ANDROID_SDK_NOT_FOUND'); assertIssue(logger, _t.androidInfo.issues, 'ANDROID_SDK_MISSING_PROGRAMS'); callback(null, value); } else { // do a quick scan to see if the path is correct android.findSDK(value, config, appc.pkginfo.package(module), function (err, results) { if (err) { callback(new Error(__('Invalid Android SDK path: %s', value))); } else { function next() { // set the android sdk in the config just in case a plugin or something needs it config.set('android.sdkPath', value); // path looks good, do a full scan again androidDetect(config, { packageJson: _t.packageJson, bypassCache: true }, function (androidInfo) { // check that the Android SDK is found and sane assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_NOT_FOUND'); assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_MISSING_PROGRAMS'); _t.androidInfo = androidInfo; callback(null, value); }); } // new android sdk path looks good // if we found an android sdk in the pre-validate hook, then we need to kill the other sdk's adb server if (_t.androidInfo.sdk) { new ADB(config).stopServer(next); } else { next(); } } }); } } }, 'avd-abi': { abbr: 'B', desc: __('the abi for the Android emulator; deprecated, use --device-id'), hint: __('abi') }, 'avd-id': { abbr: 'I', desc: __('the id for the Android emulator; deprecated, use --device-id'), hint: __('id') }, 'avd-skin': { abbr: 'S', desc: __('the skin for the Android emulator; deprecated, use --device-id'), hint: __('skin') }, 'build-type': { hidden: true }, 'debug-host': { hidden: true }, 'deploy-type': { abbr: 'D', desc: __('the type of deployment; only used when target is %s or %s', 'emulator'.cyan, 'device'.cyan), hint: __('type'), order: 110, values: ['test', 'development'] }, 'device-id': { abbr: 'C', desc: __('the name of the Android emulator or the device id to install the application to'), hint: __('name'), order: 130, prompt: function (callback) { findTargetDevices(cli.argv.target, function (err, results) { var opts = {}, title, promptLabel; // we need to sort all results into groups for the select field if (cli.argv.target == 'device' && results.length) { opts[__('Devices')] = results; title = __('Which device do you want to install your app on?'); promptLabel = __('Select a device by number or name'); } else if (cli.argv.target == 'emulator') { // for emulators, we sort by type var emus = results.filter(function (e) { return e.type == 'avd'; }); if (emus.length) { opts[__('Android Emulators')] = emus; } emus = results.filter(function (e) { return e.type == 'genymotion'; }); if (emus.length) { opts[__('Genymotion Emulators')] = emus; logger.log(__('NOTE: Genymotion emulator must be running to detect Google API support').magenta + '\n'); } title = __('Which emulator do you want to launch your app in?'); promptLabel = __('Select an emulator by number or name'); } // if there are no devices/emulators, error if (!Object.keys(opts).length) { if (cli.argv.target == 'device') { logger.error(__('Unable to find any devices') + '\n'); logger.log(__('Please plug in an Android device, then try again.') + '\n'); } else { logger.error(__('Unable to find any emulators') + '\n'); logger.log(__('Please create an Android emulator, then try again.') + '\n'); } process.exit(1); } callback(fields.select({ title: title, promptLabel: promptLabel, formatters: { option: function (opt, idx, num) { return ' ' + num + opt.name.cyan + (opt.version ? ' (' + opt.version + ')' : '') + (opt.googleApis ? (' (' + __('Google APIs supported') + ')').grey : opt.googleApis === null ? (' (' + __('Google APIs support unknown') + ')').grey : ''); } }, autoSelectOne: true, margin: '', optionLabel: 'name', optionValue: 'id', numbered: true, relistOnError: true, complete: true, suggest: true, options: opts })); }); }, required: true, validate: function (device, callback) { var dev = device.toLowerCase(); findTargetDevices(cli.argv.target, function (err, devices) { if (cli.argv.target == 'device' && dev == 'all') { // we let 'all' slide by return callback(null, dev); } var i = 0, l = devices.length; for (; i < l; i++) { if (devices[i].id.toLowerCase() == dev) { return callback(null, devices[i].id); } } callback(new Error(cli.argv.target ? __('Invalid Android device "%s"', device) : __('Invalid Android emulator "%s"', device))); }); }, verifyIfRequired: function (callback) { if (cli.argv['build-only']) { // not required if we're build only return callback(); } findTargetDevices(cli.argv.target, function (err, results) { if (cli.argv.target == 'emulator' && cli.argv['device-id'] === undefined && cli.argv['avd-id']) { // if --device-id was not specified, but --avd-id was, then we need to // try to resolve a device based on the legacy --avd-* options var avds = results.filter(function (a) { return a.type == 'avd'; }).map(function (a) { return a.name; }), name = 'titanium_' + cli.argv['avd-id'] + '_'; if (avds.length) { // try finding the first avd that starts with the avd id avds = avds.filter(function (avd) { return avd.indexOf(name) == 0; }); if (avds.length == 1) { cli.argv['device-id'] = avds[0]; return callback(); } else if (avds.length > 1) { // next try using the avd skin if (!cli.argv['avd-skin']) { // we have more than one match logger.error(__n('Found %s avd with id "%%s"', 'Found %s avds with id "%%s"', avds.length, cli.argv['avd-id'])); logger.error(__('Specify --avd-skin and --avd-abi to select a specific emulator') + '\n'); } else { name += cli.argv['avd-skin']; // try exact match var tmp = avds.filter(function (avd) { return avd == name; }); if (tmp.length) { avds = tmp; } else { // try partial match avds = avds.filter(function (avd) { return avd.indexOf(name + '_') == 0; }); } if (avds.length == 0) { logger.error(__('No emulators found with id "%s" and skin "%s"', cli.argv['avd-id'], cli.argv['avd-skin']) + '\n'); } else if (avds.length == 1) { cli.argv['device-id'] = avds[0]; return callback(); } else if (!cli.argv['avd-abi']) { // we have more than one matching avd, but no abi to filter by so we have to error logger.error(__n('Found %s avd with id "%%s" and skin "%%s"', 'Found %s avds with id "%%s" and skin "%%s"', avds.length, cli.argv['avd-id'], cli.argv['avd-skin'])); logger.error(__('Specify --avd-abi to select a specific emulator') + '\n'); } else { name += '_' + cli.argv['avd-abi']; // try exact match tmp = avds.filter(function (avd) { return avd == name; }); if (tmp.length) { avds = tmp; } else { avds = avds.filter(function (avd) { return avd.indexOf(name + '_') == 0; }); } if (avds.length == 0) { logger.error(__('No emulators found with id "%s", skin "%s", and abi "%s"', cli.argv['avd-id'], cli.argv['avd-skin'], cli.argv['avd-abi']) + '\n'); } else { // there is one or more avds, but we'll just return the first one cli.argv['device-id'] = avds[0]; return callback(); } } } } logger.warn(__('%s options have been %s, please use %s', '--avd-*'.cyan, 'deprecated'.red, '--device-id'.cyan) + '\n'); // print list of available avds if (results.length && !cli.argv.prompt) { logger.log(__('Available Emulators:')) results.forEach(function (emu) { logger.log(' ' + emu.name.cyan + ' (' + emu.version + ')'); }); logger.log(); } } } else if (cli.argv['device-id'] === undefined && results.length && config.get('android.autoSelectDevice', true)) { // we set the device-id to an array of devices so that later in validate() // after the tiapp.xml has been parsed, we can auto select the best device _t.devicesToAutoSelectFrom = results.sort(function (a, b) { var eq = a.api && b.api && appc.version.eq(a.api, b.api), gt = a.api && b.api && appc.version.gt(a.api, b.api); if (eq) { if (a.type == b.type) { if (a.googleApis == b.googleApis) { return 0; } else if (b.googleApis) { return 1; } else if (a.googleApis === false && b.googleApis === null) { return 1; } return -1; } return a.type == 'avd' ? -1 : 1; } return gt ? 1 : -1; }); return callback(); } // yup, still required callback(true); }); } }, 'key-password': { desc: __('the password for the keystore private key (defaults to the store-password)'), hint: 'keypass', order: 160, prompt: function (callback) { callback(fields.text({ promptLabel: __("What is the keystore's __key password__?") + ' ' + __('(leave blank to use the store password)').grey, password: true, validate: _t.conf.options['key-password'].validate.bind(_t) })); }, secret: true, validate: function (keyPassword, callback) { // sanity check the keystore and store password _t.conf.options['store-password'].validate(cli.argv['store-password'], function (err, storePassword) { if (err) { // we have a bad --keystore or --store-password arg cli.argv.keystore = cli.argv['store-password'] = undefined; return callback(err); } var keystoreFile = cli.argv.keystore, alias = cli.argv.alias, tmpKeystoreFile = temp.path({ suffix: '.jks' }); if (keystoreFile && storePassword && alias && _t.jdkInfo && _t.jdkInfo.executables.keytool) { // the only way to test the key password is to export the cert appc.subprocess.run(_t.jdkInfo.executables.keytool, [ '-J-Duser.language=en', '-importkeystore', '-v', '-srckeystore', keystoreFile, '-destkeystore', tmpKeystoreFile, '-srcstorepass', storePassword, '-deststorepass', storePassword, '-srcalias', alias, '-destalias', alias, '-srckeypass', keyPassword || storePassword, '-noprompt' ], function (code, out, err) { if (code) { if (out.indexOf('java.security.UnrecoverableKeyException') != -1) { return callback(new Error(__('Bad key password'))); } return callback(new Error(out.trim())); } // remove the temp keystore fs.existsSync(tmpKeystoreFile) && fs.unlinkSync(tmpKeystoreFile); callback(null, keyPassword); }); } else { callback(null, keyPassword); } }); } }, 'keystore': { abbr: 'K', callback: function (value) { _t.conf.options['alias'].required = true; _t.conf.options['store-password'].required = true; }, desc: __('the location of the keystore file'), hint: 'path', order: 140, prompt: function (callback) { _t.conf.options['key-password'].required = true; callback(fields.file({ promptLabel: __('Where is the __keystore file__ used to sign the app?'), complete: true, showHidden: true, ignoreDirs: _t.ignoreDirs, ignoreFiles: _t.ignoreFiles, validate: _t.conf.options.keystore.validate.bind(_t) })); }, validate: function (keystoreFile, callback) { if (!keystoreFile) { callback(new Error(__('Please specify the path to your keystore file'))); } else { keystoreFile = afs.resolvePath(keystoreFile); if (!fs.existsSync(keystoreFile) || !fs.statSync(keystoreFile).isFile()) { callback(new Error(__('Invalid keystore file'))); } else { callback(null, keystoreFile); } } } }, 'output-dir': { abbr: 'O', desc: __('the output directory when using %s', 'dist-playstore'.cyan), hint: 'dir', order: 180, prompt: function (callback) { callback(fields.file({ promptLabel: __('Where would you like the output APK file saved?'), default: cli.argv['project-dir'] && afs.resolvePath(cli.argv['project-dir'], 'dist'), complete: true, showHidden: true, ignoreDirs: _t.ignoreDirs, ignoreFiles: /.*/, validate: _t.conf.options['output-dir'].validate.bind(_t) })); }, validate: function (outputDir, callback) { callback(outputDir || !_t.conf.options['output-dir'].required ? null : new Error(__('Invalid output directory')), outputDir); } }, 'profiler-host': { hidden: true }, 'store-password': { abbr: 'P', desc: __('the password for the keystore'), hint: 'password', order: 150, prompt: function (callback) { callback(fields.text({ next: function (err, value) { return err && err.next || null; }, promptLabel: __("What is the keystore's __password__?"), password: true, // if the password fails due to bad keystore file, // we need to prompt for the keystore file again repromptOnError: false, validate: _t.conf.options['store-password'].validate.bind(_t) })); }, secret: true, validate: function (storePassword, callback) { if (!storePassword) { return callback(new Error(__('Please specify a keystore password'))); } // sanity check the keystore _t.conf.options.keystore.validate(cli.argv.keystore, function (err, keystoreFile) { if (err) { // we have a bad --keystore arg cli.argv.keystore = undefined; return callback(err); } if (keystoreFile && _t.jdkInfo && _t.jdkInfo.executables.keytool) { appc.subprocess.run(_t.jdkInfo.executables.keytool, [ '-J-Duser.language=en', '-list', '-v', '-keystore', keystoreFile, '-storepass', storePassword ], function (code, out, err) { if (code) { var msg = out.split('\n').shift().split('java.io.IOException:'); if (msg.length > 1) { msg = msg[1].trim(); if (/invalid keystore format/i.test(msg)) { msg = __('Invalid keystore file'); cli.argv.keystore = undefined; _t.conf.options.keystore.required = true; } } else { msg = out.trim(); } return callback(new Error(msg)); } // empty the alias array. it is important that we don't destory the original // instance since it was passed by reference to the alias select list while (_t.keystoreAliases.length) { _t.keystoreAliases.pop(); } var aliasRegExp = /Alias name\: (.+)/, sigalgRegExp = /Signature algorithm name\: (.+)/; out.split('\n\n').forEach(function (chunk) { chunk = chunk.trim(); var m = chunk.match(aliasRegExp); if (m) { var sigalg = chunk.match(sigalgRegExp); _t.keystoreAliases.push({ name: m[1], sigalg: sigalg && sigalg[1] }); } }); if (_t.keystoreAliases.length == 0) { cli.argv.keystore = undefined; return callback(new Error(__('Keystore does not contain any certificates'))); } else if (!cli.argv.alias && _t.keystoreAliases.length == 1) { cli.argv.alias = _t.keystoreAliases[0].name; } // check if this keystore requires a key password var keystoreFile = cli.argv.keystore, alias = cli.argv.alias, tmpKeystoreFile = temp.path({ suffix: '.jks' }); if (keystoreFile && storePassword && alias && _t.jdkInfo && _t.jdkInfo.executables.keytool) { // the only way to test the key password is to export the cert appc.subprocess.run(_t.jdkInfo.executables.keytool, [ '-J-Duser.language=en', '-importkeystore', '-v', '-srckeystore', keystoreFile, '-destkeystore', tmpKeystoreFile, '-srcstorepass', storePassword, '-deststorepass', storePassword, '-srcalias', alias, '-destalias', alias, '-srckeypass', storePassword, '-noprompt' ], function (code, out, err) { if (code) { if (out.indexOf('Alias <' + alias + '> does not exist') != -1) { // bad alias, we'll let --alias find it again _t.conf.options['alias'].required = true; } // since we have an error, force the key password to be required _t.conf.options['key-password'].required = true; } else { // remove the temp keystore fs.existsSync(tmpKeystoreFile) && fs.unlinkSync(tmpKeystoreFile); } callback(null, storePassword); }); } else { callback(null, storePassword); } }.bind(_t)); } else { callback(null, storePassword); } }); } }, 'target': { abbr: 'T', callback: function (value) { // as soon as we know the target, toggle required options for validation if (value === 'dist-playstore') { _t.conf.options['alias'].required = true; _t.conf.options['deploy-type'].values = ['production']; _t.conf.options['device-id'].required = false; _t.conf.options['keystore'].required = true; _t.conf.options['output-dir'].required = true; _t.conf.options['store-password'].required = true; } }, default: 'emulator', desc: __('the target to build for'), order: 120, required: true, values: _t.targets } } }; callback(null, _t.conf = conf); })(function (err, result) { finished(result); }); }.bind(this); }; AndroidBuilder.prototype.validate = function validate(logger, config, cli) { Builder.prototype.validate.apply(this, arguments); this.target = cli.argv.target; this.deployType = !/^dist-/.test(this.target) && cli.argv['deploy-type'] ? cli.argv['deploy-type'] : this.deployTypes[this.target]; this.buildType = cli.argv['build-type'] || ''; // ti.deploytype is deprecated and so we force the real deploy type if (cli.tiapp.properties['ti.deploytype']) { logger.warn(__('The %s tiapp.xml property has been deprecated, please use the %s option', 'ti.deploytype'.cyan, '--deploy-type'.cyan)); } cli.tiapp.properties['ti.deploytype'] = { type: 'string', value: this.deployType }; // get the javac params this.javacMaxMemory = cli.tiapp.properties['android.javac.maxmemory'] && cli.tiapp.properties['android.javac.maxmemory'].value || config.get('android.javac.maxMemory', '1024M'); this.javacSource = cli.tiapp.properties['android.javac.source'] && cli.tiapp.properties['android.javac.source'].value || config.get('android.javac.source', '1.6'); this.javacTarget = cli.tiapp.properties['android.javac.target'] && cli.tiapp.properties['android.javac.target'].value || config.get('android.javac.target', '1.6'); this.dxMaxMemory = cli.tiapp.properties['android.dx.maxmemory'] && cli.tiapp.properties['android.dx.maxmemory'].value || config.get('android.dx.maxMemory', '1024M'); // manually inject the build profile settings into the tiapp.xml switch (this.deployType) { case 'production': this.minifyJS = true; this.encryptJS = true; this.minifyCSS = true; this.allowDebugging = false; this.allowProfiling = false; this.includeAllTiModules = false; this.proguard = false; break; case 'test': this.minifyJS = true; this.encryptJS = true; this.minifyCSS = true; this.allowDebugging = true; this.allowProfiling = true; this.includeAllTiModules = false; this.proguard = false; break; case 'development': default: this.minifyJS = false; this.encryptJS = false; this.minifyCSS = false; this.allowDebugging = true; this.allowProfiling = true; this.includeAllTiModules = true; this.proguard = false; } if (cli.tiapp.properties['ti.android.compilejs']) { logger.warn(__('The %s tiapp.xml property has been deprecated, please use the %s option to bypass JavaScript minification', 'ti.android.compilejs'.cyan, '--skip-js-minify'.cyan)); } if (cli.argv['skip-js-minify']) { this.minifyJS = false; } // check the app name if (cli.tiapp.name.indexOf('&') != -1) { if (config.get('android.allowAppNameAmpersands', false)) { logger.warn(__('The app name "%s" contains an ampersand (&) which will most likely cause problems.', cli.tiapp.name)); logger.warn(__('It is recommended that you define the app name using i18n strings.')); logger.warn(__('Refer to %s for more information.', 'http://appcelerator.com/i18n-app-name'.cyan)); } else { logger.error(__('The app name "%s" contains an ampersand (&) which will most likely cause problems.', cli.tiapp.name)); logger.error(__('It is recommended that you define the app name using i18n strings.')); logger.error(__('Refer to %s for more information.', 'http://appcelerator.com/i18n-app-name')); logger.error(__('To allow ampersands in the app name, run:')); logger.error(' ti config android.allowAppNameAmpersands true\n'); process.exit(1); } } // check the Android specific app id rules if (!config.get('app.skipAppIdValidation') && !cli.tiapp.properties['ti.skipAppIdValidation']) { if (!/^([a-zA-Z_]{1}[a-zA-Z0-9_-]*(\.[a-zA-Z0-9_-]*)*)$/.test(cli.tiapp.id)) { logger.error(__('tiapp.xml contains an invalid app id "%s"', cli.tiapp.id)); logger.error(__('The app id must consist only of letters, numbers, dashes, and underscores.')); logger.error(__('Note: Android does not allow dashes.')); logger.error(__('The first character must be a letter or underscore.')); logger.error(__("Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)") + '\n'); process.exit(1); } if (!/^([a-zA-Z_]{1}[a-zA-Z0-9_]*(\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*)$/.test(cli.tiapp.id)) { logger.error(__('tiapp.xml contains an invalid app id "%s"', cli.tiapp.id)); logger.error(__('The app id must consist of letters, numbers, and underscores.')); logger.error(__('The first character must be a letter or underscore.')); logger.error(__('The first character after a period must not be a number.')); logger.error(__("Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)") + '\n'); process.exit(1); } if (!ti.validAppId(cli.tiapp.id)) { logger.error(__('Invalid app id "%s"', cli.tiapp.id)); logger.error(__('The app id must not contain Java reserved words.') + '\n'); process.exit(1); } } // check the default unit cli.tiapp.properties || (cli.tiapp.properties = {}); cli.tiapp.properties['ti.ui.defaultunit'] || (cli.tiapp.properties['ti.ui.defaultunit'] = { type: 'string', value: 'system'}); if (!/^system|px|dp|dip|mm|cm|in$/.test(cli.tiapp.properties['ti.ui.defaultunit'].value)) { logger.error(__('Invalid "ti.ui.defaultunit" property value "%s"', cli.tiapp.properties['ti.ui.defaultunit'].value) + '\n'); logger.log(__('Valid units:')); 'system,px,dp,dip,mm,cm,in'.split(',').forEach(function (unit) { logger.log(' ' + unit.cyan); }); logger.log(); process.exit(1); } // if we're building for the emulator, make sure we don't have any issues if (cli.argv.target == 'emulator') { this.androidInfo.issues.forEach(function (issue) { if (/^ANDROID_MISSING_(LIBGL|I386_ARCH|IA32_LIBS|32BIT_GLIBC|32BIT_LIBSTDCPP)$/.test(issue.id)) { issue.message.split('\n').forEach(function (line) { logger.warn(line); }); } }); } // check that the proguard config exists var proguardConfigFile = path.join(cli.argv['project-dir'], 'platform', 'android', 'proguard.cfg'); if (this.proguard && !fs.existsSync(proguardConfigFile)) { logger.error(__('Missing ProGuard configuration file')); logger.error(__('ProGuard settings must go in the file "%s"', proguardConfigFile)); logger.error(__('For example configurations, visit %s', 'http://proguard.sourceforge.net/index.html#manual/examples.html') + '\n'); process.exit(1); } // map sdk versions to sdk targets instead of by id var targetSDKMap = {}; Object.keys(this.androidInfo.targets).forEach(function (i) { var t = this.androidInfo.targets[i]; if (t.type === 'platform') { targetSDKMap[t.id.replace('android-', '')] = t; } }, this); try { var tiappAndroidManifest = this.tiappAndroidManifest = cli.tiapp.android && cli.tiapp.android.manifest && (new AndroidManifest).parse(cli.tiapp.android.manifest); } catch (ex) { logger.error(__('Malformed <manifest> definition in the <android> section of the tiapp.xml') + '\n'); process.exit(1); } try { var customAndroidManifestFile = path.join(cli.argv['project-dir'], 'platform', 'android', 'AndroidManifest.xml'); this.customAndroidManifest = fs.existsSync(customAndroidManifestFile) && (new AndroidManifest(customAndroidManifestFile)); } catch (ex) { logger.error(__('Malformed custom AndroidManifest.xml file: %s', customAndroidManifestFile) + '\n'); process.exit(1); } // validate the sdk levels var usesSDK = (tiappAndroidManifest && tiappAndroidManifest['uses-sdk']) || (this.customAndroidManifest && this.customAndroidManifest['uses-sdk']); this.minSDK = this.minSupportedApiLevel; this.targetSDK = cli.tiapp.android && ~~cli.tiapp.android['tool-api-level'] || null; this.maxSDK = null; if (this.targetSDK) { logger.log(); logger.warn(__('%s has been deprecated, please specify the target SDK API using the %s tag:', '<tool-api-level>'.cyan, '<uses-sdk>'.cyan)); logger.warn(); logger.warn('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.warn(' <android>'.grey); logger.warn(' <manifest>'.grey); logger.warn((' <uses-sdk android:minSdkVersion="' + this.minSupportedApiLevel + '" android:targetSdkVersion="' + this.minTargetApiLevel + '" android:maxSdkVersion="' + this.maxSupportedApiLevel + '"/>').magenta); logger.warn(' </manifest>'.grey); logger.warn(' </android>'.grey); logger.warn('</ti:app>'.grey); logger.log(); } if (usesSDK) { usesSDK.minSdkVersion && (this.minSDK = usesSDK.minSdkVersion); usesSDK.targetSdkVersion && (this.targetSDK = usesSDK.targetSdkVersion); usesSDK.maxSdkVersion && (this.maxSDK = usesSDK.maxSdkVersion); } // we need to translate the sdk to a real api level (i.e. L => 20, MNC => 22) so that // we can valiate them function getRealAPILevel(ver) { return (ver && targetSDKMap[ver] && targetSDKMap[ver].sdk) || ver; } this.realMinSDK = getRealAPILevel(this.minSDK); this.realTargetSDK = getRealAPILevel(this.targetSDK); this.realMaxSDK = getRealAPILevel(this.maxSDK); // min sdk is too old if (this.minSDK && this.realMinSDK < this.minSupportedApiLevel) { logger.error(__('The minimum supported SDK API version must be %s or newer, but is currently set to %s', this.minSupportedApiLevel, this.minSDK + (this.minSDK !== this.realMinSDK ? ' (' + this.realMinSDK + ')' : '')) + '\n'); logger.log( appc.string.wrap( __('Update the %s in the tiapp.xml or custom AndroidManifest to at least %s:', 'android:minSdkVersion'.cyan, String(this.minSupportedApiLevel).cyan), config.get('cli.width', 100) ) ); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <android>'.grey); logger.log(' <manifest>'.grey); logger.log((' <uses-sdk ' + 'android:minSdkVersion="' + this.minSupportedApiLevel + '" ' + (this.targetSDK ? 'android:targetSdkVersion="' + this.targetSDK + '" ' : '') + (this.maxSDK ? 'android:maxSdkVersion="' + this.maxSDK + '" ' : '') + '/>').magenta); logger.log(' </manifest>'.grey); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); process.exit(1); } if (this.targetSDK) { // target sdk is too old if (this.realTargetSDK < this.minTargetApiLevel) { logger.error(__('The target SDK API %s is not supported by Titanium SDK %s', this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : ''), ti.manifest.version)); logger.error(__('The target SDK API version must be %s or newer', this.minTargetApiLevel) + '\n'); logger.log( appc.string.wrap( __('Update the %s in the tiapp.xml or custom AndroidManifest to at least %s:', 'android:targetSdkVersion'.cyan, String(this.minTargetApiLevel).cyan), config.get('cli.width', 100) ) ); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <android>'.grey); logger.log(' <manifest>'.grey); logger.log((' <uses-sdk ' + (this.minSupportedApiLevel ? 'android:minSdkVersion="' + this.minSupportedApiLevel + '" ' : '') + 'android:targetSdkVersion="' + this.minTargetApiLevel + '" ' + (this.maxSDK ? 'android:maxSdkVersion="' + this.maxSDK + '" ' : '') + '/>').magenta); logger.log(' </manifest>'.grey); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); process.exit(1); } // target sdk < min sdk if (this.realTargetSDK < this.realMinSDK) { logger.error(__('The target SDK API must be greater than or equal to the minimum SDK %s, but is currently set to %s', this.minSDK + (this.minSDK !== this.realMinSDK ? ' (' + this.realMinSDK + ')' : ''), this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : '') ) + '\n'); process.exit(1); } } else { // if no target sdk, then default to most recent supported/installed Object .keys(targetSDKMap) .sort(function (a, b) { if (targetSDKMap[a].sdk === targetSDKMap[b].sdk && targetSDKMap[a].revision === targetSDKMap[b].revision) { return 0; } else if (targetSDKMap[a].sdk < targetSDKMap[b].sdk || (targetSDKMap[a].sdk === targetSDKMap[b].sdk && targetSDKMap[a].revision < targetSDKMap[b].revision)) { return -1; } return 1; }) .reverse() .some(function (ver) { if (targetSDKMap[ver].sdk >= this.minTargetApiLevel && targetSDKMap[ver].sdk <= this.maxSupportedApiLevel) { this.targetSDK = this.realTargetSDK = targetSDKMap[ver].sdk; return true; } }, this); if (!this.targetSDK || this.realTargetSDK < this.minTargetApiLevel) { if (this.minTargetApiLevel === this.maxSupportedApiLevel) { logger.error(__('Unable to find Android SDK API %s', this.maxSupportedApiLevel)); logger.error(__('Android SDK API %s is required to build Android apps', this.maxSupportedApiLevel) + '\n'); } else { logger.error(__('Unable to find a suitable installed Android SDK that is API >=%s and <=%s', this.minTargetApiLevel, this.maxSupportedApiLevel) + '\n'); } process.exit(1); } } // check that we have this target sdk installed this.androidTargetSDK = targetSDKMap[this.targetSDK]; if (!this.androidTargetSDK) { logger.error(__('Target Android SDK API %s is not installed', this.targetSDK) + '\n'); var sdks = Object.keys(targetSDKMap).filter(function (ver) { return ~~ver > this.minSupportedApiLevel; }.bind(this)).sort().filter(function (s) { return s >= this.minSDK; }, this); if (sdks.length) { logger.log(__('To target Android SDK API %s, you first must install it using the Android SDK manager.', String(this.targetSDK).cyan) + '\n'); logger.log( appc.string.wrap( __('Alternatively, you can set the %s in the %s section of the tiapp.xml to one of the following installed Android target SDK APIs: %s', '<uses-sdk>'.cyan, '<android> <manifest>'.cyan, sdks.join(', ').cyan), config.get('cli.width', 100) ) ); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <android>'.grey); logger.log(' <manifest>'.grey); logger.log((' <uses-sdk ' + (this.minSDK ? 'android:minSdkVersion="' + this.minSDK + '" ' : '') + 'android:targetSdkVersion="' + sdks[0] + '" ' + (this.maxSDK ? 'android:maxSdkVersion="' + this.maxSDK + '" ' : '') + '/>').magenta); logger.log(' </manifest>'.grey); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); } else { logger.log(__('To target Android SDK API %s, you first must install it using the Android SDK manager', String(this.targetSDK).cyan) + '\n'); } process.exit(1); } if (!this.androidTargetSDK.androidJar) { logger.error(__('Target Android SDK API %s is missing "android.jar"', this.targetSDK) + '\n'); process.exit(1); } if (this.realTargetSDK < this.realMinSDK) { logger.error(__('Target Android SDK API version must be %s or newer', this.minSDK) + '\n'); process.exit(1); } if (this.realMaxSDK && this.realMaxSDK < this.realTargetSDK) { logger.error(__('Maximum Android SDK API version must be greater than or equal to the target SDK API %s, but is currently set to %s', this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : ''), this.maxSDK + (this.maxSDK !== this.realMaxSDK ? ' (' + this.realMaxSDK + ')' : '') ) + '\n'); process.exit(1); } if (this.maxSupportedApiLevel && this.realTargetSDK > this.maxSupportedApiLevel) { // print warning that version this.targetSDK is not tested logger.warn(__('Building with Android SDK API %s which hasn\'t been tested against Titanium SDK %s', String(this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : '')).cyan, this.titaniumSdkVersion )); } // determine the abis to support this.abis = this.validABIs; if (cli.tiapp.android && cli.tiapp.android.abi && cli.tiapp.android.abi.indexOf('all') == -1) { this.abis = cli.tiapp.android.abi; this.abis.forEach(function (abi) { if (this.validABIs.indexOf(abi) == -1) { logger.error(__('Invalid ABI "%s"', abi) + '\n'); logger.log(__('Valid ABIs:')); this.validABIs.forEach(function (name) { logger.log(' ' + name.cyan); }); logger.log(); process.exit(1); } }, this); } var deviceId = cli.argv['device-id']; if (!cli.argv['build-only'] && /^device|emulator$/.test(this.target) && deviceId === undefined && config.get('android.autoSelectDevice', true)) { // no --device-id, so intelligently auto select one var ver = this.androidTargetSDK.version, apiLevel = this.androidTargetSDK.sdk, devices = this.devicesToAutoSelectFrom, i, len = devices.length, verRegExp = /^((\d\.)?\d\.)?\d$/; // reset the device id deviceId = null; if (cli.argv.target == 'device') { logger.info(__('Auto selecting device that closest matches %s', ver.cyan)); } else { logger.info(__('Auto selecting emulator that closest matches %s', ver.cyan)); } function setDeviceId(device) { deviceId = cli.argv['device-id'] = device.id; var gapi = ''; if (device.googleApis) { gapi = (' (' + __('Google APIs supported') + ')').grey; } else if (device.googleApis === null) { gapi = (' (' + __('Google APIs support unknown') + ')').grey; } if (cli.argv.target == 'device') { logger.info(__('Auto selected device %s %s', device.name.cyan, device.version) + gapi); } else { logger.info(__('Auto selected emulator %s %s', device.name.cyan, device.version) + gapi); } } function gte(device) { return device.api >= apiLevel && (!verRegExp.test(device.version) || appc.version.gte(device.version, ver)); } function lt(device) { return device.api < apiLevel && (!verRegExp.test(device.version) || appc.version.lt(device.version, ver)); } // find the first one where version is >= and google apis == true logger.debug(__('Searching for version >= %s and has Google APIs', ver)); for (i = 0; i < len; i++) { if (gte(devices[i]) && devices[i].googleApis) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version is >= and google apis is a maybe logger.debug(__('Searching for version >= %s and may have Google APIs', ver)); for (i = 0; i < len; i++) { if (gte(devices[i]) && devices[i].googleApis === null) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version is >= and no google apis logger.debug(__('Searching for version >= %s and no Google APIs', ver)); for (i = 0; i < len; i++) { if (gte(devices[i])) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version < and google apis == true logger.debug(__('Searching for version < %s and has Google APIs', ver)); for (i = len - 1; i >= 0; i--) { if (lt(devices[i])) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version < logger.debug(__('Searching for version < %s and no Google APIs', ver)); for (i = len - 1; i >= 0; i--) { if (lt(devices[i]) && devices[i].googleApis) { setDeviceId(devices[i]); break; } } if (!deviceId) { // just grab first one logger.debug(__('Selecting first device')); setDeviceId(devices[0]); } } } } } var devices = deviceId == 'all' ? this.devices : this.devices.filter(function (d) { return d.id = deviceId; }); devices.forEach(function (device) { if (Array.isArray(device.abi) && !device.abi.some(function (a) { return this.abis.indexOf(a) != -1; }.bind(this))) { if (this.target == 'emulator') { logger.error(__n('The emulator "%%s" does not support the desired ABI %%s', 'The emulator "%%s" does not support the desired ABIs %%s', this.abis.length, device.name, '"' + this.abis.join('", "') + '"')); } else { logger.error(__n('The device "%%s" does not support the desired ABI %%s', 'The device "%%s" does not support the desired ABIs %%s', this.abis.length, device.model || device.manufacturer, '"' + this.abis.join('", "') + '"')); } logger.error(__('Supported ABIs: %s', device.abi.join(', ')) + '\n'); logger.log(__('You need to add at least one of the device\'s supported ABIs to the tiapp.xml')); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <!-- snip -->'.grey); logger.log(' <android>'.grey); logger.log((' <abi>' + this.abis.concat(device.abi).join(',') + '</abi>').magenta); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); process.exit(1); } }, this); } // validate debugger and profiler options var tool = []; this.allowDebugging && tool.push('debug'); this.allowProfiling && tool.push('profiler'); this.debugHost = null; this.debugPort = null; this.profilerHost = null; this.profilerPort = null; tool.forEach(function (type) { if (cli.argv[type + '-host']) { if (typeof cli.argv[type + '-host'] == 'number') { logger.error(__('Invalid %s host "%s"', type, cli.argv[type + '-host']) + '\n'); logger.log(__('The %s host must be in the format "host:port".', type) + '\n'); process.exit(1); } var parts = cli.argv[type + '-host'].split(':'); if (parts.length < 2) { logger.error(__('Invalid ' + type + ' host "%s"', cli.argv[type + '-host']) + '\n'); logger.log(__('The %s host must be in the format "host:port".', type) + '\n'); process.exit(1); } var port = parseInt(parts[1]); if (isNaN(port) || port < 1 || port > 65535) { logger.error(__('Invalid ' + type + ' host "%s"', cli.argv[type + '-host']) + '\n'); logger.log(__('The port must be a valid integer between 1 and 65535.') + '\n'); process.exit(1); } this[type + 'Host'] = parts[0]; this[type + 'Port'] = port; } }, this); if (this.debugPort || this.profilerPort) { // if debugging/profiling, make sure we only have one device and that it has an sd card if (this.target == 'emulator') { var emu = this.devices.filter(function (d) { return d.name == deviceId; }).shift(); if (!emu) { logger.error(__('Unable find emulator "%s"', deviceId) + '\n'); process.exit(1); } else if (!emu.sdcard && emu.type != 'genymotion') { logger.error(__('The selected emulator "%s" does not have an SD card.', emu.name)); if (this.profilerPort) { logger.error(__('An SD card is required for profiling.') + '\n'); } else { logger.error(__('An SD card is required for debugging.') + '\n'); } process.exit(1); } } else if (this.target == 'device' && deviceId == 'all' && this.devices.length > 1) { // fail, can't do 'all' for debug builds logger.error(__('Cannot debug application when --device-id is set to "all" and more than one device is connected.')); logger.error(__('Please specify a single device to debug on.') + '\n'); process.exit(1); } } // check that the build directory is writeable var buildDir = path.join(cli.argv['project-dir'], 'build'); if (fs.existsSync(buildDir)) { if (!afs.isDirWritable(buildDir)) { logger.error(__('The build directory is not writeable: %s', buildDir) + '\n'); logger.log(__('Make sure the build directory is writeable and that you have sufficient free disk space.') + '\n'); process.exit(1); } } else if (!afs.isDirWritable(cli.argv['project-dir'])) { logger.error(__('The project directory is not writeable: %s', cli.argv['project-dir']) + '\n'); logger.log(__('Make sure the project directory is writeable and that you have sufficient free disk space.') + '\n'); process.exit(1); } // make sure we have an icon if (this.tiappAndroidManifest && this.tiappAndroidManifest.application && this.tiappAndroidManifest.application.icon) { cli.tiapp.icon = this.tiappAndroidManifest.application.icon.replace(/^\@drawable\//, '') + '.png'; } else if (this.customAndroidManifest && this.customAndroidManifest.application && this.customAndroidManifest.application.icon) { cli.tiapp.icon = this.customAndroidManifest.application.icon.replace(/^\@drawable\//, '') + '.png'; } if (!cli.tiapp.icon || !['Resources', 'Resources/android'].some(function (p) { return fs.existsSync(cli.argv['project-dir'], p, cli.tiapp.icon); })) { cli.tiapp.icon = 'appicon.png'; } return function (callback) { this.validateTiModules('android', this.deployType, function (err, modules) { this.modules = modules.found; this.commonJsModules = []; this.nativeLibModules = []; var manifestHashes = [], nativeHashes = [], bindingsHashes = [], jarHashes = {}; modules.found.forEach(function (module) { manifestHashes.push(this.hash(JSON.stringify(module.manifest))); if (module.platform.indexOf('commonjs') != -1) { module.native = false; // Look for legacy module.id.js first module.libFile = path.join(module.modulePath, module.id + '.js'); if (!fs.existsSync(module.libFile)) { // then package.json TODO Verify the main property points at reale file under the module! module.libFile = path.join(module.modulePath, 'package.json'); if (!fs.existsSync(module.libFile)) { // then index.js module.libFile = path.join(module.modulePath, 'index.js'); if (!fs.existsSync(module.libFile)) { // then index.json module.libFile = path.join(module.modulePath, 'index.json'); if (!fs.existsSync(module.libFile)) { this.logger.error(__('Module %s version %s is missing module files: %s, package.json, index.js, or index.json', module.id.cyan, (module.manifest.version || 'latest').cyan, path.join(module.modulePath, module.id + '.js').cyan) + '\n'); process.exit(1); } } } } this.commonJsModules.push(module); } else { module.native = true; // jar filenames are always lower case and must correspond to the name in the module's build.xml file module.jarName = module.manifest.name.toLowerCase() + '.jar', module.jarFile = path.join(module.modulePath, module.jarName); if (!fs.existsSync(module.jarFile)) { // NOTE: this should be an error, not a warning, but due to the soasta module, we can't error out // logger.error(__('Module %s version %s is missing main jar file', module.id.cyan, (module.manifest.version || 'latest').cyan) + '\n'); // process.exit(1); logger.warn(__('Module %s version %s does not have a main jar file', module.id.cyan, (module.manifest.version || 'latest').cyan)); module.jarName = module.jarFile = null; } else { // get the jar hashes var jarHash = module.hash = this.hash(fs.readFileSync(module.jarFile).toString()); nativeHashes.push(jarHash); jarHashes[module.jarName] || (jarHashes[module.jarName] = []); jarHashes[module.jarName].push({ hash: module.hash, module: module }); } var libDir = path.join(module.modulePath, 'lib'), jarRegExp = /\.jar$/; fs.existsSync(libDir) && fs.readdirSync(libDir).forEach(function (name) { var file = path.join(libDir, name); if (jarRegExp.test(name) && fs.existsSync(file)) { jarHashes[name] || (jarHashes[name] = []); jarHashes[name].push({ hash: this.hash(fs.readFileSync(file).toString()), module: module }); } }, this); // determine the module's ABIs module.abis = []; var libsDir = path.join(module.modulePath, 'libs'), soRegExp = /\.so$/; fs.existsSync(libsDir) && fs.readdirSync(libsDir).forEach(function (abi) { var dir = path.join(libsDir, abi), added = false; if (!this.ignoreDirs.test(abi) && fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { fs.readdirSync(dir).forEach(function (name) { if (soRegExp.test(name)) { var file = path.join(dir, name); if (!added) { module.abis.push(abi); added = true; } nativeHashes.push(afs.hashFile(file)); } }); } }, this); // check missing abis var missingAbis = module.abis.length && this.abis.filter(function (a) { return module.abis.indexOf(a) == -1; }); if (missingAbis.length) { /* commenting this out to preserve the old, incorrect behavior this.logger.error(__n('The module "%%s" does not support the ABI: %%s', 'The module "%%s" does not support the ABIs: %s', missingAbis.length, module.id, '"' + missingAbis.join('" "') + '"')); this.logger.error(__('It only supports the following ABIs: %s', module.abis.join(', ')) + '\n'); process.exit(1); */ this.logger.warn(__n('The module %%s does not support the ABI: %%s', 'The module %%s does not support the ABIs: %s', missingAbis.length, module.id.cyan, missingAbis.map(function (a) { return a.cyan; }).join(', '))); this.logger.warn(__('It only supports the following ABIs: %s', module.abis.map(function (a) { return a.cyan; }).join(', '))); this.logger.warn(__('Your application will most likely encounter issues')); } if (module.jarFile) { // read in the bindings try { module.bindings = this.getNativeModuleBindings(module.jarFile); if (!module.bindings) { logger.error(__('Module %s version %s is missing bindings json file', module.id.cyan, (module.manifest.version || 'latest').cyan) + '\n'); process.exit(1); } bindingsHashes.push(this.hash(JSON.stringify(module.bindings))); } catch (ex) { logger.error(__('The module "%s" has an invalid jar file: %s', module.id, module.jarFile) + '\n'); process.exit(1); } } this.nativeLibModules.push(module); } // scan the module for any CLI hooks cli.scanHooks(path.join(module.modulePath, 'hooks')); }, this); this.modulesManifestHash = this.hash(manifestHashes.length ? manifestHashes.sort().join(',') : ''); this.modulesNativeHash = this.hash(nativeHashes.length ? nativeHashes.sort().join(',') : ''); this.modulesBindingsHash = this.hash(bindingsHashes.length ? bindingsHashes.sort().join(',') : ''); // check if we have any conflicting jars var possibleConflicts = Object.keys(jarHashes).filter(function (jar) { return jarHashes[jar].length > 1; }); if (possibleConflicts.length) { var foundConflict = false; possibleConflicts.forEach(function (jar) { var modules = jarHashes[jar], maxlen = 0, h = {}; modules.forEach(function (m) { m.module.id.length > maxlen && (maxlen = m.module.id.length); h[m.hash] = 1; }); if (Object.keys(h).length > 1) { if (!foundConflict) { logger.error(__('Conflicting jar files detected:')); foundConflict = true; } logger.error(); logger.error(__('The following modules have different "%s" files', jar)); modules.forEach(function (m) { logger.error(__(' %s (version %s) (hash=%s)', appc.string.rpad(m.module.id, maxlen + 2), m.module.version, m.hash)); }); } }); if (foundConflict) { logger.error(); appc.string.wrap( __('You can either select a version of these modules where the conflicting jar file is the same or you can try copying the jar file from one module\'s "lib" folder to the other module\'s "lib" folder.'), config.get('cli.width', 100) ).split('\n').forEach(logger.error); logger.log(); process.exit(1); } } callback(); }.bind(this)); }.bind(this); }; AndroidBuilder.prototype.run = function run(logger, config, cli, finished) { Builder.prototype.run.apply(this, arguments); appc.async.series(this, [ function (next) { cli.emit('build.pre.construct', this, next); }, 'doAnalytics', 'initialize', 'loginfo', 'computeHashes', 'readBuildManifest', 'checkIfNeedToRecompile', 'getLastBuildState', function (next) { cli.emit('build.pre.compile', this, next); }, 'createBuildDirs', 'copyResources', 'generateRequireIndex', 'processTiSymbols', 'copyModuleResources', 'removeOldFiles', 'generateJavaFiles', 'generateAidl', // generate the i18n files after copyModuleResources to make sure the app_name isn't // overwritten by some module's strings.xml 'generateI18N', 'generateTheme', 'generateAndroidManifest', 'packageApp', // provide a hook event before javac function (next) { cli.emit('build.pre.build', this, next); }, // we only need to compile java classes if any files in src or gen changed 'compileJavaClasses', // provide a hook event after javac function (next) { cli.emit('build.post.build', this, next); }, // we only need to run proguard if any java classes have changed 'runProguard', // we only need to run the dexer if this.moduleJars or this.jarLibraries changes or // any files in this.buildBinClassesDir have changed or debugging/profiling toggled 'runDexer', 'createUnsignedApk', 'createSignedApk', 'zipAlignApk', 'writeBuildManifest', function (next) { if (!this.buildOnly && this.target == 'simulator') { var delta = appc.time.prettyDiff(this.cli.startTime, Date.now()); this.logger.info(__('Finished building the application in %s', delta.cyan)); } cli.emit('build.post.compile', this, next); }, function (next) { cli.emit('build.finalize', this, next); } ], finished); }; AndroidBuilder.prototype.doAnalytics = function doAnalytics(next) { var cli = this.cli, eventName = 'android.' + cli.argv.target; if (cli.argv.target == 'dist-playstore') { eventName = "android.distribute.playstore"; } else if (this.allowDebugging && this.debugPort) { eventName += '.debug'; } else if (this.allowProfiling && this.profilerPort) { eventName += '.profile'; } else { eventName += '.run'; } cli.addAnalyticsEvent(eventName, { dir: cli.argv['project-dir'], name: cli.tiapp.name, publisher: cli.tiapp.publisher, url: cli.tiapp.url, image: cli.tiapp.icon, appid: cli.tiapp.id, description: cli.tiapp.description, type: cli.argv.type, guid: cli.tiapp.guid, version: cli.tiapp.version, copyright: cli.tiapp.copyright, date: (new Date()).toDateString() }); next(); }; AndroidBuilder.prototype.initialize = function initialize(next) { var argv = this.cli.argv; this.appid = this.tiapp.id; this.appid.indexOf('.') == -1 && (this.appid = 'com.' + this.appid); this.classname = this.tiapp.name.split(/[^A-Za-z0-9_]/).map(function (word) { return appc.string.capitalize(word.toLowerCase()); }).join(''); /^[0-9]/.test(this.classname) && (this.classname = '_' + this.classname); this.buildOnly = argv['build-only']; var deviceId = this.deviceId = argv['device-id']; if (!this.buildOnly && this.target == 'emulator') { var emu = this.devices.filter(function (e) { return e.name == deviceId; }).shift(); if (!emu) { // sanity check this.logger.error(__('Unable to find Android emulator "%s"', deviceId) + '\n'); process.exit(0); } this.emulator = emu; } this.outputDir = argv['output-dir'] ? afs.resolvePath(argv['output-dir']) : null; // set the keystore to the dev keystore, if not already set this.keystore = argv.keystore; this.keystoreStorePassword = argv['store-password']; this.keystoreKeyPassword = argv['key-password']; if (!this.keystore) { this.keystore = path.join(this.platformPath, 'dev_keystore'); this.keystoreStorePassword = 'tirocks'; this.keystoreAlias = { name: 'tidev', sigalg: 'MD5withRSA' }; } var loadFromSDCardProp = this.tiapp.properties['ti.android.loadfromsdcard']; this.loadFromSDCard = loadFromSDCardProp && loadFromSDCardProp.value === true; var includeAllTiModulesProp = this.tiapp.properties['ti.android.include_all_modules']; if (includeAllTiModulesProp !== undefined) { this.includeAllTiModules = includeAllTiModulesProp.value; } // directories this.buildAssetsDir = path.join(this.buildDir, 'assets'); this.buildBinDir = path.join(this.buildDir, 'bin'); this.buildBinAssetsDir = path.join(this.buildBinDir, 'assets'); this.buildBinAssetsResourcesDir = path.join(this.buildBinAssetsDir, 'Resources'); this.buildBinClassesDir = path.join(this.buildBinDir, 'classes'); this.buildBinClassesDex = path.join(this.buildBinDir, 'dexfiles'); this.buildGenDir = path.join(this.buildDir, 'gen'); this.buildGenAppIdDir = path.join(this.buildGenDir, this.appid.split('.').join(path.sep)); this.buildResDir = path.join(this.buildDir, 'res'); this.buildResDrawableDir = path.join(this.buildResDir, 'drawable') this.buildSrcDir = path.join(this.buildDir, 'src'); this.templatesDir = path.join(this.platformPath, 'templates', 'build'); // files this.buildManifestFile = path.join(this.buildDir, 'build-manifest.json'); this.androidManifestFile = path.join(this.buildDir, 'AndroidManifest.xml'); var suffix = this.debugPort || this.profilerPort ? '-dev' + (this.debugPort ? '-debug' : '') + (this.profilerPort ? '-profiler' : '') : ''; this.unsignedApkFile = path.join(this.buildBinDir, 'app-unsigned' + suffix + '.apk'); this.apkFile = path.join(this.buildBinDir, this.tiapp.name + suffix + '.apk'); next(); }; AndroidBuilder.prototype.loginfo = function loginfo(next) { this.logger.debug(__('Titanium SDK Android directory: %s', this.platformPath.cyan)); this.logger.info(__('Deploy type: %s', this.deployType.cyan)); this.logger.info(__('Building for target: %s', this.target.cyan)); if (this.buildOnly) { this.logger.info(__('Performing build only')); } else { if (this.target == 'emulator') { this.logger.info(__('Building for emulator: %s', this.deviceId.cyan)); } else if (this.target == 'device') { this.logger.info(__('Building for device: %s', this.deviceId.cyan)); } } this.logger.info(__('Targeting Android SDK API: %s', String(this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : '')).cyan)); this.logger.info(__('Building for the following architectures: %s', this.abis.join(', ').cyan)); this.logger.info(__('Signing with keystore: %s', (this.keystore + ' (' + this.keystoreAlias.name + ')').cyan)); this.logger.debug(__('App ID: %s', this.appid.cyan)); this.logger.debug(__('Classname: %s', this.classname.cyan)); if (this.allowDebugging && this.debugPort) { this.logger.info(__('Debugging enabled via debug port: %s', String(this.debugPort).cyan)); } else { this.logger.info(__('Debugging disabled')); } if (this.allowProfiling && this.profilerPort) { this.logger.info(__('Profiler enabled via profiler port: %s', String(this.profilerPort).cyan)); } else { this.logger.info(__('Profiler disabled')); } next(); }; AndroidBuilder.prototype.computeHashes = function computeHashes(next) { // modules this.modulesHash = !Array.isArray(this.tiapp.modules) ? '' : this.hash(this.tiapp.modules.filter(function (m) { return !m.platform || /^android|commonjs$/.test(m.platform); }).map(function (m) { return m.id + ',' + m.platform + ',' + m.version; }).join('|')); // tiapp.xml properties, activities, and services this.propertiesHash = this.hash(this.tiapp.properties ? JSON.stringify(this.tiapp.properties) : ''); var android = this.tiapp.android; this.activitiesHash = this.hash(android && android.application && android.application ? JSON.stringify(android.application.activities) : ''); this.servicesHash = this.hash(android && android.services ? JSON.stringify(android.services) : ''); var self = this; function walk(dir, re) { var hashes = []; fs.existsSync(dir) && fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { var stat = fs.statSync(file); if (stat.isFile() && re.test(name)) { hashes.push(self.hash(fs.readFileSync(file).toString())); } else if (stat.isDirectory()) { hashes = hashes.concat(walk(file, re)); } } }); return hashes; } next(); }; AndroidBuilder.prototype.readBuildManifest = function readBuildManifest(next) { // read the build manifest from the last build, if exists, so we // can determine if we need to do a full rebuild this.buildManifest = {}; if (fs.existsSync(this.buildManifestFile)) { try { this.buildManifest = JSON.parse(fs.readFileSync(this.buildManifestFile)) || {}; this.prevJarLibHash = this.buildManifest.jarLibHash || ''; } catch (e) {} } next(); }; AndroidBuilder.prototype.checkIfShouldForceRebuild = function checkIfShouldForceRebuild() { var manifest = this.buildManifest; if (this.cli.argv.force) { this.logger.info(__('Forcing rebuild: %s flag was set', '--force'.cyan)); return true; } if (!fs.existsSync(this.buildManifestFile)) { this.logger.info(__('Forcing rebuild: %s does not exist', this.buildManifestFile.cyan)); return true; } if (!fs.existsSync(this.androidManifestFile)) { this.logger.info(__('Forcing rebuild: %s does not exist', this.androidManifestFile.cyan)); return true; } // check if the target changed if (this.target != manifest.target) { this.logger.info(__('Forcing rebuild: target changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.target)); this.logger.info(' ' + __('Now: %s', this.target)); return true; } // check if the deploy type changed if (this.deployType != manifest.deployType) { this.logger.info(__('Forcing rebuild: deploy type changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.deployType)); this.logger.info(' ' + __('Now: %s', this.deployType)); return true; } // check if the classname changed if (this.classname != manifest.classname) { this.logger.info(__('Forcing rebuild: classname changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.classname)); this.logger.info(' ' + __('Now: %s', this.classname)); return true; } // if encryption is enabled, then we must recompile the java files if (this.encryptJS) { this.logger.info(__('Forcing rebuild: JavaScript files need to be re-encrypted')); return true; } // if encryptJS changed, then we need to recompile the java files if (this.encryptJS != manifest.encryptJS) { this.logger.info(__('Forcing rebuild: JavaScript encryption flag changed')); this.logger.info(' ' + __('Was: %s', manifest.encryptJS)); this.logger.info(' ' + __('Now: %s', this.encryptJS)); return true; } // check if the titanium sdk paths are different if (this.platformPath != manifest.platformPath) { this.logger.info(__('Forcing rebuild: Titanium SDK path changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.platformPath)); this.logger.info(' ' + __('Now: %s', this.platformPath)); return true; } // check the git hashes are different if (!manifest.gitHash || manifest.gitHash != ti.manifest.githash) { this.logger.info(__('Forcing rebuild: githash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.gitHash)); this.logger.info(' ' + __('Now: %s', ti.manifest.githash)); return true; } // check if the modules hashes are different if (this.modulesHash != manifest.modulesHash) { this.logger.info(__('Forcing rebuild: modules hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesHash)); this.logger.info(' ' + __('Now: %s', this.modulesHash)); return true; } if (this.modulesManifestHash != manifest.modulesManifestHash) { this.logger.info(__('Forcing rebuild: module manifest hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesManifestHash)); this.logger.info(' ' + __('Now: %s', this.modulesManifestHash)); return true; } if (this.modulesNativeHash != manifest.modulesNativeHash) { this.logger.info(__('Forcing rebuild: native modules hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesNativeHash)); this.logger.info(' ' + __('Now: %s', this.modulesNativeHash)); return true; } if (this.modulesBindingsHash != manifest.modulesBindingsHash) { this.logger.info(__('Forcing rebuild: native modules bindings hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesBindingsHash)); this.logger.info(' ' + __('Now: %s', this.modulesBindingsHash)); return true; } // next we check if any tiapp.xml values changed so we know if we need to reconstruct the main.m if (this.tiapp.name != manifest.name) { this.logger.info(__('Forcing rebuild: tiapp.xml project name changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.name)); this.logger.info(' ' + __('Now: %s', this.tiapp.name)); return true; } if (this.tiapp.id != manifest.id) { this.logger.info(__('Forcing rebuild: tiapp.xml app id changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.id)); this.logger.info(' ' + __('Now: %s', this.tiapp.id)); return true; } if (!this.tiapp.analytics != !manifest.analytics) { this.logger.info(__('Forcing rebuild: tiapp.xml analytics flag changed since last build')); this.logger.info(' ' + __('Was: %s', !!manifest.analytics)); this.logger.info(' ' + __('Now: %s', !!this.tiapp.analytics)); return true; } if (this.tiapp.publisher != manifest.publisher) { this.logger.info(__('Forcing rebuild: tiapp.xml publisher changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.publisher)); this.logger.info(' ' + __('Now: %s', this.tiapp.publisher)); return true; } if (this.tiapp.url != manifest.url) { this.logger.info(__('Forcing rebuild: tiapp.xml url changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.url)); this.logger.info(' ' + __('Now: %s', this.tiapp.url)); return true; } if (this.tiapp.version != manifest.version) { this.logger.info(__('Forcing rebuild: tiapp.xml version changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.version)); this.logger.info(' ' + __('Now: %s', this.tiapp.version)); return true; } if (this.tiapp.description != manifest.description) { this.logger.info(__('Forcing rebuild: tiapp.xml description changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.description)); this.logger.info(' ' + __('Now: %s', this.tiapp.description)); return true; } if (this.tiapp.copyright != manifest.copyright) { this.logger.info(__('Forcing rebuild: tiapp.xml copyright changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.copyright)); this.logger.info(' ' + __('Now: %s', this.tiapp.copyright)); return true; } if (this.tiapp.guid != manifest.guid) { this.logger.info(__('Forcing rebuild: tiapp.xml guid changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.guid)); this.logger.info(' ' + __('Now: %s', this.tiapp.guid)); return true; } if (this.tiapp.icon != manifest.icon) { this.logger.info(__('Forcing rebuild: tiapp.xml icon changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.icon)); this.logger.info(' ' + __('Now: %s', this.tiapp.icon)); return true; } if (this.tiapp.fullscreen != manifest.fullscreen) { this.logger.info(__('Forcing rebuild: tiapp.xml fullscreen changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.fullscreen)); this.logger.info(' ' + __('Now: %s', this.tiapp.fullscreen)); return true; } if (this.tiapp.navbarHidden != manifest.navbarHidden) { this.logger.info(__('Forcing rebuild: tiapp.xml navbar-hidden changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.navbarHidden)); this.logger.info(' ' + __('Now: %s', this.tiapp.navbarHidden)); return true; } if (this.minSDK != manifest.minSDK) { this.logger.info(__('Forcing rebuild: Android minimum SDK changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.minSDK)); this.logger.info(' ' + __('Now: %s', this.minSDK)); return true; } if (this.targetSDK != manifest.targetSDK) { this.logger.info(__('Forcing rebuild: Android target SDK changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.targetSDK)); this.logger.info(' ' + __('Now: %s', this.targetSDK)); return true; } if (this.propertiesHash != manifest.propertiesHash) { this.logger.info(__('Forcing rebuild: tiapp.xml properties changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.propertiesHash)); this.logger.info(' ' + __('Now: %s', this.propertiesHash)); return true; } if (this.activitiesHash != manifest.activitiesHash) { this.logger.info(__('Forcing rebuild: Android activites in tiapp.xml changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.activitiesHash)); this.logger.info(' ' + __('Now: %s', this.activitiesHash)); return true; } if (this.servicesHash != manifest.servicesHash) { this.logger.info(__('Forcing rebuild: Android services in tiapp.xml SDK changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.servicesHash)); this.logger.info(' ' + __('Now: %s', this.servicesHash)); return true; } if (this.config.get('android.mergeCustomAndroidManifest', false) != manifest.mergeCustomAndroidManifest) { this.logger.info(__('Forcing rebuild: mergeCustomAndroidManifest config has changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.mergeCustomAndroidManifest)); this.logger.info(' ' + __('Now: %s', this.config.get('android.mergeCustomAndroidManifest', false))); return true; } return false; }; AndroidBuilder.prototype.checkIfNeedToRecompile = function checkIfNeedToRecompile(next) { // check if we need to do a rebuild this.forceRebuild = this.checkIfShouldForceRebuild(); if (this.forceRebuild && fs.existsSync(this.buildGenAppIdDir)) { wrench.rmdirSyncRecursive(this.buildGenAppIdDir); } fs.existsSync(this.buildGenAppIdDir) || wrench.mkdirSyncRecursive(this.buildGenAppIdDir); // now that we've read the build manifest, delete it so if this build // becomes incomplete, the next build will be a full rebuild fs.existsSync(this.buildManifestFile) && fs.unlinkSync(this.buildManifestFile); next(); }; AndroidBuilder.prototype.getLastBuildState = function getLastBuildState(next) { var lastBuildFiles = this.lastBuildFiles = {}; // walk the entire build dir and build a map of all files (function walk(dir) { fs.existsSync(dir) && fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file) && fs.statSync(file).isDirectory()) { walk(file); } else { lastBuildFiles[file] = 1; } }); }(this.buildDir)); next(); }; AndroidBuilder.prototype.createBuildDirs = function createBuildDirs(next) { // Make sure we have an app.js. This used to be validated in validate(), but since plugins like // Alloy generate an app.js, it may not have existed during validate(), but should exist now // that build.pre.compile was fired. ti.validateAppJsExists(this.projectDir, this.logger, 'android'); fs.existsSync(this.buildDir) || wrench.mkdirSyncRecursive(this.buildDir); // make directories if they don't already exist var dir = this.buildAssetsDir; if (this.forceRebuild) { fs.existsSync(dir) && wrench.rmdirSyncRecursive(dir); Object.keys(this.lastBuildFiles).forEach(function (file) { if (file.indexOf(dir + '/') == 0) { delete this.lastBuildFiles[file]; } }, this); wrench.mkdirSyncRecursive(dir); } else if (!fs.existsSync(dir)) { wrench.mkdirSyncRecursive(dir); } // we always destroy and rebuild the res directory if (fs.existsSync(this.buildResDir)) { wrench.rmdirSyncRecursive(this.buildResDir); } wrench.mkdirSyncRecursive(this.buildResDir); fs.existsSync(dir = this.buildBinAssetsResourcesDir) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = path.join(this.buildDir, 'gen')) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = path.join(this.buildDir, 'lib')) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = this.buildResDrawableDir) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = path.join(this.buildResDir, 'values')) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = this.buildSrcDir) || wrench.mkdirSyncRecursive(dir); // create the deploy.json file which contains debugging/profiling info var deployJsonFile = path.join(this.buildBinAssetsDir, 'deploy.json'), deployData = { debuggerEnabled: !!this.debugPort, debuggerPort: this.debugPort || -1, profilerEnabled: !!this.profilerPort, profilerPort: this.profilerPort || -1 }; fs.existsSync(deployJsonFile) && fs.unlinkSync(deployJsonFile); if (deployData.debuggerEnabled || deployData.profilerEnabled) { fs.writeFileSync(deployJsonFile, JSON.stringify(deployData)); } next(); }; AndroidBuilder.prototype.copyResources = function copyResources(next) { var ignoreDirs = this.ignoreDirs, ignoreFiles = this.ignoreFiles, extRegExp = /\.(\w+)$/, drawableRegExp = /^images\/(high|medium|low|res\-[^\/]+)(\/(.*))/, drawableDpiRegExp = /^(high|medium|low)$/, drawableExtRegExp = /((\.9)?\.(png|jpg))$/, splashScreenRegExp = /^default\.(9\.png|png|jpg)$/, relSplashScreenRegExp = /^default\.(9\.png|png|jpg)$/, drawableResources = {}, jsFiles = {}, moduleResPackages = this.moduleResPackages = [], jsFilesToEncrypt = this.jsFilesToEncrypt = [], htmlJsFiles = this.htmlJsFiles = {}, symlinkFiles = process.platform != 'win32' && this.config.get('android.symlinkResources', true), _t = this; function copyDir(opts, callback) { if (opts && opts.src && fs.existsSync(opts.src) && opts.dest) { opts.origSrc = opts.src; opts.origDest = opts.dest; recursivelyCopy.call(this, opts.src, opts.dest, opts.ignoreRootDirs, opts, callback); } else { callback(); } } function copyFile(from, to, next) { var d = path.dirname(to); fs.existsSync(d) || wrench.mkdirSyncRecursive(d); if (fs.existsSync(to)) { _t.logger.warn(__('Overwriting file %s', to.cyan)); } if (symlinkFiles) { fs.existsSync(to) && fs.unlinkSync(to); this.logger.debug(__('Symlinking %s => %s', from.cyan, to.cyan)); if (next) { fs.symlink(from, to, next); } else { fs.symlinkSync(from, to); } } else { this.logger.debug(__('Copying %s => %s', from.cyan, to.cyan)); if (next) { fs.readFile(from, function (err, data) { if (err) throw err; fs.writeFile(to, data, next); }); } else { fs.writeFileSync(to, fs.readFileSync(from)); } } } function recursivelyCopy(src, dest, ignoreRootDirs, opts, done) { var files; if (fs.statSync(src).isDirectory()) { files = fs.readdirSync(src); } else { // we have a file, so fake a directory listing files = [ path.basename(src) ]; src = path.dirname(src); } async.whilst( function () { return files.length; }, function (next) { var filename = files.shift(), destDir = dest, from = path.join(src, filename), to = path.join(destDir, filename); // check that the file actually exists and isn't a broken symlink if (!fs.existsSync(from)) return next(); var isDir = fs.statSync(from).isDirectory(); // check if we are ignoring this file if ((isDir && ignoreRootDirs && ignoreRootDirs.indexOf(filename) != -1) || (isDir ? ignoreDirs : ignoreFiles).test(filename)) { _t.logger.debug(__('Ignoring %s', from.cyan)); return next(); } // if this is a directory, recurse if (isDir) { setImmediate(function () { recursivelyCopy.call(_t, from, path.join(destDir, filename), null, opts, next); }); return; } // we have a file, now we need to see what sort of file // check if it's a drawable resource var relPath = from.replace(opts.origSrc, '').replace(/\\/g, '/').replace(/^\//, ''), m = relPath.match(drawableRegExp), isDrawable = false; if (m && m.length >= 4 && m[3]) { var destFilename = m[3].toLowerCase(), name = destFilename.replace(drawableExtRegExp, ''), extMatch = destFilename.match(drawableExtRegExp), origExt = extMatch && extMatch[1] || '', hashExt = extMatch && extMatch.length > 2 ? '.' + extMatch[3] : ''; destDir = path.join( _t.buildResDir, drawableDpiRegExp.test(m[1]) ? 'drawable-' + m[1][0] + 'dpi' : 'drawable-' + m[1].substring(4) ); if (splashScreenRegExp.test(filename)) { // we have a splash screen image to = path.join(destDir, 'background' + origExt); } else { to = path.join(destDir, name.replace(/[^a-z0-9_]/g, '_').substring(0, 80) + '_' + _t.hash(name + hashExt).substring(0, 10) + origExt); } isDrawable = true; } else if (m = relPath.match(relSplashScreenRegExp)) { // we have a splash screen // if it's a 9 patch, then the image goes in drawable-nodpi, not drawable if (m[1] == '9.png') { destDir = path.join(_t.buildResDir, 'drawable-nodpi'); to = path.join(destDir, filename.replace('default.', 'background.')); } else { destDir = _t.buildResDrawableDir; to = path.join(_t.buildResDrawableDir, filename.replace('default.', 'background.')); } isDrawable = true; } if (isDrawable) { var _from = from.replace(_t.projectDir, '').substring(1), _to = to.replace(_t.buildResDir, '').replace(drawableExtRegExp, '').substring(1); if (drawableResources[_to]) { _t.logger.error(__('Found conflicting resources:')); _t.logger.error(' ' + drawableResources[_to]); _t.logger.error(' ' + from.replace(_t.projectDir, '').substring(1)); _t.logger.error(__('You cannot have resources that resolve to the same resource entry name') + '\n'); process.exit(1); } drawableResources[_to] = _from; } // if the destination directory does not exists, create it fs.existsSync(destDir) || wrench.mkdirSyncRecursive(destDir); var ext = filename.match(extRegExp); if (ext && ext[1] != 'js') { // we exclude js files because we'll check if they need to be removed after all files have been copied delete _t.lastBuildFiles[to]; } switch (ext && ext[1]) { case 'css': // if we encounter a css file, check if we should minify it if (_t.minifyCSS) { _t.logger.debug(__('Copying and minifying %s => %s', from.cyan, to.cyan)); fs.readFile(from, function (err, data) { if (err) throw err; fs.writeFile(to, new CleanCSS({ processImport: false }).minify(data.toString()).styles, next); }); } else { copyFile.call(_t, from, to, next); } break; case 'html': // find all js files referenced in this html file var relPath = from.replace(opts.origSrc, '').replace(/\\/g, '/').replace(/^\//, '').split('/'); relPath.pop(); // remove the filename relPath = relPath.join('/'); jsanalyze.analyzeHtmlFile(from, relPath).forEach(function (file) { htmlJsFiles[file] = 1; }); _t.cli.createHook('build.android.copyResource', _t, function (from, to, cb) { copyFile.call(_t, from, to, cb); })(from, to, next); break; case 'js': // track each js file so we can copy/minify later // we use the destination file name minus the path to the assets dir as the id // which will eliminate dupes var id = to.replace(opts.origDest, opts.prefix ? opts.prefix : '').replace(/\\/g, '/').replace(/^\//, ''); if (!jsFiles[id] || !opts || !opts.onJsConflict || opts.onJsConflict(from, to, id)) { jsFiles[id] = from; } next(); break; case 'xml': if (_t.xmlMergeRegExp.test(filename)) { _t.cli.createHook('build.android.copyResource', _t, function (from, to, cb) { _t.writeXmlFile(from, to); cb(); })(from, to, next); break; } default: // normal file, just copy it into the build/android/bin/assets directory _t.cli.createHook('build.android.copyResource', _t, function (from, to, cb) { copyFile.call(_t, from, to, cb); })(from, to, next); } }, done ); } function warnDupeDrawableFolders(resourceDir) { var dir = path.join(resourceDir, 'images'); ['high', 'medium', 'low'].forEach(function (dpi) { var oldDir = path.join(dir, dpi), newDir = path.join(dir, 'res-' + dpi[0] + 'dpi'); if (fs.existsSync(oldDir) && fs.existsSync(newDir)) { oldDir = oldDir.replace(this.projectDir, '').replace(/^\//, ''); newDir = newDir.replace(this.projectDir, '').replace(/^\//, ''); this.logger.warn(__('You have both an %s folder and an %s folder', oldDir.cyan, newDir.cyan)); this.logger.warn(__('Files from both of these folders will end up in %s', ('res/drawable-' + dpi[0]+ 'dpi').cyan)); this.logger.warn(__('If two files are named the same, there is no guarantee which one will be copied last and therefore be the one the application uses')); this.logger.warn(__('You should use just one of these folders to avoid conflicts')); } }, this); } var tasks = [ // first task is to copy all files in the Resources directory, but ignore // any directory that is the name of a known platform function (cb) { var src = path.join(this.projectDir, 'Resources'); warnDupeDrawableFolders.call(this, src); _t.logger.debug(__('Copying %s', src.cyan)); copyDir.call(this, { src: src, dest: this.buildBinAssetsResourcesDir, ignoreRootDirs: ti.availablePlatformsNames }, cb); }, // next copy all files from the Android specific Resources directory function (cb) { var src = path.join(this.projectDir, 'Resources', 'android'); warnDupeDrawableFolders.call(this, src); _t.logger.debug(__('Copying %s', src.cyan)); copyDir.call(this, { src: src, dest: this.buildBinAssetsResourcesDir }, cb); } ]; // copy all commonjs modules this.commonJsModules.forEach(function (module) { // copy the main module tasks.push(function (cb) { _t.logger.debug(__('Copying %s', module.modulePath.cyan)); copyDir.call(this, { src: module.modulePath, // Copy under subfolder named after module.id dest: path.join(this.buildBinAssetsResourcesDir, path.basename(module.id)), // Don't copy files under apidoc, docs, documentation, example or assets (assets is handled below) ignoreRootDirs: ['apidoc', 'documentation', 'docs', 'example', 'assets'], // Make note that files are copied relative to the module.id folder at dest // so that we don't see clashes between module1/index.js and module2/index.js prefix: module.id, onJsConflict: function (src, dest, id) { this.logger.error(__('There is a project resource "%s" that conflicts with a CommonJS module', id)); this.logger.error(__('Please rename the file, then rebuild') + '\n'); process.exit(1); }.bind(this) }, cb); }); // copy the assets tasks.push(function (cb) { var src = path.join(module.modulePath, 'assets'); _t.logger.debug(__('Copying %s', src.cyan)); copyDir.call(this, { src: src, dest: path.join(this.buildBinAssetsResourcesDir, 'modules', module.id) }, cb); }); }); //get the respackgeinfo files if they exist this.modules.forEach(function (module) { var respackagepath = path.join(module.modulePath, 'respackageinfo'); if (fs.existsSync(respackagepath)) { var data = fs.readFileSync(respackagepath).toString().split('\n').shift().trim(); if(data.length > 0) { this.moduleResPackages.push(data); } } }, this); var platformPaths = []; // WARNING! This is pretty dangerous, but yes, we're intentionally copying // every file from platform/android and all modules into the build dir this.modules.forEach(function (module) { platformPaths.push(path.join(module.modulePath, 'platform', 'android')); }); platformPaths.push(path.join(this.projectDir, 'platform', 'android')); platformPaths.forEach(function (dir) { if (fs.existsSync(dir)) { tasks.push(function (cb) { copyDir.call(this, { src: dir, dest: this.buildDir }, cb); }); } }, this); appc.async.series(this, tasks, function (err, results) { var templateDir = path.join(this.platformPath, 'templates', 'app', 'default', 'template', 'Resources', 'android'); // if an app icon hasn't been copied, copy the default one var destIcon = path.join(this.buildBinAssetsResourcesDir, this.tiapp.icon); if (!fs.existsSync(destIcon)) { copyFile.call(this, path.join(templateDir, 'appicon.png'), destIcon); } delete this.lastBuildFiles[destIcon]; var destIcon2 = path.join(this.buildResDrawableDir, this.tiapp.icon); if (!fs.existsSync(destIcon2)) { copyFile.call(this, destIcon, destIcon2); } delete this.lastBuildFiles[destIcon2]; // make sure we have a splash screen var backgroundRegExp = /^background(\.9)?\.(png|jpg)$/, destBg = path.join(this.buildResDrawableDir, 'background.png'), nodpiDir = path.join(this.buildResDir, 'drawable-nodpi'); if (!fs.readdirSync(this.buildResDrawableDir).some(function (name) { if (backgroundRegExp.test(name)) { delete this.lastBuildFiles[path.join(this.buildResDrawableDir, name)]; return true; } }, this)) { // no background image in drawable, but what about drawable-nodpi? if (!fs.existsSync(nodpiDir) || !fs.readdirSync(nodpiDir).some(function (name) { if (backgroundRegExp.test(name)) { delete this.lastBuildFiles[path.join(nodpiDir, name)]; return true; } }, this)) { delete this.lastBuildFiles[destBg]; copyFile.call(this, path.join(templateDir, 'default.png'), destBg); } } // copy js files into assets directory and minify if needed this.logger.info(__('Processing JavaScript files')); appc.async.series(this, Object.keys(jsFiles).map(function (id) { return function (done) { var from = jsFiles[id], to = path.join(this.buildBinAssetsResourcesDir, id); if (htmlJsFiles[id]) { // this js file is referenced from an html file, so don't minify or encrypt delete this.lastBuildFiles[to]; return copyFile.call(this, from, to, done); } // we have a js file that may be minified or encrypted // if we're encrypting the JavaScript, copy the files to the assets dir // for processing later if (this.encryptJS) { to = path.join(this.buildAssetsDir, id); jsFilesToEncrypt.push(id); } delete this.lastBuildFiles[to]; try { this.cli.createHook('build.android.copyResource', this, function (from, to, cb) { // parse the AST var r = jsanalyze.analyzeJsFile(from, { minify: this.minifyJS }); // we want to sort by the "to" filename so that we correctly handle file overwriting this.tiSymbols[to] = r.symbols; var dir = path.dirname(to); fs.existsSync(dir) || wrench.mkdirSyncRecursive(dir); if (this.minifyJS) { this.logger.debug(__('Copying and minifying %s => %s', from.cyan, to.cyan)); this.cli.createHook('build.android.compileJsFile', this, function (r, from, to, cb2) { fs.writeFile(to, r.contents, cb2); })(r, from, to, cb); } else if (symlinkFiles) { copyFile.call(this, from, to, cb); } else { // we've already read in the file, so just write the original contents this.logger.debug(__('Copying %s => %s', from.cyan, to.cyan)); fs.writeFile(to, r.contents, cb); } })(from, to, done); } catch (ex) { ex.message.split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } }; }), function () { // write the properties file var appPropsFile = path.join(this.encryptJS ? this.buildAssetsDir : this.buildBinAssetsResourcesDir, '_app_props_.json'), props = {}; Object.keys(this.tiapp.properties).forEach(function (prop) { props[prop] = this.tiapp.properties[prop].value; }, this); fs.writeFileSync( appPropsFile, JSON.stringify(props) ); this.encryptJS && jsFilesToEncrypt.push('_app_props_.json'); delete this.lastBuildFiles[appPropsFile]; if (!jsFilesToEncrypt.length) { // nothing to encrypt, continue return next(); } // figure out which titanium prep to run var titaniumPrep = 'titanium_prep'; if (process.platform == 'darwin') { titaniumPrep += '.macos'; if (appc.version.lt(this.jdkInfo.version, '1.7.0')) { titaniumPrep += '.jdk16'; } } else if (process.platform == 'win32') { titaniumPrep += '.win32.exe'; } else if (process.platform == 'linux') { titaniumPrep += '.linux' + (process.arch == 'x64' ? '64' : '32'); } // encrypt the javascript var titaniumPrepHook = this.cli.createHook('build.android.titaniumprep', this, function (exe, args, opts, done) { this.logger.info(__('Encrypting JavaScript files: %s', (exe + ' "' + args.slice(1).join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { return done({ code: code, msg: err.trim() }); } // write the encrypted JS bytes to the generated Java file fs.writeFileSync( path.join(this.buildGenAppIdDir, 'AssetCryptImpl.java'), ejs.render(fs.readFileSync(path.join(this.templatesDir, 'AssetCryptImpl.java')).toString(), { appid: this.appid, encryptedAssets: out }) ); done(); }.bind(this)); }), args = [ this.tiapp.guid, this.appid, this.buildAssetsDir ].concat(jsFilesToEncrypt), opts = { env: appc.util.mix({}, process.env, { // we force the JAVA_HOME so that titaniumprep doesn't complain 'JAVA_HOME': this.jdkInfo.home }) }, fatal = function fatal(err) { this.logger.error(__('Failed to encrypt JavaScript files')); err.msg.split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); }.bind(this); titaniumPrepHook( path.join(this.platformPath, titaniumPrep), args.slice(0), opts, function (err) { if (!err) { return next(); } if (process.platform !== 'win32' || !/jvm\.dll/i.test(err.msg)) { fatal(err); } // windows 64-bit failed, try again using 32-bit this.logger.debug(__('32-bit titanium prep failed, trying again using 64-bit')); titaniumPrep = 'titanium_prep.win64.exe'; titaniumPrepHook( path.join(this.platformPath, titaniumPrep), args, opts, function (err) { if (err) { fatal(err); } next(); } ); }.bind(this) ); }); }); }; AndroidBuilder.prototype.generateRequireIndex = function generateRequireIndex(callback) { var index = {}, binAssetsDir = this.buildBinAssetsDir.replace(/\\/g, '/'), destFile = path.join(binAssetsDir, 'index.json'); (function walk(dir) { fs.readdirSync(dir).forEach(function (filename) { var file = path.join(dir, filename); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { walk(file); } else if (/\.js(on)?$/.test(filename)) { index[file.replace(/\\/g, '/').replace(binAssetsDir + '/', '')] = 1; } } }); }(this.buildBinAssetsResourcesDir)); this.jsFilesToEncrypt.forEach(function (file) { index['Resources/' + file.replace(/\\/g, '/')] = 1; }); delete index['Resources/_app_props_.json']; fs.existsSync(destFile) && fs.unlinkSync(destFile); fs.writeFile(destFile, JSON.stringify(index), callback); }; AndroidBuilder.prototype.getNativeModuleBindings = function getNativeModuleBindings(jarFile) { var zip = new AdmZip(jarFile), zipEntries = zip.getEntries(), i = 0, len = zipEntries.length, pathName = 'org/appcelerator/titanium/bindings/', pathNameLen = pathName.length, entry, name; for (; i < len; i++) { entry = zipEntries[i]; name = entry.entryName.toString(); if (name.length > pathNameLen && name.indexOf(pathName) == 0) { try { return JSON.parse(entry.getData()); } catch (e) {} return; } } }; AndroidBuilder.prototype.processTiSymbols = function processTiSymbols(next) { var depMap = JSON.parse(fs.readFileSync(path.join(this.platformPath, 'dependency.json'))), modulesMap = JSON.parse(fs.readFileSync(path.join(this.platformPath, 'modules.json'))), modulesPath = path.join(this.platformPath, 'modules'), moduleBindings = {}, externalChildModules = {}, moduleJarMap = {}, tiNamespaces = this.tiNamespaces = {}, // map of namespace => titanium functions (i.e. ui => createWindow) jarLibraries = this.jarLibraries = {}, resPackages = this.resPackages = {}, appModules = this.appModules = [], // also used in the App.java template appModulesMap = {}, customModules = this.customModules = [], ignoreNamespaces = /^(addEventListener|builddate|buildhash|fireEvent|include|_JSON|name|removeEventListener|userAgent|version)$/; // reorg the modules map by module => jar instead of jar => modules Object.keys(modulesMap).forEach(function (jar) { modulesMap[jar].forEach(function (name) { moduleJarMap[name.toLowerCase()] = jar; }); }); // load all module bindings fs.readdirSync(modulesPath).forEach(function (filename) { var file = path.join(modulesPath, filename); if (fs.existsSync(file) && fs.statSync(file).isFile() && /\.jar$/.test(filename)) { var bindings = this.getNativeModuleBindings(file); if (bindings) { Object.keys(bindings.modules).forEach(function (moduleClass) { if (bindings.proxies[moduleClass]) { moduleBindings[moduleClass] = bindings.modules[moduleClass]; moduleBindings[moduleClass].fullAPIName = bindings.proxies[moduleClass].proxyAttrs.fullAPIName; } else { // parent module is external, so the reference needs to be injected at boot time Array.isArray(externalChildModules[moduleClass]) || (externalChildModules[moduleClass] = []); externalChildModules[moduleClass] = externalChildModules[moduleClass].concat(bindings.modules[moduleClass].childModules); } }); } } }, this); // get the v8 runtime jar file(s) if (depMap && depMap.runtimes && depMap.runtimes.v8) { var v8 = depMap.runtimes.v8; (Array.isArray(v8) ? v8 : [ v8 ]).forEach(function (jar) { if (fs.existsSync(jar = path.join(this.platformPath, jar))) { this.logger.debug(__('Adding library %s', jar.cyan)); jarLibraries[jar] = 1; } }, this); } function addTitaniumLibrary(namespace) { namespace = namespace.toLowerCase(); if (ignoreNamespaces.test(namespace) || tiNamespaces[namespace]) return; tiNamespaces[namespace] = []; var jar = moduleJarMap[namespace]; if (jar) { jar = jar == 'titanium.jar' ? path.join(this.platformPath, jar) : path.join(this.platformPath, 'modules', jar); if (fs.existsSync(jar) && !jarLibraries[jar]) { this.logger.debug(__('Adding library %s', jar.cyan)); jarLibraries[jar] = 1; } } else { this.logger.debug(__('Unknown namespace %s, skipping', namespace.cyan)); } depMap.libraries[namespace] && depMap.libraries[namespace].forEach(function (jar) { if (fs.existsSync(jar = path.join(this.platformPath, jar)) && !jarLibraries[jar]) { this.logger.debug(__('Adding dependency library %s', jar.cyan)); jarLibraries[jar] = 1; } }, this); depMap.dependencies[namespace] && depMap.dependencies[namespace].forEach(addTitaniumLibrary, this); } // get all required titanium modules depMap.required.forEach(addTitaniumLibrary, this); // if we need to include all titanium modules, then do it if (this.includeAllTiModules) { Object.keys(moduleJarMap).forEach(addTitaniumLibrary, this); } // for each Titanium symbol found when we copied the JavaScript files, we need // extract the Titanium namespace and make sure we include its jar library Object.keys(this.tiSymbols).forEach(function (file) { this.tiSymbols[file].forEach(function (symbol) { var parts = symbol.split('.').slice(0, -1), // strip last part which should be the method or property namespace; // add this namespace and all parent namespaces while (parts.length) { namespace = parts.join('.'); if (namespace) { addTitaniumLibrary.call(this, namespace); if (tiNamespaces[namespace]) { // track each method/property tiNamespaces[namespace].push(parts[parts.length - 1]); } } parts.pop(); } }, this); }, this); function createModuleDescriptor(namespace) { var results = { 'api_name': '', 'class_name': '', 'bindings': tiNamespaces[namespace], 'external_child_modules': [], 'on_app_create': null }, moduleBindingKeys = Object.keys(moduleBindings), len = moduleBindingKeys.length, i, name, extChildModule; for (i = 0; i < len; i++) { name = moduleBindingKeys[i]; if (moduleBindings[name].fullAPIName.toLowerCase() == namespace) { results['api_name'] = moduleBindings[name].fullAPIName results['class_name'] = name; if (moduleBindings[name]['on_app_create']) { results['on_app_create'] = moduleBindings[name]['on_app_create']; } break; } } // check if we found the api name and if not bail if (!results['api_name']) return; if (extChildModule = externalChildModules[results['class_name']]) { for (i = 0, len = extChildModule.length; i < len; i++) { if (tiNamespaces[extChildModule[i].fullAPIName.toLowerCase()]) { results['external_child_modules'].push(extChildModule[i]); break; } } } appModulesMap[results['api_name'].toLowerCase()] = 1; return results; } // build the list of modules for the templates Object.keys(tiNamespaces).map(createModuleDescriptor).forEach(function (m) { m && appModules.push(m); }); this.modules.forEach(function (module) { // check if the module has a metadata.json (which most native-wrapped CommonJS // modules should), then make sure those Titanium namespaces are loaded var metadataFile = path.join(module.modulePath, 'metadata.json'), metadata; if (fs.existsSync(metadataFile)) { metadata = JSON.parse(fs.readFileSync(metadataFile)); if (metadata && typeof metadata == 'object' && Array.isArray(metadata.exports)) { metadata.exports.forEach(function (namespace) { addTitaniumLibrary.call(this, namespace); }, this); } else { metadata = null; } } if (!module.jarFile || !module.bindings) return; Object.keys(module.bindings.modules).forEach(function (moduleClass) { var proxy = module.bindings.proxies[moduleClass]; if (proxy.proxyAttrs.id != module.manifest.moduleid) return; var result = { apiName: module.bindings.modules[moduleClass].apiName, proxyName: proxy.proxyClassName, className: moduleClass, manifest: module.manifest, onAppCreate: proxy.onAppCreate || proxy['on_app_create'] || null, isNativeJsModule: !!module.manifest.commonjs }; // make sure that the module was not built before 1.8.0.1 if (~~module.manifest.apiversion < 2) { this.logger.error(__('The "apiversion" for "%s" in the module manifest is less than version 2.', module.manifest.moduleid.cyan)); this.logger.error(__('The module was likely built against a Titanium SDK 1.8.0.1 or older.')); this.logger.error(__('Please use a version of the module that has "apiversion" 2 or greater')); this.logger.log(); process.exit(1); } customModules.push(result); metadata && metadata.exports.forEach(function (namespace) { if (!appModulesMap[namespace]) { var r = createModuleDescriptor(namespace); r && appModules.push(r); } }); }, this); }, this); // write the app.json this.logger.info(__('Writing %s', path.join(this.buildBinAssetsDir, 'app.json').cyan)); fs.writeFileSync(path.join(this.buildBinAssetsDir, 'app.json'), JSON.stringify({ app_modules: appModules })); this.jarLibHash = this.hash(Object.keys(jarLibraries).sort().join('|')); if (this.jarLibHash != this.buildManifest.jarLibHash) { if (!this.forceRebuild) { this.logger.info(__('Forcing rebuild: Detected change in Titanium APIs used and need to recompile')); } this.forceRebuild = true; } next(); }; AndroidBuilder.prototype.copyModuleResources = function copyModuleResources(next) { var _t = this; function copy(src, dest) { fs.readdirSync(src).forEach(function (filename) { var from = path.join(src, filename), to = path.join(dest, filename); if (fs.existsSync(from)) { delete _t.lastBuildFiles[to]; if (fs.statSync(from).isDirectory()) { copy(from, to); } else if (_t.xmlMergeRegExp.test(filename)) { _t.writeXmlFile(from, to); } else { afs.copyFileSync(from, to, { logger: _t.logger.debug }); } } }); } var tasks = Object.keys(this.jarLibraries).map(function (jarFile) { return function (done) { var resFile = jarFile.replace(/\.jar$/, '.res.zip'), resPkgFile = jarFile.replace(/\.jar$/, '.respackage'); if (fs.existsSync(resPkgFile) && fs.existsSync(resFile)) { this.resPackages[resFile] = fs.readFileSync(resPkgFile).toString().split('\n').shift().trim(); return done(); } if (!fs.existsSync(jarFile) || !fs.existsSync(resFile)) return done(); this.logger.info(__('Extracting module resources: %s', resFile.cyan)); var tmp = temp.path(); fs.existsSync(tmp) && wrench.rmdirSyncRecursive(tmp); wrench.mkdirSyncRecursive(tmp); appc.zip.unzip(resFile, tmp, {}, function (ex) { if (ex) { this.logger.error(__('Failed to extract module resource zip: %s', resFile.cyan) + '\n'); process.exit(1); } // copy the files from the temp folder into the build dir copy(tmp, this.buildDir); done(); }.bind(this)); }; }); this.nativeLibModules.forEach(function (m) { var src = path.join(m.modulePath, 'assets'); if (fs.existsSync(src)) { tasks.push(function (done) { copy(src, this.buildBinAssetsResourcesDir); done(); }.bind(this)); } }, this); // for each jar library, if it has a companion resource zip file, extract // all of its files into the build dir, and yes, this is stupidly dangerous appc.async.series(this, tasks, next); }; AndroidBuilder.prototype.removeOldFiles = function removeOldFiles(next) { Object.keys(this.lastBuildFiles).forEach(function (file) { if (path.dirname(file) == this.buildDir || file.indexOf(this.buildAssetsDir) == 0 || file.indexOf(this.buildBinAssetsResourcesDir) == 0 || (this.forceRebuild && file.indexOf(this.buildGenAppIdDir) == 0) || file.indexOf(this.buildResDir) == 0) { if (fs.existsSync(file)) { this.logger.debug(__('Removing old file: %s', file.cyan)); fs.unlinkSync(file); } else { // maybe it's a symlink? try { if (fs.lstatSync(file)) { this.logger.debug(__('Removing old symlink: %s', file.cyan)); fs.unlinkSync(file); } } catch (e) {} } } }, this); next(); }; AndroidBuilder.prototype.generateJavaFiles = function generateJavaFiles(next) { if (!this.forceRebuild) return next(); var android = this.tiapp.android, copyTemplate = function (src, dest) { if (this.forceRebuild || !fs.existsSync(dest)) { this.logger.debug(__('Copying template %s => %s', src.cyan, dest.cyan)); fs.writeFileSync(dest, ejs.render(fs.readFileSync(src).toString(), this)); } }.bind(this); // copy and populate templates copyTemplate(path.join(this.templatesDir, 'AppInfo.java'), path.join(this.buildGenAppIdDir, this.classname + 'AppInfo.java')); copyTemplate(path.join(this.templatesDir, 'App.java'), path.join(this.buildGenAppIdDir, this.classname + 'Application.java')); copyTemplate(path.join(this.templatesDir, 'Activity.java'), path.join(this.buildGenAppIdDir, this.classname + 'Activity.java')); copyTemplate(path.join(this.templatesDir, 'project'), path.join(this.buildDir, '.project')); copyTemplate(path.join(this.templatesDir, 'default.properties'), path.join(this.buildDir, 'default.properties')); afs.copyFileSync(path.join(this.templatesDir, 'gitignore'), path.join(this.buildDir, '.gitignore'), { logger: this.logger.debug }); afs.copyFileSync(path.join(this.templatesDir, 'classpath'), path.join(this.buildDir, '.classpath'), { logger: this.logger.debug }); // generate the JavaScript-based activities if (android && android.activities) { var activityTemplate = fs.readFileSync(path.join(this.templatesDir, 'JSActivity.java')).toString(); Object.keys(android.activities).forEach(function (name) { var activity = android.activities[name]; this.logger.debug(__('Generating activity class: %s', activity.classname.cyan)); fs.writeFileSync(path.join(this.buildGenAppIdDir, activity.classname + '.java'), ejs.render(activityTemplate, { appid: this.appid, activity: activity })); }, this); } // generate the JavaScript-based services if (android && android.services) { var serviceTemplate = fs.readFileSync(path.join(this.templatesDir, 'JSService.java')).toString(), intervalServiceTemplate = fs.readFileSync(path.join(this.templatesDir, 'JSIntervalService.java')).toString(); Object.keys(android.services).forEach(function (name) { var service = android.services[name], tpl = serviceTemplate; if (service.type == 'interval') { tpl = intervalServiceTemplate; this.logger.debug(__('Generating interval service class: %s', service.classname.cyan)); } else { this.logger.debug(__('Generating service class: %s', service.classname.cyan)); } fs.writeFileSync(path.join(this.buildGenAppIdDir, service.classname + '.java'), ejs.render(tpl, { appid: this.appid, service: service })); }, this); } next(); }; AndroidBuilder.prototype.writeXmlFile = function writeXmlFile(srcOrDoc, dest) { var filename = path.basename(dest), destExists = fs.existsSync(dest), destDir = path.dirname(dest), srcDoc = typeof srcOrDoc == 'string' ? (new DOMParser({ errorHandler: function(){} }).parseFromString(fs.readFileSync(srcOrDoc).toString(), 'text/xml')).documentElement : srcOrDoc, destDoc, dom = new DOMParser().parseFromString('<resources/>', 'text/xml'), root = dom.documentElement, nodes = {}, _t = this, byName = function (node) { var n = xml.getAttr(node, 'name'); if (n) { if (nodes[n] && n !== 'app_name') { _t.logger.warn(__('Overwriting XML node %s in file %s', String(n).cyan, dest.cyan)); } nodes[n] = node; } }, byTagAndName = function (node) { var n = xml.getAttr(node, 'name'); if (n) { nodes[node.tagName] || (nodes[node.tagName] = {}); if (nodes[node.tagName][n] && n !== 'app_name') { _t.logger.warn(__('Overwriting XML node %s in file %s', String(n).cyan, dest.cyan)); } nodes[node.tagName][n] = node; } }; if (destExists) { // we're merging destDoc = (new DOMParser({ errorHandler: function(){} }).parseFromString(fs.readFileSync(dest).toString(), 'text/xml')).documentElement; xml.forEachAttr(destDoc, function (attr) { root.setAttribute(attr.name, attr.value); }); if (typeof srcOrDoc == 'string') { this.logger.debug(__('Merging %s => %s', srcOrDoc.cyan, dest.cyan)); } } else { // copy the file, but make sure there are no dupes if (typeof srcOrDoc == 'string') { this.logger.debug(__('Copying %s => %s', srcOrDoc.cyan, dest.cyan)); } } xml.forEachAttr(srcDoc, function (attr) { root.setAttribute(attr.name, attr.value); }); switch (filename) { case 'arrays.xml': case 'attrs.xml': case 'bools.xml': case 'colors.xml': case 'dimens.xml': case 'ids.xml': case 'integers.xml': case 'strings.xml': destDoc && xml.forEachElement(destDoc, byName); xml.forEachElement(srcDoc, byName); Object.keys(nodes).forEach(function (name) { root.appendChild(dom.createTextNode('\n\t')); if (filename == 'strings.xml') { nodes[name].setAttribute('formatted', 'false'); } root.appendChild(nodes[name]); }); break; case 'styles.xml': destDoc && xml.forEachElement(destDoc, byTagAndName); xml.forEachElement(srcDoc, byTagAndName); Object.keys(nodes).forEach(function (tag) { Object.keys(nodes[tag]).forEach(function (name) { root.appendChild(dom.createTextNode('\n\t')); root.appendChild(nodes[tag][name]); }); }); break; } root.appendChild(dom.createTextNode('\n')); fs.existsSync(destDir) || wrench.mkdirSyncRecursive(destDir); destExists && fs.unlinkSync(dest); fs.writeFileSync(dest, '<?xml version="1.0" encoding="UTF-8"?>\n' + dom.documentElement.toString()); }; AndroidBuilder.prototype.generateAidl = function generateAidl(next) { if (!this.forceRebuild) return next(); if (!this.androidTargetSDK.aidl) { this.logger.info(__('Android SDK %s missing framework aidl, skipping', this.androidTargetSDK['api-level'])); return next(); } var aidlRegExp = /\.aidl$/, files = (function scan(dir) { var f = []; fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { f = f.concat(scan(file)); } else if (aidlRegExp.test(name)) { f.push(file); } } }); return f; }(this.buildSrcDir)); if (!files.length) { this.logger.info(__('No aidl files to compile, continuing')); return next(); } appc.async.series(this, files.map(function (file) { return function (callback) { this.logger.info(__('Compiling aidl file: %s', file)); var aidlHook = this.cli.createHook('build.android.aidl', this, function (exe, args, opts, done) { this.logger.info('Running aidl: %s', (exe + ' "' + args.join('" "') + '"').cyan); appc.subprocess.run(exe, args, opts, done); }); aidlHook( this.androidInfo.sdk.executables.aidl, ['-p' + this.androidTargetSDK.aidl, '-I' + this.buildSrcDir, '-o' + this.buildGenAppIdDir, file], {}, callback ); }; }), next); }; AndroidBuilder.prototype.generateI18N = function generateI18N(next) { this.logger.info(__('Generating i18n files')); var data = i18n.load(this.projectDir, this.logger, { ignoreDirs: this.ignoreDirs, ignoreFiles: this.ignoreFiles }), badStringNames = {}; data.en || (data.en = {}); data.en.app || (data.en.app = {}); data.en.app.appname || (data.en.app.appname = this.tiapp.name); function replaceSpaces(s) { return s.replace(/./g, '\\u0020'); } function resolveRegionName(locale) { if (locale.match(/\w{2}(-|_)r?\w{2}/)) { var parts = locale.split(/-|_/), lang = parts[0], region = parts[1], separator = '-'; if (region.length == 2) { separator = '-r'; } return lang + separator + region; } return locale; } Object.keys(data).forEach(function (locale) { var dest = path.join(this.buildResDir, 'values' + (locale == 'en' ? '' : '-' + resolveRegionName(locale)), 'strings.xml'), dom = new DOMParser().parseFromString('<resources/>', 'text/xml'), root = dom.documentElement, appname = data[locale].app && data[locale].app.appname || this.tiapp.name, appnameNode = dom.createElement('string'); appnameNode.setAttribute('name', 'app_name'); appnameNode.setAttribute('formatted', 'false'); appnameNode.appendChild(dom.createTextNode(appname)); root.appendChild(dom.createTextNode('\n\t')); root.appendChild(appnameNode); data[locale].strings && Object.keys(data[locale].strings).forEach(function (name) { if (name.indexOf(' ') != -1) { badStringNames[locale] || (badStringNames[locale] = []); badStringNames[locale].push(name); } else if (name != 'appname') { var node = dom.createElement('string'); node.setAttribute('name', name); node.setAttribute('formatted', 'false'); node.appendChild(dom.createTextNode(data[locale].strings[name].replace(/\\?'/g, "\\'").replace(/^\s+/g, replaceSpaces).replace(/\s+$/g, replaceSpaces))); root.appendChild(dom.createTextNode('\n\t')); root.appendChild(node); } }); root.appendChild(dom.createTextNode('\n')); if (fs.existsSync(dest)) { this.logger.debug(__('Merging %s strings => %s', locale.cyan, dest.cyan)); } else { this.logger.debug(__('Writing %s strings => %s', locale.cyan, dest.cyan)); } this.writeXmlFile(dom.documentElement, dest); }, this); if (Object.keys(badStringNames).length) { this.logger.error(__('Found invalid i18n string names:')); Object.keys(badStringNames).forEach(function (locale) { badStringNames[locale].forEach(function (s) { this.logger.error(' "' + s + '" (' + locale + ')'); }, this); }, this); this.logger.error(__('Android does not allow i18n string names with spaces.')); if (!this.config.get('android.excludeInvalidI18nStrings', false)) { this.logger.error(__('To exclude invalid i18n strings from the build, run:')); this.logger.error(' ' + this.cli.argv.$ + ' config android.excludeInvalidI18nStrings true'); this.logger.log(); process.exit(1); } } next(); }; AndroidBuilder.prototype.generateTheme = function generateTheme(next) { var themeFile = path.join(this.buildResDir, 'values', 'theme.xml'); if (!fs.existsSync(themeFile)) { this.logger.info(__('Generating %s', themeFile.cyan)); var flags = 'Theme.AppCompat'; if (this.tiapp.fullscreen || this.tiapp['statusbar-hidden']) { flags += '.Fullscreen'; } fs.writeFileSync(themeFile, ejs.render(fs.readFileSync(path.join(this.templatesDir, 'theme.xml')).toString(), { flags: flags })); } next(); }; AndroidBuilder.prototype.generateAndroidManifest = function generateAndroidManifest(next) { if (!this.forceRebuild && fs.existsSync(this.androidManifestFile)) { return next(); } var calendarPermissions = [ 'android.permission.READ_CALENDAR', 'android.permission.WRITE_CALENDAR' ], cameraPermissions = [ 'android.permission.CAMERA' ], contactsPermissions = [ 'android.permission.READ_CONTACTS', 'android.permission.WRITE_CONTACTS' ], contactsReadPermissions = [ 'android.permission.READ_CONTACTS' ], geoPermissions = [ 'android.permission.ACCESS_COARSE_LOCATION', 'android.permission.ACCESS_FINE_LOCATION' ], vibratePermissions = [ 'android.permission.VIBRATE' ], wallpaperPermissions = [ 'android.permission.SET_WALLPAPER' ], permissions = { 'android.permission.INTERNET': 1, 'android.permission.ACCESS_WIFI_STATE': 1, 'android.permission.ACCESS_NETWORK_STATE': 1, 'android.permission.WRITE_EXTERNAL_STORAGE': 1 }, tiNamespacePermissions = { 'geolocation': geoPermissions }, tiMethodPermissions = { // old calendar 'Android.Calendar.getAllAlerts': calendarPermissions, 'Android.Calendar.getAllCalendars': calendarPermissions, 'Android.Calendar.getCalendarById': calendarPermissions, 'Android.Calendar.getSelectableCalendars': calendarPermissions, // new calendar 'Calendar.getAllAlerts': calendarPermissions, 'Calendar.getAllCalendars': calendarPermissions, 'Calendar.getCalendarById': calendarPermissions, 'Calendar.getSelectableCalendars': calendarPermissions, 'Contacts.createPerson': contactsPermissions, 'Contacts.removePerson': contactsPermissions, 'Contacts.getAllContacts': contactsReadPermissions, 'Contacts.showContactPicker': contactsReadPermissions, 'Contacts.showContacts': contactsReadPermissions, 'Contacts.getPersonByID': contactsReadPermissions, 'Contacts.getPeopleWithName': contactsReadPermissions, 'Contacts.getAllPeople': contactsReadPermissions, 'Contacts.getAllGroups': contactsReadPermissions, 'Contacts.getGroupByID': contactsReadPermissions, 'Map.createView': geoPermissions, 'Media.Android.setSystemWallpaper': wallpaperPermissions, 'Media.showCamera': cameraPermissions, 'Media.vibrate': vibratePermissions, }, tiMethodActivities = { 'Map.createView': { 'activity': { 'name': 'ti.modules.titanium.map.TiMapActivity', 'configChanges': ['keyboardHidden', 'orientation'], 'launchMode': 'singleTask' }, 'uses-library': { 'name': 'com.google.android.maps' } }, 'Media.createVideoPlayer': { 'activity': { 'name': 'ti.modules.titanium.media.TiVideoActivity', 'configChanges': ['keyboardHidden', 'orientation'], 'theme': '@style/Theme.AppCompat.Fullscreen', 'launchMode': 'singleTask' } }, 'Media.showCamera': { 'activity': { 'name': 'ti.modules.titanium.media.TiCameraActivity', 'configChanges': ['keyboardHidden', 'orientation'], 'theme': '@style/Theme.AppCompat.Translucent.NoTitleBar.Fullscreen' } } }, googleAPIs = [ 'Map.createView' ], enableGoogleAPIWarning = this.target == 'emulator' && this.emulator && !this.emulator.googleApis, fill = function (str) { // first we replace all legacy variable placeholders with EJS style placeholders str = str.replace(/(\$\{tiapp\.properties\[['"]([^'"]+)['"]\]\})/g, function (s, m1, m2) { // if the property is the "id", we want to force our scrubbed "appid" if (m2 == 'id') { m2 = 'appid'; } else { m2 = 'tiapp.' + m2; } return '<%- ' + m2 + ' %>'; }); // then process the string as an EJS template return ejs.render(str, this); }.bind(this), finalAndroidManifest = (new AndroidManifest).parse(fill(fs.readFileSync(path.join(this.templatesDir, 'AndroidManifest.xml')).toString())), customAndroidManifest = this.customAndroidManifest, tiappAndroidManifest = this.tiappAndroidManifest; // if they are using a custom AndroidManifest and merging is disabled, then write the custom one as is if (!this.config.get('android.mergeCustomAndroidManifest', false) && this.customAndroidManifest) { (this.cli.createHook('build.android.writeAndroidManifest', this, function (file, xml, done) { this.logger.info(__('Writing unmerged custom AndroidManifest.xml')); fs.writeFileSync(file, xml.toString('xml')); done(); }))(this.androidManifestFile, customAndroidManifest, next); return; } finalAndroidManifest.__attr__['android:versionName'] = this.tiapp.version || '1'; if (this.deployType != 'production') { // enable mock location if in development or test mode geoPermissions.push('android.permission.ACCESS_MOCK_LOCATION'); } // set permissions for each titanium namespace found Object.keys(this.tiNamespaces).forEach(function (ns) { if (tiNamespacePermissions[ns]) { tiNamespacePermissions[ns].forEach(function (perm) { permissions[perm] = 1; }); } }, this); // set permissions for each titanium method found var tmp = {}; Object.keys(this.tiSymbols).forEach(function (file) { this.tiSymbols[file].forEach(function (symbol) { if (tmp[symbol]) return; tmp[symbol] = 1; if (tiMethodPermissions[symbol]) { tiMethodPermissions[symbol].forEach(function (perm) { permissions[perm] = 1; }); } var obj = tiMethodActivities[symbol]; if (obj) { if (obj.activity) { finalAndroidManifest.application.activity || (finalAndroidManifest.application.activity = {}); finalAndroidManifest.application.activity[obj.activity.name] = obj.activity; } if (obj['uses-library']) { finalAndroidManifest.application['uses-library'] || (finalAndroidManifest.application['uses-library'] = {}); finalAndroidManifest.application['uses-library'][obj['uses-library'].name] = obj['uses-library']; } } if (enableGoogleAPIWarning && googleAPIs.indexOf(symbol) != -1) { var fn = 'Titanium.' + symbol + '()'; if (this.emulator.googleApis === null) { this.logger.warn(__('Detected %s call which requires Google APIs, however the selected emulator %s may or may not support Google APIs', fn.cyan, ('"' + this.emulator.name + '"').cyan)); this.logger.warn(__('If the emulator does not support Google APIs, the %s call will fail', fn.cyan)); } else { this.logger.warn(__('Detected %s call which requires Google APIs, but the selected emulator %s does not support Google APIs', fn.cyan, ('"' + this.emulator.name + '"').cyan)); this.logger.warn(__('Expect the %s call to fail', fn.cyan)); } this.logger.warn(__('You should use, or create, an Android emulator that does support Google APIs')); } }, this); }, this); // gather activities var tiappActivities = this.tiapp.android && this.tiapp.android.activities; tiappActivities && Object.keys(tiappActivities).forEach(function (filename) { var activity = tiappActivities[filename]; if (activity.url) { var a = { name: this.appid + '.' + activity.classname }; Object.keys(activity).forEach(function (key) { if (!/^(name|url|options|classname|android\:name)$/.test(key)) { a[key.replace(/^android\:/, '')] = activity[key]; } }); a.configChanges || (a.configChanges = ['keyboardHidden', 'orientation']); finalAndroidManifest.application.activity || (finalAndroidManifest.application.activity = {}); finalAndroidManifest.application.activity[a.name] = a; } }, this); // gather services var tiappServices = this.tiapp.android && this.tiapp.android.services; tiappServices && Object.keys(tiappServices).forEach(function (filename) { var service = tiappServices[filename]; if (service.url) { var s = { 'name': this.appid + '.' + service.classname }; Object.keys(service).forEach(function (key) { if (!/^(type|name|url|options|classname|android\:name)$/.test(key)) { s[key.replace(/^android\:/, '')] = service[key]; } }); finalAndroidManifest.application.service || (finalAndroidManifest.application.service = {}); finalAndroidManifest.application.service[s.name] = s; } }, this); // add the analytics service if (this.tiapp.analytics) { var tiAnalyticsService = 'com.appcelerator.aps.APSAnalyticsService'; finalAndroidManifest.application.service || (finalAndroidManifest.application.service = {}); finalAndroidManifest.application.service[tiAnalyticsService] = { name: tiAnalyticsService, exported: false }; } // set the app icon finalAndroidManifest.application.icon = '@drawable/' + this.tiapp.icon.replace(/((\.9)?\.(png|jpg))$/, ''); // merge the custom android manifest finalAndroidManifest.merge(customAndroidManifest); // merge the tiapp.xml android manifest finalAndroidManifest.merge(tiappAndroidManifest); this.modules.forEach(function (module) { var moduleXmlFile = path.join(module.modulePath, 'timodule.xml'); if (fs.existsSync(moduleXmlFile)) { var moduleXml = new tiappxml(moduleXmlFile); if (moduleXml.android && moduleXml.android.manifest) { var am = new AndroidManifest; am.parse(fill(moduleXml.android.manifest)); // we don't want modules to override the <supports-screens> or <uses-sdk> tags delete am.__attr__; delete am['supports-screens']; delete am['uses-sdk']; finalAndroidManifest.merge(am); } // point to the .jar file if the timodule.xml file has properties of 'dexAgent' if (moduleXml.properties && moduleXml.properties['dexAgent']) { this.dexAgent = path.join(module.modulePath, moduleXml.properties['dexAgent'].value); } } }, this); // if the target sdk is Android 3.2 or newer, then we need to add 'screenSize' to // the default AndroidManifest.xml's 'configChanges' attribute for all <activity> // elements, otherwise changes in orientation will cause the app to restart if (this.realTargetSDK >= 13) { Object.keys(finalAndroidManifest.application.activity).forEach(function (name) { var activity = finalAndroidManifest.application.activity[name]; if (!activity.configChanges) { activity.configChanges = ['screenSize']; } else if (activity.configChanges.indexOf('screenSize') == -1) { activity.configChanges.push('screenSize'); } }); } // add permissions Array.isArray(finalAndroidManifest['uses-permission']) || (finalAndroidManifest['uses-permission'] = []); Object.keys(permissions).forEach(function (perm) { finalAndroidManifest['uses-permission'].indexOf(perm) == -1 && finalAndroidManifest['uses-permission'].push(perm); }); // if the AndroidManifest.xml already exists, remove it so that we aren't updating the original file (if it's symlinked) fs.existsSync(this.androidManifestFile) && fs.unlinkSync(this.androidManifestFile); (this.cli.createHook('build.android.writeAndroidManifest', this, function (file, xml, done) { fs.writeFileSync(file, xml.toString('xml')); done(); }))(this.androidManifestFile, finalAndroidManifest, next); }; AndroidBuilder.prototype.packageApp = function packageApp(next) { this.ap_File = path.join(this.buildBinDir, 'app.ap_'); var aaptHook = this.cli.createHook('build.android.aapt', this, function (exe, args, opts, done) { this.logger.info(__('Packaging application: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to package application:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } // check that the R.java file exists var rFile = path.join(this.buildGenAppIdDir, 'R.java'); if (!fs.existsSync(rFile)) { this.logger.error(__('Unable to find generated R.java file') + '\n'); process.exit(1); } done(); }.bind(this)); }), args = [ 'package', '-f', '-m', '-J', path.join(this.buildDir, 'gen'), '-M', this.androidManifestFile, '-A', this.buildBinAssetsDir, '-S', this.buildResDir, '-I', this.androidTargetSDK.androidJar, '-F', this.ap_File ]; function runAapt() { aaptHook( this.androidInfo.sdk.executables.aapt, args, {}, next ); } if ( (!Object.keys(this.resPackages).length) && (!this.moduleResPackages.length) ) { return runAapt(); } args.push('--auto-add-overlay'); var namespaces = ''; Object.keys(this.resPackages).forEach(function(resFile){ namespaces && (namespaces+=':'); namespaces += this.resPackages[resFile]; }, this); this.moduleResPackages.forEach(function (data) { namespaces && (namespaces+=':'); namespaces += data; }, this); args.push('--extra-packages', namespaces); appc.async.series(this, Object.keys(this.resPackages).map(function (resFile) { return function (cb) { var namespace = this.resPackages[resFile], tmp = temp.path(); appc.zip.unzip(resFile, tmp, {}, function (ex) { if (ex) { this.logger.error(__('Failed to extract module resource zip: %s', resFile.cyan) + '\n'); process.exit(1); } args.push('-S', tmp+'/res'); cb(); }.bind(this)); }; }), runAapt); }; AndroidBuilder.prototype.compileJavaClasses = function compileJavaClasses(next) { var classpath = {}, moduleJars = this.moduleJars = {}, jarNames = {}; classpath[this.androidTargetSDK.androidJar] = 1; Object.keys(this.jarLibraries).map(function (jarFile) { classpath[jarFile] = 1; }); this.modules.forEach(function (module) { if (fs.existsSync(module.jarFile)) { var jarHash = this.hash(fs.readFileSync(module.jarFile).toString()); if (!jarNames[jarHash]) { moduleJars[module.jarFile] = 1; classpath[module.jarFile] = 1; jarNames[jarHash] = 1; } else { this.logger.debug(__('Skipping duplicate jar file: %s', module.jarFile.cyan)); } var libDir = path.join(module.modulePath, 'lib'), jarRegExp = /\.jar$/; fs.existsSync(libDir) && fs.readdirSync(libDir).forEach(function (name) { var jarFile = path.join(libDir, name); if (jarRegExp.test(name) && fs.existsSync(jarFile)) { var jarHash = this.hash(fs.readFileSync(jarFile).toString()); if (!jarNames[jarHash]) { moduleJars[jarFile] = 1; classpath[jarFile] = 1; jarNames[jarHash] = 1; } else { this.logger.debug(__('Skipping duplicate jar file: %s', jarFile.cyan)); } } }, this); } }, this); if (!this.forceRebuild) { // if we don't have to compile the java files, then we can return here // we just needed the moduleJars return next(); } if (Object.keys(moduleJars).length) { // we need to include kroll-apt.jar if there are any modules classpath[path.join(this.platformPath, 'kroll-apt.jar')] = 1; } classpath[path.join(this.platformPath, 'lib', 'titanium-verify.jar')] = 1; if (this.allowDebugging && this.debugPort) { classpath[path.join(this.platformPath, 'lib', 'titanium-debug.jar')] = 1; } if (this.allowProfiling && this.profilerPort) { classpath[path.join(this.platformPath, 'lib', 'titanium-profiler.jar')] = 1; } // find all java files and write them to the temp file var javaFiles = [], javaRegExp = /\.java$/, javaSourcesFile = path.join(this.buildDir, 'java-sources.txt'); [this.buildGenDir, this.buildSrcDir].forEach(function scanJavaFiles(dir) { fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { scanJavaFiles(file); } else if (javaRegExp.test(name)) { javaFiles.push(file); classpath[name.replace(javaRegExp, '.class')] = 1; } } }); }); fs.writeFileSync(javaSourcesFile, '"' + javaFiles.join('"\n"').replace(/\\/g, '/') + '"'); // if we're recompiling the java files, then nuke the classes dir if (fs.existsSync(this.buildBinClassesDir)) { wrench.rmdirSyncRecursive(this.buildBinClassesDir); } wrench.mkdirSyncRecursive(this.buildBinClassesDir); var javacHook = this.cli.createHook('build.android.javac', this, function (exe, args, opts, done) { this.logger.info(__('Building Java source files: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to compile Java source files:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }); javacHook( this.jdkInfo.executables.javac, [ '-J-Xmx' + this.javacMaxMemory, '-encoding', 'utf8', '-bootclasspath', Object.keys(classpath).join(process.platform == 'win32' ? ';' : ':'), '-d', this.buildBinClassesDir, '-proc:none', '-target', this.javacTarget, '-source', this.javacSource, '@' + javaSourcesFile ], {}, next ); }; AndroidBuilder.prototype.runProguard = function runProguard(next) { if (!this.forceRebuild || !this.proguard) return next(); // check that the proguard config exists var proguardConfigFile = path.join(this.buildDir, 'proguard.cfg'), proguardHook = this.cli.createHook('build.android.proguard', this, function (exe, args, opts, done) { this.logger.info(__('Running ProGuard: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to run ProGuard')); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }); proguardHook( this.jdkInfo.executables.java, ['-jar', this.androidInfo.sdk.proguard, '@' + proguardConfigFile], { cwd: this.buildDir }, next ); }; AndroidBuilder.prototype.runDexer = function runDexer(next) { if (!this.forceRebuild && fs.existsSync(this.buildBinClassesDex)) return next(); var dexerHook = this.cli.createHook('build.android.dexer', this, function (exe, args, opts, done) { this.logger.info(__('Running dexer: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to run dexer:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }), injars = [ this.buildBinClassesDir, path.join(this.platformPath, 'lib', 'titanium-verify.jar') ].concat(Object.keys(this.moduleJars)).concat(Object.keys(this.jarLibraries)), dexArgs = [ '-Xmx' + this.dxMaxMemory, '-XX:-UseGCOverheadLimit', '-Djava.ext.dirs=' + this.androidInfo.sdk.platformTools.path, '-jar', this.androidInfo.sdk.dx, '--dex', '--multi-dex', '--output=' + this.buildBinClassesDex, ], shrinkedAndroid = path.join(path.dirname(this.androidInfo.sdk.dx), 'shrinkedAndroid.jar'), baserules = path.join(path.dirname(this.androidInfo.sdk.dx), '..', 'mainDexClasses.rules'), outjar = path.join(this.buildDir, 'mainDexClasses.jar'); // inserts the -javaagent arg earlier on in the dexArgs to allow for proper dexing if // dexAgent is set in the module's timodule.xml if (this.dexAgent) { dexArgs.unshift('-javaagent:' + this.dexAgent); } if (this.allowDebugging && this.debugPort) { injars.push(path.join(this.platformPath, 'lib', 'titanium-debug.jar')); } if (this.allowProfiling && this.profilerPort) { injars.push(path.join(this.platformPath, 'lib', 'titanium-profiler.jar')); } // nuke and create the folder holding all the classes*.dex files if (fs.existsSync(this.buildBinClassesDex)) { wrench.rmdirSyncRecursive(this.buildBinClassesDex); } wrench.mkdirSyncRecursive(this.buildBinClassesDex); // Wipe existing outjar fs.existsSync(outjar) && fs.unlinkSync(outjar); // We need to hack multidex for APi level < 21 to generate the list of classes that *need* to go into the first dex file // We skip these intermediate steps if 21+ and eventually just run dexer async.series([ // Run: java -jar $this.androidInfo.sdk.proguard -injars "${@}" -dontwarn -forceprocessing -outjars ${tmpOut} -libraryjars "${shrinkedAndroidJar}" -dontoptimize -dontobfuscate -dontpreverify -include "${baserules}" function (done) { // 'api-level' and 'sdk' properties both seem to hold apiLevel if (this.androidTargetSDK.sdk >= 21) { return done(); } appc.subprocess.run(this.jdkInfo.executables.java, [ '-jar', this.androidInfo.sdk.proguard, '-injars', injars.join(':'), '-dontwarn', '-forceprocessing', '-outjars', outjar, '-libraryjars', shrinkedAndroid, '-dontoptimize', '-dontobfuscate', '-dontpreverify', '-include', baserules ], {}, function (code, out, err) { if (code) { this.logger.error(__('Failed to run dexer:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }.bind(this), // Run: java -cp $this.androidInfo.sdk.dx com.android.multidex.MainDexListBuilder "$outjar" "$injars" function (done) { // 'api-level' and 'sdk' properties both seem to hold apiLevel if (this.androidTargetSDK.sdk >= 21) { return done(); } appc.subprocess.run(this.jdkInfo.executables.java, ['-cp', this.androidInfo.sdk.dx, 'com.android.multidex.MainDexListBuilder', outjar, injars.join(':')], {}, function (code, out, err) { var mainDexClassesList = path.join(this.buildDir, 'main-dex-classes.txt'); if (code) { this.logger.error(__('Failed to run dexer:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } // Record output to a file like main-dex-classes.txt fs.writeFileSync(mainDexClassesList, out); // Pass that file into dex, like so: dexArgs.push('--main-dex-list'); dexArgs.push(mainDexClassesList); done(); }.bind(this)); }.bind(this), function (done) { dexArgs = dexArgs.concat(injars); dexerHook(this.jdkInfo.executables.java, dexArgs, {}, done); }.bind(this) ], next); }; AndroidBuilder.prototype.createUnsignedApk = function createUnsignedApk(next) { var dest = archiver('zip', { forceUTC: true }), apkStream, jsonRegExp = /\.json$/, javaRegExp = /\.java$/, classRegExp = /\.class$/, dexRegExp = /^classes(\d+)?\.dex$/, soRegExp = /\.so$/, trailingSlashRegExp = /\/$/, nativeLibs = {}, origConsoleError = console.error; // since the archiver library didn't set max listeners, we squelch all error output console.error = function () {}; try { fs.existsSync(this.unsignedApkFile) && fs.unlinkSync(this.unsignedApkFile); apkStream = fs.createWriteStream(this.unsignedApkFile); apkStream.on('close', function() { console.error = origConsoleError; next(); }); dest.catchEarlyExitAttached = true; // silence exceptions dest.pipe(apkStream); this.logger.info(__('Creating unsigned apk')); // merge files from the app.ap_ file as well as all titanium and 3rd party jar files var archives = [ this.ap_File ].concat(Object.keys(this.moduleJars)).concat(Object.keys(this.jarLibraries)); archives.forEach(function (file) { var src = new AdmZip(file), entries = src.getEntries(); this.logger.debug(__('Processing %s', file.cyan)); entries.forEach(function (entry) { if (entry.entryName.indexOf('META-INF/') == -1 && (entry.entryName.indexOf('org/appcelerator/titanium/bindings/') == -1 || !jsonRegExp.test(entry.name)) && entry.name.charAt(0) != '.' && !classRegExp.test(entry.name) && !trailingSlashRegExp.test(entry.entryName) ) { var store = this.uncompressedTypes.indexOf(entry.entryName.split('.').pop()) != -1; this.logger.debug(store ? __('Adding %s', entry.entryName.cyan) : __('Deflating %s', entry.entryName.cyan)); dest.append(src.readFile(entry), { name: entry.entryName, store: store }); } }, this); }, this); // Add dex files this.logger.info(__('Processing %s', this.buildBinClassesDex.cyan)); fs.readdirSync(this.buildBinClassesDex).forEach(function (name) { var file = path.join(this.buildBinClassesDex, name); if (dexRegExp.test(name)) { this.logger.debug(__('Adding %s', name.cyan)); dest.append(fs.createReadStream(file), { name: name }); } }, this); this.logger.info(__('Processing %s', this.buildSrcDir.cyan)); (function copyDir(dir, base) { base = base || dir; fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { copyDir(file, base); } else if (!javaRegExp.test(name)) { name = file.replace(base, '').replace(/^[\/\\]/, ''); this.logger.debug(__('Adding %s', name.cyan)); dest.append(fs.createReadStream(file), { name: name }); } } }, this); }.call(this, this.buildSrcDir)); var addNativeLibs = function (dir) { if (!fs.existsSync(dir)) return; for (var i = 0; i < this.abis.length; i++) { var abiDir = path.join(dir, this.abis[i]); // check that we found the desired abi, otherwise we abort the build if (!fs.existsSync(abiDir) || !fs.statSync(abiDir).isDirectory()) { throw this.abis[i]; } // copy all the .so files into the archive fs.readdirSync(abiDir).forEach(function (name) { if (name != 'libtiprofiler.so' || (this.allowProfiling && this.profilerPort)) { var file = path.join(abiDir, name), rel = 'lib/' + this.abis[i] + '/' + name; if (!nativeLibs[rel] && soRegExp.test(name) && fs.existsSync(file)) { nativeLibs[rel] = 1; this.logger.debug(__('Adding %s', rel.cyan)); dest.append(fs.createReadStream(file), { name: rel }); } } }, this); } }.bind(this); try { // add Titanium native modules addNativeLibs(path.join(this.platformPath, 'native', 'libs')); } catch (abi) { // this should never be called since we already validated this var abis = []; fs.readdirSync(path.join(this.platformPath, 'native', 'libs')).forEach(function (abi) { var dir = path.join(this.platformPath, 'native', 'libs', abi); if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { abis.push(abi); } }); this.logger.error(__('Invalid native Titanium library ABI "%s"', abi)); this.logger.error(__('Supported ABIs: %s', abis.join(', ')) + '\n'); process.exit(1); } try { // add native modules from the build dir's "libs" dir addNativeLibs(path.join(this.buildDir, 'libs')); } catch (e) {} this.modules.forEach(function (m) { if (m.native) { try { // add native modules for each module addNativeLibs(path.join(m.modulePath, 'libs')); } catch (abi) { // this should never be called since we already validated this var abis = []; fs.readdirSync(path.join(m.modulePath, 'libs')).forEach(function (abi) { var dir = path.join(m.modulePath, 'libs', abi); if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { abis.push(abi); } }); /* commenting this out to preserve the old, incorrect behavior this.logger.error(__('The module "%s" does not support the ABI "%s"', m.id, abi)); this.logger.error(__('Supported ABIs: %s', abis.join(', ')) + '\n'); process.exit(1); */ this.logger.warn(__('The module %s does not support the ABI: %s', m.id.cyan, abi.cyan)); this.logger.warn(__('It only supports the following ABIs: %s', abis.map(function (a) { return a.cyan; }).join(', '))); this.logger.warn(__('Your application will most likely encounter issues')); } } }, this); this.logger.info(__('Writing unsigned apk: %s', this.unsignedApkFile.cyan)); dest.finalize(); } catch (ex) { console.error = origConsoleError; throw ex; } }; AndroidBuilder.prototype.createSignedApk = function createSignedApk(next) { var sigalg = this.keystoreAlias.sigalg || 'MD5withRSA', signerArgs = [ '-sigalg', sigalg, '-digestalg', 'SHA1', '-keystore', this.keystore, '-storepass', this.keystoreStorePassword ]; this.logger.info(__('Using %s signature algorithm', sigalg.cyan)); this.keystoreKeyPassword && signerArgs.push('-keypass', this.keystoreKeyPassword); signerArgs.push('-signedjar', this.apkFile, this.unsignedApkFile, this.keystoreAlias.name); var jarsignerHook = this.cli.createHook('build.android.jarsigner', this, function (exe, args, opts, done) { var safeArgs = []; for (var i = 0, l = args.length; i < l; i++) { safeArgs.push(args[i]); if (args[i] == '-storepass' || args[i] == 'keypass') { safeArgs.push(args[++i].replace(/./g, '*')); } } this.logger.info(__('Signing apk: %s', (exe + ' "' + safeArgs.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to sign apk:')); out.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }); jarsignerHook( this.jdkInfo.executables.jarsigner, signerArgs, {}, next ); }; AndroidBuilder.prototype.zipAlignApk = function zipAlignApk(next) { var zipAlignedApk = this.apkFile + 'z', zipalignHook = this.cli.createHook('build.android.zipalign', this, function (exe, args, opts, done) { this.logger.info(__('Aligning zip file: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to zipalign apk:')); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } fs.unlinkSync(this.apkFile); fs.renameSync(zipAlignedApk, this.apkFile); done(); }.bind(this)); }); zipalignHook( this.androidInfo.sdk.executables.zipalign, [ '-v', '4', // 4 byte alignment this.apkFile, zipAlignedApk ], {}, next ); }; AndroidBuilder.prototype.writeBuildManifest = function writeBuildManifest(callback) { this.logger.info(__('Writing build manifest: %s', this.buildManifestFile.cyan)); this.cli.createHook('build.android.writeBuildManifest', this, function (manifest, cb) { fs.existsSync(this.buildDir) || wrench.mkdirSyncRecursive(this.buildDir); fs.existsSync(this.buildManifestFile) && fs.unlinkSync(this.buildManifestFile); fs.writeFile(this.buildManifestFile, JSON.stringify(this.buildManifest = manifest, null, '\t'), cb); })({ target: this.target, deployType: this.deployType, classname: this.classname, platformPath: this.platformPath, modulesHash: this.modulesHash, modulesManifestHash: this.modulesManifestHash, modulesNativeHash: this.modulesNativeHash, modulesBindingsHash: this.modulesBindingsHash, gitHash: ti.manifest.githash, outputDir: this.cli.argv['output-dir'], name: this.tiapp.name, id: this.tiapp.id, analytics: this.tiapp.analytics, publisher: this.tiapp.publisher, url: this.tiapp.url, version: this.tiapp.version, description: this.tiapp.description, copyright: this.tiapp.copyright, guid: this.tiapp.guid, icon: this.tiapp.icon, fullscreen: this.tiapp.fullscreen, navbarHidden: this.tiapp['navbar-hidden'], skipJSMinification: !!this.cli.argv['skip-js-minify'], mergeCustomAndroidManifest: this.config.get('android.mergeCustomAndroidManifest', false), encryptJS: this.encryptJS, minSDK: this.minSDK, targetSDK: this.targetSDK, propertiesHash: this.propertiesHash, activitiesHash: this.activitiesHash, servicesHash: this.servicesHash, jarLibHash: this.jarLibHash }, callback); }; // create the builder instance and expose the public api (function (androidBuilder) { exports.config = androidBuilder.config.bind(androidBuilder); exports.validate = androidBuilder.validate.bind(androidBuilder); exports.run = androidBuilder.run.bind(androidBuilder); }(new AndroidBuilder(module)));
android/cli/commands/_build.js
/** * Android build command. * * @module cli/_build * * @copyright * Copyright (c) 2009-2015 by Appcelerator, Inc. All Rights Reserved. * * Copyright (c) 2012-2013 Chris Talkington, contributors. * {@link https://github.com/ctalkington/node-archiver} * * @license * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ var ADB = require('titanium-sdk/lib/adb'), AdmZip = require('adm-zip'), android = require('titanium-sdk/lib/android'), androidDetect = require('../lib/detect').detect, AndroidManifest = require('../lib/AndroidManifest'), appc = require('node-appc'), archiver = require('archiver'), async = require('async'), Builder = require('titanium-sdk/lib/builder'), CleanCSS = require('clean-css'), DOMParser = require('xmldom').DOMParser, ejs = require('ejs'), EmulatorManager = require('titanium-sdk/lib/emulator'), fields = require('fields'), fs = require('fs'), i18n = require('titanium-sdk/lib/i18n'), jsanalyze = require('titanium-sdk/lib/jsanalyze'), path = require('path'), temp = require('temp'), ti = require('titanium-sdk'), tiappxml = require('titanium-sdk/lib/tiappxml'), util = require('util'), wrench = require('wrench'), afs = appc.fs, i18nLib = appc.i18n(__dirname), __ = i18nLib.__, __n = i18nLib.__n, version = appc.version, xml = appc.xml; function AndroidBuilder() { Builder.apply(this, arguments); this.devices = null; // set by findTargetDevices() during 'config' phase this.devicesToAutoSelectFrom = []; this.keystoreAliases = []; this.tiSymbols = {}; this.dexAgent = false; this.minSupportedApiLevel = parseInt(this.packageJson.minSDKVersion); this.minTargetApiLevel = parseInt(version.parseMin(this.packageJson.vendorDependencies['android sdk'])); this.maxSupportedApiLevel = parseInt(version.parseMax(this.packageJson.vendorDependencies['android sdk'])); this.deployTypes = { 'emulator': 'development', 'device': 'test', 'dist-playstore': 'production' }; this.targets = ['emulator', 'device', 'dist-playstore']; this.validABIs = ['armeabi-v7a', 'x86']; this.xmlMergeRegExp = /^(strings|attrs|styles|bools|colors|dimens|ids|integers|arrays)\.xml$/; this.uncompressedTypes = [ 'jpg', 'jpeg', 'png', 'gif', 'wav', 'mp2', 'mp3', 'ogg', 'aac', 'mpg', 'mpeg', 'mid', 'midi', 'smf', 'jet', 'rtttl', 'imy', 'xmf', 'mp4', 'm4a', 'm4v', '3gp', '3gpp', '3g2', '3gpp2', 'amr', 'awb', 'wma', 'wmv' ]; } util.inherits(AndroidBuilder, Builder); AndroidBuilder.prototype.config = function config(logger, config, cli) { Builder.prototype.config.apply(this, arguments); var _t = this; function assertIssue(logger, issues, name) { var i = 0, len = issues.length; for (; i < len; i++) { if ((typeof name == 'string' && issues[i].id == name) || (typeof name == 'object' && name.test(issues[i].id))) { issues[i].message.split('\n').forEach(function (line) { logger[issues[i].type === 'error' ? 'error' : 'warn'](line.replace(/(__(.+?)__)/g, '$2'.bold)); }); logger.log(); if (issues[i].type === 'error') {process.exit(1);} } } } // we hook into the pre-validate event so that we can stop the build before // prompting if we know the build is going to fail. // // this is also where we can detect android and jdk environments before // prompting occurs. because detection is expensive we also do it here instead // of during config() because there's no sense detecting if config() is being // called because of the help command. cli.on('cli:pre-validate', function (obj, callback) { if (cli.argv.platform && cli.argv.platform != 'android') { return callback(); } async.series([ function (next) { // detect android environment androidDetect(config, { packageJson: _t.packageJson }, function (androidInfo) { _t.androidInfo = androidInfo; assertIssue(logger, androidInfo.issues, 'ANDROID_JDK_NOT_FOUND'); assertIssue(logger, androidInfo.issues, 'ANDROID_JDK_PATH_CONTAINS_AMPERSANDS'); assertIssue(logger, androidInfo.issues, 'ANDROID_BUILD_TOOLS_TOO_NEW'); if (!cli.argv.prompt) { // check that the Android SDK is found and sane // note: if we're prompting, then we'll do this check in the --android-sdk validate() callback assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_NOT_FOUND'); assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_MISSING_PROGRAMS'); // make sure we have an Android SDK and some Android targets if (!Object.keys(androidInfo.targets).filter(function (id) { var t = androidInfo.targets[id]; return t.type == 'platform' && t['api-level'] >= _t.minTargetApiLevel; }).length) { if (Object.keys(androidInfo.targets).length) { logger.error(__('No valid Android SDK targets found.')); } else { logger.error(__('No Android SDK targets found.')); } logger.error(__('Please download an Android SDK target API level %s or newer from the Android SDK Manager and try again.', _t.minTargetApiLevel) + '\n'); process.exit(1); } } // if --android-sdk was not specified, then we simply try to set a default android sdk if (!cli.argv['android-sdk']) { var androidSdkPath = config.android && config.android.sdkPath; if (!androidSdkPath && androidInfo.sdk) { androidSdkPath = androidInfo.sdk.path; } androidSdkPath && (cli.argv['android-sdk'] = afs.resolvePath(androidSdkPath)); } next(); }); }, function (next) { // detect java development kit appc.jdk.detect(config, null, function (jdkInfo) { assertIssue(logger, jdkInfo.issues, 'JDK_NOT_INSTALLED'); assertIssue(logger, jdkInfo.issues, 'JDK_MISSING_PROGRAMS'); assertIssue(logger, jdkInfo.issues, 'JDK_INVALID_JAVA_HOME'); if (!jdkInfo.version) { logger.error(__('Unable to locate the Java Development Kit') + '\n'); logger.log(__('You can specify the location by setting the %s environment variable.', 'JAVA_HOME'.cyan) + '\n'); process.exit(1); } if (!version.satisfies(jdkInfo.version, _t.packageJson.vendorDependencies.java)) { logger.error(__('JDK version %s detected, but only version %s is supported', jdkInfo.version, _t.packageJson.vendorDependencies.java) + '\n'); process.exit(1); } _t.jdkInfo = jdkInfo; next(); }); } ], callback); }); var targetDeviceCache = {}, findTargetDevices = function findTargetDevices(target, callback) { if (targetDeviceCache[target]) { return callback(null, targetDeviceCache[target]); } if (target == 'device') { new ADB(config).devices(function (err, devices) { if (err) { callback(err); } else { this.devices = devices.filter(function (d) { return !d.emulator && d.state == 'device'; }); if (this.devices.length > 1) { // we have more than 1 device, so we should show 'all' this.devices.push({ id: 'all', model: 'All Devices' }); } callback(null, targetDeviceCache[target] = this.devices.map(function (d) { return { name: d.model || d.manufacturer, id: d.id, version: d.release, abi: Array.isArray(d.abi) ? d.abi.join(',') : d.abi, type: 'device' }; })); } }.bind(this)); } else if (target == 'emulator') { new EmulatorManager(config).detect(function (err, emus) { if (err) { callback(err); } else { this.devices = emus; callback(null, targetDeviceCache[target] = emus.map(function (emu) { // normalize the emulator info if (emu.type == 'avd') { return { name: emu.name, id: emu.name, api: emu['api-level'], version: emu['sdk-version'], abi: emu.abi, type: emu.type, googleApis: emu.googleApis, sdcard: emu.sdcard }; } else if (emu.type == 'genymotion') { return { name: emu.name, id: emu.name, api: emu['api-level'], version: emu['sdk-version'], abi: emu.abi, type: emu.type, googleApis: emu.googleApis, sdcard: true }; } return emu; // not good })); } }.bind(this)); } else { callback(); } }.bind(this); return function (finished) { cli.createHook('build.android.config', this, function (callback) { var conf = { flags: { 'launch': { desc: __('disable launching the app after installing'), default: true, hideDefault: true, negate: true } }, options: { 'alias': { abbr: 'L', desc: __('the alias for the keystore'), hint: 'alias', order: 155, prompt: function (callback) { callback(fields.select({ title: __("What is the name of the keystore's certificate alias?"), promptLabel: __('Select a certificate alias by number or name'), margin: '', optionLabel: 'name', optionValue: 'name', numbered: true, relistOnError: true, complete: true, suggest: false, options: _t.keystoreAliases, validate: conf.options.alias.validate })); }, validate: function (value, callback) { // if there's a value, then they entered something, otherwise let the cli prompt if (value) { var selectedAlias = value.toLowerCase(), alias = _t.keystoreAlias = _t.keystoreAliases.filter(function (a) { return a.name && a.name.toLowerCase() == selectedAlias; }).shift(); if (!alias) { return callback(new Error(__('Invalid "--alias" value "%s"', value))); } if (alias.sigalg && alias.sigalg.toLowerCase() == 'sha256withrsa') { logger.warn(__('The selected alias %s uses the %s signature algorithm which will likely have issues with Android 4.3 and older.', ('"' + value + '"').cyan, ('"' + alias.sigalg + '"').cyan)); logger.warn(__('Certificates that use the %s or %s signature algorithm will provide better compatibility.', '"SHA1withRSA"'.cyan, '"MD5withRSA"'.cyan)); } } callback(null, value); } }, 'android-sdk': { abbr: 'A', default: config.android && config.android.sdkPath && afs.resolvePath(config.android.sdkPath), desc: __('the path to the Android SDK'), hint: __('path'), order: 100, prompt: function (callback) { var androidSdkPath = config.android && config.android.sdkPath; if (!androidSdkPath && _t.androidInfo.sdk) { androidSdkPath = _t.androidInfo.sdk.path; } if (androidSdkPath) { androidSdkPath = afs.resolvePath(androidSdkPath); if (process.platform == 'win32' || androidSdkPath.indexOf('&') != -1) { androidSdkPath = undefined; } } callback(fields.file({ promptLabel: __('Where is the Android SDK?'), default: androidSdkPath, complete: true, showHidden: true, ignoreDirs: _t.ignoreDirs, ignoreFiles: _t.ignoreFiles, validate: _t.conf.options['android-sdk'].validate.bind(_t) })); }, required: true, validate: function (value, callback) { if (!value) { callback(new Error(__('Invalid Android SDK path'))); } else if (process.platform == 'win32' && value.indexOf('&') != -1) { callback(new Error(__('The Android SDK path cannot contain ampersands (&) on Windows'))); } else if (_t.androidInfo.sdk && _t.androidInfo.sdk.path == afs.resolvePath(value)) { // no sense doing the detection again, just make sure we found the sdk assertIssue(logger, _t.androidInfo.issues, 'ANDROID_SDK_NOT_FOUND'); assertIssue(logger, _t.androidInfo.issues, 'ANDROID_SDK_MISSING_PROGRAMS'); callback(null, value); } else { // do a quick scan to see if the path is correct android.findSDK(value, config, appc.pkginfo.package(module), function (err, results) { if (err) { callback(new Error(__('Invalid Android SDK path: %s', value))); } else { function next() { // set the android sdk in the config just in case a plugin or something needs it config.set('android.sdkPath', value); // path looks good, do a full scan again androidDetect(config, { packageJson: _t.packageJson, bypassCache: true }, function (androidInfo) { // check that the Android SDK is found and sane assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_NOT_FOUND'); assertIssue(logger, androidInfo.issues, 'ANDROID_SDK_MISSING_PROGRAMS'); _t.androidInfo = androidInfo; callback(null, value); }); } // new android sdk path looks good // if we found an android sdk in the pre-validate hook, then we need to kill the other sdk's adb server if (_t.androidInfo.sdk) { new ADB(config).stopServer(next); } else { next(); } } }); } } }, 'avd-abi': { abbr: 'B', desc: __('the abi for the Android emulator; deprecated, use --device-id'), hint: __('abi') }, 'avd-id': { abbr: 'I', desc: __('the id for the Android emulator; deprecated, use --device-id'), hint: __('id') }, 'avd-skin': { abbr: 'S', desc: __('the skin for the Android emulator; deprecated, use --device-id'), hint: __('skin') }, 'build-type': { hidden: true }, 'debug-host': { hidden: true }, 'deploy-type': { abbr: 'D', desc: __('the type of deployment; only used when target is %s or %s', 'emulator'.cyan, 'device'.cyan), hint: __('type'), order: 110, values: ['test', 'development'] }, 'device-id': { abbr: 'C', desc: __('the name of the Android emulator or the device id to install the application to'), hint: __('name'), order: 130, prompt: function (callback) { findTargetDevices(cli.argv.target, function (err, results) { var opts = {}, title, promptLabel; // we need to sort all results into groups for the select field if (cli.argv.target == 'device' && results.length) { opts[__('Devices')] = results; title = __('Which device do you want to install your app on?'); promptLabel = __('Select a device by number or name'); } else if (cli.argv.target == 'emulator') { // for emulators, we sort by type var emus = results.filter(function (e) { return e.type == 'avd'; }); if (emus.length) { opts[__('Android Emulators')] = emus; } emus = results.filter(function (e) { return e.type == 'genymotion'; }); if (emus.length) { opts[__('Genymotion Emulators')] = emus; logger.log(__('NOTE: Genymotion emulator must be running to detect Google API support').magenta + '\n'); } title = __('Which emulator do you want to launch your app in?'); promptLabel = __('Select an emulator by number or name'); } // if there are no devices/emulators, error if (!Object.keys(opts).length) { if (cli.argv.target == 'device') { logger.error(__('Unable to find any devices') + '\n'); logger.log(__('Please plug in an Android device, then try again.') + '\n'); } else { logger.error(__('Unable to find any emulators') + '\n'); logger.log(__('Please create an Android emulator, then try again.') + '\n'); } process.exit(1); } callback(fields.select({ title: title, promptLabel: promptLabel, formatters: { option: function (opt, idx, num) { return ' ' + num + opt.name.cyan + (opt.version ? ' (' + opt.version + ')' : '') + (opt.googleApis ? (' (' + __('Google APIs supported') + ')').grey : opt.googleApis === null ? (' (' + __('Google APIs support unknown') + ')').grey : ''); } }, autoSelectOne: true, margin: '', optionLabel: 'name', optionValue: 'id', numbered: true, relistOnError: true, complete: true, suggest: true, options: opts })); }); }, required: true, validate: function (device, callback) { var dev = device.toLowerCase(); findTargetDevices(cli.argv.target, function (err, devices) { if (cli.argv.target == 'device' && dev == 'all') { // we let 'all' slide by return callback(null, dev); } var i = 0, l = devices.length; for (; i < l; i++) { if (devices[i].id.toLowerCase() == dev) { return callback(null, devices[i].id); } } callback(new Error(cli.argv.target ? __('Invalid Android device "%s"', device) : __('Invalid Android emulator "%s"', device))); }); }, verifyIfRequired: function (callback) { if (cli.argv['build-only']) { // not required if we're build only return callback(); } findTargetDevices(cli.argv.target, function (err, results) { if (cli.argv.target == 'emulator' && cli.argv['device-id'] === undefined && cli.argv['avd-id']) { // if --device-id was not specified, but --avd-id was, then we need to // try to resolve a device based on the legacy --avd-* options var avds = results.filter(function (a) { return a.type == 'avd'; }).map(function (a) { return a.name; }), name = 'titanium_' + cli.argv['avd-id'] + '_'; if (avds.length) { // try finding the first avd that starts with the avd id avds = avds.filter(function (avd) { return avd.indexOf(name) == 0; }); if (avds.length == 1) { cli.argv['device-id'] = avds[0]; return callback(); } else if (avds.length > 1) { // next try using the avd skin if (!cli.argv['avd-skin']) { // we have more than one match logger.error(__n('Found %s avd with id "%%s"', 'Found %s avds with id "%%s"', avds.length, cli.argv['avd-id'])); logger.error(__('Specify --avd-skin and --avd-abi to select a specific emulator') + '\n'); } else { name += cli.argv['avd-skin']; // try exact match var tmp = avds.filter(function (avd) { return avd == name; }); if (tmp.length) { avds = tmp; } else { // try partial match avds = avds.filter(function (avd) { return avd.indexOf(name + '_') == 0; }); } if (avds.length == 0) { logger.error(__('No emulators found with id "%s" and skin "%s"', cli.argv['avd-id'], cli.argv['avd-skin']) + '\n'); } else if (avds.length == 1) { cli.argv['device-id'] = avds[0]; return callback(); } else if (!cli.argv['avd-abi']) { // we have more than one matching avd, but no abi to filter by so we have to error logger.error(__n('Found %s avd with id "%%s" and skin "%%s"', 'Found %s avds with id "%%s" and skin "%%s"', avds.length, cli.argv['avd-id'], cli.argv['avd-skin'])); logger.error(__('Specify --avd-abi to select a specific emulator') + '\n'); } else { name += '_' + cli.argv['avd-abi']; // try exact match tmp = avds.filter(function (avd) { return avd == name; }); if (tmp.length) { avds = tmp; } else { avds = avds.filter(function (avd) { return avd.indexOf(name + '_') == 0; }); } if (avds.length == 0) { logger.error(__('No emulators found with id "%s", skin "%s", and abi "%s"', cli.argv['avd-id'], cli.argv['avd-skin'], cli.argv['avd-abi']) + '\n'); } else { // there is one or more avds, but we'll just return the first one cli.argv['device-id'] = avds[0]; return callback(); } } } } logger.warn(__('%s options have been %s, please use %s', '--avd-*'.cyan, 'deprecated'.red, '--device-id'.cyan) + '\n'); // print list of available avds if (results.length && !cli.argv.prompt) { logger.log(__('Available Emulators:')) results.forEach(function (emu) { logger.log(' ' + emu.name.cyan + ' (' + emu.version + ')'); }); logger.log(); } } } else if (cli.argv['device-id'] === undefined && results.length && config.get('android.autoSelectDevice', true)) { // we set the device-id to an array of devices so that later in validate() // after the tiapp.xml has been parsed, we can auto select the best device _t.devicesToAutoSelectFrom = results.sort(function (a, b) { var eq = a.api && b.api && appc.version.eq(a.api, b.api), gt = a.api && b.api && appc.version.gt(a.api, b.api); if (eq) { if (a.type == b.type) { if (a.googleApis == b.googleApis) { return 0; } else if (b.googleApis) { return 1; } else if (a.googleApis === false && b.googleApis === null) { return 1; } return -1; } return a.type == 'avd' ? -1 : 1; } return gt ? 1 : -1; }); return callback(); } // yup, still required callback(true); }); } }, 'key-password': { desc: __('the password for the keystore private key (defaults to the store-password)'), hint: 'keypass', order: 160, prompt: function (callback) { callback(fields.text({ promptLabel: __("What is the keystore's __key password__?") + ' ' + __('(leave blank to use the store password)').grey, password: true, validate: _t.conf.options['key-password'].validate.bind(_t) })); }, secret: true, validate: function (keyPassword, callback) { // sanity check the keystore and store password _t.conf.options['store-password'].validate(cli.argv['store-password'], function (err, storePassword) { if (err) { // we have a bad --keystore or --store-password arg cli.argv.keystore = cli.argv['store-password'] = undefined; return callback(err); } var keystoreFile = cli.argv.keystore, alias = cli.argv.alias, tmpKeystoreFile = temp.path({ suffix: '.jks' }); if (keystoreFile && storePassword && alias && _t.jdkInfo && _t.jdkInfo.executables.keytool) { // the only way to test the key password is to export the cert appc.subprocess.run(_t.jdkInfo.executables.keytool, [ '-J-Duser.language=en', '-importkeystore', '-v', '-srckeystore', keystoreFile, '-destkeystore', tmpKeystoreFile, '-srcstorepass', storePassword, '-deststorepass', storePassword, '-srcalias', alias, '-destalias', alias, '-srckeypass', keyPassword || storePassword, '-noprompt' ], function (code, out, err) { if (code) { if (out.indexOf('java.security.UnrecoverableKeyException') != -1) { return callback(new Error(__('Bad key password'))); } return callback(new Error(out.trim())); } // remove the temp keystore fs.existsSync(tmpKeystoreFile) && fs.unlinkSync(tmpKeystoreFile); callback(null, keyPassword); }); } else { callback(null, keyPassword); } }); } }, 'keystore': { abbr: 'K', callback: function (value) { _t.conf.options['alias'].required = true; _t.conf.options['store-password'].required = true; }, desc: __('the location of the keystore file'), hint: 'path', order: 140, prompt: function (callback) { _t.conf.options['key-password'].required = true; callback(fields.file({ promptLabel: __('Where is the __keystore file__ used to sign the app?'), complete: true, showHidden: true, ignoreDirs: _t.ignoreDirs, ignoreFiles: _t.ignoreFiles, validate: _t.conf.options.keystore.validate.bind(_t) })); }, validate: function (keystoreFile, callback) { if (!keystoreFile) { callback(new Error(__('Please specify the path to your keystore file'))); } else { keystoreFile = afs.resolvePath(keystoreFile); if (!fs.existsSync(keystoreFile) || !fs.statSync(keystoreFile).isFile()) { callback(new Error(__('Invalid keystore file'))); } else { callback(null, keystoreFile); } } } }, 'output-dir': { abbr: 'O', desc: __('the output directory when using %s', 'dist-playstore'.cyan), hint: 'dir', order: 180, prompt: function (callback) { callback(fields.file({ promptLabel: __('Where would you like the output APK file saved?'), default: cli.argv['project-dir'] && afs.resolvePath(cli.argv['project-dir'], 'dist'), complete: true, showHidden: true, ignoreDirs: _t.ignoreDirs, ignoreFiles: /.*/, validate: _t.conf.options['output-dir'].validate.bind(_t) })); }, validate: function (outputDir, callback) { callback(outputDir || !_t.conf.options['output-dir'].required ? null : new Error(__('Invalid output directory')), outputDir); } }, 'profiler-host': { hidden: true }, 'store-password': { abbr: 'P', desc: __('the password for the keystore'), hint: 'password', order: 150, prompt: function (callback) { callback(fields.text({ next: function (err, value) { return err && err.next || null; }, promptLabel: __("What is the keystore's __password__?"), password: true, // if the password fails due to bad keystore file, // we need to prompt for the keystore file again repromptOnError: false, validate: _t.conf.options['store-password'].validate.bind(_t) })); }, secret: true, validate: function (storePassword, callback) { if (!storePassword) { return callback(new Error(__('Please specify a keystore password'))); } // sanity check the keystore _t.conf.options.keystore.validate(cli.argv.keystore, function (err, keystoreFile) { if (err) { // we have a bad --keystore arg cli.argv.keystore = undefined; return callback(err); } if (keystoreFile && _t.jdkInfo && _t.jdkInfo.executables.keytool) { appc.subprocess.run(_t.jdkInfo.executables.keytool, [ '-J-Duser.language=en', '-list', '-v', '-keystore', keystoreFile, '-storepass', storePassword ], function (code, out, err) { if (code) { var msg = out.split('\n').shift().split('java.io.IOException:'); if (msg.length > 1) { msg = msg[1].trim(); if (/invalid keystore format/i.test(msg)) { msg = __('Invalid keystore file'); cli.argv.keystore = undefined; _t.conf.options.keystore.required = true; } } else { msg = out.trim(); } return callback(new Error(msg)); } // empty the alias array. it is important that we don't destory the original // instance since it was passed by reference to the alias select list while (_t.keystoreAliases.length) { _t.keystoreAliases.pop(); } var aliasRegExp = /Alias name\: (.+)/, sigalgRegExp = /Signature algorithm name\: (.+)/; out.split('\n\n').forEach(function (chunk) { chunk = chunk.trim(); var m = chunk.match(aliasRegExp); if (m) { var sigalg = chunk.match(sigalgRegExp); _t.keystoreAliases.push({ name: m[1], sigalg: sigalg && sigalg[1] }); } }); if (_t.keystoreAliases.length == 0) { cli.argv.keystore = undefined; return callback(new Error(__('Keystore does not contain any certificates'))); } else if (!cli.argv.alias && _t.keystoreAliases.length == 1) { cli.argv.alias = _t.keystoreAliases[0].name; } // check if this keystore requires a key password var keystoreFile = cli.argv.keystore, alias = cli.argv.alias, tmpKeystoreFile = temp.path({ suffix: '.jks' }); if (keystoreFile && storePassword && alias && _t.jdkInfo && _t.jdkInfo.executables.keytool) { // the only way to test the key password is to export the cert appc.subprocess.run(_t.jdkInfo.executables.keytool, [ '-J-Duser.language=en', '-importkeystore', '-v', '-srckeystore', keystoreFile, '-destkeystore', tmpKeystoreFile, '-srcstorepass', storePassword, '-deststorepass', storePassword, '-srcalias', alias, '-destalias', alias, '-srckeypass', storePassword, '-noprompt' ], function (code, out, err) { if (code) { if (out.indexOf('Alias <' + alias + '> does not exist') != -1) { // bad alias, we'll let --alias find it again _t.conf.options['alias'].required = true; } // since we have an error, force the key password to be required _t.conf.options['key-password'].required = true; } else { // remove the temp keystore fs.existsSync(tmpKeystoreFile) && fs.unlinkSync(tmpKeystoreFile); } callback(null, storePassword); }); } else { callback(null, storePassword); } }.bind(_t)); } else { callback(null, storePassword); } }); } }, 'target': { abbr: 'T', callback: function (value) { // as soon as we know the target, toggle required options for validation if (value === 'dist-playstore') { _t.conf.options['alias'].required = true; _t.conf.options['deploy-type'].values = ['production']; _t.conf.options['device-id'].required = false; _t.conf.options['keystore'].required = true; _t.conf.options['output-dir'].required = true; _t.conf.options['store-password'].required = true; } }, default: 'emulator', desc: __('the target to build for'), order: 120, required: true, values: _t.targets } } }; callback(null, _t.conf = conf); })(function (err, result) { finished(result); }); }.bind(this); }; AndroidBuilder.prototype.validate = function validate(logger, config, cli) { Builder.prototype.validate.apply(this, arguments); this.target = cli.argv.target; this.deployType = !/^dist-/.test(this.target) && cli.argv['deploy-type'] ? cli.argv['deploy-type'] : this.deployTypes[this.target]; this.buildType = cli.argv['build-type'] || ''; // ti.deploytype is deprecated and so we force the real deploy type if (cli.tiapp.properties['ti.deploytype']) { logger.warn(__('The %s tiapp.xml property has been deprecated, please use the %s option', 'ti.deploytype'.cyan, '--deploy-type'.cyan)); } cli.tiapp.properties['ti.deploytype'] = { type: 'string', value: this.deployType }; // get the javac params this.javacMaxMemory = cli.tiapp.properties['android.javac.maxmemory'] && cli.tiapp.properties['android.javac.maxmemory'].value || config.get('android.javac.maxMemory', '1024M'); this.javacSource = cli.tiapp.properties['android.javac.source'] && cli.tiapp.properties['android.javac.source'].value || config.get('android.javac.source', '1.6'); this.javacTarget = cli.tiapp.properties['android.javac.target'] && cli.tiapp.properties['android.javac.target'].value || config.get('android.javac.target', '1.6'); this.dxMaxMemory = cli.tiapp.properties['android.dx.maxmemory'] && cli.tiapp.properties['android.dx.maxmemory'].value || config.get('android.dx.maxMemory', '1024M'); // manually inject the build profile settings into the tiapp.xml switch (this.deployType) { case 'production': this.minifyJS = true; this.encryptJS = true; this.minifyCSS = true; this.allowDebugging = false; this.allowProfiling = false; this.includeAllTiModules = false; this.proguard = false; break; case 'test': this.minifyJS = true; this.encryptJS = true; this.minifyCSS = true; this.allowDebugging = true; this.allowProfiling = true; this.includeAllTiModules = false; this.proguard = false; break; case 'development': default: this.minifyJS = false; this.encryptJS = false; this.minifyCSS = false; this.allowDebugging = true; this.allowProfiling = true; this.includeAllTiModules = true; this.proguard = false; } if (cli.tiapp.properties['ti.android.compilejs']) { logger.warn(__('The %s tiapp.xml property has been deprecated, please use the %s option to bypass JavaScript minification', 'ti.android.compilejs'.cyan, '--skip-js-minify'.cyan)); } if (cli.argv['skip-js-minify']) { this.minifyJS = false; } // check the app name if (cli.tiapp.name.indexOf('&') != -1) { if (config.get('android.allowAppNameAmpersands', false)) { logger.warn(__('The app name "%s" contains an ampersand (&) which will most likely cause problems.', cli.tiapp.name)); logger.warn(__('It is recommended that you define the app name using i18n strings.')); logger.warn(__('Refer to %s for more information.', 'http://appcelerator.com/i18n-app-name'.cyan)); } else { logger.error(__('The app name "%s" contains an ampersand (&) which will most likely cause problems.', cli.tiapp.name)); logger.error(__('It is recommended that you define the app name using i18n strings.')); logger.error(__('Refer to %s for more information.', 'http://appcelerator.com/i18n-app-name')); logger.error(__('To allow ampersands in the app name, run:')); logger.error(' ti config android.allowAppNameAmpersands true\n'); process.exit(1); } } // check the Android specific app id rules if (!config.get('app.skipAppIdValidation') && !cli.tiapp.properties['ti.skipAppIdValidation']) { if (!/^([a-zA-Z_]{1}[a-zA-Z0-9_-]*(\.[a-zA-Z0-9_-]*)*)$/.test(cli.tiapp.id)) { logger.error(__('tiapp.xml contains an invalid app id "%s"', cli.tiapp.id)); logger.error(__('The app id must consist only of letters, numbers, dashes, and underscores.')); logger.error(__('Note: Android does not allow dashes.')); logger.error(__('The first character must be a letter or underscore.')); logger.error(__("Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)") + '\n'); process.exit(1); } if (!/^([a-zA-Z_]{1}[a-zA-Z0-9_]*(\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*)$/.test(cli.tiapp.id)) { logger.error(__('tiapp.xml contains an invalid app id "%s"', cli.tiapp.id)); logger.error(__('The app id must consist of letters, numbers, and underscores.')); logger.error(__('The first character must be a letter or underscore.')); logger.error(__('The first character after a period must not be a number.')); logger.error(__("Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)") + '\n'); process.exit(1); } if (!ti.validAppId(cli.tiapp.id)) { logger.error(__('Invalid app id "%s"', cli.tiapp.id)); logger.error(__('The app id must not contain Java reserved words.') + '\n'); process.exit(1); } } // check the default unit cli.tiapp.properties || (cli.tiapp.properties = {}); cli.tiapp.properties['ti.ui.defaultunit'] || (cli.tiapp.properties['ti.ui.defaultunit'] = { type: 'string', value: 'system'}); if (!/^system|px|dp|dip|mm|cm|in$/.test(cli.tiapp.properties['ti.ui.defaultunit'].value)) { logger.error(__('Invalid "ti.ui.defaultunit" property value "%s"', cli.tiapp.properties['ti.ui.defaultunit'].value) + '\n'); logger.log(__('Valid units:')); 'system,px,dp,dip,mm,cm,in'.split(',').forEach(function (unit) { logger.log(' ' + unit.cyan); }); logger.log(); process.exit(1); } // if we're building for the emulator, make sure we don't have any issues if (cli.argv.target == 'emulator') { this.androidInfo.issues.forEach(function (issue) { if (/^ANDROID_MISSING_(LIBGL|I386_ARCH|IA32_LIBS|32BIT_GLIBC|32BIT_LIBSTDCPP)$/.test(issue.id)) { issue.message.split('\n').forEach(function (line) { logger.warn(line); }); } }); } // check that the proguard config exists var proguardConfigFile = path.join(cli.argv['project-dir'], 'platform', 'android', 'proguard.cfg'); if (this.proguard && !fs.existsSync(proguardConfigFile)) { logger.error(__('Missing ProGuard configuration file')); logger.error(__('ProGuard settings must go in the file "%s"', proguardConfigFile)); logger.error(__('For example configurations, visit %s', 'http://proguard.sourceforge.net/index.html#manual/examples.html') + '\n'); process.exit(1); } // map sdk versions to sdk targets instead of by id var targetSDKMap = {}; Object.keys(this.androidInfo.targets).forEach(function (i) { var t = this.androidInfo.targets[i]; if (t.type === 'platform') { targetSDKMap[t.id.replace('android-', '')] = t; } }, this); try { var tiappAndroidManifest = this.tiappAndroidManifest = cli.tiapp.android && cli.tiapp.android.manifest && (new AndroidManifest).parse(cli.tiapp.android.manifest); } catch (ex) { logger.error(__('Malformed <manifest> definition in the <android> section of the tiapp.xml') + '\n'); process.exit(1); } try { var customAndroidManifestFile = path.join(cli.argv['project-dir'], 'platform', 'android', 'AndroidManifest.xml'); this.customAndroidManifest = fs.existsSync(customAndroidManifestFile) && (new AndroidManifest(customAndroidManifestFile)); } catch (ex) { logger.error(__('Malformed custom AndroidManifest.xml file: %s', customAndroidManifestFile) + '\n'); process.exit(1); } // validate the sdk levels var usesSDK = (tiappAndroidManifest && tiappAndroidManifest['uses-sdk']) || (this.customAndroidManifest && this.customAndroidManifest['uses-sdk']); this.minSDK = this.minSupportedApiLevel; this.targetSDK = cli.tiapp.android && ~~cli.tiapp.android['tool-api-level'] || null; this.maxSDK = null; if (this.targetSDK) { logger.log(); logger.warn(__('%s has been deprecated, please specify the target SDK API using the %s tag:', '<tool-api-level>'.cyan, '<uses-sdk>'.cyan)); logger.warn(); logger.warn('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.warn(' <android>'.grey); logger.warn(' <manifest>'.grey); logger.warn((' <uses-sdk android:minSdkVersion="' + this.minSupportedApiLevel + '" android:targetSdkVersion="' + this.minTargetApiLevel + '" android:maxSdkVersion="' + this.maxSupportedApiLevel + '"/>').magenta); logger.warn(' </manifest>'.grey); logger.warn(' </android>'.grey); logger.warn('</ti:app>'.grey); logger.log(); } if (usesSDK) { usesSDK.minSdkVersion && (this.minSDK = usesSDK.minSdkVersion); usesSDK.targetSdkVersion && (this.targetSDK = usesSDK.targetSdkVersion); usesSDK.maxSdkVersion && (this.maxSDK = usesSDK.maxSdkVersion); } // we need to translate the sdk to a real api level (i.e. L => 20, MNC => 22) so that // we can valiate them function getRealAPILevel(ver) { return (ver && targetSDKMap[ver] && targetSDKMap[ver].sdk) || ver; } this.realMinSDK = getRealAPILevel(this.minSDK); this.realTargetSDK = getRealAPILevel(this.targetSDK); this.realMaxSDK = getRealAPILevel(this.maxSDK); // min sdk is too old if (this.minSDK && this.realMinSDK < this.minSupportedApiLevel) { logger.error(__('The minimum supported SDK API version must be %s or newer, but is currently set to %s', this.minSupportedApiLevel, this.minSDK + (this.minSDK !== this.realMinSDK ? ' (' + this.realMinSDK + ')' : '')) + '\n'); logger.log( appc.string.wrap( __('Update the %s in the tiapp.xml or custom AndroidManifest to at least %s:', 'android:minSdkVersion'.cyan, String(this.minSupportedApiLevel).cyan), config.get('cli.width', 100) ) ); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <android>'.grey); logger.log(' <manifest>'.grey); logger.log((' <uses-sdk ' + 'android:minSdkVersion="' + this.minSupportedApiLevel + '" ' + (this.targetSDK ? 'android:targetSdkVersion="' + this.targetSDK + '" ' : '') + (this.maxSDK ? 'android:maxSdkVersion="' + this.maxSDK + '" ' : '') + '/>').magenta); logger.log(' </manifest>'.grey); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); process.exit(1); } if (this.targetSDK) { // target sdk is too old if (this.realTargetSDK < this.minTargetApiLevel) { logger.error(__('The target SDK API %s is not supported by Titanium SDK %s', this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : ''), ti.manifest.version)); logger.error(__('The target SDK API version must be %s or newer', this.minTargetApiLevel) + '\n'); logger.log( appc.string.wrap( __('Update the %s in the tiapp.xml or custom AndroidManifest to at least %s:', 'android:targetSdkVersion'.cyan, String(this.minTargetApiLevel).cyan), config.get('cli.width', 100) ) ); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <android>'.grey); logger.log(' <manifest>'.grey); logger.log((' <uses-sdk ' + (this.minSupportedApiLevel ? 'android:minSdkVersion="' + this.minSupportedApiLevel + '" ' : '') + 'android:targetSdkVersion="' + this.minTargetApiLevel + '" ' + (this.maxSDK ? 'android:maxSdkVersion="' + this.maxSDK + '" ' : '') + '/>').magenta); logger.log(' </manifest>'.grey); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); process.exit(1); } // target sdk < min sdk if (this.realTargetSDK < this.realMinSDK) { logger.error(__('The target SDK API must be greater than or equal to the minimum SDK %s, but is currently set to %s', this.minSDK + (this.minSDK !== this.realMinSDK ? ' (' + this.realMinSDK + ')' : ''), this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : '') ) + '\n'); process.exit(1); } } else { // if no target sdk, then default to most recent supported/installed Object .keys(targetSDKMap) .sort(function (a, b) { if (targetSDKMap[a].sdk === targetSDKMap[b].sdk && targetSDKMap[a].revision === targetSDKMap[b].revision) { return 0; } else if (targetSDKMap[a].sdk < targetSDKMap[b].sdk || (targetSDKMap[a].sdk === targetSDKMap[b].sdk && targetSDKMap[a].revision < targetSDKMap[b].revision)) { return -1; } return 1; }) .reverse() .some(function (ver) { if (targetSDKMap[ver].sdk >= this.minTargetApiLevel && targetSDKMap[ver].sdk <= this.maxSupportedApiLevel) { this.targetSDK = this.realTargetSDK = targetSDKMap[ver].sdk; return true; } }, this); if (!this.targetSDK || this.realTargetSDK < this.minTargetApiLevel) { if (this.minTargetApiLevel === this.maxSupportedApiLevel) { logger.error(__('Unable to find Android SDK API %s', this.maxSupportedApiLevel)); logger.error(__('Android SDK API %s is required to build Android apps', this.maxSupportedApiLevel) + '\n'); } else { logger.error(__('Unable to find a suitable installed Android SDK that is API >=%s and <=%s', this.minTargetApiLevel, this.maxSupportedApiLevel) + '\n'); } process.exit(1); } } // check that we have this target sdk installed this.androidTargetSDK = targetSDKMap[this.targetSDK]; if (!this.androidTargetSDK) { logger.error(__('Target Android SDK API %s is not installed', this.targetSDK) + '\n'); var sdks = Object.keys(targetSDKMap).filter(function (ver) { return ~~ver > this.minSupportedApiLevel; }.bind(this)).sort().filter(function (s) { return s >= this.minSDK; }, this); if (sdks.length) { logger.log(__('To target Android SDK API %s, you first must install it using the Android SDK manager.', String(this.targetSDK).cyan) + '\n'); logger.log( appc.string.wrap( __('Alternatively, you can set the %s in the %s section of the tiapp.xml to one of the following installed Android target SDK APIs: %s', '<uses-sdk>'.cyan, '<android> <manifest>'.cyan, sdks.join(', ').cyan), config.get('cli.width', 100) ) ); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <android>'.grey); logger.log(' <manifest>'.grey); logger.log((' <uses-sdk ' + (this.minSDK ? 'android:minSdkVersion="' + this.minSDK + '" ' : '') + 'android:targetSdkVersion="' + sdks[0] + '" ' + (this.maxSDK ? 'android:maxSdkVersion="' + this.maxSDK + '" ' : '') + '/>').magenta); logger.log(' </manifest>'.grey); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); } else { logger.log(__('To target Android SDK API %s, you first must install it using the Android SDK manager', String(this.targetSDK).cyan) + '\n'); } process.exit(1); } if (!this.androidTargetSDK.androidJar) { logger.error(__('Target Android SDK API %s is missing "android.jar"', this.targetSDK) + '\n'); process.exit(1); } if (this.realTargetSDK < this.realMinSDK) { logger.error(__('Target Android SDK API version must be %s or newer', this.minSDK) + '\n'); process.exit(1); } if (this.realMaxSDK && this.realMaxSDK < this.realTargetSDK) { logger.error(__('Maximum Android SDK API version must be greater than or equal to the target SDK API %s, but is currently set to %s', this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : ''), this.maxSDK + (this.maxSDK !== this.realMaxSDK ? ' (' + this.realMaxSDK + ')' : '') ) + '\n'); process.exit(1); } if (this.maxSupportedApiLevel && this.realTargetSDK > this.maxSupportedApiLevel) { // print warning that version this.targetSDK is not tested logger.warn(__('Building with Android SDK API %s which hasn\'t been tested against Titanium SDK %s', String(this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : '')).cyan, this.titaniumSdkVersion )); } // determine the abis to support this.abis = this.validABIs; if (cli.tiapp.android && cli.tiapp.android.abi && cli.tiapp.android.abi.indexOf('all') == -1) { this.abis = cli.tiapp.android.abi; this.abis.forEach(function (abi) { if (this.validABIs.indexOf(abi) == -1) { logger.error(__('Invalid ABI "%s"', abi) + '\n'); logger.log(__('Valid ABIs:')); this.validABIs.forEach(function (name) { logger.log(' ' + name.cyan); }); logger.log(); process.exit(1); } }, this); } var deviceId = cli.argv['device-id']; if (!cli.argv['build-only'] && /^device|emulator$/.test(this.target) && deviceId === undefined && config.get('android.autoSelectDevice', true)) { // no --device-id, so intelligently auto select one var ver = this.androidTargetSDK.version, apiLevel = this.androidTargetSDK.sdk, devices = this.devicesToAutoSelectFrom, i, len = devices.length, verRegExp = /^((\d\.)?\d\.)?\d$/; // reset the device id deviceId = null; if (cli.argv.target == 'device') { logger.info(__('Auto selecting device that closest matches %s', ver.cyan)); } else { logger.info(__('Auto selecting emulator that closest matches %s', ver.cyan)); } function setDeviceId(device) { deviceId = cli.argv['device-id'] = device.id; var gapi = ''; if (device.googleApis) { gapi = (' (' + __('Google APIs supported') + ')').grey; } else if (device.googleApis === null) { gapi = (' (' + __('Google APIs support unknown') + ')').grey; } if (cli.argv.target == 'device') { logger.info(__('Auto selected device %s %s', device.name.cyan, device.version) + gapi); } else { logger.info(__('Auto selected emulator %s %s', device.name.cyan, device.version) + gapi); } } function gte(device) { return device.api >= apiLevel && (!verRegExp.test(device.version) || appc.version.gte(device.version, ver)); } function lt(device) { return device.api < apiLevel && (!verRegExp.test(device.version) || appc.version.lt(device.version, ver)); } // find the first one where version is >= and google apis == true logger.debug(__('Searching for version >= %s and has Google APIs', ver)); for (i = 0; i < len; i++) { if (gte(devices[i]) && devices[i].googleApis) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version is >= and google apis is a maybe logger.debug(__('Searching for version >= %s and may have Google APIs', ver)); for (i = 0; i < len; i++) { if (gte(devices[i]) && devices[i].googleApis === null) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version is >= and no google apis logger.debug(__('Searching for version >= %s and no Google APIs', ver)); for (i = 0; i < len; i++) { if (gte(devices[i])) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version < and google apis == true logger.debug(__('Searching for version < %s and has Google APIs', ver)); for (i = len - 1; i >= 0; i--) { if (lt(devices[i])) { setDeviceId(devices[i]); break; } } if (!deviceId) { // find first one where version < logger.debug(__('Searching for version < %s and no Google APIs', ver)); for (i = len - 1; i >= 0; i--) { if (lt(devices[i]) && devices[i].googleApis) { setDeviceId(devices[i]); break; } } if (!deviceId) { // just grab first one logger.debug(__('Selecting first device')); setDeviceId(devices[0]); } } } } } var devices = deviceId == 'all' ? this.devices : this.devices.filter(function (d) { return d.id = deviceId; }); devices.forEach(function (device) { if (Array.isArray(device.abi) && !device.abi.some(function (a) { return this.abis.indexOf(a) != -1; }.bind(this))) { if (this.target == 'emulator') { logger.error(__n('The emulator "%%s" does not support the desired ABI %%s', 'The emulator "%%s" does not support the desired ABIs %%s', this.abis.length, device.name, '"' + this.abis.join('", "') + '"')); } else { logger.error(__n('The device "%%s" does not support the desired ABI %%s', 'The device "%%s" does not support the desired ABIs %%s', this.abis.length, device.model || device.manufacturer, '"' + this.abis.join('", "') + '"')); } logger.error(__('Supported ABIs: %s', device.abi.join(', ')) + '\n'); logger.log(__('You need to add at least one of the device\'s supported ABIs to the tiapp.xml')); logger.log(); logger.log('<ti:app xmlns:ti="http://ti.appcelerator.org">'.grey); logger.log(' <!-- snip -->'.grey); logger.log(' <android>'.grey); logger.log((' <abi>' + this.abis.concat(device.abi).join(',') + '</abi>').magenta); logger.log(' </android>'.grey); logger.log('</ti:app>'.grey); logger.log(); process.exit(1); } }, this); } // validate debugger and profiler options var tool = []; this.allowDebugging && tool.push('debug'); this.allowProfiling && tool.push('profiler'); this.debugHost = null; this.debugPort = null; this.profilerHost = null; this.profilerPort = null; tool.forEach(function (type) { if (cli.argv[type + '-host']) { if (typeof cli.argv[type + '-host'] == 'number') { logger.error(__('Invalid %s host "%s"', type, cli.argv[type + '-host']) + '\n'); logger.log(__('The %s host must be in the format "host:port".', type) + '\n'); process.exit(1); } var parts = cli.argv[type + '-host'].split(':'); if (parts.length < 2) { logger.error(__('Invalid ' + type + ' host "%s"', cli.argv[type + '-host']) + '\n'); logger.log(__('The %s host must be in the format "host:port".', type) + '\n'); process.exit(1); } var port = parseInt(parts[1]); if (isNaN(port) || port < 1 || port > 65535) { logger.error(__('Invalid ' + type + ' host "%s"', cli.argv[type + '-host']) + '\n'); logger.log(__('The port must be a valid integer between 1 and 65535.') + '\n'); process.exit(1); } this[type + 'Host'] = parts[0]; this[type + 'Port'] = port; } }, this); if (this.debugPort || this.profilerPort) { // if debugging/profiling, make sure we only have one device and that it has an sd card if (this.target == 'emulator') { var emu = this.devices.filter(function (d) { return d.name == deviceId; }).shift(); if (!emu) { logger.error(__('Unable find emulator "%s"', deviceId) + '\n'); process.exit(1); } else if (!emu.sdcard && emu.type != 'genymotion') { logger.error(__('The selected emulator "%s" does not have an SD card.', emu.name)); if (this.profilerPort) { logger.error(__('An SD card is required for profiling.') + '\n'); } else { logger.error(__('An SD card is required for debugging.') + '\n'); } process.exit(1); } } else if (this.target == 'device' && deviceId == 'all' && this.devices.length > 1) { // fail, can't do 'all' for debug builds logger.error(__('Cannot debug application when --device-id is set to "all" and more than one device is connected.')); logger.error(__('Please specify a single device to debug on.') + '\n'); process.exit(1); } } // check that the build directory is writeable var buildDir = path.join(cli.argv['project-dir'], 'build'); if (fs.existsSync(buildDir)) { if (!afs.isDirWritable(buildDir)) { logger.error(__('The build directory is not writeable: %s', buildDir) + '\n'); logger.log(__('Make sure the build directory is writeable and that you have sufficient free disk space.') + '\n'); process.exit(1); } } else if (!afs.isDirWritable(cli.argv['project-dir'])) { logger.error(__('The project directory is not writeable: %s', cli.argv['project-dir']) + '\n'); logger.log(__('Make sure the project directory is writeable and that you have sufficient free disk space.') + '\n'); process.exit(1); } // make sure we have an icon if (this.tiappAndroidManifest && this.tiappAndroidManifest.application && this.tiappAndroidManifest.application.icon) { cli.tiapp.icon = this.tiappAndroidManifest.application.icon.replace(/^\@drawable\//, '') + '.png'; } else if (this.customAndroidManifest && this.customAndroidManifest.application && this.customAndroidManifest.application.icon) { cli.tiapp.icon = this.customAndroidManifest.application.icon.replace(/^\@drawable\//, '') + '.png'; } if (!cli.tiapp.icon || !['Resources', 'Resources/android'].some(function (p) { return fs.existsSync(cli.argv['project-dir'], p, cli.tiapp.icon); })) { cli.tiapp.icon = 'appicon.png'; } return function (callback) { this.validateTiModules('android', this.deployType, function (err, modules) { this.modules = modules.found; this.commonJsModules = []; this.nativeLibModules = []; var manifestHashes = [], nativeHashes = [], bindingsHashes = [], jarHashes = {}; modules.found.forEach(function (module) { manifestHashes.push(this.hash(JSON.stringify(module.manifest))); if (module.platform.indexOf('commonjs') != -1) { module.native = false; // Look for legacy module.id.js first module.libFile = path.join(module.modulePath, module.id + '.js'); if (!fs.existsSync(module.libFile)) { // then package.json TODO Verify the main property points at reale file under the module! module.libFile = path.join(module.modulePath, 'package.json'); if (!fs.existsSync(module.libFile)) { // then index.js module.libFile = path.join(module.modulePath, 'index.js'); if (!fs.existsSync(module.libFile)) { // then index.json module.libFile = path.join(module.modulePath, 'index.json'); if (!fs.existsSync(module.libFile)) { this.logger.error(__('Module %s version %s is missing module files: %s, package.json, index.js, or index.json', module.id.cyan, (module.manifest.version || 'latest').cyan, path.join(module.modulePath, module.id + '.js').cyan) + '\n'); process.exit(1); } } } } this.commonJsModules.push(module); } else { module.native = true; // jar filenames are always lower case and must correspond to the name in the module's build.xml file module.jarName = module.manifest.name.toLowerCase() + '.jar', module.jarFile = path.join(module.modulePath, module.jarName); if (!fs.existsSync(module.jarFile)) { // NOTE: this should be an error, not a warning, but due to the soasta module, we can't error out // logger.error(__('Module %s version %s is missing main jar file', module.id.cyan, (module.manifest.version || 'latest').cyan) + '\n'); // process.exit(1); logger.warn(__('Module %s version %s does not have a main jar file', module.id.cyan, (module.manifest.version || 'latest').cyan)); module.jarName = module.jarFile = null; } else { // get the jar hashes var jarHash = module.hash = this.hash(fs.readFileSync(module.jarFile).toString()); nativeHashes.push(jarHash); jarHashes[module.jarName] || (jarHashes[module.jarName] = []); jarHashes[module.jarName].push({ hash: module.hash, module: module }); } var libDir = path.join(module.modulePath, 'lib'), jarRegExp = /\.jar$/; fs.existsSync(libDir) && fs.readdirSync(libDir).forEach(function (name) { var file = path.join(libDir, name); if (jarRegExp.test(name) && fs.existsSync(file)) { jarHashes[name] || (jarHashes[name] = []); jarHashes[name].push({ hash: this.hash(fs.readFileSync(file).toString()), module: module }); } }, this); // determine the module's ABIs module.abis = []; var libsDir = path.join(module.modulePath, 'libs'), soRegExp = /\.so$/; fs.existsSync(libsDir) && fs.readdirSync(libsDir).forEach(function (abi) { var dir = path.join(libsDir, abi), added = false; if (!this.ignoreDirs.test(abi) && fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { fs.readdirSync(dir).forEach(function (name) { if (soRegExp.test(name)) { var file = path.join(dir, name); if (!added) { module.abis.push(abi); added = true; } nativeHashes.push(afs.hashFile(file)); } }); } }, this); // check missing abis var missingAbis = module.abis.length && this.abis.filter(function (a) { return module.abis.indexOf(a) == -1; }); if (missingAbis.length) { /* commenting this out to preserve the old, incorrect behavior this.logger.error(__n('The module "%%s" does not support the ABI: %%s', 'The module "%%s" does not support the ABIs: %s', missingAbis.length, module.id, '"' + missingAbis.join('" "') + '"')); this.logger.error(__('It only supports the following ABIs: %s', module.abis.join(', ')) + '\n'); process.exit(1); */ this.logger.warn(__n('The module %%s does not support the ABI: %%s', 'The module %%s does not support the ABIs: %s', missingAbis.length, module.id.cyan, missingAbis.map(function (a) { return a.cyan; }).join(', '))); this.logger.warn(__('It only supports the following ABIs: %s', module.abis.map(function (a) { return a.cyan; }).join(', '))); this.logger.warn(__('Your application will most likely encounter issues')); } if (module.jarFile) { // read in the bindings try { module.bindings = this.getNativeModuleBindings(module.jarFile); if (!module.bindings) { logger.error(__('Module %s version %s is missing bindings json file', module.id.cyan, (module.manifest.version || 'latest').cyan) + '\n'); process.exit(1); } bindingsHashes.push(this.hash(JSON.stringify(module.bindings))); } catch (ex) { logger.error(__('The module "%s" has an invalid jar file: %s', module.id, module.jarFile) + '\n'); process.exit(1); } } this.nativeLibModules.push(module); } // scan the module for any CLI hooks cli.scanHooks(path.join(module.modulePath, 'hooks')); }, this); this.modulesManifestHash = this.hash(manifestHashes.length ? manifestHashes.sort().join(',') : ''); this.modulesNativeHash = this.hash(nativeHashes.length ? nativeHashes.sort().join(',') : ''); this.modulesBindingsHash = this.hash(bindingsHashes.length ? bindingsHashes.sort().join(',') : ''); // check if we have any conflicting jars var possibleConflicts = Object.keys(jarHashes).filter(function (jar) { return jarHashes[jar].length > 1; }); if (possibleConflicts.length) { var foundConflict = false; possibleConflicts.forEach(function (jar) { var modules = jarHashes[jar], maxlen = 0, h = {}; modules.forEach(function (m) { m.module.id.length > maxlen && (maxlen = m.module.id.length); h[m.hash] = 1; }); if (Object.keys(h).length > 1) { if (!foundConflict) { logger.error(__('Conflicting jar files detected:')); foundConflict = true; } logger.error(); logger.error(__('The following modules have different "%s" files', jar)); modules.forEach(function (m) { logger.error(__(' %s (version %s) (hash=%s)', appc.string.rpad(m.module.id, maxlen + 2), m.module.version, m.hash)); }); } }); if (foundConflict) { logger.error(); appc.string.wrap( __('You can either select a version of these modules where the conflicting jar file is the same or you can try copying the jar file from one module\'s "lib" folder to the other module\'s "lib" folder.'), config.get('cli.width', 100) ).split('\n').forEach(logger.error); logger.log(); process.exit(1); } } callback(); }.bind(this)); }.bind(this); }; AndroidBuilder.prototype.run = function run(logger, config, cli, finished) { Builder.prototype.run.apply(this, arguments); appc.async.series(this, [ function (next) { cli.emit('build.pre.construct', this, next); }, 'doAnalytics', 'initialize', 'loginfo', 'computeHashes', 'readBuildManifest', 'checkIfNeedToRecompile', 'getLastBuildState', function (next) { cli.emit('build.pre.compile', this, next); }, 'createBuildDirs', 'copyResources', 'generateRequireIndex', 'processTiSymbols', 'copyModuleResources', 'removeOldFiles', 'generateJavaFiles', 'generateAidl', // generate the i18n files after copyModuleResources to make sure the app_name isn't // overwritten by some module's strings.xml 'generateI18N', 'generateTheme', 'generateAndroidManifest', 'packageApp', // provide a hook event before javac function (next) { cli.emit('build.pre.build', this, next); }, // we only need to compile java classes if any files in src or gen changed 'compileJavaClasses', // provide a hook event after javac function (next) { cli.emit('build.post.build', this, next); }, // we only need to run proguard if any java classes have changed 'runProguard', // we only need to run the dexer if this.moduleJars or this.jarLibraries changes or // any files in this.buildBinClassesDir have changed or debugging/profiling toggled 'runDexer', 'createUnsignedApk', 'createSignedApk', 'zipAlignApk', 'writeBuildManifest', function (next) { if (!this.buildOnly && this.target == 'simulator') { var delta = appc.time.prettyDiff(this.cli.startTime, Date.now()); this.logger.info(__('Finished building the application in %s', delta.cyan)); } cli.emit('build.post.compile', this, next); }, function (next) { cli.emit('build.finalize', this, next); } ], finished); }; AndroidBuilder.prototype.doAnalytics = function doAnalytics(next) { var cli = this.cli, eventName = 'android.' + cli.argv.target; if (cli.argv.target == 'dist-playstore') { eventName = "android.distribute.playstore"; } else if (this.allowDebugging && this.debugPort) { eventName += '.debug'; } else if (this.allowProfiling && this.profilerPort) { eventName += '.profile'; } else { eventName += '.run'; } cli.addAnalyticsEvent(eventName, { dir: cli.argv['project-dir'], name: cli.tiapp.name, publisher: cli.tiapp.publisher, url: cli.tiapp.url, image: cli.tiapp.icon, appid: cli.tiapp.id, description: cli.tiapp.description, type: cli.argv.type, guid: cli.tiapp.guid, version: cli.tiapp.version, copyright: cli.tiapp.copyright, date: (new Date()).toDateString() }); next(); }; AndroidBuilder.prototype.initialize = function initialize(next) { var argv = this.cli.argv; this.appid = this.tiapp.id; this.appid.indexOf('.') == -1 && (this.appid = 'com.' + this.appid); this.classname = this.tiapp.name.split(/[^A-Za-z0-9_]/).map(function (word) { return appc.string.capitalize(word.toLowerCase()); }).join(''); /^[0-9]/.test(this.classname) && (this.classname = '_' + this.classname); this.buildOnly = argv['build-only']; var deviceId = this.deviceId = argv['device-id']; if (!this.buildOnly && this.target == 'emulator') { var emu = this.devices.filter(function (e) { return e.name == deviceId; }).shift(); if (!emu) { // sanity check this.logger.error(__('Unable to find Android emulator "%s"', deviceId) + '\n'); process.exit(0); } this.emulator = emu; } this.outputDir = argv['output-dir'] ? afs.resolvePath(argv['output-dir']) : null; // set the keystore to the dev keystore, if not already set this.keystore = argv.keystore; this.keystoreStorePassword = argv['store-password']; this.keystoreKeyPassword = argv['key-password']; if (!this.keystore) { this.keystore = path.join(this.platformPath, 'dev_keystore'); this.keystoreStorePassword = 'tirocks'; this.keystoreAlias = { name: 'tidev', sigalg: 'MD5withRSA' }; } var loadFromSDCardProp = this.tiapp.properties['ti.android.loadfromsdcard']; this.loadFromSDCard = loadFromSDCardProp && loadFromSDCardProp.value === true; var includeAllTiModulesProp = this.tiapp.properties['ti.android.include_all_modules']; if (includeAllTiModulesProp !== undefined) { this.includeAllTiModules = includeAllTiModulesProp.value; } // directories this.buildAssetsDir = path.join(this.buildDir, 'assets'); this.buildBinDir = path.join(this.buildDir, 'bin'); this.buildBinAssetsDir = path.join(this.buildBinDir, 'assets'); this.buildBinAssetsResourcesDir = path.join(this.buildBinAssetsDir, 'Resources'); this.buildBinClassesDir = path.join(this.buildBinDir, 'classes'); this.buildBinClassesDex = path.join(this.buildBinDir, 'dexfiles'); this.buildGenDir = path.join(this.buildDir, 'gen'); this.buildGenAppIdDir = path.join(this.buildGenDir, this.appid.split('.').join(path.sep)); this.buildResDir = path.join(this.buildDir, 'res'); this.buildResDrawableDir = path.join(this.buildResDir, 'drawable') this.buildSrcDir = path.join(this.buildDir, 'src'); this.templatesDir = path.join(this.platformPath, 'templates', 'build'); // files this.buildManifestFile = path.join(this.buildDir, 'build-manifest.json'); this.androidManifestFile = path.join(this.buildDir, 'AndroidManifest.xml'); var suffix = this.debugPort || this.profilerPort ? '-dev' + (this.debugPort ? '-debug' : '') + (this.profilerPort ? '-profiler' : '') : ''; this.unsignedApkFile = path.join(this.buildBinDir, 'app-unsigned' + suffix + '.apk'); this.apkFile = path.join(this.buildBinDir, this.tiapp.name + suffix + '.apk'); next(); }; AndroidBuilder.prototype.loginfo = function loginfo(next) { this.logger.debug(__('Titanium SDK Android directory: %s', this.platformPath.cyan)); this.logger.info(__('Deploy type: %s', this.deployType.cyan)); this.logger.info(__('Building for target: %s', this.target.cyan)); if (this.buildOnly) { this.logger.info(__('Performing build only')); } else { if (this.target == 'emulator') { this.logger.info(__('Building for emulator: %s', this.deviceId.cyan)); } else if (this.target == 'device') { this.logger.info(__('Building for device: %s', this.deviceId.cyan)); } } this.logger.info(__('Targeting Android SDK API: %s', String(this.targetSDK + (this.targetSDK !== this.realTargetSDK ? ' (' + this.realTargetSDK + ')' : '')).cyan)); this.logger.info(__('Building for the following architectures: %s', this.abis.join(', ').cyan)); this.logger.info(__('Signing with keystore: %s', (this.keystore + ' (' + this.keystoreAlias.name + ')').cyan)); this.logger.debug(__('App ID: %s', this.appid.cyan)); this.logger.debug(__('Classname: %s', this.classname.cyan)); if (this.allowDebugging && this.debugPort) { this.logger.info(__('Debugging enabled via debug port: %s', String(this.debugPort).cyan)); } else { this.logger.info(__('Debugging disabled')); } if (this.allowProfiling && this.profilerPort) { this.logger.info(__('Profiler enabled via profiler port: %s', String(this.profilerPort).cyan)); } else { this.logger.info(__('Profiler disabled')); } next(); }; AndroidBuilder.prototype.computeHashes = function computeHashes(next) { // modules this.modulesHash = !Array.isArray(this.tiapp.modules) ? '' : this.hash(this.tiapp.modules.filter(function (m) { return !m.platform || /^android|commonjs$/.test(m.platform); }).map(function (m) { return m.id + ',' + m.platform + ',' + m.version; }).join('|')); // tiapp.xml properties, activities, and services this.propertiesHash = this.hash(this.tiapp.properties ? JSON.stringify(this.tiapp.properties) : ''); var android = this.tiapp.android; this.activitiesHash = this.hash(android && android.application && android.application ? JSON.stringify(android.application.activities) : ''); this.servicesHash = this.hash(android && android.services ? JSON.stringify(android.services) : ''); var self = this; function walk(dir, re) { var hashes = []; fs.existsSync(dir) && fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { var stat = fs.statSync(file); if (stat.isFile() && re.test(name)) { hashes.push(self.hash(fs.readFileSync(file).toString())); } else if (stat.isDirectory()) { hashes = hashes.concat(walk(file, re)); } } }); return hashes; } next(); }; AndroidBuilder.prototype.readBuildManifest = function readBuildManifest(next) { // read the build manifest from the last build, if exists, so we // can determine if we need to do a full rebuild this.buildManifest = {}; if (fs.existsSync(this.buildManifestFile)) { try { this.buildManifest = JSON.parse(fs.readFileSync(this.buildManifestFile)) || {}; this.prevJarLibHash = this.buildManifest.jarLibHash || ''; } catch (e) {} } next(); }; AndroidBuilder.prototype.checkIfShouldForceRebuild = function checkIfShouldForceRebuild() { var manifest = this.buildManifest; if (this.cli.argv.force) { this.logger.info(__('Forcing rebuild: %s flag was set', '--force'.cyan)); return true; } if (!fs.existsSync(this.buildManifestFile)) { this.logger.info(__('Forcing rebuild: %s does not exist', this.buildManifestFile.cyan)); return true; } if (!fs.existsSync(this.androidManifestFile)) { this.logger.info(__('Forcing rebuild: %s does not exist', this.androidManifestFile.cyan)); return true; } // check if the target changed if (this.target != manifest.target) { this.logger.info(__('Forcing rebuild: target changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.target)); this.logger.info(' ' + __('Now: %s', this.target)); return true; } // check if the deploy type changed if (this.deployType != manifest.deployType) { this.logger.info(__('Forcing rebuild: deploy type changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.deployType)); this.logger.info(' ' + __('Now: %s', this.deployType)); return true; } // check if the classname changed if (this.classname != manifest.classname) { this.logger.info(__('Forcing rebuild: classname changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.classname)); this.logger.info(' ' + __('Now: %s', this.classname)); return true; } // if encryption is enabled, then we must recompile the java files if (this.encryptJS) { this.logger.info(__('Forcing rebuild: JavaScript files need to be re-encrypted')); return true; } // if encryptJS changed, then we need to recompile the java files if (this.encryptJS != manifest.encryptJS) { this.logger.info(__('Forcing rebuild: JavaScript encryption flag changed')); this.logger.info(' ' + __('Was: %s', manifest.encryptJS)); this.logger.info(' ' + __('Now: %s', this.encryptJS)); return true; } // check if the titanium sdk paths are different if (this.platformPath != manifest.platformPath) { this.logger.info(__('Forcing rebuild: Titanium SDK path changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.platformPath)); this.logger.info(' ' + __('Now: %s', this.platformPath)); return true; } // check the git hashes are different if (!manifest.gitHash || manifest.gitHash != ti.manifest.githash) { this.logger.info(__('Forcing rebuild: githash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.gitHash)); this.logger.info(' ' + __('Now: %s', ti.manifest.githash)); return true; } // check if the modules hashes are different if (this.modulesHash != manifest.modulesHash) { this.logger.info(__('Forcing rebuild: modules hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesHash)); this.logger.info(' ' + __('Now: %s', this.modulesHash)); return true; } if (this.modulesManifestHash != manifest.modulesManifestHash) { this.logger.info(__('Forcing rebuild: module manifest hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesManifestHash)); this.logger.info(' ' + __('Now: %s', this.modulesManifestHash)); return true; } if (this.modulesNativeHash != manifest.modulesNativeHash) { this.logger.info(__('Forcing rebuild: native modules hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesNativeHash)); this.logger.info(' ' + __('Now: %s', this.modulesNativeHash)); return true; } if (this.modulesBindingsHash != manifest.modulesBindingsHash) { this.logger.info(__('Forcing rebuild: native modules bindings hash changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.modulesBindingsHash)); this.logger.info(' ' + __('Now: %s', this.modulesBindingsHash)); return true; } // next we check if any tiapp.xml values changed so we know if we need to reconstruct the main.m if (this.tiapp.name != manifest.name) { this.logger.info(__('Forcing rebuild: tiapp.xml project name changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.name)); this.logger.info(' ' + __('Now: %s', this.tiapp.name)); return true; } if (this.tiapp.id != manifest.id) { this.logger.info(__('Forcing rebuild: tiapp.xml app id changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.id)); this.logger.info(' ' + __('Now: %s', this.tiapp.id)); return true; } if (!this.tiapp.analytics != !manifest.analytics) { this.logger.info(__('Forcing rebuild: tiapp.xml analytics flag changed since last build')); this.logger.info(' ' + __('Was: %s', !!manifest.analytics)); this.logger.info(' ' + __('Now: %s', !!this.tiapp.analytics)); return true; } if (this.tiapp.publisher != manifest.publisher) { this.logger.info(__('Forcing rebuild: tiapp.xml publisher changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.publisher)); this.logger.info(' ' + __('Now: %s', this.tiapp.publisher)); return true; } if (this.tiapp.url != manifest.url) { this.logger.info(__('Forcing rebuild: tiapp.xml url changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.url)); this.logger.info(' ' + __('Now: %s', this.tiapp.url)); return true; } if (this.tiapp.version != manifest.version) { this.logger.info(__('Forcing rebuild: tiapp.xml version changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.version)); this.logger.info(' ' + __('Now: %s', this.tiapp.version)); return true; } if (this.tiapp.description != manifest.description) { this.logger.info(__('Forcing rebuild: tiapp.xml description changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.description)); this.logger.info(' ' + __('Now: %s', this.tiapp.description)); return true; } if (this.tiapp.copyright != manifest.copyright) { this.logger.info(__('Forcing rebuild: tiapp.xml copyright changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.copyright)); this.logger.info(' ' + __('Now: %s', this.tiapp.copyright)); return true; } if (this.tiapp.guid != manifest.guid) { this.logger.info(__('Forcing rebuild: tiapp.xml guid changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.guid)); this.logger.info(' ' + __('Now: %s', this.tiapp.guid)); return true; } if (this.tiapp.icon != manifest.icon) { this.logger.info(__('Forcing rebuild: tiapp.xml icon changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.icon)); this.logger.info(' ' + __('Now: %s', this.tiapp.icon)); return true; } if (this.tiapp.fullscreen != manifest.fullscreen) { this.logger.info(__('Forcing rebuild: tiapp.xml fullscreen changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.fullscreen)); this.logger.info(' ' + __('Now: %s', this.tiapp.fullscreen)); return true; } if (this.tiapp.navbarHidden != manifest.navbarHidden) { this.logger.info(__('Forcing rebuild: tiapp.xml navbar-hidden changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.navbarHidden)); this.logger.info(' ' + __('Now: %s', this.tiapp.navbarHidden)); return true; } if (this.minSDK != manifest.minSDK) { this.logger.info(__('Forcing rebuild: Android minimum SDK changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.minSDK)); this.logger.info(' ' + __('Now: %s', this.minSDK)); return true; } if (this.targetSDK != manifest.targetSDK) { this.logger.info(__('Forcing rebuild: Android target SDK changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.targetSDK)); this.logger.info(' ' + __('Now: %s', this.targetSDK)); return true; } if (this.propertiesHash != manifest.propertiesHash) { this.logger.info(__('Forcing rebuild: tiapp.xml properties changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.propertiesHash)); this.logger.info(' ' + __('Now: %s', this.propertiesHash)); return true; } if (this.activitiesHash != manifest.activitiesHash) { this.logger.info(__('Forcing rebuild: Android activites in tiapp.xml changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.activitiesHash)); this.logger.info(' ' + __('Now: %s', this.activitiesHash)); return true; } if (this.servicesHash != manifest.servicesHash) { this.logger.info(__('Forcing rebuild: Android services in tiapp.xml SDK changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.servicesHash)); this.logger.info(' ' + __('Now: %s', this.servicesHash)); return true; } if (this.config.get('android.mergeCustomAndroidManifest', false) != manifest.mergeCustomAndroidManifest) { this.logger.info(__('Forcing rebuild: mergeCustomAndroidManifest config has changed since last build')); this.logger.info(' ' + __('Was: %s', manifest.mergeCustomAndroidManifest)); this.logger.info(' ' + __('Now: %s', this.config.get('android.mergeCustomAndroidManifest', false))); return true; } return false; }; AndroidBuilder.prototype.checkIfNeedToRecompile = function checkIfNeedToRecompile(next) { // check if we need to do a rebuild this.forceRebuild = this.checkIfShouldForceRebuild(); if (this.forceRebuild && fs.existsSync(this.buildGenAppIdDir)) { wrench.rmdirSyncRecursive(this.buildGenAppIdDir); } fs.existsSync(this.buildGenAppIdDir) || wrench.mkdirSyncRecursive(this.buildGenAppIdDir); // now that we've read the build manifest, delete it so if this build // becomes incomplete, the next build will be a full rebuild fs.existsSync(this.buildManifestFile) && fs.unlinkSync(this.buildManifestFile); next(); }; AndroidBuilder.prototype.getLastBuildState = function getLastBuildState(next) { var lastBuildFiles = this.lastBuildFiles = {}; // walk the entire build dir and build a map of all files (function walk(dir) { fs.existsSync(dir) && fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file) && fs.statSync(file).isDirectory()) { walk(file); } else { lastBuildFiles[file] = 1; } }); }(this.buildDir)); next(); }; AndroidBuilder.prototype.createBuildDirs = function createBuildDirs(next) { // Make sure we have an app.js. This used to be validated in validate(), but since plugins like // Alloy generate an app.js, it may not have existed during validate(), but should exist now // that build.pre.compile was fired. ti.validateAppJsExists(this.projectDir, this.logger, 'android'); fs.existsSync(this.buildDir) || wrench.mkdirSyncRecursive(this.buildDir); // make directories if they don't already exist var dir = this.buildAssetsDir; if (this.forceRebuild) { fs.existsSync(dir) && wrench.rmdirSyncRecursive(dir); Object.keys(this.lastBuildFiles).forEach(function (file) { if (file.indexOf(dir + '/') == 0) { delete this.lastBuildFiles[file]; } }, this); wrench.mkdirSyncRecursive(dir); } else if (!fs.existsSync(dir)) { wrench.mkdirSyncRecursive(dir); } // we always destroy and rebuild the res directory if (fs.existsSync(this.buildResDir)) { wrench.rmdirSyncRecursive(this.buildResDir); } wrench.mkdirSyncRecursive(this.buildResDir); fs.existsSync(dir = this.buildBinAssetsResourcesDir) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = path.join(this.buildDir, 'gen')) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = path.join(this.buildDir, 'lib')) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = this.buildResDrawableDir) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = path.join(this.buildResDir, 'values')) || wrench.mkdirSyncRecursive(dir); fs.existsSync(dir = this.buildSrcDir) || wrench.mkdirSyncRecursive(dir); // create the deploy.json file which contains debugging/profiling info var deployJsonFile = path.join(this.buildBinAssetsDir, 'deploy.json'), deployData = { debuggerEnabled: !!this.debugPort, debuggerPort: this.debugPort || -1, profilerEnabled: !!this.profilerPort, profilerPort: this.profilerPort || -1 }; fs.existsSync(deployJsonFile) && fs.unlinkSync(deployJsonFile); if (deployData.debuggerEnabled || deployData.profilerEnabled) { fs.writeFileSync(deployJsonFile, JSON.stringify(deployData)); } next(); }; AndroidBuilder.prototype.copyResources = function copyResources(next) { var ignoreDirs = this.ignoreDirs, ignoreFiles = this.ignoreFiles, extRegExp = /\.(\w+)$/, drawableRegExp = /^images\/(high|medium|low|res\-[^\/]+)(\/(.*))/, drawableDpiRegExp = /^(high|medium|low)$/, drawableExtRegExp = /((\.9)?\.(png|jpg))$/, splashScreenRegExp = /^default\.(9\.png|png|jpg)$/, relSplashScreenRegExp = /^default\.(9\.png|png|jpg)$/, drawableResources = {}, jsFiles = {}, moduleResPackages = this.moduleResPackages = [], jsFilesToEncrypt = this.jsFilesToEncrypt = [], htmlJsFiles = this.htmlJsFiles = {}, symlinkFiles = process.platform != 'win32' && this.config.get('android.symlinkResources', true), _t = this; function copyDir(opts, callback) { if (opts && opts.src && fs.existsSync(opts.src) && opts.dest) { opts.origSrc = opts.src; opts.origDest = opts.dest; recursivelyCopy.call(this, opts.src, opts.dest, opts.ignoreRootDirs, opts, callback); } else { callback(); } } function copyFile(from, to, next) { var d = path.dirname(to); fs.existsSync(d) || wrench.mkdirSyncRecursive(d); if (fs.existsSync(to)) { _t.logger.warn(__('Overwriting file %s', to.cyan)); } if (symlinkFiles) { fs.existsSync(to) && fs.unlinkSync(to); this.logger.debug(__('Symlinking %s => %s', from.cyan, to.cyan)); if (next) { fs.symlink(from, to, next); } else { fs.symlinkSync(from, to); } } else { this.logger.debug(__('Copying %s => %s', from.cyan, to.cyan)); if (next) { fs.readFile(from, function (err, data) { if (err) throw err; fs.writeFile(to, data, next); }); } else { fs.writeFileSync(to, fs.readFileSync(from)); } } } function recursivelyCopy(src, dest, ignoreRootDirs, opts, done) { var files; if (fs.statSync(src).isDirectory()) { files = fs.readdirSync(src); } else { // we have a file, so fake a directory listing files = [ path.basename(src) ]; src = path.dirname(src); } async.whilst( function () { return files.length; }, function (next) { var filename = files.shift(), destDir = dest, from = path.join(src, filename), to = path.join(destDir, filename); // check that the file actually exists and isn't a broken symlink if (!fs.existsSync(from)) return next(); var isDir = fs.statSync(from).isDirectory(); // check if we are ignoring this file if ((isDir && ignoreRootDirs && ignoreRootDirs.indexOf(filename) != -1) || (isDir ? ignoreDirs : ignoreFiles).test(filename)) { _t.logger.debug(__('Ignoring %s', from.cyan)); return next(); } // if this is a directory, recurse if (isDir) { setImmediate(function () { recursivelyCopy.call(_t, from, path.join(destDir, filename), null, opts, next); }); return; } // we have a file, now we need to see what sort of file // check if it's a drawable resource var relPath = from.replace(opts.origSrc, '').replace(/\\/g, '/').replace(/^\//, ''), m = relPath.match(drawableRegExp), isDrawable = false; if (m && m.length >= 4 && m[3]) { var destFilename = m[3].toLowerCase(), name = destFilename.replace(drawableExtRegExp, ''), extMatch = destFilename.match(drawableExtRegExp), origExt = extMatch && extMatch[1] || '', hashExt = extMatch && extMatch.length > 2 ? '.' + extMatch[3] : ''; destDir = path.join( _t.buildResDir, drawableDpiRegExp.test(m[1]) ? 'drawable-' + m[1][0] + 'dpi' : 'drawable-' + m[1].substring(4) ); if (splashScreenRegExp.test(filename)) { // we have a splash screen image to = path.join(destDir, 'background' + origExt); } else { to = path.join(destDir, name.replace(/[^a-z0-9_]/g, '_').substring(0, 80) + '_' + _t.hash(name + hashExt).substring(0, 10) + origExt); } isDrawable = true; } else if (m = relPath.match(relSplashScreenRegExp)) { // we have a splash screen // if it's a 9 patch, then the image goes in drawable-nodpi, not drawable if (m[1] == '9.png') { destDir = path.join(_t.buildResDir, 'drawable-nodpi'); to = path.join(destDir, filename.replace('default.', 'background.')); } else { destDir = _t.buildResDrawableDir; to = path.join(_t.buildResDrawableDir, filename.replace('default.', 'background.')); } isDrawable = true; } if (isDrawable) { var _from = from.replace(_t.projectDir, '').substring(1), _to = to.replace(_t.buildResDir, '').replace(drawableExtRegExp, '').substring(1); if (drawableResources[_to]) { _t.logger.error(__('Found conflicting resources:')); _t.logger.error(' ' + drawableResources[_to]); _t.logger.error(' ' + from.replace(_t.projectDir, '').substring(1)); _t.logger.error(__('You cannot have resources that resolve to the same resource entry name') + '\n'); process.exit(1); } drawableResources[_to] = _from; } // if the destination directory does not exists, create it fs.existsSync(destDir) || wrench.mkdirSyncRecursive(destDir); var ext = filename.match(extRegExp); if (ext && ext[1] != 'js') { // we exclude js files because we'll check if they need to be removed after all files have been copied delete _t.lastBuildFiles[to]; } switch (ext && ext[1]) { case 'css': // if we encounter a css file, check if we should minify it if (_t.minifyCSS) { _t.logger.debug(__('Copying and minifying %s => %s', from.cyan, to.cyan)); fs.readFile(from, function (err, data) { if (err) throw err; fs.writeFile(to, new CleanCSS({ processImport: false }).minify(data.toString()).styles, next); }); } else { copyFile.call(_t, from, to, next); } break; case 'html': // find all js files referenced in this html file var relPath = from.replace(opts.origSrc, '').replace(/\\/g, '/').replace(/^\//, '').split('/'); relPath.pop(); // remove the filename relPath = relPath.join('/'); jsanalyze.analyzeHtmlFile(from, relPath).forEach(function (file) { htmlJsFiles[file] = 1; }); _t.cli.createHook('build.android.copyResource', _t, function (from, to, cb) { copyFile.call(_t, from, to, cb); })(from, to, next); break; case 'js': // track each js file so we can copy/minify later // we use the destination file name minus the path to the assets dir as the id // which will eliminate dupes var id = to.replace(opts.origDest, opts.prefix ? opts.prefix + '/' : '').replace(/\\/g, '/').replace(/^\//, ''); if (!jsFiles[id] || !opts || !opts.onJsConflict || opts.onJsConflict(from, to, id)) { jsFiles[id] = from; } next(); break; case 'xml': if (_t.xmlMergeRegExp.test(filename)) { _t.cli.createHook('build.android.copyResource', _t, function (from, to, cb) { _t.writeXmlFile(from, to); cb(); })(from, to, next); break; } default: // normal file, just copy it into the build/android/bin/assets directory _t.cli.createHook('build.android.copyResource', _t, function (from, to, cb) { copyFile.call(_t, from, to, cb); })(from, to, next); } }, done ); } function warnDupeDrawableFolders(resourceDir) { var dir = path.join(resourceDir, 'images'); ['high', 'medium', 'low'].forEach(function (dpi) { var oldDir = path.join(dir, dpi), newDir = path.join(dir, 'res-' + dpi[0] + 'dpi'); if (fs.existsSync(oldDir) && fs.existsSync(newDir)) { oldDir = oldDir.replace(this.projectDir, '').replace(/^\//, ''); newDir = newDir.replace(this.projectDir, '').replace(/^\//, ''); this.logger.warn(__('You have both an %s folder and an %s folder', oldDir.cyan, newDir.cyan)); this.logger.warn(__('Files from both of these folders will end up in %s', ('res/drawable-' + dpi[0]+ 'dpi').cyan)); this.logger.warn(__('If two files are named the same, there is no guarantee which one will be copied last and therefore be the one the application uses')); this.logger.warn(__('You should use just one of these folders to avoid conflicts')); } }, this); } var tasks = [ // first task is to copy all files in the Resources directory, but ignore // any directory that is the name of a known platform function (cb) { var src = path.join(this.projectDir, 'Resources'); warnDupeDrawableFolders.call(this, src); _t.logger.debug(__('Copying %s', src.cyan)); copyDir.call(this, { src: src, dest: this.buildBinAssetsResourcesDir, ignoreRootDirs: ti.availablePlatformsNames }, cb); }, // next copy all files from the Android specific Resources directory function (cb) { var src = path.join(this.projectDir, 'Resources', 'android'); warnDupeDrawableFolders.call(this, src); _t.logger.debug(__('Copying %s', src.cyan)); copyDir.call(this, { src: src, dest: this.buildBinAssetsResourcesDir }, cb); } ]; // copy all commonjs modules this.commonJsModules.forEach(function (module) { // copy the main module tasks.push(function (cb) { _t.logger.debug(__('Copying %s', module.modulePath.cyan)); copyDir.call(this, { src: module.modulePath, // Copy under subfolder named after module.id dest: path.join(this.buildBinAssetsResourcesDir, path.basename(module.id)), // Don't copy files under apidoc, docs, documentation, example or assets (assets is handled below) ignoreRootDirs: ['apidoc', 'documentation', 'docs', 'example', 'assets'], // Make note that files are copied relative to the module.id folder at dest // so that we don't see clashes between module1/index.js and module2/index.js prefix: module.id, onJsConflict: function (src, dest, id) { this.logger.error(__('There is a project resource "%s" that conflicts with a CommonJS module', id)); this.logger.error(__('Please rename the file, then rebuild') + '\n'); process.exit(1); }.bind(this) }, cb); }); // copy the assets tasks.push(function (cb) { var src = path.join(module.modulePath, 'assets'); _t.logger.debug(__('Copying %s', src.cyan)); copyDir.call(this, { src: src, dest: path.join(this.buildBinAssetsResourcesDir, 'modules', module.id) }, cb); }); }); //get the respackgeinfo files if they exist this.modules.forEach(function (module) { var respackagepath = path.join(module.modulePath, 'respackageinfo'); if (fs.existsSync(respackagepath)) { var data = fs.readFileSync(respackagepath).toString().split('\n').shift().trim(); if(data.length > 0) { this.moduleResPackages.push(data); } } }, this); var platformPaths = []; // WARNING! This is pretty dangerous, but yes, we're intentionally copying // every file from platform/android and all modules into the build dir this.modules.forEach(function (module) { platformPaths.push(path.join(module.modulePath, 'platform', 'android')); }); platformPaths.push(path.join(this.projectDir, 'platform', 'android')); platformPaths.forEach(function (dir) { if (fs.existsSync(dir)) { tasks.push(function (cb) { copyDir.call(this, { src: dir, dest: this.buildDir }, cb); }); } }, this); appc.async.series(this, tasks, function (err, results) { var templateDir = path.join(this.platformPath, 'templates', 'app', 'default', 'template', 'Resources', 'android'); // if an app icon hasn't been copied, copy the default one var destIcon = path.join(this.buildBinAssetsResourcesDir, this.tiapp.icon); if (!fs.existsSync(destIcon)) { copyFile.call(this, path.join(templateDir, 'appicon.png'), destIcon); } delete this.lastBuildFiles[destIcon]; var destIcon2 = path.join(this.buildResDrawableDir, this.tiapp.icon); if (!fs.existsSync(destIcon2)) { copyFile.call(this, destIcon, destIcon2); } delete this.lastBuildFiles[destIcon2]; // make sure we have a splash screen var backgroundRegExp = /^background(\.9)?\.(png|jpg)$/, destBg = path.join(this.buildResDrawableDir, 'background.png'), nodpiDir = path.join(this.buildResDir, 'drawable-nodpi'); if (!fs.readdirSync(this.buildResDrawableDir).some(function (name) { if (backgroundRegExp.test(name)) { delete this.lastBuildFiles[path.join(this.buildResDrawableDir, name)]; return true; } }, this)) { // no background image in drawable, but what about drawable-nodpi? if (!fs.existsSync(nodpiDir) || !fs.readdirSync(nodpiDir).some(function (name) { if (backgroundRegExp.test(name)) { delete this.lastBuildFiles[path.join(nodpiDir, name)]; return true; } }, this)) { delete this.lastBuildFiles[destBg]; copyFile.call(this, path.join(templateDir, 'default.png'), destBg); } } // copy js files into assets directory and minify if needed this.logger.info(__('Processing JavaScript files')); appc.async.series(this, Object.keys(jsFiles).map(function (id) { return function (done) { var from = jsFiles[id], to = path.join(this.buildBinAssetsResourcesDir, id); if (htmlJsFiles[id]) { // this js file is referenced from an html file, so don't minify or encrypt delete this.lastBuildFiles[to]; return copyFile.call(this, from, to, done); } // we have a js file that may be minified or encrypted // if we're encrypting the JavaScript, copy the files to the assets dir // for processing later if (this.encryptJS) { to = path.join(this.buildAssetsDir, id); jsFilesToEncrypt.push(id); } delete this.lastBuildFiles[to]; try { this.cli.createHook('build.android.copyResource', this, function (from, to, cb) { // parse the AST var r = jsanalyze.analyzeJsFile(from, { minify: this.minifyJS }); // we want to sort by the "to" filename so that we correctly handle file overwriting this.tiSymbols[to] = r.symbols; var dir = path.dirname(to); fs.existsSync(dir) || wrench.mkdirSyncRecursive(dir); if (this.minifyJS) { this.logger.debug(__('Copying and minifying %s => %s', from.cyan, to.cyan)); this.cli.createHook('build.android.compileJsFile', this, function (r, from, to, cb2) { fs.writeFile(to, r.contents, cb2); })(r, from, to, cb); } else if (symlinkFiles) { copyFile.call(this, from, to, cb); } else { // we've already read in the file, so just write the original contents this.logger.debug(__('Copying %s => %s', from.cyan, to.cyan)); fs.writeFile(to, r.contents, cb); } })(from, to, done); } catch (ex) { ex.message.split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } }; }), function () { // write the properties file var appPropsFile = path.join(this.encryptJS ? this.buildAssetsDir : this.buildBinAssetsResourcesDir, '_app_props_.json'), props = {}; Object.keys(this.tiapp.properties).forEach(function (prop) { props[prop] = this.tiapp.properties[prop].value; }, this); fs.writeFileSync( appPropsFile, JSON.stringify(props) ); this.encryptJS && jsFilesToEncrypt.push('_app_props_.json'); delete this.lastBuildFiles[appPropsFile]; if (!jsFilesToEncrypt.length) { // nothing to encrypt, continue return next(); } // figure out which titanium prep to run var titaniumPrep = 'titanium_prep'; if (process.platform == 'darwin') { titaniumPrep += '.macos'; if (appc.version.lt(this.jdkInfo.version, '1.7.0')) { titaniumPrep += '.jdk16'; } } else if (process.platform == 'win32') { titaniumPrep += '.win32.exe'; } else if (process.platform == 'linux') { titaniumPrep += '.linux' + (process.arch == 'x64' ? '64' : '32'); } // encrypt the javascript var titaniumPrepHook = this.cli.createHook('build.android.titaniumprep', this, function (exe, args, opts, done) { this.logger.info(__('Encrypting JavaScript files: %s', (exe + ' "' + args.slice(1).join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { return done({ code: code, msg: err.trim() }); } // write the encrypted JS bytes to the generated Java file fs.writeFileSync( path.join(this.buildGenAppIdDir, 'AssetCryptImpl.java'), ejs.render(fs.readFileSync(path.join(this.templatesDir, 'AssetCryptImpl.java')).toString(), { appid: this.appid, encryptedAssets: out }) ); done(); }.bind(this)); }), args = [ this.tiapp.guid, this.appid, this.buildAssetsDir ].concat(jsFilesToEncrypt), opts = { env: appc.util.mix({}, process.env, { // we force the JAVA_HOME so that titaniumprep doesn't complain 'JAVA_HOME': this.jdkInfo.home }) }, fatal = function fatal(err) { this.logger.error(__('Failed to encrypt JavaScript files')); err.msg.split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); }.bind(this); titaniumPrepHook( path.join(this.platformPath, titaniumPrep), args.slice(0), opts, function (err) { if (!err) { return next(); } if (process.platform !== 'win32' || !/jvm\.dll/i.test(err.msg)) { fatal(err); } // windows 64-bit failed, try again using 32-bit this.logger.debug(__('32-bit titanium prep failed, trying again using 64-bit')); titaniumPrep = 'titanium_prep.win64.exe'; titaniumPrepHook( path.join(this.platformPath, titaniumPrep), args, opts, function (err) { if (err) { fatal(err); } next(); } ); }.bind(this) ); }); }); }; AndroidBuilder.prototype.generateRequireIndex = function generateRequireIndex(callback) { var index = {}, binAssetsDir = this.buildBinAssetsDir.replace(/\\/g, '/'), destFile = path.join(binAssetsDir, 'index.json'); (function walk(dir) { fs.readdirSync(dir).forEach(function (filename) { var file = path.join(dir, filename); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { walk(file); } else if (/\.js(on)?$/.test(filename)) { index[file.replace(/\\/g, '/').replace(binAssetsDir + '/', '')] = 1; } } }); }(this.buildBinAssetsResourcesDir)); this.jsFilesToEncrypt.forEach(function (file) { index['Resources/' + file.replace(/\\/g, '/')] = 1; }); delete index['Resources/_app_props_.json']; fs.existsSync(destFile) && fs.unlinkSync(destFile); fs.writeFile(destFile, JSON.stringify(index), callback); }; AndroidBuilder.prototype.getNativeModuleBindings = function getNativeModuleBindings(jarFile) { var zip = new AdmZip(jarFile), zipEntries = zip.getEntries(), i = 0, len = zipEntries.length, pathName = 'org/appcelerator/titanium/bindings/', pathNameLen = pathName.length, entry, name; for (; i < len; i++) { entry = zipEntries[i]; name = entry.entryName.toString(); if (name.length > pathNameLen && name.indexOf(pathName) == 0) { try { return JSON.parse(entry.getData()); } catch (e) {} return; } } }; AndroidBuilder.prototype.processTiSymbols = function processTiSymbols(next) { var depMap = JSON.parse(fs.readFileSync(path.join(this.platformPath, 'dependency.json'))), modulesMap = JSON.parse(fs.readFileSync(path.join(this.platformPath, 'modules.json'))), modulesPath = path.join(this.platformPath, 'modules'), moduleBindings = {}, externalChildModules = {}, moduleJarMap = {}, tiNamespaces = this.tiNamespaces = {}, // map of namespace => titanium functions (i.e. ui => createWindow) jarLibraries = this.jarLibraries = {}, resPackages = this.resPackages = {}, appModules = this.appModules = [], // also used in the App.java template appModulesMap = {}, customModules = this.customModules = [], ignoreNamespaces = /^(addEventListener|builddate|buildhash|fireEvent|include|_JSON|name|removeEventListener|userAgent|version)$/; // reorg the modules map by module => jar instead of jar => modules Object.keys(modulesMap).forEach(function (jar) { modulesMap[jar].forEach(function (name) { moduleJarMap[name.toLowerCase()] = jar; }); }); // load all module bindings fs.readdirSync(modulesPath).forEach(function (filename) { var file = path.join(modulesPath, filename); if (fs.existsSync(file) && fs.statSync(file).isFile() && /\.jar$/.test(filename)) { var bindings = this.getNativeModuleBindings(file); if (bindings) { Object.keys(bindings.modules).forEach(function (moduleClass) { if (bindings.proxies[moduleClass]) { moduleBindings[moduleClass] = bindings.modules[moduleClass]; moduleBindings[moduleClass].fullAPIName = bindings.proxies[moduleClass].proxyAttrs.fullAPIName; } else { // parent module is external, so the reference needs to be injected at boot time Array.isArray(externalChildModules[moduleClass]) || (externalChildModules[moduleClass] = []); externalChildModules[moduleClass] = externalChildModules[moduleClass].concat(bindings.modules[moduleClass].childModules); } }); } } }, this); // get the v8 runtime jar file(s) if (depMap && depMap.runtimes && depMap.runtimes.v8) { var v8 = depMap.runtimes.v8; (Array.isArray(v8) ? v8 : [ v8 ]).forEach(function (jar) { if (fs.existsSync(jar = path.join(this.platformPath, jar))) { this.logger.debug(__('Adding library %s', jar.cyan)); jarLibraries[jar] = 1; } }, this); } function addTitaniumLibrary(namespace) { namespace = namespace.toLowerCase(); if (ignoreNamespaces.test(namespace) || tiNamespaces[namespace]) return; tiNamespaces[namespace] = []; var jar = moduleJarMap[namespace]; if (jar) { jar = jar == 'titanium.jar' ? path.join(this.platformPath, jar) : path.join(this.platformPath, 'modules', jar); if (fs.existsSync(jar) && !jarLibraries[jar]) { this.logger.debug(__('Adding library %s', jar.cyan)); jarLibraries[jar] = 1; } } else { this.logger.debug(__('Unknown namespace %s, skipping', namespace.cyan)); } depMap.libraries[namespace] && depMap.libraries[namespace].forEach(function (jar) { if (fs.existsSync(jar = path.join(this.platformPath, jar)) && !jarLibraries[jar]) { this.logger.debug(__('Adding dependency library %s', jar.cyan)); jarLibraries[jar] = 1; } }, this); depMap.dependencies[namespace] && depMap.dependencies[namespace].forEach(addTitaniumLibrary, this); } // get all required titanium modules depMap.required.forEach(addTitaniumLibrary, this); // if we need to include all titanium modules, then do it if (this.includeAllTiModules) { Object.keys(moduleJarMap).forEach(addTitaniumLibrary, this); } // for each Titanium symbol found when we copied the JavaScript files, we need // extract the Titanium namespace and make sure we include its jar library Object.keys(this.tiSymbols).forEach(function (file) { this.tiSymbols[file].forEach(function (symbol) { var parts = symbol.split('.').slice(0, -1), // strip last part which should be the method or property namespace; // add this namespace and all parent namespaces while (parts.length) { namespace = parts.join('.'); if (namespace) { addTitaniumLibrary.call(this, namespace); if (tiNamespaces[namespace]) { // track each method/property tiNamespaces[namespace].push(parts[parts.length - 1]); } } parts.pop(); } }, this); }, this); function createModuleDescriptor(namespace) { var results = { 'api_name': '', 'class_name': '', 'bindings': tiNamespaces[namespace], 'external_child_modules': [], 'on_app_create': null }, moduleBindingKeys = Object.keys(moduleBindings), len = moduleBindingKeys.length, i, name, extChildModule; for (i = 0; i < len; i++) { name = moduleBindingKeys[i]; if (moduleBindings[name].fullAPIName.toLowerCase() == namespace) { results['api_name'] = moduleBindings[name].fullAPIName results['class_name'] = name; if (moduleBindings[name]['on_app_create']) { results['on_app_create'] = moduleBindings[name]['on_app_create']; } break; } } // check if we found the api name and if not bail if (!results['api_name']) return; if (extChildModule = externalChildModules[results['class_name']]) { for (i = 0, len = extChildModule.length; i < len; i++) { if (tiNamespaces[extChildModule[i].fullAPIName.toLowerCase()]) { results['external_child_modules'].push(extChildModule[i]); break; } } } appModulesMap[results['api_name'].toLowerCase()] = 1; return results; } // build the list of modules for the templates Object.keys(tiNamespaces).map(createModuleDescriptor).forEach(function (m) { m && appModules.push(m); }); this.modules.forEach(function (module) { // check if the module has a metadata.json (which most native-wrapped CommonJS // modules should), then make sure those Titanium namespaces are loaded var metadataFile = path.join(module.modulePath, 'metadata.json'), metadata; if (fs.existsSync(metadataFile)) { metadata = JSON.parse(fs.readFileSync(metadataFile)); if (metadata && typeof metadata == 'object' && Array.isArray(metadata.exports)) { metadata.exports.forEach(function (namespace) { addTitaniumLibrary.call(this, namespace); }, this); } else { metadata = null; } } if (!module.jarFile || !module.bindings) return; Object.keys(module.bindings.modules).forEach(function (moduleClass) { var proxy = module.bindings.proxies[moduleClass]; if (proxy.proxyAttrs.id != module.manifest.moduleid) return; var result = { apiName: module.bindings.modules[moduleClass].apiName, proxyName: proxy.proxyClassName, className: moduleClass, manifest: module.manifest, onAppCreate: proxy.onAppCreate || proxy['on_app_create'] || null, isNativeJsModule: !!module.manifest.commonjs }; // make sure that the module was not built before 1.8.0.1 if (~~module.manifest.apiversion < 2) { this.logger.error(__('The "apiversion" for "%s" in the module manifest is less than version 2.', module.manifest.moduleid.cyan)); this.logger.error(__('The module was likely built against a Titanium SDK 1.8.0.1 or older.')); this.logger.error(__('Please use a version of the module that has "apiversion" 2 or greater')); this.logger.log(); process.exit(1); } customModules.push(result); metadata && metadata.exports.forEach(function (namespace) { if (!appModulesMap[namespace]) { var r = createModuleDescriptor(namespace); r && appModules.push(r); } }); }, this); }, this); // write the app.json this.logger.info(__('Writing %s', path.join(this.buildBinAssetsDir, 'app.json').cyan)); fs.writeFileSync(path.join(this.buildBinAssetsDir, 'app.json'), JSON.stringify({ app_modules: appModules })); this.jarLibHash = this.hash(Object.keys(jarLibraries).sort().join('|')); if (this.jarLibHash != this.buildManifest.jarLibHash) { if (!this.forceRebuild) { this.logger.info(__('Forcing rebuild: Detected change in Titanium APIs used and need to recompile')); } this.forceRebuild = true; } next(); }; AndroidBuilder.prototype.copyModuleResources = function copyModuleResources(next) { var _t = this; function copy(src, dest) { fs.readdirSync(src).forEach(function (filename) { var from = path.join(src, filename), to = path.join(dest, filename); if (fs.existsSync(from)) { delete _t.lastBuildFiles[to]; if (fs.statSync(from).isDirectory()) { copy(from, to); } else if (_t.xmlMergeRegExp.test(filename)) { _t.writeXmlFile(from, to); } else { afs.copyFileSync(from, to, { logger: _t.logger.debug }); } } }); } var tasks = Object.keys(this.jarLibraries).map(function (jarFile) { return function (done) { var resFile = jarFile.replace(/\.jar$/, '.res.zip'), resPkgFile = jarFile.replace(/\.jar$/, '.respackage'); if (fs.existsSync(resPkgFile) && fs.existsSync(resFile)) { this.resPackages[resFile] = fs.readFileSync(resPkgFile).toString().split('\n').shift().trim(); return done(); } if (!fs.existsSync(jarFile) || !fs.existsSync(resFile)) return done(); this.logger.info(__('Extracting module resources: %s', resFile.cyan)); var tmp = temp.path(); fs.existsSync(tmp) && wrench.rmdirSyncRecursive(tmp); wrench.mkdirSyncRecursive(tmp); appc.zip.unzip(resFile, tmp, {}, function (ex) { if (ex) { this.logger.error(__('Failed to extract module resource zip: %s', resFile.cyan) + '\n'); process.exit(1); } // copy the files from the temp folder into the build dir copy(tmp, this.buildDir); done(); }.bind(this)); }; }); this.nativeLibModules.forEach(function (m) { var src = path.join(m.modulePath, 'assets'); if (fs.existsSync(src)) { tasks.push(function (done) { copy(src, this.buildBinAssetsResourcesDir); done(); }.bind(this)); } }, this); // for each jar library, if it has a companion resource zip file, extract // all of its files into the build dir, and yes, this is stupidly dangerous appc.async.series(this, tasks, next); }; AndroidBuilder.prototype.removeOldFiles = function removeOldFiles(next) { Object.keys(this.lastBuildFiles).forEach(function (file) { if (path.dirname(file) == this.buildDir || file.indexOf(this.buildAssetsDir) == 0 || file.indexOf(this.buildBinAssetsResourcesDir) == 0 || (this.forceRebuild && file.indexOf(this.buildGenAppIdDir) == 0) || file.indexOf(this.buildResDir) == 0) { if (fs.existsSync(file)) { this.logger.debug(__('Removing old file: %s', file.cyan)); fs.unlinkSync(file); } else { // maybe it's a symlink? try { if (fs.lstatSync(file)) { this.logger.debug(__('Removing old symlink: %s', file.cyan)); fs.unlinkSync(file); } } catch (e) {} } } }, this); next(); }; AndroidBuilder.prototype.generateJavaFiles = function generateJavaFiles(next) { if (!this.forceRebuild) return next(); var android = this.tiapp.android, copyTemplate = function (src, dest) { if (this.forceRebuild || !fs.existsSync(dest)) { this.logger.debug(__('Copying template %s => %s', src.cyan, dest.cyan)); fs.writeFileSync(dest, ejs.render(fs.readFileSync(src).toString(), this)); } }.bind(this); // copy and populate templates copyTemplate(path.join(this.templatesDir, 'AppInfo.java'), path.join(this.buildGenAppIdDir, this.classname + 'AppInfo.java')); copyTemplate(path.join(this.templatesDir, 'App.java'), path.join(this.buildGenAppIdDir, this.classname + 'Application.java')); copyTemplate(path.join(this.templatesDir, 'Activity.java'), path.join(this.buildGenAppIdDir, this.classname + 'Activity.java')); copyTemplate(path.join(this.templatesDir, 'project'), path.join(this.buildDir, '.project')); copyTemplate(path.join(this.templatesDir, 'default.properties'), path.join(this.buildDir, 'default.properties')); afs.copyFileSync(path.join(this.templatesDir, 'gitignore'), path.join(this.buildDir, '.gitignore'), { logger: this.logger.debug }); afs.copyFileSync(path.join(this.templatesDir, 'classpath'), path.join(this.buildDir, '.classpath'), { logger: this.logger.debug }); // generate the JavaScript-based activities if (android && android.activities) { var activityTemplate = fs.readFileSync(path.join(this.templatesDir, 'JSActivity.java')).toString(); Object.keys(android.activities).forEach(function (name) { var activity = android.activities[name]; this.logger.debug(__('Generating activity class: %s', activity.classname.cyan)); fs.writeFileSync(path.join(this.buildGenAppIdDir, activity.classname + '.java'), ejs.render(activityTemplate, { appid: this.appid, activity: activity })); }, this); } // generate the JavaScript-based services if (android && android.services) { var serviceTemplate = fs.readFileSync(path.join(this.templatesDir, 'JSService.java')).toString(), intervalServiceTemplate = fs.readFileSync(path.join(this.templatesDir, 'JSIntervalService.java')).toString(); Object.keys(android.services).forEach(function (name) { var service = android.services[name], tpl = serviceTemplate; if (service.type == 'interval') { tpl = intervalServiceTemplate; this.logger.debug(__('Generating interval service class: %s', service.classname.cyan)); } else { this.logger.debug(__('Generating service class: %s', service.classname.cyan)); } fs.writeFileSync(path.join(this.buildGenAppIdDir, service.classname + '.java'), ejs.render(tpl, { appid: this.appid, service: service })); }, this); } next(); }; AndroidBuilder.prototype.writeXmlFile = function writeXmlFile(srcOrDoc, dest) { var filename = path.basename(dest), destExists = fs.existsSync(dest), destDir = path.dirname(dest), srcDoc = typeof srcOrDoc == 'string' ? (new DOMParser({ errorHandler: function(){} }).parseFromString(fs.readFileSync(srcOrDoc).toString(), 'text/xml')).documentElement : srcOrDoc, destDoc, dom = new DOMParser().parseFromString('<resources/>', 'text/xml'), root = dom.documentElement, nodes = {}, _t = this, byName = function (node) { var n = xml.getAttr(node, 'name'); if (n) { if (nodes[n] && n !== 'app_name') { _t.logger.warn(__('Overwriting XML node %s in file %s', String(n).cyan, dest.cyan)); } nodes[n] = node; } }, byTagAndName = function (node) { var n = xml.getAttr(node, 'name'); if (n) { nodes[node.tagName] || (nodes[node.tagName] = {}); if (nodes[node.tagName][n] && n !== 'app_name') { _t.logger.warn(__('Overwriting XML node %s in file %s', String(n).cyan, dest.cyan)); } nodes[node.tagName][n] = node; } }; if (destExists) { // we're merging destDoc = (new DOMParser({ errorHandler: function(){} }).parseFromString(fs.readFileSync(dest).toString(), 'text/xml')).documentElement; xml.forEachAttr(destDoc, function (attr) { root.setAttribute(attr.name, attr.value); }); if (typeof srcOrDoc == 'string') { this.logger.debug(__('Merging %s => %s', srcOrDoc.cyan, dest.cyan)); } } else { // copy the file, but make sure there are no dupes if (typeof srcOrDoc == 'string') { this.logger.debug(__('Copying %s => %s', srcOrDoc.cyan, dest.cyan)); } } xml.forEachAttr(srcDoc, function (attr) { root.setAttribute(attr.name, attr.value); }); switch (filename) { case 'arrays.xml': case 'attrs.xml': case 'bools.xml': case 'colors.xml': case 'dimens.xml': case 'ids.xml': case 'integers.xml': case 'strings.xml': destDoc && xml.forEachElement(destDoc, byName); xml.forEachElement(srcDoc, byName); Object.keys(nodes).forEach(function (name) { root.appendChild(dom.createTextNode('\n\t')); if (filename == 'strings.xml') { nodes[name].setAttribute('formatted', 'false'); } root.appendChild(nodes[name]); }); break; case 'styles.xml': destDoc && xml.forEachElement(destDoc, byTagAndName); xml.forEachElement(srcDoc, byTagAndName); Object.keys(nodes).forEach(function (tag) { Object.keys(nodes[tag]).forEach(function (name) { root.appendChild(dom.createTextNode('\n\t')); root.appendChild(nodes[tag][name]); }); }); break; } root.appendChild(dom.createTextNode('\n')); fs.existsSync(destDir) || wrench.mkdirSyncRecursive(destDir); destExists && fs.unlinkSync(dest); fs.writeFileSync(dest, '<?xml version="1.0" encoding="UTF-8"?>\n' + dom.documentElement.toString()); }; AndroidBuilder.prototype.generateAidl = function generateAidl(next) { if (!this.forceRebuild) return next(); if (!this.androidTargetSDK.aidl) { this.logger.info(__('Android SDK %s missing framework aidl, skipping', this.androidTargetSDK['api-level'])); return next(); } var aidlRegExp = /\.aidl$/, files = (function scan(dir) { var f = []; fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { f = f.concat(scan(file)); } else if (aidlRegExp.test(name)) { f.push(file); } } }); return f; }(this.buildSrcDir)); if (!files.length) { this.logger.info(__('No aidl files to compile, continuing')); return next(); } appc.async.series(this, files.map(function (file) { return function (callback) { this.logger.info(__('Compiling aidl file: %s', file)); var aidlHook = this.cli.createHook('build.android.aidl', this, function (exe, args, opts, done) { this.logger.info('Running aidl: %s', (exe + ' "' + args.join('" "') + '"').cyan); appc.subprocess.run(exe, args, opts, done); }); aidlHook( this.androidInfo.sdk.executables.aidl, ['-p' + this.androidTargetSDK.aidl, '-I' + this.buildSrcDir, '-o' + this.buildGenAppIdDir, file], {}, callback ); }; }), next); }; AndroidBuilder.prototype.generateI18N = function generateI18N(next) { this.logger.info(__('Generating i18n files')); var data = i18n.load(this.projectDir, this.logger, { ignoreDirs: this.ignoreDirs, ignoreFiles: this.ignoreFiles }), badStringNames = {}; data.en || (data.en = {}); data.en.app || (data.en.app = {}); data.en.app.appname || (data.en.app.appname = this.tiapp.name); function replaceSpaces(s) { return s.replace(/./g, '\\u0020'); } function resolveRegionName(locale) { if (locale.match(/\w{2}(-|_)r?\w{2}/)) { var parts = locale.split(/-|_/), lang = parts[0], region = parts[1], separator = '-'; if (region.length == 2) { separator = '-r'; } return lang + separator + region; } return locale; } Object.keys(data).forEach(function (locale) { var dest = path.join(this.buildResDir, 'values' + (locale == 'en' ? '' : '-' + resolveRegionName(locale)), 'strings.xml'), dom = new DOMParser().parseFromString('<resources/>', 'text/xml'), root = dom.documentElement, appname = data[locale].app && data[locale].app.appname || this.tiapp.name, appnameNode = dom.createElement('string'); appnameNode.setAttribute('name', 'app_name'); appnameNode.setAttribute('formatted', 'false'); appnameNode.appendChild(dom.createTextNode(appname)); root.appendChild(dom.createTextNode('\n\t')); root.appendChild(appnameNode); data[locale].strings && Object.keys(data[locale].strings).forEach(function (name) { if (name.indexOf(' ') != -1) { badStringNames[locale] || (badStringNames[locale] = []); badStringNames[locale].push(name); } else if (name != 'appname') { var node = dom.createElement('string'); node.setAttribute('name', name); node.setAttribute('formatted', 'false'); node.appendChild(dom.createTextNode(data[locale].strings[name].replace(/\\?'/g, "\\'").replace(/^\s+/g, replaceSpaces).replace(/\s+$/g, replaceSpaces))); root.appendChild(dom.createTextNode('\n\t')); root.appendChild(node); } }); root.appendChild(dom.createTextNode('\n')); if (fs.existsSync(dest)) { this.logger.debug(__('Merging %s strings => %s', locale.cyan, dest.cyan)); } else { this.logger.debug(__('Writing %s strings => %s', locale.cyan, dest.cyan)); } this.writeXmlFile(dom.documentElement, dest); }, this); if (Object.keys(badStringNames).length) { this.logger.error(__('Found invalid i18n string names:')); Object.keys(badStringNames).forEach(function (locale) { badStringNames[locale].forEach(function (s) { this.logger.error(' "' + s + '" (' + locale + ')'); }, this); }, this); this.logger.error(__('Android does not allow i18n string names with spaces.')); if (!this.config.get('android.excludeInvalidI18nStrings', false)) { this.logger.error(__('To exclude invalid i18n strings from the build, run:')); this.logger.error(' ' + this.cli.argv.$ + ' config android.excludeInvalidI18nStrings true'); this.logger.log(); process.exit(1); } } next(); }; AndroidBuilder.prototype.generateTheme = function generateTheme(next) { var themeFile = path.join(this.buildResDir, 'values', 'theme.xml'); if (!fs.existsSync(themeFile)) { this.logger.info(__('Generating %s', themeFile.cyan)); var flags = 'Theme.AppCompat'; if (this.tiapp.fullscreen || this.tiapp['statusbar-hidden']) { flags += '.Fullscreen'; } fs.writeFileSync(themeFile, ejs.render(fs.readFileSync(path.join(this.templatesDir, 'theme.xml')).toString(), { flags: flags })); } next(); }; AndroidBuilder.prototype.generateAndroidManifest = function generateAndroidManifest(next) { if (!this.forceRebuild && fs.existsSync(this.androidManifestFile)) { return next(); } var calendarPermissions = [ 'android.permission.READ_CALENDAR', 'android.permission.WRITE_CALENDAR' ], cameraPermissions = [ 'android.permission.CAMERA' ], contactsPermissions = [ 'android.permission.READ_CONTACTS', 'android.permission.WRITE_CONTACTS' ], contactsReadPermissions = [ 'android.permission.READ_CONTACTS' ], geoPermissions = [ 'android.permission.ACCESS_COARSE_LOCATION', 'android.permission.ACCESS_FINE_LOCATION' ], vibratePermissions = [ 'android.permission.VIBRATE' ], wallpaperPermissions = [ 'android.permission.SET_WALLPAPER' ], permissions = { 'android.permission.INTERNET': 1, 'android.permission.ACCESS_WIFI_STATE': 1, 'android.permission.ACCESS_NETWORK_STATE': 1, 'android.permission.WRITE_EXTERNAL_STORAGE': 1 }, tiNamespacePermissions = { 'geolocation': geoPermissions }, tiMethodPermissions = { // old calendar 'Android.Calendar.getAllAlerts': calendarPermissions, 'Android.Calendar.getAllCalendars': calendarPermissions, 'Android.Calendar.getCalendarById': calendarPermissions, 'Android.Calendar.getSelectableCalendars': calendarPermissions, // new calendar 'Calendar.getAllAlerts': calendarPermissions, 'Calendar.getAllCalendars': calendarPermissions, 'Calendar.getCalendarById': calendarPermissions, 'Calendar.getSelectableCalendars': calendarPermissions, 'Contacts.createPerson': contactsPermissions, 'Contacts.removePerson': contactsPermissions, 'Contacts.getAllContacts': contactsReadPermissions, 'Contacts.showContactPicker': contactsReadPermissions, 'Contacts.showContacts': contactsReadPermissions, 'Contacts.getPersonByID': contactsReadPermissions, 'Contacts.getPeopleWithName': contactsReadPermissions, 'Contacts.getAllPeople': contactsReadPermissions, 'Contacts.getAllGroups': contactsReadPermissions, 'Contacts.getGroupByID': contactsReadPermissions, 'Map.createView': geoPermissions, 'Media.Android.setSystemWallpaper': wallpaperPermissions, 'Media.showCamera': cameraPermissions, 'Media.vibrate': vibratePermissions, }, tiMethodActivities = { 'Map.createView': { 'activity': { 'name': 'ti.modules.titanium.map.TiMapActivity', 'configChanges': ['keyboardHidden', 'orientation'], 'launchMode': 'singleTask' }, 'uses-library': { 'name': 'com.google.android.maps' } }, 'Media.createVideoPlayer': { 'activity': { 'name': 'ti.modules.titanium.media.TiVideoActivity', 'configChanges': ['keyboardHidden', 'orientation'], 'theme': '@style/Theme.AppCompat.Fullscreen', 'launchMode': 'singleTask' } }, 'Media.showCamera': { 'activity': { 'name': 'ti.modules.titanium.media.TiCameraActivity', 'configChanges': ['keyboardHidden', 'orientation'], 'theme': '@style/Theme.AppCompat.Translucent.NoTitleBar.Fullscreen' } } }, googleAPIs = [ 'Map.createView' ], enableGoogleAPIWarning = this.target == 'emulator' && this.emulator && !this.emulator.googleApis, fill = function (str) { // first we replace all legacy variable placeholders with EJS style placeholders str = str.replace(/(\$\{tiapp\.properties\[['"]([^'"]+)['"]\]\})/g, function (s, m1, m2) { // if the property is the "id", we want to force our scrubbed "appid" if (m2 == 'id') { m2 = 'appid'; } else { m2 = 'tiapp.' + m2; } return '<%- ' + m2 + ' %>'; }); // then process the string as an EJS template return ejs.render(str, this); }.bind(this), finalAndroidManifest = (new AndroidManifest).parse(fill(fs.readFileSync(path.join(this.templatesDir, 'AndroidManifest.xml')).toString())), customAndroidManifest = this.customAndroidManifest, tiappAndroidManifest = this.tiappAndroidManifest; // if they are using a custom AndroidManifest and merging is disabled, then write the custom one as is if (!this.config.get('android.mergeCustomAndroidManifest', false) && this.customAndroidManifest) { (this.cli.createHook('build.android.writeAndroidManifest', this, function (file, xml, done) { this.logger.info(__('Writing unmerged custom AndroidManifest.xml')); fs.writeFileSync(file, xml.toString('xml')); done(); }))(this.androidManifestFile, customAndroidManifest, next); return; } finalAndroidManifest.__attr__['android:versionName'] = this.tiapp.version || '1'; if (this.deployType != 'production') { // enable mock location if in development or test mode geoPermissions.push('android.permission.ACCESS_MOCK_LOCATION'); } // set permissions for each titanium namespace found Object.keys(this.tiNamespaces).forEach(function (ns) { if (tiNamespacePermissions[ns]) { tiNamespacePermissions[ns].forEach(function (perm) { permissions[perm] = 1; }); } }, this); // set permissions for each titanium method found var tmp = {}; Object.keys(this.tiSymbols).forEach(function (file) { this.tiSymbols[file].forEach(function (symbol) { if (tmp[symbol]) return; tmp[symbol] = 1; if (tiMethodPermissions[symbol]) { tiMethodPermissions[symbol].forEach(function (perm) { permissions[perm] = 1; }); } var obj = tiMethodActivities[symbol]; if (obj) { if (obj.activity) { finalAndroidManifest.application.activity || (finalAndroidManifest.application.activity = {}); finalAndroidManifest.application.activity[obj.activity.name] = obj.activity; } if (obj['uses-library']) { finalAndroidManifest.application['uses-library'] || (finalAndroidManifest.application['uses-library'] = {}); finalAndroidManifest.application['uses-library'][obj['uses-library'].name] = obj['uses-library']; } } if (enableGoogleAPIWarning && googleAPIs.indexOf(symbol) != -1) { var fn = 'Titanium.' + symbol + '()'; if (this.emulator.googleApis === null) { this.logger.warn(__('Detected %s call which requires Google APIs, however the selected emulator %s may or may not support Google APIs', fn.cyan, ('"' + this.emulator.name + '"').cyan)); this.logger.warn(__('If the emulator does not support Google APIs, the %s call will fail', fn.cyan)); } else { this.logger.warn(__('Detected %s call which requires Google APIs, but the selected emulator %s does not support Google APIs', fn.cyan, ('"' + this.emulator.name + '"').cyan)); this.logger.warn(__('Expect the %s call to fail', fn.cyan)); } this.logger.warn(__('You should use, or create, an Android emulator that does support Google APIs')); } }, this); }, this); // gather activities var tiappActivities = this.tiapp.android && this.tiapp.android.activities; tiappActivities && Object.keys(tiappActivities).forEach(function (filename) { var activity = tiappActivities[filename]; if (activity.url) { var a = { name: this.appid + '.' + activity.classname }; Object.keys(activity).forEach(function (key) { if (!/^(name|url|options|classname|android\:name)$/.test(key)) { a[key.replace(/^android\:/, '')] = activity[key]; } }); a.configChanges || (a.configChanges = ['keyboardHidden', 'orientation']); finalAndroidManifest.application.activity || (finalAndroidManifest.application.activity = {}); finalAndroidManifest.application.activity[a.name] = a; } }, this); // gather services var tiappServices = this.tiapp.android && this.tiapp.android.services; tiappServices && Object.keys(tiappServices).forEach(function (filename) { var service = tiappServices[filename]; if (service.url) { var s = { 'name': this.appid + '.' + service.classname }; Object.keys(service).forEach(function (key) { if (!/^(type|name|url|options|classname|android\:name)$/.test(key)) { s[key.replace(/^android\:/, '')] = service[key]; } }); finalAndroidManifest.application.service || (finalAndroidManifest.application.service = {}); finalAndroidManifest.application.service[s.name] = s; } }, this); // add the analytics service if (this.tiapp.analytics) { var tiAnalyticsService = 'com.appcelerator.aps.APSAnalyticsService'; finalAndroidManifest.application.service || (finalAndroidManifest.application.service = {}); finalAndroidManifest.application.service[tiAnalyticsService] = { name: tiAnalyticsService, exported: false }; } // set the app icon finalAndroidManifest.application.icon = '@drawable/' + this.tiapp.icon.replace(/((\.9)?\.(png|jpg))$/, ''); // merge the custom android manifest finalAndroidManifest.merge(customAndroidManifest); // merge the tiapp.xml android manifest finalAndroidManifest.merge(tiappAndroidManifest); this.modules.forEach(function (module) { var moduleXmlFile = path.join(module.modulePath, 'timodule.xml'); if (fs.existsSync(moduleXmlFile)) { var moduleXml = new tiappxml(moduleXmlFile); if (moduleXml.android && moduleXml.android.manifest) { var am = new AndroidManifest; am.parse(fill(moduleXml.android.manifest)); // we don't want modules to override the <supports-screens> or <uses-sdk> tags delete am.__attr__; delete am['supports-screens']; delete am['uses-sdk']; finalAndroidManifest.merge(am); } // point to the .jar file if the timodule.xml file has properties of 'dexAgent' if (moduleXml.properties && moduleXml.properties['dexAgent']) { this.dexAgent = path.join(module.modulePath, moduleXml.properties['dexAgent'].value); } } }, this); // if the target sdk is Android 3.2 or newer, then we need to add 'screenSize' to // the default AndroidManifest.xml's 'configChanges' attribute for all <activity> // elements, otherwise changes in orientation will cause the app to restart if (this.realTargetSDK >= 13) { Object.keys(finalAndroidManifest.application.activity).forEach(function (name) { var activity = finalAndroidManifest.application.activity[name]; if (!activity.configChanges) { activity.configChanges = ['screenSize']; } else if (activity.configChanges.indexOf('screenSize') == -1) { activity.configChanges.push('screenSize'); } }); } // add permissions Array.isArray(finalAndroidManifest['uses-permission']) || (finalAndroidManifest['uses-permission'] = []); Object.keys(permissions).forEach(function (perm) { finalAndroidManifest['uses-permission'].indexOf(perm) == -1 && finalAndroidManifest['uses-permission'].push(perm); }); // if the AndroidManifest.xml already exists, remove it so that we aren't updating the original file (if it's symlinked) fs.existsSync(this.androidManifestFile) && fs.unlinkSync(this.androidManifestFile); (this.cli.createHook('build.android.writeAndroidManifest', this, function (file, xml, done) { fs.writeFileSync(file, xml.toString('xml')); done(); }))(this.androidManifestFile, finalAndroidManifest, next); }; AndroidBuilder.prototype.packageApp = function packageApp(next) { this.ap_File = path.join(this.buildBinDir, 'app.ap_'); var aaptHook = this.cli.createHook('build.android.aapt', this, function (exe, args, opts, done) { this.logger.info(__('Packaging application: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to package application:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } // check that the R.java file exists var rFile = path.join(this.buildGenAppIdDir, 'R.java'); if (!fs.existsSync(rFile)) { this.logger.error(__('Unable to find generated R.java file') + '\n'); process.exit(1); } done(); }.bind(this)); }), args = [ 'package', '-f', '-m', '-J', path.join(this.buildDir, 'gen'), '-M', this.androidManifestFile, '-A', this.buildBinAssetsDir, '-S', this.buildResDir, '-I', this.androidTargetSDK.androidJar, '-F', this.ap_File ]; function runAapt() { aaptHook( this.androidInfo.sdk.executables.aapt, args, {}, next ); } if ( (!Object.keys(this.resPackages).length) && (!this.moduleResPackages.length) ) { return runAapt(); } args.push('--auto-add-overlay'); var namespaces = ''; Object.keys(this.resPackages).forEach(function(resFile){ namespaces && (namespaces+=':'); namespaces += this.resPackages[resFile]; }, this); this.moduleResPackages.forEach(function (data) { namespaces && (namespaces+=':'); namespaces += data; }, this); args.push('--extra-packages', namespaces); appc.async.series(this, Object.keys(this.resPackages).map(function (resFile) { return function (cb) { var namespace = this.resPackages[resFile], tmp = temp.path(); appc.zip.unzip(resFile, tmp, {}, function (ex) { if (ex) { this.logger.error(__('Failed to extract module resource zip: %s', resFile.cyan) + '\n'); process.exit(1); } args.push('-S', tmp+'/res'); cb(); }.bind(this)); }; }), runAapt); }; AndroidBuilder.prototype.compileJavaClasses = function compileJavaClasses(next) { var classpath = {}, moduleJars = this.moduleJars = {}, jarNames = {}; classpath[this.androidTargetSDK.androidJar] = 1; Object.keys(this.jarLibraries).map(function (jarFile) { classpath[jarFile] = 1; }); this.modules.forEach(function (module) { if (fs.existsSync(module.jarFile)) { var jarHash = this.hash(fs.readFileSync(module.jarFile).toString()); if (!jarNames[jarHash]) { moduleJars[module.jarFile] = 1; classpath[module.jarFile] = 1; jarNames[jarHash] = 1; } else { this.logger.debug(__('Skipping duplicate jar file: %s', module.jarFile.cyan)); } var libDir = path.join(module.modulePath, 'lib'), jarRegExp = /\.jar$/; fs.existsSync(libDir) && fs.readdirSync(libDir).forEach(function (name) { var jarFile = path.join(libDir, name); if (jarRegExp.test(name) && fs.existsSync(jarFile)) { var jarHash = this.hash(fs.readFileSync(jarFile).toString()); if (!jarNames[jarHash]) { moduleJars[jarFile] = 1; classpath[jarFile] = 1; jarNames[jarHash] = 1; } else { this.logger.debug(__('Skipping duplicate jar file: %s', jarFile.cyan)); } } }, this); } }, this); if (!this.forceRebuild) { // if we don't have to compile the java files, then we can return here // we just needed the moduleJars return next(); } if (Object.keys(moduleJars).length) { // we need to include kroll-apt.jar if there are any modules classpath[path.join(this.platformPath, 'kroll-apt.jar')] = 1; } classpath[path.join(this.platformPath, 'lib', 'titanium-verify.jar')] = 1; if (this.allowDebugging && this.debugPort) { classpath[path.join(this.platformPath, 'lib', 'titanium-debug.jar')] = 1; } if (this.allowProfiling && this.profilerPort) { classpath[path.join(this.platformPath, 'lib', 'titanium-profiler.jar')] = 1; } // find all java files and write them to the temp file var javaFiles = [], javaRegExp = /\.java$/, javaSourcesFile = path.join(this.buildDir, 'java-sources.txt'); [this.buildGenDir, this.buildSrcDir].forEach(function scanJavaFiles(dir) { fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { scanJavaFiles(file); } else if (javaRegExp.test(name)) { javaFiles.push(file); classpath[name.replace(javaRegExp, '.class')] = 1; } } }); }); fs.writeFileSync(javaSourcesFile, '"' + javaFiles.join('"\n"').replace(/\\/g, '/') + '"'); // if we're recompiling the java files, then nuke the classes dir if (fs.existsSync(this.buildBinClassesDir)) { wrench.rmdirSyncRecursive(this.buildBinClassesDir); } wrench.mkdirSyncRecursive(this.buildBinClassesDir); var javacHook = this.cli.createHook('build.android.javac', this, function (exe, args, opts, done) { this.logger.info(__('Building Java source files: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to compile Java source files:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }); javacHook( this.jdkInfo.executables.javac, [ '-J-Xmx' + this.javacMaxMemory, '-encoding', 'utf8', '-bootclasspath', Object.keys(classpath).join(process.platform == 'win32' ? ';' : ':'), '-d', this.buildBinClassesDir, '-proc:none', '-target', this.javacTarget, '-source', this.javacSource, '@' + javaSourcesFile ], {}, next ); }; AndroidBuilder.prototype.runProguard = function runProguard(next) { if (!this.forceRebuild || !this.proguard) return next(); // check that the proguard config exists var proguardConfigFile = path.join(this.buildDir, 'proguard.cfg'), proguardHook = this.cli.createHook('build.android.proguard', this, function (exe, args, opts, done) { this.logger.info(__('Running ProGuard: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to run ProGuard')); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }); proguardHook( this.jdkInfo.executables.java, ['-jar', this.androidInfo.sdk.proguard, '@' + proguardConfigFile], { cwd: this.buildDir }, next ); }; AndroidBuilder.prototype.runDexer = function runDexer(next) { if (!this.forceRebuild && fs.existsSync(this.buildBinClassesDex)) return next(); var dexerHook = this.cli.createHook('build.android.dexer', this, function (exe, args, opts, done) { this.logger.info(__('Running dexer: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to run dexer:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }), injars = [ this.buildBinClassesDir, path.join(this.platformPath, 'lib', 'titanium-verify.jar') ].concat(Object.keys(this.moduleJars)).concat(Object.keys(this.jarLibraries)), dexArgs = [ '-Xmx' + this.dxMaxMemory, '-XX:-UseGCOverheadLimit', '-Djava.ext.dirs=' + this.androidInfo.sdk.platformTools.path, '-jar', this.androidInfo.sdk.dx, '--dex', '--multi-dex', '--output=' + this.buildBinClassesDex, ], shrinkedAndroid = path.join(path.dirname(this.androidInfo.sdk.dx), 'shrinkedAndroid.jar'), baserules = path.join(path.dirname(this.androidInfo.sdk.dx), '..', 'mainDexClasses.rules'), outjar = path.join(this.buildDir, 'mainDexClasses.jar'); // inserts the -javaagent arg earlier on in the dexArgs to allow for proper dexing if // dexAgent is set in the module's timodule.xml if (this.dexAgent) { dexArgs.unshift('-javaagent:' + this.dexAgent); } if (this.allowDebugging && this.debugPort) { injars.push(path.join(this.platformPath, 'lib', 'titanium-debug.jar')); } if (this.allowProfiling && this.profilerPort) { injars.push(path.join(this.platformPath, 'lib', 'titanium-profiler.jar')); } // nuke and create the folder holding all the classes*.dex files if (fs.existsSync(this.buildBinClassesDex)) { wrench.rmdirSyncRecursive(this.buildBinClassesDex); } wrench.mkdirSyncRecursive(this.buildBinClassesDex); // Wipe existing outjar fs.existsSync(outjar) && fs.unlinkSync(outjar); // We need to hack multidex for APi level < 21 to generate the list of classes that *need* to go into the first dex file // We skip these intermediate steps if 21+ and eventually just run dexer async.series([ // Run: java -jar $this.androidInfo.sdk.proguard -injars "${@}" -dontwarn -forceprocessing -outjars ${tmpOut} -libraryjars "${shrinkedAndroidJar}" -dontoptimize -dontobfuscate -dontpreverify -include "${baserules}" function (done) { // 'api-level' and 'sdk' properties both seem to hold apiLevel if (this.androidTargetSDK.sdk >= 21) { return done(); } appc.subprocess.run(this.jdkInfo.executables.java, [ '-jar', this.androidInfo.sdk.proguard, '-injars', injars.join(':'), '-dontwarn', '-forceprocessing', '-outjars', outjar, '-libraryjars', shrinkedAndroid, '-dontoptimize', '-dontobfuscate', '-dontpreverify', '-include', baserules ], {}, function (code, out, err) { if (code) { this.logger.error(__('Failed to run dexer:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }.bind(this), // Run: java -cp $this.androidInfo.sdk.dx com.android.multidex.MainDexListBuilder "$outjar" "$injars" function (done) { // 'api-level' and 'sdk' properties both seem to hold apiLevel if (this.androidTargetSDK.sdk >= 21) { return done(); } appc.subprocess.run(this.jdkInfo.executables.java, ['-cp', this.androidInfo.sdk.dx, 'com.android.multidex.MainDexListBuilder', outjar, injars.join(':')], {}, function (code, out, err) { var mainDexClassesList = path.join(this.buildDir, 'main-dex-classes.txt'); if (code) { this.logger.error(__('Failed to run dexer:')); this.logger.error(); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } // Record output to a file like main-dex-classes.txt fs.writeFileSync(mainDexClassesList, out); // Pass that file into dex, like so: dexArgs.push('--main-dex-list'); dexArgs.push(mainDexClassesList); done(); }.bind(this)); }.bind(this), function (done) { dexArgs = dexArgs.concat(injars); dexerHook(this.jdkInfo.executables.java, dexArgs, {}, done); }.bind(this) ], next); }; AndroidBuilder.prototype.createUnsignedApk = function createUnsignedApk(next) { var dest = archiver('zip', { forceUTC: true }), apkStream, jsonRegExp = /\.json$/, javaRegExp = /\.java$/, classRegExp = /\.class$/, dexRegExp = /^classes(\d+)?\.dex$/, soRegExp = /\.so$/, trailingSlashRegExp = /\/$/, nativeLibs = {}, origConsoleError = console.error; // since the archiver library didn't set max listeners, we squelch all error output console.error = function () {}; try { fs.existsSync(this.unsignedApkFile) && fs.unlinkSync(this.unsignedApkFile); apkStream = fs.createWriteStream(this.unsignedApkFile); apkStream.on('close', function() { console.error = origConsoleError; next(); }); dest.catchEarlyExitAttached = true; // silence exceptions dest.pipe(apkStream); this.logger.info(__('Creating unsigned apk')); // merge files from the app.ap_ file as well as all titanium and 3rd party jar files var archives = [ this.ap_File ].concat(Object.keys(this.moduleJars)).concat(Object.keys(this.jarLibraries)); archives.forEach(function (file) { var src = new AdmZip(file), entries = src.getEntries(); this.logger.debug(__('Processing %s', file.cyan)); entries.forEach(function (entry) { if (entry.entryName.indexOf('META-INF/') == -1 && (entry.entryName.indexOf('org/appcelerator/titanium/bindings/') == -1 || !jsonRegExp.test(entry.name)) && entry.name.charAt(0) != '.' && !classRegExp.test(entry.name) && !trailingSlashRegExp.test(entry.entryName) ) { var store = this.uncompressedTypes.indexOf(entry.entryName.split('.').pop()) != -1; this.logger.debug(store ? __('Adding %s', entry.entryName.cyan) : __('Deflating %s', entry.entryName.cyan)); dest.append(src.readFile(entry), { name: entry.entryName, store: store }); } }, this); }, this); // Add dex files this.logger.info(__('Processing %s', this.buildBinClassesDex.cyan)); fs.readdirSync(this.buildBinClassesDex).forEach(function (name) { var file = path.join(this.buildBinClassesDex, name); if (dexRegExp.test(name)) { this.logger.debug(__('Adding %s', name.cyan)); dest.append(fs.createReadStream(file), { name: name }); } }, this); this.logger.info(__('Processing %s', this.buildSrcDir.cyan)); (function copyDir(dir, base) { base = base || dir; fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.existsSync(file)) { if (fs.statSync(file).isDirectory()) { copyDir(file, base); } else if (!javaRegExp.test(name)) { name = file.replace(base, '').replace(/^[\/\\]/, ''); this.logger.debug(__('Adding %s', name.cyan)); dest.append(fs.createReadStream(file), { name: name }); } } }, this); }.call(this, this.buildSrcDir)); var addNativeLibs = function (dir) { if (!fs.existsSync(dir)) return; for (var i = 0; i < this.abis.length; i++) { var abiDir = path.join(dir, this.abis[i]); // check that we found the desired abi, otherwise we abort the build if (!fs.existsSync(abiDir) || !fs.statSync(abiDir).isDirectory()) { throw this.abis[i]; } // copy all the .so files into the archive fs.readdirSync(abiDir).forEach(function (name) { if (name != 'libtiprofiler.so' || (this.allowProfiling && this.profilerPort)) { var file = path.join(abiDir, name), rel = 'lib/' + this.abis[i] + '/' + name; if (!nativeLibs[rel] && soRegExp.test(name) && fs.existsSync(file)) { nativeLibs[rel] = 1; this.logger.debug(__('Adding %s', rel.cyan)); dest.append(fs.createReadStream(file), { name: rel }); } } }, this); } }.bind(this); try { // add Titanium native modules addNativeLibs(path.join(this.platformPath, 'native', 'libs')); } catch (abi) { // this should never be called since we already validated this var abis = []; fs.readdirSync(path.join(this.platformPath, 'native', 'libs')).forEach(function (abi) { var dir = path.join(this.platformPath, 'native', 'libs', abi); if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { abis.push(abi); } }); this.logger.error(__('Invalid native Titanium library ABI "%s"', abi)); this.logger.error(__('Supported ABIs: %s', abis.join(', ')) + '\n'); process.exit(1); } try { // add native modules from the build dir's "libs" dir addNativeLibs(path.join(this.buildDir, 'libs')); } catch (e) {} this.modules.forEach(function (m) { if (m.native) { try { // add native modules for each module addNativeLibs(path.join(m.modulePath, 'libs')); } catch (abi) { // this should never be called since we already validated this var abis = []; fs.readdirSync(path.join(m.modulePath, 'libs')).forEach(function (abi) { var dir = path.join(m.modulePath, 'libs', abi); if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { abis.push(abi); } }); /* commenting this out to preserve the old, incorrect behavior this.logger.error(__('The module "%s" does not support the ABI "%s"', m.id, abi)); this.logger.error(__('Supported ABIs: %s', abis.join(', ')) + '\n'); process.exit(1); */ this.logger.warn(__('The module %s does not support the ABI: %s', m.id.cyan, abi.cyan)); this.logger.warn(__('It only supports the following ABIs: %s', abis.map(function (a) { return a.cyan; }).join(', '))); this.logger.warn(__('Your application will most likely encounter issues')); } } }, this); this.logger.info(__('Writing unsigned apk: %s', this.unsignedApkFile.cyan)); dest.finalize(); } catch (ex) { console.error = origConsoleError; throw ex; } }; AndroidBuilder.prototype.createSignedApk = function createSignedApk(next) { var sigalg = this.keystoreAlias.sigalg || 'MD5withRSA', signerArgs = [ '-sigalg', sigalg, '-digestalg', 'SHA1', '-keystore', this.keystore, '-storepass', this.keystoreStorePassword ]; this.logger.info(__('Using %s signature algorithm', sigalg.cyan)); this.keystoreKeyPassword && signerArgs.push('-keypass', this.keystoreKeyPassword); signerArgs.push('-signedjar', this.apkFile, this.unsignedApkFile, this.keystoreAlias.name); var jarsignerHook = this.cli.createHook('build.android.jarsigner', this, function (exe, args, opts, done) { var safeArgs = []; for (var i = 0, l = args.length; i < l; i++) { safeArgs.push(args[i]); if (args[i] == '-storepass' || args[i] == 'keypass') { safeArgs.push(args[++i].replace(/./g, '*')); } } this.logger.info(__('Signing apk: %s', (exe + ' "' + safeArgs.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to sign apk:')); out.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } done(); }.bind(this)); }); jarsignerHook( this.jdkInfo.executables.jarsigner, signerArgs, {}, next ); }; AndroidBuilder.prototype.zipAlignApk = function zipAlignApk(next) { var zipAlignedApk = this.apkFile + 'z', zipalignHook = this.cli.createHook('build.android.zipalign', this, function (exe, args, opts, done) { this.logger.info(__('Aligning zip file: %s', (exe + ' "' + args.join('" "') + '"').cyan)); appc.subprocess.run(exe, args, opts, function (code, out, err) { if (code) { this.logger.error(__('Failed to zipalign apk:')); err.trim().split('\n').forEach(this.logger.error); this.logger.log(); process.exit(1); } fs.unlinkSync(this.apkFile); fs.renameSync(zipAlignedApk, this.apkFile); done(); }.bind(this)); }); zipalignHook( this.androidInfo.sdk.executables.zipalign, [ '-v', '4', // 4 byte alignment this.apkFile, zipAlignedApk ], {}, next ); }; AndroidBuilder.prototype.writeBuildManifest = function writeBuildManifest(callback) { this.logger.info(__('Writing build manifest: %s', this.buildManifestFile.cyan)); this.cli.createHook('build.android.writeBuildManifest', this, function (manifest, cb) { fs.existsSync(this.buildDir) || wrench.mkdirSyncRecursive(this.buildDir); fs.existsSync(this.buildManifestFile) && fs.unlinkSync(this.buildManifestFile); fs.writeFile(this.buildManifestFile, JSON.stringify(this.buildManifest = manifest, null, '\t'), cb); })({ target: this.target, deployType: this.deployType, classname: this.classname, platformPath: this.platformPath, modulesHash: this.modulesHash, modulesManifestHash: this.modulesManifestHash, modulesNativeHash: this.modulesNativeHash, modulesBindingsHash: this.modulesBindingsHash, gitHash: ti.manifest.githash, outputDir: this.cli.argv['output-dir'], name: this.tiapp.name, id: this.tiapp.id, analytics: this.tiapp.analytics, publisher: this.tiapp.publisher, url: this.tiapp.url, version: this.tiapp.version, description: this.tiapp.description, copyright: this.tiapp.copyright, guid: this.tiapp.guid, icon: this.tiapp.icon, fullscreen: this.tiapp.fullscreen, navbarHidden: this.tiapp['navbar-hidden'], skipJSMinification: !!this.cli.argv['skip-js-minify'], mergeCustomAndroidManifest: this.config.get('android.mergeCustomAndroidManifest', false), encryptJS: this.encryptJS, minSDK: this.minSDK, targetSDK: this.targetSDK, propertiesHash: this.propertiesHash, activitiesHash: this.activitiesHash, servicesHash: this.servicesHash, jarLibHash: this.jarLibHash }, callback); }; // create the builder instance and expose the public api (function (androidBuilder) { exports.config = androidBuilder.config.bind(androidBuilder); exports.validate = androidBuilder.validate.bind(androidBuilder); exports.run = androidBuilder.run.bind(androidBuilder); }(new AndroidBuilder(module)));
fix android commonjs copy file
android/cli/commands/_build.js
fix android commonjs copy file
<ide><path>ndroid/cli/commands/_build.js <ide> <ide> // we use the destination file name minus the path to the assets dir as the id <ide> // which will eliminate dupes <del> var id = to.replace(opts.origDest, opts.prefix ? opts.prefix + '/' : '').replace(/\\/g, '/').replace(/^\//, ''); <add> var id = to.replace(opts.origDest, opts.prefix ? opts.prefix : '').replace(/\\/g, '/').replace(/^\//, ''); <ide> <ide> if (!jsFiles[id] || !opts || !opts.onJsConflict || opts.onJsConflict(from, to, id)) { <ide> jsFiles[id] = from;
Java
apache-2.0
3daa88704e50f38b27b15c3df4c59118f56114d2
0
statsbiblioteket/newspaper-batch-metadata-checker,statsbiblioteket/newspaper-batch-metadata-checker,statsbiblioteket/newspaper-batch-metadata-checker
package dk.statsbiblioteket.newspaper.metadatachecker; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventHandlerFactory; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; import dk.statsbiblioteket.util.xml.DOM; import org.testng.annotations.Test; import org.w3c.dom.Document; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Properties; import static org.testng.Assert.assertTrue; /** */ public class MetadataCheckerComponentIT { private final static String TEST_BATCH_ID = "400022028241"; /** Tests that the BatchStructureChecker can parse a production like batch. */ @Test(groups = "integrationTest") public void testMetadataCheck() throws Exception { String pathToProperties = System.getProperty("integration.test.newspaper.properties"); Properties properties = new Properties(); properties.load(new FileInputStream(pathToProperties)); TreeIterator iterator = getIterator(); EventRunner batchStructureChecker = new EventRunner(iterator); ResultCollector resultCollector = new ResultCollector("Batch Structure Checker", "v0.1"); Batch batch = new Batch(); batch.setBatchID(TEST_BATCH_ID); batch.setRoundTripNumber(1); InputStream batchXmlStructureStream = retrieveBatchStructure(batch); if (batchXmlStructureStream == null) { throw new RuntimeException("Failed to resolve batch manifest from data collector"); } Document batchXmlManifest = DOM.streamToDOM(batchXmlStructureStream); MfPakConfiguration mfPakConfiguration = new MfPakConfiguration(); mfPakConfiguration.setDatabaseUrl(properties.getProperty(ConfigurationProperties.DATABASE_URL)); mfPakConfiguration.setDatabaseUser(properties.getProperty(ConfigurationProperties.DATABASE_USER)); mfPakConfiguration.setDatabasePassword(properties.getProperty(ConfigurationProperties.DATABASE_PASSWORD)); EventHandlerFactory eventHandlerFactory = new MetadataChecksFactory(resultCollector, true, getBatchFolder().getParentFile() .getAbsolutePath(), getJpylyzerPath(), null, new MfPakDAO(mfPakConfiguration), batch, batchXmlManifest); batchStructureChecker.runEvents(eventHandlerFactory.createEventHandlers()); System.out.println(resultCollector.toReport()); assertTrue(resultCollector.isSuccess()); //Assert.fail(); } private InputStream retrieveBatchStructure(Batch batch) { return Thread.currentThread().getContextClassLoader().getResourceAsStream("assumed-valid-structure.xml"); } private String getJpylyzerPath() { return "src/main/extras/jpylyzer-1.10.1/jpylyzer.py"; } /** * Creates and returns a iteration based on the test batch file structure found in the test/ressources folder. * * @return A iterator the the test batch * @throws URISyntaxException */ public TreeIterator getIterator() throws URISyntaxException { File file = getBatchFolder(); System.out.println(file); return new TransformingIteratorForFileSystems(file, "\\.", ".*\\.jp2$", ".md5"); } private File getBatchFolder() { String pathToTestBatch = System.getProperty("integration.test.newspaper.testdata"); return new File(pathToTestBatch, "small-test-batch/B" + TEST_BATCH_ID + "-RT1"); } }
src/test/java/dk/statsbiblioteket/newspaper/metadatachecker/MetadataCheckerComponentIT.java
package dk.statsbiblioteket.newspaper.metadatachecker; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; import dk.statsbiblioteket.util.Streams; import org.testng.annotations.Test; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventHandlerFactory; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Properties; import static org.testng.Assert.assertTrue; /** */ public class MetadataCheckerComponentIT { private final static String TEST_BATCH_ID = "400022028241"; /** Tests that the BatchStructureChecker can parse a production like batch. */ @Test(groups = "integrationTest") public void testMetadataCheck() throws Exception { String pathToProperties = System.getProperty("integration.test.newspaper.properties"); Properties properties = new Properties(); properties.load(new FileInputStream(pathToProperties)); TreeIterator iterator = getIterator(); EventRunner batchStructureChecker = new EventRunner(iterator); ResultCollector resultCollector = new ResultCollector("Batch Structure Checker", "v0.1"); Batch batch = new Batch(); batch.setBatchID(TEST_BATCH_ID); batch.setRoundTripNumber(1); InputStream batchXmlStructureStream = retrieveBatchStructure(batch); if (batchXmlStructureStream == null) { throw new RuntimeException("Failed to resolve batch manifest from data collector"); } ByteArrayOutputStream temp = new ByteArrayOutputStream(); Streams.pipe(batchXmlStructureStream, temp); String batchXmlManifest = new String(temp.toByteArray(), "UTF-8"); MfPakConfiguration mfPakConfiguration = new MfPakConfiguration(); mfPakConfiguration.setDatabaseUrl(properties.getProperty(ConfigurationProperties.DATABASE_URL)); mfPakConfiguration.setDatabaseUser(properties.getProperty(ConfigurationProperties.DATABASE_USER)); mfPakConfiguration.setDatabasePassword(properties.getProperty(ConfigurationProperties.DATABASE_PASSWORD)); EventHandlerFactory eventHandlerFactory = new MetadataChecksFactory(resultCollector, true, getBatchFolder().getParentFile() .getAbsolutePath(), getJpylyzerPath(), null, new MfPakDAO(mfPakConfiguration), batch, batchXmlManifest); batchStructureChecker.runEvents(eventHandlerFactory.createEventHandlers()); System.out.println(resultCollector.toReport()); assertTrue(resultCollector.isSuccess()); //Assert.fail(); } private InputStream retrieveBatchStructure(Batch batch) { return Thread.currentThread().getContextClassLoader().getResourceAsStream("assumed-valid-structure.xml"); } private String getJpylyzerPath() { return "src/main/extras/jpylyzer-1.10.1/jpylyzer.py"; } /** * Creates and returns a iteration based on the test batch file structure found in the test/ressources folder. * * @return A iterator the the test batch * @throws URISyntaxException */ public TreeIterator getIterator() throws URISyntaxException { File file = getBatchFolder(); System.out.println(file); return new TransformingIteratorForFileSystems(file, "\\.", ".*\\.jp2$", ".md5"); } private File getBatchFolder() { String pathToTestBatch = System.getProperty("integration.test.newspaper.testdata"); return new File(pathToTestBatch, "small-test-batch/B" + TEST_BATCH_ID + "-RT1"); } }
Fixed test
src/test/java/dk/statsbiblioteket/newspaper/metadatachecker/MetadataCheckerComponentIT.java
Fixed test
<ide><path>rc/test/java/dk/statsbiblioteket/newspaper/metadatachecker/MetadataCheckerComponentIT.java <ide> package dk.statsbiblioteket.newspaper.metadatachecker; <del> <del>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; <del>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; <del>import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; <del>import dk.statsbiblioteket.util.Streams; <del>import org.testng.annotations.Test; <ide> <ide> import dk.statsbiblioteket.medieplatform.autonomous.Batch; <ide> import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; <ide> import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventHandlerFactory; <ide> import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; <ide> import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems; <add>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; <add>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; <add>import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; <add>import dk.statsbiblioteket.util.xml.DOM; <add>import org.testng.annotations.Test; <add>import org.w3c.dom.Document; <ide> <del>import java.io.ByteArrayOutputStream; <ide> import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.io.InputStream; <ide> if (batchXmlStructureStream == null) { <ide> throw new RuntimeException("Failed to resolve batch manifest from data collector"); <ide> } <del> ByteArrayOutputStream temp = new ByteArrayOutputStream(); <del> Streams.pipe(batchXmlStructureStream, temp); <del> String batchXmlManifest = new String(temp.toByteArray(), "UTF-8"); <add> Document batchXmlManifest = DOM.streamToDOM(batchXmlStructureStream); <ide> <ide> MfPakConfiguration mfPakConfiguration = new MfPakConfiguration(); <ide> mfPakConfiguration.setDatabaseUrl(properties.getProperty(ConfigurationProperties.DATABASE_URL));
JavaScript
mit
09a78cf52d6f965c5befb307f47e70c281f4102c
0
yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View, Image} from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); type Props = {}; class Greeting extends Component { render() { return ( <Text>Hello {this.props.name}!</Text> ); } } class Blink extends Component { constructor(props) { super(props); this.state = {isShowingText: true}; // Toggle the state every second setInterval(() => { this.setState(previousState => { return { isShowingText: !previousState.isShowingText }; }); }, 1000); } render() { let display = this.state.isShowingText ? this.props.text : ' '; return ( <Text>{display}</Text> ); } } export default class App extends Component<Props> { render() { let pic = { uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' }; return ( <View> <Text>Hello world!</Text> <Image source={pic} style={{width: 193, height: 110}}/> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> <Blink text='I love to blink' /> <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text> </View> ); } } const styles = StyleSheet.create({ bigblue: { color: 'blue', fontWeight: 'bold', fontSize: 30, }, red: { color: 'red', }, });
react-native/AwesomeProject/App.js
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View, Image} from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); type Props = {}; class Greeting extends Component { render() { return ( <Text>Hello {this.props.name}!</Text> ); } } class Blink extends Component { constructor(props) { super(props); this.state = {isShowingText: true}; // Toggle the state every second setInterval(() => { this.setState(previousState => { return { isShowingText: !previousState.isShowingText }; }); }, 1000); } render() { let display = this.state.isShowingText ? this.props.text : ' '; return ( <Text>{display}</Text> ); } } export default class App extends Component<Props> { render() { let pic = { uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' }; return ( <View> <Text>Hello world!</Text> <Image source={pic} style={{width: 193, height: 110}}/> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> <Blink text='I love to blink' /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
Add styles
react-native/AwesomeProject/App.js
Add styles
<ide><path>eact-native/AwesomeProject/App.js <ide> <Greeting name='Jaina' /> <ide> <Greeting name='Valeera' /> <ide> <Blink text='I love to blink' /> <add> <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text> <ide> </View> <ide> ); <ide> } <ide> } <ide> <ide> const styles = StyleSheet.create({ <del> container: { <del> flex: 1, <del> justifyContent: 'center', <del> alignItems: 'center', <del> backgroundColor: '#F5FCFF', <add> bigblue: { <add> color: 'blue', <add> fontWeight: 'bold', <add> fontSize: 30, <ide> }, <del> welcome: { <del> fontSize: 20, <del> textAlign: 'center', <del> margin: 10, <del> }, <del> instructions: { <del> textAlign: 'center', <del> color: '#333333', <del> marginBottom: 5, <add> red: { <add> color: 'red', <ide> }, <ide> });
Java
apache-2.0
ba560563bf5a3e34df7812083f33df374342ca85
0
CELAR/app-orchestrator,CELAR/app-orchestrator
/* * Copyright 2014 CELAR. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gr.ntua.cslab.orchestrator.rest; import static gr.ntua.cslab.database.EntityTools.store; //import gr.ntua.cslab.orchestrator.beans.DeploymentState; import gr.ntua.cslab.orchestrator.shared.ServerStaticComponents; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.GET; import javax.ws.rs.Path; import gr.ntua.cslab.celar.server.beans.DeploymentState; import static gr.ntua.cslab.database.DBConnectable.closeConnection; import static gr.ntua.cslab.database.DBConnectable.openConnection; import gr.ntua.cslab.orchestrator.beans.DeploymentState2; import java.io.ByteArrayOutputStream; import static java.util.logging.Level.*; /** * Service used to return the IP addresses of the VMs for the deployment. * * @author Giannis Giannakopoulos */ @Path("state/") public class DeploymentStateResource { static Logger logger = Logger.getLogger(DeploymentStateResource.class.getName()); private final static String deploymentId = ServerStaticComponents.properties.getProperty("slipstream.deployment.id"); // @GET // public DeploymentState getDeploymentState() { // HashMap<String,String> ipAddresses = null; // try { // ipAddresses=ServerStaticComponents.service.getDeploymentIPs(deploymentId); // } catch (Exception ex) { // Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); // } // return new DeploymentState(ipAddresses); // } @GET public static DeploymentState2 writeDeploymentState() { try { // openConnection(ServerStaticComponents.properties); Map<String,String> propsMap = ServerStaticComponents.service.getAllRuntimeParams(deploymentId); logger.log(INFO, "Got state map ({0} entries)", propsMap.size()); DeploymentState depState = new DeploymentState(propsMap, deploymentId); store(depState); logger.log(INFO, "stored Deployment State"); propsMap.put("timestamp", ""+depState.timestamp); return new DeploymentState2(depState.deployment_id, propsMap); } catch (Exception ex) { Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); } return null; } @Path("string/") @GET public static Map<String, String> writeDeploymentState2() { try { // openConnection(ServerStaticComponents.properties); Map<String, String> test = ServerStaticComponents.service.getAllRuntimeParams(deploymentId); logger.log(INFO, "Got state map ({0} entries)", test.size()); DeploymentState depState = new DeploymentState(test, deploymentId); store(depState); logger.log(INFO, "stored Deployment State"); // String rv = "Got deployment state and updated CelarDB\n"; // rv += "State: " + test.get("state") + "\n"; // rv += test; // return rv; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // depState.marshal(baos); // String s = new String( baos.toByteArray(), java.nio.charset.StandardCharsets.UTF_8 ); // return s; depState.deployment_state.put("timestamp", depState.timestamp); return depState.deployment_state; } catch (Exception ex) { Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
orchestrator-daemon/src/main/java/gr/ntua/cslab/orchestrator/rest/DeploymentStateResource.java
/* * Copyright 2014 CELAR. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gr.ntua.cslab.orchestrator.rest; import static gr.ntua.cslab.database.EntityTools.store; //import gr.ntua.cslab.orchestrator.beans.DeploymentState; import gr.ntua.cslab.orchestrator.shared.ServerStaticComponents; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.GET; import javax.ws.rs.Path; import gr.ntua.cslab.celar.server.beans.DeploymentState; import static gr.ntua.cslab.database.DBConnectable.closeConnection; import static gr.ntua.cslab.database.DBConnectable.openConnection; import java.io.ByteArrayOutputStream; import static java.util.logging.Level.*; /** * Service used to return the IP addresses of the VMs for the deployment. * * @author Giannis Giannakopoulos */ @Path("state/") public class DeploymentStateResource { static Logger logger = Logger.getLogger(DeploymentStateResource.class.getName()); private final static String deploymentId = ServerStaticComponents.properties.getProperty("slipstream.deployment.id"); // @GET // public DeploymentState getDeploymentState() { // HashMap<String,String> ipAddresses = null; // try { // ipAddresses=ServerStaticComponents.service.getDeploymentIPs(deploymentId); // } catch (Exception ex) { // Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); // } // return new DeploymentState(ipAddresses); // } @GET public static DeploymentState writeDeploymentState() { try { // openConnection(ServerStaticComponents.properties); Map<String,String> test = ServerStaticComponents.service.getAllRuntimeParams(deploymentId); logger.log(INFO, "Got state map ({0} entries)", test.size()); DeploymentState depState = new DeploymentState(test, deploymentId); store(depState); logger.log(INFO, "stored Deployment State"); return depState; } catch (Exception ex) { Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); } return null; } @Path("string/") @GET public static Map<String, String> writeDeploymentState2() { try { // openConnection(ServerStaticComponents.properties); Map<String, String> test = ServerStaticComponents.service.getAllRuntimeParams(deploymentId); logger.log(INFO, "Got state map ({0} entries)", test.size()); DeploymentState depState = new DeploymentState(test, deploymentId); store(depState); logger.log(INFO, "stored Deployment State"); // String rv = "Got deployment state and updated CelarDB\n"; // rv += "State: " + test.get("state") + "\n"; // rv += test; // return rv; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // depState.marshal(baos); // String s = new String( baos.toByteArray(), java.nio.charset.StandardCharsets.UTF_8 ); // return s; depState.deployment_state.put("timestamp", depState.timestamp); return depState.deployment_state; } catch (Exception ex) { Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
Deployment State workaround 2
orchestrator-daemon/src/main/java/gr/ntua/cslab/orchestrator/rest/DeploymentStateResource.java
Deployment State workaround 2
<ide><path>rchestrator-daemon/src/main/java/gr/ntua/cslab/orchestrator/rest/DeploymentStateResource.java <ide> import gr.ntua.cslab.celar.server.beans.DeploymentState; <ide> import static gr.ntua.cslab.database.DBConnectable.closeConnection; <ide> import static gr.ntua.cslab.database.DBConnectable.openConnection; <add>import gr.ntua.cslab.orchestrator.beans.DeploymentState2; <ide> import java.io.ByteArrayOutputStream; <ide> import static java.util.logging.Level.*; <ide> <ide> // } <ide> <ide> @GET <del> public static DeploymentState writeDeploymentState() { <add> public static DeploymentState2 writeDeploymentState() { <ide> try { <ide> // openConnection(ServerStaticComponents.properties); <del> Map<String,String> test = ServerStaticComponents.service.getAllRuntimeParams(deploymentId); <del> logger.log(INFO, "Got state map ({0} entries)", test.size()); <del> DeploymentState depState = new DeploymentState(test, deploymentId); <add> Map<String,String> propsMap = ServerStaticComponents.service.getAllRuntimeParams(deploymentId); <add> logger.log(INFO, "Got state map ({0} entries)", propsMap.size()); <add> DeploymentState depState = new DeploymentState(propsMap, deploymentId); <ide> store(depState); <ide> logger.log(INFO, "stored Deployment State"); <add> propsMap.put("timestamp", ""+depState.timestamp); <ide> <del> return depState; <add> return new DeploymentState2(depState.deployment_id, propsMap); <ide> } catch (Exception ex) { <ide> Logger.getLogger(DeploymentStateResource.class.getName()).log(Level.SEVERE, null, ex); <ide> }
Java
apache-2.0
507658e86ce85ea832e7bd7337ab49d1b06627f3
0
SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.gradle.compiler.validate; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.Descriptors.FieldDescriptor; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.spine.base.ConversionException; import io.spine.base.Types; import io.spine.gradle.compiler.message.MessageTypeCache; import io.spine.gradle.compiler.message.fieldtype.FieldType; import io.spine.gradle.compiler.message.fieldtype.ProtoScalarType; import io.spine.validate.ValidationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.lang.model.element.Modifier; import java.util.Collection; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static io.spine.gradle.compiler.util.JavaCode.toJavaFieldName; import static io.spine.gradle.compiler.validate.MethodConstructors.clearPrefix; import static io.spine.gradle.compiler.validate.MethodConstructors.clearProperty; import static io.spine.gradle.compiler.validate.MethodConstructors.createConvertSingularValue; import static io.spine.gradle.compiler.validate.MethodConstructors.createDescriptorStatement; import static io.spine.gradle.compiler.validate.MethodConstructors.createValidateStatement; import static io.spine.gradle.compiler.validate.MethodConstructors.getMessageBuilder; import static io.spine.gradle.compiler.validate.MethodConstructors.rawSuffix; import static io.spine.gradle.compiler.validate.MethodConstructors.removePrefix; import static io.spine.gradle.compiler.validate.MethodConstructors.returnThis; import static java.lang.String.format; /** * A method constructor of the {@code MethodSpec} objects based on the Protobuf message declaration. * * <p>Constructs the {@code MethodSpec} objects for the repeated fields. * * @author Illia Shepilov */ @SuppressWarnings("DuplicateStringLiteralInspection") // It cannot be used as the constant across the project. // Although it has the equivalent literal they have the different meaning. class RepeatedFieldMethodConstructor implements MethodConstructor { private static final String VALUE = "value"; private static final String INDEX = "index"; private static final String ADD_PREFIX = "add"; private static final String SET_PREFIX = "set"; private static final String ADD_RAW_PREFIX = "addRaw"; private static final String SET_RAW_PREFIX = "setRaw"; private static final String CONVERTED_VALUE = "convertedValue"; private final int fieldIndex; private final FieldType fieldType; private final String javaFieldName; private final String methodNamePart; private final ClassName builderClassName; private final ClassName listElementClassName; private final ClassName builderGenericClassName; private final FieldDescriptorProto fieldDescriptor; private final boolean isScalarType; /** * Constructs the {@code RepeatedFieldMethodConstructor}. * * @param builder the {@code RepeatedFieldMethodConstructorBuilder} instance */ @SuppressWarnings("ConstantConditions") // The fields are checked in the {@code #build()} method // of the {@code RepeatedFieldMethodsConstructorBuilder} class. private RepeatedFieldMethodConstructor(RepeatedFieldMethodsConstructorBuilder builder) { super(); this.fieldType = builder.getFieldType(); this.fieldIndex = builder.getFieldIndex(); this.fieldDescriptor = builder.getFieldDescriptor(); this.builderGenericClassName = builder.getGenericClassName(); this.javaFieldName = toJavaFieldName(fieldDescriptor.getName(), false); this.methodNamePart = toJavaFieldName(fieldDescriptor.getName(), true); final String javaClass = builder.getJavaClass(); final String javaPackage = builder.getJavaPackage(); this.builderClassName = ClassNames.getClassName(javaPackage, javaClass); final MessageTypeCache messageTypeCache = builder.getMessageTypeCache(); this.listElementClassName = ClassNames.getParameterClassName(fieldDescriptor, messageTypeCache); this.isScalarType = isScalarType(fieldDescriptor); } @Override public Collection<MethodSpec> construct() { log().trace("The methods construction for the {} repeated field is started.", javaFieldName); final List<MethodSpec> methods = newArrayList(); methods.add(createGetter()); methods.addAll(createRepeatedMethods()); methods.addAll(createRepeatedRawMethods()); log().trace("The methods construction for the {} repeated field is finished.", javaFieldName); return methods; } private MethodSpec createGetter() { log().trace("The getter construction for the repeated field is started."); final String methodName = "get" + methodNamePart; final ClassName rawType = ClassName.get(List.class); final ParameterizedTypeName returnType = ParameterizedTypeName.get(rawType, listElementClassName); final String returnStatement = format("return %s.get%sList()", getMessageBuilder(), methodNamePart); final MethodSpec methodSpec = MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PUBLIC) .returns(returnType) .addStatement(returnStatement) .build(); log().trace("The getter construction for the repeated field is finished."); return methodSpec; } private Collection<MethodSpec> createRepeatedRawMethods() { log().trace("The raw methods construction for the repeated field is is started."); final List<MethodSpec> methods = newArrayList(); methods.add(createRawAddObjectMethod()); methods.add(createRawSetObjectByIndexMethod()); methods.add(createRawAddAllMethod()); // Some methods are not available in Protobuf Message.Builder for scalar types. if (!isScalarType) { methods.add(createRawAddObjectByIndexMethod()); } log().trace("The raw methods construction for the repeated field is is finished."); return methods; } private Collection<MethodSpec> createRepeatedMethods() { final List<MethodSpec> methods = newArrayList(); methods.add(createClearMethod()); methods.add(createAddObjectMethod()); methods.add(createSetObjectByIndexMethod()); methods.add(createAddAllMethod()); // Some methods are not available in Protobuf Message.Builder for scalar types. if (!isScalarType) { methods.add(createAddObjectByIndexMethod()); methods.add(createRemoveObjectByIndexMethod()); } return methods; } private static boolean isScalarType(FieldDescriptorProto fieldDescriptor) { boolean isScalarType = false; final FieldDescriptorProto.Type type = fieldDescriptor.getType(); for (ProtoScalarType scalarType : ProtoScalarType.values()) { if (scalarType.getProtoScalarType() == type) { isScalarType = true; } } return isScalarType; } private MethodSpec createRawAddObjectMethod() { final String methodName = ADD_RAW_PREFIX + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String addValueStatement = getMessageBuilder() + '.' + ADD_PREFIX + methodNamePart + "(convertedValue)"; final String convertStatement = createValidateStatement(CONVERTED_VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(String.class, VALUE) .addException(ValidationException.class) .addException(ConversionException.class) .addStatement(createConvertSingularValue(VALUE), listElementClassName, listElementClassName) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(convertStatement, fieldDescriptor.getName()) .addStatement(addValueStatement) .addStatement(returnThis()) .build(); return result; } private MethodSpec createRawAddObjectByIndexMethod() { final MethodSpec result = modifyCollectionByIndexWithRaw(ADD_RAW_PREFIX, ADD_PREFIX); return result; } private MethodSpec createRawSetObjectByIndexMethod() { return modifyCollectionByIndexWithRaw(SET_RAW_PREFIX, SET_PREFIX); } @SuppressWarnings("MethodParameterNamingConvention") // named according to its meaning. private MethodSpec modifyCollectionByIndexWithRaw(String methodNamePrefix, String realBuilderCallPrefix) { final String methodName = methodNamePrefix + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String modificationStatement = format("%s.%s%s(%s, convertedValue)", getMessageBuilder(), realBuilderCallPrefix, methodNamePart, INDEX); final String convertStatement = createValidateStatement(CONVERTED_VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.INT, INDEX) .addParameter(String.class, VALUE) .addException(ValidationException.class) .addException(ConversionException.class) .addStatement(createConvertSingularValue(VALUE), listElementClassName, listElementClassName) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(convertStatement, fieldDescriptor.getName()) .addStatement(modificationStatement) .addStatement(returnThis()) .build(); return result; } private MethodSpec createRawAddAllMethod() { final String rawMethodName = fieldType.getSetterPrefix() + rawSuffix() + methodNamePart; final String methodName = toJavaFieldName(rawMethodName, false); final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String addAllValues = getMessageBuilder() + format(".addAll%s(%s)", methodNamePart, CONVERTED_VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(String.class, VALUE) .addException(ValidationException.class) .addException(ConversionException.class) .addStatement(createGetConvertedCollectionValue(), List.class, listElementClassName, Types.class, listElementClassName) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(CONVERTED_VALUE), fieldDescriptor.getName()) .addStatement(addAllValues) .addStatement(returnThis()) .build(); return result; } private MethodSpec createAddAllMethod() { final String methodName = fieldType.getSetterPrefix() + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final ClassName rawType = ClassName.get(List.class); final ParameterizedTypeName parameter = ParameterizedTypeName.get(rawType, listElementClassName); final String fieldName = fieldDescriptor.getName(); final String addAllValues = getMessageBuilder() + format(".addAll%s(%s)", methodNamePart, "value"); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(parameter, VALUE) .addException(ValidationException.class) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(VALUE), fieldName) .addStatement(addAllValues) .addStatement(returnThis()) .build(); return result; } private MethodSpec createAddObjectMethod() { final String methodName = ADD_PREFIX + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String addValue = format("%s.%s%s(%s)", getMessageBuilder(), ADD_PREFIX, methodNamePart, VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(listElementClassName, VALUE) .addException(ValidationException.class) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(VALUE), javaFieldName) .addStatement(addValue) .addStatement(returnThis()) .build(); return result; } private MethodSpec createAddObjectByIndexMethod() { return modifyCollectionByIndex(ADD_PREFIX); } private MethodSpec createSetObjectByIndexMethod() { return modifyCollectionByIndex(SET_PREFIX); } private MethodSpec createRemoveObjectByIndexMethod() { final String methodName = removePrefix() + methodNamePart; final String addValue = format("%s.%s%s(%s)", getMessageBuilder(), removePrefix(), methodNamePart, INDEX); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.INT, INDEX) .addStatement(addValue) .addStatement(returnThis()) .build(); return result; } private MethodSpec modifyCollectionByIndex(String methodPrefix) { final String methodName = methodPrefix + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String modificationStatement = format("%s.%s%s(%s, %s)", getMessageBuilder(), methodPrefix, methodNamePart, INDEX, VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.INT, INDEX) .addParameter(listElementClassName, VALUE) .addException(ValidationException.class) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(VALUE), javaFieldName) .addStatement(modificationStatement) .addStatement(returnThis()) .build(); return result; } private MethodSpec createClearMethod() { final String clearField = getMessageBuilder() + clearProperty(methodNamePart); final MethodSpec result = MethodSpec.methodBuilder(clearPrefix() + methodNamePart) .addModifiers(Modifier.PUBLIC) .returns(builderClassName) .addStatement(clearField) .addStatement(returnThis()) .build(); return result; } private static String createGetConvertedCollectionValue() { final String result = "final $T<$T> convertedValue = " + "convert(value, $T.listTypeOf($T.class))"; return result; } /** * Creates a new builder for the {@code RepeatedFieldMethodConstructor} class. * * @return created builder */ static RepeatedFieldMethodsConstructorBuilder newBuilder() { return new RepeatedFieldMethodsConstructorBuilder(); } /** * A builder for the {@code RepeatedFieldMethodConstructor} class. */ static class RepeatedFieldMethodsConstructorBuilder extends AbstractMethodConstructorBuilder<RepeatedFieldMethodConstructor> { @Override RepeatedFieldMethodConstructor build() { super.build(); return new RepeatedFieldMethodConstructor(this); } } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(RepeatedFieldMethodConstructor.class); } private static Logger log() { return LogSingleton.INSTANCE.value; } }
gradle-plugins/model-compiler/src/main/java/io/spine/gradle/compiler/validate/RepeatedFieldMethodConstructor.java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.gradle.compiler.validate; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.Descriptors.FieldDescriptor; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.spine.base.ConversionException; import io.spine.base.Types; import io.spine.gradle.compiler.message.MessageTypeCache; import io.spine.gradle.compiler.message.fieldtype.FieldType; import io.spine.gradle.compiler.message.fieldtype.ProtoScalarType; import io.spine.validate.ValidationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.lang.model.element.Modifier; import java.util.Collection; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static io.spine.gradle.compiler.util.JavaCode.toJavaFieldName; import static io.spine.gradle.compiler.validate.MethodConstructors.clearPrefix; import static io.spine.gradle.compiler.validate.MethodConstructors.clearProperty; import static io.spine.gradle.compiler.validate.MethodConstructors.createConvertSingularValue; import static io.spine.gradle.compiler.validate.MethodConstructors.createDescriptorStatement; import static io.spine.gradle.compiler.validate.MethodConstructors.createValidateStatement; import static io.spine.gradle.compiler.validate.MethodConstructors.getMessageBuilder; import static io.spine.gradle.compiler.validate.MethodConstructors.rawSuffix; import static io.spine.gradle.compiler.validate.MethodConstructors.returnThis; import static java.lang.String.format; /** * A method constructor of the {@code MethodSpec} objects based on the Protobuf message declaration. * * <p>Constructs the {@code MethodSpec} objects for the repeated fields. * * @author Illia Shepilov */ @SuppressWarnings("DuplicateStringLiteralInspection") // It cannot be used as the constant across the project. // Although it has the equivalent literal they have the different meaning. class RepeatedFieldMethodConstructor implements MethodConstructor { private static final String VALUE = "value"; private static final String INDEX = "index"; private static final String ADD_PREFIX = "add"; private static final String SET_PREFIX = "set"; private static final String REMOVE_PREFIX = "remove"; private static final String ADD_RAW_PREFIX = "addRaw"; private static final String SET_RAW_PREFIX = "setRaw"; private static final String CONVERTED_VALUE = "convertedValue"; private final int fieldIndex; private final FieldType fieldType; private final String javaFieldName; private final String methodNamePart; private final ClassName builderClassName; private final ClassName listElementClassName; private final ClassName builderGenericClassName; private final FieldDescriptorProto fieldDescriptor; private final boolean isScalarType; /** * Constructs the {@code RepeatedFieldMethodConstructor}. * * @param builder the {@code RepeatedFieldMethodConstructorBuilder} instance */ @SuppressWarnings("ConstantConditions") // The fields are checked in the {@code #build()} method // of the {@code RepeatedFieldMethodsConstructorBuilder} class. private RepeatedFieldMethodConstructor(RepeatedFieldMethodsConstructorBuilder builder) { super(); this.fieldType = builder.getFieldType(); this.fieldIndex = builder.getFieldIndex(); this.fieldDescriptor = builder.getFieldDescriptor(); this.builderGenericClassName = builder.getGenericClassName(); this.javaFieldName = toJavaFieldName(fieldDescriptor.getName(), false); this.methodNamePart = toJavaFieldName(fieldDescriptor.getName(), true); final String javaClass = builder.getJavaClass(); final String javaPackage = builder.getJavaPackage(); this.builderClassName = ClassNames.getClassName(javaPackage, javaClass); final MessageTypeCache messageTypeCache = builder.getMessageTypeCache(); this.listElementClassName = ClassNames.getParameterClassName(fieldDescriptor, messageTypeCache); this.isScalarType = isScalarType(fieldDescriptor); } @Override public Collection<MethodSpec> construct() { log().trace("The methods construction for the {} repeated field is started.", javaFieldName); final List<MethodSpec> methods = newArrayList(); methods.add(createGetter()); methods.addAll(createRepeatedMethods()); methods.addAll(createRepeatedRawMethods()); log().trace("The methods construction for the {} repeated field is finished.", javaFieldName); return methods; } private MethodSpec createGetter() { log().trace("The getter construction for the repeated field is started."); final String methodName = "get" + methodNamePart; final ClassName rawType = ClassName.get(List.class); final ParameterizedTypeName returnType = ParameterizedTypeName.get(rawType, listElementClassName); final String returnStatement = format("return %s.get%sList()", getMessageBuilder(), methodNamePart); final MethodSpec methodSpec = MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PUBLIC) .returns(returnType) .addStatement(returnStatement) .build(); log().trace("The getter construction for the repeated field is finished."); return methodSpec; } private Collection<MethodSpec> createRepeatedRawMethods() { log().trace("The raw methods construction for the repeated field is is started."); final List<MethodSpec> methods = newArrayList(); methods.add(createRawAddObjectMethod()); methods.add(createRawSetObjectByIndexMethod()); methods.add(createRawAddAllMethod()); // Some methods are not available in Protobuf Message.Builder for scalar types. if (!isScalarType) { methods.add(createRawAddObjectByIndexMethod()); } log().trace("The raw methods construction for the repeated field is is finished."); return methods; } private Collection<MethodSpec> createRepeatedMethods() { final List<MethodSpec> methods = newArrayList(); methods.add(createClearMethod()); methods.add(createAddObjectMethod()); methods.add(createSetObjectByIndexMethod()); methods.add(createAddAllMethod()); // Some methods are not available in Protobuf Message.Builder for scalar types. if (!isScalarType) { methods.add(createAddObjectByIndexMethod()); methods.add(createRemoveObjectByIndexMethod()); } return methods; } private static boolean isScalarType(FieldDescriptorProto fieldDescriptor) { boolean isScalarType = false; final FieldDescriptorProto.Type type = fieldDescriptor.getType(); for (ProtoScalarType scalarType : ProtoScalarType.values()) { if (scalarType.getProtoScalarType() == type) { isScalarType = true; } } return isScalarType; } private MethodSpec createRawAddObjectMethod() { final String methodName = ADD_RAW_PREFIX + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String addValueStatement = getMessageBuilder() + '.' + ADD_PREFIX + methodNamePart + "(convertedValue)"; final String convertStatement = createValidateStatement(CONVERTED_VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(String.class, VALUE) .addException(ValidationException.class) .addException(ConversionException.class) .addStatement(createConvertSingularValue(VALUE), listElementClassName, listElementClassName) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(convertStatement, fieldDescriptor.getName()) .addStatement(addValueStatement) .addStatement(returnThis()) .build(); return result; } private MethodSpec createRawAddObjectByIndexMethod() { final MethodSpec result = modifyCollectionByIndexWithRaw(ADD_RAW_PREFIX, ADD_PREFIX); return result; } private MethodSpec createRawSetObjectByIndexMethod() { return modifyCollectionByIndexWithRaw(SET_RAW_PREFIX, SET_PREFIX); } @SuppressWarnings("MethodParameterNamingConvention") // named according to its meaning. private MethodSpec modifyCollectionByIndexWithRaw(String methodNamePrefix, String realBuilderCallPrefix) { final String methodName = methodNamePrefix + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String modificationStatement = format("%s.%s%s(%s, convertedValue)", getMessageBuilder(), realBuilderCallPrefix, methodNamePart, INDEX); final String convertStatement = createValidateStatement(CONVERTED_VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.INT, INDEX) .addParameter(String.class, VALUE) .addException(ValidationException.class) .addException(ConversionException.class) .addStatement(createConvertSingularValue(VALUE), listElementClassName, listElementClassName) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(convertStatement, fieldDescriptor.getName()) .addStatement(modificationStatement) .addStatement(returnThis()) .build(); return result; } private MethodSpec createRawAddAllMethod() { final String rawMethodName = fieldType.getSetterPrefix() + rawSuffix() + methodNamePart; final String methodName = toJavaFieldName(rawMethodName, false); final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String addAllValues = getMessageBuilder() + format(".addAll%s(%s)", methodNamePart, CONVERTED_VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(String.class, VALUE) .addException(ValidationException.class) .addException(ConversionException.class) .addStatement(createGetConvertedCollectionValue(), List.class, listElementClassName, Types.class, listElementClassName) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(CONVERTED_VALUE), fieldDescriptor.getName()) .addStatement(addAllValues) .addStatement(returnThis()) .build(); return result; } private MethodSpec createAddAllMethod() { final String methodName = fieldType.getSetterPrefix() + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final ClassName rawType = ClassName.get(List.class); final ParameterizedTypeName parameter = ParameterizedTypeName.get(rawType, listElementClassName); final String fieldName = fieldDescriptor.getName(); final String addAllValues = getMessageBuilder() + format(".addAll%s(%s)", methodNamePart, "value"); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(parameter, VALUE) .addException(ValidationException.class) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(VALUE), fieldName) .addStatement(addAllValues) .addStatement(returnThis()) .build(); return result; } private MethodSpec createAddObjectMethod() { final String methodName = ADD_PREFIX + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String addValue = format("%s.%s%s(%s)", getMessageBuilder(), ADD_PREFIX, methodNamePart, VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(listElementClassName, VALUE) .addException(ValidationException.class) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(VALUE), javaFieldName) .addStatement(addValue) .addStatement(returnThis()) .build(); return result; } private MethodSpec createAddObjectByIndexMethod() { return modifyCollectionByIndex(ADD_PREFIX); } private MethodSpec createSetObjectByIndexMethod() { return modifyCollectionByIndex(SET_PREFIX); } private MethodSpec createRemoveObjectByIndexMethod() { final String methodName = REMOVE_PREFIX + methodNamePart; final String addValue = format("%s.%s%s(%s)", getMessageBuilder(), REMOVE_PREFIX, methodNamePart, INDEX); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.INT, INDEX) .addStatement(addValue) .addStatement(returnThis()) .build(); return result; } private MethodSpec modifyCollectionByIndex(String methodPrefix) { final String methodName = methodPrefix + methodNamePart; final String descriptorCodeLine = createDescriptorStatement(fieldIndex, builderGenericClassName); final String modificationStatement = format("%s.%s%s(%s, %s)", getMessageBuilder(), methodPrefix, methodNamePart, INDEX, VALUE); final MethodSpec result = MethodSpec.methodBuilder(methodName) .returns(builderClassName) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.INT, INDEX) .addParameter(listElementClassName, VALUE) .addException(ValidationException.class) .addStatement(descriptorCodeLine, FieldDescriptor.class) .addStatement(createValidateStatement(VALUE), javaFieldName) .addStatement(modificationStatement) .addStatement(returnThis()) .build(); return result; } private MethodSpec createClearMethod() { final String clearField = getMessageBuilder() + clearProperty(methodNamePart); final MethodSpec result = MethodSpec.methodBuilder(clearPrefix() + methodNamePart) .addModifiers(Modifier.PUBLIC) .returns(builderClassName) .addStatement(clearField) .addStatement(returnThis()) .build(); return result; } private static String createGetConvertedCollectionValue() { final String result = "final $T<$T> convertedValue = " + "convert(value, $T.listTypeOf($T.class))"; return result; } /** * Creates a new builder for the {@code RepeatedFieldMethodConstructor} class. * * @return created builder */ static RepeatedFieldMethodsConstructorBuilder newBuilder() { return new RepeatedFieldMethodsConstructorBuilder(); } /** * A builder for the {@code RepeatedFieldMethodConstructor} class. */ static class RepeatedFieldMethodsConstructorBuilder extends AbstractMethodConstructorBuilder<RepeatedFieldMethodConstructor> { @Override RepeatedFieldMethodConstructor build() { super.build(); return new RepeatedFieldMethodConstructor(this); } } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(RepeatedFieldMethodConstructor.class); } private static Logger log() { return LogSingleton.INSTANCE.value; } }
Reuse `removePrefix()` instead of a constant.
gradle-plugins/model-compiler/src/main/java/io/spine/gradle/compiler/validate/RepeatedFieldMethodConstructor.java
Reuse `removePrefix()` instead of a constant.
<ide><path>radle-plugins/model-compiler/src/main/java/io/spine/gradle/compiler/validate/RepeatedFieldMethodConstructor.java <ide> import static io.spine.gradle.compiler.validate.MethodConstructors.createValidateStatement; <ide> import static io.spine.gradle.compiler.validate.MethodConstructors.getMessageBuilder; <ide> import static io.spine.gradle.compiler.validate.MethodConstructors.rawSuffix; <add>import static io.spine.gradle.compiler.validate.MethodConstructors.removePrefix; <ide> import static io.spine.gradle.compiler.validate.MethodConstructors.returnThis; <ide> import static java.lang.String.format; <ide> <ide> private static final String INDEX = "index"; <ide> private static final String ADD_PREFIX = "add"; <ide> private static final String SET_PREFIX = "set"; <del> private static final String REMOVE_PREFIX = "remove"; <ide> private static final String ADD_RAW_PREFIX = "addRaw"; <ide> private static final String SET_RAW_PREFIX = "setRaw"; <ide> private static final String CONVERTED_VALUE = "convertedValue"; <ide> } <ide> <ide> private MethodSpec createRemoveObjectByIndexMethod() { <del> final String methodName = REMOVE_PREFIX + methodNamePart; <add> final String methodName = removePrefix() + methodNamePart; <ide> final String addValue = format("%s.%s%s(%s)", getMessageBuilder(), <del> REMOVE_PREFIX, methodNamePart, INDEX); <add> removePrefix(), methodNamePart, INDEX); <ide> final MethodSpec result = MethodSpec.methodBuilder(methodName) <ide> .returns(builderClassName) <ide> .addModifiers(Modifier.PUBLIC)
Java
mit
error: pathspec 'src/service/flow/flow.java' did not match any file(s) known to git
f947f508a394d301afce9cf6e1c0d07f08414020
1
fulapay/fulapay-demo,fulapay/fulapay-demo,fulapay/fulapay-demo,fulapay/fulapay-demo,fulapay/fulapay-demo
package service.flow; import config.Config; import util.HttpsUtil; import util.PayUtil; import util.XmlUtil; import java.util.SortedMap; import java.util.TreeMap; /** * Created by 87119 on 2017/3/4. */ public class flow { public static void main(String[] args) { SortedMap<String, String> param = new TreeMap(); param.put("service", "flow.buyflow"); param.put("mobile", "18658161306"); param.put("flow_id", "500000020"); System.out.println(">>>>post sign map: " + param); String xmlStr = PayUtil.buildRequestXml(param); System.out.println(">>>>post xmlStr: " + xmlStr); String resText = HttpsUtil.post("http://localhost:8080/flow/buyFlow", xmlStr, Config.CHARSET); System.out.println("<<<<resText: " + resText); // 验签后取得支付数据 try { SortedMap<String, String> result = XmlUtil.doXMLParse(resText); System.out.println("<<<<res map: " + result); if (PayUtil.verifyFulaParam(result)) { System.out.println("<<<<verify success-----------------"); System.out.println("<<<<流量充值结果:" + result); } else { System.out.println("<<<<verify fail-----------------"); } } catch (Exception e) { e.printStackTrace(); } } }
src/service/flow/flow.java
update
src/service/flow/flow.java
update
<ide><path>rc/service/flow/flow.java <add>package service.flow; <add> <add>import config.Config; <add>import util.HttpsUtil; <add>import util.PayUtil; <add>import util.XmlUtil; <add> <add>import java.util.SortedMap; <add>import java.util.TreeMap; <add> <add>/** <add> * Created by 87119 on 2017/3/4. <add> */ <add>public class flow { <add> public static void main(String[] args) { <add> SortedMap<String, String> param = new TreeMap(); <add> param.put("service", "flow.buyflow"); <add> param.put("mobile", "18658161306"); <add> param.put("flow_id", "500000020"); <add> System.out.println(">>>>post sign map: " + param); <add> String xmlStr = PayUtil.buildRequestXml(param); <add> System.out.println(">>>>post xmlStr: " + xmlStr); <add> String resText = HttpsUtil.post("http://localhost:8080/flow/buyFlow", xmlStr, Config.CHARSET); <add> System.out.println("<<<<resText: " + resText); <add> // 验签后取得支付数据 <add> try { <add> SortedMap<String, String> result = XmlUtil.doXMLParse(resText); <add> System.out.println("<<<<res map: " + result); <add> if (PayUtil.verifyFulaParam(result)) { <add> System.out.println("<<<<verify success-----------------"); <add> System.out.println("<<<<流量充值结果:" + result); <add> } else { <add> System.out.println("<<<<verify fail-----------------"); <add> } <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } <add> } <add>}
Java
apache-2.0
ecadd0ec2bc5716f9c0602f4bd1ee7660b275c26
0
kool79/intellij-community,caot/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,consulo/consulo,tmpgit/intellij-community,caot/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,caot/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,allotria/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,dslomov/intellij-community,supersven/intellij-community,blademainer/intellij-community,holmes/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,caot/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ryano144/intellij-community,kdwink/intellij-community,semonte/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,signed/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,FHannes/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,nicolargo/intellij-community,signed/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,consulo/consulo,jagguli/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,holmes/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,semonte/intellij-community,suncycheng/intellij-community,holmes/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,vladmm/intellij-community,FHannes/intellij-community,holmes/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,slisson/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,ryano144/intellij-community,allotria/intellij-community,semonte/intellij-community,robovm/robovm-studio,holmes/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ibinti/intellij-community,apixandru/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,signed/intellij-community,signed/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fnouama/intellij-community,ernestp/consulo,SerCeMan/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,da1z/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,hurricup/intellij-community,izonder/intellij-community,supersven/intellij-community,dslomov/intellij-community,caot/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,izonder/intellij-community,Distrotech/intellij-community,consulo/consulo,pwoodworth/intellij-community,allotria/intellij-community,allotria/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,adedayo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,samthor/intellij-community,akosyakov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,consulo/consulo,robovm/robovm-studio,asedunov/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,apixandru/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,holmes/intellij-community,caot/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ernestp/consulo,caot/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ahb0327/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,kool79/intellij-community,fitermay/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,slisson/intellij-community,blademainer/intellij-community,diorcety/intellij-community,FHannes/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,consulo/consulo,akosyakov/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,kool79/intellij-community,fitermay/intellij-community,apixandru/intellij-community,kdwink/intellij-community,FHannes/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,kdwink/intellij-community,kool79/intellij-community,apixandru/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,izonder/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,da1z/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,semonte/intellij-community,FHannes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,caot/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,samthor/intellij-community,adedayo/intellij-community,FHannes/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,supersven/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fitermay/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,signed/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ernestp/consulo,salguarnieri/intellij-community,ernestp/consulo,retomerz/intellij-community,robovm/robovm-studio,diorcety/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,signed/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,izonder/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,amith01994/intellij-community,vladmm/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,retomerz/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,apixandru/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,orekyuu/intellij-community,caot/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,hurricup/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,slisson/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,holmes/intellij-community,caot/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,allotria/intellij-community,asedunov/intellij-community,blademainer/intellij-community,kool79/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,slisson/intellij-community,hurricup/intellij-community,robovm/robovm-studio,adedayo/intellij-community,adedayo/intellij-community,apixandru/intellij-community,dslomov/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,samthor/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,samthor/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,hurricup/intellij-community,allotria/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,clumsy/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,vladmm/intellij-community,FHannes/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,samthor/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,holmes/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,petteyg/intellij-community,diorcety/intellij-community,blademainer/intellij-community,holmes/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,retomerz/intellij-community,supersven/intellij-community,jagguli/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fitermay/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,petteyg/intellij-community,petteyg/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,allotria/intellij-community,da1z/intellij-community,samthor/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,signed/intellij-community,kool79/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,FHannes/intellij-community,fitermay/intellij-community,supersven/intellij-community,FHannes/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.search; import com.intellij.codeInsight.CommentUtil; import com.intellij.concurrency.JobUtil; import com.intellij.ide.todo.TodoIndexPatternProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.ReadActionProcessor; import com.intellij.openapi.application.Result; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.impl.cache.impl.IndexCacheManagerImpl; import com.intellij.psi.impl.cache.impl.id.IdIndex; import com.intellij.psi.impl.cache.impl.id.IdIndexEntry; import com.intellij.psi.search.*; import com.intellij.psi.search.searches.IndexPatternSearch; import com.intellij.psi.util.PsiUtilBase; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.SmartList; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.containers.MultiMap; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.text.StringSearcher; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class PsiSearchHelperImpl implements PsiSearchHelper { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.PsiSearchHelperImpl"); private final PsiManagerEx myManager; private static final TodoItem[] EMPTY_TODO_ITEMS = new TodoItem[0]; @Override @NotNull public SearchScope getUseScope(@NotNull PsiElement element) { SearchScope scope = element.getUseScope(); for (UseScopeEnlarger enlarger : UseScopeEnlarger.EP_NAME.getExtensions()) { final SearchScope additionalScope = enlarger.getAdditionalUseScope(element); if (additionalScope != null) { scope = scope.union(additionalScope); } } return scope; } public PsiSearchHelperImpl(PsiManagerEx manager) { myManager = manager; } @Override @NotNull public PsiFile[] findFilesWithTodoItems() { return CacheManager.SERVICE.getInstance(myManager.getProject()).getFilesWithTodoItems(); } @Override @NotNull public TodoItem[] findTodoItems(@NotNull PsiFile file) { return findTodoItems(file, 0, file.getTextLength()); } @Override @NotNull public TodoItem[] findTodoItems(@NotNull PsiFile file, int startOffset, int endOffset) { final Collection<IndexPatternOccurrence> occurrences = IndexPatternSearch.search(file, TodoIndexPatternProvider.getInstance()).findAll(); if (occurrences.isEmpty()) { return EMPTY_TODO_ITEMS; } return processTodoOccurences(startOffset, endOffset, occurrences); } private TodoItem[] processTodoOccurences(int startOffset, int endOffset, Collection<IndexPatternOccurrence> occurrences) { List<TodoItem> items = new ArrayList<TodoItem>(occurrences.size()); TextRange textRange = new TextRange(startOffset, endOffset); final TodoItemsCreator todoItemsCreator = new TodoItemsCreator(); for(IndexPatternOccurrence occurrence: occurrences) { TextRange occurrenceRange = occurrence.getTextRange(); if (textRange.contains(occurrenceRange)) { items.add(todoItemsCreator.createTodo(occurrence)); } } return items.toArray(new TodoItem[items.size()]); } @NotNull @Override public TodoItem[] findTodoItemsLight(@NotNull PsiFile file) { return findTodoItemsLight(file, 0, file.getTextLength()); } @NotNull @Override public TodoItem[] findTodoItemsLight(@NotNull PsiFile file, int startOffset, int endOffset) { final Collection<IndexPatternOccurrence> occurrences = LightIndexPatternSearch.SEARCH.createQuery(new IndexPatternSearch.SearchParameters(file, TodoIndexPatternProvider.getInstance())).findAll(); if (occurrences.isEmpty()) { return EMPTY_TODO_ITEMS; } return processTodoOccurences(startOffset, endOffset, occurrences); } @Override public int getTodoItemsCount(@NotNull PsiFile file) { int count = CacheManager.SERVICE.getInstance(myManager.getProject()).getTodoCount(file.getVirtualFile(), TodoIndexPatternProvider.getInstance()); if (count != -1) return count; return findTodoItems(file).length; } @Override public int getTodoItemsCount(@NotNull PsiFile file, @NotNull TodoPattern pattern) { int count = CacheManager.SERVICE.getInstance(myManager.getProject()).getTodoCount(file.getVirtualFile(), pattern.getIndexPattern()); if (count != -1) return count; TodoItem[] items = findTodoItems(file); count = 0; for (TodoItem item : items) { if (item.getPattern().equals(pattern)) count++; } return count; } @Override @NotNull public PsiElement[] findCommentsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope) { final ArrayList<PsiElement> results = new ArrayList<PsiElement>(); processCommentsContainingIdentifier(identifier, searchScope, new Processor<PsiElement>() { @Override public boolean process(PsiElement element) { synchronized (results) { results.add(element); } return true; } }); synchronized (results) { return PsiUtilBase.toPsiElementArray(results); } } @Override public boolean processCommentsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope, @NotNull final Processor<PsiElement> processor) { TextOccurenceProcessor occurrenceProcessor = new TextOccurenceProcessor() { @Override public boolean execute(PsiElement element, int offsetInElement) { if (CommentUtil.isCommentTextElement(element)) { if (element.findReferenceAt(offsetInElement) == null) { return processor.process(element); } } return true; } }; return processElementsWithWord(occurrenceProcessor, searchScope, identifier, UsageSearchContext.IN_COMMENTS, true); } @Override public boolean processElementsWithWord(@NotNull final TextOccurenceProcessor processor, @NotNull SearchScope searchScope, @NotNull final String text, short searchContext, final boolean caseSensitively) { if (text.length() == 0) { throw new IllegalArgumentException("Cannot search for elements with empty text"); } final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); if (searchScope instanceof GlobalSearchScope) { StringSearcher searcher = new StringSearcher(text, caseSensitively, true); return processElementsWithTextInGlobalScope(processor, (GlobalSearchScope)searchScope, searcher, searchContext, caseSensitively, progress); } else { LocalSearchScope scope = (LocalSearchScope)searchScope; PsiElement[] scopeElements = scope.getScope(); final boolean ignoreInjectedPsi = scope.isIgnoreInjectedPsi(); return JobUtil.invokeConcurrentlyUnderProgress(Arrays.asList(scopeElements), progress, false, new Processor<PsiElement>() { @Override public boolean process(PsiElement scopeElement) { return processElementsWithWordInScopeElement(scopeElement, processor, text, caseSensitively, ignoreInjectedPsi, progress); } }); } } private static boolean processElementsWithWordInScopeElement(final PsiElement scopeElement, final TextOccurenceProcessor processor, final String word, final boolean caseSensitive, final boolean ignoreInjectedPsi, final ProgressIndicator progress) { return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { @Override public Boolean compute() { StringSearcher searcher = new StringSearcher(word, caseSensitive, true); return LowLevelSearchUtil.processElementsContainingWordInElement(processor, scopeElement, searcher, !ignoreInjectedPsi, progress); } }).booleanValue(); } private boolean processElementsWithTextInGlobalScope(@NotNull final TextOccurenceProcessor processor, @NotNull final GlobalSearchScope scope, @NotNull final StringSearcher searcher, final short searchContext, final boolean caseSensitively, final ProgressIndicator progress) { LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "You must not run search from within updating PSI activity. Please consider invokeLatering it instead."); if (progress != null) { progress.pushState(); progress.setText(PsiBundle.message("psi.scanning.files.progress")); } String text = searcher.getPattern(); List<VirtualFile> fileSet = getFilesWithText(scope, searchContext, caseSensitively, text, progress); if (progress != null) { progress.setText(PsiBundle.message("psi.search.for.word.progress", text)); } try { return processPsiFileRoots(fileSet, new Processor<PsiElement>() { @Override public boolean process(PsiElement psiRoot) { return LowLevelSearchUtil.processElementsContainingWordInElement(processor, psiRoot, searcher, true, progress); } }, progress); } finally { if (progress != null) { progress.popState(); } } } private boolean processPsiFileRoots(@NotNull List<VirtualFile> files, @NotNull final Processor<PsiElement> psiRootProcessor, final ProgressIndicator progress) { myManager.startBatchFilesProcessingMode(); try { final AtomicInteger counter = new AtomicInteger(0); final AtomicBoolean canceled = new AtomicBoolean(false); final AtomicBoolean pceThrown = new AtomicBoolean(false); final int size = files.size(); boolean completed = JobUtil.invokeConcurrentlyUnderProgress(files, progress, false, new Processor<VirtualFile>() { @Override public boolean process(final VirtualFile vfile) { final PsiFile file = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() { @Override public PsiFile compute() { return myManager.findFile(vfile); } }); if (file != null && !(file instanceof PsiBinaryFile)) { file.getViewProvider().getContents(); // load contents outside readaction ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { try { if (myManager.getProject().isDisposed()) throw new ProcessCanceledException(); PsiElement[] psiRoots = file.getPsiRoots(); Set<PsiElement> processed = new HashSet<PsiElement>(psiRoots.length * 2, (float)0.5); for (PsiElement psiRoot : psiRoots) { if (progress != null) progress.checkCanceled(); if (!processed.add(psiRoot)) continue; if (!psiRootProcessor.process(psiRoot)) { canceled.set(true); return; } } myManager.dropResolveCaches(); } catch (ProcessCanceledException e) { canceled.set(true); pceThrown.set(true); } } }); } if (progress != null && progress.isRunning()) { double fraction = (double)counter.incrementAndGet() / size; progress.setFraction(fraction); } return !canceled.get(); } }); if (pceThrown.get()) { throw new ProcessCanceledException(); } return completed; } finally { myManager.finishBatchFilesProcessingMode(); } } @NotNull private List<VirtualFile> getFilesWithText(@NotNull GlobalSearchScope scope, final short searchContext, final boolean caseSensitively, @NotNull String text, ProgressIndicator progress) { myManager.startBatchFilesProcessingMode(); try { final List<VirtualFile> result = new ArrayList<VirtualFile>(); boolean success = processFilesWithText( scope, searchContext, caseSensitively, text, new CommonProcessors.CollectProcessor<VirtualFile>(result), progress ); LOG.assertTrue(success); return result; } finally { myManager.finishBatchFilesProcessingMode(); } } public boolean processFilesWithText(@NotNull final GlobalSearchScope scope, final short searchContext, final boolean caseSensitively, @NotNull String text, @NotNull final Processor<VirtualFile> processor, @Nullable ProgressIndicator progress) { List<String> words = StringUtil.getWordsIn(text); if (words.isEmpty()) return true; Collections.sort(words, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.length() - o1.length(); } }); final Set<VirtualFile> fileSet; CacheManager cacheManager = CacheManager.SERVICE.getInstance(myManager.getProject()); if (words.size() > 1) { fileSet = new THashSet<VirtualFile>(); Set<VirtualFile> copy = new THashSet<VirtualFile>(); for (int i = 0; i < words.size() - 1; i++) { if (progress != null) { progress.checkCanceled(); } else { ProgressManager.checkCanceled(); } final String word = words.get(i); final int finalI = i; cacheManager.collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(i != 0 ? copy:fileSet) { @Override protected boolean accept(VirtualFile virtualFile) { return finalI == 0 || fileSet.contains(virtualFile); } }, word, searchContext, scope, caseSensitively); if (i != 0) { fileSet.retainAll(copy); } copy.clear(); if (fileSet.isEmpty()) break; } if (fileSet.isEmpty()) return true; } else { fileSet = null; } final String lastWord = words.get(words.size() - 1); if (processor instanceof CommonProcessors.CollectProcessor) { final CommonProcessors.CollectProcessor collectProcessor = (CommonProcessors.CollectProcessor)processor; return cacheManager.collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(collectProcessor.getResults()) { @Override public boolean process(VirtualFile virtualFile) { if (fileSet == null || fileSet.contains(virtualFile)) return collectProcessor.process(virtualFile); return true; } }, lastWord, searchContext, scope, caseSensitively); } else { THashSet<VirtualFile> files = new THashSet<VirtualFile>(); cacheManager.collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(files) { @Override protected boolean accept(VirtualFile virtualFile) { return fileSet == null || fileSet.contains(virtualFile); } }, lastWord, searchContext, scope, caseSensitively); ReadActionProcessor<VirtualFile> readActionProcessor = new ReadActionProcessor<VirtualFile>() { @Override public boolean processInReadAction(VirtualFile virtualFile) { return processor.process(virtualFile); } }; for(VirtualFile file:files) { if (!readActionProcessor.process(file)) return false; } return true; } } @Override @NotNull public PsiFile[] findFilesWithPlainTextWords(@NotNull String word) { return CacheManager.SERVICE.getInstance(myManager.getProject()).getFilesWithWord(word, UsageSearchContext.IN_PLAIN_TEXT, GlobalSearchScope.projectScope(myManager.getProject()), true); } @Override public void processUsagesInNonJavaFiles(@NotNull String qName, @NotNull PsiNonJavaFileReferenceProcessor processor, @NotNull GlobalSearchScope searchScope) { processUsagesInNonJavaFiles(null, qName, processor, searchScope); } @Override public void processUsagesInNonJavaFiles(@Nullable final PsiElement originalElement, @NotNull String qName, @NotNull final PsiNonJavaFileReferenceProcessor processor, @NotNull GlobalSearchScope searchScope) { if (qName.length() == 0) { throw new IllegalArgumentException("Cannot search for elements with empty text"); } final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); int dotIndex = qName.lastIndexOf('.'); int dollarIndex = qName.lastIndexOf('$'); int maxIndex = Math.max(dotIndex, dollarIndex); final String wordToSearch = maxIndex >= 0 ? qName.substring(maxIndex + 1) : qName; if (originalElement != null && myManager.isInProject(originalElement) && searchScope.isSearchInLibraries()) { searchScope = searchScope.intersectWith(GlobalSearchScope.projectScope(myManager.getProject())); } final GlobalSearchScope theSearchScope = searchScope; PsiFile[] files = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile[]>() { @Override public PsiFile[] compute() { return CacheManager.SERVICE.getInstance(myManager.getProject()).getFilesWithWord(wordToSearch, UsageSearchContext.IN_PLAIN_TEXT, theSearchScope, true); } }); final StringSearcher searcher = new StringSearcher(qName, true, true); if (progress != null) { progress.pushState(); progress.setText(PsiBundle.message("psi.search.in.non.java.files.progress")); } final SearchScope useScope = new ReadAction<SearchScope>() { @Override protected void run(final Result<SearchScope> result) { if (originalElement != null) { result.setResult(getUseScope(originalElement)); } } }.execute().getResultObject(); final Ref<Boolean> cancelled = new Ref<Boolean>(Boolean.FALSE); final GlobalSearchScope finalScope = searchScope; for (int i = 0; i < files.length; i++) { if (progress != null) progress.checkCanceled(); final PsiFile psiFile = files[i]; ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { CharSequence text = psiFile.getViewProvider().getContents(); for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher, progress); index >= 0;) { PsiReference referenceAt = psiFile.findReferenceAt(index); if (referenceAt == null || useScope == null || !PsiSearchScopeUtil.isInScope(useScope.intersectWith(finalScope), psiFile)) { if (!processor.process(psiFile, index, index + searcher.getPattern().length())) { cancelled.set(Boolean.TRUE); return; } } index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length(), searcher, progress); } } }); if (cancelled.get()) break; if (progress != null) { progress.setFraction((double)(i + 1) / files.length); } } if (progress != null) { progress.popState(); } } @Override public void processAllFilesWithWord(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor, final boolean caseSensitively) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_CODE, scope, caseSensitively); } @Override public void processAllFilesWithWordInText(@NotNull final String word, @NotNull final GlobalSearchScope scope, @NotNull final Processor<PsiFile> processor, final boolean caseSensitively) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_PLAIN_TEXT, scope, caseSensitively); } @Override public void processAllFilesWithWordInComments(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_COMMENTS, scope, true); } @Override public void processAllFilesWithWordInLiterals(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_STRINGS, scope, true); } private static class RequestWithProcessor { final PsiSearchRequest request; Processor<PsiReference> refProcessor; private RequestWithProcessor(PsiSearchRequest first, Processor<PsiReference> second) { request = first; refProcessor = second; } boolean uniteWith(final RequestWithProcessor another) { if (request.equals(another.request)) { final Processor<PsiReference> myProcessor = refProcessor; if (myProcessor != another.refProcessor) { refProcessor = new Processor<PsiReference>() { @Override public boolean process(PsiReference psiReference) { return myProcessor.process(psiReference) && another.refProcessor.process(psiReference); } }; } return true; } return false; } @Override public String toString() { return request.toString(); } } @Override public boolean processRequests(@NotNull SearchRequestCollector collector, @NotNull Processor<PsiReference> processor) { Map<SearchRequestCollector, Processor<PsiReference>> collectors = CollectionFactory.hashMap(); collectors.put(collector, processor); appendCollectorsFromQueryRequests(collectors); ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); do { final MultiMap<Set<IdIndexEntry>, RequestWithProcessor> globals = new MultiMap<Set<IdIndexEntry>, RequestWithProcessor>(); final List<Computable<Boolean>> customs = CollectionFactory.arrayList(); final LinkedHashSet<RequestWithProcessor> locals = CollectionFactory.linkedHashSet(); distributePrimitives(collectors, locals, globals, customs); if (!processGlobalRequestsOptimized(globals, progress)) { return false; } for (RequestWithProcessor local : locals) { if (!processSingleRequest(local.request, local.refProcessor)) { return false; } } for (Computable<Boolean> custom : customs) { if (!custom.compute()) { return false; } } } while (appendCollectorsFromQueryRequests(collectors)); return true; } private static boolean appendCollectorsFromQueryRequests(Map<SearchRequestCollector, Processor<PsiReference>> collectors) { boolean changed = false; LinkedList<SearchRequestCollector> queue = new LinkedList<SearchRequestCollector>(collectors.keySet()); while (!queue.isEmpty()) { final SearchRequestCollector each = queue.removeFirst(); for (QuerySearchRequest request : each.takeQueryRequests()) { request.runQuery(); collectors.put(request.collector, request.processor); queue.addLast(request.collector); changed = true; } } return changed; } private boolean processGlobalRequestsOptimized(MultiMap<Set<IdIndexEntry>, RequestWithProcessor> singles, final ProgressIndicator progress) { if (singles.isEmpty()) { return true; } if (singles.size() == 1) { final Collection<RequestWithProcessor> requests = singles.get(singles.keySet().iterator().next()); if (requests.size() == 1) { final RequestWithProcessor theOnly = requests.iterator().next(); return processSingleRequest(theOnly.request, theOnly.refProcessor); } } if (progress != null) { progress.pushState(); progress.setText(PsiBundle.message("psi.scanning.files.progress")); } final MultiMap<VirtualFile, RequestWithProcessor> candidateFiles = collectFiles(singles, progress); try { if (candidateFiles.isEmpty()) { return true; } final Map<RequestWithProcessor, StringSearcher> searchers = new HashMap<RequestWithProcessor, StringSearcher>(); final Set<String> allWords = new TreeSet<String>(); for (RequestWithProcessor singleRequest : candidateFiles.values()) { searchers.put(singleRequest, new StringSearcher(singleRequest.request.word, singleRequest.request.caseSensitive, true)); allWords.add(singleRequest.request.word); } if (progress != null) { final StringBuilder result = new StringBuilder(); for (String string : allWords) { if (string != null && string.length() != 0) { if (result.length() > 50) { result.append("..."); break; } if (result.length() != 0) result.append(", "); result.append(string); } } progress.setText(PsiBundle.message("psi.search.for.word.progress", result.toString())); } return processPsiFileRoots(new ArrayList<VirtualFile>(candidateFiles.keySet()), new Processor<PsiElement>() { @Override public boolean process(PsiElement psiRoot) { final VirtualFile vfile = psiRoot.getContainingFile().getVirtualFile(); for (final RequestWithProcessor singleRequest : candidateFiles.get(vfile)) { StringSearcher searcher = searchers.get(singleRequest); TextOccurenceProcessor adapted = adaptProcessor(singleRequest.request, singleRequest.refProcessor); if (!LowLevelSearchUtil.processElementsContainingWordInElement(adapted, psiRoot, searcher, true, progress)) { return false; } } return true; } }, progress); } finally { if (progress != null) { progress.popState(); } } } private static TextOccurenceProcessor adaptProcessor(final PsiSearchRequest singleRequest, final Processor<PsiReference> consumer) { final SearchScope searchScope = singleRequest.searchScope; final boolean ignoreInjectedPsi = searchScope instanceof LocalSearchScope && ((LocalSearchScope)searchScope).isIgnoreInjectedPsi(); final RequestResultProcessor wrapped = singleRequest.processor; return new TextOccurenceProcessor() { @Override public boolean execute(PsiElement element, int offsetInElement) { if (ignoreInjectedPsi && element instanceof PsiLanguageInjectionHost) return true; return wrapped.processTextOccurrence(element, offsetInElement, consumer); } }; } private MultiMap<VirtualFile, RequestWithProcessor> collectFiles(MultiMap<Set<IdIndexEntry>, RequestWithProcessor> singles, ProgressIndicator progress) { final FileIndexFacade index = FileIndexFacade.getInstance(myManager.getProject()); final MultiMap<VirtualFile, RequestWithProcessor> result = createMultiMap(); for (Set<IdIndexEntry> key : singles.keySet()) { if (key.isEmpty()) { continue; } final Collection<RequestWithProcessor> data = singles.get(key); GlobalSearchScope commonScope = uniteScopes(data); MultiMap<VirtualFile, RequestWithProcessor> intersection = null; boolean first = true; for (IdIndexEntry entry : key) { final MultiMap<VirtualFile, RequestWithProcessor> local = findFilesWithIndexEntry(entry, index, data, commonScope, progress); if (first) { intersection = local; first = false; } else { intersection.keySet().retainAll(local.keySet()); for (VirtualFile file : intersection.keySet()) { intersection.get(file).retainAll(local.get(file)); } } } result.putAllValues(intersection); } return result; } private static MultiMap<VirtualFile, RequestWithProcessor> createMultiMap() { return new MultiMap<VirtualFile, RequestWithProcessor>(){ @Override protected Collection<RequestWithProcessor> createCollection() { return new SmartList<RequestWithProcessor>(); // usually there is just one request } }; } private static GlobalSearchScope uniteScopes(Collection<RequestWithProcessor> requests) { GlobalSearchScope commonScope = null; for (RequestWithProcessor r : requests) { final GlobalSearchScope scope = (GlobalSearchScope)r.request.searchScope; commonScope = commonScope == null ? scope : commonScope.uniteWith(scope); } assert commonScope != null; return commonScope; } private static MultiMap<VirtualFile, RequestWithProcessor> findFilesWithIndexEntry(final IdIndexEntry entry, final FileIndexFacade index, final Collection<RequestWithProcessor> data, final GlobalSearchScope commonScope, final ProgressIndicator progress) { final MultiMap<VirtualFile, RequestWithProcessor> local = createMultiMap(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { if (progress != null) progress.checkCanceled(); FileBasedIndex.getInstance().processValues(IdIndex.NAME, entry, null, new FileBasedIndex.ValueProcessor<Integer>() { @Override public boolean process(VirtualFile file, Integer value) { if (progress != null) progress.checkCanceled(); if (IndexCacheManagerImpl.shouldBeFound(commonScope, file, index)) { int mask = value.intValue(); for (RequestWithProcessor single : data) { final PsiSearchRequest request = single.request; if ((mask & request.searchContext) != 0 && ((GlobalSearchScope)request.searchScope).contains(file)) { local.putValue(file, single); } } } return true; } }, commonScope); } }); return local; } private static void distributePrimitives(final Map<SearchRequestCollector, Processor<PsiReference>> collectors, LinkedHashSet<RequestWithProcessor> locals, MultiMap<Set<IdIndexEntry>, RequestWithProcessor> singles, List<Computable<Boolean>> customs) { for (final SearchRequestCollector collector : collectors.keySet()) { final Processor<PsiReference> processor = collectors.get(collector); for (final PsiSearchRequest primitive : collector.takeSearchRequests()) { final SearchScope scope = primitive.searchScope; if (scope instanceof LocalSearchScope) { registerRequest(locals, primitive, processor); } else { final List<String> words = StringUtil.getWordsIn(primitive.word); final Set<IdIndexEntry> key = new HashSet<IdIndexEntry>(words.size() * 2); for (String word : words) { key.add(new IdIndexEntry(word, primitive.caseSensitive)); } registerRequest(singles.getModifiable(key), primitive, processor); } } for (final Processor<Processor<PsiReference>> customAction : collector.takeCustomSearchActions()) { customs.add(new Computable<Boolean>() { @Override public Boolean compute() { return customAction.process(processor); } }); } } } private static void registerRequest(Collection<RequestWithProcessor> collection, PsiSearchRequest primitive, Processor<PsiReference> processor) { final RequestWithProcessor newValue = new RequestWithProcessor(primitive, processor); for (RequestWithProcessor existing : collection) { if (existing.uniteWith(newValue)) { return; } } collection.add(newValue); } private boolean processSingleRequest(PsiSearchRequest single, Processor<PsiReference> consumer) { return processElementsWithWord(adaptProcessor(single, consumer), single.searchScope, single.word, single.searchContext, single.caseSensitive); } @Override public SearchCostResult isCheapEnoughToSearch(@NotNull String name, @NotNull GlobalSearchScope scope, @Nullable final PsiFile fileToIgnoreOccurencesIn, @Nullable ProgressIndicator progress) { final AtomicInteger count = new AtomicInteger(); if (!processFilesWithText(scope, UsageSearchContext.ANY, true, name, new CommonProcessors.CollectProcessor<VirtualFile> (Collections.<VirtualFile>emptyList()) { private final VirtualFile fileToIgnoreOccurencesInVirtualFile = fileToIgnoreOccurencesIn != null ? fileToIgnoreOccurencesIn.getVirtualFile():null; @Override public boolean process(VirtualFile file) { if (file == fileToIgnoreOccurencesInVirtualFile) return true; int value = count.incrementAndGet(); return value < 10; } }, progress)) { return SearchCostResult.TOO_MANY_OCCURRENCES; } return count.get() == 0 ? SearchCostResult.ZERO_OCCURRENCES : SearchCostResult.FEW_OCCURRENCES; } }
platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.search; import com.intellij.codeInsight.CommentUtil; import com.intellij.concurrency.JobUtil; import com.intellij.ide.todo.TodoIndexPatternProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.ReadActionProcessor; import com.intellij.openapi.application.Result; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.impl.cache.impl.IndexCacheManagerImpl; import com.intellij.psi.impl.cache.impl.id.IdIndex; import com.intellij.psi.impl.cache.impl.id.IdIndexEntry; import com.intellij.psi.search.*; import com.intellij.psi.search.searches.IndexPatternSearch; import com.intellij.psi.util.PsiUtilBase; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.SmartList; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.containers.MultiMap; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.text.StringSearcher; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class PsiSearchHelperImpl implements PsiSearchHelper { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.PsiSearchHelperImpl"); private final PsiManagerEx myManager; private static final TodoItem[] EMPTY_TODO_ITEMS = new TodoItem[0]; @Override @NotNull public SearchScope getUseScope(@NotNull PsiElement element) { SearchScope scope = element.getUseScope(); for (UseScopeEnlarger enlarger : UseScopeEnlarger.EP_NAME.getExtensions()) { final SearchScope additionalScope = enlarger.getAdditionalUseScope(element); if (additionalScope != null) { scope = scope.union(additionalScope); } } return scope; } public PsiSearchHelperImpl(PsiManagerEx manager) { myManager = manager; } @Override @NotNull public PsiFile[] findFilesWithTodoItems() { return CacheManager.SERVICE.getInstance(myManager.getProject()).getFilesWithTodoItems(); } @Override @NotNull public TodoItem[] findTodoItems(@NotNull PsiFile file) { return findTodoItems(file, 0, file.getTextLength()); } @Override @NotNull public TodoItem[] findTodoItems(@NotNull PsiFile file, int startOffset, int endOffset) { final Collection<IndexPatternOccurrence> occurrences = IndexPatternSearch.search(file, TodoIndexPatternProvider.getInstance()).findAll(); if (occurrences.isEmpty()) { return EMPTY_TODO_ITEMS; } return processTodoOccurences(startOffset, endOffset, occurrences); } private TodoItem[] processTodoOccurences(int startOffset, int endOffset, Collection<IndexPatternOccurrence> occurrences) { List<TodoItem> items = new ArrayList<TodoItem>(occurrences.size()); TextRange textRange = new TextRange(startOffset, endOffset); final TodoItemsCreator todoItemsCreator = new TodoItemsCreator(); for(IndexPatternOccurrence occurrence: occurrences) { TextRange occurrenceRange = occurrence.getTextRange(); if (textRange.contains(occurrenceRange)) { items.add(todoItemsCreator.createTodo(occurrence)); } } return items.toArray(new TodoItem[items.size()]); } @NotNull @Override public TodoItem[] findTodoItemsLight(@NotNull PsiFile file) { return findTodoItemsLight(file, 0, file.getTextLength()); } @NotNull @Override public TodoItem[] findTodoItemsLight(@NotNull PsiFile file, int startOffset, int endOffset) { final Collection<IndexPatternOccurrence> occurrences = LightIndexPatternSearch.SEARCH.createQuery(new IndexPatternSearch.SearchParameters(file, TodoIndexPatternProvider.getInstance())).findAll(); if (occurrences.isEmpty()) { return EMPTY_TODO_ITEMS; } return processTodoOccurences(startOffset, endOffset, occurrences); } @Override public int getTodoItemsCount(@NotNull PsiFile file) { int count = CacheManager.SERVICE.getInstance(myManager.getProject()).getTodoCount(file.getVirtualFile(), TodoIndexPatternProvider.getInstance()); if (count != -1) return count; return findTodoItems(file).length; } @Override public int getTodoItemsCount(@NotNull PsiFile file, @NotNull TodoPattern pattern) { int count = CacheManager.SERVICE.getInstance(myManager.getProject()).getTodoCount(file.getVirtualFile(), pattern.getIndexPattern()); if (count != -1) return count; TodoItem[] items = findTodoItems(file); count = 0; for (TodoItem item : items) { if (item.getPattern().equals(pattern)) count++; } return count; } @Override @NotNull public PsiElement[] findCommentsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope) { final ArrayList<PsiElement> results = new ArrayList<PsiElement>(); processCommentsContainingIdentifier(identifier, searchScope, new Processor<PsiElement>() { @Override public boolean process(PsiElement element) { synchronized (results) { results.add(element); } return true; } }); synchronized (results) { return PsiUtilBase.toPsiElementArray(results); } } @Override public boolean processCommentsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope, @NotNull final Processor<PsiElement> processor) { TextOccurenceProcessor occurrenceProcessor = new TextOccurenceProcessor() { @Override public boolean execute(PsiElement element, int offsetInElement) { if (CommentUtil.isCommentTextElement(element)) { if (element.findReferenceAt(offsetInElement) == null) { return processor.process(element); } } return true; } }; return processElementsWithWord(occurrenceProcessor, searchScope, identifier, UsageSearchContext.IN_COMMENTS, true); } @Override public boolean processElementsWithWord(@NotNull final TextOccurenceProcessor processor, @NotNull SearchScope searchScope, @NotNull final String text, short searchContext, final boolean caseSensitively) { if (text.length() == 0) { throw new IllegalArgumentException("Cannot search for elements with empty text"); } final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); if (searchScope instanceof GlobalSearchScope) { StringSearcher searcher = new StringSearcher(text, caseSensitively, true); return processElementsWithTextInGlobalScope(processor, (GlobalSearchScope)searchScope, searcher, searchContext, caseSensitively, progress); } else { LocalSearchScope scope = (LocalSearchScope)searchScope; PsiElement[] scopeElements = scope.getScope(); final boolean ignoreInjectedPsi = scope.isIgnoreInjectedPsi(); return JobUtil.invokeConcurrentlyUnderProgress(Arrays.asList(scopeElements), progress, false, new Processor<PsiElement>() { @Override public boolean process(PsiElement scopeElement) { return processElementsWithWordInScopeElement(scopeElement, processor, text, caseSensitively, ignoreInjectedPsi, progress); } }); } } private static boolean processElementsWithWordInScopeElement(final PsiElement scopeElement, final TextOccurenceProcessor processor, final String word, final boolean caseSensitive, final boolean ignoreInjectedPsi, final ProgressIndicator progress) { return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { @Override public Boolean compute() { StringSearcher searcher = new StringSearcher(word, caseSensitive, true); return LowLevelSearchUtil.processElementsContainingWordInElement(processor, scopeElement, searcher, !ignoreInjectedPsi, progress); } }).booleanValue(); } private boolean processElementsWithTextInGlobalScope(@NotNull final TextOccurenceProcessor processor, @NotNull final GlobalSearchScope scope, @NotNull final StringSearcher searcher, final short searchContext, final boolean caseSensitively, final ProgressIndicator progress) { LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "You must not run search from within updating PSI activity. Please consider invokeLatering it instead."); if (progress != null) { progress.pushState(); progress.setText(PsiBundle.message("psi.scanning.files.progress")); } String text = searcher.getPattern(); List<VirtualFile> fileSet = getFilesWithText(scope, searchContext, caseSensitively, text, progress); if (progress != null) { progress.setText(PsiBundle.message("psi.search.for.word.progress", text)); } try { return processPsiFileRoots(fileSet, new Processor<PsiElement>() { @Override public boolean process(PsiElement psiRoot) { return LowLevelSearchUtil.processElementsContainingWordInElement(processor, psiRoot, searcher, true, progress); } }, progress); } finally { if (progress != null) { progress.popState(); } } } private boolean processPsiFileRoots(@NotNull List<VirtualFile> files, @NotNull final Processor<PsiElement> psiRootProcessor, final ProgressIndicator progress) { myManager.startBatchFilesProcessingMode(); try { final AtomicInteger counter = new AtomicInteger(0); final AtomicBoolean canceled = new AtomicBoolean(false); final AtomicBoolean pceThrown = new AtomicBoolean(false); final int size = files.size(); boolean completed = JobUtil.invokeConcurrentlyUnderProgress(files, progress, false, new Processor<VirtualFile>() { @Override public boolean process(final VirtualFile vfile) { final PsiFile file = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() { @Override public PsiFile compute() { return myManager.findFile(vfile); } }); if (file != null && !(file instanceof PsiBinaryFile)) { file.getViewProvider().getContents(); // load contents outside readaction ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { try { if (myManager.getProject().isDisposed()) throw new ProcessCanceledException(); PsiElement[] psiRoots = file.getPsiRoots(); Set<PsiElement> processed = new HashSet<PsiElement>(psiRoots.length * 2, (float)0.5); for (PsiElement psiRoot : psiRoots) { if (progress != null) progress.checkCanceled(); if (!processed.add(psiRoot)) continue; if (!psiRootProcessor.process(psiRoot)) { canceled.set(true); return; } } myManager.dropResolveCaches(); } catch (ProcessCanceledException e) { canceled.set(true); pceThrown.set(true); } } }); } if (progress != null) { double fraction = (double)counter.incrementAndGet() / size; progress.setFraction(fraction); } return !canceled.get(); } }); if (pceThrown.get()) { throw new ProcessCanceledException(); } return completed; } finally { myManager.finishBatchFilesProcessingMode(); } } @NotNull private List<VirtualFile> getFilesWithText(@NotNull GlobalSearchScope scope, final short searchContext, final boolean caseSensitively, @NotNull String text, ProgressIndicator progress) { myManager.startBatchFilesProcessingMode(); try { final List<VirtualFile> result = new ArrayList<VirtualFile>(); boolean success = processFilesWithText( scope, searchContext, caseSensitively, text, new CommonProcessors.CollectProcessor<VirtualFile>(result), progress ); LOG.assertTrue(success); return result; } finally { myManager.finishBatchFilesProcessingMode(); } } public boolean processFilesWithText(@NotNull final GlobalSearchScope scope, final short searchContext, final boolean caseSensitively, @NotNull String text, @NotNull final Processor<VirtualFile> processor, @Nullable ProgressIndicator progress) { List<String> words = StringUtil.getWordsIn(text); if (words.isEmpty()) return true; Collections.sort(words, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.length() - o1.length(); } }); final Set<VirtualFile> fileSet; CacheManager cacheManager = CacheManager.SERVICE.getInstance(myManager.getProject()); if (words.size() > 1) { fileSet = new THashSet<VirtualFile>(); Set<VirtualFile> copy = new THashSet<VirtualFile>(); for (int i = 0; i < words.size() - 1; i++) { if (progress != null) { progress.checkCanceled(); } else { ProgressManager.checkCanceled(); } final String word = words.get(i); final int finalI = i; cacheManager.collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(i != 0 ? copy:fileSet) { @Override protected boolean accept(VirtualFile virtualFile) { return finalI == 0 || fileSet.contains(virtualFile); } }, word, searchContext, scope, caseSensitively); if (i != 0) { fileSet.retainAll(copy); } copy.clear(); if (fileSet.isEmpty()) break; } if (fileSet.isEmpty()) return true; } else { fileSet = null; } final String lastWord = words.get(words.size() - 1); if (processor instanceof CommonProcessors.CollectProcessor) { final CommonProcessors.CollectProcessor collectProcessor = (CommonProcessors.CollectProcessor)processor; return cacheManager.collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(collectProcessor.getResults()) { @Override public boolean process(VirtualFile virtualFile) { if (fileSet == null || fileSet.contains(virtualFile)) return collectProcessor.process(virtualFile); return true; } }, lastWord, searchContext, scope, caseSensitively); } else { THashSet<VirtualFile> files = new THashSet<VirtualFile>(); cacheManager.collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(files) { @Override protected boolean accept(VirtualFile virtualFile) { return fileSet == null || fileSet.contains(virtualFile); } }, lastWord, searchContext, scope, caseSensitively); ReadActionProcessor<VirtualFile> readActionProcessor = new ReadActionProcessor<VirtualFile>() { @Override public boolean processInReadAction(VirtualFile virtualFile) { return processor.process(virtualFile); } }; for(VirtualFile file:files) { if (!readActionProcessor.process(file)) return false; } return true; } } @Override @NotNull public PsiFile[] findFilesWithPlainTextWords(@NotNull String word) { return CacheManager.SERVICE.getInstance(myManager.getProject()).getFilesWithWord(word, UsageSearchContext.IN_PLAIN_TEXT, GlobalSearchScope.projectScope(myManager.getProject()), true); } @Override public void processUsagesInNonJavaFiles(@NotNull String qName, @NotNull PsiNonJavaFileReferenceProcessor processor, @NotNull GlobalSearchScope searchScope) { processUsagesInNonJavaFiles(null, qName, processor, searchScope); } @Override public void processUsagesInNonJavaFiles(@Nullable final PsiElement originalElement, @NotNull String qName, @NotNull final PsiNonJavaFileReferenceProcessor processor, @NotNull GlobalSearchScope searchScope) { if (qName.length() == 0) { throw new IllegalArgumentException("Cannot search for elements with empty text"); } final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); int dotIndex = qName.lastIndexOf('.'); int dollarIndex = qName.lastIndexOf('$'); int maxIndex = Math.max(dotIndex, dollarIndex); final String wordToSearch = maxIndex >= 0 ? qName.substring(maxIndex + 1) : qName; if (originalElement != null && myManager.isInProject(originalElement) && searchScope.isSearchInLibraries()) { searchScope = searchScope.intersectWith(GlobalSearchScope.projectScope(myManager.getProject())); } final GlobalSearchScope theSearchScope = searchScope; PsiFile[] files = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile[]>() { @Override public PsiFile[] compute() { return CacheManager.SERVICE.getInstance(myManager.getProject()).getFilesWithWord(wordToSearch, UsageSearchContext.IN_PLAIN_TEXT, theSearchScope, true); } }); final StringSearcher searcher = new StringSearcher(qName, true, true); if (progress != null) { progress.pushState(); progress.setText(PsiBundle.message("psi.search.in.non.java.files.progress")); } final SearchScope useScope = new ReadAction<SearchScope>() { @Override protected void run(final Result<SearchScope> result) { if (originalElement != null) { result.setResult(getUseScope(originalElement)); } } }.execute().getResultObject(); final Ref<Boolean> cancelled = new Ref<Boolean>(Boolean.FALSE); final GlobalSearchScope finalScope = searchScope; for (int i = 0; i < files.length; i++) { if (progress != null) progress.checkCanceled(); final PsiFile psiFile = files[i]; ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { CharSequence text = psiFile.getViewProvider().getContents(); for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher, progress); index >= 0;) { PsiReference referenceAt = psiFile.findReferenceAt(index); if (referenceAt == null || useScope == null || !PsiSearchScopeUtil.isInScope(useScope.intersectWith(finalScope), psiFile)) { if (!processor.process(psiFile, index, index + searcher.getPattern().length())) { cancelled.set(Boolean.TRUE); return; } } index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length(), searcher, progress); } } }); if (cancelled.get()) break; if (progress != null) { progress.setFraction((double)(i + 1) / files.length); } } if (progress != null) { progress.popState(); } } @Override public void processAllFilesWithWord(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor, final boolean caseSensitively) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_CODE, scope, caseSensitively); } @Override public void processAllFilesWithWordInText(@NotNull final String word, @NotNull final GlobalSearchScope scope, @NotNull final Processor<PsiFile> processor, final boolean caseSensitively) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_PLAIN_TEXT, scope, caseSensitively); } @Override public void processAllFilesWithWordInComments(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_COMMENTS, scope, true); } @Override public void processAllFilesWithWordInLiterals(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) { CacheManager.SERVICE.getInstance(myManager.getProject()).processFilesWithWord(processor, word, UsageSearchContext.IN_STRINGS, scope, true); } private static class RequestWithProcessor { final PsiSearchRequest request; Processor<PsiReference> refProcessor; private RequestWithProcessor(PsiSearchRequest first, Processor<PsiReference> second) { request = first; refProcessor = second; } boolean uniteWith(final RequestWithProcessor another) { if (request.equals(another.request)) { final Processor<PsiReference> myProcessor = refProcessor; if (myProcessor != another.refProcessor) { refProcessor = new Processor<PsiReference>() { @Override public boolean process(PsiReference psiReference) { return myProcessor.process(psiReference) && another.refProcessor.process(psiReference); } }; } return true; } return false; } @Override public String toString() { return request.toString(); } } @Override public boolean processRequests(@NotNull SearchRequestCollector collector, @NotNull Processor<PsiReference> processor) { Map<SearchRequestCollector, Processor<PsiReference>> collectors = CollectionFactory.hashMap(); collectors.put(collector, processor); appendCollectorsFromQueryRequests(collectors); ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); do { final MultiMap<Set<IdIndexEntry>, RequestWithProcessor> globals = new MultiMap<Set<IdIndexEntry>, RequestWithProcessor>(); final List<Computable<Boolean>> customs = CollectionFactory.arrayList(); final LinkedHashSet<RequestWithProcessor> locals = CollectionFactory.linkedHashSet(); distributePrimitives(collectors, locals, globals, customs); if (!processGlobalRequestsOptimized(globals, progress)) { return false; } for (RequestWithProcessor local : locals) { if (!processSingleRequest(local.request, local.refProcessor)) { return false; } } for (Computable<Boolean> custom : customs) { if (!custom.compute()) { return false; } } } while (appendCollectorsFromQueryRequests(collectors)); return true; } private static boolean appendCollectorsFromQueryRequests(Map<SearchRequestCollector, Processor<PsiReference>> collectors) { boolean changed = false; LinkedList<SearchRequestCollector> queue = new LinkedList<SearchRequestCollector>(collectors.keySet()); while (!queue.isEmpty()) { final SearchRequestCollector each = queue.removeFirst(); for (QuerySearchRequest request : each.takeQueryRequests()) { request.runQuery(); collectors.put(request.collector, request.processor); queue.addLast(request.collector); changed = true; } } return changed; } private boolean processGlobalRequestsOptimized(MultiMap<Set<IdIndexEntry>, RequestWithProcessor> singles, final ProgressIndicator progress) { if (singles.isEmpty()) { return true; } if (singles.size() == 1) { final Collection<RequestWithProcessor> requests = singles.get(singles.keySet().iterator().next()); if (requests.size() == 1) { final RequestWithProcessor theOnly = requests.iterator().next(); return processSingleRequest(theOnly.request, theOnly.refProcessor); } } if (progress != null) { progress.pushState(); progress.setText(PsiBundle.message("psi.scanning.files.progress")); } final MultiMap<VirtualFile, RequestWithProcessor> candidateFiles = collectFiles(singles, progress); try { if (candidateFiles.isEmpty()) { return true; } final Map<RequestWithProcessor, StringSearcher> searchers = new HashMap<RequestWithProcessor, StringSearcher>(); final Set<String> allWords = new TreeSet<String>(); for (RequestWithProcessor singleRequest : candidateFiles.values()) { searchers.put(singleRequest, new StringSearcher(singleRequest.request.word, singleRequest.request.caseSensitive, true)); allWords.add(singleRequest.request.word); } if (progress != null) { final StringBuilder result = new StringBuilder(); for (String string : allWords) { if (string != null && string.length() != 0) { if (result.length() > 50) { result.append("..."); break; } if (result.length() != 0) result.append(", "); result.append(string); } } progress.setText(PsiBundle.message("psi.search.for.word.progress", result.toString())); } return processPsiFileRoots(new ArrayList<VirtualFile>(candidateFiles.keySet()), new Processor<PsiElement>() { @Override public boolean process(PsiElement psiRoot) { final VirtualFile vfile = psiRoot.getContainingFile().getVirtualFile(); for (final RequestWithProcessor singleRequest : candidateFiles.get(vfile)) { StringSearcher searcher = searchers.get(singleRequest); TextOccurenceProcessor adapted = adaptProcessor(singleRequest.request, singleRequest.refProcessor); if (!LowLevelSearchUtil.processElementsContainingWordInElement(adapted, psiRoot, searcher, true, progress)) { return false; } } return true; } }, progress); } finally { if (progress != null) { progress.popState(); } } } private static TextOccurenceProcessor adaptProcessor(final PsiSearchRequest singleRequest, final Processor<PsiReference> consumer) { final SearchScope searchScope = singleRequest.searchScope; final boolean ignoreInjectedPsi = searchScope instanceof LocalSearchScope && ((LocalSearchScope)searchScope).isIgnoreInjectedPsi(); final RequestResultProcessor wrapped = singleRequest.processor; return new TextOccurenceProcessor() { @Override public boolean execute(PsiElement element, int offsetInElement) { if (ignoreInjectedPsi && element instanceof PsiLanguageInjectionHost) return true; return wrapped.processTextOccurrence(element, offsetInElement, consumer); } }; } private MultiMap<VirtualFile, RequestWithProcessor> collectFiles(MultiMap<Set<IdIndexEntry>, RequestWithProcessor> singles, ProgressIndicator progress) { final FileIndexFacade index = FileIndexFacade.getInstance(myManager.getProject()); final MultiMap<VirtualFile, RequestWithProcessor> result = createMultiMap(); for (Set<IdIndexEntry> key : singles.keySet()) { if (key.isEmpty()) { continue; } final Collection<RequestWithProcessor> data = singles.get(key); GlobalSearchScope commonScope = uniteScopes(data); MultiMap<VirtualFile, RequestWithProcessor> intersection = null; boolean first = true; for (IdIndexEntry entry : key) { final MultiMap<VirtualFile, RequestWithProcessor> local = findFilesWithIndexEntry(entry, index, data, commonScope, progress); if (first) { intersection = local; first = false; } else { intersection.keySet().retainAll(local.keySet()); for (VirtualFile file : intersection.keySet()) { intersection.get(file).retainAll(local.get(file)); } } } result.putAllValues(intersection); } return result; } private static MultiMap<VirtualFile, RequestWithProcessor> createMultiMap() { return new MultiMap<VirtualFile, RequestWithProcessor>(){ @Override protected Collection<RequestWithProcessor> createCollection() { return new SmartList<RequestWithProcessor>(); // usually there is just one request } }; } private static GlobalSearchScope uniteScopes(Collection<RequestWithProcessor> requests) { GlobalSearchScope commonScope = null; for (RequestWithProcessor r : requests) { final GlobalSearchScope scope = (GlobalSearchScope)r.request.searchScope; commonScope = commonScope == null ? scope : commonScope.uniteWith(scope); } assert commonScope != null; return commonScope; } private static MultiMap<VirtualFile, RequestWithProcessor> findFilesWithIndexEntry(final IdIndexEntry entry, final FileIndexFacade index, final Collection<RequestWithProcessor> data, final GlobalSearchScope commonScope, final ProgressIndicator progress) { final MultiMap<VirtualFile, RequestWithProcessor> local = createMultiMap(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { if (progress != null) progress.checkCanceled(); FileBasedIndex.getInstance().processValues(IdIndex.NAME, entry, null, new FileBasedIndex.ValueProcessor<Integer>() { @Override public boolean process(VirtualFile file, Integer value) { if (progress != null) progress.checkCanceled(); if (IndexCacheManagerImpl.shouldBeFound(commonScope, file, index)) { int mask = value.intValue(); for (RequestWithProcessor single : data) { final PsiSearchRequest request = single.request; if ((mask & request.searchContext) != 0 && ((GlobalSearchScope)request.searchScope).contains(file)) { local.putValue(file, single); } } } return true; } }, commonScope); } }); return local; } private static void distributePrimitives(final Map<SearchRequestCollector, Processor<PsiReference>> collectors, LinkedHashSet<RequestWithProcessor> locals, MultiMap<Set<IdIndexEntry>, RequestWithProcessor> singles, List<Computable<Boolean>> customs) { for (final SearchRequestCollector collector : collectors.keySet()) { final Processor<PsiReference> processor = collectors.get(collector); for (final PsiSearchRequest primitive : collector.takeSearchRequests()) { final SearchScope scope = primitive.searchScope; if (scope instanceof LocalSearchScope) { registerRequest(locals, primitive, processor); } else { final List<String> words = StringUtil.getWordsIn(primitive.word); final Set<IdIndexEntry> key = new HashSet<IdIndexEntry>(words.size() * 2); for (String word : words) { key.add(new IdIndexEntry(word, primitive.caseSensitive)); } registerRequest(singles.getModifiable(key), primitive, processor); } } for (final Processor<Processor<PsiReference>> customAction : collector.takeCustomSearchActions()) { customs.add(new Computable<Boolean>() { @Override public Boolean compute() { return customAction.process(processor); } }); } } } private static void registerRequest(Collection<RequestWithProcessor> collection, PsiSearchRequest primitive, Processor<PsiReference> processor) { final RequestWithProcessor newValue = new RequestWithProcessor(primitive, processor); for (RequestWithProcessor existing : collection) { if (existing.uniteWith(newValue)) { return; } } collection.add(newValue); } private boolean processSingleRequest(PsiSearchRequest single, Processor<PsiReference> consumer) { return processElementsWithWord(adaptProcessor(single, consumer), single.searchScope, single.word, single.searchContext, single.caseSensitive); } @Override public SearchCostResult isCheapEnoughToSearch(@NotNull String name, @NotNull GlobalSearchScope scope, @Nullable final PsiFile fileToIgnoreOccurencesIn, @Nullable ProgressIndicator progress) { final AtomicInteger count = new AtomicInteger(); if (!processFilesWithText(scope, UsageSearchContext.ANY, true, name, new CommonProcessors.CollectProcessor<VirtualFile> (Collections.<VirtualFile>emptyList()) { private final VirtualFile fileToIgnoreOccurencesInVirtualFile = fileToIgnoreOccurencesIn != null ? fileToIgnoreOccurencesIn.getVirtualFile():null; @Override public boolean process(VirtualFile file) { if (file == fileToIgnoreOccurencesInVirtualFile) return true; int value = count.incrementAndGet(); return value < 10; } }, progress)) { return SearchCostResult.TOO_MANY_OCCURRENCES; } return count.get() == 0 ? SearchCostResult.ZERO_OCCURRENCES : SearchCostResult.FEW_OCCURRENCES; } }
EA-32575 - assert: Alarm._addRequest
platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java
EA-32575 - assert: Alarm._addRequest
<ide><path>latform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java <ide> } <ide> }); <ide> } <del> if (progress != null) { <add> if (progress != null && progress.isRunning()) { <ide> double fraction = (double)counter.incrementAndGet() / size; <ide> progress.setFraction(fraction); <ide> }
Java
apache-2.0
102bcec062ec57ca67f0473e696863e60653810d
0
GFriedrich/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/logging-log4j2,apache/logging-log4j2,lburgazzoli/apache-logging-log4j2,xnslong/logging-log4j2,lburgazzoli/apache-logging-log4j2,xnslong/logging-log4j2,lburgazzoli/logging-log4j2,xnslong/logging-log4j2,lburgazzoli/apache-logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,lburgazzoli/logging-log4j2,lqbweb/logging-log4j2,lqbweb/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.impl; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.async.RingBufferLogEvent; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.core.util.Clock; import org.apache.logging.log4j.core.util.ClockFactory; import org.apache.logging.log4j.core.util.DummyNanoClock; import org.apache.logging.log4j.core.util.NanoClock; import org.apache.logging.log4j.message.LoggerNameAwareMessage; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.TimestampMessage; import org.apache.logging.log4j.status.StatusLogger; import org.apache.logging.log4j.util.Strings; /** * Implementation of a LogEvent. */ public class Log4jLogEvent implements LogEvent { private static final long serialVersionUID = -1351367343806656055L; private static final Clock CLOCK = ClockFactory.getClock(); private static volatile NanoClock nanoClock = new DummyNanoClock(); private final String loggerFqcn; private final Marker marker; private final Level level; private final String loggerName; private final Message message; private final long timeMillis; private final transient Throwable thrown; private ThrowableProxy thrownProxy; private final Map<String, String> contextMap; private final ThreadContext.ContextStack contextStack; private String threadName; private StackTraceElement source; private boolean includeLocation; private boolean endOfBatch = false; /** @since Log4J 2.4 */ private final transient long nanoTime; /** LogEvent Builder helper class. */ public static class Builder implements org.apache.logging.log4j.core.util.Builder<LogEvent> { private String loggerFqcn; private Marker marker; private Level level; private String loggerName; private Message message; private Throwable thrown; private long timeMillis = CLOCK.currentTimeMillis(); private ThrowableProxy thrownProxy; private Map<String, String> contextMap = ThreadContext.getImmutableContext(); private ThreadContext.ContextStack contextStack = ThreadContext.getImmutableStack(); private String threadName = null; private StackTraceElement source; private boolean includeLocation; private boolean endOfBatch = false; private long nanoTime; public Builder() { } public Builder(LogEvent other) { Objects.requireNonNull(other); if (other instanceof RingBufferLogEvent) { RingBufferLogEvent evt = (RingBufferLogEvent) other; evt.initializeBuilder(this); return; } this.loggerFqcn = other.getLoggerFqcn(); this.marker = other.getMarker(); this.level = other.getLevel(); this.loggerName = other.getLoggerName(); this.message = other.getMessage(); this.timeMillis = other.getTimeMillis(); this.thrown = other.getThrown(); this.contextMap = other.getContextMap(); this.contextStack = other.getContextStack(); this.includeLocation = other.isIncludeLocation(); this.endOfBatch = other.isEndOfBatch(); this.nanoTime = other.getNanoTime(); // Avoid unnecessarily initializing thrownProxy, threadName and source if possible if (other instanceof Log4jLogEvent) { Log4jLogEvent evt = (Log4jLogEvent) other; this.thrownProxy = evt.thrownProxy; this.source = evt.source; this.threadName = evt.threadName; } else { this.thrownProxy = other.getThrownProxy(); this.source = other.getSource(); this.threadName = other.getThreadName(); } } public Builder setLevel(final Level level) { this.level = level; return this; } public Builder setLoggerFqcn(final String loggerFqcn) { this.loggerFqcn = loggerFqcn; return this; } public Builder setLoggerName(final String loggerName) { this.loggerName = loggerName; return this; } public Builder setMarker(final Marker marker) { this.marker = marker; return this; } public Builder setMessage(final Message message) { this.message = message; return this; } public Builder setThrown(final Throwable thrown) { this.thrown = thrown; return this; } public Builder setTimeMillis(long timeMillis) { this.timeMillis = timeMillis; return this; } public Builder setThrownProxy(ThrowableProxy thrownProxy) { this.thrownProxy = thrownProxy; return this; } public Builder setContextMap(Map<String, String> contextMap) { this.contextMap = contextMap; return this; } public Builder setContextStack(ThreadContext.ContextStack contextStack) { this.contextStack = contextStack; return this; } public Builder setThreadName(String threadName) { this.threadName = threadName; return this; } public Builder setSource(StackTraceElement source) { this.source = source; return this; } public Builder setIncludeLocation(boolean includeLocation) { this.includeLocation = includeLocation; return this; } public Builder setEndOfBatch(boolean endOfBatch) { this.endOfBatch = endOfBatch; return this; } /** * Sets the nano time for the event. * @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event * was created. * @return this builder */ public Builder setNanoTime(long nanoTime) { this.nanoTime = nanoTime; return this; } @Override public Log4jLogEvent build() { final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFqcn, level, message, thrown, thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime); result.setIncludeLocation(includeLocation); result.setEndOfBatch(endOfBatch); return result; } } /** * Returns a new empty {@code Log4jLogEvent.Builder} with all fields empty. * @return a new empty builder. */ public static Builder newBuilder() { return new Builder(); } public Log4jLogEvent() { this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null, CLOCK.currentTimeMillis(), nanoClock.nanoTime()); } /** * * @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release. */ @Deprecated public Log4jLogEvent(final long timestamp) { this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null, timestamp, nanoClock.nanoTime()); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param t A Throwable or null. * @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release. */ @Deprecated public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable t) { this(loggerName, marker, loggerFQCN, level, message, null, t); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param properties properties to add to the event. * @param t A Throwable or null. */ // This constructor is called from LogEventFactories. public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final List<Property> properties, final Throwable t) { this(loggerName, marker, loggerFQCN, level, message, t, null, createMap(properties), ThreadContext.getDepth() == 0 ? null : ThreadContext.cloneStack(), // mutable copy null, // thread name null, // stack trace element // LOG4J2-628 use log4j.Clock for timestamps // LOG4J2-744 unless TimestampMessage already has one message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() : CLOCK.currentTimeMillis(), nanoClock.nanoTime()); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param t A Throwable or null. * @param mdc The mapped diagnostic context. * @param ndc the nested diagnostic context. * @param threadName The name of the thread. * @param location The locations of the caller. * @param timestampMillis The timestamp of the event. * @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release. */ @Deprecated public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable t, final Map<String, String> mdc, final ThreadContext.ContextStack ndc, final String threadName, final StackTraceElement location, final long timestampMillis) { this(loggerName, marker, loggerFQCN, level, message, t, null, mdc, ndc, threadName, location, timestampMillis, nanoClock.nanoTime()); } /** * Create a new LogEvent. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param thrown A Throwable or null. * @param thrownProxy A ThrowableProxy or null. * @param mdc The mapped diagnostic context. * @param ndc the nested diagnostic context. * @param threadName The name of the thread. * @param location The locations of the caller. * @param timestamp The timestamp of the event. * @return a new LogEvent * @deprecated use {@link Log4jLogEvent.Builder} instead. This method will be removed in an upcoming release. */ @Deprecated public static Log4jLogEvent createEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable thrown, final ThrowableProxy thrownProxy, final Map<String, String> mdc, final ThreadContext.ContextStack ndc, final String threadName, final StackTraceElement location, final long timestamp) { final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown, thrownProxy, mdc, ndc, threadName, location, timestamp, nanoClock.nanoTime()); return result; } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param thrown A Throwable or null. * @param thrownProxy A ThrowableProxy or null. * @param contextMap The mapped diagnostic context. * @param contextStack the nested diagnostic context. * @param threadName The name of the thread. * @param source The locations of the caller. * @param timestampMillis The timestamp of the event. * @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event was * created. */ private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable thrown, final ThrowableProxy thrownProxy, final Map<String, String> contextMap, final ThreadContext.ContextStack contextStack, final String threadName, final StackTraceElement source, final long timestampMillis, final long nanoTime) { this.loggerName = loggerName; this.marker = marker; this.loggerFqcn = loggerFQCN; this.level = level == null ? Level.OFF : level; // LOG4J2-462, LOG4J2-465 this.message = message; this.thrown = thrown; this.thrownProxy = thrownProxy; this.contextMap = contextMap == null ? ThreadContext.EMPTY_MAP : contextMap; this.contextStack = contextStack == null ? ThreadContext.EMPTY_STACK : contextStack; this.timeMillis = message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() : timestampMillis; this.threadName = threadName; this.source = source; if (message != null && message instanceof LoggerNameAwareMessage) { ((LoggerNameAwareMessage) message).setLoggerName(loggerName); } this.nanoTime = nanoTime; } private static Map<String, String> createMap(final List<Property> properties) { final Map<String, String> contextMap = ThreadContext.getImmutableContext(); if (properties == null || properties.isEmpty()) { return contextMap; // may be ThreadContext.EMPTY_MAP but not null } final Map<String, String> map = new HashMap<>(contextMap); for (final Property prop : properties) { if (!map.containsKey(prop.getName())) { map.put(prop.getName(), prop.getValue()); } } return Collections.unmodifiableMap(map); } /** * Returns the {@code NanoClock} to use for creating the nanoTime timestamp of log events. * @return the {@code NanoClock} to use for creating the nanoTime timestamp of log events */ public static NanoClock getNanoClock() { return nanoClock; } /** * Sets the {@code NanoClock} to use for creating the nanoTime timestamp of log events. * <p> * FOR INTERNAL USE. This method may be called with a different {@code NanoClock} implementation when the * configuration changes. * * @param nanoClock the {@code NanoClock} to use for creating the nanoTime timestamp of log events */ public static void setNanoClock(NanoClock nanoClock) { Log4jLogEvent.nanoClock = Objects.requireNonNull(nanoClock, "NanoClock must be non-null"); StatusLogger.getLogger().trace("Using {} for nanosecond timestamps.", nanoClock.getClass().getSimpleName()); } /** * Returns a new fully initialized {@code Log4jLogEvent.Builder} containing a copy of all fields of this event. * @return a new fully initialized builder. */ public Builder asBuilder() { return new Builder(this); } /** * Returns the logging Level. * @return the Level associated with this event. */ @Override public Level getLevel() { return level; } /** * Returns the name of the Logger used to generate the event. * @return The Logger name. */ @Override public String getLoggerName() { return loggerName; } /** * Returns the Message associated with the event. * @return The Message. */ @Override public Message getMessage() { return message; } /** * Returns the name of the Thread on which the event was generated. * @return The name of the Thread. */ @Override public String getThreadName() { if (threadName == null) { threadName = Thread.currentThread().getName(); } return threadName; } /** * Returns the time in milliseconds from the epoch when the event occurred. * @return The time the event occurred. */ @Override public long getTimeMillis() { return timeMillis; } /** * Returns the Throwable associated with the event, or null. * @return The Throwable associated with the event. */ @Override public Throwable getThrown() { return thrown; } /** * Returns the ThrowableProxy associated with the event, or null. * @return The ThrowableProxy associated with the event. */ @Override public ThrowableProxy getThrownProxy() { if (thrownProxy == null && thrown != null) { thrownProxy = new ThrowableProxy(thrown); } return thrownProxy; } /** * Returns the Marker associated with the event, or null. * @return the Marker associated with the event. */ @Override public Marker getMarker() { return marker; } /** * The fully qualified class name of the class that was called by the caller. * @return the fully qualified class name of the class that is performing logging. */ @Override public String getLoggerFqcn() { return loggerFqcn; } /** * Returns the immutable copy of the ThreadContext Map. * @return The context Map. */ @Override public Map<String, String> getContextMap() { return contextMap; } /** * Returns an immutable copy of the ThreadContext stack. * @return The context Stack. */ @Override public ThreadContext.ContextStack getContextStack() { return contextStack; } /** * Returns the StackTraceElement for the caller. This will be the entry that occurs right * before the first occurrence of FQCN as a class name. * @return the StackTraceElement for the caller. */ @Override public StackTraceElement getSource() { if (source != null) { return source; } if (loggerFqcn == null || !includeLocation) { return null; } source = calcLocation(loggerFqcn); return source; } public static StackTraceElement calcLocation(final String fqcnOfLogger) { if (fqcnOfLogger == null) { return null; } // LOG4J2-1029 new Throwable().getStackTrace is faster than Thread.currentThread().getStackTrace(). final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); StackTraceElement last = null; for (int i = stackTrace.length - 1; i > 0; i--) { final String className = stackTrace[i].getClassName(); if (fqcnOfLogger.equals(className)) { return last; } last = stackTrace[i]; } return null; } @Override public boolean isIncludeLocation() { return includeLocation; } @Override public void setIncludeLocation(final boolean includeLocation) { this.includeLocation = includeLocation; } @Override public boolean isEndOfBatch() { return endOfBatch; } @Override public void setEndOfBatch(final boolean endOfBatch) { this.endOfBatch = endOfBatch; } @Override public long getNanoTime() { return nanoTime; } /** * Creates a LogEventProxy that can be serialized. * @return a LogEventProxy. */ protected Object writeReplace() { getThrownProxy(); // ensure ThrowableProxy is initialized return new LogEventProxy(this, this.includeLocation); } public static Serializable serialize(final Log4jLogEvent event, final boolean includeLocation) { event.getThrownProxy(); // ensure ThrowableProxy is initialized return new LogEventProxy(event, includeLocation); } public static boolean canDeserialize(final Serializable event) { return event instanceof LogEventProxy; } public static Log4jLogEvent deserialize(final Serializable event) { Objects.requireNonNull(event, "Event cannot be null"); if (event instanceof LogEventProxy) { final LogEventProxy proxy = (LogEventProxy) event; final Log4jLogEvent result = new Log4jLogEvent(proxy.loggerName, proxy.marker, proxy.loggerFQCN, proxy.level, proxy.message, proxy.thrown, proxy.thrownProxy, proxy.contextMap, proxy.contextStack, proxy.threadName, proxy.source, proxy.timeMillis, proxy.nanoTime); result.setEndOfBatch(proxy.isEndOfBatch); result.setIncludeLocation(proxy.isLocationRequired); return result; } throw new IllegalArgumentException("Event is not a serialized LogEvent: " + event.toString()); } private void readObject(final ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Proxy required"); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); final String n = loggerName.isEmpty() ? LoggerConfig.ROOT : loggerName; sb.append("Logger=").append(n); sb.append(" Level=").append(level.name()); sb.append(" Message=").append(message.getFormattedMessage()); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Log4jLogEvent that = (Log4jLogEvent) o; if (endOfBatch != that.endOfBatch) { return false; } if (includeLocation != that.includeLocation) { return false; } if (timeMillis != that.timeMillis) { return false; } if (nanoTime != that.nanoTime) { return false; } if (loggerFqcn != null ? !loggerFqcn.equals(that.loggerFqcn) : that.loggerFqcn != null) { return false; } if (level != null ? !level.equals(that.level) : that.level != null) { return false; } if (source != null ? !source.equals(that.source) : that.source != null) { return false; } if (marker != null ? !marker.equals(that.marker) : that.marker != null) { return false; } if (contextMap != null ? !contextMap.equals(that.contextMap) : that.contextMap != null) { return false; } if (!message.equals(that.message)) { return false; } if (!loggerName.equals(that.loggerName)) { return false; } if (contextStack != null ? !contextStack.equals(that.contextStack) : that.contextStack != null) { return false; } if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) { return false; } if (thrown != null ? !thrown.equals(that.thrown) : that.thrown != null) { return false; } if (thrownProxy != null ? !thrownProxy.equals(that.thrownProxy) : that.thrownProxy != null) { return false; } return true; } @Override public int hashCode() { // Check:OFF: MagicNumber int result = loggerFqcn != null ? loggerFqcn.hashCode() : 0; result = 31 * result + (marker != null ? marker.hashCode() : 0); result = 31 * result + (level != null ? level.hashCode() : 0); result = 31 * result + loggerName.hashCode(); result = 31 * result + message.hashCode(); result = 31 * result + (int) (timeMillis ^ (timeMillis >>> 32)); result = 31 * result + (int) (nanoTime ^ (nanoTime >>> 32)); result = 31 * result + (thrown != null ? thrown.hashCode() : 0); result = 31 * result + (thrownProxy != null ? thrownProxy.hashCode() : 0); result = 31 * result + (contextMap != null ? contextMap.hashCode() : 0); result = 31 * result + (contextStack != null ? contextStack.hashCode() : 0); result = 31 * result + (threadName != null ? threadName.hashCode() : 0); result = 31 * result + (source != null ? source.hashCode() : 0); result = 31 * result + (includeLocation ? 1 : 0); result = 31 * result + (endOfBatch ? 1 : 0); // Check:ON: MagicNumber return result; } /** * Proxy pattern used to serialize the LogEvent. */ private static class LogEventProxy implements Serializable { private static final long serialVersionUID = -7139032940312647146L; private final String loggerFQCN; private final Marker marker; private final Level level; private final String loggerName; private final Message message; private final long timeMillis; private final transient Throwable thrown; private final ThrowableProxy thrownProxy; private final Map<String, String> contextMap; private final ThreadContext.ContextStack contextStack; private final String threadName; private final StackTraceElement source; private final boolean isLocationRequired; private final boolean isEndOfBatch; /** @since Log4J 2.4 */ private final transient long nanoTime; public LogEventProxy(final Log4jLogEvent event, final boolean includeLocation) { this.loggerFQCN = event.loggerFqcn; this.marker = event.marker; this.level = event.level; this.loggerName = event.loggerName; this.message = event.message; this.timeMillis = event.timeMillis; this.thrown = event.thrown; this.thrownProxy = event.thrownProxy; this.contextMap = event.contextMap; this.contextStack = event.contextStack; this.source = includeLocation ? event.getSource() : null; this.threadName = event.getThreadName(); this.isLocationRequired = includeLocation; this.isEndOfBatch = event.endOfBatch; this.nanoTime = event.nanoTime; } /** * Returns a Log4jLogEvent using the data in the proxy. * @return Log4jLogEvent. */ protected Object readResolve() { final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown, thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime); result.setEndOfBatch(isEndOfBatch); result.setIncludeLocation(isLocationRequired); return result; } } }
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.impl; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.async.RingBufferLogEvent; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.core.util.Clock; import org.apache.logging.log4j.core.util.ClockFactory; import org.apache.logging.log4j.core.util.DummyNanoClock; import org.apache.logging.log4j.core.util.NanoClock; import org.apache.logging.log4j.message.LoggerNameAwareMessage; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.TimestampMessage; import org.apache.logging.log4j.status.StatusLogger; import org.apache.logging.log4j.util.Strings; /** * Implementation of a LogEvent. */ public class Log4jLogEvent implements LogEvent { private static final long serialVersionUID = -1351367343806656055L; private static final Clock CLOCK = ClockFactory.getClock(); private static volatile NanoClock nanoClock = new DummyNanoClock(); private final String loggerFqcn; private final Marker marker; private final Level level; private final String loggerName; private final Message message; private final long timeMillis; private final transient Throwable thrown; private ThrowableProxy thrownProxy; private final Map<String, String> contextMap; private final ThreadContext.ContextStack contextStack; private String threadName; private StackTraceElement source; private boolean includeLocation; private boolean endOfBatch = false; /** @since Log4J 2.4 */ private final transient long nanoTime; /** LogEvent Builder helper class. */ public static class Builder implements org.apache.logging.log4j.core.util.Builder<LogEvent> { private String loggerFqcn; private Marker marker; private Level level; private String loggerName; private Message message; private Throwable thrown; private long timeMillis = CLOCK.currentTimeMillis(); private ThrowableProxy thrownProxy; private Map<String, String> contextMap = ThreadContext.getImmutableContext(); private ThreadContext.ContextStack contextStack = ThreadContext.getImmutableStack(); private String threadName = null; private StackTraceElement source; private boolean includeLocation; private boolean endOfBatch = false; private long nanoTime; public Builder() { } public Builder(LogEvent other) { Objects.requireNonNull(other); if (other instanceof RingBufferLogEvent) { RingBufferLogEvent evt = (RingBufferLogEvent) other; evt.initializeBuilder(this); return; } this.loggerFqcn = other.getLoggerFqcn(); this.marker = other.getMarker(); this.level = other.getLevel(); this.loggerName = other.getLoggerName(); this.message = other.getMessage(); this.timeMillis = other.getTimeMillis(); this.thrown = other.getThrown(); this.contextMap = other.getContextMap(); this.contextStack = other.getContextStack(); this.includeLocation = other.isIncludeLocation(); this.endOfBatch = other.isEndOfBatch(); this.nanoTime = other.getNanoTime(); // Avoid unnecessarily initializing thrownProxy, threadName and source if possible if (other instanceof Log4jLogEvent) { Log4jLogEvent evt = (Log4jLogEvent) other; this.thrownProxy = evt.thrownProxy; this.source = evt.source; this.threadName = evt.threadName; } else { this.thrownProxy = other.getThrownProxy(); this.source = other.getSource(); this.threadName = other.getThreadName(); } } public Builder setLevel(final Level level) { this.level = level; return this; } public Builder setLoggerFqcn(final String loggerFqcn) { this.loggerFqcn = loggerFqcn; return this; } public Builder setLoggerName(final String loggerName) { this.loggerName = loggerName; return this; } public Builder setMarker(final Marker marker) { this.marker = marker; return this; } public Builder setMessage(final Message message) { this.message = message; return this; } public Builder setThrown(final Throwable thrown) { this.thrown = thrown; return this; } public Builder setTimeMillis(long timeMillis) { this.timeMillis = timeMillis; return this; } public Builder setThrownProxy(ThrowableProxy thrownProxy) { this.thrownProxy = thrownProxy; return this; } public Builder setContextMap(Map<String, String> contextMap) { this.contextMap = contextMap; return this; } public Builder setContextStack(ThreadContext.ContextStack contextStack) { this.contextStack = contextStack; return this; } public Builder setThreadName(String threadName) { this.threadName = threadName; return this; } public Builder setSource(StackTraceElement source) { this.source = source; return this; } public Builder setIncludeLocation(boolean includeLocation) { this.includeLocation = includeLocation; return this; } public Builder setEndOfBatch(boolean endOfBatch) { this.endOfBatch = endOfBatch; return this; } /** * Sets the nano time for the event. * @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event * was created. * @return this builder */ public Builder setNanoTime(long nanoTime) { this.nanoTime = nanoTime; return this; } @Override public Log4jLogEvent build() { final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFqcn, level, message, thrown, thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime); result.setIncludeLocation(includeLocation); result.setEndOfBatch(endOfBatch); return result; } } /** * Returns a new empty {@code Log4jLogEvent.Builder} with all fields empty. * @return a new empty builder. */ public static Builder newBuilder() { return new Builder(); } public Log4jLogEvent() { this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null, CLOCK.currentTimeMillis(), nanoClock.nanoTime()); } /** * * @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release. */ @Deprecated public Log4jLogEvent(final long timestamp) { this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null, timestamp, nanoClock.nanoTime()); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param t A Throwable or null. * @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release. */ @Deprecated public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable t) { this(loggerName, marker, loggerFQCN, level, message, null, t); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param properties properties to add to the event. * @param t A Throwable or null. */ // This constructor is called from LogEventFactories. public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final List<Property> properties, final Throwable t) { this(loggerName, marker, loggerFQCN, level, message, t, null, createMap(properties), ThreadContext.getDepth() == 0 ? null : ThreadContext.cloneStack(), // mutable copy null, // thread name null, // stack trace element // LOG4J2-628 use log4j.Clock for timestamps // LOG4J2-744 unless TimestampMessage already has one message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() : CLOCK.currentTimeMillis(), nanoClock.nanoTime()); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param t A Throwable or null. * @param mdc The mapped diagnostic context. * @param ndc the nested diagnostic context. * @param threadName The name of the thread. * @param location The locations of the caller. * @param timestampMillis The timestamp of the event. * @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release. */ @Deprecated public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable t, final Map<String, String> mdc, final ThreadContext.ContextStack ndc, final String threadName, final StackTraceElement location, final long timestampMillis) { this(loggerName, marker, loggerFQCN, level, message, t, null, mdc, ndc, threadName, location, timestampMillis, nanoClock.nanoTime()); } /** * Create a new LogEvent. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param thrown A Throwable or null. * @param thrownProxy A ThrowableProxy or null. * @param mdc The mapped diagnostic context. * @param ndc the nested diagnostic context. * @param threadName The name of the thread. * @param location The locations of the caller. * @param timestamp The timestamp of the event. * @return a new LogEvent * @deprecated use {@link Log4jLogEvent.Builder} instead. This method will be removed in an upcoming release. */ @Deprecated public static Log4jLogEvent createEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable thrown, final ThrowableProxy thrownProxy, final Map<String, String> mdc, final ThreadContext.ContextStack ndc, final String threadName, final StackTraceElement location, final long timestamp) { final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown, thrownProxy, mdc, ndc, threadName, location, timestamp, nanoClock.nanoTime()); return result; } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified class name of the caller. * @param level The logging Level. * @param message The Message. * @param thrown A Throwable or null. * @param thrownProxy A ThrowableProxy or null. * @param contextMap The mapped diagnostic context. * @param contextStack the nested diagnostic context. * @param threadName The name of the thread. * @param source The locations of the caller. * @param timestamp The timestamp of the event. * @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event was * created. */ private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable thrown, final ThrowableProxy thrownProxy, final Map<String, String> contextMap, final ThreadContext.ContextStack contextStack, final String threadName, final StackTraceElement source, final long timestampMillis, final long nanoTime) { this.loggerName = loggerName; this.marker = marker; this.loggerFqcn = loggerFQCN; this.level = level == null ? Level.OFF : level; // LOG4J2-462, LOG4J2-465 this.message = message; this.thrown = thrown; this.thrownProxy = thrownProxy; this.contextMap = contextMap == null ? ThreadContext.EMPTY_MAP : contextMap; this.contextStack = contextStack == null ? ThreadContext.EMPTY_STACK : contextStack; this.timeMillis = message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() : timestampMillis; this.threadName = threadName; this.source = source; if (message != null && message instanceof LoggerNameAwareMessage) { ((LoggerNameAwareMessage) message).setLoggerName(loggerName); } this.nanoTime = nanoTime; } private static Map<String, String> createMap(final List<Property> properties) { final Map<String, String> contextMap = ThreadContext.getImmutableContext(); if (properties == null || properties.isEmpty()) { return contextMap; // may be ThreadContext.EMPTY_MAP but not null } final Map<String, String> map = new HashMap<>(contextMap); for (final Property prop : properties) { if (!map.containsKey(prop.getName())) { map.put(prop.getName(), prop.getValue()); } } return Collections.unmodifiableMap(map); } /** * Returns the {@code NanoClock} to use for creating the nanoTime timestamp of log events. * @return the {@code NanoClock} to use for creating the nanoTime timestamp of log events */ public static NanoClock getNanoClock() { return nanoClock; } /** * Sets the {@code NanoClock} to use for creating the nanoTime timestamp of log events. * <p> * FOR INTERNAL USE. This method may be called with a different {@code NanoClock} implementation when the * configuration changes. * * @param nanoClock the {@code NanoClock} to use for creating the nanoTime timestamp of log events */ public static void setNanoClock(NanoClock nanoClock) { Log4jLogEvent.nanoClock = Objects.requireNonNull(nanoClock, "NanoClock must be non-null"); StatusLogger.getLogger().trace("Using {} for nanosecond timestamps.", nanoClock.getClass().getSimpleName()); } /** * Returns a new fully initialized {@code Log4jLogEvent.Builder} containing a copy of all fields of this event. * @return a new fully initialized builder. */ public Builder asBuilder() { return new Builder(this); } /** * Returns the logging Level. * @return the Level associated with this event. */ @Override public Level getLevel() { return level; } /** * Returns the name of the Logger used to generate the event. * @return The Logger name. */ @Override public String getLoggerName() { return loggerName; } /** * Returns the Message associated with the event. * @return The Message. */ @Override public Message getMessage() { return message; } /** * Returns the name of the Thread on which the event was generated. * @return The name of the Thread. */ @Override public String getThreadName() { if (threadName == null) { threadName = Thread.currentThread().getName(); } return threadName; } /** * Returns the time in milliseconds from the epoch when the event occurred. * @return The time the event occurred. */ @Override public long getTimeMillis() { return timeMillis; } /** * Returns the Throwable associated with the event, or null. * @return The Throwable associated with the event. */ @Override public Throwable getThrown() { return thrown; } /** * Returns the ThrowableProxy associated with the event, or null. * @return The ThrowableProxy associated with the event. */ @Override public ThrowableProxy getThrownProxy() { if (thrownProxy == null && thrown != null) { thrownProxy = new ThrowableProxy(thrown); } return thrownProxy; } /** * Returns the Marker associated with the event, or null. * @return the Marker associated with the event. */ @Override public Marker getMarker() { return marker; } /** * The fully qualified class name of the class that was called by the caller. * @return the fully qualified class name of the class that is performing logging. */ @Override public String getLoggerFqcn() { return loggerFqcn; } /** * Returns the immutable copy of the ThreadContext Map. * @return The context Map. */ @Override public Map<String, String> getContextMap() { return contextMap; } /** * Returns an immutable copy of the ThreadContext stack. * @return The context Stack. */ @Override public ThreadContext.ContextStack getContextStack() { return contextStack; } /** * Returns the StackTraceElement for the caller. This will be the entry that occurs right * before the first occurrence of FQCN as a class name. * @return the StackTraceElement for the caller. */ @Override public StackTraceElement getSource() { if (source != null) { return source; } if (loggerFqcn == null || !includeLocation) { return null; } source = calcLocation(loggerFqcn); return source; } public static StackTraceElement calcLocation(final String fqcnOfLogger) { if (fqcnOfLogger == null) { return null; } // LOG4J2-1029 new Throwable().getStackTrace is faster than Thread.currentThread().getStackTrace(). final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); StackTraceElement last = null; for (int i = stackTrace.length - 1; i > 0; i--) { final String className = stackTrace[i].getClassName(); if (fqcnOfLogger.equals(className)) { return last; } last = stackTrace[i]; } return null; } @Override public boolean isIncludeLocation() { return includeLocation; } @Override public void setIncludeLocation(final boolean includeLocation) { this.includeLocation = includeLocation; } @Override public boolean isEndOfBatch() { return endOfBatch; } @Override public void setEndOfBatch(final boolean endOfBatch) { this.endOfBatch = endOfBatch; } @Override public long getNanoTime() { return nanoTime; } /** * Creates a LogEventProxy that can be serialized. * @return a LogEventProxy. */ protected Object writeReplace() { getThrownProxy(); // ensure ThrowableProxy is initialized return new LogEventProxy(this, this.includeLocation); } public static Serializable serialize(final Log4jLogEvent event, final boolean includeLocation) { event.getThrownProxy(); // ensure ThrowableProxy is initialized return new LogEventProxy(event, includeLocation); } public static boolean canDeserialize(final Serializable event) { return event instanceof LogEventProxy; } public static Log4jLogEvent deserialize(final Serializable event) { Objects.requireNonNull(event, "Event cannot be null"); if (event instanceof LogEventProxy) { final LogEventProxy proxy = (LogEventProxy) event; final Log4jLogEvent result = new Log4jLogEvent(proxy.loggerName, proxy.marker, proxy.loggerFQCN, proxy.level, proxy.message, proxy.thrown, proxy.thrownProxy, proxy.contextMap, proxy.contextStack, proxy.threadName, proxy.source, proxy.timeMillis, proxy.nanoTime); result.setEndOfBatch(proxy.isEndOfBatch); result.setIncludeLocation(proxy.isLocationRequired); return result; } throw new IllegalArgumentException("Event is not a serialized LogEvent: " + event.toString()); } private void readObject(final ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Proxy required"); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); final String n = loggerName.isEmpty() ? LoggerConfig.ROOT : loggerName; sb.append("Logger=").append(n); sb.append(" Level=").append(level.name()); sb.append(" Message=").append(message.getFormattedMessage()); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Log4jLogEvent that = (Log4jLogEvent) o; if (endOfBatch != that.endOfBatch) { return false; } if (includeLocation != that.includeLocation) { return false; } if (timeMillis != that.timeMillis) { return false; } if (nanoTime != that.nanoTime) { return false; } if (loggerFqcn != null ? !loggerFqcn.equals(that.loggerFqcn) : that.loggerFqcn != null) { return false; } if (level != null ? !level.equals(that.level) : that.level != null) { return false; } if (source != null ? !source.equals(that.source) : that.source != null) { return false; } if (marker != null ? !marker.equals(that.marker) : that.marker != null) { return false; } if (contextMap != null ? !contextMap.equals(that.contextMap) : that.contextMap != null) { return false; } if (!message.equals(that.message)) { return false; } if (!loggerName.equals(that.loggerName)) { return false; } if (contextStack != null ? !contextStack.equals(that.contextStack) : that.contextStack != null) { return false; } if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) { return false; } if (thrown != null ? !thrown.equals(that.thrown) : that.thrown != null) { return false; } if (thrownProxy != null ? !thrownProxy.equals(that.thrownProxy) : that.thrownProxy != null) { return false; } return true; } @Override public int hashCode() { // Check:OFF: MagicNumber int result = loggerFqcn != null ? loggerFqcn.hashCode() : 0; result = 31 * result + (marker != null ? marker.hashCode() : 0); result = 31 * result + (level != null ? level.hashCode() : 0); result = 31 * result + loggerName.hashCode(); result = 31 * result + message.hashCode(); result = 31 * result + (int) (timeMillis ^ (timeMillis >>> 32)); result = 31 * result + (int) (nanoTime ^ (nanoTime >>> 32)); result = 31 * result + (thrown != null ? thrown.hashCode() : 0); result = 31 * result + (thrownProxy != null ? thrownProxy.hashCode() : 0); result = 31 * result + (contextMap != null ? contextMap.hashCode() : 0); result = 31 * result + (contextStack != null ? contextStack.hashCode() : 0); result = 31 * result + (threadName != null ? threadName.hashCode() : 0); result = 31 * result + (source != null ? source.hashCode() : 0); result = 31 * result + (includeLocation ? 1 : 0); result = 31 * result + (endOfBatch ? 1 : 0); // Check:ON: MagicNumber return result; } /** * Proxy pattern used to serialize the LogEvent. */ private static class LogEventProxy implements Serializable { private static final long serialVersionUID = -7139032940312647146L; private final String loggerFQCN; private final Marker marker; private final Level level; private final String loggerName; private final Message message; private final long timeMillis; private final transient Throwable thrown; private final ThrowableProxy thrownProxy; private final Map<String, String> contextMap; private final ThreadContext.ContextStack contextStack; private final String threadName; private final StackTraceElement source; private final boolean isLocationRequired; private final boolean isEndOfBatch; /** @since Log4J 2.4 */ private final transient long nanoTime; public LogEventProxy(final Log4jLogEvent event, final boolean includeLocation) { this.loggerFQCN = event.loggerFqcn; this.marker = event.marker; this.level = event.level; this.loggerName = event.loggerName; this.message = event.message; this.timeMillis = event.timeMillis; this.thrown = event.thrown; this.thrownProxy = event.thrownProxy; this.contextMap = event.contextMap; this.contextStack = event.contextStack; this.source = includeLocation ? event.getSource() : null; this.threadName = event.getThreadName(); this.isLocationRequired = includeLocation; this.isEndOfBatch = event.endOfBatch; this.nanoTime = event.nanoTime; } /** * Returns a Log4jLogEvent using the data in the proxy. * @return Log4jLogEvent. */ protected Object readResolve() { final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown, thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime); result.setEndOfBatch(isEndOfBatch); result.setIncludeLocation(isLocationRequired); return result; } } }
formatting
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java
formatting
<ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java <ide> private boolean includeLocation; <ide> private boolean endOfBatch = false; <ide> private long nanoTime; <del> <add> <ide> public Builder() { <ide> } <del> <add> <ide> public Builder(LogEvent other) { <ide> Objects.requireNonNull(other); <ide> if (other instanceof RingBufferLogEvent) { <ide> this.includeLocation = other.isIncludeLocation(); <ide> this.endOfBatch = other.isEndOfBatch(); <ide> this.nanoTime = other.getNanoTime(); <del> <add> <ide> // Avoid unnecessarily initializing thrownProxy, threadName and source if possible <ide> if (other instanceof Log4jLogEvent) { <ide> Log4jLogEvent evt = (Log4jLogEvent) other; <ide> final Map<String, String> mdc, final ThreadContext.ContextStack ndc, <ide> final String threadName, final StackTraceElement location, <ide> final long timestamp) { <del> final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown, <add> final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown, <ide> thrownProxy, mdc, ndc, threadName, location, timestamp, nanoClock.nanoTime()); <ide> return result; <ide> } <ide> * @param contextStack the nested diagnostic context. <ide> * @param threadName The name of the thread. <ide> * @param source The locations of the caller. <del> * @param timestamp The timestamp of the event. <add> * @param timestampMillis The timestamp of the event. <ide> * @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event was <ide> * created. <ide> */ <ide> } <ide> return Collections.unmodifiableMap(map); <ide> } <del> <add> <ide> /** <ide> * Returns the {@code NanoClock} to use for creating the nanoTime timestamp of log events. <ide> * @return the {@code NanoClock} to use for creating the nanoTime timestamp of log events <ide> public static NanoClock getNanoClock() { <ide> return nanoClock; <ide> } <del> <add> <ide> /** <ide> * Sets the {@code NanoClock} to use for creating the nanoTime timestamp of log events. <ide> * <p> <ide> * FOR INTERNAL USE. This method may be called with a different {@code NanoClock} implementation when the <ide> * configuration changes. <del> * <add> * <ide> * @param nanoClock the {@code NanoClock} to use for creating the nanoTime timestamp of log events <ide> */ <ide> public static void setNanoClock(NanoClock nanoClock) { <ide> Log4jLogEvent.nanoClock = Objects.requireNonNull(nanoClock, "NanoClock must be non-null"); <ide> StatusLogger.getLogger().trace("Using {} for nanosecond timestamps.", nanoClock.getClass().getSimpleName()); <ide> } <del> <add> <ide> /** <ide> * Returns a new fully initialized {@code Log4jLogEvent.Builder} containing a copy of all fields of this event. <ide> * @return a new fully initialized builder.
Java
bsd-3-clause
176c2baab7670691fafb9f4c472ed0e012032bee
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.calab.service.util; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.log4j.Logger; import java.util.List; /** * This class contains a set of utilities for converting Strings to other * formats or converting other formats to String. * * @author pansu * */ /* CVS $Id: StringUtils.java,v 1.14 2007-06-05 20:10:02 pansu Exp $ */ public class StringUtils { private static Logger logger = Logger.getLogger(StringUtils.class); public static Date convertToDate(String dateString, String dateFormat) { if (dateString == null || dateString == "") { return null; } Date theDate = null; try { ParsePosition pos = new ParsePosition(0); SimpleDateFormat format = new SimpleDateFormat(dateFormat); theDate = format.parse(dateString, pos); // method parse doesn't throw an exception when parsing is partial. // e.g. date 5/11/200w will // be parsed as 5/11/200 !!! if (pos.getIndex() != dateString.length()) { throw new RuntimeException( "The date String is not completely parsed"); } return theDate; } catch (Exception e) { logger .error( "Error parsing the given date String using the given dateFormat", e); throw new RuntimeException("The date String " + dateString + " can't be parsed against the date format:" + dateFormat); } } public static String join(String[] stringArray, String delimiter) { String joinedStr = ""; if (stringArray == null) { return joinedStr; } for (int i = 0; i < stringArray.length; i++) { String str = stringArray[i]; if (str == null) { str = ""; } if ((str.length() > 0)) { if (i < stringArray.length - 1) { joinedStr += str + delimiter; } else { joinedStr += str; } } } if (joinedStr.endsWith(delimiter)) { joinedStr = joinedStr.substring(0, joinedStr.length() - 1); } return joinedStr; } public static String join(List<String> stringList, String delimiter) { String joinedStr = ""; if (stringList == null || stringList.isEmpty()) { return joinedStr; } // remove null and empty item from the list for (String str : stringList) { if (str == null) { stringList.remove(str); } if (str.length() == 0) { stringList.remove(str); } } int i = 0; for (String str : stringList) { if (i < stringList.size() - 1) { joinedStr += str + delimiter; } else { joinedStr += str; } i++; } return joinedStr; } public static String convertDateToString(Date date, String format) { if (date == null) { return ""; } String dateStr = null; SimpleDateFormat dateFormat = new SimpleDateFormat(format); try { dateStr = dateFormat.format(date); } catch (Exception e) { logger .error( "Error converting the given date using the given dateFormat", e); throw new RuntimeException("Can't format the given date: " + date); } return dateStr; } public static Float convertToFloat(String floatStr) { if (floatStr == null || floatStr == "") { return null; } try { Float floatNum = Float.parseFloat(floatStr); return floatNum; } catch (NumberFormatException e) { logger.error("Error converting the given string to a float number", e); throw new RuntimeException( "Can't convert the given string to a float number: " + floatStr); } } public static Long convertToLong(String longStr) { if (longStr == null || longStr == "") { return null; } try { Long longNum = Long.parseLong(longStr); return longNum; } catch (NumberFormatException e) { logger.error("Error converting the given string to a long number", e); throw new RuntimeException( "Can't convert the given string to a long number: " + longStr); } } public static String convertToString(Object obj) { if (obj == null) { return ""; } else { return obj.toString(); } } public static boolean isInteger(String theStr) { if (theStr == null || theStr.length() == 0) { return false; } else { for (int i = 0; i < theStr.length(); i++) { if (!Character.isDigit(theStr.charAt(i))) { return false; } } return true; } } public static boolean isDouble(String theStr) { int decimalCount = 0; if (theStr == null || theStr.length() == 0) { return false; } else { for (int i = 0; i < theStr.length(); i++) { if (!Character.isDigit(theStr.charAt(i))) { if (theStr.charAt(i) == ('.')) { decimalCount++; continue; } else { return false; } } } if (decimalCount == 1) return true; else return false; } } public static boolean contains(String[] array, String aString, boolean ignoreCase) { boolean containsString = false; for (int i = 0; i < array.length; i++) { if (ignoreCase) { if (array[i].equalsIgnoreCase(aString)) containsString = true; } else { if (array[i].equals(aString)) containsString = true; } } return containsString; } public static String[] add(String[] x, String aString) { String[] result = new String[x.length + 1]; for (int i = 0; i < x.length; i++) { result[i] = x[i]; } result[x.length] = aString; return result; } public static String getTimeAsString() { String time = null; Calendar calendar = Calendar.getInstance(); time = "" + calendar.get(Calendar.YEAR); time = time + (calendar.get(Calendar.MONTH) < 9 ? "0" + (calendar.get(Calendar.MONTH) + 1) : "" + (calendar.get(Calendar.MONTH) + 1)); time = time + (calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + calendar.get(Calendar.DAY_OF_MONTH) : "" + calendar.get(Calendar.DAY_OF_MONTH)) + "_"; time = time + calendar.get(Calendar.HOUR_OF_DAY) + "-"; time = time + (calendar.get(Calendar.MINUTE) < 10 ? "0" + calendar.get(Calendar.MINUTE) : "" + calendar.get(Calendar.MINUTE)) + "-"; time = time + (calendar.get(Calendar.SECOND) < 10 ? "0" + calendar.get(Calendar.SECOND) : "" + calendar.get(Calendar.SECOND)) + "-"; time = time + calendar.get(Calendar.MILLISECOND); return time; } public static String getDateAsString() { Calendar calendar = Calendar.getInstance(); String month=calendar.get(Calendar.MONTH) < 9 ? "0" + (calendar.get(Calendar.MONTH) + 1) : "" + (calendar.get(Calendar.MONTH) + 1); String day=calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + calendar.get(Calendar.DAY_OF_MONTH) : "" + calendar.get(Calendar.DAY_OF_MONTH); String year=calendar.get(Calendar.YEAR)+""; return month+day+year; } public static void main(String[] args) { String dateString=StringUtils.getDateAsString(); System.out.println(dateString); } }
src/gov/nih/nci/calab/service/util/StringUtils.java
package gov.nih.nci.calab.service.util; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.log4j.Logger; import java.util.List; /** * This class contains a set of utilities for converting Strings to other * formats or converting other formats to String. * * @author pansu * */ /* CVS $Id: StringUtils.java,v 1.13 2007-05-11 20:44:03 pansu Exp $ */ public class StringUtils { private static Logger logger = Logger.getLogger(StringUtils.class); public static Date convertToDate(String dateString, String dateFormat) { if (dateString == null || dateString == "") { return null; } Date theDate = null; try { ParsePosition pos = new ParsePosition(0); SimpleDateFormat format = new SimpleDateFormat(dateFormat); theDate = format.parse(dateString, pos); // method parse doesn't throw an exception when parsing is partial. // e.g. date 5/11/200w will // be parsed as 5/11/200 !!! if (pos.getIndex() != dateString.length()) { throw new RuntimeException( "The date String is not completely parsed"); } return theDate; } catch (Exception e) { logger .error( "Error parsing the given date String using the given dateFormat", e); throw new RuntimeException("The date String " + dateString + " can't be parsed against the date format:" + dateFormat); } } public static String join(String[] stringArray, String delimiter) { String joinedStr = ""; if (stringArray == null) { return joinedStr; } for (int i = 0; i < stringArray.length; i++) { String str = stringArray[i]; if (str == null) { str = ""; } if ((str.length() > 0)) { if (i < stringArray.length - 1) { joinedStr += str + delimiter; } else { joinedStr += str; } } } if (joinedStr.endsWith(delimiter)) { joinedStr = joinedStr.substring(0, joinedStr.length() - 1); } return joinedStr; } public static String join(List<String> stringList, String delimiter) { String joinedStr = ""; if (stringList == null || stringList.isEmpty()) { return joinedStr; } // remove null and empty item from the list for (String str : stringList) { if (str == null) { stringList.remove(str); } if (str.length() == 0) { stringList.remove(str); } } int i = 0; for (String str : stringList) { if (i < stringList.size() - 1) { joinedStr += str + delimiter; } else { joinedStr += str; } i++; } return joinedStr; } public static String convertDateToString(Date date, String format) { if (date == null) { return ""; } String dateStr = null; SimpleDateFormat dateFormat = new SimpleDateFormat(format); try { dateStr = dateFormat.format(date); } catch (Exception e) { logger .error( "Error converting the given date using the given dateFormat", e); throw new RuntimeException("Can't format the given date: " + date); } return dateStr; } public static Float convertToFloat(String floatStr) { if (floatStr == null || floatStr == "") { return null; } try { Float floatNum = Float.parseFloat(floatStr); return floatNum; } catch (NumberFormatException e) { logger.error("Error converting the given string to a float number", e); throw new RuntimeException( "Can't convert the given string to a float number: " + floatStr); } } public static Long convertToLong(String longStr) { if (longStr == null || longStr == "") { return null; } try { Long longNum = Long.parseLong(longStr); return longNum; } catch (NumberFormatException e) { logger.error("Error converting the given string to a long number", e); throw new RuntimeException( "Can't convert the given string to a long number: " + longStr); } } public static String convertToString(Object obj) { if (obj == null) { return ""; } else { return obj.toString(); } } public static boolean isInteger(String theStr) { if (theStr == null || theStr.length() == 0) { return false; } else { for (int i = 0; i < theStr.length(); i++) { if (!Character.isDigit(theStr.charAt(i))) { return false; } } return true; } } public static boolean isDouble(String theStr) { int decimalCount = 0; if (theStr == null || theStr.length() == 0) { return false; } else { for (int i = 0; i < theStr.length(); i++) { if (!Character.isDigit(theStr.charAt(i))) { if (theStr.charAt(i) == ('.')) { decimalCount++; continue; } else { return false; } } } if (decimalCount == 1) return true; else return false; } } public static boolean contains(String[] array, String aString, boolean ignoreCase) { boolean containsString = false; for (int i = 0; i < array.length; i++) { if (ignoreCase) { if (array[i].equalsIgnoreCase(aString)) containsString = true; } else { if (array[i].equals(aString)) containsString = true; } } return containsString; } public static String[] add(String[] x, String aString) { String[] result = new String[x.length + 1]; for (int i = 0; i < x.length; i++) { result[i] = x[i]; } result[x.length] = aString; return result; } public static String getTimeAsString() { String time = null; Calendar calendar = Calendar.getInstance(); time = "" + calendar.get(Calendar.YEAR); time = time + (calendar.get(Calendar.MONTH) < 9 ? "0" + (calendar.get(Calendar.MONTH) + 1) : "" + (calendar.get(Calendar.MONTH) + 1)); time = time + (calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + calendar.get(Calendar.DAY_OF_MONTH) : "" + calendar.get(Calendar.DAY_OF_MONTH)) + "_"; time = time + calendar.get(Calendar.HOUR_OF_DAY) + "-"; time = time + (calendar.get(Calendar.MINUTE) < 10 ? "0" + calendar.get(Calendar.MINUTE) : "" + calendar.get(Calendar.MINUTE)) + "-"; time = time + (calendar.get(Calendar.SECOND) < 10 ? "0" + calendar.get(Calendar.SECOND) : "" + calendar.get(Calendar.SECOND)) + "-"; time = time + calendar.get(Calendar.MILLISECOND); return time; } }
added getDateAsString SVN-Revision: 3208
src/gov/nih/nci/calab/service/util/StringUtils.java
added getDateAsString
<ide><path>rc/gov/nih/nci/calab/service/util/StringUtils.java <ide> * @author pansu <ide> * <ide> */ <del>/* CVS $Id: StringUtils.java,v 1.13 2007-05-11 20:44:03 pansu Exp $ */ <add>/* CVS $Id: StringUtils.java,v 1.14 2007-06-05 20:10:02 pansu Exp $ */ <ide> <ide> public class StringUtils { <ide> private static Logger logger = Logger.getLogger(StringUtils.class); <ide> time = time + calendar.get(Calendar.MILLISECOND); <ide> return time; <ide> } <add> <add> public static String getDateAsString() { <add> <add> Calendar calendar = Calendar.getInstance(); <add> String month=calendar.get(Calendar.MONTH) < 9 ? "0" <add> + (calendar.get(Calendar.MONTH) + 1) : "" <add> + (calendar.get(Calendar.MONTH) + 1); <add> String day=calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" <add> + calendar.get(Calendar.DAY_OF_MONTH) : "" <add> + calendar.get(Calendar.DAY_OF_MONTH); <add> String year=calendar.get(Calendar.YEAR)+""; <add> return month+day+year; <add> } <add> <add> public static void main(String[] args) { <add> String dateString=StringUtils.getDateAsString(); <add> System.out.println(dateString); <add> } <ide> }
Java
apache-2.0
8b4bf2be1091271cbdc936179bd22061aff8c881
0
Juanjojara/cordova-plugin-background-geolocation,Juanjojara/cordova-plugin-background-geolocation,Juanjojara/cordova-plugin-background-geolocation
package com.tenforwardconsulting.cordova.bgloc; import java.io.IOException; import java.util.List; import java.util.Iterator; import java.util.Locale; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import com.tenforwardconsulting.cordova.bgloc.data.DAOFactory; import com.tenforwardconsulting.cordova.bgloc.data.LocationDAO; import com.tenforwardconsulting.cordova.bgloc.data.CardDAO; import android.annotation.TargetApi; import android.media.AudioManager; import android.media.ToneGenerator; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import static android.telephony.PhoneStateListener.*; import android.telephony.CellLocation; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.location.Location; import android.location.Criteria; import android.location.Address; import android.location.Geocoder; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; import static java.lang.Math.*; public class LocationUpdateService extends Service implements LocationListener { private static final String TAG = "LocationUpdateService"; private static final String STATIONARY_REGION_ACTION = "com.tenforwardconsulting.cordova.bgloc.STATIONARY_REGION_ACTION"; private static final String STATIONARY_ALARM_ACTION = "com.tenforwardconsulting.cordova.bgloc.STATIONARY_ALARM_ACTION"; private static final String SINGLE_LOCATION_UPDATE_ACTION = "com.tenforwardconsulting.cordova.bgloc.SINGLE_LOCATION_UPDATE_ACTION"; private static final String STATIONARY_LOCATION_MONITOR_ACTION = "com.tenforwardconsulting.cordova.bgloc.STATIONARY_LOCATION_MONITOR_ACTION"; private static final String NOTIFICATION_CONFIRM_ACTION = "com.tenforwardconsulting.cordova.bgloc.NOTIFICATION_CONFIRM_ACTION"; private static final String NOTIFICATION_DISCARD_ACTION = "com.tenforwardconsulting.cordova.bgloc.NOTIFICATION_DISCARD_ACTION"; private static final String NOTIFICATION_ARG_ID = "NOTIF_ID"; private static final String NOTIFICATION_ARG_CARD_ID = "CARD_ID"; private static final long STATIONARY_TIMEOUT = 5 * 1000 * 60; // 5 minutes. private static final long STATIONARY_LOCATION_POLLING_INTERVAL_LAZY = 3 * 1000 * 60; // 3 minutes. private static final long STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE = 1 * 1000 * 60; // 1 minute. private static final Integer MAX_STATIONARY_ACQUISITION_ATTEMPTS = 5; private static final Integer MAX_SPEED_ACQUISITION_ATTEMPTS = 3; private static Context mContext; private static String message; private PowerManager.WakeLock wakeLock; private Location lastLocation; private long lastUpdateTime = 0l; private JSONObject params; private JSONObject params_share; private JSONObject headers; private String url = "http://192.168.2.15:3000/users/current_location.json"; private float stationaryRadius; private Location stationaryLocation; private PendingIntent stationaryAlarmPI; private PendingIntent stationaryLocationPollingPI; private long stationaryLocationPollingInterval; private PendingIntent stationaryRegionPI; private PendingIntent singleUpdatePI; private PendingIntent notificationConfirmPI; //private PendingIntent notificationDiscardPI; private Boolean isMoving = false; private Boolean isAcquiringStationaryLocation = false; private Boolean isAcquiringSpeed = false; private Integer locationAcquisitionAttempts = 0; private Integer desiredAccuracy = 100; private Integer distanceFilter = 30; private Integer scaledDistanceFilter; private Integer locationTimeout = 30; private Boolean isDebugging; private String notificationTitle = "Background checking"; private String notificationText = "ENABLED"; private ToneGenerator toneGenerator; private Criteria criteria; private LocationManager locationManager; private AlarmManager alarmManager; private ConnectivityManager connectivityManager; private NotificationManager notificationManager; public static TelephonyManager telephonyManager = null; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.i(TAG, "OnBind" + intent); return null; } @Override public void onCreate() { super.onCreate(); mContext = this; Log.i(TAG, "OnCreate"); locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // Stop-detection PI stationaryAlarmPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_ALARM_ACTION), 0); registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION)); // Stationary region PI stationaryRegionPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_REGION_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION)); // Stationary location monitor PI stationaryLocationPollingPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0); registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION)); // One-shot PI (TODO currently unused) singleUpdatePI = PendingIntent.getBroadcast(this, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION)); // Notification Confirm Monitor PI notificationConfirmPI = PendingIntent.getBroadcast(this, 0, new Intent(NOTIFICATION_CONFIRM_ACTION), 0); registerReceiver(notificatinConfirmReceiver, new IntentFilter(NOTIFICATION_CONFIRM_ACTION)); // Notification Discard Monitor PI //notificationDiscardPI = PendingIntent.getBroadcast(this, 0, new Intent(NOTIFICATION_DISCARD_ACTION), 0); //registerReceiver(notificatinDiscardReceiver, new IntentFilter(NOTIFICATION_DISCARD_ACTION)); //// // DISABLED // Listen to Cell-tower switches (NOTE does not operate while suspended) //telephonyManager.listen(phoneStateListener, LISTEN_CELL_LOCATION); // PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(); // Location criteria criteria = new Criteria(); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setSpeedRequired(true); criteria.setCostAllowed(true); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "Received start id " + startId + ": " + intent); if (intent != null) { try { params = new JSONObject(intent.getStringExtra("params")); headers = new JSONObject(intent.getStringExtra("headers")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } url = intent.getStringExtra("url"); stationaryRadius = Float.parseFloat(intent.getStringExtra("stationaryRadius")); distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter")); scaledDistanceFilter = distanceFilter; desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy")); locationTimeout = Integer.parseInt(intent.getStringExtra("locationTimeout")); isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging")); notificationTitle = intent.getStringExtra("notificationTitle"); notificationText = intent.getStringExtra("notificationText"); // Build a Notification required for running service in foreground. Intent main = new Intent(this, BackgroundGpsPlugin.class); main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle(notificationTitle); builder.setContentText(notificationText); builder.setSmallIcon(android.R.drawable.ic_menu_mylocation); builder.setContentIntent(pendingIntent); Notification notification; if (android.os.Build.VERSION.SDK_INT >= 16) { notification = buildForegroundNotification(builder); } else { notification = buildForegroundNotificationCompat(builder); } notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR; startForeground(startId, notification); } Log.i(TAG, "- url: " + url); Log.i(TAG, "- params: " + params.toString()); Log.i(TAG, "- headers: " + headers.toString()); Log.i(TAG, "- stationaryRadius: " + stationaryRadius); Log.i(TAG, "- distanceFilter: " + distanceFilter); Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy); Log.i(TAG, "- locationTimeout: " + locationTimeout); Log.i(TAG, "- isDebugging: " + isDebugging); Log.i(TAG, "- notificationTitle: " + notificationTitle); Log.i(TAG, "- notificationText: " + notificationText); this.setPace(false); //We want this service to continue running until it is explicitly stopped return START_REDELIVER_INTENT; } @TargetApi(16) private Notification buildForegroundNotification(Notification.Builder builder) { return builder.build(); } @SuppressWarnings("deprecation") @TargetApi(15) private Notification buildForegroundNotificationCompat(Notification.Builder builder) { return builder.getNotification(); } @Override public boolean stopService(Intent intent) { Log.i(TAG, "- Received stop: " + intent); cleanUp(); if (isDebugging) { Toast.makeText(this, "Background location tracking stopped", Toast.LENGTH_SHORT).show(); } return super.stopService(intent); } /** * * @param value set true to engage "aggressive", battery-consuming tracking, false for stationary-region tracking */ private void setPace(Boolean value) { Log.i(TAG, "setPace: " + value); Boolean wasMoving = isMoving; isMoving = value; isAcquiringStationaryLocation = false; isAcquiringSpeed = false; stationaryLocation = null; locationManager.removeUpdates(this); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(translateDesiredAccuracy(desiredAccuracy)); criteria.setPowerRequirement(Criteria.POWER_HIGH); if (isMoving) { // setPace can be called while moving, after distanceFilter has been recalculated. We don't want to re-acquire velocity in this case. if (!wasMoving) { isAcquiringSpeed = true; } } else { isAcquiringStationaryLocation = true; } // Temporarily turn on super-aggressive geolocation on all providers when acquiring velocity or stationary location. if (isAcquiringSpeed || isAcquiringStationaryLocation) { locationAcquisitionAttempts = 0; // Turn on each provider aggressively for a short period of time List<String> matchingProviders = locationManager.getAllProviders(); for (String provider: matchingProviders) { if (provider != LocationManager.PASSIVE_PROVIDER) { locationManager.requestLocationUpdates(provider, 0, 0, this); } } } else { locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), locationTimeout*1000, scaledDistanceFilter, this); } } /** * Translates a number representing desired accuracy of GeoLocation system from set [0, 10, 100, 1000]. * 0: most aggressive, most accurate, worst battery drain * 1000: least aggressive, least accurate, best for battery. */ private Integer translateDesiredAccuracy(Integer accuracy) { switch (accuracy) { case 1000: accuracy = Criteria.ACCURACY_LOW; break; case 100: accuracy = Criteria.ACCURACY_MEDIUM; break; case 10: accuracy = Criteria.ACCURACY_HIGH; break; case 0: accuracy = Criteria.ACCURACY_HIGH; break; default: accuracy = Criteria.ACCURACY_MEDIUM; } return accuracy; } /** * Returns the most accurate and timely previously detected location. * Where the last result is beyond the specified maximum distance or * latency a one-off location update is returned via the {@link LocationListener} * specified in {@link setChangedLocationListener}. * @param minDistance Minimum distance before we require a location update. * @param minTime Minimum time required between location updates. * @return The most accurate and / or timely previously detected location. */ public Location getLastBestLocation() { int minDistance = (int) stationaryRadius; long minTime = System.currentTimeMillis() - (locationTimeout * 1000); Log.i(TAG, "- fetching last best location " + minDistance + "," + minTime); Location bestResult = null; float bestAccuracy = Float.MAX_VALUE; long bestTime = Long.MIN_VALUE; // Iterate through all the providers on the system, keeping // note of the most accurate result within the acceptable time limit. // If no result is found within maxTime, return the newest Location. List<String> matchingProviders = locationManager.getAllProviders(); for (String provider: matchingProviders) { Log.d(TAG, "- provider: " + provider); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { Log.d(TAG, " location: " + location.getLatitude() + "," + location.getLongitude() + "," + location.getAccuracy() + "," + location.getSpeed() + "m/s"); float accuracy = location.getAccuracy(); long time = location.getTime(); Log.d(TAG, "time>minTime: " + (time > minTime) + ", accuracy<bestAccuracy: " + (accuracy < bestAccuracy)); if ((time > minTime && accuracy < bestAccuracy)) { bestResult = location; bestAccuracy = accuracy; bestTime = time; } } } return bestResult; } public void onLocationChanged(Location location) { Log.d(TAG, "- onLocationChanged: " + location.getLatitude() + "," + location.getLongitude() + ", accuracy: " + location.getAccuracy() + ", isMoving: " + isMoving + ", speed: " + location.getSpeed()); if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation==null) { // Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now. setPace(false); } if (isDebugging) { Toast.makeText(this, "mv:"+isMoving+",acy:"+location.getAccuracy()+",v:"+location.getSpeed()+",df:"+scaledDistanceFilter, Toast.LENGTH_LONG).show(); } if (isAcquiringStationaryLocation) { if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) { stationaryLocation = location; } if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) { isAcquiringStationaryLocation = false; startMonitoringStationaryRegion(stationaryLocation); if (isDebugging) { startTone("long_beep"); } } else { // Unacceptable stationary-location: bail-out and wait for another. if (isDebugging) { startTone("beep"); } return; } } else if (isAcquiringSpeed) { if (++locationAcquisitionAttempts == MAX_SPEED_ACQUISITION_ATTEMPTS) { // Got enough samples, assume we're confident in reported speed now. Play "woohoo" sound. if (isDebugging) { startTone("doodly_doo"); } isAcquiringSpeed = false; scaledDistanceFilter = calculateDistanceFilter(location.getSpeed()); setPace(true); } else { if (isDebugging) { startTone("beep"); } return; } } else if (isMoving) { if (isDebugging) { startTone("beep"); } // Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped. if ( (location.getSpeed() >= 1) && (location.getAccuracy() <= stationaryRadius) ) { resetStationaryAlarm(); } // Calculate latest distanceFilter, if it changed by 5 m/s, we'll reconfigure our pace. Integer newDistanceFilter = calculateDistanceFilter(location.getSpeed()); if (newDistanceFilter != scaledDistanceFilter.intValue()) { Log.i(TAG, "- updated distanceFilter, new: " + newDistanceFilter + ", old: " + scaledDistanceFilter); scaledDistanceFilter = newDistanceFilter; setPace(true); } if (location.distanceTo(lastLocation) < distanceFilter) { return; } } else if (stationaryLocation != null) { return; } // Go ahead and cache, push to server lastLocation = location; persistLocation(location); if (this.isNetworkConnected()) { Log.d(TAG, "Scheduling location network post"); schedulePostLocations(); } else { Log.d(TAG, "Network unavailable, waiting for now"); } } /** * Plays debug sound * @param name */ private void startTone(String name) { int tone = 0; int duration = 1000; if (name.equals("beep")) { tone = ToneGenerator.TONE_PROP_BEEP; } else if (name.equals("beep_beep_beep")) { tone = ToneGenerator.TONE_CDMA_CONFIRM; } else if (name.equals("long_beep")) { tone = ToneGenerator.TONE_CDMA_ABBR_ALERT; } else if (name.equals("doodly_doo")) { tone = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE; } else if (name.equals("chirp_chirp_chirp")) { tone = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD; } else if (name.equals("dialtone")) { tone = ToneGenerator.TONE_SUP_RINGTONE; } toneGenerator.startTone(tone, duration); } public void resetStationaryAlarm() { alarmManager.cancel(stationaryAlarmPI); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + STATIONARY_TIMEOUT, stationaryAlarmPI); // Millisec * Second * Minute } private Integer calculateDistanceFilter(Float speed) { Double newDistanceFilter = (double) distanceFilter; if (speed < 100) { float roundedDistanceFilter = (round(speed / 5) * 5); newDistanceFilter = pow(roundedDistanceFilter, 2) + (double) distanceFilter; } return (newDistanceFilter.intValue() < 1000) ? newDistanceFilter.intValue() : 1000; } private void startMonitoringStationaryRegion(Location location) { locationManager.removeUpdates(this); stationaryLocation = location; Log.i(TAG, "- startMonitoringStationaryRegion (" + location.getLatitude() + "," + location.getLongitude() + "), accuracy:" + location.getAccuracy()); // Here be the execution of the stationary region monitor locationManager.addProximityAlert( location.getLatitude(), location.getLongitude(), (location.getAccuracy() < stationaryRadius) ? stationaryRadius : location.getAccuracy(), (long)-1, stationaryRegionPI ); startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY); } public void startPollingStationaryLocation(long interval) { // proximity-alerts don't seem to work while suspended in latest Android 4.42 (works in 4.03). Have to use AlarmManager to sample // location at regular intervals with a one-shot. stationaryLocationPollingInterval = interval; alarmManager.cancel(stationaryLocationPollingPI); long start = System.currentTimeMillis() + (60 * 1000); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, start, interval, stationaryLocationPollingPI); } public void onPollStationaryLocation(Location location) { if (isMoving) { return; } if (isDebugging) { startTone("beep"); } float distance = abs(location.distanceTo(stationaryLocation) - stationaryLocation.getAccuracy() - location.getAccuracy()); if (isDebugging) { Toast.makeText(this, "Stationary exit in " + (stationaryRadius-distance) + "m", Toast.LENGTH_LONG).show(); } // TODO http://www.cse.buffalo.edu/~demirbas/publications/proximity.pdf // determine if we're almost out of stationary-distance and increase monitoring-rate. Log.i(TAG, "- distance from stationary location: " + distance); if (distance > stationaryRadius) { onExitStationaryRegion(location); } else if (distance > 0) { startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE); } else if (stationaryLocationPollingInterval != STATIONARY_LOCATION_POLLING_INTERVAL_LAZY) { startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY); } } /** * User has exit his stationary region! Initiate aggressive geolocation! */ public void onExitStationaryRegion(Location location) { // Filter-out spurious region-exits: must have at least a little speed to move out of stationary-region if (isDebugging) { startTone("beep_beep_beep"); } // Cancel the periodic stationary location monitor alarm. alarmManager.cancel(stationaryLocationPollingPI); // Kill the current region-monitor we just walked out of. locationManager.removeProximityAlert(stationaryRegionPI); // Engage aggressive tracking. this.setPace(true); } /** * TODO Experimental cell-tower change system; something like ios significant changes. */ public void onCellLocationChange(CellLocation cellLocation) { Log.i(TAG, "- onCellLocationChange" + cellLocation.toString()); if (isDebugging) { Toast.makeText(this, "Cellular location change", Toast.LENGTH_LONG).show(); startTone("chirp_chirp_chirp"); } if (!isMoving && stationaryLocation != null) { criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); criteria.setPowerRequirement(Criteria.POWER_HIGH); locationManager.requestSingleUpdate(criteria, singleUpdatePI); } } /** * Broadcast receiver for receiving a single-update from LocationManager. */ private BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String key = LocationManager.KEY_LOCATION_CHANGED; Location location = (Location)intent.getExtras().get(key); if (location != null) { Log.d(TAG, "- singleUpdateReciever" + location.toString()); onPollStationaryLocation(location); } } }; /** * Broadcast receiver which detcts a user has stopped for a long enough time to be determined as STOPPED */ private BroadcastReceiver stationaryAlarmReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "- stationaryAlarm fired"); setPace(false); } }; /** * Broadcast receiver to handle stationaryMonitor alarm, fired at low frequency while monitoring stationary-region. * This is required because latest Android proximity-alerts don't seem to operate while suspended. Regularly polling * the location seems to trigger the proximity-alerts while suspended. */ private BroadcastReceiver stationaryLocationMonitorReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "- stationaryLocationMonitorReceiver fired"); if (isDebugging) { startTone("dialtone"); } criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); criteria.setPowerRequirement(Criteria.POWER_HIGH); locationManager.requestSingleUpdate(criteria, singleUpdatePI); } }; /** * Broadcast receiver which detects a user has exit his circular stationary-region determined by the greater of stationaryLocation.getAccuracy() OR stationaryRadius */ private BroadcastReceiver stationaryRegionReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "stationaryRegionReceiver"); String key = LocationManager.KEY_PROXIMITY_ENTERING; Boolean entering = intent.getBooleanExtra(key, false); if (entering) { Log.d(TAG, "- ENTER"); if (isMoving) { setPace(false); } } else { Log.d(TAG, "- EXIT"); // There MUST be a valid, recent location if this event-handler was called. Location location = getLastBestLocation(); if (location != null) { onExitStationaryRegion(location); } } } }; /** * Listen to Notification confirmation action */ private BroadcastReceiver notificatinConfirmReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "- CONFIRMED CARD ACTION"); if (intent.hasExtra(NOTIFICATION_ARG_CARD_ID)){ Log.i(TAG, "- YES CARD EXTRA"); }else{ Log.i(TAG, "- NO CARD EXTRA"); } int notificationId = intent.getIntExtra(NOTIFICATION_ARG_ID, -1); int notificationCardId = intent.getIntExtra(NOTIFICATION_ARG_CARD_ID, -1); //boolean confirmed_card = true; Log.i(TAG, "- NOTIFICATION CARD ID: " + intent.getIntExtra(NOTIFICATION_ARG_CARD_ID, -1)); if (notificationCardId > 0){ /*ShareTask task = new LocationUpdateService.ShareTask(); Log.d(TAG, "beforeexecute N Share" + task.getStatus()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notificationCardId); else task.execute(notificationCardId); Log.d(TAG, "afterexecute N Share" + task.getStatus()); */ //new ShareTask().execute(notificationCardId); /* CardDAO cdao = DAOFactory.createCardDAO(context); com.tenforwardconsulting.cordova.bgloc.data.Card confirmCard = cdao.getCardById("pending_confirm", notificationCardId); if (confirmCard != null){ Log.i(TAG, "Confirm Sharing"); if (shareCard(confirmCard)){ if (cdao.persistCard("shared_cards", confirmCard)) { Log.d(TAG, "Persisted Card in shared_cards: " + confirmCard); } else { Log.w(TAG, "CARD SHARED! but failed to persist card in shared_cards table"); } } else{ if (cdao.persistCard("pending_internet", confirmCard)) { Log.d(TAG, "Persisted Card in pending_internet: " + confirmCard); } else { Log.w(TAG, "Failed to persist card in pending_internet table"); confirmed_card = false; } } if (confirmed_card){ cdao.deleteCard("pending_confirm", confirmCard); NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); if (notificationId >= 0){ mNotificationManager.cancel(notificationId); } } } */ } } }; /** * Listen to Notification discarding action */ private BroadcastReceiver notificatinDiscardReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int notificationId = intent.getIntExtra(NOTIFICATION_ARG_ID, -1); NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); if (notificationId>=0){ mNotificationManager.cancel(notificationId); } } }; /** * TODO Experimental, hoping to implement some sort of "significant changes" system here like ios based upon cell-tower changes. */ private PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCellLocationChanged(CellLocation location) { onCellLocationChange(location); } }; public void onProviderDisabled(String provider) { // TODO Auto-generated method stub Log.d(TAG, "- onProviderDisabled: " + provider); } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub Log.d(TAG, "- onProviderEnabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub Log.d(TAG, "- onStatusChanged: " + provider + ", status: " + status); } private void schedulePostLocations() { PostLocationTask task = new LocationUpdateService.PostLocationTask(); Log.d(TAG, "beforeexecute " + task.getStatus()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); Log.d(TAG, "afterexecute " + task.getStatus()); } private boolean postCard(com.tenforwardconsulting.cordova.bgloc.data.Card geoCard) { if (geoCard == null) { Log.w(TAG, "postCard: invalid geo card"); return false; }else{ try { Log.i(TAG, "Posting native card: " + geoCard); //Get user settings for creating and sharing a card SharedPreferences pref = mContext.getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); //SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext); String location_setting = pref.getString("location_setting", ""); String sharing_setting = pref.getString("sharing_setting", ""); String user_id = pref.getString("user_id", ""); String curAdd = getAddress(Double.parseDouble(geoCard.getLatitude()), Double.parseDouble(geoCard.getLongitude()), geoCard.getLocation_level()); if (curAdd == null){ if (isNetworkConnected()){ postNotification("Error", "Please reset your device and start the application again", -1); } return false; } String curInfo = getInfo(); //Control to avoid creating redundant cards SharedPreferences.Editor edit = pref.edit(); String lastAdd = pref.getString("lastAddress", ""); String lastInfo = pref.getString("lastInfo", ""); /*if (curAdd.equals(lastAdd) && curInfo.equals(lastInfo)){ Log.i(TAG, "repeated card"); //postNotification(curInfo, curAdd + " (Not shared)", -1); return true; }else{*/ Log.i(TAG, "new card"); edit.putString("lastAddress", curAdd); edit.putString("lastInfo", curInfo); edit.commit(); geoCard.setInfo(curInfo); geoCard.setLocation(curAdd); //} CardDAO cdao = DAOFactory.createCardDAO(this.getApplicationContext()); //Create a notification if necessary if (sharing_setting.equals("confirm")){ if (cdao.persistCard("pending_confirm", geoCard)) { Log.i(TAG, "Confirm Sharing"); //SEND NOTIFICATION postNotification(curInfo, curAdd, geoCard.getId()); Log.d(TAG, "Persisted Card in pending_confirm: " + geoCard); return true; } else { Log.w(TAG, "Failed to persist card in pending_confirm table"); return false; } }else{ Log.i(TAG, "Automatic Sharing"); if (shareCard(geoCard)){ if (cdao.persistCard("shared_cards", geoCard)) { Log.d(TAG, "Persisted Card in shared_cards: " + geoCard); } else { Log.w(TAG, "CARD SHARED! but failed to persist card in shared_cards table"); } return true; } else{ if (cdao.persistCard("pending_internet", geoCard)) { Log.d(TAG, "Persisted Card in pending_internet: " + geoCard); return true; } else { Log.w(TAG, "Failed to persist card in pending_internet table"); return false; } } } } catch (Throwable e) { Log.w(TAG, "Exception updating geo card: " + e); e.printStackTrace(); return false; } } } private boolean shareCard(com.tenforwardconsulting.cordova.bgloc.data.Card geoCard){ try { Log.i(TAG, "SS 11"); //params.remove("LocationSetting"); //Log.i(TAG, "SS 22"); //params.remove("SharingSetting"); //params.remove("UserId"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); Log.i(TAG, "SS 33"); //Proces for creating the card on the server params_share = new JSONObject(); params_share.put("info", geoCard.getInfo()); params_share.put("lat", geoCard.getLatitude()); params_share.put("lon", geoCard.getLongitude()); params_share.put("location", geoCard.getLocation()); params_share.put("timestamp", geoCard.getCreated()); Log.i(TAG, "info: " + geoCard.getInfo() + " - location: " + geoCard.getLocation()); /* params.put("info", geoCard.getInfo()); params.put("lat", geoCard.getLatitude()); params.put("lon", geoCard.getLongitude()); params.put("location", geoCard.getLocation()); params.put("timestamp", geoCard.getCreated()); */ Log.i(TAG, "SS 44"); StringEntity se = new StringEntity(params_share.toString()); //StringEntity se = new StringEntity(params.toString()); request.setEntity(se); request.setHeader("Content-type", "application/json"); Iterator<String> headkeys = headers.keys(); while( headkeys.hasNext() ){ String headkey = headkeys.next(); if(headkey != null) { Log.d(TAG, "Adding Header: " + headkey + " : " + (String)headers.getString(headkey)); request.setHeader(headkey, (String)headers.getString(headkey)); } } Log.i(TAG, "SS 55"); Log.d(TAG, "Posting to " + request.getURI().toString()); HttpResponse response = httpClient.execute(request); Log.i(TAG, "Response received: " + response.getStatusLine()); if ((response.getStatusLine().getStatusCode() == 200) || (response.getStatusLine().getStatusCode() == 204)) { return true; } else { return false; } } catch (Throwable e) { Log.w(TAG, "Exception sharing card: " + e); e.printStackTrace(); return false; } } private void postNotification(String info, String loc, int cardId){ //Intent notificationServiceIntent; //notificationServiceIntent = new Intent(this, LifeshareNotificationService.class); //PendingIntent pintent = PendingIntent.getService(mContext, 0, notificationServiceIntent, 0); //Intent snoozeIntent = new Intent("confirm"); //PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0); Notification.Builder shareLocBuilder = new Notification.Builder(this); shareLocBuilder.setContentTitle("Lifeshare Card"); shareLocBuilder.setContentText(info + " " + loc); shareLocBuilder.setSmallIcon(android.R.drawable.ic_menu_mylocation); int notifiId = getNotificationId(); //Construct the Confirm Action button for the notification //We need to create a specific intent or else the putExtra data will be overwritten be the new notification Intent notificationConfirmIntent = new Intent(NOTIFICATION_CONFIRM_ACTION+notifiId); //We need to notify the broadcast listener to listen for the new created intent registerReceiver(notificatinConfirmReceiver, new IntentFilter(NOTIFICATION_CONFIRM_ACTION+notifiId)); //For the discard action we only need the notification id notificationConfirmIntent.putExtra(NOTIFICATION_ARG_ID, notifiId); notificationConfirmIntent.putExtra(NOTIFICATION_ARG_CARD_ID, cardId); //We create the Pending intent using the created intent. FLAG_UPDATE_CURRENT is needed or else the putExtra does not "put" the data PendingIntent piConfirm = PendingIntent.getBroadcast(this, 0, notificationConfirmIntent, PendingIntent.FLAG_UPDATE_CURRENT); //We add the created intent to the notification shareLocBuilder.addAction(android.R.drawable.ic_menu_agenda, "Confirm", piConfirm); //Construct the Discard Action button for the notification //We need to create a specific intent or else the putExtra data will be overwritten be the new notification Intent notificationDiscardIntent = new Intent(NOTIFICATION_DISCARD_ACTION+notifiId); //We need to notify the broadcast listener to listen for the new created intent registerReceiver(notificatinDiscardReceiver, new IntentFilter(NOTIFICATION_DISCARD_ACTION+notifiId)); //For the discard action we only need the notification id notificationDiscardIntent.putExtra(NOTIFICATION_ARG_ID, notifiId); //We create the Pending intent using the created intent. FLAG_UPDATE_CURRENT is needed or else the putExtra does not "put" the data PendingIntent piDiscard = PendingIntent.getBroadcast(this, 0, notificationDiscardIntent, PendingIntent.FLAG_UPDATE_CURRENT); //We add the created intent to the notification shareLocBuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Discard", piDiscard); Notification shareNotification; if (android.os.Build.VERSION.SDK_INT >= 16) { shareNotification = buildForegroundNotification(shareLocBuilder); } else { shareNotification = buildForegroundNotificationCompat(shareLocBuilder); } //shareNotification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR; //shareNotification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE; shareNotification.flags |= Notification.FLAG_ONGOING_EVENT; NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Including the notification ID allows you to update the notification later on. mNotificationManager.notify(notifiId, shareNotification); } private int getNotificationId() { SharedPreferences pref = mContext.getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); int currentNotId = pref.getInt("notificationId", 1); SharedPreferences.Editor edit = pref.edit(); edit.putInt("notificationId", currentNotId+1); edit.commit(); return currentNotId; } private String getInfo(){ Date currentdate = new Date(); DateFormat df = new SimpleDateFormat("HH"); String curInfo = "is at"; if (Integer.parseInt(df.format(currentdate)) <= 6){ curInfo = "is sleeping"; } else if (Integer.parseInt(df.format(currentdate)) >= 12 && Integer.parseInt(df.format(currentdate)) <=14){ curInfo = "is having lunch"; } return curInfo; } private String getAddress(double lat, double lng, String location_setting) { Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); String revCity = null; String revRegion = null; String revCountry = null; String add = "unavailable"; try { List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); if (addresses != null) if (!addresses.isEmpty()) { Address obj = addresses.get(0); if (obj.getLocality() != null) revCity = obj.getLocality(); if (obj.getAdminArea() != null) revRegion = obj.getAdminArea(); if (obj.getCountryName() != null) revCountry = obj.getCountryName(); add = prepareLocation(revCity, revRegion, revCountry, location_setting); } } catch (IOException e) { e.printStackTrace(); message = "Error during reverse geocoding. " + e.getMessage(); add = null; } return add; } private String prepareLocation(String curCity, String curRegion, String curCountry, String userloc_setting){ int loc_level = location_level(userloc_setting); String curLocation = "unavailable. City: " + curCity + ". Reg: " + curRegion + ". Coun: " + curCountry + ". Sets: " + loc_level; if ((curCity != null) && (location_level(userloc_setting) <= 0)){ curLocation = curCity; if (curRegion != null){ curLocation = curLocation + ", " + curRegion; } if (curCountry != null){ curLocation = curLocation + ", " + curCountry; } }else if ((curRegion != null) && (location_level(userloc_setting) <= 1)){ curLocation = curRegion; if (curCountry != null){ curLocation = curLocation + ", " + curCountry; } }else if ((curCountry != null) && (location_level(userloc_setting) <= 2)){ curLocation = curCountry; } return curLocation; }; private int location_level(String loc_level){ int ret_level = 3; if (loc_level.equals("city")) ret_level = 0; if (loc_level.equals("region")) ret_level = 1; if (loc_level.equals("country")) ret_level = 2; return ret_level; } private void persistLocation(Location location) { //LocationDAO dao = DAOFactory.createLocationDAO(this.getApplicationContext()); CardDAO cdao = DAOFactory.createCardDAO(this.getApplicationContext()); //com.tenforwardconsulting.cordova.bgloc.data.Location savedLocation = com.tenforwardconsulting.cordova.bgloc.data.Location.fromAndroidLocation(location); //Store settings variables passed during the initial configuration of the service //SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); SharedPreferences pref = this.getApplicationContext().getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); SharedPreferences.Editor edit = pref.edit(); String user_id = ""; String location_setting = ""; String sharing_setting = ""; try{ user_id = params.getString("UserId"); location_setting = params.getString("LocationSetting"); sharing_setting = params.getString("SharingSetting"); edit.putString("user_id", user_id); edit.putString("location_setting", location_setting); edit.putString("sharing_setting", sharing_setting); edit.commit(); } catch (Throwable e) { Log.w(TAG, "Exception obtaining user Id: " + e); e.printStackTrace(); } //Create the partial card for this location int cardId = cdao.getCardId(); com.tenforwardconsulting.cordova.bgloc.data.Card savedCard = com.tenforwardconsulting.cordova.bgloc.data.Card.createCard(location, mContext, user_id, cardId); /*if (dao.persistLocation(savedLocation)) { Log.d(TAG, "Persisted Location: " + savedLocation); } else { Log.w(TAG, "Failed to persist location"); }*/ if (cdao.persistCard("pending_geo", savedCard)) { Log.d(TAG, "Persisted Card in pending_geo: " + savedCard); } else { Log.w(TAG, "Failed to persist card in pending_geo table"); } } private boolean isNetworkConnected() { NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { Log.d(TAG, "Network found, type = " + networkInfo.getTypeName()); return networkInfo.isConnected(); } else { Log.d(TAG, "No active network info"); return false; } } @Override public void onDestroy() { Log.w(TAG, "------------------------------------------ Destroyed Location update Service"); cleanUp(); super.onDestroy(); } private void cleanUp() { locationManager.removeUpdates(this); alarmManager.cancel(stationaryAlarmPI); alarmManager.cancel(stationaryLocationPollingPI); toneGenerator.release(); CardDAO cdao = DAOFactory.createCardDAO(this.getApplicationContext()); cdao.closeDB(); unregisterReceiver(stationaryAlarmReceiver); unregisterReceiver(singleUpdateReceiver); unregisterReceiver(stationaryRegionReceiver); unregisterReceiver(stationaryLocationMonitorReceiver); unregisterReceiver(notificatinConfirmReceiver); unregisterReceiver(notificatinDiscardReceiver); if (stationaryLocation != null && !isMoving) { try { locationManager.removeProximityAlert(stationaryRegionPI); } catch (Throwable e) { Log.w(TAG, "- Something bad happened while removing proximity-alert"); } } stopForeground(true); wakeLock.release(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onTaskRemoved(Intent rootIntent) { this.stopSelf(); super.onTaskRemoved(rootIntent); } private class PostLocationTask extends AsyncTask<Object, Integer, Boolean> { @Override protected Boolean doInBackground(Object...objects) { Log.d(TAG, "Executing PostLocationTask#doInBackground"); Log.i(TAG, "1111 Post saved card"); CardDAO cardDAO = DAOFactory.createCardDAO(LocationUpdateService.this.getApplicationContext()); for (com.tenforwardconsulting.cordova.bgloc.data.Card savedGeoCard : cardDAO.geoPendingCards()) { Log.d(TAG, "Posting saved card"); if (postCard(savedGeoCard)) { cardDAO.deleteCard("pending_geo", savedGeoCard); } } Log.i(TAG, "9999 Post saved card"); return true; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "PostLocationTask#onPostExecture"); } } private class ShareCardTask extends AsyncTask<Integer, Integer, Boolean> { @Override protected Boolean doInBackground(Integer...ids) { Log.d(TAG, "Executing PostLocationTask#doInBackground"); Log.i(TAG, "1111 Post shared card"); int notificationId = ids[0]; int notificationCardId = ids[1]; Boolean confirmed_card = true; Log.i(TAG, "9999 Post shared card"); return true; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "PostLocationTask#onPostExecture"); } } /*private class ShareTask extends AsyncTask<Integer, Void, Boolean> { @Override protected Boolean doInBackground(int...confirmCardId) { boolean confirmed_card = true; //CardDAO cdao = DAOFactory.createCardDAO(context); CardDAO cdao = DAOFactory.createCardDAO(LocationUpdateService.this.getApplicationContext()); com.tenforwardconsulting.cordova.bgloc.data.Card confirmCard = cdao.getCardById("pending_confirm", confirmCardId); if (confirmCard != null){ Log.i(TAG, "Confirm Sharing"); if (shareCard(confirmCard)){ if (cdao.persistCard("shared_cards", confirmCard)) { Log.d(TAG, "Persisted Card in shared_cards: " + confirmCard); } else { Log.w(TAG, "CARD SHARED! but failed to persist card in shared_cards table"); } } else{ if (cdao.persistCard("pending_internet", confirmCard)) { Log.d(TAG, "Persisted Card in pending_internet: " + confirmCard); } else { Log.w(TAG, "Failed to persist card in pending_internet table"); confirmed_card = false; } } if (confirmed_card){ cdao.deleteCard("pending_confirm", confirmCard); //NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); //if (notificationId >= 0){ // mNotificationManager.cancel(notificationId); //} } } return confirmed_card; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "PostCardTask#onPostExecture"); } }*/ }
src/android/LocationUpdateService.java
package com.tenforwardconsulting.cordova.bgloc; import java.io.IOException; import java.util.List; import java.util.Iterator; import java.util.Locale; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import com.tenforwardconsulting.cordova.bgloc.data.DAOFactory; import com.tenforwardconsulting.cordova.bgloc.data.LocationDAO; import com.tenforwardconsulting.cordova.bgloc.data.CardDAO; import android.annotation.TargetApi; import android.media.AudioManager; import android.media.ToneGenerator; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import static android.telephony.PhoneStateListener.*; import android.telephony.CellLocation; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.location.Location; import android.location.Criteria; import android.location.Address; import android.location.Geocoder; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; import static java.lang.Math.*; public class LocationUpdateService extends Service implements LocationListener { private static final String TAG = "LocationUpdateService"; private static final String STATIONARY_REGION_ACTION = "com.tenforwardconsulting.cordova.bgloc.STATIONARY_REGION_ACTION"; private static final String STATIONARY_ALARM_ACTION = "com.tenforwardconsulting.cordova.bgloc.STATIONARY_ALARM_ACTION"; private static final String SINGLE_LOCATION_UPDATE_ACTION = "com.tenforwardconsulting.cordova.bgloc.SINGLE_LOCATION_UPDATE_ACTION"; private static final String STATIONARY_LOCATION_MONITOR_ACTION = "com.tenforwardconsulting.cordova.bgloc.STATIONARY_LOCATION_MONITOR_ACTION"; private static final String NOTIFICATION_CONFIRM_ACTION = "com.tenforwardconsulting.cordova.bgloc.NOTIFICATION_CONFIRM_ACTION"; private static final String NOTIFICATION_DISCARD_ACTION = "com.tenforwardconsulting.cordova.bgloc.NOTIFICATION_DISCARD_ACTION"; private static final String NOTIFICATION_ARG_ID = "NOTIF_ID"; private static final String NOTIFICATION_ARG_CARD_ID = "CARD_ID"; private static final long STATIONARY_TIMEOUT = 5 * 1000 * 60; // 5 minutes. private static final long STATIONARY_LOCATION_POLLING_INTERVAL_LAZY = 3 * 1000 * 60; // 3 minutes. private static final long STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE = 1 * 1000 * 60; // 1 minute. private static final Integer MAX_STATIONARY_ACQUISITION_ATTEMPTS = 5; private static final Integer MAX_SPEED_ACQUISITION_ATTEMPTS = 3; private static Context mContext; private static String message; private PowerManager.WakeLock wakeLock; private Location lastLocation; private long lastUpdateTime = 0l; private JSONObject params; private JSONObject params_share; private JSONObject headers; private String url = "http://192.168.2.15:3000/users/current_location.json"; private float stationaryRadius; private Location stationaryLocation; private PendingIntent stationaryAlarmPI; private PendingIntent stationaryLocationPollingPI; private long stationaryLocationPollingInterval; private PendingIntent stationaryRegionPI; private PendingIntent singleUpdatePI; private PendingIntent notificationConfirmPI; //private PendingIntent notificationDiscardPI; private Boolean isMoving = false; private Boolean isAcquiringStationaryLocation = false; private Boolean isAcquiringSpeed = false; private Integer locationAcquisitionAttempts = 0; private Integer desiredAccuracy = 100; private Integer distanceFilter = 30; private Integer scaledDistanceFilter; private Integer locationTimeout = 30; private Boolean isDebugging; private String notificationTitle = "Background checking"; private String notificationText = "ENABLED"; private ToneGenerator toneGenerator; private Criteria criteria; private LocationManager locationManager; private AlarmManager alarmManager; private ConnectivityManager connectivityManager; private NotificationManager notificationManager; public static TelephonyManager telephonyManager = null; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.i(TAG, "OnBind" + intent); return null; } @Override public void onCreate() { super.onCreate(); mContext = this; Log.i(TAG, "OnCreate"); locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // Stop-detection PI stationaryAlarmPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_ALARM_ACTION), 0); registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION)); // Stationary region PI stationaryRegionPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_REGION_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION)); // Stationary location monitor PI stationaryLocationPollingPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0); registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION)); // One-shot PI (TODO currently unused) singleUpdatePI = PendingIntent.getBroadcast(this, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION)); // Notification Confirm Monitor PI notificationConfirmPI = PendingIntent.getBroadcast(this, 0, new Intent(NOTIFICATION_CONFIRM_ACTION), 0); registerReceiver(notificatinConfirmReceiver, new IntentFilter(NOTIFICATION_CONFIRM_ACTION)); // Notification Discard Monitor PI //notificationDiscardPI = PendingIntent.getBroadcast(this, 0, new Intent(NOTIFICATION_DISCARD_ACTION), 0); //registerReceiver(notificatinDiscardReceiver, new IntentFilter(NOTIFICATION_DISCARD_ACTION)); //// // DISABLED // Listen to Cell-tower switches (NOTE does not operate while suspended) //telephonyManager.listen(phoneStateListener, LISTEN_CELL_LOCATION); // PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(); // Location criteria criteria = new Criteria(); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setSpeedRequired(true); criteria.setCostAllowed(true); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "Received start id " + startId + ": " + intent); if (intent != null) { try { params = new JSONObject(intent.getStringExtra("params")); headers = new JSONObject(intent.getStringExtra("headers")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } url = intent.getStringExtra("url"); stationaryRadius = Float.parseFloat(intent.getStringExtra("stationaryRadius")); distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter")); scaledDistanceFilter = distanceFilter; desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy")); locationTimeout = Integer.parseInt(intent.getStringExtra("locationTimeout")); isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging")); notificationTitle = intent.getStringExtra("notificationTitle"); notificationText = intent.getStringExtra("notificationText"); // Build a Notification required for running service in foreground. Intent main = new Intent(this, BackgroundGpsPlugin.class); main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle(notificationTitle); builder.setContentText(notificationText); builder.setSmallIcon(android.R.drawable.ic_menu_mylocation); builder.setContentIntent(pendingIntent); Notification notification; if (android.os.Build.VERSION.SDK_INT >= 16) { notification = buildForegroundNotification(builder); } else { notification = buildForegroundNotificationCompat(builder); } notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR; startForeground(startId, notification); } Log.i(TAG, "- url: " + url); Log.i(TAG, "- params: " + params.toString()); Log.i(TAG, "- headers: " + headers.toString()); Log.i(TAG, "- stationaryRadius: " + stationaryRadius); Log.i(TAG, "- distanceFilter: " + distanceFilter); Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy); Log.i(TAG, "- locationTimeout: " + locationTimeout); Log.i(TAG, "- isDebugging: " + isDebugging); Log.i(TAG, "- notificationTitle: " + notificationTitle); Log.i(TAG, "- notificationText: " + notificationText); this.setPace(false); //We want this service to continue running until it is explicitly stopped return START_REDELIVER_INTENT; } @TargetApi(16) private Notification buildForegroundNotification(Notification.Builder builder) { return builder.build(); } @SuppressWarnings("deprecation") @TargetApi(15) private Notification buildForegroundNotificationCompat(Notification.Builder builder) { return builder.getNotification(); } @Override public boolean stopService(Intent intent) { Log.i(TAG, "- Received stop: " + intent); cleanUp(); if (isDebugging) { Toast.makeText(this, "Background location tracking stopped", Toast.LENGTH_SHORT).show(); } return super.stopService(intent); } /** * * @param value set true to engage "aggressive", battery-consuming tracking, false for stationary-region tracking */ private void setPace(Boolean value) { Log.i(TAG, "setPace: " + value); Boolean wasMoving = isMoving; isMoving = value; isAcquiringStationaryLocation = false; isAcquiringSpeed = false; stationaryLocation = null; locationManager.removeUpdates(this); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(translateDesiredAccuracy(desiredAccuracy)); criteria.setPowerRequirement(Criteria.POWER_HIGH); if (isMoving) { // setPace can be called while moving, after distanceFilter has been recalculated. We don't want to re-acquire velocity in this case. if (!wasMoving) { isAcquiringSpeed = true; } } else { isAcquiringStationaryLocation = true; } // Temporarily turn on super-aggressive geolocation on all providers when acquiring velocity or stationary location. if (isAcquiringSpeed || isAcquiringStationaryLocation) { locationAcquisitionAttempts = 0; // Turn on each provider aggressively for a short period of time List<String> matchingProviders = locationManager.getAllProviders(); for (String provider: matchingProviders) { if (provider != LocationManager.PASSIVE_PROVIDER) { locationManager.requestLocationUpdates(provider, 0, 0, this); } } } else { locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), locationTimeout*1000, scaledDistanceFilter, this); } } /** * Translates a number representing desired accuracy of GeoLocation system from set [0, 10, 100, 1000]. * 0: most aggressive, most accurate, worst battery drain * 1000: least aggressive, least accurate, best for battery. */ private Integer translateDesiredAccuracy(Integer accuracy) { switch (accuracy) { case 1000: accuracy = Criteria.ACCURACY_LOW; break; case 100: accuracy = Criteria.ACCURACY_MEDIUM; break; case 10: accuracy = Criteria.ACCURACY_HIGH; break; case 0: accuracy = Criteria.ACCURACY_HIGH; break; default: accuracy = Criteria.ACCURACY_MEDIUM; } return accuracy; } /** * Returns the most accurate and timely previously detected location. * Where the last result is beyond the specified maximum distance or * latency a one-off location update is returned via the {@link LocationListener} * specified in {@link setChangedLocationListener}. * @param minDistance Minimum distance before we require a location update. * @param minTime Minimum time required between location updates. * @return The most accurate and / or timely previously detected location. */ public Location getLastBestLocation() { int minDistance = (int) stationaryRadius; long minTime = System.currentTimeMillis() - (locationTimeout * 1000); Log.i(TAG, "- fetching last best location " + minDistance + "," + minTime); Location bestResult = null; float bestAccuracy = Float.MAX_VALUE; long bestTime = Long.MIN_VALUE; // Iterate through all the providers on the system, keeping // note of the most accurate result within the acceptable time limit. // If no result is found within maxTime, return the newest Location. List<String> matchingProviders = locationManager.getAllProviders(); for (String provider: matchingProviders) { Log.d(TAG, "- provider: " + provider); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { Log.d(TAG, " location: " + location.getLatitude() + "," + location.getLongitude() + "," + location.getAccuracy() + "," + location.getSpeed() + "m/s"); float accuracy = location.getAccuracy(); long time = location.getTime(); Log.d(TAG, "time>minTime: " + (time > minTime) + ", accuracy<bestAccuracy: " + (accuracy < bestAccuracy)); if ((time > minTime && accuracy < bestAccuracy)) { bestResult = location; bestAccuracy = accuracy; bestTime = time; } } } return bestResult; } public void onLocationChanged(Location location) { Log.d(TAG, "- onLocationChanged: " + location.getLatitude() + "," + location.getLongitude() + ", accuracy: " + location.getAccuracy() + ", isMoving: " + isMoving + ", speed: " + location.getSpeed()); if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation==null) { // Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now. setPace(false); } if (isDebugging) { Toast.makeText(this, "mv:"+isMoving+",acy:"+location.getAccuracy()+",v:"+location.getSpeed()+",df:"+scaledDistanceFilter, Toast.LENGTH_LONG).show(); } if (isAcquiringStationaryLocation) { if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) { stationaryLocation = location; } if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) { isAcquiringStationaryLocation = false; startMonitoringStationaryRegion(stationaryLocation); if (isDebugging) { startTone("long_beep"); } } else { // Unacceptable stationary-location: bail-out and wait for another. if (isDebugging) { startTone("beep"); } return; } } else if (isAcquiringSpeed) { if (++locationAcquisitionAttempts == MAX_SPEED_ACQUISITION_ATTEMPTS) { // Got enough samples, assume we're confident in reported speed now. Play "woohoo" sound. if (isDebugging) { startTone("doodly_doo"); } isAcquiringSpeed = false; scaledDistanceFilter = calculateDistanceFilter(location.getSpeed()); setPace(true); } else { if (isDebugging) { startTone("beep"); } return; } } else if (isMoving) { if (isDebugging) { startTone("beep"); } // Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped. if ( (location.getSpeed() >= 1) && (location.getAccuracy() <= stationaryRadius) ) { resetStationaryAlarm(); } // Calculate latest distanceFilter, if it changed by 5 m/s, we'll reconfigure our pace. Integer newDistanceFilter = calculateDistanceFilter(location.getSpeed()); if (newDistanceFilter != scaledDistanceFilter.intValue()) { Log.i(TAG, "- updated distanceFilter, new: " + newDistanceFilter + ", old: " + scaledDistanceFilter); scaledDistanceFilter = newDistanceFilter; setPace(true); } if (location.distanceTo(lastLocation) < distanceFilter) { return; } } else if (stationaryLocation != null) { return; } // Go ahead and cache, push to server lastLocation = location; persistLocation(location); if (this.isNetworkConnected()) { Log.d(TAG, "Scheduling location network post"); schedulePostLocations(); } else { Log.d(TAG, "Network unavailable, waiting for now"); } } /** * Plays debug sound * @param name */ private void startTone(String name) { int tone = 0; int duration = 1000; if (name.equals("beep")) { tone = ToneGenerator.TONE_PROP_BEEP; } else if (name.equals("beep_beep_beep")) { tone = ToneGenerator.TONE_CDMA_CONFIRM; } else if (name.equals("long_beep")) { tone = ToneGenerator.TONE_CDMA_ABBR_ALERT; } else if (name.equals("doodly_doo")) { tone = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE; } else if (name.equals("chirp_chirp_chirp")) { tone = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD; } else if (name.equals("dialtone")) { tone = ToneGenerator.TONE_SUP_RINGTONE; } toneGenerator.startTone(tone, duration); } public void resetStationaryAlarm() { alarmManager.cancel(stationaryAlarmPI); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + STATIONARY_TIMEOUT, stationaryAlarmPI); // Millisec * Second * Minute } private Integer calculateDistanceFilter(Float speed) { Double newDistanceFilter = (double) distanceFilter; if (speed < 100) { float roundedDistanceFilter = (round(speed / 5) * 5); newDistanceFilter = pow(roundedDistanceFilter, 2) + (double) distanceFilter; } return (newDistanceFilter.intValue() < 1000) ? newDistanceFilter.intValue() : 1000; } private void startMonitoringStationaryRegion(Location location) { locationManager.removeUpdates(this); stationaryLocation = location; Log.i(TAG, "- startMonitoringStationaryRegion (" + location.getLatitude() + "," + location.getLongitude() + "), accuracy:" + location.getAccuracy()); // Here be the execution of the stationary region monitor locationManager.addProximityAlert( location.getLatitude(), location.getLongitude(), (location.getAccuracy() < stationaryRadius) ? stationaryRadius : location.getAccuracy(), (long)-1, stationaryRegionPI ); startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY); } public void startPollingStationaryLocation(long interval) { // proximity-alerts don't seem to work while suspended in latest Android 4.42 (works in 4.03). Have to use AlarmManager to sample // location at regular intervals with a one-shot. stationaryLocationPollingInterval = interval; alarmManager.cancel(stationaryLocationPollingPI); long start = System.currentTimeMillis() + (60 * 1000); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, start, interval, stationaryLocationPollingPI); } public void onPollStationaryLocation(Location location) { if (isMoving) { return; } if (isDebugging) { startTone("beep"); } float distance = abs(location.distanceTo(stationaryLocation) - stationaryLocation.getAccuracy() - location.getAccuracy()); if (isDebugging) { Toast.makeText(this, "Stationary exit in " + (stationaryRadius-distance) + "m", Toast.LENGTH_LONG).show(); } // TODO http://www.cse.buffalo.edu/~demirbas/publications/proximity.pdf // determine if we're almost out of stationary-distance and increase monitoring-rate. Log.i(TAG, "- distance from stationary location: " + distance); if (distance > stationaryRadius) { onExitStationaryRegion(location); } else if (distance > 0) { startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE); } else if (stationaryLocationPollingInterval != STATIONARY_LOCATION_POLLING_INTERVAL_LAZY) { startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY); } } /** * User has exit his stationary region! Initiate aggressive geolocation! */ public void onExitStationaryRegion(Location location) { // Filter-out spurious region-exits: must have at least a little speed to move out of stationary-region if (isDebugging) { startTone("beep_beep_beep"); } // Cancel the periodic stationary location monitor alarm. alarmManager.cancel(stationaryLocationPollingPI); // Kill the current region-monitor we just walked out of. locationManager.removeProximityAlert(stationaryRegionPI); // Engage aggressive tracking. this.setPace(true); } /** * TODO Experimental cell-tower change system; something like ios significant changes. */ public void onCellLocationChange(CellLocation cellLocation) { Log.i(TAG, "- onCellLocationChange" + cellLocation.toString()); if (isDebugging) { Toast.makeText(this, "Cellular location change", Toast.LENGTH_LONG).show(); startTone("chirp_chirp_chirp"); } if (!isMoving && stationaryLocation != null) { criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); criteria.setPowerRequirement(Criteria.POWER_HIGH); locationManager.requestSingleUpdate(criteria, singleUpdatePI); } } /** * Broadcast receiver for receiving a single-update from LocationManager. */ private BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String key = LocationManager.KEY_LOCATION_CHANGED; Location location = (Location)intent.getExtras().get(key); if (location != null) { Log.d(TAG, "- singleUpdateReciever" + location.toString()); onPollStationaryLocation(location); } } }; /** * Broadcast receiver which detcts a user has stopped for a long enough time to be determined as STOPPED */ private BroadcastReceiver stationaryAlarmReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "- stationaryAlarm fired"); setPace(false); } }; /** * Broadcast receiver to handle stationaryMonitor alarm, fired at low frequency while monitoring stationary-region. * This is required because latest Android proximity-alerts don't seem to operate while suspended. Regularly polling * the location seems to trigger the proximity-alerts while suspended. */ private BroadcastReceiver stationaryLocationMonitorReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "- stationaryLocationMonitorReceiver fired"); if (isDebugging) { startTone("dialtone"); } criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); criteria.setPowerRequirement(Criteria.POWER_HIGH); locationManager.requestSingleUpdate(criteria, singleUpdatePI); } }; /** * Broadcast receiver which detects a user has exit his circular stationary-region determined by the greater of stationaryLocation.getAccuracy() OR stationaryRadius */ private BroadcastReceiver stationaryRegionReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "stationaryRegionReceiver"); String key = LocationManager.KEY_PROXIMITY_ENTERING; Boolean entering = intent.getBooleanExtra(key, false); if (entering) { Log.d(TAG, "- ENTER"); if (isMoving) { setPace(false); } } else { Log.d(TAG, "- EXIT"); // There MUST be a valid, recent location if this event-handler was called. Location location = getLastBestLocation(); if (location != null) { onExitStationaryRegion(location); } } } }; /** * Listen to Notification confirmation action */ private BroadcastReceiver notificatinConfirmReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "- CONFIRMED CARD ACTION"); if (intent.hasExtra(NOTIFICATION_ARG_CARD_ID)){ Log.i(TAG, "- YES CARD EXTRA"); }else{ Log.i(TAG, "- NO CARD EXTRA"); } int notificationId = intent.getIntExtra(NOTIFICATION_ARG_ID, -1); int notificationCardId = intent.getIntExtra(NOTIFICATION_ARG_CARD_ID, -1); //boolean confirmed_card = true; Log.i(TAG, "- NOTIFICATION CARD ID: " + intent.getIntExtra(NOTIFICATION_ARG_CARD_ID, -1)); if (notificationCardId > 0){ /*ShareTask task = new LocationUpdateService.ShareTask(); Log.d(TAG, "beforeexecute N Share" + task.getStatus()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notificationCardId); else task.execute(notificationCardId); Log.d(TAG, "afterexecute N Share" + task.getStatus()); */ //new ShareTask().execute(notificationCardId); /* CardDAO cdao = DAOFactory.createCardDAO(context); com.tenforwardconsulting.cordova.bgloc.data.Card confirmCard = cdao.getCardById("pending_confirm", notificationCardId); if (confirmCard != null){ Log.i(TAG, "Confirm Sharing"); if (shareCard(confirmCard)){ if (cdao.persistCard("shared_cards", confirmCard)) { Log.d(TAG, "Persisted Card in shared_cards: " + confirmCard); } else { Log.w(TAG, "CARD SHARED! but failed to persist card in shared_cards table"); } } else{ if (cdao.persistCard("pending_internet", confirmCard)) { Log.d(TAG, "Persisted Card in pending_internet: " + confirmCard); } else { Log.w(TAG, "Failed to persist card in pending_internet table"); confirmed_card = false; } } if (confirmed_card){ cdao.deleteCard("pending_confirm", confirmCard); NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); if (notificationId >= 0){ mNotificationManager.cancel(notificationId); } } } */ } } }; /** * Listen to Notification discarding action */ private BroadcastReceiver notificatinDiscardReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int notificationId = intent.getIntExtra(NOTIFICATION_ARG_ID, -1); NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); if (notificationId>=0){ mNotificationManager.cancel(notificationId); } } }; /** * TODO Experimental, hoping to implement some sort of "significant changes" system here like ios based upon cell-tower changes. */ private PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCellLocationChanged(CellLocation location) { onCellLocationChange(location); } }; public void onProviderDisabled(String provider) { // TODO Auto-generated method stub Log.d(TAG, "- onProviderDisabled: " + provider); } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub Log.d(TAG, "- onProviderEnabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub Log.d(TAG, "- onStatusChanged: " + provider + ", status: " + status); } private void schedulePostLocations() { PostLocationTask task = new LocationUpdateService.PostLocationTask(); Log.d(TAG, "beforeexecute " + task.getStatus()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); Log.d(TAG, "afterexecute " + task.getStatus()); } private boolean postCard(com.tenforwardconsulting.cordova.bgloc.data.Card geoCard) { if (geoCard == null) { Log.w(TAG, "postCard: invalid geo card"); return false; }else{ try { Log.i(TAG, "Posting native card: " + geoCard); //Get user settings for creating and sharing a card SharedPreferences pref = mContext.getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); //SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext); String location_setting = pref.getString("location_setting", ""); String sharing_setting = pref.getString("sharing_setting", ""); String user_id = pref.getString("user_id", ""); String curAdd = getAddress(Double.parseDouble(geoCard.getLatitude()), Double.parseDouble(geoCard.getLongitude()), geoCard.getLocation_level()); if (curAdd == null){ if (isNetworkConnected()){ postNotification("Error", "Please reset your device and start the application again", -1); } return false; } String curInfo = getInfo(); //Control to avoid creating redundant cards SharedPreferences.Editor edit = pref.edit(); String lastAdd = pref.getString("lastAddress", ""); String lastInfo = pref.getString("lastInfo", ""); /*if (curAdd.equals(lastAdd) && curInfo.equals(lastInfo)){ Log.i(TAG, "repeated card"); //postNotification(curInfo, curAdd + " (Not shared)", -1); return true; }else{*/ Log.i(TAG, "new card"); edit.putString("lastAddress", curAdd); edit.putString("lastInfo", curInfo); edit.commit(); geoCard.setInfo(curInfo); geoCard.setLocation(curAdd); //} CardDAO cdao = DAOFactory.createCardDAO(this.getApplicationContext()); //Create a notification if necessary if (sharing_setting.equals("confirm")){ if (cdao.persistCard("pending_confirm", geoCard)) { Log.i(TAG, "Confirm Sharing"); //SEND NOTIFICATION postNotification(curInfo, curAdd, geoCard.getId()); Log.d(TAG, "Persisted Card in pending_confirm: " + geoCard); return true; } else { Log.w(TAG, "Failed to persist card in pending_confirm table"); return false; } }else{ Log.i(TAG, "Automatic Sharing"); if (shareCard(geoCard)){ if (cdao.persistCard("shared_cards", geoCard)) { Log.d(TAG, "Persisted Card in shared_cards: " + geoCard); } else { Log.w(TAG, "CARD SHARED! but failed to persist card in shared_cards table"); } return true; } else{ if (cdao.persistCard("pending_internet", geoCard)) { Log.d(TAG, "Persisted Card in pending_internet: " + geoCard); return true; } else { Log.w(TAG, "Failed to persist card in pending_internet table"); return false; } } } } catch (Throwable e) { Log.w(TAG, "Exception updating geo card: " + e); e.printStackTrace(); return false; } } } private boolean shareCard(com.tenforwardconsulting.cordova.bgloc.data.Card geoCard){ try { Log.i(TAG, "SS 11"); //params.remove("LocationSetting"); //Log.i(TAG, "SS 22"); //params.remove("SharingSetting"); //params.remove("UserId"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); Log.i(TAG, "SS 33"); //Proces for creating the card on the server params_share = new JSONObject(); params_share.put("info", geoCard.getInfo()); params_share.put("lat", geoCard.getLatitude()); params_share.put("lon", geoCard.getLongitude()); params_share.put("location", geoCard.getLocation()); params_share.put("timestamp", geoCard.getCreated()); Log.i(TAG, "info: " + geoCard.getInfo() + " - location: " + geoCard.getLocation()); /* params.put("info", geoCard.getInfo()); params.put("lat", geoCard.getLatitude()); params.put("lon", geoCard.getLongitude()); params.put("location", geoCard.getLocation()); params.put("timestamp", geoCard.getCreated()); */ Log.i(TAG, "SS 44"); StringEntity se = new StringEntity(params_share.toString()); //StringEntity se = new StringEntity(params.toString()); request.setEntity(se); request.setHeader("Content-type", "application/json"); Iterator<String> headkeys = headers.keys(); while( headkeys.hasNext() ){ String headkey = headkeys.next(); if(headkey != null) { Log.d(TAG, "Adding Header: " + headkey + " : " + (String)headers.getString(headkey)); request.setHeader(headkey, (String)headers.getString(headkey)); } } Log.i(TAG, "SS 55"); Log.d(TAG, "Posting to " + request.getURI().toString()); HttpResponse response = httpClient.execute(request); Log.i(TAG, "Response received: " + response.getStatusLine()); if ((response.getStatusLine().getStatusCode() == 200) || (response.getStatusLine().getStatusCode() == 204)) { return true; } else { return false; } } catch (Throwable e) { Log.w(TAG, "Exception sharing card: " + e); e.printStackTrace(); return false; } } private void postNotification(String info, String loc, int cardId){ //Intent notificationServiceIntent; //notificationServiceIntent = new Intent(this, LifeshareNotificationService.class); //PendingIntent pintent = PendingIntent.getService(mContext, 0, notificationServiceIntent, 0); //Intent snoozeIntent = new Intent("confirm"); //PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0); Notification.Builder shareLocBuilder = new Notification.Builder(this); shareLocBuilder.setContentTitle("Lifeshare Card"); shareLocBuilder.setContentText(info + " " + loc); shareLocBuilder.setSmallIcon(android.R.drawable.ic_menu_mylocation); int notifiId = getNotificationId(); //Construct the Confirm Action button for the notification //We need to create a specific intent or else the putExtra data will be overwritten be the new notification Intent notificationConfirmIntent = new Intent(NOTIFICATION_CONFIRM_ACTION+notifiId); //We need to notify the broadcast listener to listen for the new created intent registerReceiver(notificatinConfirmReceiver, new IntentFilter(NOTIFICATION_CONFIRM_ACTION+notifiId)); //For the discard action we only need the notification id notificationConfirmIntent.putExtra(NOTIFICATION_ARG_ID, notifiId); notificationConfirmIntent.putExtra(NOTIFICATION_ARG_CARD_ID, cardId); //We create the Pending intent using the created intent. FLAG_UPDATE_CURRENT is needed or else the putExtra does not "put" the data PendingIntent piConfirm = PendingIntent.getBroadcast(this, 0, notificationConfirmIntent, PendingIntent.FLAG_UPDATE_CURRENT); //We add the created intent to the notification shareLocBuilder.addAction(android.R.drawable.ic_menu_agenda, "Confirm", piConfirm); //Construct the Discard Action button for the notification //We need to create a specific intent or else the putExtra data will be overwritten be the new notification Intent notificationDiscardIntent = new Intent(NOTIFICATION_DISCARD_ACTION+notifiId); //We need to notify the broadcast listener to listen for the new created intent registerReceiver(notificatinDiscardReceiver, new IntentFilter(NOTIFICATION_DISCARD_ACTION+notifiId)); //For the discard action we only need the notification id notificationDiscardIntent.putExtra(NOTIFICATION_ARG_ID, notifiId); //We create the Pending intent using the created intent. FLAG_UPDATE_CURRENT is needed or else the putExtra does not "put" the data PendingIntent piDiscard = PendingIntent.getBroadcast(this, 0, notificationDiscardIntent, PendingIntent.FLAG_UPDATE_CURRENT); //We add the created intent to the notification shareLocBuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Discard", piDiscard); Notification shareNotification; if (android.os.Build.VERSION.SDK_INT >= 16) { shareNotification = buildForegroundNotification(shareLocBuilder); } else { shareNotification = buildForegroundNotificationCompat(shareLocBuilder); } //shareNotification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR; //shareNotification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE; shareNotification.flags |= Notification.FLAG_ONGOING_EVENT; NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Including the notification ID allows you to update the notification later on. mNotificationManager.notify(notifiId, shareNotification); } private int getNotificationId() { SharedPreferences pref = mContext.getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); int currentNotId = pref.getInt("notificationId", 1); SharedPreferences.Editor edit = pref.edit(); edit.putInt("notificationId", currentNotId+1); edit.commit(); return currentNotId; } private String getInfo(){ Date currentdate = new Date(); DateFormat df = new SimpleDateFormat("HH"); String curInfo = "is at"; if (Integer.parseInt(df.format(currentdate)) <= 6){ curInfo = "is sleeping"; } else if (Integer.parseInt(df.format(currentdate)) >= 12 && Integer.parseInt(df.format(currentdate)) <=14){ curInfo = "is having lunch"; } return curInfo; } private String getAddress(double lat, double lng, String location_setting) { Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); String revCity = null; String revRegion = null; String revCountry = null; String add = "unavailable"; try { List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); if (addresses != null) if (!addresses.isEmpty()) { Address obj = addresses.get(0); if (obj.getLocality() != null) revCity = obj.getLocality(); if (obj.getAdminArea() != null) revRegion = obj.getAdminArea(); if (obj.getCountryName() != null) revCountry = obj.getCountryName(); add = prepareLocation(revCity, revRegion, revCountry, location_setting); } } catch (IOException e) { e.printStackTrace(); message = "Error during reverse geocoding. " + e.getMessage(); add = null; } return add; } private String prepareLocation(String curCity, String curRegion, String curCountry, String userloc_setting){ int loc_level = location_level(userloc_setting); String curLocation = "unavailable. City: " + curCity + ". Reg: " + curRegion + ". Coun: " + curCountry + ". Sets: " + loc_level; if ((curCity != null) && (location_level(userloc_setting) <= 0)){ curLocation = curCity; if (curRegion != null){ curLocation = curLocation + ", " + curRegion; } if (curCountry != null){ curLocation = curLocation + ", " + curCountry; } }else if ((curRegion != null) && (location_level(userloc_setting) <= 1)){ curLocation = curRegion; if (curCountry != null){ curLocation = curLocation + ", " + curCountry; } }else if ((curCountry != null) && (location_level(userloc_setting) <= 2)){ curLocation = curCountry; } return curLocation; }; private int location_level(String loc_level){ int ret_level = 3; if (loc_level.equals("city")) ret_level = 0; if (loc_level.equals("region")) ret_level = 1; if (loc_level.equals("country")) ret_level = 2; return ret_level; } private void persistLocation(Location location) { //LocationDAO dao = DAOFactory.createLocationDAO(this.getApplicationContext()); CardDAO cdao = DAOFactory.createCardDAO(this.getApplicationContext()); //com.tenforwardconsulting.cordova.bgloc.data.Location savedLocation = com.tenforwardconsulting.cordova.bgloc.data.Location.fromAndroidLocation(location); //Store settings variables passed during the initial configuration of the service //SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); SharedPreferences pref = this.getApplicationContext().getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); SharedPreferences.Editor edit = pref.edit(); String user_id = ""; String location_setting = ""; String sharing_setting = ""; try{ user_id = params.getString("UserId"); location_setting = params.getString("LocationSetting"); sharing_setting = params.getString("SharingSetting"); edit.putString("user_id", user_id); edit.putString("location_setting", location_setting); edit.putString("sharing_setting", sharing_setting); edit.commit(); } catch (Throwable e) { Log.w(TAG, "Exception obtaining user Id: " + e); e.printStackTrace(); } //Create the partial card for this location int cardId = cdao.getCardId(); com.tenforwardconsulting.cordova.bgloc.data.Card savedCard = com.tenforwardconsulting.cordova.bgloc.data.Card.createCard(location, mContext, user_id, cardId); /*if (dao.persistLocation(savedLocation)) { Log.d(TAG, "Persisted Location: " + savedLocation); } else { Log.w(TAG, "Failed to persist location"); }*/ if (cdao.persistCard("pending_geo", savedCard)) { Log.d(TAG, "Persisted Card in pending_geo: " + savedCard); } else { Log.w(TAG, "Failed to persist card in pending_geo table"); } } private boolean isNetworkConnected() { NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { Log.d(TAG, "Network found, type = " + networkInfo.getTypeName()); return networkInfo.isConnected(); } else { Log.d(TAG, "No active network info"); return false; } } @Override public void onDestroy() { Log.w(TAG, "------------------------------------------ Destroyed Location update Service"); cleanUp(); super.onDestroy(); } private void cleanUp() { locationManager.removeUpdates(this); alarmManager.cancel(stationaryAlarmPI); alarmManager.cancel(stationaryLocationPollingPI); toneGenerator.release(); CardDAO cdao = DAOFactory.createCardDAO(this.getApplicationContext()); cdao.closeDB(); unregisterReceiver(stationaryAlarmReceiver); unregisterReceiver(singleUpdateReceiver); unregisterReceiver(stationaryRegionReceiver); unregisterReceiver(stationaryLocationMonitorReceiver); unregisterReceiver(notificatinConfirmReceiver); unregisterReceiver(notificatinDiscardReceiver); if (stationaryLocation != null && !isMoving) { try { locationManager.removeProximityAlert(stationaryRegionPI); } catch (Throwable e) { Log.w(TAG, "- Something bad happened while removing proximity-alert"); } } stopForeground(true); wakeLock.release(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onTaskRemoved(Intent rootIntent) { this.stopSelf(); super.onTaskRemoved(rootIntent); } private class PostLocationTask extends AsyncTask<Object, Integer, Boolean> { @Override protected Boolean doInBackground(Object...objects) { Log.d(TAG, "Executing PostLocationTask#doInBackground"); Log.i(TAG, "1111 Post saved card"); CardDAO cardDAO = DAOFactory.createCardDAO(LocationUpdateService.this.getApplicationContext()); for (com.tenforwardconsulting.cordova.bgloc.data.Card savedGeoCard : cardDAO.geoPendingCards()) { Log.d(TAG, "Posting saved card"); if (postCard(savedGeoCard)) { cardDAO.deleteCard("pending_geo", savedGeoCard); } } Log.i(TAG, "9999 Post saved card"); return true; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "PostLocationTask#onPostExecture"); } } private class ShareCardTask extends AsyncTask<Object, Integer, Boolean> { @Override protected Boolean doInBackground(Object...objects) { Log.d(TAG, "Executing PostLocationTask#doInBackground"); Log.i(TAG, "1111 Post saved card"); CardDAO cardDAO = DAOFactory.createCardDAO(LocationUpdateService.this.getApplicationContext()); for (com.tenforwardconsulting.cordova.bgloc.data.Card savedGeoCard : cardDAO.geoPendingCards()) { Log.d(TAG, "Posting saved card"); if (postCard(savedGeoCard)) { cardDAO.deleteCard("pending_geo", savedGeoCard); } } Log.i(TAG, "9999 Post saved card"); return true; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "PostLocationTask#onPostExecture"); } } /*private class ShareTask extends AsyncTask<Integer, Void, Boolean> { @Override protected Boolean doInBackground(int...confirmCardId) { boolean confirmed_card = true; //CardDAO cdao = DAOFactory.createCardDAO(context); CardDAO cdao = DAOFactory.createCardDAO(LocationUpdateService.this.getApplicationContext()); com.tenforwardconsulting.cordova.bgloc.data.Card confirmCard = cdao.getCardById("pending_confirm", confirmCardId); if (confirmCard != null){ Log.i(TAG, "Confirm Sharing"); if (shareCard(confirmCard)){ if (cdao.persistCard("shared_cards", confirmCard)) { Log.d(TAG, "Persisted Card in shared_cards: " + confirmCard); } else { Log.w(TAG, "CARD SHARED! but failed to persist card in shared_cards table"); } } else{ if (cdao.persistCard("pending_internet", confirmCard)) { Log.d(TAG, "Persisted Card in pending_internet: " + confirmCard); } else { Log.w(TAG, "Failed to persist card in pending_internet table"); confirmed_card = false; } } if (confirmed_card){ cdao.deleteCard("pending_confirm", confirmCard); //NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); //if (notificationId >= 0){ // mNotificationManager.cancel(notificationId); //} } } return confirmed_card; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "PostCardTask#onPostExecture"); } }*/ }
no message
src/android/LocationUpdateService.java
no message
<ide><path>rc/android/LocationUpdateService.java <ide> } <ide> } <ide> <del> private class ShareCardTask extends AsyncTask<Object, Integer, Boolean> { <add> private class ShareCardTask extends AsyncTask<Integer, Integer, Boolean> { <ide> <ide> @Override <del> protected Boolean doInBackground(Object...objects) { <add> protected Boolean doInBackground(Integer...ids) { <ide> Log.d(TAG, "Executing PostLocationTask#doInBackground"); <del> Log.i(TAG, "1111 Post saved card"); <del> CardDAO cardDAO = DAOFactory.createCardDAO(LocationUpdateService.this.getApplicationContext()); <del> for (com.tenforwardconsulting.cordova.bgloc.data.Card savedGeoCard : cardDAO.geoPendingCards()) { <del> Log.d(TAG, "Posting saved card"); <del> if (postCard(savedGeoCard)) { <del> cardDAO.deleteCard("pending_geo", savedGeoCard); <del> } <del> } <del> Log.i(TAG, "9999 Post saved card"); <add> Log.i(TAG, "1111 Post shared card"); <add> int notificationId = ids[0]; <add> int notificationCardId = ids[1]; <add> Boolean confirmed_card = true; <add> <add> Log.i(TAG, "9999 Post shared card"); <ide> return true; <ide> } <ide> @Override
JavaScript
mit
3d098cbe31572b550b34b52d4c467d881ca5cd0d
0
reapp/reapp-kit
import { Promise } from 'bluebird'; Promise.longStackTraces(); window.Promise = Promise; // fetch import 'isomorphic-fetch'; import UI from 'reapp-ui'; import Helpers from 'reapp-ui/helpers'; import 'reapp-object-assign'; // data import Immutable from 'immutable'; import store from './lib/store'; import Store from './lib/StoreComponent'; import action from './lib/action'; // theme import theme from './lib/theme'; // ui import Components from 'reapp-ui/all'; // router import Router from 'react-router'; import generator from 'reapp-routes/react-router/generator'; import render from 'reapp-routes/react-router/render'; // reapp import Theme from 'reapp-ui/helpers/Theme'; import Reapp from './lib/Reapp'; // react patch import React from 'react'; import Component from './lib/Component'; import Page from './lib/Page'; React._Component = React.Component; React.Component = Component; React.Page = Page; // inappbrowser if (window.cordova && window.cordova.InAppBrowser) window.open = window.cordova.InAppBrowser.open; module.exports = Object.assign( Components, { // react React, // reapp component/page export Component, Page, // immutable Immutable, // promise Promise, // reapp Reapp, // data action, store, Store, // UI theme, makeStyles: UI.makeStyles, Helpers, // router Router, router: function(require, routes, opts, cb) { return render.async(generator.routes(require, routes), opts, cb); }, route: generator.route } );
src/index.js
import { Promise } from 'bluebird'; Promise.longStackTraces(); window.Promise = Promise; // fetch import 'isomorphic-fetch'; import UI from 'reapp-ui'; import 'reapp-object-assign'; // data import Immutable from 'immutable'; import store from './lib/store'; import Store from './lib/StoreComponent'; import action from './lib/action'; // theme import theme from './lib/theme'; // ui import Components from 'reapp-ui/all'; // router import Router from 'react-router'; import generator from 'reapp-routes/react-router/generator'; import render from 'reapp-routes/react-router/render'; // reapp import Theme from 'reapp-ui/helpers/Theme'; import Reapp from './lib/Reapp'; // react patch import React from 'react'; import Component from './lib/Component'; import Page from './lib/Page'; React._Component = React.Component; React.Component = Component; React.Page = Page; // inappbrowser if (window.cordova && window.cordova.InAppBrowser) window.open = window.cordova.InAppBrowser.open; module.exports = Object.assign( Components, { // react React, // reapp component/page export Component, Page, // immutable Immutable, // promise Promise, // reapp Reapp, // data action, store, Store, // theme theme, makeStyles: UI.makeStyles, // router Router, router: function(require, routes, opts, cb) { return render.async(generator.routes(require, routes), opts, cb); }, route: generator.route } );
export helpers from reapp-ui
src/index.js
export helpers from reapp-ui
<ide><path>rc/index.js <ide> import 'isomorphic-fetch'; <ide> <ide> import UI from 'reapp-ui'; <add>import Helpers from 'reapp-ui/helpers'; <ide> import 'reapp-object-assign'; <ide> <ide> // data <ide> store, <ide> Store, <ide> <del> // theme <add> // UI <ide> theme, <ide> makeStyles: UI.makeStyles, <add> Helpers, <ide> <ide> // router <ide> Router,
Java
apache-2.0
463b3f13974d61606f03f8ec048947cdb17e2f7c
0
franz1981/JCTools,JCTools/JCTools
package org.jctools.queues; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import java.util.ArrayList; import java.util.Collection; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import org.jctools.queues.spec.ConcurrentQueueSpec; import org.jctools.queues.spec.Ordering; import org.jctools.queues.spec.Preference; import org.jctools.util.Pow2; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class MessagePassingQueueSanityTest { private static final int SIZE = 8192 * 2; @Parameterized.Parameters public static Collection parameters() { ArrayList<Object[]> list = new ArrayList<Object[]>(); list.add(test(0, 1, 4, Ordering.FIFO, new MpscChunkedArrayQueue<>(4)));// MPSC size 1 list.add(test(0, 1, SIZE, Ordering.FIFO, new MpscChunkedArrayQueue<>(2, SIZE)));// MPSC size SIZE return list; } private final MessagePassingQueue<Integer> queue; private final ConcurrentQueueSpec spec; public MessagePassingQueueSanityTest(ConcurrentQueueSpec spec, MessagePassingQueue<Integer> queue) { this.queue = queue; this.spec = spec; } @Before public void clear() { queue.clear(); } @Test public void sanity() { for (int i = 0; i < SIZE; i++) { assertNull(queue.relaxedPoll()); assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); } int i = 0; while (i < SIZE && queue.relaxedOffer(i)) i++; int size = i; assertEquals(size, queue.size()); if (spec.ordering == Ordering.FIFO) { // expect FIFO i = 0; Integer p; Integer e; while ((p = queue.relaxedPeek()) != null) { e = queue.relaxedPoll(); assertEquals(p, e); assertEquals(size - (i + 1), queue.size()); assertEquals(i++, e.intValue()); } assertEquals(size, i); } else { // expect sum of elements is (size - 1) * size / 2 = 0 + 1 + .... + (size - 1) int sum = (size - 1) * size / 2; i = 0; Integer e; while ((e = queue.relaxedPoll()) != null) { assertEquals(--size, queue.size()); sum -= e; } assertEquals(0, sum); } } int count = 0; Integer p; @Test public void sanityDrainBatch() { assertEquals(0, queue.drain(e -> { } , SIZE)); assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); count = 0; int i = queue.fill(() -> { return count++; } , SIZE); final int size = i; assertEquals(size, queue.size()); if (spec.ordering == Ordering.FIFO) { // expect FIFO p = queue.relaxedPeek(); count = 0; i = queue.drain(e -> { // batch consumption can cause size to differ from following expectation // this is because elements are 'claimed' in a batch and their consumption lags if (spec.consumers == 1) { assertEquals(p, e); // peek will return the post claim peek assertEquals(size - (count + 1), queue.size()); // size will return the post claim size } assertEquals(count++, e.intValue()); p = queue.relaxedPeek(); }); p = null; assertEquals(size, i); assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); } else { } } @Test public void testSizeIsTheNumberOfOffers() { int currentSize = 0; while (currentSize < SIZE && queue.relaxedOffer(currentSize)) { currentSize++; assertFalse(queue.isEmpty()); assertTrue(queue.size() == currentSize); } } @Test public void whenFirstInThenFirstOut() { assumeThat(spec.ordering, is(Ordering.FIFO)); // Arrange int i = 0; while (i < SIZE && queue.relaxedOffer(i)) { i++; } final int size = queue.size(); // Act i = 0; Integer prev; while ((prev = queue.relaxedPeek()) != null) { final Integer item = queue.relaxedPoll(); assertThat(item, is(prev)); assertEquals((size - (i + 1)), queue.size()); assertThat(item, is(i)); i++; } // Assert assertThat(i, is(size)); } @Test public void test_FIFO_PRODUCER_Ordering() throws Exception { assumeThat(spec.ordering, is(not((Ordering.FIFO)))); // Arrange int i = 0; while (i < SIZE && queue.relaxedOffer(i)) { i++; } int size = queue.size(); // Act // expect sum of elements is (size - 1) * size / 2 = 0 + 1 + .... + (size - 1) int sum = (size - 1) * size / 2; Integer e; while ((e = queue.relaxedPoll()) != null) { size--; assertEquals(size, queue.size()); sum -= e; } // Assert assertThat(sum, is(0)); } @Test public void whenOfferItemAndPollItemThenSameInstanceReturnedAndQueueIsEmpty() { assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); // Act final Integer e = 1; queue.relaxedOffer(e); assertFalse(queue.isEmpty()); assertEquals(1, queue.size()); final Integer oh = queue.relaxedPoll(); // Assert assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); } @Test public void testPowerOf2Capacity() { assumeThat(spec.isBounded(), is(true)); int n = Pow2.roundToPowerOfTwo(spec.capacity); for (int i = 0; i < n; i++) { assertTrue("Failed to insert:" + i, queue.relaxedOffer(i)); } assertFalse(queue.relaxedOffer(n)); } static final class Val { public int value; } @Test public void testHappensBefore() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { for (int i = 1; i <= 10; i++) { Val v = new Val(); v.value = i; q.relaxedOffer(v); } // slow down the producer, this will make the queue mostly empty encouraging visibility // issues. Thread.yield(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { for (int i = 0; i < 10; i++) { Val v = (Val) q.relaxedPeek(); if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } q.relaxedPoll(); } } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } @Test public void testHappensBeforePrepetualDrain() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { int counter; @Override public void run() { while (!stop.get()) { for (int i = 1; i <= 10; i++) { Val v = new Val(); v.value = i; q.relaxedOffer(v); } // slow down the producer, this will make the queue mostly empty encouraging visibility // issues. Thread.yield(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { q.drain(e -> { Val v = (Val) e; if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } } , e -> { return e; } , () -> { return !stop.get(); }); } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } @Test public void testHappensBeforePrepetualFill() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { int counter; @Override public void run() { counter = 1; q.fill(() -> { Val v = new Val(); v.value = 1 + (counter++ % 10); return v; } , e -> { return e; } , () -> { // slow down the producer, this will make the queue mostly empty encouraging visibility // issues. Thread.yield(); return !stop.get(); }); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { for (int i = 0; i < 10; i++) { Val v = (Val) q.relaxedPeek(); int r; if (v != null && (r = v.value) == 0) { fail.value = 1; stop.set(true); } q.relaxedPoll(); } } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } @Test public void testHappensBeforePrepetualFillDrain() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { int counter; @Override public void run() { counter = 1; q.fill(() -> { Val v = new Val(); v.value = 1 + (counter++ % 10); return v; } , e -> { return e; } , () -> { // slow down the producer, this will make the queue mostly empty encouraging // visibility issues. Thread.yield(); return !stop.get(); }); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { q.drain(e -> { Val v = (Val) e; if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } } , e -> { return e; } , () -> { return !stop.get(); }); } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } private static Object[] test(int producers, int consumers, int capacity, Ordering ordering, Queue<Integer> q) { ConcurrentQueueSpec spec = new ConcurrentQueueSpec(producers, consumers, capacity, ordering, Preference.NONE); if (q == null) { q = QueueFactory.newQueue(spec); } return new Object[] { spec, q }; } }
jctools-experimental/src/test/java/org/jctools/queues/MessagePassingQueueSanityTest.java
package org.jctools.queues; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import java.util.ArrayList; import java.util.Collection; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import org.jctools.queues.spec.ConcurrentQueueSpec; import org.jctools.queues.spec.Ordering; import org.jctools.queues.spec.Preference; import org.jctools.util.Pow2; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class MessagePassingQueueSanityTest { private static final int SIZE = 8192 * 2; @Parameterized.Parameters public static Collection parameters() { ArrayList<Object[]> list = new ArrayList<Object[]>(); list.add(test(0, 1, 4, Ordering.FIFO, new MpscChunkedArrayQueue<>(4)));// MPSC size 1 list.add(test(0, 1, SIZE, Ordering.FIFO, new MpscChunkedArrayQueue<>(2, SIZE)));// MPSC size SIZE return list; } private final MessagePassingQueue<Integer> queue; private final ConcurrentQueueSpec spec; public MessagePassingQueueSanityTest(ConcurrentQueueSpec spec, MessagePassingQueue<Integer> queue) { this.queue = queue; this.spec = spec; } @Before public void clear() { queue.clear(); } @Test public void sanity() { for (int i = 0; i < SIZE; i++) { assertNull(queue.relaxedPoll()); assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); } int i = 0; while (i < SIZE && queue.relaxedOffer(i)) i++; int size = i; assertEquals(size, queue.size()); if (spec.ordering == Ordering.FIFO) { // expect FIFO i = 0; Integer p; Integer e; while ((p = queue.relaxedPeek()) != null) { e = queue.relaxedPoll(); assertEquals(p, e); assertEquals(size - (i + 1), queue.size()); assertEquals(i++, e.intValue()); } assertEquals(size, i); } else { // expect sum of elements is (size - 1) * size / 2 = 0 + 1 + .... + (size - 1) int sum = (size - 1) * size / 2; i = 0; Integer e; while ((e = queue.relaxedPoll()) != null) { assertEquals(--size, queue.size()); sum -= e; } assertEquals(0, sum); } } int count = 0; Integer p; @Test public void sanityDrainBatch() { assertEquals(0, queue.drain(e -> { } , SIZE)); assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); count = 0; int i = queue.fill(() -> { return count++; } , SIZE); final int size = i; assertEquals(size, queue.size()); if (spec.ordering == Ordering.FIFO) { // expect FIFO p = queue.relaxedPeek(); count = 0; i = queue.drain(e -> { // batch consumption can cause size to differ from following expectation // this is because elements are 'claimed' in a batch and their consumption lags if (spec.consumers == 1) { assertEquals(p, e); // peek will return the post claim peek assertEquals(size - (count + 1), queue.size()); // size will return the post claim size } assertEquals(count++, e.intValue()); p = queue.relaxedPeek(); }); p = null; assertEquals(size, i); assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); } else { } } @Test public void testSizeIsTheNumberOfOffers() { int currentSize = 0; while (currentSize < SIZE && queue.relaxedOffer(currentSize)) { currentSize++; assertFalse(queue.isEmpty()); assertTrue(queue.size() == currentSize); } } @Test public void whenFirstInThenFirstOut() { assumeThat(spec.ordering, is(Ordering.FIFO)); // Arrange int i = 0; while (i < SIZE && queue.relaxedOffer(i)) { i++; } final int size = queue.size(); // Act i = 0; Integer prev; while ((prev = queue.relaxedPeek()) != null) { final Integer item = queue.relaxedPoll(); assertThat(item, is(prev)); assertEquals((size - (i + 1)), queue.size()); assertThat(item, is(i)); i++; } // Assert assertThat(i, is(size)); } @Test public void test_FIFO_PRODUCER_Ordering() throws Exception { assumeThat(spec.ordering, is(not((Ordering.FIFO)))); // Arrange int i = 0; while (i < SIZE && queue.relaxedOffer(i)) { i++; } int size = queue.size(); // Act // expect sum of elements is (size - 1) * size / 2 = 0 + 1 + .... + (size - 1) int sum = (size - 1) * size / 2; Integer e; while ((e = queue.relaxedPoll()) != null) { size--; assertEquals(size, queue.size()); sum -= e; } // Assert assertThat(sum, is(0)); } @Test public void whenOfferItemAndPollItemThenSameInstanceReturnedAndQueueIsEmpty() { assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); // Act final Integer e = 1; queue.relaxedOffer(e); assertFalse(queue.isEmpty()); assertEquals(1, queue.size()); final Integer oh = queue.relaxedPoll(); // Assert assertTrue(queue.isEmpty()); assertTrue(queue.size() == 0); } @Test public void testPowerOf2Capacity() { assumeThat(spec.isBounded(), is(true)); int n = Pow2.roundToPowerOfTwo(spec.capacity); for (int i = 0; i < n; i++) { assertTrue("Failed to insert:" + i, queue.relaxedOffer(i)); } assertFalse(queue.relaxedOffer(n)); } static final class Val { public int value; } @Test public void testHappensBefore() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { for (int i = 1; i <= 10; i++) { Val v = new Val(); v.value = i; q.relaxedOffer(v); } } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { for (int i = 0; i < 10; i++) { Val v = (Val) q.relaxedPeek(); if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } q.relaxedPoll(); } } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } @Test public void testHappensBeforePrepetualDrain() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { int counter; @Override public void run() { while (!stop.get()) { for (int i = 1; i <= 10; i++) { Val v = new Val(); v.value = i; q.relaxedOffer(v); } } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { q.drain(e -> { Val v = (Val) e; if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } } , e -> { return e; } , () -> { return !stop.get(); }); } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } @Test public void testHappensBeforePrepetualFill() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { int counter; @Override public void run() { counter = 1; q.fill(() -> { Val v = new Val(); v.value = 1 + (counter++ % 10); return v; } , e -> { return e; } , () -> { return !stop.get(); }); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { for (int i = 0; i < 10; i++) { Val v = (Val) q.relaxedPeek(); if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } q.relaxedPoll(); } } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } @Test public void testHappensBeforePrepetualFillDrain() throws Exception { final AtomicBoolean stop = new AtomicBoolean(); final MessagePassingQueue q = queue; final Val fail = new Val(); Thread t1 = new Thread(new Runnable() { int counter; @Override public void run() { counter = 1; q.fill(() -> { Val v = new Val(); v.value = 1 + (counter++ % 10); return v; } , e -> { return e; } , () -> { return !stop.get(); }); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (!stop.get()) { q.drain(e -> { Val v = (Val) e; if (v != null && v.value == 0) { fail.value = 1; stop.set(true); } } , e -> { return e; } , () -> { return !stop.get(); }); } } }); t1.start(); t2.start(); Thread.sleep(1000); stop.set(true); t1.join(); t2.join(); assertEquals("reordering detected", 0, fail.value); } private static Object[] test(int producers, int consumers, int capacity, Ordering ordering, Queue<Integer> q) { ConcurrentQueueSpec spec = new ConcurrentQueueSpec(producers, consumers, capacity, ordering, Preference.NONE); if (q == null) { q = QueueFactory.newQueue(spec); } return new Object[] { spec, q }; } }
Debugging CI issue.
jctools-experimental/src/test/java/org/jctools/queues/MessagePassingQueueSanityTest.java
Debugging CI issue.
<ide><path>ctools-experimental/src/test/java/org/jctools/queues/MessagePassingQueueSanityTest.java <ide> v.value = i; <ide> q.relaxedOffer(v); <ide> } <add> // slow down the producer, this will make the queue mostly empty encouraging visibility <add> // issues. <add> Thread.yield(); <ide> } <ide> } <ide> }); <ide> v.value = i; <ide> q.relaxedOffer(v); <ide> } <add> // slow down the producer, this will make the queue mostly empty encouraging visibility <add> // issues. <add> Thread.yield(); <ide> } <ide> } <ide> }); <ide> } , e -> { <ide> return e; <ide> } , () -> { <add> // slow down the producer, this will make the queue mostly empty encouraging visibility <add> // issues. <add> Thread.yield(); <ide> return !stop.get(); <ide> }); <ide> } <ide> while (!stop.get()) { <ide> for (int i = 0; i < 10; i++) { <ide> Val v = (Val) q.relaxedPeek(); <del> if (v != null && v.value == 0) { <add> int r; <add> if (v != null && (r = v.value) == 0) { <ide> fail.value = 1; <ide> stop.set(true); <ide> } <ide> return v; <ide> } , e -> { <ide> return e; <del> } , () -> { <add> } , () -> { // slow down the producer, this will make the queue mostly empty encouraging <add> // visibility issues. <add> Thread.yield(); <ide> return !stop.get(); <ide> }); <ide> }
JavaScript
mit
f0df009923286b80890ded2a246e4d9b359d2721
0
jdillard/jdillard.github.io,jdillard/personal-site,jdillard/personal-site,jdillard/jdillard.github.io,jdillard/jdillard.github.io,jdillard/personal-site,jdillard/personal-site
const webpack = require('webpack'); const path = require("path"); const ManifestPlugin = require('webpack-manifest-plugin'); const WebpackCleanupPlugin = require('webpack-cleanup-plugin'); //const ExtractTextPlugin = require("extract-text-webpack-plugin"); //const extractSass = new ExtractTextPlugin({ // filename: "css/styles.[contenthash].css", // disable: process.env.NODE_ENV === "development" //}); module.exports = { plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", moment: "moment", axios: "axios" }), //new ExtractTextPlugin("./assets/dist/css/styles.css"), new webpack.optimize.CommonsChunkPlugin('vendor'), new ManifestPlugin({ fileName: '../../_data/asset-manifest.json' }), new WebpackCleanupPlugin() ], entry: { about: "./assets/js/about.js", archive: "./assets/js/archive.js", index: "./assets/js/index.js", post: "./assets/js/post.js", commons: "./assets/js/commons.js" }, output: { path: path.resolve(__dirname, 'assets/dist/'), filename: "js/[name].[chunkhash].js" }, module: { rules: [ { test: /\.js$/, // include .js files enforce: "pre", // preload the jshint loader exclude: /node_modules/, // exclude any and all files in the node_modules folder use: [ { loader: "jshint-loader" } ] }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: 'url-loader?limit=100000' }, /* { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader!postcss-loader!sass-loader" }) }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, */ { test: /\.hbs$/, loader: 'handlebars-loader', query: { helperDirs: [ __dirname + "/assets/js/helpers" ] } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules$/, query: { presets: ['es2015'] } } ] } };
webpack.common.js
const webpack = require('webpack'); const path = require("path"); const ManifestPlugin = require('webpack-manifest-plugin'); const WebpackCleanupPlugin = require('webpack-cleanup-plugin'); //const ExtractTextPlugin = require("extract-text-webpack-plugin"); //const extractSass = new ExtractTextPlugin({ // filename: "css/styles.[contenthash].css", // disable: process.env.NODE_ENV === "development" //}); module.exports = { plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", moment: "moment", axios: "axios" }), //new ExtractTextPlugin("./assets/dist/css/styles.css"), new webpack.optimize.CommonsChunkPlugin('vendor'), new ManifestPlugin({ fileName: '../../_data/asset-manifest.json' }), new WebpackCleanupPlugin() ], entry: { about: "./assets/js/about.js", archive: "./assets/js/archive.js", post: "./assets/js/post.js", commons: "./assets/js/commons.js" }, output: { path: path.resolve(__dirname, 'assets/dist/'), filename: "js/[name].[chunkhash].js" }, module: { rules: [ { test: /\.js$/, // include .js files enforce: "pre", // preload the jshint loader exclude: /node_modules/, // exclude any and all files in the node_modules folder use: [ { loader: "jshint-loader" } ] }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: 'url-loader?limit=100000' }, /* { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader!postcss-loader!sass-loader" }) }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, */ { test: /\.hbs$/, loader: 'handlebars-loader', query: { helperDirs: [ __dirname + "/assets/js/helpers" ] } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules$/, query: { presets: ['es2015'] } } ] } };
add new index entrypoint
webpack.common.js
add new index entrypoint
<ide><path>ebpack.common.js <ide> entry: { <ide> about: "./assets/js/about.js", <ide> archive: "./assets/js/archive.js", <add> index: "./assets/js/index.js", <ide> post: "./assets/js/post.js", <ide> commons: "./assets/js/commons.js" <ide> },
Java
apache-2.0
da7f9962c640666a743675085922bf75a656f81b
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.jms.Connection; import javax.jms.ConnectionConsumer; import javax.jms.ConnectionMetaData; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.ExceptionListener; import javax.jms.IllegalStateException; import javax.jms.InvalidDestinationException; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueSession; import javax.jms.ServerSessionPool; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicSession; import javax.jms.XAConnection; import org.apache.activemq.advisory.DestinationSource; import org.apache.activemq.blob.BlobTransferPolicy; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQTempDestination; import org.apache.activemq.command.ActiveMQTempQueue; import org.apache.activemq.command.ActiveMQTempTopic; import org.apache.activemq.command.BrokerInfo; import org.apache.activemq.command.Command; import org.apache.activemq.command.CommandTypes; import org.apache.activemq.command.ConnectionControl; import org.apache.activemq.command.ConnectionError; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConsumerControl; import org.apache.activemq.command.ConsumerId; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.ControlCommand; import org.apache.activemq.command.DestinationInfo; import org.apache.activemq.command.ExceptionResponse; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.ProducerAck; import org.apache.activemq.command.ProducerId; import org.apache.activemq.command.RemoveInfo; import org.apache.activemq.command.RemoveSubscriptionInfo; import org.apache.activemq.command.Response; import org.apache.activemq.command.SessionId; import org.apache.activemq.command.ShutdownInfo; import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.management.JMSConnectionStatsImpl; import org.apache.activemq.management.JMSStatsImpl; import org.apache.activemq.management.StatsCapable; import org.apache.activemq.management.StatsImpl; import org.apache.activemq.state.CommandVisitorAdapter; import org.apache.activemq.thread.Scheduler; import org.apache.activemq.thread.TaskRunnerFactory; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportListener; import org.apache.activemq.transport.failover.FailoverTransport; import org.apache.activemq.util.IdGenerator; import org.apache.activemq.util.IntrospectionSupport; import org.apache.activemq.util.JMSExceptionSupport; import org.apache.activemq.util.LongSequenceGenerator; import org.apache.activemq.util.ServiceSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActiveMQConnection implements Connection, TopicConnection, QueueConnection, StatsCapable, Closeable, StreamConnection, TransportListener, EnhancedConnection { public static final String DEFAULT_USER = ActiveMQConnectionFactory.DEFAULT_USER; public static final String DEFAULT_PASSWORD = ActiveMQConnectionFactory.DEFAULT_PASSWORD; public static final String DEFAULT_BROKER_URL = ActiveMQConnectionFactory.DEFAULT_BROKER_URL; private static final Logger LOG = LoggerFactory.getLogger(ActiveMQConnection.class); public final ConcurrentHashMap<ActiveMQTempDestination, ActiveMQTempDestination> activeTempDestinations = new ConcurrentHashMap<ActiveMQTempDestination, ActiveMQTempDestination>(); protected boolean dispatchAsync=true; protected boolean alwaysSessionAsync = true; private TaskRunnerFactory sessionTaskRunner; private final ThreadPoolExecutor executor; // Connection state variables private final ConnectionInfo info; private ExceptionListener exceptionListener; private ClientInternalExceptionListener clientInternalExceptionListener; private boolean clientIDSet; private boolean isConnectionInfoSentToBroker; private boolean userSpecifiedClientID; // Configuration options variables private ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); private BlobTransferPolicy blobTransferPolicy; private RedeliveryPolicy redeliveryPolicy; private MessageTransformer transformer; private boolean disableTimeStampsByDefault; private boolean optimizedMessageDispatch = true; private boolean copyMessageOnSend = true; private boolean useCompression; private boolean objectMessageSerializationDefered; private boolean useAsyncSend; private boolean optimizeAcknowledge; private long optimizeAcknowledgeTimeOut = 0; private boolean nestedMapAndListEnabled = true; private boolean useRetroactiveConsumer; private boolean exclusiveConsumer; private boolean alwaysSyncSend; private int closeTimeout = 15000; private boolean watchTopicAdvisories = true; private long warnAboutUnstartedConnectionTimeout = 500L; private int sendTimeout =0; private boolean sendAcksAsync=true; private boolean checkForDuplicates = true; private final Transport transport; private final IdGenerator clientIdGenerator; private final JMSStatsImpl factoryStats; private final JMSConnectionStatsImpl stats; private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicBoolean closing = new AtomicBoolean(false); private final AtomicBoolean closed = new AtomicBoolean(false); private final AtomicBoolean transportFailed = new AtomicBoolean(false); private final CopyOnWriteArrayList<ActiveMQSession> sessions = new CopyOnWriteArrayList<ActiveMQSession>(); private final CopyOnWriteArrayList<ActiveMQConnectionConsumer> connectionConsumers = new CopyOnWriteArrayList<ActiveMQConnectionConsumer>(); private final CopyOnWriteArrayList<ActiveMQInputStream> inputStreams = new CopyOnWriteArrayList<ActiveMQInputStream>(); private final CopyOnWriteArrayList<ActiveMQOutputStream> outputStreams = new CopyOnWriteArrayList<ActiveMQOutputStream>(); private final CopyOnWriteArrayList<TransportListener> transportListeners = new CopyOnWriteArrayList<TransportListener>(); // Maps ConsumerIds to ActiveMQConsumer objects private final ConcurrentHashMap<ConsumerId, ActiveMQDispatcher> dispatchers = new ConcurrentHashMap<ConsumerId, ActiveMQDispatcher>(); private final ConcurrentHashMap<ProducerId, ActiveMQMessageProducer> producers = new ConcurrentHashMap<ProducerId, ActiveMQMessageProducer>(); private final LongSequenceGenerator sessionIdGenerator = new LongSequenceGenerator(); private final SessionId connectionSessionId; private final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator producerIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator tempDestinationIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator localTransactionIdGenerator = new LongSequenceGenerator(); private AdvisoryConsumer advisoryConsumer; private final CountDownLatch brokerInfoReceived = new CountDownLatch(1); private BrokerInfo brokerInfo; private IOException firstFailureError; private int producerWindowSize = ActiveMQConnectionFactory.DEFAULT_PRODUCER_WINDOW_SIZE; // Assume that protocol is the latest. Change to the actual protocol // version when a WireFormatInfo is received. private final AtomicInteger protocolVersion = new AtomicInteger(CommandTypes.PROTOCOL_VERSION); private final long timeCreated; private final ConnectionAudit connectionAudit = new ConnectionAudit(); private DestinationSource destinationSource; private final Object ensureConnectionInfoSentMutex = new Object(); private boolean useDedicatedTaskRunner; protected volatile CountDownLatch transportInterruptionProcessingComplete; private long consumerFailoverRedeliveryWaitPeriod; private final Scheduler scheduler; private boolean messagePrioritySupported = true; private boolean transactedIndividualAck = false; private boolean nonBlockingRedelivery = false; /** * Construct an <code>ActiveMQConnection</code> * * @param transport * @param factoryStats * @throws Exception */ protected ActiveMQConnection(final Transport transport, IdGenerator clientIdGenerator, IdGenerator connectionIdGenerator, JMSStatsImpl factoryStats) throws Exception { this.transport = transport; this.clientIdGenerator = clientIdGenerator; this.factoryStats = factoryStats; // Configure a single threaded executor who's core thread can timeout if // idle executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r, "ActiveMQ Connection Executor: " + transport); thread.setDaemon(true); return thread; } }); // asyncConnectionThread.allowCoreThreadTimeOut(true); String uniqueId = connectionIdGenerator.generateId(); this.info = new ConnectionInfo(new ConnectionId(uniqueId)); this.info.setManageable(true); this.info.setFaultTolerant(transport.isFaultTolerant()); this.connectionSessionId = new SessionId(info.getConnectionId(), -1); this.transport.setTransportListener(this); this.stats = new JMSConnectionStatsImpl(sessions, this instanceof XAConnection); this.factoryStats.addConnection(this); this.timeCreated = System.currentTimeMillis(); this.connectionAudit.setCheckForDuplicates(transport.isFaultTolerant()); this.scheduler = new Scheduler("ActiveMQConnection["+uniqueId+"] Scheduler"); this.scheduler.start(); } protected void setUserName(String userName) { this.info.setUserName(userName); } protected void setPassword(String password) { this.info.setPassword(password); } /** * A static helper method to create a new connection * * @return an ActiveMQConnection * @throws JMSException */ public static ActiveMQConnection makeConnection() throws JMSException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); return (ActiveMQConnection)factory.createConnection(); } /** * A static helper method to create a new connection * * @param uri * @return and ActiveMQConnection * @throws JMSException */ public static ActiveMQConnection makeConnection(String uri) throws JMSException, URISyntaxException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); return (ActiveMQConnection)factory.createConnection(); } /** * A static helper method to create a new connection * * @param user * @param password * @param uri * @return an ActiveMQConnection * @throws JMSException */ public static ActiveMQConnection makeConnection(String user, String password, String uri) throws JMSException, URISyntaxException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, new URI(uri)); return (ActiveMQConnection)factory.createConnection(); } /** * @return a number unique for this connection */ public JMSConnectionStatsImpl getConnectionStats() { return stats; } /** * Creates a <CODE>Session</CODE> object. * * @param transacted indicates whether the session is transacted * @param acknowledgeMode indicates whether the consumer or the client will * acknowledge any messages it receives; ignored if the * session is transacted. Legal values are * <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, and * <code>Session.DUPS_OK_ACKNOWLEDGE</code>. * @return a newly created session * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a session due to some internal error or lack of * support for the specific transaction and acknowledgement * mode. * @see Session#AUTO_ACKNOWLEDGE * @see Session#CLIENT_ACKNOWLEDGE * @see Session#DUPS_OK_ACKNOWLEDGE * @since 1.1 */ public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); if(!transacted) { if (acknowledgeMode==Session.SESSION_TRANSACTED) { throw new JMSException("acknowledgeMode SESSION_TRANSACTED cannot be used for an non-transacted Session"); } else if (acknowledgeMode < Session.SESSION_TRANSACTED || acknowledgeMode > ActiveMQSession.MAX_ACK_CONSTANT) { throw new JMSException("invalid acknowledgeMode: " + acknowledgeMode + ". Valid values are Session.AUTO_ACKNOWLEDGE (1), " + "Session.CLIENT_ACKNOWLEDGE (2), Session.DUPS_OK_ACKNOWLEDGE (3), ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE (4) or for transacted sessions Session.SESSION_TRANSACTED (0)"); } } return new ActiveMQSession(this, getNextSessionId(), transacted ? Session.SESSION_TRANSACTED : (acknowledgeMode == Session.SESSION_TRANSACTED ? Session.AUTO_ACKNOWLEDGE : acknowledgeMode), isDispatchAsync(), isAlwaysSessionAsync()); } /** * @return sessionId */ protected SessionId getNextSessionId() { return new SessionId(info.getConnectionId(), sessionIdGenerator.getNextSequenceId()); } /** * Gets the client identifier for this connection. * <P> * This value is specific to the JMS provider. It is either preconfigured by * an administrator in a <CODE> ConnectionFactory</CODE> object or assigned * dynamically by the application by calling the <code>setClientID</code> * method. * * @return the unique client identifier * @throws JMSException if the JMS provider fails to return the client ID * for this connection due to some internal error. */ public String getClientID() throws JMSException { checkClosedOrFailed(); return this.info.getClientId(); } /** * Sets the client identifier for this connection. * <P> * The preferred way to assign a JMS client's client identifier is for it to * be configured in a client-specific <CODE>ConnectionFactory</CODE> * object and transparently assigned to the <CODE>Connection</CODE> object * it creates. * <P> * Alternatively, a client can set a connection's client identifier using a * provider-specific value. The facility to set a connection's client * identifier explicitly is not a mechanism for overriding the identifier * that has been administratively configured. It is provided for the case * where no administratively specified identifier exists. If one does exist, * an attempt to change it by setting it must throw an * <CODE>IllegalStateException</CODE>. If a client sets the client * identifier explicitly, it must do so immediately after it creates the * connection and before any other action on the connection is taken. After * this point, setting the client identifier is a programming error that * should throw an <CODE>IllegalStateException</CODE>. * <P> * The purpose of the client identifier is to associate a connection and its * objects with a state maintained on behalf of the client by a provider. * The only such state identified by the JMS API is that required to support * durable subscriptions. * <P> * If another connection with the same <code>clientID</code> is already * running when this method is called, the JMS provider should detect the * duplicate ID and throw an <CODE>InvalidClientIDException</CODE>. * * @param newClientID the unique client identifier * @throws JMSException if the JMS provider fails to set the client ID for * this connection due to some internal error. * @throws javax.jms.InvalidClientIDException if the JMS client specifies an * invalid or duplicate client ID. * @throws javax.jms.IllegalStateException if the JMS client attempts to set * a connection's client ID at the wrong time or when it has * been administratively configured. */ public void setClientID(String newClientID) throws JMSException { checkClosedOrFailed(); if (this.clientIDSet) { throw new IllegalStateException("The clientID has already been set"); } if (this.isConnectionInfoSentToBroker) { throw new IllegalStateException("Setting clientID on a used Connection is not allowed"); } this.info.setClientId(newClientID); this.userSpecifiedClientID = true; ensureConnectionInfoSent(); } /** * Sets the default client id that the connection will use if explicitly not * set with the setClientId() call. */ public void setDefaultClientID(String clientID) throws JMSException { this.info.setClientId(clientID); this.userSpecifiedClientID = true; } /** * Gets the metadata for this connection. * * @return the connection metadata * @throws JMSException if the JMS provider fails to get the connection * metadata for this connection. * @see javax.jms.ConnectionMetaData */ public ConnectionMetaData getMetaData() throws JMSException { checkClosedOrFailed(); return ActiveMQConnectionMetaData.INSTANCE; } /** * Gets the <CODE>ExceptionListener</CODE> object for this connection. Not * every <CODE>Connection</CODE> has an <CODE>ExceptionListener</CODE> * associated with it. * * @return the <CODE>ExceptionListener</CODE> for this connection, or * null, if no <CODE>ExceptionListener</CODE> is associated with * this connection. * @throws JMSException if the JMS provider fails to get the * <CODE>ExceptionListener</CODE> for this connection. * @see javax.jms.Connection#setExceptionListener(ExceptionListener) */ public ExceptionListener getExceptionListener() throws JMSException { checkClosedOrFailed(); return this.exceptionListener; } /** * Sets an exception listener for this connection. * <P> * If a JMS provider detects a serious problem with a connection, it informs * the connection's <CODE> ExceptionListener</CODE>, if one has been * registered. It does this by calling the listener's <CODE>onException * </CODE> * method, passing it a <CODE>JMSException</CODE> object describing the * problem. * <P> * An exception listener allows a client to be notified of a problem * asynchronously. Some connections only consume messages, so they would * have no other way to learn their connection has failed. * <P> * A connection serializes execution of its <CODE>ExceptionListener</CODE>. * <P> * A JMS provider should attempt to resolve connection problems itself * before it notifies the client of them. * * @param listener the exception listener * @throws JMSException if the JMS provider fails to set the exception * listener for this connection. */ public void setExceptionListener(ExceptionListener listener) throws JMSException { checkClosedOrFailed(); this.exceptionListener = listener; } /** * Gets the <code>ClientInternalExceptionListener</code> object for this connection. * Not every <CODE>ActiveMQConnectionn</CODE> has a <CODE>ClientInternalExceptionListener</CODE> * associated with it. * * @return the listener or <code>null</code> if no listener is registered with the connection. */ public ClientInternalExceptionListener getClientInternalExceptionListener() { return clientInternalExceptionListener; } /** * Sets a client internal exception listener for this connection. * The connection will notify the listener, if one has been registered, of exceptions thrown by container components * (e.g. an EJB container in case of Message Driven Beans) during asynchronous processing of a message. * It does this by calling the listener's <code>onException()</code> method passing it a <code>Throwable</code> * describing the problem. * * @param listener the exception listener */ public void setClientInternalExceptionListener(ClientInternalExceptionListener listener) { this.clientInternalExceptionListener = listener; } /** * Starts (or restarts) a connection's delivery of incoming messages. A call * to <CODE>start</CODE> on a connection that has already been started is * ignored. * * @throws JMSException if the JMS provider fails to start message delivery * due to some internal error. * @see javax.jms.Connection#stop() */ public void start() throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); if (started.compareAndSet(false, true)) { for (Iterator<ActiveMQSession> i = sessions.iterator(); i.hasNext();) { ActiveMQSession session = i.next(); session.start(); } } } /** * Temporarily stops a connection's delivery of incoming messages. Delivery * can be restarted using the connection's <CODE>start</CODE> method. When * the connection is stopped, delivery to all the connection's message * consumers is inhibited: synchronous receives block, and messages are not * delivered to message listeners. * <P> * This call blocks until receives and/or message listeners in progress have * completed. * <P> * Stopping a connection has no effect on its ability to send messages. A * call to <CODE>stop</CODE> on a connection that has already been stopped * is ignored. * <P> * A call to <CODE>stop</CODE> must not return until delivery of messages * has paused. This means that a client can rely on the fact that none of * its message listeners will be called and that all threads of control * waiting for <CODE>receive</CODE> calls to return will not return with a * message until the connection is restarted. The receive timers for a * stopped connection continue to advance, so receives may time out while * the connection is stopped. * <P> * If message listeners are running when <CODE>stop</CODE> is invoked, the * <CODE>stop</CODE> call must wait until all of them have returned before * it may return. While these message listeners are completing, they must * have the full services of the connection available to them. * * @throws JMSException if the JMS provider fails to stop message delivery * due to some internal error. * @see javax.jms.Connection#start() */ public void stop() throws JMSException { checkClosedOrFailed(); if (started.compareAndSet(true, false)) { synchronized(sessions) { for (Iterator<ActiveMQSession> i = sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.stop(); } } } } /** * Closes the connection. * <P> * Since a provider typically allocates significant resources outside the * JVM on behalf of a connection, clients should close these resources when * they are not needed. Relying on garbage collection to eventually reclaim * these resources may not be timely enough. * <P> * There is no need to close the sessions, producers, and consumers of a * closed connection. * <P> * Closing a connection causes all temporary destinations to be deleted. * <P> * When this method is invoked, it should not return until message * processing has been shut down in an orderly fashion. This means that all * message listeners that may have been running have returned, and that all * pending receives have returned. A close terminates all pending message * receives on the connection's sessions' consumers. The receives may return * with a message or with null, depending on whether there was a message * available at the time of the close. If one or more of the connection's * sessions' message listeners is processing a message at the time when * connection <CODE>close</CODE> is invoked, all the facilities of the * connection and its sessions must remain available to those listeners * until they return control to the JMS provider. * <P> * Closing a connection causes any of its sessions' transactions in progress * to be rolled back. In the case where a session's work is coordinated by * an external transaction manager, a session's <CODE>commit</CODE> and * <CODE> rollback</CODE> methods are not used and the result of a closed * session's work is determined later by the transaction manager. Closing a * connection does NOT force an acknowledgment of client-acknowledged * sessions. * <P> * Invoking the <CODE>acknowledge</CODE> method of a received message from * a closed connection's session must throw an * <CODE>IllegalStateException</CODE>. Closing a closed connection must * NOT throw an exception. * * @throws JMSException if the JMS provider fails to close the connection * due to some internal error. For example, a failure to * release resources or to close a socket connection can * cause this exception to be thrown. */ public void close() throws JMSException { // Store the interrupted state and clear so that cleanup happens without // leaking connection resources. Reset in finally to preserve state. boolean interrupted = Thread.interrupted(); try { // If we were running, lets stop first. if (!closed.get() && !transportFailed.get()) { stop(); } synchronized (this) { if (!closed.get()) { closing.set(true); if (destinationSource != null) { destinationSource.stop(); destinationSource = null; } if (advisoryConsumer != null) { advisoryConsumer.dispose(); advisoryConsumer = null; } if (this.scheduler != null) { try { this.scheduler.stop(); } catch (Exception e) { JMSException ex = JMSExceptionSupport.create(e); throw ex; } } long lastDeliveredSequenceId = 0; for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.dispose(); lastDeliveredSequenceId = Math.max(lastDeliveredSequenceId, s.getLastDeliveredSequenceId()); } for (Iterator<ActiveMQConnectionConsumer> i = this.connectionConsumers.iterator(); i.hasNext();) { ActiveMQConnectionConsumer c = i.next(); c.dispose(); } for (Iterator<ActiveMQInputStream> i = this.inputStreams.iterator(); i.hasNext();) { ActiveMQInputStream c = i.next(); c.dispose(); } for (Iterator<ActiveMQOutputStream> i = this.outputStreams.iterator(); i.hasNext();) { ActiveMQOutputStream c = i.next(); c.dispose(); } // As TemporaryQueue and TemporaryTopic instances are bound // to a connection we should just delete them after the connection // is closed to free up memory for (Iterator<ActiveMQTempDestination> i = this.activeTempDestinations.values().iterator(); i.hasNext();) { ActiveMQTempDestination c = i.next(); c.delete(); } if (isConnectionInfoSentToBroker) { // If we announced ourselfs to the broker.. Try to let // the broker // know that the connection is being shutdown. RemoveInfo removeCommand = info.createRemoveCommand(); removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId); doSyncSendPacket(info.createRemoveCommand(), closeTimeout); doAsyncSendPacket(new ShutdownInfo()); } started.set(false); // TODO if we move the TaskRunnerFactory to the connection // factory // then we may need to call // factory.onConnectionClose(this); if (sessionTaskRunner != null) { sessionTaskRunner.shutdown(); } closed.set(true); closing.set(false); } } } finally { try { if (executor != null) { executor.shutdown(); } } catch (Throwable e) { LOG.error("Error shutting down thread pool " + e, e); } ServiceSupport.dispose(this.transport); factoryStats.removeConnection(this); if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Tells the broker to terminate its VM. This can be used to cleanly * terminate a broker running in a standalone java process. Server must have * property enable.vm.shutdown=true defined to allow this to work. */ // TODO : org.apache.activemq.message.BrokerAdminCommand not yet // implemented. /* * public void terminateBrokerVM() throws JMSException { BrokerAdminCommand * command = new BrokerAdminCommand(); * command.setCommand(BrokerAdminCommand.SHUTDOWN_SERVER_VM); * asyncSendPacket(command); } */ /** * Create a durable connection consumer for this connection (optional * operation). This is an expert facility not used by regular JMS clients. * * @param topic topic to access * @param subscriptionName durable subscription name * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this durable * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the durable connection consumer * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a connection consumer due to some internal error * or invalid arguments for <CODE>sessionPool</CODE> and * <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid destination * is specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer * @since 1.1 */ public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return this.createDurableConnectionConsumer(topic, subscriptionName, messageSelector, sessionPool, maxMessages, false); } /** * Create a durable connection consumer for this connection (optional * operation). This is an expert facility not used by regular JMS clients. * * @param topic topic to access * @param subscriptionName durable subscription name * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this durable * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @param noLocal set true if you want to filter out messages published * locally * @return the durable connection consumer * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a connection consumer due to some internal error * or invalid arguments for <CODE>sessionPool</CODE> and * <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid destination * is specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer * @since 1.1 */ public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages, boolean noLocal) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); SessionId sessionId = new SessionId(info.getConnectionId(), -1); ConsumerInfo info = new ConsumerInfo(new ConsumerId(sessionId, consumerIdGenerator.getNextSequenceId())); info.setDestination(ActiveMQMessageTransformation.transformDestination(topic)); info.setSubscriptionName(subscriptionName); info.setSelector(messageSelector); info.setPrefetchSize(maxMessages); info.setDispatchAsync(isDispatchAsync()); // Allows the options on the destination to configure the consumerInfo if (info.getDestination().getOptions() != null) { Map<String, String> options = new HashMap<String, String>(info.getDestination().getOptions()); IntrospectionSupport.setProperties(this.info, options, "consumer."); } return new ActiveMQConnectionConsumer(this, sessionPool, info); } // Properties // ------------------------------------------------------------------------- /** * Returns true if this connection has been started * * @return true if this Connection is started */ public boolean isStarted() { return started.get(); } /** * Returns true if the connection is closed */ public boolean isClosed() { return closed.get(); } /** * Returns true if the connection is in the process of being closed */ public boolean isClosing() { return closing.get(); } /** * Returns true if the underlying transport has failed */ public boolean isTransportFailed() { return transportFailed.get(); } /** * @return Returns the prefetchPolicy. */ public ActiveMQPrefetchPolicy getPrefetchPolicy() { return prefetchPolicy; } /** * Sets the <a * href="http://activemq.apache.org/what-is-the-prefetch-limit-for.html">prefetch * policy</a> for consumers created by this connection. */ public void setPrefetchPolicy(ActiveMQPrefetchPolicy prefetchPolicy) { this.prefetchPolicy = prefetchPolicy; } /** */ public Transport getTransportChannel() { return transport; } /** * @return Returns the clientID of the connection, forcing one to be * generated if one has not yet been configured. */ public String getInitializedClientID() throws JMSException { ensureConnectionInfoSent(); return info.getClientId(); } /** * @return Returns the timeStampsDisableByDefault. */ public boolean isDisableTimeStampsByDefault() { return disableTimeStampsByDefault; } /** * Sets whether or not timestamps on messages should be disabled or not. If * you disable them it adds a small performance boost. */ public void setDisableTimeStampsByDefault(boolean timeStampsDisableByDefault) { this.disableTimeStampsByDefault = timeStampsDisableByDefault; } /** * @return Returns the dispatchOptimizedMessage. */ public boolean isOptimizedMessageDispatch() { return optimizedMessageDispatch; } /** * If this flag is set then an larger prefetch limit is used - only * applicable for durable topic subscribers. */ public void setOptimizedMessageDispatch(boolean dispatchOptimizedMessage) { this.optimizedMessageDispatch = dispatchOptimizedMessage; } /** * @return Returns the closeTimeout. */ public int getCloseTimeout() { return closeTimeout; } /** * Sets the timeout before a close is considered complete. Normally a * close() on a connection waits for confirmation from the broker; this * allows that operation to timeout to save the client hanging if there is * no broker */ public void setCloseTimeout(int closeTimeout) { this.closeTimeout = closeTimeout; } /** * @return ConnectionInfo */ public ConnectionInfo getConnectionInfo() { return this.info; } public boolean isUseRetroactiveConsumer() { return useRetroactiveConsumer; } /** * Sets whether or not retroactive consumers are enabled. Retroactive * consumers allow non-durable topic subscribers to receive old messages * that were published before the non-durable subscriber started. */ public void setUseRetroactiveConsumer(boolean useRetroactiveConsumer) { this.useRetroactiveConsumer = useRetroactiveConsumer; } public boolean isNestedMapAndListEnabled() { return nestedMapAndListEnabled; } /** * Enables/disables whether or not Message properties and MapMessage entries * support <a * href="http://activemq.apache.org/structured-message-properties-and-mapmessages.html">Nested * Structures</a> of Map and List objects */ public void setNestedMapAndListEnabled(boolean structuredMapsEnabled) { this.nestedMapAndListEnabled = structuredMapsEnabled; } public boolean isExclusiveConsumer() { return exclusiveConsumer; } /** * Enables or disables whether or not queue consumers should be exclusive or * not for example to preserve ordering when not using <a * href="http://activemq.apache.org/message-groups.html">Message Groups</a> * * @param exclusiveConsumer */ public void setExclusiveConsumer(boolean exclusiveConsumer) { this.exclusiveConsumer = exclusiveConsumer; } /** * Adds a transport listener so that a client can be notified of events in * the underlying transport */ public void addTransportListener(TransportListener transportListener) { transportListeners.add(transportListener); } public void removeTransportListener(TransportListener transportListener) { transportListeners.remove(transportListener); } public boolean isUseDedicatedTaskRunner() { return useDedicatedTaskRunner; } public void setUseDedicatedTaskRunner(boolean useDedicatedTaskRunner) { this.useDedicatedTaskRunner = useDedicatedTaskRunner; } public TaskRunnerFactory getSessionTaskRunner() { synchronized (this) { if (sessionTaskRunner == null) { sessionTaskRunner = new TaskRunnerFactory("ActiveMQ Session Task", ThreadPriorities.INBOUND_CLIENT_SESSION, false, 1000, isUseDedicatedTaskRunner()); } } return sessionTaskRunner; } public void setSessionTaskRunner(TaskRunnerFactory sessionTaskRunner) { this.sessionTaskRunner = sessionTaskRunner; } public MessageTransformer getTransformer() { return transformer; } /** * Sets the transformer used to transform messages before they are sent on * to the JMS bus or when they are received from the bus but before they are * delivered to the JMS client */ public void setTransformer(MessageTransformer transformer) { this.transformer = transformer; } /** * @return the statsEnabled */ public boolean isStatsEnabled() { return this.stats.isEnabled(); } /** * @param statsEnabled the statsEnabled to set */ public void setStatsEnabled(boolean statsEnabled) { this.stats.setEnabled(statsEnabled); } /** * Returns the {@link DestinationSource} object which can be used to listen to destinations * being created or destroyed or to enquire about the current destinations available on the broker * * @return a lazily created destination source * @throws JMSException */ public DestinationSource getDestinationSource() throws JMSException { if (destinationSource == null) { destinationSource = new DestinationSource(this); destinationSource.start(); } return destinationSource; } // Implementation methods // ------------------------------------------------------------------------- /** * Used internally for adding Sessions to the Connection * * @param session * @throws JMSException * @throws JMSException */ protected void addSession(ActiveMQSession session) throws JMSException { this.sessions.add(session); if (sessions.size() > 1 || session.isTransacted()) { optimizedMessageDispatch = false; } } /** * Used interanlly for removing Sessions from a Connection * * @param session */ protected void removeSession(ActiveMQSession session) { this.sessions.remove(session); this.removeDispatcher(session); } /** * Add a ConnectionConsumer * * @param connectionConsumer * @throws JMSException */ protected void addConnectionConsumer(ActiveMQConnectionConsumer connectionConsumer) throws JMSException { this.connectionConsumers.add(connectionConsumer); } /** * Remove a ConnectionConsumer * * @param connectionConsumer */ protected void removeConnectionConsumer(ActiveMQConnectionConsumer connectionConsumer) { this.connectionConsumers.remove(connectionConsumer); this.removeDispatcher(connectionConsumer); } /** * Creates a <CODE>TopicSession</CODE> object. * * @param transacted indicates whether the session is transacted * @param acknowledgeMode indicates whether the consumer or the client will * acknowledge any messages it receives; ignored if the * session is transacted. Legal values are * <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, and * <code>Session.DUPS_OK_ACKNOWLEDGE</code>. * @return a newly created topic session * @throws JMSException if the <CODE>TopicConnection</CODE> object fails * to create a session due to some internal error or lack of * support for the specific transaction and acknowledgement * mode. * @see Session#AUTO_ACKNOWLEDGE * @see Session#CLIENT_ACKNOWLEDGE * @see Session#DUPS_OK_ACKNOWLEDGE */ public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException { return new ActiveMQTopicSession((ActiveMQSession)createSession(transacted, acknowledgeMode)); } /** * Creates a connection consumer for this connection (optional operation). * This is an expert facility not used by regular JMS clients. * * @param topic the topic to access * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the connection consumer * @throws JMSException if the <CODE>TopicConnection</CODE> object fails * to create a connection consumer due to some internal * error or invalid arguments for <CODE>sessionPool</CODE> * and <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid topic is * specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer */ public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return createConnectionConsumer(topic, messageSelector, sessionPool, maxMessages, false); } /** * Creates a connection consumer for this connection (optional operation). * This is an expert facility not used by regular JMS clients. * * @param queue the queue to access * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the connection consumer * @throws JMSException if the <CODE>QueueConnection</CODE> object fails * to create a connection consumer due to some internal * error or invalid arguments for <CODE>sessionPool</CODE> * and <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid queue is * specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer */ public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return createConnectionConsumer(queue, messageSelector, sessionPool, maxMessages, false); } /** * Creates a connection consumer for this connection (optional operation). * This is an expert facility not used by regular JMS clients. * * @param destination the destination to access * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the connection consumer * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a connection consumer due to some internal error * or invalid arguments for <CODE>sessionPool</CODE> and * <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid destination * is specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer * @since 1.1 */ public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return createConnectionConsumer(destination, messageSelector, sessionPool, maxMessages, false); } public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, ServerSessionPool sessionPool, int maxMessages, boolean noLocal) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); ConsumerId consumerId = createConsumerId(); ConsumerInfo consumerInfo = new ConsumerInfo(consumerId); consumerInfo.setDestination(ActiveMQMessageTransformation.transformDestination(destination)); consumerInfo.setSelector(messageSelector); consumerInfo.setPrefetchSize(maxMessages); consumerInfo.setNoLocal(noLocal); consumerInfo.setDispatchAsync(isDispatchAsync()); // Allows the options on the destination to configure the consumerInfo if (consumerInfo.getDestination().getOptions() != null) { Map<String, String> options = new HashMap<String, String>(consumerInfo.getDestination().getOptions()); IntrospectionSupport.setProperties(consumerInfo, options, "consumer."); } return new ActiveMQConnectionConsumer(this, sessionPool, consumerInfo); } /** * @return */ private ConsumerId createConsumerId() { return new ConsumerId(connectionSessionId, consumerIdGenerator.getNextSequenceId()); } /** * @return */ private ProducerId createProducerId() { return new ProducerId(connectionSessionId, producerIdGenerator.getNextSequenceId()); } /** * Creates a <CODE>QueueSession</CODE> object. * * @param transacted indicates whether the session is transacted * @param acknowledgeMode indicates whether the consumer or the client will * acknowledge any messages it receives; ignored if the * session is transacted. Legal values are * <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, and * <code>Session.DUPS_OK_ACKNOWLEDGE</code>. * @return a newly created queue session * @throws JMSException if the <CODE>QueueConnection</CODE> object fails * to create a session due to some internal error or lack of * support for the specific transaction and acknowledgement * mode. * @see Session#AUTO_ACKNOWLEDGE * @see Session#CLIENT_ACKNOWLEDGE * @see Session#DUPS_OK_ACKNOWLEDGE */ public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException { return new ActiveMQQueueSession((ActiveMQSession)createSession(transacted, acknowledgeMode)); } /** * Ensures that the clientID was manually specified and not auto-generated. * If the clientID was not specified this method will throw an exception. * This method is used to ensure that the clientID + durableSubscriber name * are used correctly. * * @throws JMSException */ public void checkClientIDWasManuallySpecified() throws JMSException { if (!userSpecifiedClientID) { throw new JMSException("You cannot create a durable subscriber without specifying a unique clientID on a Connection"); } } /** * send a Packet through the Connection - for internal use only * * @param command * @throws JMSException */ public void asyncSendPacket(Command command) throws JMSException { if (isClosed()) { throw new ConnectionClosedException(); } else { doAsyncSendPacket(command); } } private void doAsyncSendPacket(Command command) throws JMSException { try { this.transport.oneway(command); } catch (IOException e) { throw JMSExceptionSupport.create(e); } } /** * Send a packet through a Connection - for internal use only * * @param command * @return * @throws JMSException */ public Response syncSendPacket(Command command) throws JMSException { if (isClosed()) { throw new ConnectionClosedException(); } else { try { Response response = (Response)this.transport.request(command); if (response.isException()) { ExceptionResponse er = (ExceptionResponse)response; if (er.getException() instanceof JMSException) { throw (JMSException)er.getException(); } else { if (isClosed()||closing.get()) { LOG.debug("Received an exception but connection is closing"); } JMSException jmsEx = null; try { jmsEx = JMSExceptionSupport.create(er.getException()); }catch(Throwable e) { LOG.error("Caught an exception trying to create a JMSException for " +er.getException(),e); } //dispose of transport for security exceptions if (er.getException() instanceof SecurityException){ Transport t = this.transport; if (null != t){ ServiceSupport.dispose(t); } if(jmsEx !=null) { throw jmsEx; } } } } return response; } catch (IOException e) { throw JMSExceptionSupport.create(e); } } } /** * Send a packet through a Connection - for internal use only * * @param command * @return * @throws JMSException */ public Response syncSendPacket(Command command, int timeout) throws JMSException { if (isClosed() || closing.get()) { throw new ConnectionClosedException(); } else { return doSyncSendPacket(command, timeout); } } private Response doSyncSendPacket(Command command, int timeout) throws JMSException { try { Response response = (Response) (timeout > 0 ? this.transport.request(command, timeout) : this.transport.request(command)); if (response != null && response.isException()) { ExceptionResponse er = (ExceptionResponse)response; if (er.getException() instanceof JMSException) { throw (JMSException)er.getException(); } else { throw JMSExceptionSupport.create(er.getException()); } } return response; } catch (IOException e) { throw JMSExceptionSupport.create(e); } } /** * @return statistics for this Connection */ public StatsImpl getStats() { return stats; } /** * simply throws an exception if the Connection is already closed or the * Transport has failed * * @throws JMSException */ protected synchronized void checkClosedOrFailed() throws JMSException { checkClosed(); if (transportFailed.get()) { throw new ConnectionFailedException(firstFailureError); } } /** * simply throws an exception if the Connection is already closed * * @throws JMSException */ protected synchronized void checkClosed() throws JMSException { if (closed.get()) { throw new ConnectionClosedException(); } } /** * Send the ConnectionInfo to the Broker * * @throws JMSException */ protected void ensureConnectionInfoSent() throws JMSException { synchronized(this.ensureConnectionInfoSentMutex) { // Can we skip sending the ConnectionInfo packet?? if (isConnectionInfoSentToBroker || closed.get()) { return; } //TODO shouldn't this check be on userSpecifiedClientID rather than the value of clientID? if (info.getClientId() == null || info.getClientId().trim().length() == 0) { info.setClientId(clientIdGenerator.generateId()); } syncSendPacket(info.copy()); this.isConnectionInfoSentToBroker = true; // Add a temp destination advisory consumer so that // We know what the valid temporary destinations are on the // broker without having to do an RPC to the broker. ConsumerId consumerId = new ConsumerId(new SessionId(info.getConnectionId(), -1), consumerIdGenerator.getNextSequenceId()); if (watchTopicAdvisories) { advisoryConsumer = new AdvisoryConsumer(this, consumerId); } } } public synchronized boolean isWatchTopicAdvisories() { return watchTopicAdvisories; } public synchronized void setWatchTopicAdvisories(boolean watchTopicAdvisories) { this.watchTopicAdvisories = watchTopicAdvisories; } /** * @return Returns the useAsyncSend. */ public boolean isUseAsyncSend() { return useAsyncSend; } /** * Forces the use of <a * href="http://activemq.apache.org/async-sends.html">Async Sends</a> which * adds a massive performance boost; but means that the send() method will * return immediately whether the message has been sent or not which could * lead to message loss. */ public void setUseAsyncSend(boolean useAsyncSend) { this.useAsyncSend = useAsyncSend; } /** * @return true if always sync send messages */ public boolean isAlwaysSyncSend() { return this.alwaysSyncSend; } /** * Set true if always require messages to be sync sent * * @param alwaysSyncSend */ public void setAlwaysSyncSend(boolean alwaysSyncSend) { this.alwaysSyncSend = alwaysSyncSend; } /** * @return the messagePrioritySupported */ public boolean isMessagePrioritySupported() { return this.messagePrioritySupported; } /** * @param messagePrioritySupported the messagePrioritySupported to set */ public void setMessagePrioritySupported(boolean messagePrioritySupported) { this.messagePrioritySupported = messagePrioritySupported; } /** * Cleans up this connection so that it's state is as if the connection was * just created. This allows the Resource Adapter to clean up a connection * so that it can be reused without having to close and recreate the * connection. */ public void cleanup() throws JMSException { if (advisoryConsumer != null && !isTransportFailed()) { advisoryConsumer.dispose(); advisoryConsumer = null; } for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.dispose(); } for (Iterator<ActiveMQConnectionConsumer> i = this.connectionConsumers.iterator(); i.hasNext();) { ActiveMQConnectionConsumer c = i.next(); c.dispose(); } for (Iterator<ActiveMQInputStream> i = this.inputStreams.iterator(); i.hasNext();) { ActiveMQInputStream c = i.next(); c.dispose(); } for (Iterator<ActiveMQOutputStream> i = this.outputStreams.iterator(); i.hasNext();) { ActiveMQOutputStream c = i.next(); c.dispose(); } if (isConnectionInfoSentToBroker) { if (!transportFailed.get() && !closing.get()) { syncSendPacket(info.createRemoveCommand()); } isConnectionInfoSentToBroker = false; } if (userSpecifiedClientID) { info.setClientId(null); userSpecifiedClientID = false; } clientIDSet = false; started.set(false); } public void finalize() throws Throwable{ Scheduler s = this.scheduler; if (s != null){ s.stop(); } } /** * Changes the associated username/password that is associated with this * connection. If the connection has been used, you must called cleanup() * before calling this method. * * @throws IllegalStateException if the connection is in used. */ public void changeUserInfo(String userName, String password) throws JMSException { if (isConnectionInfoSentToBroker) { throw new IllegalStateException("changeUserInfo used Connection is not allowed"); } this.info.setUserName(userName); this.info.setPassword(password); } /** * @return Returns the resourceManagerId. * @throws JMSException */ public String getResourceManagerId() throws JMSException { waitForBrokerInfo(); if (brokerInfo == null) { throw new JMSException("Connection failed before Broker info was received."); } return brokerInfo.getBrokerId().getValue(); } /** * Returns the broker name if one is available or null if one is not * available yet. */ public String getBrokerName() { try { brokerInfoReceived.await(5, TimeUnit.SECONDS); if (brokerInfo == null) { return null; } return brokerInfo.getBrokerName(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } } /** * Returns the broker information if it is available or null if it is not * available yet. */ public BrokerInfo getBrokerInfo() { return brokerInfo; } /** * @return Returns the RedeliveryPolicy. * @throws JMSException */ public RedeliveryPolicy getRedeliveryPolicy() throws JMSException { return redeliveryPolicy; } /** * Sets the redelivery policy to be used when messages are rolled back */ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } public BlobTransferPolicy getBlobTransferPolicy() { if (blobTransferPolicy == null) { blobTransferPolicy = createBlobTransferPolicy(); } return blobTransferPolicy; } /** * Sets the policy used to describe how out-of-band BLOBs (Binary Large * OBjects) are transferred from producers to brokers to consumers */ public void setBlobTransferPolicy(BlobTransferPolicy blobTransferPolicy) { this.blobTransferPolicy = blobTransferPolicy; } /** * @return Returns the alwaysSessionAsync. */ public boolean isAlwaysSessionAsync() { return alwaysSessionAsync; } /** * If this flag is set then a separate thread is not used for dispatching * messages for each Session in the Connection. However, a separate thread * is always used if there is more than one session, or the session isn't in * auto acknowledge or duplicates ok mode */ public void setAlwaysSessionAsync(boolean alwaysSessionAsync) { this.alwaysSessionAsync = alwaysSessionAsync; } /** * @return Returns the optimizeAcknowledge. */ public boolean isOptimizeAcknowledge() { return optimizeAcknowledge; } /** * Enables an optimised acknowledgement mode where messages are acknowledged * in batches rather than individually * * @param optimizeAcknowledge The optimizeAcknowledge to set. */ public void setOptimizeAcknowledge(boolean optimizeAcknowledge) { this.optimizeAcknowledge = optimizeAcknowledge; } /** * The max time in milliseconds between optimized ack batches * @param optimizeAcknowledgeTimeOut */ public void setOptimizeAcknowledgeTimeOut(long optimizeAcknowledgeTimeOut) { this.optimizeAcknowledgeTimeOut = optimizeAcknowledgeTimeOut; } public long getOptimizeAcknowledgeTimeOut() { return optimizeAcknowledgeTimeOut; } public long getWarnAboutUnstartedConnectionTimeout() { return warnAboutUnstartedConnectionTimeout; } /** * Enables the timeout from a connection creation to when a warning is * generated if the connection is not properly started via {@link #start()} * and a message is received by a consumer. It is a very common gotcha to * forget to <a * href="http://activemq.apache.org/i-am-not-receiving-any-messages-what-is-wrong.html">start * the connection</a> so this option makes the default case to create a * warning if the user forgets. To disable the warning just set the value to < * 0 (say -1). */ public void setWarnAboutUnstartedConnectionTimeout(long warnAboutUnstartedConnectionTimeout) { this.warnAboutUnstartedConnectionTimeout = warnAboutUnstartedConnectionTimeout; } /** * @return the sendTimeout */ public int getSendTimeout() { return sendTimeout; } /** * @param sendTimeout the sendTimeout to set */ public void setSendTimeout(int sendTimeout) { this.sendTimeout = sendTimeout; } /** * @return the sendAcksAsync */ public boolean isSendAcksAsync() { return sendAcksAsync; } /** * @param sendAcksAsync the sendAcksAsync to set */ public void setSendAcksAsync(boolean sendAcksAsync) { this.sendAcksAsync = sendAcksAsync; } /** * Returns the time this connection was created */ public long getTimeCreated() { return timeCreated; } private void waitForBrokerInfo() throws JMSException { try { brokerInfoReceived.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw JMSExceptionSupport.create(e); } } // Package protected so that it can be used in unit tests public Transport getTransport() { return transport; } public void addProducer(ProducerId producerId, ActiveMQMessageProducer producer) { producers.put(producerId, producer); } public void removeProducer(ProducerId producerId) { producers.remove(producerId); } public void addDispatcher(ConsumerId consumerId, ActiveMQDispatcher dispatcher) { dispatchers.put(consumerId, dispatcher); } public void removeDispatcher(ConsumerId consumerId) { dispatchers.remove(consumerId); } /** * @param o - the command to consume */ public void onCommand(final Object o) { final Command command = (Command)o; if (!closed.get() && command != null) { try { command.visit(new CommandVisitorAdapter() { @Override public Response processMessageDispatch(MessageDispatch md) throws Exception { waitForTransportInterruptionProcessingToComplete(); ActiveMQDispatcher dispatcher = dispatchers.get(md.getConsumerId()); if (dispatcher != null) { // Copy in case a embedded broker is dispatching via // vm:// // md.getMessage() == null to signal end of queue // browse. Message msg = md.getMessage(); if (msg != null) { msg = msg.copy(); msg.setReadOnlyBody(true); msg.setReadOnlyProperties(true); msg.setRedeliveryCounter(md.getRedeliveryCounter()); msg.setConnection(ActiveMQConnection.this); md.setMessage(msg); } dispatcher.dispatch(md); } return null; } @Override public Response processProducerAck(ProducerAck pa) throws Exception { if (pa != null && pa.getProducerId() != null) { ActiveMQMessageProducer producer = producers.get(pa.getProducerId()); if (producer != null) { producer.onProducerAck(pa); } } return null; } @Override public Response processBrokerInfo(BrokerInfo info) throws Exception { brokerInfo = info; brokerInfoReceived.countDown(); optimizeAcknowledge &= !brokerInfo.isFaultTolerantConfiguration(); getBlobTransferPolicy().setBrokerUploadUrl(info.getBrokerUploadUrl()); return null; } @Override public Response processConnectionError(final ConnectionError error) throws Exception { executor.execute(new Runnable() { public void run() { onAsyncException(error.getException()); } }); return null; } @Override public Response processControlCommand(ControlCommand command) throws Exception { onControlCommand(command); return null; } @Override public Response processConnectionControl(ConnectionControl control) throws Exception { onConnectionControl((ConnectionControl)command); return null; } @Override public Response processConsumerControl(ConsumerControl control) throws Exception { onConsumerControl((ConsumerControl)command); return null; } @Override public Response processWireFormat(WireFormatInfo info) throws Exception { onWireFormatInfo((WireFormatInfo)command); return null; } }); } catch (Exception e) { onClientInternalException(e); } } for (Iterator<TransportListener> iter = transportListeners.iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.onCommand(command); } } protected void onWireFormatInfo(WireFormatInfo info) { protocolVersion.set(info.getVersion()); } /** * Handles async client internal exceptions. * A client internal exception is usually one that has been thrown * by a container runtime component during asynchronous processing of a * message that does not affect the connection itself. * This method notifies the <code>ClientInternalExceptionListener</code> by invoking * its <code>onException</code> method, if one has been registered with this connection. * * @param error the exception that the problem */ public void onClientInternalException(final Throwable error) { if ( !closed.get() && !closing.get() ) { if ( this.clientInternalExceptionListener != null ) { executor.execute(new Runnable() { public void run() { ActiveMQConnection.this.clientInternalExceptionListener.onException(error); } }); } else { LOG.debug("Async client internal exception occurred with no exception listener registered: " + error, error); } } } /** * Used for handling async exceptions * * @param error */ public void onAsyncException(Throwable error) { if (!closed.get() && !closing.get()) { if (this.exceptionListener != null) { if (!(error instanceof JMSException)) { error = JMSExceptionSupport.create(error); } final JMSException e = (JMSException)error; executor.execute(new Runnable() { public void run() { ActiveMQConnection.this.exceptionListener.onException(e); } }); } else { LOG.debug("Async exception with no exception listener: " + error, error); } } } public void onException(final IOException error) { onAsyncException(error); if (!closing.get() && !closed.get()) { executor.execute(new Runnable() { public void run() { transportFailed(error); ServiceSupport.dispose(ActiveMQConnection.this.transport); brokerInfoReceived.countDown(); try { cleanup(); } catch (JMSException e) { LOG.warn("Exception during connection cleanup, " + e, e); } for (Iterator<TransportListener> iter = transportListeners .iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.onException(error); } } }); } } public void transportInterupted() { this.transportInterruptionProcessingComplete = new CountDownLatch(dispatchers.size() - (advisoryConsumer != null ? 1:0)); if (LOG.isDebugEnabled()) { LOG.debug("transport interrupted, dispatchers: " + transportInterruptionProcessingComplete.getCount()); } signalInterruptionProcessingNeeded(); for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.clearMessagesInProgress(); } for (ActiveMQConnectionConsumer connectionConsumer : this.connectionConsumers) { connectionConsumer.clearMessagesInProgress(); } for (Iterator<TransportListener> iter = transportListeners.iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.transportInterupted(); } } public void transportResumed() { for (Iterator<TransportListener> iter = transportListeners.iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.transportResumed(); } } /** * Create the DestinationInfo object for the temporary destination. * * @param topic - if its true topic, else queue. * @return DestinationInfo * @throws JMSException */ protected ActiveMQTempDestination createTempDestination(boolean topic) throws JMSException { // Check if Destination info is of temporary type. ActiveMQTempDestination dest; if (topic) { dest = new ActiveMQTempTopic(info.getConnectionId(), tempDestinationIdGenerator.getNextSequenceId()); } else { dest = new ActiveMQTempQueue(info.getConnectionId(), tempDestinationIdGenerator.getNextSequenceId()); } DestinationInfo info = new DestinationInfo(); info.setConnectionId(this.info.getConnectionId()); info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); info.setDestination(dest); syncSendPacket(info); dest.setConnection(this); activeTempDestinations.put(dest, dest); return dest; } /** * @param destination * @throws JMSException */ public void deleteTempDestination(ActiveMQTempDestination destination) throws JMSException { checkClosedOrFailed(); for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); if (s.isInUse(destination)) { throw new JMSException("A consumer is consuming from the temporary destination"); } } activeTempDestinations.remove(destination); DestinationInfo destInfo = new DestinationInfo(); destInfo.setConnectionId(this.info.getConnectionId()); destInfo.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE); destInfo.setDestination(destination); destInfo.setTimeout(0); syncSendPacket(destInfo); } public boolean isDeleted(ActiveMQDestination dest) { // If we are not watching the advisories.. then // we will assume that the temp destination does exist. if (advisoryConsumer == null) { return false; } return !activeTempDestinations.contains(dest); } public boolean isCopyMessageOnSend() { return copyMessageOnSend; } public LongSequenceGenerator getLocalTransactionIdGenerator() { return localTransactionIdGenerator; } public boolean isUseCompression() { return useCompression; } /** * Enables the use of compression of the message bodies */ public void setUseCompression(boolean useCompression) { this.useCompression = useCompression; } public void destroyDestination(ActiveMQDestination destination) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); DestinationInfo info = new DestinationInfo(); info.setConnectionId(this.info.getConnectionId()); info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE); info.setDestination(destination); info.setTimeout(0); syncSendPacket(info); } public boolean isDispatchAsync() { return dispatchAsync; } /** * Enables or disables the default setting of whether or not consumers have * their messages <a * href="http://activemq.apache.org/consumer-dispatch-async.html">dispatched * synchronously or asynchronously by the broker</a>. For non-durable * topics for example we typically dispatch synchronously by default to * minimize context switches which boost performance. However sometimes its * better to go slower to ensure that a single blocked consumer socket does * not block delivery to other consumers. * * @param asyncDispatch If true then consumers created on this connection * will default to having their messages dispatched * asynchronously. The default value is false. */ public void setDispatchAsync(boolean asyncDispatch) { this.dispatchAsync = asyncDispatch; } public boolean isObjectMessageSerializationDefered() { return objectMessageSerializationDefered; } /** * When an object is set on an ObjectMessage, the JMS spec requires the * object to be serialized by that set method. Enabling this flag causes the * object to not get serialized. The object may subsequently get serialized * if the message needs to be sent over a socket or stored to disk. */ public void setObjectMessageSerializationDefered(boolean objectMessageSerializationDefered) { this.objectMessageSerializationDefered = objectMessageSerializationDefered; } public InputStream createInputStream(Destination dest) throws JMSException { return createInputStream(dest, null); } public InputStream createInputStream(Destination dest, String messageSelector) throws JMSException { return createInputStream(dest, messageSelector, false); } public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal) throws JMSException { return createInputStream(dest, messageSelector, noLocal, -1); } public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal, long timeout) throws JMSException { return doCreateInputStream(dest, messageSelector, noLocal, null, timeout); } public InputStream createDurableInputStream(Topic dest, String name) throws JMSException { return createInputStream(dest, null, false); } public InputStream createDurableInputStream(Topic dest, String name, String messageSelector) throws JMSException { return createDurableInputStream(dest, name, messageSelector, false); } public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal) throws JMSException { return createDurableInputStream(dest, name, messageSelector, noLocal, -1); } public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal, long timeout) throws JMSException { return doCreateInputStream(dest, messageSelector, noLocal, name, timeout); } private InputStream doCreateInputStream(Destination dest, String messageSelector, boolean noLocal, String subName, long timeout) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); return new ActiveMQInputStream(this, createConsumerId(), ActiveMQDestination.transform(dest), messageSelector, noLocal, subName, prefetchPolicy.getInputStreamPrefetch(), timeout); } /** * Creates a persistent output stream; individual messages will be written * to disk/database by the broker */ public OutputStream createOutputStream(Destination dest) throws JMSException { return createOutputStream(dest, null, ActiveMQMessage.DEFAULT_DELIVERY_MODE, ActiveMQMessage.DEFAULT_PRIORITY, ActiveMQMessage.DEFAULT_TIME_TO_LIVE); } /** * Creates a non persistent output stream; messages will not be written to * disk */ public OutputStream createNonPersistentOutputStream(Destination dest) throws JMSException { return createOutputStream(dest, null, DeliveryMode.NON_PERSISTENT, ActiveMQMessage.DEFAULT_PRIORITY, ActiveMQMessage.DEFAULT_TIME_TO_LIVE); } /** * Creates an output stream allowing full control over the delivery mode, * the priority and time to live of the messages and the properties added to * messages on the stream. * * @param streamProperties defines a map of key-value pairs where the keys * are strings and the values are primitive values (numbers * and strings) which are appended to the messages similarly * to using the * {@link javax.jms.Message#setObjectProperty(String, Object)} * method */ public OutputStream createOutputStream(Destination dest, Map<String, Object> streamProperties, int deliveryMode, int priority, long timeToLive) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); return new ActiveMQOutputStream(this, createProducerId(), ActiveMQDestination.transform(dest), streamProperties, deliveryMode, priority, timeToLive); } /** * Unsubscribes a durable subscription that has been created by a client. * <P> * This method deletes the state being maintained on behalf of the * subscriber by its provider. * <P> * It is erroneous for a client to delete a durable subscription while there * is an active <CODE>MessageConsumer </CODE> or * <CODE>TopicSubscriber</CODE> for the subscription, or while a consumed * message is part of a pending transaction or has not been acknowledged in * the session. * * @param name the name used to identify this subscription * @throws JMSException if the session fails to unsubscribe to the durable * subscription due to some internal error. * @throws InvalidDestinationException if an invalid subscription name is * specified. * @since 1.1 */ public void unsubscribe(String name) throws InvalidDestinationException, JMSException { checkClosedOrFailed(); RemoveSubscriptionInfo rsi = new RemoveSubscriptionInfo(); rsi.setConnectionId(getConnectionInfo().getConnectionId()); rsi.setSubscriptionName(name); rsi.setClientId(getConnectionInfo().getClientId()); syncSendPacket(rsi); } /** * Internal send method optimized: - It does not copy the message - It can * only handle ActiveMQ messages. - You can specify if the send is async or * sync - Does not allow you to send /w a transaction. */ void send(ActiveMQDestination destination, ActiveMQMessage msg, MessageId messageId, int deliveryMode, int priority, long timeToLive, boolean async) throws JMSException { checkClosedOrFailed(); if (destination.isTemporary() && isDeleted(destination)) { throw new JMSException("Cannot publish to a deleted Destination: " + destination); } msg.setJMSDestination(destination); msg.setJMSDeliveryMode(deliveryMode); long expiration = 0L; if (!isDisableTimeStampsByDefault()) { long timeStamp = System.currentTimeMillis(); msg.setJMSTimestamp(timeStamp); if (timeToLive > 0) { expiration = timeToLive + timeStamp; } } msg.setJMSExpiration(expiration); msg.setJMSPriority(priority); msg.setJMSRedelivered(false); msg.setMessageId(messageId); msg.onSend(); msg.setProducerId(msg.getMessageId().getProducerId()); if (LOG.isDebugEnabled()) { LOG.debug("Sending message: " + msg); } if (async) { asyncSendPacket(msg); } else { syncSendPacket(msg); } } public void addOutputStream(ActiveMQOutputStream stream) { outputStreams.add(stream); } public void removeOutputStream(ActiveMQOutputStream stream) { outputStreams.remove(stream); } public void addInputStream(ActiveMQInputStream stream) { inputStreams.add(stream); } public void removeInputStream(ActiveMQInputStream stream) { inputStreams.remove(stream); } protected void onControlCommand(ControlCommand command) { String text = command.getCommand(); if (text != null) { if ("shutdown".equals(text)) { LOG.info("JVM told to shutdown"); System.exit(0); } if (false && "close".equals(text)){ LOG.error("Broker " + getBrokerInfo() + "shutdown connection"); try { close(); } catch (JMSException e) { } } } } protected void onConnectionControl(ConnectionControl command) { if (command.isFaultTolerant()) { this.optimizeAcknowledge = false; for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.setOptimizeAcknowledge(false); } } } protected void onConsumerControl(ConsumerControl command) { if (command.isClose()) { for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.close(command.getConsumerId()); } } else { for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.setPrefetchSize(command.getConsumerId(), command.getPrefetch()); } } } protected void transportFailed(IOException error) { transportFailed.set(true); if (firstFailureError == null) { firstFailureError = error; } } /** * Should a JMS message be copied to a new JMS Message object as part of the * send() method in JMS. This is enabled by default to be compliant with the * JMS specification. You can disable it if you do not mutate JMS messages * after they are sent for a performance boost */ public void setCopyMessageOnSend(boolean copyMessageOnSend) { this.copyMessageOnSend = copyMessageOnSend; } @Override public String toString() { return "ActiveMQConnection {id=" + info.getConnectionId() + ",clientId=" + info.getClientId() + ",started=" + started.get() + "}"; } protected BlobTransferPolicy createBlobTransferPolicy() { return new BlobTransferPolicy(); } public int getProtocolVersion() { return protocolVersion.get(); } public int getProducerWindowSize() { return producerWindowSize; } public void setProducerWindowSize(int producerWindowSize) { this.producerWindowSize = producerWindowSize; } public void setAuditDepth(int auditDepth) { connectionAudit.setAuditDepth(auditDepth); } public void setAuditMaximumProducerNumber(int auditMaximumProducerNumber) { connectionAudit.setAuditMaximumProducerNumber(auditMaximumProducerNumber); } protected void removeDispatcher(ActiveMQDispatcher dispatcher) { connectionAudit.removeDispatcher(dispatcher); } protected boolean isDuplicate(ActiveMQDispatcher dispatcher, Message message) { return checkForDuplicates && connectionAudit.isDuplicate(dispatcher, message); } protected void rollbackDuplicate(ActiveMQDispatcher dispatcher, Message message) { connectionAudit.rollbackDuplicate(dispatcher, message); } public IOException getFirstFailureError() { return firstFailureError; } protected void waitForTransportInterruptionProcessingToComplete() throws InterruptedException { CountDownLatch cdl = this.transportInterruptionProcessingComplete; if (cdl != null) { if (!closed.get() && !transportFailed.get() && cdl.getCount()>0) { LOG.warn("dispatch paused, waiting for outstanding dispatch interruption processing (" + cdl.getCount() + ") to complete.."); cdl.await(10, TimeUnit.SECONDS); } signalInterruptionProcessingComplete(); } } protected void transportInterruptionProcessingComplete() { CountDownLatch cdl = this.transportInterruptionProcessingComplete; if (cdl != null) { cdl.countDown(); try { signalInterruptionProcessingComplete(); } catch (InterruptedException ignored) {} } } private void signalInterruptionProcessingComplete() throws InterruptedException { CountDownLatch cdl = this.transportInterruptionProcessingComplete; if (cdl.getCount()==0) { if (LOG.isDebugEnabled()) { LOG.debug("transportInterruptionProcessingComplete for: " + this.getConnectionInfo().getConnectionId()); } this.transportInterruptionProcessingComplete = null; FailoverTransport failoverTransport = transport.narrow(FailoverTransport.class); if (failoverTransport != null) { failoverTransport.connectionInterruptProcessingComplete(this.getConnectionInfo().getConnectionId()); if (LOG.isDebugEnabled()) { LOG.debug("notified failover transport (" + failoverTransport + ") of interruption completion for: " + this.getConnectionInfo().getConnectionId()); } } } } private void signalInterruptionProcessingNeeded() { FailoverTransport failoverTransport = transport.narrow(FailoverTransport.class); if (failoverTransport != null) { failoverTransport.getStateTracker().transportInterrupted(this.getConnectionInfo().getConnectionId()); if (LOG.isDebugEnabled()) { LOG.debug("notified failover transport (" + failoverTransport + ") of pending interruption processing for: " + this.getConnectionInfo().getConnectionId()); } } } /* * specify the amount of time in milliseconds that a consumer with a transaction pending recovery * will wait to receive re dispatched messages. * default value is 0 so there is no wait by default. */ public void setConsumerFailoverRedeliveryWaitPeriod(long consumerFailoverRedeliveryWaitPeriod) { this.consumerFailoverRedeliveryWaitPeriod = consumerFailoverRedeliveryWaitPeriod; } public long getConsumerFailoverRedeliveryWaitPeriod() { return consumerFailoverRedeliveryWaitPeriod; } protected Scheduler getScheduler() { return this.scheduler; } protected ThreadPoolExecutor getExecutor() { return this.executor; } /** * @return the checkForDuplicates */ public boolean isCheckForDuplicates() { return this.checkForDuplicates; } /** * @param checkForDuplicates the checkForDuplicates to set */ public void setCheckForDuplicates(boolean checkForDuplicates) { this.checkForDuplicates = checkForDuplicates; } public boolean isTransactedIndividualAck() { return transactedIndividualAck; } public void setTransactedIndividualAck(boolean transactedIndividualAck) { this.transactedIndividualAck = transactedIndividualAck; } public boolean isNonBlockingRedelivery() { return nonBlockingRedelivery; } public void setNonBlockingRedelivery(boolean nonBlockingRedelivery) { this.nonBlockingRedelivery = nonBlockingRedelivery; } /** * Removes any TempDestinations that this connection has cached, ignoring * any exceptions generated because the destination is in use as they should * not be removed. */ public void cleanUpTempDestinations() { if (this.activeTempDestinations == null || this.activeTempDestinations.isEmpty()) { return; } Iterator<ConcurrentHashMap.Entry<ActiveMQTempDestination, ActiveMQTempDestination>> entries = this.activeTempDestinations.entrySet().iterator(); while(entries.hasNext()) { ConcurrentHashMap.Entry<ActiveMQTempDestination, ActiveMQTempDestination> entry = entries.next(); try { // Only delete this temp destination if it was created from this connection. The connection used // for the advisory consumer may also have a reference to this temp destination. ActiveMQTempDestination dest = entry.getValue(); String thisConnectionId = (info.getConnectionId() == null) ? "" : info.getConnectionId().toString(); if (dest.getConnectionId() != null && dest.getConnectionId().equals(thisConnectionId)) { this.deleteTempDestination(entry.getValue()); } } catch (Exception ex) { // the temp dest is in use so it can not be deleted. // it is ok to leave it to connection tear down phase } } } }
activemq-core/src/main/java/org/apache/activemq/ActiveMQConnection.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.jms.Connection; import javax.jms.ConnectionConsumer; import javax.jms.ConnectionMetaData; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.ExceptionListener; import javax.jms.IllegalStateException; import javax.jms.InvalidDestinationException; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueSession; import javax.jms.ServerSessionPool; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicSession; import javax.jms.XAConnection; import org.apache.activemq.advisory.DestinationSource; import org.apache.activemq.blob.BlobTransferPolicy; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQTempDestination; import org.apache.activemq.command.ActiveMQTempQueue; import org.apache.activemq.command.ActiveMQTempTopic; import org.apache.activemq.command.BrokerInfo; import org.apache.activemq.command.Command; import org.apache.activemq.command.CommandTypes; import org.apache.activemq.command.ConnectionControl; import org.apache.activemq.command.ConnectionError; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConsumerControl; import org.apache.activemq.command.ConsumerId; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.ControlCommand; import org.apache.activemq.command.DestinationInfo; import org.apache.activemq.command.ExceptionResponse; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.ProducerAck; import org.apache.activemq.command.ProducerId; import org.apache.activemq.command.RemoveInfo; import org.apache.activemq.command.RemoveSubscriptionInfo; import org.apache.activemq.command.Response; import org.apache.activemq.command.SessionId; import org.apache.activemq.command.ShutdownInfo; import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.management.JMSConnectionStatsImpl; import org.apache.activemq.management.JMSStatsImpl; import org.apache.activemq.management.StatsCapable; import org.apache.activemq.management.StatsImpl; import org.apache.activemq.state.CommandVisitorAdapter; import org.apache.activemq.thread.Scheduler; import org.apache.activemq.thread.TaskRunnerFactory; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportListener; import org.apache.activemq.transport.failover.FailoverTransport; import org.apache.activemq.util.IdGenerator; import org.apache.activemq.util.IntrospectionSupport; import org.apache.activemq.util.JMSExceptionSupport; import org.apache.activemq.util.LongSequenceGenerator; import org.apache.activemq.util.ServiceSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActiveMQConnection implements Connection, TopicConnection, QueueConnection, StatsCapable, Closeable, StreamConnection, TransportListener, EnhancedConnection { public static final String DEFAULT_USER = ActiveMQConnectionFactory.DEFAULT_USER; public static final String DEFAULT_PASSWORD = ActiveMQConnectionFactory.DEFAULT_PASSWORD; public static final String DEFAULT_BROKER_URL = ActiveMQConnectionFactory.DEFAULT_BROKER_URL; private static final Logger LOG = LoggerFactory.getLogger(ActiveMQConnection.class); public final ConcurrentHashMap<ActiveMQTempDestination, ActiveMQTempDestination> activeTempDestinations = new ConcurrentHashMap<ActiveMQTempDestination, ActiveMQTempDestination>(); protected boolean dispatchAsync=true; protected boolean alwaysSessionAsync = true; private TaskRunnerFactory sessionTaskRunner; private final ThreadPoolExecutor executor; // Connection state variables private final ConnectionInfo info; private ExceptionListener exceptionListener; private ClientInternalExceptionListener clientInternalExceptionListener; private boolean clientIDSet; private boolean isConnectionInfoSentToBroker; private boolean userSpecifiedClientID; // Configuration options variables private ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); private BlobTransferPolicy blobTransferPolicy; private RedeliveryPolicy redeliveryPolicy; private MessageTransformer transformer; private boolean disableTimeStampsByDefault; private boolean optimizedMessageDispatch = true; private boolean copyMessageOnSend = true; private boolean useCompression; private boolean objectMessageSerializationDefered; private boolean useAsyncSend; private boolean optimizeAcknowledge; private long optimizeAcknowledgeTimeOut = 0; private boolean nestedMapAndListEnabled = true; private boolean useRetroactiveConsumer; private boolean exclusiveConsumer; private boolean alwaysSyncSend; private int closeTimeout = 15000; private boolean watchTopicAdvisories = true; private long warnAboutUnstartedConnectionTimeout = 500L; private int sendTimeout =0; private boolean sendAcksAsync=true; private boolean checkForDuplicates = true; private final Transport transport; private final IdGenerator clientIdGenerator; private final JMSStatsImpl factoryStats; private final JMSConnectionStatsImpl stats; private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicBoolean closing = new AtomicBoolean(false); private final AtomicBoolean closed = new AtomicBoolean(false); private final AtomicBoolean transportFailed = new AtomicBoolean(false); private final CopyOnWriteArrayList<ActiveMQSession> sessions = new CopyOnWriteArrayList<ActiveMQSession>(); private final CopyOnWriteArrayList<ActiveMQConnectionConsumer> connectionConsumers = new CopyOnWriteArrayList<ActiveMQConnectionConsumer>(); private final CopyOnWriteArrayList<ActiveMQInputStream> inputStreams = new CopyOnWriteArrayList<ActiveMQInputStream>(); private final CopyOnWriteArrayList<ActiveMQOutputStream> outputStreams = new CopyOnWriteArrayList<ActiveMQOutputStream>(); private final CopyOnWriteArrayList<TransportListener> transportListeners = new CopyOnWriteArrayList<TransportListener>(); // Maps ConsumerIds to ActiveMQConsumer objects private final ConcurrentHashMap<ConsumerId, ActiveMQDispatcher> dispatchers = new ConcurrentHashMap<ConsumerId, ActiveMQDispatcher>(); private final ConcurrentHashMap<ProducerId, ActiveMQMessageProducer> producers = new ConcurrentHashMap<ProducerId, ActiveMQMessageProducer>(); private final LongSequenceGenerator sessionIdGenerator = new LongSequenceGenerator(); private final SessionId connectionSessionId; private final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator producerIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator tempDestinationIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator localTransactionIdGenerator = new LongSequenceGenerator(); private AdvisoryConsumer advisoryConsumer; private final CountDownLatch brokerInfoReceived = new CountDownLatch(1); private BrokerInfo brokerInfo; private IOException firstFailureError; private int producerWindowSize = ActiveMQConnectionFactory.DEFAULT_PRODUCER_WINDOW_SIZE; // Assume that protocol is the latest. Change to the actual protocol // version when a WireFormatInfo is received. private final AtomicInteger protocolVersion = new AtomicInteger(CommandTypes.PROTOCOL_VERSION); private final long timeCreated; private final ConnectionAudit connectionAudit = new ConnectionAudit(); private DestinationSource destinationSource; private final Object ensureConnectionInfoSentMutex = new Object(); private boolean useDedicatedTaskRunner; protected volatile CountDownLatch transportInterruptionProcessingComplete; private long consumerFailoverRedeliveryWaitPeriod; private final Scheduler scheduler; private boolean messagePrioritySupported = true; private boolean transactedIndividualAck = false; private boolean nonBlockingRedelivery = false; /** * Construct an <code>ActiveMQConnection</code> * * @param transport * @param factoryStats * @throws Exception */ protected ActiveMQConnection(final Transport transport, IdGenerator clientIdGenerator, IdGenerator connectionIdGenerator, JMSStatsImpl factoryStats) throws Exception { this.transport = transport; this.clientIdGenerator = clientIdGenerator; this.factoryStats = factoryStats; // Configure a single threaded executor who's core thread can timeout if // idle executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r, "ActiveMQ Connection Executor: " + transport); thread.setDaemon(true); return thread; } }); // asyncConnectionThread.allowCoreThreadTimeOut(true); String uniqueId = connectionIdGenerator.generateId(); this.info = new ConnectionInfo(new ConnectionId(uniqueId)); this.info.setManageable(true); this.info.setFaultTolerant(transport.isFaultTolerant()); this.connectionSessionId = new SessionId(info.getConnectionId(), -1); this.transport.setTransportListener(this); this.stats = new JMSConnectionStatsImpl(sessions, this instanceof XAConnection); this.factoryStats.addConnection(this); this.timeCreated = System.currentTimeMillis(); this.connectionAudit.setCheckForDuplicates(transport.isFaultTolerant()); this.scheduler = new Scheduler("ActiveMQConnection["+uniqueId+"] Scheduler"); this.scheduler.start(); } protected void setUserName(String userName) { this.info.setUserName(userName); } protected void setPassword(String password) { this.info.setPassword(password); } /** * A static helper method to create a new connection * * @return an ActiveMQConnection * @throws JMSException */ public static ActiveMQConnection makeConnection() throws JMSException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); return (ActiveMQConnection)factory.createConnection(); } /** * A static helper method to create a new connection * * @param uri * @return and ActiveMQConnection * @throws JMSException */ public static ActiveMQConnection makeConnection(String uri) throws JMSException, URISyntaxException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri); return (ActiveMQConnection)factory.createConnection(); } /** * A static helper method to create a new connection * * @param user * @param password * @param uri * @return an ActiveMQConnection * @throws JMSException */ public static ActiveMQConnection makeConnection(String user, String password, String uri) throws JMSException, URISyntaxException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, new URI(uri)); return (ActiveMQConnection)factory.createConnection(); } /** * @return a number unique for this connection */ public JMSConnectionStatsImpl getConnectionStats() { return stats; } /** * Creates a <CODE>Session</CODE> object. * * @param transacted indicates whether the session is transacted * @param acknowledgeMode indicates whether the consumer or the client will * acknowledge any messages it receives; ignored if the * session is transacted. Legal values are * <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, and * <code>Session.DUPS_OK_ACKNOWLEDGE</code>. * @return a newly created session * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a session due to some internal error or lack of * support for the specific transaction and acknowledgement * mode. * @see Session#AUTO_ACKNOWLEDGE * @see Session#CLIENT_ACKNOWLEDGE * @see Session#DUPS_OK_ACKNOWLEDGE * @since 1.1 */ public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); if(!transacted) { if (acknowledgeMode==Session.SESSION_TRANSACTED) { throw new JMSException("acknowledgeMode SESSION_TRANSACTED cannot be used for an non-transacted Session"); } else if (acknowledgeMode < Session.SESSION_TRANSACTED || acknowledgeMode > ActiveMQSession.MAX_ACK_CONSTANT) { throw new JMSException("invalid acknowledgeMode: " + acknowledgeMode + ". Valid values are Session.AUTO_ACKNOWLEDGE (1), " + "Session.CLIENT_ACKNOWLEDGE (2), Session.DUPS_OK_ACKNOWLEDGE (3), ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE (4) or for transacted sessions Session.SESSION_TRANSACTED (0)"); } } return new ActiveMQSession(this, getNextSessionId(), transacted ? Session.SESSION_TRANSACTED : (acknowledgeMode == Session.SESSION_TRANSACTED ? Session.AUTO_ACKNOWLEDGE : acknowledgeMode), isDispatchAsync(), isAlwaysSessionAsync()); } /** * @return sessionId */ protected SessionId getNextSessionId() { return new SessionId(info.getConnectionId(), sessionIdGenerator.getNextSequenceId()); } /** * Gets the client identifier for this connection. * <P> * This value is specific to the JMS provider. It is either preconfigured by * an administrator in a <CODE> ConnectionFactory</CODE> object or assigned * dynamically by the application by calling the <code>setClientID</code> * method. * * @return the unique client identifier * @throws JMSException if the JMS provider fails to return the client ID * for this connection due to some internal error. */ public String getClientID() throws JMSException { checkClosedOrFailed(); return this.info.getClientId(); } /** * Sets the client identifier for this connection. * <P> * The preferred way to assign a JMS client's client identifier is for it to * be configured in a client-specific <CODE>ConnectionFactory</CODE> * object and transparently assigned to the <CODE>Connection</CODE> object * it creates. * <P> * Alternatively, a client can set a connection's client identifier using a * provider-specific value. The facility to set a connection's client * identifier explicitly is not a mechanism for overriding the identifier * that has been administratively configured. It is provided for the case * where no administratively specified identifier exists. If one does exist, * an attempt to change it by setting it must throw an * <CODE>IllegalStateException</CODE>. If a client sets the client * identifier explicitly, it must do so immediately after it creates the * connection and before any other action on the connection is taken. After * this point, setting the client identifier is a programming error that * should throw an <CODE>IllegalStateException</CODE>. * <P> * The purpose of the client identifier is to associate a connection and its * objects with a state maintained on behalf of the client by a provider. * The only such state identified by the JMS API is that required to support * durable subscriptions. * <P> * If another connection with the same <code>clientID</code> is already * running when this method is called, the JMS provider should detect the * duplicate ID and throw an <CODE>InvalidClientIDException</CODE>. * * @param newClientID the unique client identifier * @throws JMSException if the JMS provider fails to set the client ID for * this connection due to some internal error. * @throws javax.jms.InvalidClientIDException if the JMS client specifies an * invalid or duplicate client ID. * @throws javax.jms.IllegalStateException if the JMS client attempts to set * a connection's client ID at the wrong time or when it has * been administratively configured. */ public void setClientID(String newClientID) throws JMSException { checkClosedOrFailed(); if (this.clientIDSet) { throw new IllegalStateException("The clientID has already been set"); } if (this.isConnectionInfoSentToBroker) { throw new IllegalStateException("Setting clientID on a used Connection is not allowed"); } this.info.setClientId(newClientID); this.userSpecifiedClientID = true; ensureConnectionInfoSent(); } /** * Sets the default client id that the connection will use if explicitly not * set with the setClientId() call. */ public void setDefaultClientID(String clientID) throws JMSException { this.info.setClientId(clientID); this.userSpecifiedClientID = true; } /** * Gets the metadata for this connection. * * @return the connection metadata * @throws JMSException if the JMS provider fails to get the connection * metadata for this connection. * @see javax.jms.ConnectionMetaData */ public ConnectionMetaData getMetaData() throws JMSException { checkClosedOrFailed(); return ActiveMQConnectionMetaData.INSTANCE; } /** * Gets the <CODE>ExceptionListener</CODE> object for this connection. Not * every <CODE>Connection</CODE> has an <CODE>ExceptionListener</CODE> * associated with it. * * @return the <CODE>ExceptionListener</CODE> for this connection, or * null, if no <CODE>ExceptionListener</CODE> is associated with * this connection. * @throws JMSException if the JMS provider fails to get the * <CODE>ExceptionListener</CODE> for this connection. * @see javax.jms.Connection#setExceptionListener(ExceptionListener) */ public ExceptionListener getExceptionListener() throws JMSException { checkClosedOrFailed(); return this.exceptionListener; } /** * Sets an exception listener for this connection. * <P> * If a JMS provider detects a serious problem with a connection, it informs * the connection's <CODE> ExceptionListener</CODE>, if one has been * registered. It does this by calling the listener's <CODE>onException * </CODE> * method, passing it a <CODE>JMSException</CODE> object describing the * problem. * <P> * An exception listener allows a client to be notified of a problem * asynchronously. Some connections only consume messages, so they would * have no other way to learn their connection has failed. * <P> * A connection serializes execution of its <CODE>ExceptionListener</CODE>. * <P> * A JMS provider should attempt to resolve connection problems itself * before it notifies the client of them. * * @param listener the exception listener * @throws JMSException if the JMS provider fails to set the exception * listener for this connection. */ public void setExceptionListener(ExceptionListener listener) throws JMSException { checkClosedOrFailed(); this.exceptionListener = listener; } /** * Gets the <code>ClientInternalExceptionListener</code> object for this connection. * Not every <CODE>ActiveMQConnectionn</CODE> has a <CODE>ClientInternalExceptionListener</CODE> * associated with it. * * @return the listener or <code>null</code> if no listener is registered with the connection. */ public ClientInternalExceptionListener getClientInternalExceptionListener() { return clientInternalExceptionListener; } /** * Sets a client internal exception listener for this connection. * The connection will notify the listener, if one has been registered, of exceptions thrown by container components * (e.g. an EJB container in case of Message Driven Beans) during asynchronous processing of a message. * It does this by calling the listener's <code>onException()</code> method passing it a <code>Throwable</code> * describing the problem. * * @param listener the exception listener */ public void setClientInternalExceptionListener(ClientInternalExceptionListener listener) { this.clientInternalExceptionListener = listener; } /** * Starts (or restarts) a connection's delivery of incoming messages. A call * to <CODE>start</CODE> on a connection that has already been started is * ignored. * * @throws JMSException if the JMS provider fails to start message delivery * due to some internal error. * @see javax.jms.Connection#stop() */ public void start() throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); if (started.compareAndSet(false, true)) { for (Iterator<ActiveMQSession> i = sessions.iterator(); i.hasNext();) { ActiveMQSession session = i.next(); session.start(); } } } /** * Temporarily stops a connection's delivery of incoming messages. Delivery * can be restarted using the connection's <CODE>start</CODE> method. When * the connection is stopped, delivery to all the connection's message * consumers is inhibited: synchronous receives block, and messages are not * delivered to message listeners. * <P> * This call blocks until receives and/or message listeners in progress have * completed. * <P> * Stopping a connection has no effect on its ability to send messages. A * call to <CODE>stop</CODE> on a connection that has already been stopped * is ignored. * <P> * A call to <CODE>stop</CODE> must not return until delivery of messages * has paused. This means that a client can rely on the fact that none of * its message listeners will be called and that all threads of control * waiting for <CODE>receive</CODE> calls to return will not return with a * message until the connection is restarted. The receive timers for a * stopped connection continue to advance, so receives may time out while * the connection is stopped. * <P> * If message listeners are running when <CODE>stop</CODE> is invoked, the * <CODE>stop</CODE> call must wait until all of them have returned before * it may return. While these message listeners are completing, they must * have the full services of the connection available to them. * * @throws JMSException if the JMS provider fails to stop message delivery * due to some internal error. * @see javax.jms.Connection#start() */ public void stop() throws JMSException { checkClosedOrFailed(); if (started.compareAndSet(true, false)) { synchronized(sessions) { for (Iterator<ActiveMQSession> i = sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.stop(); } } } } /** * Closes the connection. * <P> * Since a provider typically allocates significant resources outside the * JVM on behalf of a connection, clients should close these resources when * they are not needed. Relying on garbage collection to eventually reclaim * these resources may not be timely enough. * <P> * There is no need to close the sessions, producers, and consumers of a * closed connection. * <P> * Closing a connection causes all temporary destinations to be deleted. * <P> * When this method is invoked, it should not return until message * processing has been shut down in an orderly fashion. This means that all * message listeners that may have been running have returned, and that all * pending receives have returned. A close terminates all pending message * receives on the connection's sessions' consumers. The receives may return * with a message or with null, depending on whether there was a message * available at the time of the close. If one or more of the connection's * sessions' message listeners is processing a message at the time when * connection <CODE>close</CODE> is invoked, all the facilities of the * connection and its sessions must remain available to those listeners * until they return control to the JMS provider. * <P> * Closing a connection causes any of its sessions' transactions in progress * to be rolled back. In the case where a session's work is coordinated by * an external transaction manager, a session's <CODE>commit</CODE> and * <CODE> rollback</CODE> methods are not used and the result of a closed * session's work is determined later by the transaction manager. Closing a * connection does NOT force an acknowledgment of client-acknowledged * sessions. * <P> * Invoking the <CODE>acknowledge</CODE> method of a received message from * a closed connection's session must throw an * <CODE>IllegalStateException</CODE>. Closing a closed connection must * NOT throw an exception. * * @throws JMSException if the JMS provider fails to close the connection * due to some internal error. For example, a failure to * release resources or to close a socket connection can * cause this exception to be thrown. */ public void close() throws JMSException { // Store the interrupted state and clear so that cleanup happens without // leaking connection resources. Reset in finally to preserve state. boolean interrupted = Thread.interrupted(); try { // If we were running, lets stop first. if (!closed.get() && !transportFailed.get()) { stop(); } synchronized (this) { if (!closed.get()) { closing.set(true); if (destinationSource != null) { destinationSource.stop(); destinationSource = null; } if (advisoryConsumer != null) { advisoryConsumer.dispose(); advisoryConsumer = null; } if (this.scheduler != null) { try { this.scheduler.stop(); } catch (Exception e) { JMSException ex = JMSExceptionSupport.create(e); throw ex; } } long lastDeliveredSequenceId = 0; for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.dispose(); lastDeliveredSequenceId = Math.max(lastDeliveredSequenceId, s.getLastDeliveredSequenceId()); } for (Iterator<ActiveMQConnectionConsumer> i = this.connectionConsumers.iterator(); i.hasNext();) { ActiveMQConnectionConsumer c = i.next(); c.dispose(); } for (Iterator<ActiveMQInputStream> i = this.inputStreams.iterator(); i.hasNext();) { ActiveMQInputStream c = i.next(); c.dispose(); } for (Iterator<ActiveMQOutputStream> i = this.outputStreams.iterator(); i.hasNext();) { ActiveMQOutputStream c = i.next(); c.dispose(); } // As TemporaryQueue and TemporaryTopic instances are bound // to a connection we should just delete them after the connection // is closed to free up memory for (Iterator<ActiveMQTempDestination> i = this.activeTempDestinations.values().iterator(); i.hasNext();) { ActiveMQTempDestination c = i.next(); c.delete(); } if (isConnectionInfoSentToBroker) { // If we announced ourselfs to the broker.. Try to let // the broker // know that the connection is being shutdown. RemoveInfo removeCommand = info.createRemoveCommand(); removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId); doSyncSendPacket(info.createRemoveCommand(), closeTimeout); doAsyncSendPacket(new ShutdownInfo()); } started.set(false); // TODO if we move the TaskRunnerFactory to the connection // factory // then we may need to call // factory.onConnectionClose(this); if (sessionTaskRunner != null) { sessionTaskRunner.shutdown(); } closed.set(true); closing.set(false); } } } finally { try { if (executor != null) { executor.shutdown(); } } catch (Throwable e) { LOG.error("Error shutting down thread pool " + e, e); } ServiceSupport.dispose(this.transport); factoryStats.removeConnection(this); if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Tells the broker to terminate its VM. This can be used to cleanly * terminate a broker running in a standalone java process. Server must have * property enable.vm.shutdown=true defined to allow this to work. */ // TODO : org.apache.activemq.message.BrokerAdminCommand not yet // implemented. /* * public void terminateBrokerVM() throws JMSException { BrokerAdminCommand * command = new BrokerAdminCommand(); * command.setCommand(BrokerAdminCommand.SHUTDOWN_SERVER_VM); * asyncSendPacket(command); } */ /** * Create a durable connection consumer for this connection (optional * operation). This is an expert facility not used by regular JMS clients. * * @param topic topic to access * @param subscriptionName durable subscription name * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this durable * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the durable connection consumer * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a connection consumer due to some internal error * or invalid arguments for <CODE>sessionPool</CODE> and * <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid destination * is specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer * @since 1.1 */ public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return this.createDurableConnectionConsumer(topic, subscriptionName, messageSelector, sessionPool, maxMessages, false); } /** * Create a durable connection consumer for this connection (optional * operation). This is an expert facility not used by regular JMS clients. * * @param topic topic to access * @param subscriptionName durable subscription name * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this durable * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @param noLocal set true if you want to filter out messages published * locally * @return the durable connection consumer * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a connection consumer due to some internal error * or invalid arguments for <CODE>sessionPool</CODE> and * <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid destination * is specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer * @since 1.1 */ public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages, boolean noLocal) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); SessionId sessionId = new SessionId(info.getConnectionId(), -1); ConsumerInfo info = new ConsumerInfo(new ConsumerId(sessionId, consumerIdGenerator.getNextSequenceId())); info.setDestination(ActiveMQMessageTransformation.transformDestination(topic)); info.setSubscriptionName(subscriptionName); info.setSelector(messageSelector); info.setPrefetchSize(maxMessages); info.setDispatchAsync(isDispatchAsync()); // Allows the options on the destination to configure the consumerInfo if (info.getDestination().getOptions() != null) { Map<String, String> options = new HashMap<String, String>(info.getDestination().getOptions()); IntrospectionSupport.setProperties(this.info, options, "consumer."); } return new ActiveMQConnectionConsumer(this, sessionPool, info); } // Properties // ------------------------------------------------------------------------- /** * Returns true if this connection has been started * * @return true if this Connection is started */ public boolean isStarted() { return started.get(); } /** * Returns true if the connection is closed */ public boolean isClosed() { return closed.get(); } /** * Returns true if the connection is in the process of being closed */ public boolean isClosing() { return closing.get(); } /** * Returns true if the underlying transport has failed */ public boolean isTransportFailed() { return transportFailed.get(); } /** * @return Returns the prefetchPolicy. */ public ActiveMQPrefetchPolicy getPrefetchPolicy() { return prefetchPolicy; } /** * Sets the <a * href="http://activemq.apache.org/what-is-the-prefetch-limit-for.html">prefetch * policy</a> for consumers created by this connection. */ public void setPrefetchPolicy(ActiveMQPrefetchPolicy prefetchPolicy) { this.prefetchPolicy = prefetchPolicy; } /** */ public Transport getTransportChannel() { return transport; } /** * @return Returns the clientID of the connection, forcing one to be * generated if one has not yet been configured. */ public String getInitializedClientID() throws JMSException { ensureConnectionInfoSent(); return info.getClientId(); } /** * @return Returns the timeStampsDisableByDefault. */ public boolean isDisableTimeStampsByDefault() { return disableTimeStampsByDefault; } /** * Sets whether or not timestamps on messages should be disabled or not. If * you disable them it adds a small performance boost. */ public void setDisableTimeStampsByDefault(boolean timeStampsDisableByDefault) { this.disableTimeStampsByDefault = timeStampsDisableByDefault; } /** * @return Returns the dispatchOptimizedMessage. */ public boolean isOptimizedMessageDispatch() { return optimizedMessageDispatch; } /** * If this flag is set then an larger prefetch limit is used - only * applicable for durable topic subscribers. */ public void setOptimizedMessageDispatch(boolean dispatchOptimizedMessage) { this.optimizedMessageDispatch = dispatchOptimizedMessage; } /** * @return Returns the closeTimeout. */ public int getCloseTimeout() { return closeTimeout; } /** * Sets the timeout before a close is considered complete. Normally a * close() on a connection waits for confirmation from the broker; this * allows that operation to timeout to save the client hanging if there is * no broker */ public void setCloseTimeout(int closeTimeout) { this.closeTimeout = closeTimeout; } /** * @return ConnectionInfo */ public ConnectionInfo getConnectionInfo() { return this.info; } public boolean isUseRetroactiveConsumer() { return useRetroactiveConsumer; } /** * Sets whether or not retroactive consumers are enabled. Retroactive * consumers allow non-durable topic subscribers to receive old messages * that were published before the non-durable subscriber started. */ public void setUseRetroactiveConsumer(boolean useRetroactiveConsumer) { this.useRetroactiveConsumer = useRetroactiveConsumer; } public boolean isNestedMapAndListEnabled() { return nestedMapAndListEnabled; } /** * Enables/disables whether or not Message properties and MapMessage entries * support <a * href="http://activemq.apache.org/structured-message-properties-and-mapmessages.html">Nested * Structures</a> of Map and List objects */ public void setNestedMapAndListEnabled(boolean structuredMapsEnabled) { this.nestedMapAndListEnabled = structuredMapsEnabled; } public boolean isExclusiveConsumer() { return exclusiveConsumer; } /** * Enables or disables whether or not queue consumers should be exclusive or * not for example to preserve ordering when not using <a * href="http://activemq.apache.org/message-groups.html">Message Groups</a> * * @param exclusiveConsumer */ public void setExclusiveConsumer(boolean exclusiveConsumer) { this.exclusiveConsumer = exclusiveConsumer; } /** * Adds a transport listener so that a client can be notified of events in * the underlying transport */ public void addTransportListener(TransportListener transportListener) { transportListeners.add(transportListener); } public void removeTransportListener(TransportListener transportListener) { transportListeners.remove(transportListener); } public boolean isUseDedicatedTaskRunner() { return useDedicatedTaskRunner; } public void setUseDedicatedTaskRunner(boolean useDedicatedTaskRunner) { this.useDedicatedTaskRunner = useDedicatedTaskRunner; } public TaskRunnerFactory getSessionTaskRunner() { synchronized (this) { if (sessionTaskRunner == null) { sessionTaskRunner = new TaskRunnerFactory("ActiveMQ Session Task", ThreadPriorities.INBOUND_CLIENT_SESSION, false, 1000, isUseDedicatedTaskRunner()); } } return sessionTaskRunner; } public void setSessionTaskRunner(TaskRunnerFactory sessionTaskRunner) { this.sessionTaskRunner = sessionTaskRunner; } public MessageTransformer getTransformer() { return transformer; } /** * Sets the transformer used to transform messages before they are sent on * to the JMS bus or when they are received from the bus but before they are * delivered to the JMS client */ public void setTransformer(MessageTransformer transformer) { this.transformer = transformer; } /** * @return the statsEnabled */ public boolean isStatsEnabled() { return this.stats.isEnabled(); } /** * @param statsEnabled the statsEnabled to set */ public void setStatsEnabled(boolean statsEnabled) { this.stats.setEnabled(statsEnabled); } /** * Returns the {@link DestinationSource} object which can be used to listen to destinations * being created or destroyed or to enquire about the current destinations available on the broker * * @return a lazily created destination source * @throws JMSException */ public DestinationSource getDestinationSource() throws JMSException { if (destinationSource == null) { destinationSource = new DestinationSource(this); destinationSource.start(); } return destinationSource; } // Implementation methods // ------------------------------------------------------------------------- /** * Used internally for adding Sessions to the Connection * * @param session * @throws JMSException * @throws JMSException */ protected void addSession(ActiveMQSession session) throws JMSException { this.sessions.add(session); if (sessions.size() > 1 || session.isTransacted()) { optimizedMessageDispatch = false; } } /** * Used interanlly for removing Sessions from a Connection * * @param session */ protected void removeSession(ActiveMQSession session) { this.sessions.remove(session); this.removeDispatcher(session); } /** * Add a ConnectionConsumer * * @param connectionConsumer * @throws JMSException */ protected void addConnectionConsumer(ActiveMQConnectionConsumer connectionConsumer) throws JMSException { this.connectionConsumers.add(connectionConsumer); } /** * Remove a ConnectionConsumer * * @param connectionConsumer */ protected void removeConnectionConsumer(ActiveMQConnectionConsumer connectionConsumer) { this.connectionConsumers.remove(connectionConsumer); this.removeDispatcher(connectionConsumer); } /** * Creates a <CODE>TopicSession</CODE> object. * * @param transacted indicates whether the session is transacted * @param acknowledgeMode indicates whether the consumer or the client will * acknowledge any messages it receives; ignored if the * session is transacted. Legal values are * <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, and * <code>Session.DUPS_OK_ACKNOWLEDGE</code>. * @return a newly created topic session * @throws JMSException if the <CODE>TopicConnection</CODE> object fails * to create a session due to some internal error or lack of * support for the specific transaction and acknowledgement * mode. * @see Session#AUTO_ACKNOWLEDGE * @see Session#CLIENT_ACKNOWLEDGE * @see Session#DUPS_OK_ACKNOWLEDGE */ public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException { return new ActiveMQTopicSession((ActiveMQSession)createSession(transacted, acknowledgeMode)); } /** * Creates a connection consumer for this connection (optional operation). * This is an expert facility not used by regular JMS clients. * * @param topic the topic to access * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the connection consumer * @throws JMSException if the <CODE>TopicConnection</CODE> object fails * to create a connection consumer due to some internal * error or invalid arguments for <CODE>sessionPool</CODE> * and <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid topic is * specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer */ public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return createConnectionConsumer(topic, messageSelector, sessionPool, maxMessages, false); } /** * Creates a connection consumer for this connection (optional operation). * This is an expert facility not used by regular JMS clients. * * @param queue the queue to access * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the connection consumer * @throws JMSException if the <CODE>QueueConnection</CODE> object fails * to create a connection consumer due to some internal * error or invalid arguments for <CODE>sessionPool</CODE> * and <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid queue is * specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer */ public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return createConnectionConsumer(queue, messageSelector, sessionPool, maxMessages, false); } /** * Creates a connection consumer for this connection (optional operation). * This is an expert facility not used by regular JMS clients. * * @param destination the destination to access * @param messageSelector only messages with properties matching the message * selector expression are delivered. A value of null or an * empty string indicates that there is no message selector * for the message consumer. * @param sessionPool the server session pool to associate with this * connection consumer * @param maxMessages the maximum number of messages that can be assigned to * a server session at one time * @return the connection consumer * @throws JMSException if the <CODE>Connection</CODE> object fails to * create a connection consumer due to some internal error * or invalid arguments for <CODE>sessionPool</CODE> and * <CODE>messageSelector</CODE>. * @throws javax.jms.InvalidDestinationException if an invalid destination * is specified. * @throws javax.jms.InvalidSelectorException if the message selector is * invalid. * @see javax.jms.ConnectionConsumer * @since 1.1 */ public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { return createConnectionConsumer(destination, messageSelector, sessionPool, maxMessages, false); } public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, ServerSessionPool sessionPool, int maxMessages, boolean noLocal) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); ConsumerId consumerId = createConsumerId(); ConsumerInfo consumerInfo = new ConsumerInfo(consumerId); consumerInfo.setDestination(ActiveMQMessageTransformation.transformDestination(destination)); consumerInfo.setSelector(messageSelector); consumerInfo.setPrefetchSize(maxMessages); consumerInfo.setNoLocal(noLocal); consumerInfo.setDispatchAsync(isDispatchAsync()); // Allows the options on the destination to configure the consumerInfo if (consumerInfo.getDestination().getOptions() != null) { Map<String, String> options = new HashMap<String, String>(consumerInfo.getDestination().getOptions()); IntrospectionSupport.setProperties(consumerInfo, options, "consumer."); } return new ActiveMQConnectionConsumer(this, sessionPool, consumerInfo); } /** * @return */ private ConsumerId createConsumerId() { return new ConsumerId(connectionSessionId, consumerIdGenerator.getNextSequenceId()); } /** * @return */ private ProducerId createProducerId() { return new ProducerId(connectionSessionId, producerIdGenerator.getNextSequenceId()); } /** * Creates a <CODE>QueueSession</CODE> object. * * @param transacted indicates whether the session is transacted * @param acknowledgeMode indicates whether the consumer or the client will * acknowledge any messages it receives; ignored if the * session is transacted. Legal values are * <code>Session.AUTO_ACKNOWLEDGE</code>, * <code>Session.CLIENT_ACKNOWLEDGE</code>, and * <code>Session.DUPS_OK_ACKNOWLEDGE</code>. * @return a newly created queue session * @throws JMSException if the <CODE>QueueConnection</CODE> object fails * to create a session due to some internal error or lack of * support for the specific transaction and acknowledgement * mode. * @see Session#AUTO_ACKNOWLEDGE * @see Session#CLIENT_ACKNOWLEDGE * @see Session#DUPS_OK_ACKNOWLEDGE */ public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException { return new ActiveMQQueueSession((ActiveMQSession)createSession(transacted, acknowledgeMode)); } /** * Ensures that the clientID was manually specified and not auto-generated. * If the clientID was not specified this method will throw an exception. * This method is used to ensure that the clientID + durableSubscriber name * are used correctly. * * @throws JMSException */ public void checkClientIDWasManuallySpecified() throws JMSException { if (!userSpecifiedClientID) { throw new JMSException("You cannot create a durable subscriber without specifying a unique clientID on a Connection"); } } /** * send a Packet through the Connection - for internal use only * * @param command * @throws JMSException */ public void asyncSendPacket(Command command) throws JMSException { if (isClosed()) { throw new ConnectionClosedException(); } else { doAsyncSendPacket(command); } } private void doAsyncSendPacket(Command command) throws JMSException { try { this.transport.oneway(command); } catch (IOException e) { throw JMSExceptionSupport.create(e); } } /** * Send a packet through a Connection - for internal use only * * @param command * @return * @throws JMSException */ public Response syncSendPacket(Command command) throws JMSException { if (isClosed()) { throw new ConnectionClosedException(); } else { try { Response response = (Response)this.transport.request(command); if (response.isException()) { ExceptionResponse er = (ExceptionResponse)response; if (er.getException() instanceof JMSException) { throw (JMSException)er.getException(); } else { if (isClosed()||closing.get()) { LOG.debug("Received an exception but connection is closing"); } JMSException jmsEx = null; try { jmsEx = JMSExceptionSupport.create(er.getException()); }catch(Throwable e) { LOG.error("Caught an exception trying to create a JMSException for " +er.getException(),e); } //dispose of transport Transport t = this.transport; if (null != t){ ServiceSupport.dispose(t); } if(jmsEx !=null) { throw jmsEx; } } } return response; } catch (IOException e) { throw JMSExceptionSupport.create(e); } } } /** * Send a packet through a Connection - for internal use only * * @param command * @return * @throws JMSException */ public Response syncSendPacket(Command command, int timeout) throws JMSException { if (isClosed() || closing.get()) { throw new ConnectionClosedException(); } else { return doSyncSendPacket(command, timeout); } } private Response doSyncSendPacket(Command command, int timeout) throws JMSException { try { Response response = (Response) (timeout > 0 ? this.transport.request(command, timeout) : this.transport.request(command)); if (response != null && response.isException()) { ExceptionResponse er = (ExceptionResponse)response; if (er.getException() instanceof JMSException) { throw (JMSException)er.getException(); } else { throw JMSExceptionSupport.create(er.getException()); } } return response; } catch (IOException e) { throw JMSExceptionSupport.create(e); } } /** * @return statistics for this Connection */ public StatsImpl getStats() { return stats; } /** * simply throws an exception if the Connection is already closed or the * Transport has failed * * @throws JMSException */ protected synchronized void checkClosedOrFailed() throws JMSException { checkClosed(); if (transportFailed.get()) { throw new ConnectionFailedException(firstFailureError); } } /** * simply throws an exception if the Connection is already closed * * @throws JMSException */ protected synchronized void checkClosed() throws JMSException { if (closed.get()) { throw new ConnectionClosedException(); } } /** * Send the ConnectionInfo to the Broker * * @throws JMSException */ protected void ensureConnectionInfoSent() throws JMSException { synchronized(this.ensureConnectionInfoSentMutex) { // Can we skip sending the ConnectionInfo packet?? if (isConnectionInfoSentToBroker || closed.get()) { return; } //TODO shouldn't this check be on userSpecifiedClientID rather than the value of clientID? if (info.getClientId() == null || info.getClientId().trim().length() == 0) { info.setClientId(clientIdGenerator.generateId()); } syncSendPacket(info.copy()); this.isConnectionInfoSentToBroker = true; // Add a temp destination advisory consumer so that // We know what the valid temporary destinations are on the // broker without having to do an RPC to the broker. ConsumerId consumerId = new ConsumerId(new SessionId(info.getConnectionId(), -1), consumerIdGenerator.getNextSequenceId()); if (watchTopicAdvisories) { advisoryConsumer = new AdvisoryConsumer(this, consumerId); } } } public synchronized boolean isWatchTopicAdvisories() { return watchTopicAdvisories; } public synchronized void setWatchTopicAdvisories(boolean watchTopicAdvisories) { this.watchTopicAdvisories = watchTopicAdvisories; } /** * @return Returns the useAsyncSend. */ public boolean isUseAsyncSend() { return useAsyncSend; } /** * Forces the use of <a * href="http://activemq.apache.org/async-sends.html">Async Sends</a> which * adds a massive performance boost; but means that the send() method will * return immediately whether the message has been sent or not which could * lead to message loss. */ public void setUseAsyncSend(boolean useAsyncSend) { this.useAsyncSend = useAsyncSend; } /** * @return true if always sync send messages */ public boolean isAlwaysSyncSend() { return this.alwaysSyncSend; } /** * Set true if always require messages to be sync sent * * @param alwaysSyncSend */ public void setAlwaysSyncSend(boolean alwaysSyncSend) { this.alwaysSyncSend = alwaysSyncSend; } /** * @return the messagePrioritySupported */ public boolean isMessagePrioritySupported() { return this.messagePrioritySupported; } /** * @param messagePrioritySupported the messagePrioritySupported to set */ public void setMessagePrioritySupported(boolean messagePrioritySupported) { this.messagePrioritySupported = messagePrioritySupported; } /** * Cleans up this connection so that it's state is as if the connection was * just created. This allows the Resource Adapter to clean up a connection * so that it can be reused without having to close and recreate the * connection. */ public void cleanup() throws JMSException { if (advisoryConsumer != null && !isTransportFailed()) { advisoryConsumer.dispose(); advisoryConsumer = null; } for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.dispose(); } for (Iterator<ActiveMQConnectionConsumer> i = this.connectionConsumers.iterator(); i.hasNext();) { ActiveMQConnectionConsumer c = i.next(); c.dispose(); } for (Iterator<ActiveMQInputStream> i = this.inputStreams.iterator(); i.hasNext();) { ActiveMQInputStream c = i.next(); c.dispose(); } for (Iterator<ActiveMQOutputStream> i = this.outputStreams.iterator(); i.hasNext();) { ActiveMQOutputStream c = i.next(); c.dispose(); } if (isConnectionInfoSentToBroker) { if (!transportFailed.get() && !closing.get()) { syncSendPacket(info.createRemoveCommand()); } isConnectionInfoSentToBroker = false; } if (userSpecifiedClientID) { info.setClientId(null); userSpecifiedClientID = false; } clientIDSet = false; started.set(false); } public void finalize() throws Throwable{ if (scheduler != null){ scheduler.stop(); } } /** * Changes the associated username/password that is associated with this * connection. If the connection has been used, you must called cleanup() * before calling this method. * * @throws IllegalStateException if the connection is in used. */ public void changeUserInfo(String userName, String password) throws JMSException { if (isConnectionInfoSentToBroker) { throw new IllegalStateException("changeUserInfo used Connection is not allowed"); } this.info.setUserName(userName); this.info.setPassword(password); } /** * @return Returns the resourceManagerId. * @throws JMSException */ public String getResourceManagerId() throws JMSException { waitForBrokerInfo(); if (brokerInfo == null) { throw new JMSException("Connection failed before Broker info was received."); } return brokerInfo.getBrokerId().getValue(); } /** * Returns the broker name if one is available or null if one is not * available yet. */ public String getBrokerName() { try { brokerInfoReceived.await(5, TimeUnit.SECONDS); if (brokerInfo == null) { return null; } return brokerInfo.getBrokerName(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } } /** * Returns the broker information if it is available or null if it is not * available yet. */ public BrokerInfo getBrokerInfo() { return brokerInfo; } /** * @return Returns the RedeliveryPolicy. * @throws JMSException */ public RedeliveryPolicy getRedeliveryPolicy() throws JMSException { return redeliveryPolicy; } /** * Sets the redelivery policy to be used when messages are rolled back */ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } public BlobTransferPolicy getBlobTransferPolicy() { if (blobTransferPolicy == null) { blobTransferPolicy = createBlobTransferPolicy(); } return blobTransferPolicy; } /** * Sets the policy used to describe how out-of-band BLOBs (Binary Large * OBjects) are transferred from producers to brokers to consumers */ public void setBlobTransferPolicy(BlobTransferPolicy blobTransferPolicy) { this.blobTransferPolicy = blobTransferPolicy; } /** * @return Returns the alwaysSessionAsync. */ public boolean isAlwaysSessionAsync() { return alwaysSessionAsync; } /** * If this flag is set then a separate thread is not used for dispatching * messages for each Session in the Connection. However, a separate thread * is always used if there is more than one session, or the session isn't in * auto acknowledge or duplicates ok mode */ public void setAlwaysSessionAsync(boolean alwaysSessionAsync) { this.alwaysSessionAsync = alwaysSessionAsync; } /** * @return Returns the optimizeAcknowledge. */ public boolean isOptimizeAcknowledge() { return optimizeAcknowledge; } /** * Enables an optimised acknowledgement mode where messages are acknowledged * in batches rather than individually * * @param optimizeAcknowledge The optimizeAcknowledge to set. */ public void setOptimizeAcknowledge(boolean optimizeAcknowledge) { this.optimizeAcknowledge = optimizeAcknowledge; } /** * The max time in milliseconds between optimized ack batches * @param optimizeAcknowledgeTimeOut */ public void setOptimizeAcknowledgeTimeOut(long optimizeAcknowledgeTimeOut) { this.optimizeAcknowledgeTimeOut = optimizeAcknowledgeTimeOut; } public long getOptimizeAcknowledgeTimeOut() { return optimizeAcknowledgeTimeOut; } public long getWarnAboutUnstartedConnectionTimeout() { return warnAboutUnstartedConnectionTimeout; } /** * Enables the timeout from a connection creation to when a warning is * generated if the connection is not properly started via {@link #start()} * and a message is received by a consumer. It is a very common gotcha to * forget to <a * href="http://activemq.apache.org/i-am-not-receiving-any-messages-what-is-wrong.html">start * the connection</a> so this option makes the default case to create a * warning if the user forgets. To disable the warning just set the value to < * 0 (say -1). */ public void setWarnAboutUnstartedConnectionTimeout(long warnAboutUnstartedConnectionTimeout) { this.warnAboutUnstartedConnectionTimeout = warnAboutUnstartedConnectionTimeout; } /** * @return the sendTimeout */ public int getSendTimeout() { return sendTimeout; } /** * @param sendTimeout the sendTimeout to set */ public void setSendTimeout(int sendTimeout) { this.sendTimeout = sendTimeout; } /** * @return the sendAcksAsync */ public boolean isSendAcksAsync() { return sendAcksAsync; } /** * @param sendAcksAsync the sendAcksAsync to set */ public void setSendAcksAsync(boolean sendAcksAsync) { this.sendAcksAsync = sendAcksAsync; } /** * Returns the time this connection was created */ public long getTimeCreated() { return timeCreated; } private void waitForBrokerInfo() throws JMSException { try { brokerInfoReceived.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw JMSExceptionSupport.create(e); } } // Package protected so that it can be used in unit tests public Transport getTransport() { return transport; } public void addProducer(ProducerId producerId, ActiveMQMessageProducer producer) { producers.put(producerId, producer); } public void removeProducer(ProducerId producerId) { producers.remove(producerId); } public void addDispatcher(ConsumerId consumerId, ActiveMQDispatcher dispatcher) { dispatchers.put(consumerId, dispatcher); } public void removeDispatcher(ConsumerId consumerId) { dispatchers.remove(consumerId); } /** * @param o - the command to consume */ public void onCommand(final Object o) { final Command command = (Command)o; if (!closed.get() && command != null) { try { command.visit(new CommandVisitorAdapter() { @Override public Response processMessageDispatch(MessageDispatch md) throws Exception { waitForTransportInterruptionProcessingToComplete(); ActiveMQDispatcher dispatcher = dispatchers.get(md.getConsumerId()); if (dispatcher != null) { // Copy in case a embedded broker is dispatching via // vm:// // md.getMessage() == null to signal end of queue // browse. Message msg = md.getMessage(); if (msg != null) { msg = msg.copy(); msg.setReadOnlyBody(true); msg.setReadOnlyProperties(true); msg.setRedeliveryCounter(md.getRedeliveryCounter()); msg.setConnection(ActiveMQConnection.this); md.setMessage(msg); } dispatcher.dispatch(md); } return null; } @Override public Response processProducerAck(ProducerAck pa) throws Exception { if (pa != null && pa.getProducerId() != null) { ActiveMQMessageProducer producer = producers.get(pa.getProducerId()); if (producer != null) { producer.onProducerAck(pa); } } return null; } @Override public Response processBrokerInfo(BrokerInfo info) throws Exception { brokerInfo = info; brokerInfoReceived.countDown(); optimizeAcknowledge &= !brokerInfo.isFaultTolerantConfiguration(); getBlobTransferPolicy().setBrokerUploadUrl(info.getBrokerUploadUrl()); return null; } @Override public Response processConnectionError(final ConnectionError error) throws Exception { executor.execute(new Runnable() { public void run() { onAsyncException(error.getException()); } }); return null; } @Override public Response processControlCommand(ControlCommand command) throws Exception { onControlCommand(command); return null; } @Override public Response processConnectionControl(ConnectionControl control) throws Exception { onConnectionControl((ConnectionControl)command); return null; } @Override public Response processConsumerControl(ConsumerControl control) throws Exception { onConsumerControl((ConsumerControl)command); return null; } @Override public Response processWireFormat(WireFormatInfo info) throws Exception { onWireFormatInfo((WireFormatInfo)command); return null; } }); } catch (Exception e) { onClientInternalException(e); } } for (Iterator<TransportListener> iter = transportListeners.iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.onCommand(command); } } protected void onWireFormatInfo(WireFormatInfo info) { protocolVersion.set(info.getVersion()); } /** * Handles async client internal exceptions. * A client internal exception is usually one that has been thrown * by a container runtime component during asynchronous processing of a * message that does not affect the connection itself. * This method notifies the <code>ClientInternalExceptionListener</code> by invoking * its <code>onException</code> method, if one has been registered with this connection. * * @param error the exception that the problem */ public void onClientInternalException(final Throwable error) { if ( !closed.get() && !closing.get() ) { if ( this.clientInternalExceptionListener != null ) { executor.execute(new Runnable() { public void run() { ActiveMQConnection.this.clientInternalExceptionListener.onException(error); } }); } else { LOG.debug("Async client internal exception occurred with no exception listener registered: " + error, error); } } } /** * Used for handling async exceptions * * @param error */ public void onAsyncException(Throwable error) { if (!closed.get() && !closing.get()) { if (this.exceptionListener != null) { if (!(error instanceof JMSException)) { error = JMSExceptionSupport.create(error); } final JMSException e = (JMSException)error; executor.execute(new Runnable() { public void run() { ActiveMQConnection.this.exceptionListener.onException(e); } }); } else { LOG.debug("Async exception with no exception listener: " + error, error); } } } public void onException(final IOException error) { onAsyncException(error); if (!closing.get() && !closed.get()) { executor.execute(new Runnable() { public void run() { transportFailed(error); ServiceSupport.dispose(ActiveMQConnection.this.transport); brokerInfoReceived.countDown(); try { cleanup(); } catch (JMSException e) { LOG.warn("Exception during connection cleanup, " + e, e); } for (Iterator<TransportListener> iter = transportListeners .iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.onException(error); } } }); } } public void transportInterupted() { this.transportInterruptionProcessingComplete = new CountDownLatch(dispatchers.size() - (advisoryConsumer != null ? 1:0)); if (LOG.isDebugEnabled()) { LOG.debug("transport interrupted, dispatchers: " + transportInterruptionProcessingComplete.getCount()); } signalInterruptionProcessingNeeded(); for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.clearMessagesInProgress(); } for (ActiveMQConnectionConsumer connectionConsumer : this.connectionConsumers) { connectionConsumer.clearMessagesInProgress(); } for (Iterator<TransportListener> iter = transportListeners.iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.transportInterupted(); } } public void transportResumed() { for (Iterator<TransportListener> iter = transportListeners.iterator(); iter.hasNext();) { TransportListener listener = iter.next(); listener.transportResumed(); } } /** * Create the DestinationInfo object for the temporary destination. * * @param topic - if its true topic, else queue. * @return DestinationInfo * @throws JMSException */ protected ActiveMQTempDestination createTempDestination(boolean topic) throws JMSException { // Check if Destination info is of temporary type. ActiveMQTempDestination dest; if (topic) { dest = new ActiveMQTempTopic(info.getConnectionId(), tempDestinationIdGenerator.getNextSequenceId()); } else { dest = new ActiveMQTempQueue(info.getConnectionId(), tempDestinationIdGenerator.getNextSequenceId()); } DestinationInfo info = new DestinationInfo(); info.setConnectionId(this.info.getConnectionId()); info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); info.setDestination(dest); syncSendPacket(info); dest.setConnection(this); activeTempDestinations.put(dest, dest); return dest; } /** * @param destination * @throws JMSException */ public void deleteTempDestination(ActiveMQTempDestination destination) throws JMSException { checkClosedOrFailed(); for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); if (s.isInUse(destination)) { throw new JMSException("A consumer is consuming from the temporary destination"); } } activeTempDestinations.remove(destination); DestinationInfo destInfo = new DestinationInfo(); destInfo.setConnectionId(this.info.getConnectionId()); destInfo.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE); destInfo.setDestination(destination); destInfo.setTimeout(0); syncSendPacket(destInfo); } public boolean isDeleted(ActiveMQDestination dest) { // If we are not watching the advisories.. then // we will assume that the temp destination does exist. if (advisoryConsumer == null) { return false; } return !activeTempDestinations.contains(dest); } public boolean isCopyMessageOnSend() { return copyMessageOnSend; } public LongSequenceGenerator getLocalTransactionIdGenerator() { return localTransactionIdGenerator; } public boolean isUseCompression() { return useCompression; } /** * Enables the use of compression of the message bodies */ public void setUseCompression(boolean useCompression) { this.useCompression = useCompression; } public void destroyDestination(ActiveMQDestination destination) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); DestinationInfo info = new DestinationInfo(); info.setConnectionId(this.info.getConnectionId()); info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE); info.setDestination(destination); info.setTimeout(0); syncSendPacket(info); } public boolean isDispatchAsync() { return dispatchAsync; } /** * Enables or disables the default setting of whether or not consumers have * their messages <a * href="http://activemq.apache.org/consumer-dispatch-async.html">dispatched * synchronously or asynchronously by the broker</a>. For non-durable * topics for example we typically dispatch synchronously by default to * minimize context switches which boost performance. However sometimes its * better to go slower to ensure that a single blocked consumer socket does * not block delivery to other consumers. * * @param asyncDispatch If true then consumers created on this connection * will default to having their messages dispatched * asynchronously. The default value is false. */ public void setDispatchAsync(boolean asyncDispatch) { this.dispatchAsync = asyncDispatch; } public boolean isObjectMessageSerializationDefered() { return objectMessageSerializationDefered; } /** * When an object is set on an ObjectMessage, the JMS spec requires the * object to be serialized by that set method. Enabling this flag causes the * object to not get serialized. The object may subsequently get serialized * if the message needs to be sent over a socket or stored to disk. */ public void setObjectMessageSerializationDefered(boolean objectMessageSerializationDefered) { this.objectMessageSerializationDefered = objectMessageSerializationDefered; } public InputStream createInputStream(Destination dest) throws JMSException { return createInputStream(dest, null); } public InputStream createInputStream(Destination dest, String messageSelector) throws JMSException { return createInputStream(dest, messageSelector, false); } public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal) throws JMSException { return createInputStream(dest, messageSelector, noLocal, -1); } public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal, long timeout) throws JMSException { return doCreateInputStream(dest, messageSelector, noLocal, null, timeout); } public InputStream createDurableInputStream(Topic dest, String name) throws JMSException { return createInputStream(dest, null, false); } public InputStream createDurableInputStream(Topic dest, String name, String messageSelector) throws JMSException { return createDurableInputStream(dest, name, messageSelector, false); } public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal) throws JMSException { return createDurableInputStream(dest, name, messageSelector, noLocal, -1); } public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal, long timeout) throws JMSException { return doCreateInputStream(dest, messageSelector, noLocal, name, timeout); } private InputStream doCreateInputStream(Destination dest, String messageSelector, boolean noLocal, String subName, long timeout) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); return new ActiveMQInputStream(this, createConsumerId(), ActiveMQDestination.transform(dest), messageSelector, noLocal, subName, prefetchPolicy.getInputStreamPrefetch(), timeout); } /** * Creates a persistent output stream; individual messages will be written * to disk/database by the broker */ public OutputStream createOutputStream(Destination dest) throws JMSException { return createOutputStream(dest, null, ActiveMQMessage.DEFAULT_DELIVERY_MODE, ActiveMQMessage.DEFAULT_PRIORITY, ActiveMQMessage.DEFAULT_TIME_TO_LIVE); } /** * Creates a non persistent output stream; messages will not be written to * disk */ public OutputStream createNonPersistentOutputStream(Destination dest) throws JMSException { return createOutputStream(dest, null, DeliveryMode.NON_PERSISTENT, ActiveMQMessage.DEFAULT_PRIORITY, ActiveMQMessage.DEFAULT_TIME_TO_LIVE); } /** * Creates an output stream allowing full control over the delivery mode, * the priority and time to live of the messages and the properties added to * messages on the stream. * * @param streamProperties defines a map of key-value pairs where the keys * are strings and the values are primitive values (numbers * and strings) which are appended to the messages similarly * to using the * {@link javax.jms.Message#setObjectProperty(String, Object)} * method */ public OutputStream createOutputStream(Destination dest, Map<String, Object> streamProperties, int deliveryMode, int priority, long timeToLive) throws JMSException { checkClosedOrFailed(); ensureConnectionInfoSent(); return new ActiveMQOutputStream(this, createProducerId(), ActiveMQDestination.transform(dest), streamProperties, deliveryMode, priority, timeToLive); } /** * Unsubscribes a durable subscription that has been created by a client. * <P> * This method deletes the state being maintained on behalf of the * subscriber by its provider. * <P> * It is erroneous for a client to delete a durable subscription while there * is an active <CODE>MessageConsumer </CODE> or * <CODE>TopicSubscriber</CODE> for the subscription, or while a consumed * message is part of a pending transaction or has not been acknowledged in * the session. * * @param name the name used to identify this subscription * @throws JMSException if the session fails to unsubscribe to the durable * subscription due to some internal error. * @throws InvalidDestinationException if an invalid subscription name is * specified. * @since 1.1 */ public void unsubscribe(String name) throws InvalidDestinationException, JMSException { checkClosedOrFailed(); RemoveSubscriptionInfo rsi = new RemoveSubscriptionInfo(); rsi.setConnectionId(getConnectionInfo().getConnectionId()); rsi.setSubscriptionName(name); rsi.setClientId(getConnectionInfo().getClientId()); syncSendPacket(rsi); } /** * Internal send method optimized: - It does not copy the message - It can * only handle ActiveMQ messages. - You can specify if the send is async or * sync - Does not allow you to send /w a transaction. */ void send(ActiveMQDestination destination, ActiveMQMessage msg, MessageId messageId, int deliveryMode, int priority, long timeToLive, boolean async) throws JMSException { checkClosedOrFailed(); if (destination.isTemporary() && isDeleted(destination)) { throw new JMSException("Cannot publish to a deleted Destination: " + destination); } msg.setJMSDestination(destination); msg.setJMSDeliveryMode(deliveryMode); long expiration = 0L; if (!isDisableTimeStampsByDefault()) { long timeStamp = System.currentTimeMillis(); msg.setJMSTimestamp(timeStamp); if (timeToLive > 0) { expiration = timeToLive + timeStamp; } } msg.setJMSExpiration(expiration); msg.setJMSPriority(priority); msg.setJMSRedelivered(false); msg.setMessageId(messageId); msg.onSend(); msg.setProducerId(msg.getMessageId().getProducerId()); if (LOG.isDebugEnabled()) { LOG.debug("Sending message: " + msg); } if (async) { asyncSendPacket(msg); } else { syncSendPacket(msg); } } public void addOutputStream(ActiveMQOutputStream stream) { outputStreams.add(stream); } public void removeOutputStream(ActiveMQOutputStream stream) { outputStreams.remove(stream); } public void addInputStream(ActiveMQInputStream stream) { inputStreams.add(stream); } public void removeInputStream(ActiveMQInputStream stream) { inputStreams.remove(stream); } protected void onControlCommand(ControlCommand command) { String text = command.getCommand(); if (text != null) { if ("shutdown".equals(text)) { LOG.info("JVM told to shutdown"); System.exit(0); } if (false && "close".equals(text)){ LOG.error("Broker " + getBrokerInfo() + "shutdown connection"); try { close(); } catch (JMSException e) { } } } } protected void onConnectionControl(ConnectionControl command) { if (command.isFaultTolerant()) { this.optimizeAcknowledge = false; for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.setOptimizeAcknowledge(false); } } } protected void onConsumerControl(ConsumerControl command) { if (command.isClose()) { for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.close(command.getConsumerId()); } } else { for (Iterator<ActiveMQSession> i = this.sessions.iterator(); i.hasNext();) { ActiveMQSession s = i.next(); s.setPrefetchSize(command.getConsumerId(), command.getPrefetch()); } } } protected void transportFailed(IOException error) { transportFailed.set(true); if (firstFailureError == null) { firstFailureError = error; } } /** * Should a JMS message be copied to a new JMS Message object as part of the * send() method in JMS. This is enabled by default to be compliant with the * JMS specification. You can disable it if you do not mutate JMS messages * after they are sent for a performance boost */ public void setCopyMessageOnSend(boolean copyMessageOnSend) { this.copyMessageOnSend = copyMessageOnSend; } @Override public String toString() { return "ActiveMQConnection {id=" + info.getConnectionId() + ",clientId=" + info.getClientId() + ",started=" + started.get() + "}"; } protected BlobTransferPolicy createBlobTransferPolicy() { return new BlobTransferPolicy(); } public int getProtocolVersion() { return protocolVersion.get(); } public int getProducerWindowSize() { return producerWindowSize; } public void setProducerWindowSize(int producerWindowSize) { this.producerWindowSize = producerWindowSize; } public void setAuditDepth(int auditDepth) { connectionAudit.setAuditDepth(auditDepth); } public void setAuditMaximumProducerNumber(int auditMaximumProducerNumber) { connectionAudit.setAuditMaximumProducerNumber(auditMaximumProducerNumber); } protected void removeDispatcher(ActiveMQDispatcher dispatcher) { connectionAudit.removeDispatcher(dispatcher); } protected boolean isDuplicate(ActiveMQDispatcher dispatcher, Message message) { return checkForDuplicates && connectionAudit.isDuplicate(dispatcher, message); } protected void rollbackDuplicate(ActiveMQDispatcher dispatcher, Message message) { connectionAudit.rollbackDuplicate(dispatcher, message); } public IOException getFirstFailureError() { return firstFailureError; } protected void waitForTransportInterruptionProcessingToComplete() throws InterruptedException { CountDownLatch cdl = this.transportInterruptionProcessingComplete; if (cdl != null) { if (!closed.get() && !transportFailed.get() && cdl.getCount()>0) { LOG.warn("dispatch paused, waiting for outstanding dispatch interruption processing (" + cdl.getCount() + ") to complete.."); cdl.await(10, TimeUnit.SECONDS); } signalInterruptionProcessingComplete(); } } protected void transportInterruptionProcessingComplete() { CountDownLatch cdl = this.transportInterruptionProcessingComplete; if (cdl != null) { cdl.countDown(); try { signalInterruptionProcessingComplete(); } catch (InterruptedException ignored) {} } } private void signalInterruptionProcessingComplete() throws InterruptedException { CountDownLatch cdl = this.transportInterruptionProcessingComplete; if (cdl.getCount()==0) { if (LOG.isDebugEnabled()) { LOG.debug("transportInterruptionProcessingComplete for: " + this.getConnectionInfo().getConnectionId()); } this.transportInterruptionProcessingComplete = null; FailoverTransport failoverTransport = transport.narrow(FailoverTransport.class); if (failoverTransport != null) { failoverTransport.connectionInterruptProcessingComplete(this.getConnectionInfo().getConnectionId()); if (LOG.isDebugEnabled()) { LOG.debug("notified failover transport (" + failoverTransport + ") of interruption completion for: " + this.getConnectionInfo().getConnectionId()); } } } } private void signalInterruptionProcessingNeeded() { FailoverTransport failoverTransport = transport.narrow(FailoverTransport.class); if (failoverTransport != null) { failoverTransport.getStateTracker().transportInterrupted(this.getConnectionInfo().getConnectionId()); if (LOG.isDebugEnabled()) { LOG.debug("notified failover transport (" + failoverTransport + ") of pending interruption processing for: " + this.getConnectionInfo().getConnectionId()); } } } /* * specify the amount of time in milliseconds that a consumer with a transaction pending recovery * will wait to receive re dispatched messages. * default value is 0 so there is no wait by default. */ public void setConsumerFailoverRedeliveryWaitPeriod(long consumerFailoverRedeliveryWaitPeriod) { this.consumerFailoverRedeliveryWaitPeriod = consumerFailoverRedeliveryWaitPeriod; } public long getConsumerFailoverRedeliveryWaitPeriod() { return consumerFailoverRedeliveryWaitPeriod; } protected Scheduler getScheduler() { return this.scheduler; } protected ThreadPoolExecutor getExecutor() { return this.executor; } /** * @return the checkForDuplicates */ public boolean isCheckForDuplicates() { return this.checkForDuplicates; } /** * @param checkForDuplicates the checkForDuplicates to set */ public void setCheckForDuplicates(boolean checkForDuplicates) { this.checkForDuplicates = checkForDuplicates; } public boolean isTransactedIndividualAck() { return transactedIndividualAck; } public void setTransactedIndividualAck(boolean transactedIndividualAck) { this.transactedIndividualAck = transactedIndividualAck; } public boolean isNonBlockingRedelivery() { return nonBlockingRedelivery; } public void setNonBlockingRedelivery(boolean nonBlockingRedelivery) { this.nonBlockingRedelivery = nonBlockingRedelivery; } /** * Removes any TempDestinations that this connection has cached, ignoring * any exceptions generated because the destination is in use as they should * not be removed. */ public void cleanUpTempDestinations() { if (this.activeTempDestinations == null || this.activeTempDestinations.isEmpty()) { return; } Iterator<ConcurrentHashMap.Entry<ActiveMQTempDestination, ActiveMQTempDestination>> entries = this.activeTempDestinations.entrySet().iterator(); while(entries.hasNext()) { ConcurrentHashMap.Entry<ActiveMQTempDestination, ActiveMQTempDestination> entry = entries.next(); try { // Only delete this temp destination if it was created from this connection. The connection used // for the advisory consumer may also have a reference to this temp destination. ActiveMQTempDestination dest = entry.getValue(); String thisConnectionId = (info.getConnectionId() == null) ? "" : info.getConnectionId().toString(); if (dest.getConnectionId() != null && dest.getConnectionId().equals(thisConnectionId)) { this.deleteTempDestination(entry.getValue()); } } catch (Exception ex) { // the temp dest is in use so it can not be deleted. // it is ok to leave it to connection tear down phase } } } }
Only stop transport for java.lang.SecurityException - as some tests rely on Connection continung after an exception from the broker git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1209841 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/main/java/org/apache/activemq/ActiveMQConnection.java
Only stop transport for java.lang.SecurityException - as some tests rely on Connection continung after an exception from the broker
<ide><path>ctivemq-core/src/main/java/org/apache/activemq/ActiveMQConnection.java <ide> }catch(Throwable e) { <ide> LOG.error("Caught an exception trying to create a JMSException for " +er.getException(),e); <ide> } <del> //dispose of transport <del> Transport t = this.transport; <del> if (null != t){ <del> ServiceSupport.dispose(t); <del> } <del> if(jmsEx !=null) { <del> throw jmsEx; <add> //dispose of transport for security exceptions <add> if (er.getException() instanceof SecurityException){ <add> Transport t = this.transport; <add> if (null != t){ <add> ServiceSupport.dispose(t); <add> } <add> if(jmsEx !=null) { <add> throw jmsEx; <add> } <ide> } <ide> } <ide> } <ide> } <ide> <ide> public void finalize() throws Throwable{ <del> if (scheduler != null){ <del> scheduler.stop(); <add> Scheduler s = this.scheduler; <add> if (s != null){ <add> s.stop(); <ide> } <ide> } <ide> <ide> } <ide> } <ide> } <del> <ide> }
Java
apache-2.0
0a8b805f47c73651eeaebd2563352dcad09b9be3
0
krzysztof-magosa/encog-java-core,SpenceSouth/encog-java-core,danilodesousacubas/encog-java-core,danilodesousacubas/encog-java-core,SpenceSouth/encog-java-core,Crespo911/encog-java-core,spradnyesh/encog-java-core,krzysztof-magosa/encog-java-core,ThiagoGarciaAlves/encog-java-core,Crespo911/encog-java-core,spradnyesh/encog-java-core,ThiagoGarciaAlves/encog-java-core
/* * Encog(tm) Core v3.1 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2012 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.hmm; import java.io.Serializable; import java.util.Iterator; import org.encog.ml.MLStateSequence; import org.encog.ml.data.MLDataPair; import org.encog.ml.data.MLDataSet; import org.encog.ml.hmm.alog.ForwardBackwardCalculator; import org.encog.ml.hmm.alog.ForwardBackwardScaledCalculator; import org.encog.ml.hmm.alog.ViterbiCalculator; import org.encog.ml.hmm.distributions.ContinousDistribution; import org.encog.ml.hmm.distributions.DiscreteDistribution; import org.encog.ml.hmm.distributions.StateDistribution; /** * A Hidden Markov Model (HMM) is a Machine Learning Method that allows for * predictions to be made about the hidden states and observations of a given * system over time. A HMM can be thought of as a simple dynamic Bayesian * network. The HMM is dynamic as it deals with changes that unfold over time. * * The Hidden Markov Model is made up of a number of states and observations. A * simple example might be the state of the economy. There are three hidden * states, such as bull market, bear market and level. We do not know which * state we are currently in. However, there are observations that can be made * such as interest rate and the level of the S&P500. The HMM learns what state * we are in by seeing how the observations change over time. * * The HMM is only in one state at a given time. There is a percent probability * that the HMM will move from one state to any of the other states. These * probabilities are arranged in a grid, and are called the state transition * probabilities. * * Observations can be discrete or continuous. These observations allow the HMM * to predict state transitions. * * The HMM can handle single-value or multivariate observations. * * http://www.heatonresearch.com/wiki/Hidden_Markov_Model * * Rabiner, Juang, An introduction to Hidden Markov Models, IEEE ASSP Mag.,pp * 4-16, June 1986. * * Baum, L. E.; Petrie, T. (1966). * "Statistical Inference for Probabilistic Functions of Finite State Markov Chains" * The Annals of Mathematical Statistics 37 (6): 1554-1563. * */ public class HiddenMarkovModel implements MLStateSequence, Serializable, Cloneable { /** * The serial id. */ private static final long serialVersionUID = 1L; /** * The initial probabilities for each state. */ private double pi[]; /** * The transitional probabilities between the states. */ private double transitionProbability[][]; /** * The mapping of observation probabilities to the * states. */ private final StateDistribution[] stateDistributions; private final int items; /** * Construct a continuous HMM with the specified number of states. * @param nbStates The number of states. */ public HiddenMarkovModel(final int nbStates) { this.items = -1; this.pi = new double[nbStates]; this.transitionProbability = new double[nbStates][nbStates]; this.stateDistributions = new StateDistribution[nbStates]; for (int i = 0; i < nbStates; i++) { this.pi[i] = 1. / nbStates; if (isContinuous()) { this.stateDistributions[i] = new ContinousDistribution( getStateCount()); } else { this.stateDistributions[i] = new DiscreteDistribution( getStateCount()); } for (int j = 0; j < nbStates; j++) { this.transitionProbability[i][j] = 1. / nbStates; } } } public HiddenMarkovModel(final int theStates, final int theItems) { this.items = theItems; this.pi = new double[theStates]; this.transitionProbability = new double[theStates][theStates]; this.stateDistributions = new StateDistribution[theStates]; for (int i = 0; i < theStates; i++) { this.pi[i] = 1. / theStates; this.stateDistributions[i] = new DiscreteDistribution(this.items); for (int j = 0; j < theStates; j++) { this.transitionProbability[i][j] = 1.0 / theStates; } } } @Override public HiddenMarkovModel clone() throws CloneNotSupportedException { final HiddenMarkovModel hmm = cloneStructure(); hmm.pi = this.pi.clone(); hmm.transitionProbability = this.transitionProbability.clone(); for (int i = 0; i < this.transitionProbability.length; i++) { hmm.transitionProbability[i] = this.transitionProbability[i] .clone(); } for (int i = 0; i < hmm.stateDistributions.length; i++) { hmm.stateDistributions[i] = this.stateDistributions[i].clone(); } return hmm; } public HiddenMarkovModel cloneStructure() { HiddenMarkovModel hmm; if (isDiscrete()) { hmm = new HiddenMarkovModel(getStateCount(), this.items); } else { hmm = new HiddenMarkovModel(getStateCount()); } return hmm; } public StateDistribution createNewDistribution() { if (isContinuous()) { return new ContinousDistribution(this.items); } else { return new DiscreteDistribution(this.items); } } public double getPi(final int stateNb) { return this.pi[stateNb]; } public int getStateCount() { return this.pi.length; } public StateDistribution getStateDistribution(final int i) { return this.stateDistributions[i]; } @Override public int[] getStatesForSequence(final MLDataSet seq) { return (new ViterbiCalculator(seq, this)).stateSequence(); } public double getTransitionProbability(final int i, final int j) { return this.transitionProbability[i][j]; } public boolean isContinuous() { return this.items == -1; } public boolean isDiscrete() { return !isContinuous(); } public double lnProbability(final MLDataSet seq) { return (new ForwardBackwardScaledCalculator(seq, this)).lnProbability(); } @Override public double probability(final MLDataSet seq) { return (new ForwardBackwardCalculator(seq, this)).probability(); } @Override public double probability(final MLDataSet seq, final int[] states) { if ((seq.size() != states.length) || (seq.size() < 1)) { throw new IllegalArgumentException(); } double probability = getPi(states[0]); final Iterator<MLDataPair> oseqIterator = seq.iterator(); for (int i = 0; i < (states.length - 1); i++) { probability *= getStateDistribution(states[i]).probability( oseqIterator.next()) * getTransitionProbability(states[i], states[i + 1]); } return probability * getStateDistribution(states[states.length - 1]).probability( seq.get(states.length - 1)); } public void setPi(final int stateNb, final double value) { this.pi[stateNb] = value; } public void setStateDistribution(final int stateNb, final StateDistribution opdf) { this.stateDistributions[stateNb] = opdf; } public void setTransitionProbability(final int i, final int j, final double value) { this.transitionProbability[i][j] = value; } }
src/main/java/org/encog/ml/hmm/HiddenMarkovModel.java
/* * Encog(tm) Core v3.1 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2012 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.hmm; import java.io.Serializable; import java.util.Iterator; import org.encog.ml.MLStateSequence; import org.encog.ml.data.MLDataPair; import org.encog.ml.data.MLDataSet; import org.encog.ml.hmm.alog.ForwardBackwardCalculator; import org.encog.ml.hmm.alog.ForwardBackwardScaledCalculator; import org.encog.ml.hmm.alog.ViterbiCalculator; import org.encog.ml.hmm.distributions.ContinousDistribution; import org.encog.ml.hmm.distributions.DiscreteDistribution; import org.encog.ml.hmm.distributions.StateDistribution; /** * A Hidden Markov Model (HMM) is a Machine Learning Method that allows for * predictions to be made about the hidden states and observations of a given * system over time. A HMM can be thought of as a simple dynamic Bayesian * network. The HMM is dynamic as it deals with changes that unfold over time. * * The Hidden Markov Model is made up of a number of states and observations. A * simple example might be the state of the economy. There are three hidden * states, such as bull market, bear market and level. We do not know which * state we are currently in. However, there are observations that can be made * such as interest rate and the level of the S&P500. The HMM learns what state * we are in by seeing how the observations change over time. * * The HMM is only in one state at a given time. There is a percent probability * that the HMM will move from one state to any of the other states. These * probabilities are arranged in a grid, and are called the state transition * probabilities. * * Observations can be discrete or continuous. These observations allow the HMM * to predict state transitions. * * The HMM can handle single-value or multivariate observations. * * http://www.heatonresearch.com/wiki/Hidden_Markov_Model * * Rabiner, Juang, An introduction to Hidden Markov Models, IEEE ASSP Mag.,pp * 4-16, June 1986. * * Baum, L. E.; Petrie, T. (1966). * "Statistical Inference for Probabilistic Functions of Finite State Markov Chains" * The Annals of Mathematical Statistics 37 (6): 1554-1563. * */ public class HiddenMarkovModel implements MLStateSequence, Serializable, Cloneable { /** * */ private static final long serialVersionUID = 1L; private double pi[]; private double transitionProbability[][]; private final StateDistribution[] stateDistributions; private final int items; public HiddenMarkovModel(final int nbStates) { this.items = -1; this.pi = new double[nbStates]; this.transitionProbability = new double[nbStates][nbStates]; this.stateDistributions = new StateDistribution[nbStates]; for (int i = 0; i < nbStates; i++) { this.pi[i] = 1. / nbStates; if (isContinuous()) { this.stateDistributions[i] = new ContinousDistribution( getStateCount()); } else { this.stateDistributions[i] = new DiscreteDistribution( getStateCount()); } for (int j = 0; j < nbStates; j++) { this.transitionProbability[i][j] = 1. / nbStates; } } } public HiddenMarkovModel(final int theStates, final int theItems) { this.items = theItems; this.pi = new double[theStates]; this.transitionProbability = new double[theStates][theStates]; this.stateDistributions = new StateDistribution[theStates]; for (int i = 0; i < theStates; i++) { this.pi[i] = 1. / theStates; this.stateDistributions[i] = new DiscreteDistribution(this.items); for (int j = 0; j < theStates; j++) { this.transitionProbability[i][j] = 1.0 / theStates; } } } @Override public HiddenMarkovModel clone() throws CloneNotSupportedException { final HiddenMarkovModel hmm = cloneStructure(); hmm.pi = this.pi.clone(); hmm.transitionProbability = this.transitionProbability.clone(); for (int i = 0; i < this.transitionProbability.length; i++) { hmm.transitionProbability[i] = this.transitionProbability[i] .clone(); } for (int i = 0; i < hmm.stateDistributions.length; i++) { hmm.stateDistributions[i] = this.stateDistributions[i].clone(); } return hmm; } public HiddenMarkovModel cloneStructure() { HiddenMarkovModel hmm; if (isDiscrete()) { hmm = new HiddenMarkovModel(getStateCount(), this.items); } else { hmm = new HiddenMarkovModel(getStateCount()); } return hmm; } public StateDistribution createNewDistribution() { if (isContinuous()) { return new ContinousDistribution(this.items); } else { return new DiscreteDistribution(this.items); } } public double getPi(final int stateNb) { return this.pi[stateNb]; } public int getStateCount() { return this.pi.length; } public StateDistribution getStateDistribution(final int i) { return this.stateDistributions[i]; } @Override public int[] getStatesForSequence(final MLDataSet seq) { return (new ViterbiCalculator(seq, this)).stateSequence(); } public double getTransitionProbability(final int i, final int j) { return this.transitionProbability[i][j]; } public boolean isContinuous() { return this.items == -1; } public boolean isDiscrete() { return !isContinuous(); } public double lnProbability(final MLDataSet seq) { return (new ForwardBackwardScaledCalculator(seq, this)).lnProbability(); } @Override public double probability(final MLDataSet seq) { return (new ForwardBackwardCalculator(seq, this)).probability(); } @Override public double probability(final MLDataSet seq, final int[] states) { if ((seq.size() != states.length) || (seq.size() < 1)) { throw new IllegalArgumentException(); } double probability = getPi(states[0]); final Iterator<MLDataPair> oseqIterator = seq.iterator(); for (int i = 0; i < (states.length - 1); i++) { probability *= getStateDistribution(states[i]).probability( oseqIterator.next()) * getTransitionProbability(states[i], states[i + 1]); } return probability * getStateDistribution(states[states.length - 1]).probability( seq.get(states.length - 1)); } public void setPi(final int stateNb, final double value) { this.pi[stateNb] = value; } public void setStateDistribution(final int stateNb, final StateDistribution opdf) { this.stateDistributions[stateNb] = opdf; } public void setTransitionProbability(final int i, final int j, final double value) { this.transitionProbability[i][j] = value; } }
Added some javadocs to HMM
src/main/java/org/encog/ml/hmm/HiddenMarkovModel.java
Added some javadocs to HMM
<ide><path>rc/main/java/org/encog/ml/hmm/HiddenMarkovModel.java <ide> public class HiddenMarkovModel implements MLStateSequence, Serializable, <ide> Cloneable { <ide> /** <del> * <add> * The serial id. <ide> */ <ide> private static final long serialVersionUID = 1L; <add> <add> /** <add> * The initial probabilities for each state. <add> */ <ide> private double pi[]; <add> <add> /** <add> * The transitional probabilities between the states. <add> */ <ide> private double transitionProbability[][]; <add> <add> /** <add> * The mapping of observation probabilities to the <add> * states. <add> */ <ide> private final StateDistribution[] stateDistributions; <ide> private final int items; <ide> <add> /** <add> * Construct a continuous HMM with the specified number of states. <add> * @param nbStates The number of states. <add> */ <ide> public HiddenMarkovModel(final int nbStates) { <ide> this.items = -1; <ide> this.pi = new double[nbStates];
Java
apache-2.0
a352ff4003abee6ef845f411cea61cd886efa7df
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
package org.openspaces.grid.gsm.capacity; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.openspaces.core.internal.commons.math.fraction.Fraction; public class AggregatedAllocatedCapacity { // allocated capacity per grid service agent (UUID) private final Map<String,AllocatedCapacity> capacityPerAgent; private AllocatedCapacity totalCapacity; public AggregatedAllocatedCapacity() { this.capacityPerAgent = new ConcurrentHashMap<String, AllocatedCapacity>(); totalCapacity = new AllocatedCapacity(Fraction.ZERO, 0); } public AllocatedCapacity getTotalAllocatedCapacity() { return totalCapacity; } public boolean equalsZero() { return capacityPerAgent.isEmpty(); } public boolean equals(Object other) { return other instanceof AggregatedAllocatedCapacity && ((AggregatedAllocatedCapacity)other).capacityPerAgent.equals(capacityPerAgent); } public Collection<String> getAgentUids() { return capacityPerAgent.keySet(); } public String toString() { return capacityPerAgent.size() + " machines with total capacity of " + getTotalAllocatedCapacity(); } public static AggregatedAllocatedCapacity add( AggregatedAllocatedCapacity aggregatedCapacity1, AggregatedAllocatedCapacity aggregatedCapacity2) { AggregatedAllocatedCapacity sum = new AggregatedAllocatedCapacity(); sum.addAll(aggregatedCapacity1); sum.addAll(aggregatedCapacity2); return sum; } public static AggregatedAllocatedCapacity subtract( AggregatedAllocatedCapacity aggregatedCapacity1, AggregatedAllocatedCapacity aggregatedCapacity2) { AggregatedAllocatedCapacity diff = new AggregatedAllocatedCapacity(); diff.addAll(aggregatedCapacity1); diff.subtractAll(aggregatedCapacity2); return diff; } public static AggregatedAllocatedCapacity add( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid, AllocatedCapacity capacity) { AggregatedAllocatedCapacity sum = new AggregatedAllocatedCapacity(); sum.addAll(aggregatedCapacity); sum.add(agentUid,capacity); return sum; } public static AggregatedAllocatedCapacity subtract( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid, AllocatedCapacity capacity) { AggregatedAllocatedCapacity remaining = new AggregatedAllocatedCapacity(); remaining.addAll(aggregatedCapacity); remaining.subtract(agentUid,capacity); return remaining; } public static AggregatedAllocatedCapacity subtractAgent( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid) { return subtract(aggregatedCapacity, agentUid, aggregatedCapacity.getAgentCapacity(agentUid)); } public static AggregatedAllocatedCapacity subtractOrZero( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid, AllocatedCapacity capacity) { AggregatedAllocatedCapacity remaining = new AggregatedAllocatedCapacity(); remaining.addAll(aggregatedCapacity); remaining.subtractOrZero(agentUid,capacity); return remaining; } public AllocatedCapacity getAgentCapacity(String agentUid) { if (!capacityPerAgent.containsKey(agentUid)) { throw new IllegalArgumentException("agent"); } return this.capacityPerAgent.get(agentUid); } public AllocatedCapacity getAgentCapacityOrZero(String agentUid) { if (capacityPerAgent.containsKey(agentUid)) { return this.capacityPerAgent.get(agentUid); } else { return new AllocatedCapacity(Fraction.ZERO, 0); } } private void addAll(AggregatedAllocatedCapacity aggregatedCapacity) { for (String agentUid : aggregatedCapacity.capacityPerAgent.keySet()) { AllocatedCapacity capacity = aggregatedCapacity.capacityPerAgent.get(agentUid); add(agentUid,capacity); } } private void subtractAll(AggregatedAllocatedCapacity aggregatedCapacity) { for (String agentUid : aggregatedCapacity.capacityPerAgent.keySet()) { AllocatedCapacity capacity = aggregatedCapacity.capacityPerAgent.get(agentUid); subtract(agentUid,capacity); } } private void add(String agentUid, AllocatedCapacity capacityToAdd) { validateAllocation(capacityToAdd); AllocatedCapacity sumCapacity = capacityToAdd; if (capacityPerAgent.containsKey(agentUid)) { sumCapacity = AllocatedCapacity.add( capacityPerAgent.get(agentUid), sumCapacity); } capacityPerAgent.put(agentUid,sumCapacity); totalCapacity = AllocatedCapacity.add(totalCapacity, capacityToAdd); } private void subtract(String agentUid, AllocatedCapacity capacity) { validateAllocation(capacity); if (!capacityPerAgent.containsKey(agentUid)) { throw new IllegalArgumentException("Agent UID " + agentUid + " no found"); } AllocatedCapacity newAllocation = AllocatedCapacity.subtract(capacityPerAgent.get(agentUid), capacity); updateAgentCapacity(agentUid, newAllocation); totalCapacity = AllocatedCapacity.subtract(totalCapacity, capacity); } private void subtractOrZero(String agentUid, AllocatedCapacity capacity) { validateAllocation(capacity); if (!capacityPerAgent.containsKey(agentUid)) { throw new IllegalArgumentException("Agent UID " + agentUid + " no found"); } AllocatedCapacity newAllocation = AllocatedCapacity.subtractOrZero(capacityPerAgent.get(agentUid), capacity); updateAgentCapacity(agentUid, newAllocation); totalCapacity = AllocatedCapacity.subtract(totalCapacity, capacity); } private void updateAgentCapacity(String agentUid, AllocatedCapacity newAllocation) { if (newAllocation.equalsZero()) { capacityPerAgent.remove(agentUid); } else { capacityPerAgent.put(agentUid,newAllocation); } } private void validateAllocation(AllocatedCapacity allocation) { if (allocation.equalsZero()) { throw new IllegalArgumentException(allocation + " equals zero"); } } }
src/main/src/org/openspaces/grid/gsm/capacity/AggregatedAllocatedCapacity.java
package org.openspaces.grid.gsm.capacity; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.openspaces.core.internal.commons.math.fraction.Fraction; public class AggregatedAllocatedCapacity { // allocated capacity per grid service agent (UUID) private final Map<String,AllocatedCapacity> capacityPerAgent; public AggregatedAllocatedCapacity() { this.capacityPerAgent = new ConcurrentHashMap<String, AllocatedCapacity>(); } public AllocatedCapacity getTotalAllocatedCapacity() { AllocatedCapacity total = new AllocatedCapacity(Fraction.ZERO, 0); for (String agentUid : capacityPerAgent.keySet()) { AllocatedCapacity capacity = capacityPerAgent.get(agentUid); total = AllocatedCapacity.add(total,capacity); } return total; } public boolean equalsZero() { return capacityPerAgent.isEmpty(); } public boolean equals(Object other) { return other instanceof AggregatedAllocatedCapacity && ((AggregatedAllocatedCapacity)other).capacityPerAgent.equals(capacityPerAgent); } public Collection<String> getAgentUids() { return capacityPerAgent.keySet(); } public String toString() { return capacityPerAgent.size() + " machines with total capacity of " + getTotalAllocatedCapacity(); } public static AggregatedAllocatedCapacity add( AggregatedAllocatedCapacity aggregatedCapacity1, AggregatedAllocatedCapacity aggregatedCapacity2) { AggregatedAllocatedCapacity sum = new AggregatedAllocatedCapacity(); sum.addAll(aggregatedCapacity1); sum.addAll(aggregatedCapacity2); return sum; } public static AggregatedAllocatedCapacity subtract( AggregatedAllocatedCapacity aggregatedCapacity1, AggregatedAllocatedCapacity aggregatedCapacity2) { AggregatedAllocatedCapacity diff = new AggregatedAllocatedCapacity(); diff.addAll(aggregatedCapacity1); diff.subtractAll(aggregatedCapacity2); return diff; } public static AggregatedAllocatedCapacity add( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid, AllocatedCapacity capacity) { AggregatedAllocatedCapacity sum = new AggregatedAllocatedCapacity(); sum.addAll(aggregatedCapacity); sum.add(agentUid,capacity); return sum; } public static AggregatedAllocatedCapacity subtract( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid, AllocatedCapacity capacity) { AggregatedAllocatedCapacity remaining = new AggregatedAllocatedCapacity(); remaining.addAll(aggregatedCapacity); remaining.subtract(agentUid,capacity); return remaining; } public static AggregatedAllocatedCapacity subtractOrZero( AggregatedAllocatedCapacity aggregatedCapacity, String agentUid, AllocatedCapacity capacity) { AggregatedAllocatedCapacity remaining = new AggregatedAllocatedCapacity(); remaining.addAll(aggregatedCapacity); remaining.subtractOrZero(agentUid,capacity); return remaining; } public AllocatedCapacity getAgentCapacity(String agentUid) { if (!capacityPerAgent.containsKey(agentUid)) { throw new IllegalArgumentException("agent"); } return this.capacityPerAgent.get(agentUid); } private void addAll(AggregatedAllocatedCapacity aggregatedCapacity) { for (String agentUid : aggregatedCapacity.capacityPerAgent.keySet()) { AllocatedCapacity capacity = aggregatedCapacity.capacityPerAgent.get(agentUid); add(agentUid,capacity); } } private void subtractAll(AggregatedAllocatedCapacity aggregatedCapacity) { for (String agentUid : aggregatedCapacity.capacityPerAgent.keySet()) { AllocatedCapacity capacity = aggregatedCapacity.capacityPerAgent.get(agentUid); subtract(agentUid,capacity); } } private void add(String agentUid, AllocatedCapacity capacity) { validateAllocation(capacity); if (capacityPerAgent.containsKey(agentUid)) { capacity = AllocatedCapacity.add( capacityPerAgent.get(agentUid), capacity); } capacityPerAgent.put(agentUid,capacity); } private void subtract(String agentUid, AllocatedCapacity capacity) { validateAllocation(capacity); if (!capacityPerAgent.containsKey(agentUid)) { throw new IllegalArgumentException("Agent UID " + agentUid + " no found"); } AllocatedCapacity newAllocation = AllocatedCapacity.subtract(capacityPerAgent.get(agentUid), capacity); updateAgentCapacity(agentUid, newAllocation); } private void subtractOrZero(String agentUid, AllocatedCapacity capacity) { validateAllocation(capacity); if (!capacityPerAgent.containsKey(agentUid)) { throw new IllegalArgumentException("Agent UID " + agentUid + " no found"); } AllocatedCapacity newAllocation = AllocatedCapacity.subtractOrZero(capacityPerAgent.get(agentUid), capacity); updateAgentCapacity(agentUid, newAllocation); } private void updateAgentCapacity(String agentUid, AllocatedCapacity newAllocation) { if (newAllocation.equalsZero()) { capacityPerAgent.remove(agentUid); } else { capacityPerAgent.put(agentUid,newAllocation); } } private void validateAllocation(AllocatedCapacity allocation) { if (allocation.equalsZero()) { throw new IllegalArgumentException(allocation + " equals zero"); } } }
GS-8654 Added totalCapacity to AggregatedAllocatedCapacity that works in O(1) instead of O(machines). This is similiar to list.size() taking O(1) instead of O(items). svn path=/trunk/openspaces/; revision=83708 Former-commit-id: 4b2f78d4d932968f652ac28d0d89e96ac0d8eebd
src/main/src/org/openspaces/grid/gsm/capacity/AggregatedAllocatedCapacity.java
GS-8654 Added totalCapacity to AggregatedAllocatedCapacity that works in O(1) instead of O(machines). This is similiar to list.size() taking O(1) instead of O(items).
<ide><path>rc/main/src/org/openspaces/grid/gsm/capacity/AggregatedAllocatedCapacity.java <ide> <ide> // allocated capacity per grid service agent (UUID) <ide> private final Map<String,AllocatedCapacity> capacityPerAgent; <del> <add> private AllocatedCapacity totalCapacity; <ide> <ide> public AggregatedAllocatedCapacity() { <ide> this.capacityPerAgent = new ConcurrentHashMap<String, AllocatedCapacity>(); <add> totalCapacity = new AllocatedCapacity(Fraction.ZERO, 0); <ide> } <ide> <ide> public AllocatedCapacity getTotalAllocatedCapacity() { <del> AllocatedCapacity total = new AllocatedCapacity(Fraction.ZERO, 0); <del> for (String agentUid : capacityPerAgent.keySet()) { <del> AllocatedCapacity capacity = capacityPerAgent.get(agentUid); <del> total = AllocatedCapacity.add(total,capacity); <del> } <del> return total; <add> return totalCapacity; <ide> } <ide> <ide> public boolean equalsZero() { <ide> return remaining; <ide> } <ide> <add> <add> <add> public static AggregatedAllocatedCapacity subtractAgent( <add> AggregatedAllocatedCapacity aggregatedCapacity, <add> String agentUid) { <add> return subtract(aggregatedCapacity, agentUid, aggregatedCapacity.getAgentCapacity(agentUid)); <add> } <add> <ide> public static AggregatedAllocatedCapacity subtractOrZero( <ide> AggregatedAllocatedCapacity aggregatedCapacity, <ide> String agentUid, <ide> return this.capacityPerAgent.get(agentUid); <ide> } <ide> <add> public AllocatedCapacity getAgentCapacityOrZero(String agentUid) { <add> <add> if (capacityPerAgent.containsKey(agentUid)) { <add> return this.capacityPerAgent.get(agentUid); <add> } <add> else { <add> return new AllocatedCapacity(Fraction.ZERO, 0); <add> } <add> } <add> <ide> private void addAll(AggregatedAllocatedCapacity aggregatedCapacity) { <ide> for (String agentUid : aggregatedCapacity.capacityPerAgent.keySet()) { <ide> AllocatedCapacity capacity = aggregatedCapacity.capacityPerAgent.get(agentUid); <ide> } <ide> } <ide> <del> private void add(String agentUid, AllocatedCapacity capacity) { <add> private void add(String agentUid, AllocatedCapacity capacityToAdd) { <ide> <del> validateAllocation(capacity); <del> <add> validateAllocation(capacityToAdd); <add> AllocatedCapacity sumCapacity = capacityToAdd; <ide> if (capacityPerAgent.containsKey(agentUid)) { <ide> <del> capacity = <del> AllocatedCapacity.add( <del> capacityPerAgent.get(agentUid), <del> capacity); <add> sumCapacity = AllocatedCapacity.add( <add> capacityPerAgent.get(agentUid), <add> sumCapacity); <ide> } <ide> <del> capacityPerAgent.put(agentUid,capacity); <add> capacityPerAgent.put(agentUid,sumCapacity); <add> totalCapacity = AllocatedCapacity.add(totalCapacity, capacityToAdd); <ide> } <ide> <ide> <ide> AllocatedCapacity newAllocation = <ide> AllocatedCapacity.subtract(capacityPerAgent.get(agentUid), capacity); <ide> <del> updateAgentCapacity(agentUid, newAllocation); <add> updateAgentCapacity(agentUid, newAllocation); <add> <add> totalCapacity = AllocatedCapacity.subtract(totalCapacity, capacity); <ide> } <ide> <ide> <ide> AllocatedCapacity.subtractOrZero(capacityPerAgent.get(agentUid), capacity); <ide> <ide> updateAgentCapacity(agentUid, newAllocation); <add> totalCapacity = AllocatedCapacity.subtract(totalCapacity, capacity); <ide> <ide> } <ide>
Java
apache-2.0
bee9de83e5082272d4ddaf35f4ea496b997ae748
0
donNewtonAlpha/onos,kuujo/onos,Shashikanth-Huawei/bmp,donNewtonAlpha/onos,kuujo/onos,opennetworkinglab/onos,y-higuchi/onos,gkatsikas/onos,sdnwiselab/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,Shashikanth-Huawei/bmp,oplinkoms/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,donNewtonAlpha/onos,donNewtonAlpha/onos,Shashikanth-Huawei/bmp,Shashikanth-Huawei/bmp,oplinkoms/onos,sdnwiselab/onos,LorenzReinhart/ONOSnew,osinstom/onos,osinstom/onos,gkatsikas/onos,opennetworkinglab/onos,oplinkoms/onos,y-higuchi/onos,kuujo/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,osinstom/onos,y-higuchi/onos,sdnwiselab/onos,gkatsikas/onos,kuujo/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,sdnwiselab/onos,osinstom/onos,opennetworkinglab/onos,kuujo/onos,kuujo/onos,opennetworkinglab/onos,donNewtonAlpha/onos,opennetworkinglab/onos,sdnwiselab/onos,sdnwiselab/onos,opennetworkinglab/onos,gkatsikas/onos,kuujo/onos,y-higuchi/onos,oplinkoms/onos,y-higuchi/onos,osinstom/onos
/* * Copyright 2015-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ovsdb.rfc.table; import java.util.Map; import java.util.Set; import org.onosproject.ovsdb.rfc.notation.Column; import org.onosproject.ovsdb.rfc.notation.Row; import org.onosproject.ovsdb.rfc.notation.Uuid; import org.onosproject.ovsdb.rfc.schema.DatabaseSchema; import org.onosproject.ovsdb.rfc.tableservice.AbstractOvsdbTableService; import org.onosproject.ovsdb.rfc.tableservice.ColumnDescription; /** * This class provides operations of Mirror Table. */ public class Mirror extends AbstractOvsdbTableService { /** * Mirror table column name. */ public enum MirrorColumn { NAME("name"), SELECTSRCPORT("select_src_port"), SELECTDSTPORT("select_dst_port"), SELECTVLAN("select_vlan"), OUTPUTPORT("output_port"), EXTERNALIDS("external_ids"), OUTPUTVLAN("output_vlan"), STATISTICS("statistics"), SELECTALL("select_all"); private final String columnName; private MirrorColumn(String columnName) { this.columnName = columnName; } /** * Returns the table column name for MirrorColumn. * @return the table column name */ public String columnName() { return columnName; } } /** * Constructs a Mirror object. Generate Mirror Table Description. * @param dbSchema DatabaseSchema * @param row Row */ public Mirror(DatabaseSchema dbSchema, Row row) { super(dbSchema, row, OvsdbTable.MIRROR, VersionNum.VERSION100); } /** * Get the Column entity which column name is "name" from the Row entity of * attributes. * @return the Column entity which column name is "name" */ public Column getNameColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), "getNameColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "name" to the Row entity of * attributes. * @param name the column data which column name is "name" */ public void setName(String name) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), "setName", VersionNum.VERSION100); super.setDataHandler(columndesc, name); } /** * Get the column data which column name is "name" from the Row entity of * attributes. * @return the column data which column name is "name" */ public String getName() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), "getName", VersionNum.VERSION100); return (String) super.getDataHandler(columndesc); } /** * Get the Column entity which column name is "select_src_port" from the Row * entity of attributes. * @return the Column entity which column name is "select_src_port" */ public Column getSelectSrcPortColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTSRCPORT.columnName(), "getSelectSrcPortColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_src_port" to the Row * entity of attributes. * @param selectSrcPort the column data which column name is * "select_src_port" */ public void setSelectSrcPort(Set<Uuid> selectSrcPort) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTSRCPORT.columnName(), "setSelectSrcPort", VersionNum.VERSION100); super.setDataHandler(columndesc, selectSrcPort); } /** * Get the Column entity which column name is "select_dst_port" from the Row * entity of attributes. * @return the Column entity which column name is "select_dst_port" */ public Column getSelectDstPortColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTDSTPORT.columnName(), "getSelectDstPortColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_dst_port" to the Row * entity of attributes. * @param selectDstPrt the column data which column name is * "select_dst_port" */ public void setSelectDstPort(Set<Uuid> selectDstPrt) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTDSTPORT.columnName(), "setSelectDstPort", VersionNum.VERSION100); super.setDataHandler(columndesc, selectDstPrt); } /** * Get the Column entity which column name is "select_vlan" from the Row * entity of attributes. * @return the Column entity which column name is "select_vlan" */ public Column getSelectVlanColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTVLAN.columnName(), "getSelectVlanColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_vlan" to the Row entity * of attributes. * @param selectVlan the column data which column name is "select_vlan" */ public void setSelectVlan(Set<Short> selectVlan) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTVLAN.columnName(), "setSelectVlan", VersionNum.VERSION100); super.setDataHandler(columndesc, selectVlan); } /** * Get the Column entity which column name is "output_port" from the Row * entity of attributes. * @return the Column entity which column name is "output_port" */ public Column getOutputPortColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTPORT.columnName(), "getOutputPortColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "output_port" to the Row entity * of attributes. * @param outputPort the column data which column name is "output_port" */ public void setOutputPort(Uuid outputPort) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTPORT.columnName(), "setOutputPort", VersionNum.VERSION100); super.setDataHandler(columndesc, outputPort); } /** * Get the Column entity which column name is "output_vlan" from the Row * entity of attributes. * @return the Column entity which column name is "output_vlan" */ public Column getOutputVlanColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTVLAN.columnName(), "getOutputVlanColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "output_vlan" to the Row entity * of attributes. * @param outputVlan the column data which column name is "output_vlan" */ public void setOutputVlan(Set<Short> outputVlan) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTVLAN.columnName(), "setOutputVlan", VersionNum.VERSION100); super.setDataHandler(columndesc, outputVlan); } /** * Get the Column entity which column name is "statistics" from the Row * entity of attributes. * @return the Column entity which column name is "statistics" */ public Column getStatisticsColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.STATISTICS.columnName(), "getStatisticsColumn", VersionNum.VERSION640); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "statistics" to the Row entity * of attributes. * @param statistics the column data which column name is "statistics" */ public void setStatistics(Map<String, Long> statistics) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.STATISTICS.columnName(), "setStatistics", VersionNum.VERSION640); super.setDataHandler(columndesc, statistics); } /** * Get the Column entity which column name is "external_ids" from the Row * entity of attributes. * @return the Column entity which column name is "external_ids" */ public Column getExternalIdsColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.EXTERNALIDS.columnName(), "getExternalIdsColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "external_ids" to the Row entity * of attributes. * @param externalIds the column data which column name is "external_ids" */ public void setExternalIds(Map<String, String> externalIds) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.EXTERNALIDS.columnName(), "setExternalIds", VersionNum.VERSION100); super.setDataHandler(columndesc, externalIds); } /** * Get the Column entity which column name is "select_all" from the Row * entity of attributes. * @return the Column entity which column name is "select_all" */ public Column getSelectAllColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTALL.columnName(), "getSelectAllColumn", VersionNum.VERSION620); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_all" to the Row entity * of attributes. * @param selectAll the column data which column name is "select_all" */ public void setSelectAll(Boolean selectAll) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTALL.columnName(), "setSelectAll", VersionNum.VERSION620); super.setDataHandler(columndesc, selectAll); } }
protocols/ovsdb/rfc/src/main/java/org/onosproject/ovsdb/rfc/table/Mirror.java
/* * Copyright 2015-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ovsdb.rfc.table; import java.util.Map; import java.util.Set; import org.onosproject.ovsdb.rfc.notation.Column; import org.onosproject.ovsdb.rfc.notation.Row; import org.onosproject.ovsdb.rfc.notation.Uuid; import org.onosproject.ovsdb.rfc.schema.DatabaseSchema; import org.onosproject.ovsdb.rfc.tableservice.AbstractOvsdbTableService; import org.onosproject.ovsdb.rfc.tableservice.ColumnDescription; /** * This class provides operations of Mirror Table. */ public class Mirror extends AbstractOvsdbTableService { /** * Mirror table column name. */ public enum MirrorColumn { NAME("name"), SELECTSRCPORT("select_src_port"), SELECTDSTPORT("select_dst_port"), SELECTVLAN("select_vlan"), OUTPUTPORT("output_port"), EXTERNALIDS("external_ids"), OUTPUTVLAN("output_vlan"), STATISTICS("statistics"), SELECTALL("select_all"); private final String columnName; private MirrorColumn(String columnName) { this.columnName = columnName; } /** * Returns the table column name for MirrorColumn. * @return the table column name */ public String columnName() { return columnName; } } /** * Constructs a Mirror object. Generate Mirror Table Description. * @param dbSchema DatabaseSchema * @param row Row */ public Mirror(DatabaseSchema dbSchema, Row row) { super(dbSchema, row, OvsdbTable.MIRROR, VersionNum.VERSION100); } /** * Get the Column entity which column name is "name" from the Row entity of * attributes. * @return the Column entity which column name is "name" */ public Column getNameColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), "getNameColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "name" to the Row entity of * attributes. * @param name the column data which column name is "name" */ public void setName(Set<String> name) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), "setName", VersionNum.VERSION100); super.setDataHandler(columndesc, name); } /** * Get the column data which column name is "name" from the Row entity of * attributes. * @return the column data which column name is "name" */ public Set<String> getName() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), "getName", VersionNum.VERSION100); return (Set<String>) super.getDataHandler(columndesc); } /** * Get the Column entity which column name is "select_src_port" from the Row * entity of attributes. * @return the Column entity which column name is "select_src_port" */ public Column getSelectSrcPortColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTSRCPORT.columnName(), "getSelectSrcPortColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_src_port" to the Row * entity of attributes. * @param selectSrcPort the column data which column name is * "select_src_port" */ public void setSelectSrcPort(Set<Uuid> selectSrcPort) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTSRCPORT.columnName(), "setSelectSrcPort", VersionNum.VERSION100); super.setDataHandler(columndesc, selectSrcPort); } /** * Get the Column entity which column name is "select_dst_port" from the Row * entity of attributes. * @return the Column entity which column name is "select_dst_port" */ public Column getSelectDstPortColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTDSTPORT.columnName(), "getSelectDstPortColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_dst_port" to the Row * entity of attributes. * @param selectDstPrt the column data which column name is * "select_dst_port" */ public void setSelectDstPort(Set<Uuid> selectDstPrt) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTDSTPORT.columnName(), "setSelectDstPort", VersionNum.VERSION100); super.setDataHandler(columndesc, selectDstPrt); } /** * Get the Column entity which column name is "select_vlan" from the Row * entity of attributes. * @return the Column entity which column name is "select_vlan" */ public Column getSelectVlanColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTVLAN.columnName(), "getSelectVlanColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_vlan" to the Row entity * of attributes. * @param selectVlan the column data which column name is "select_vlan" */ public void setSelectVlan(Set<Long> selectVlan) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTVLAN.columnName(), "setSelectVlan", VersionNum.VERSION100); super.setDataHandler(columndesc, selectVlan); } /** * Get the Column entity which column name is "output_port" from the Row * entity of attributes. * @return the Column entity which column name is "output_port" */ public Column getOutputPortColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTPORT.columnName(), "getOutputPortColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "output_port" to the Row entity * of attributes. * @param outputPort the column data which column name is "output_port" */ public void setOutputPort(Set<Uuid> outputPort) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTPORT.columnName(), "setOutputPort", VersionNum.VERSION100); super.setDataHandler(columndesc, outputPort); } /** * Get the Column entity which column name is "output_vlan" from the Row * entity of attributes. * @return the Column entity which column name is "output_vlan" */ public Column getOutputVlanColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTVLAN.columnName(), "getOutputVlanColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "output_vlan" to the Row entity * of attributes. * @param outputVlan the column data which column name is "output_vlan" */ public void setOutputVlan(Set<Long> outputVlan) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTVLAN.columnName(), "setOutputVlan", VersionNum.VERSION100); super.setDataHandler(columndesc, outputVlan); } /** * Get the Column entity which column name is "statistics" from the Row * entity of attributes. * @return the Column entity which column name is "statistics" */ public Column getStatisticsColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.STATISTICS.columnName(), "getStatisticsColumn", VersionNum.VERSION640); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "statistics" to the Row entity * of attributes. * @param statistics the column data which column name is "statistics" */ public void setStatistics(Map<String, Long> statistics) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.STATISTICS.columnName(), "setStatistics", VersionNum.VERSION640); super.setDataHandler(columndesc, statistics); } /** * Get the Column entity which column name is "external_ids" from the Row * entity of attributes. * @return the Column entity which column name is "external_ids" */ public Column getExternalIdsColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.EXTERNALIDS.columnName(), "getExternalIdsColumn", VersionNum.VERSION100); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "external_ids" to the Row entity * of attributes. * @param externalIds the column data which column name is "external_ids" */ public void setExternalIds(Map<String, String> externalIds) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.EXTERNALIDS.columnName(), "setExternalIds", VersionNum.VERSION100); super.setDataHandler(columndesc, externalIds); } /** * Get the Column entity which column name is "select_all" from the Row * entity of attributes. * @return the Column entity which column name is "select_all" */ public Column getSelectAllColumn() { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTALL.columnName(), "getSelectAllColumn", VersionNum.VERSION620); return (Column) super.getColumnHandler(columndesc); } /** * Add a Column entity which column name is "select_all" to the Row entity * of attributes. * @param selectAll the column data which column name is "select_all" */ public void setSelectAll(Boolean selectAll) { ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTALL.columnName(), "setSelectAll", VersionNum.VERSION620); super.setDataHandler(columndesc, selectAll); } }
[ONOS-5036] Revise Mirror table in OVSDB protocol Change-Id: I99f5151a7a7abe7c79aec88020b1b9c63337c052
protocols/ovsdb/rfc/src/main/java/org/onosproject/ovsdb/rfc/table/Mirror.java
[ONOS-5036] Revise Mirror table in OVSDB protocol
<ide><path>rotocols/ovsdb/rfc/src/main/java/org/onosproject/ovsdb/rfc/table/Mirror.java <ide> * attributes. <ide> * @param name the column data which column name is "name" <ide> */ <del> public void setName(Set<String> name) { <add> public void setName(String name) { <ide> ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), <ide> "setName", <ide> VersionNum.VERSION100); <ide> * attributes. <ide> * @return the column data which column name is "name" <ide> */ <del> public Set<String> getName() { <add> public String getName() { <ide> ColumnDescription columndesc = new ColumnDescription(MirrorColumn.NAME.columnName(), <ide> "getName", <ide> VersionNum.VERSION100); <del> return (Set<String>) super.getDataHandler(columndesc); <add> return (String) super.getDataHandler(columndesc); <ide> } <ide> <ide> /** <ide> * of attributes. <ide> * @param selectVlan the column data which column name is "select_vlan" <ide> */ <del> public void setSelectVlan(Set<Long> selectVlan) { <add> public void setSelectVlan(Set<Short> selectVlan) { <ide> ColumnDescription columndesc = new ColumnDescription(MirrorColumn.SELECTVLAN.columnName(), <ide> "setSelectVlan", VersionNum.VERSION100); <ide> super.setDataHandler(columndesc, selectVlan); <ide> * of attributes. <ide> * @param outputPort the column data which column name is "output_port" <ide> */ <del> public void setOutputPort(Set<Uuid> outputPort) { <add> public void setOutputPort(Uuid outputPort) { <ide> ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTPORT.columnName(), <ide> "setOutputPort", VersionNum.VERSION100); <ide> super.setDataHandler(columndesc, outputPort); <ide> * of attributes. <ide> * @param outputVlan the column data which column name is "output_vlan" <ide> */ <del> public void setOutputVlan(Set<Long> outputVlan) { <add> public void setOutputVlan(Set<Short> outputVlan) { <ide> ColumnDescription columndesc = new ColumnDescription(MirrorColumn.OUTPUTVLAN.columnName(), <ide> "setOutputVlan", VersionNum.VERSION100); <ide> super.setDataHandler(columndesc, outputVlan);
Java
apache-2.0
61939179d80c437a1f96dc678d54885405ac1f8b
0
SignalK/signalk-server-java,SignalK/signalk-server-java
/* * * Copyright (C) 2012-2014 R T Huitema. All Rights Reserved. * Web: www.42.co.nz * Email: [email protected] * Author: R T Huitema * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package nz.co.fortytwo.signalk.server; import static nz.co.fortytwo.signalk.util.SignalKConstants.MSG_SRC_BUS; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_API; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_AUTH; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_CONFIG; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_DISCOVERY; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_INSTALL; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_LOGGER; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_UPGRADE; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_UPLOAD; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import javax.jmdns.JmmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import org.apache.activemq.camel.component.ActiveMQComponent; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.ahc.ws.WsEndpoint; import org.apache.camel.component.stomp.SkStompComponent; import org.apache.camel.component.websocket.SignalkWebsocketComponent; import org.apache.camel.component.websocket.WebsocketEndpoint; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.impl.PropertyPlaceholderDelegateRegistry; import org.apache.camel.model.RouteDefinition; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.server.handler.ResourceHandler; import mjson.Json; import nz.co.fortytwo.signalk.model.SignalKModel; import nz.co.fortytwo.signalk.model.impl.SignalKModelFactory; import nz.co.fortytwo.signalk.util.ConfigConstants; import nz.co.fortytwo.signalk.util.SignalKConstants; import nz.co.fortytwo.signalk.util.Util; /** * Main camel route definition to handle input to signalk * * * <ul> * <li>Basically all input is added to seda:input * <li>Message is converted to hashmap, processed,added to signalk model * <li>Output is sent out 1 sec. * </ul> * * * @author robert * */ public class RouteManager extends RouteBuilder { protected static final String JETTY_HTTP_0_0_0_0 = "jetty:http://0.0.0.0:"; public static final String _SIGNALK_HTTP_TCP_LOCAL = "_signalk-http._tcp.local."; public static final String _SIGNALK_WS_TCP_LOCAL = "_signalk-ws._tcp.local."; private static Logger logger = LogManager.getLogger(RouteManager.class); //public static final String SEDA_INPUT = "seda:inputData?purgeWhenStopping=true&size=1000"; public static final String SEDA_INPUT = "activemq:queue:inputData?jmsMessageType=Text&timeToLive=10000&asyncConsumer=true&acceptMessagesWhileStopping=true"; public static final String SEDA_WEBSOCKETS = "seda:websockets?purgeWhenStopping=true&size=1000"; public static final String DIRECT_STOMP = "direct:stomp"; public static final String DIRECT_MQTT = "direct:mqtt"; public static final String DIRECT_TCP = "seda:tcp?purgeWhenStopping=true&size=1000"; public static final String SEDA_NMEA = "seda:nmeaOutput?purgeWhenStopping=true&size=100"; public static final String SEDA_COMMON_OUT = "seda:commonOut?purgeWhenStopping=true&size=100"; public static final String STOMP = "skStomp:queue:signalk?brokerURL=tcp://0.0.0.0:"+Util.getConfigPropertyInt(ConfigConstants.STOMP_PORT); public static final String MQTT = "mqtt:signalk?host=tcp://0.0.0.0:"+Util.getConfigPropertyInt(ConfigConstants.MQTT_PORT); private JmmDNS jmdns = null; private int wsPort = 3000; private int restPort = 8080; //private String streamUrl; private SerialPortManager serialPortManager; private SignalKModel signalkModel=SignalKModelFactory.getInstance(); private NettyServer skServer; private NettyServer nmeaServer; protected RouteManager() { // web socket on port 3000 logger.info(" Websocket port:"+Util.getConfigPropertyInt(ConfigConstants.WEBSOCKET_PORT)); wsPort=Util.getConfigPropertyInt(ConfigConstants.WEBSOCKET_PORT); logger.info(" Signalk REST API port:"+Util.getConfigPropertyInt(ConfigConstants.REST_PORT)); restPort=Util.getConfigPropertyInt(ConfigConstants.REST_PORT); } @Override public void configure() throws Exception { configure0(); } public void configure0() throws Exception { //restConfiguration().component("jetty").port(8080); //sessionSupport=true&matchOnUriPrefix=true&handlers=#staticHandler&enableJMX=true //.componentProperty("handlers", "#staticHandler"); errorHandler(deadLetterChannel("direct:fail") .useOriginalMessage() .maximumRedeliveries(1) .redeliveryDelay(1000)); from ("direct:fail").id("Fail") .to("log:log:nz.co.fortytwo.signalk.error?level=ERROR&showAll=true"); SignalKModelFactory.load(signalkModel); //set shutdown quickly, 5 min is too long CamelContextFactory.getInstance().getShutdownStrategy().setShutdownNowOnTimeout(true); CamelContextFactory.getInstance().getShutdownStrategy().setTimeout(10); //CamelContextFactory.getInstance().addComponent("activemq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false")); //DNS-SD, zeroconf mDNS startMdns(); //Netty tcp server skServer = new NettyServer(null, ConfigConstants.OUTPUT_TCP); skServer.setTcpPort(Util.getConfigPropertyInt(ConfigConstants.TCP_PORT)); skServer.setUdpPort(Util.getConfigPropertyInt(ConfigConstants.UDP_PORT)); skServer.run(); nmeaServer = new NettyServer(null, ConfigConstants.OUTPUT_NMEA); nmeaServer.setTcpPort(Util.getConfigPropertyInt(ConfigConstants.TCP_NMEA_PORT)); nmeaServer.setUdpPort(Util.getConfigPropertyInt(ConfigConstants.UDP_NMEA_PORT)); nmeaServer.run(); // start a serial port manager if(serialPortManager==null){ serialPortManager = new SerialPortManager(); } new Thread(serialPortManager).start(); // main input to destination route // put all input into signalk model SignalkRouteFactory.configureInputRoute(this, SEDA_INPUT); File htmlRoot = new File(Util.getConfigProperty(ConfigConstants.STATIC_DIR)); log.info("Serving static files from "+htmlRoot.getAbsolutePath()); //restlet //bind in registry PropertyPlaceholderDelegateRegistry registry = (PropertyPlaceholderDelegateRegistry) CamelContextFactory.getInstance().getRegistry(); JndiRegistry reg = (JndiRegistry)registry.getRegistry(); if(reg.lookup("staticHandler")==null){ ResourceHandler staticHandler = new ResourceHandler(); staticHandler.setResourceBase(Util.getConfigProperty(ConfigConstants.STATIC_DIR)); staticHandler.setDirectoriesListed(false); MimeTypes mimeTypes = staticHandler.getMimeTypes(); mimeTypes.addMimeMapping("log", MimeTypes.TEXT_HTML_UTF_8); staticHandler.setMimeTypes(mimeTypes); //static files reg.bind("staticHandler",staticHandler ); } restConfiguration().component("jetty") .consumerProperty("matchOnUriPrefix", "true") .componentProperty("matchOnUriPrefix", "true") .host("0.0.0.0").port(8080); //websockets if(CamelContextFactory.getInstance().getComponent("skWebsocket")==null){ SignalkWebsocketComponent skws = new SignalkWebsocketComponent(); CamelContextFactory.getInstance().addComponent("skWebsocket", skws); } //STOMP if(CamelContextFactory.getInstance().getComponent("skStomp")==null){ CamelContextFactory.getInstance().addComponent("skStomp", new SkStompComponent()); } //setup routes SignalkRouteFactory.configureWebsocketTxRoute(this, SEDA_WEBSOCKETS, wsPort); SignalkRouteFactory.configureWebsocketRxRoute(this, SEDA_INPUT, wsPort); SignalkRouteFactory.configureTcpServerRoute(this, DIRECT_TCP, skServer, ConfigConstants.OUTPUT_TCP); SignalkRouteFactory.configureTcpServerRoute(this, SEDA_NMEA, nmeaServer, ConfigConstants.OUTPUT_NMEA); SignalkRouteFactory.configureCommonOut(this); SignalkRouteFactory.configureHeartbeatRoute(this,"timer://heartbeat?fixedRate=true&period=1000"); SignalkRouteFactory.configureAuthRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_AUTH+"?sessionSupport=true&matchOnUriPrefix=true&handlers=#staticHandler&enableJMX=true&enableCORS=true"); SignalkRouteFactory.configureRestRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_DISCOVERY+"?sessionSupport=true&matchOnUriPrefix=false&enableJMX=true&enableCORS=true","REST Discovery"); SignalkRouteFactory.configureRestRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_API+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true&enableCORS=true","REST Api"); SignalkRouteFactory.configureRestConfigRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_CONFIG+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true&enableCORS=false","Config Api"); SignalkRouteFactory.configureRestLoggerRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_LOGGER+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true&enableCORS=false","Logger"); SignalkRouteFactory.configureRestUploadRoute(this, SIGNALK_UPLOAD,"Upload"); if(Util.getConfigPropertyBoolean(ConfigConstants.ALLOW_INSTALL)){ SignalkRouteFactory.configureInstallRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_INSTALL+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true", "REST Install"); } if(Util.getConfigPropertyBoolean(ConfigConstants.ALLOW_UPGRADE)){ SignalkRouteFactory.configureInstallRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_UPGRADE+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true", "REST Upgrade"); } // timed actions SignalkRouteFactory.configureBackgroundTimer(this, "timer://background?fixedRate=true&period=60000"); SignalkRouteFactory.configureWindTimer(this, "timer://wind?fixedRate=true&period=1000"); SignalkRouteFactory.configureAnchorWatchTimer(this, "timer://anchorWatch?fixedRate=true&period=5000"); SignalkRouteFactory.configureAlarmsTimer(this, "timer://alarms?fixedRate=true&period=1000"); if(Util.getConfigPropertyBoolean(ConfigConstants.GENERATE_NMEA0183)){ SignalkRouteFactory.configureNMEA0183Timer(this, "timer://nmea0183?fixedRate=true&period=1000"); } //STOMP if(Util.getConfigPropertyBoolean(ConfigConstants.START_STOMP)){ from("skStomp:queue:signalk.put").id("STOMP In") .setHeader(ConfigConstants.OUTPUT_TYPE, constant(ConfigConstants.OUTPUT_STOMP)) .setHeader(MSG_SRC_BUS, constant("stomp.queue:signalk.put")) .to(SEDA_INPUT).id(SignalkRouteFactory.getName("SEDA_INPUT")); } //MQTT if(Util.getConfigPropertyBoolean(ConfigConstants.START_MQTT)){ from(MQTT+"&subscribeTopicName=signalk.put").id("MQTT In") .transform(body().convertToString()) .setHeader(ConfigConstants.OUTPUT_TYPE, constant(ConfigConstants.OUTPUT_MQTT)) .setHeader(MSG_SRC_BUS, constant("mqtt.queue:signalk.put")) .to(SEDA_INPUT).id(SignalkRouteFactory.getName("SEDA_INPUT")); } //start any clients if they exist //WS Json wsClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_WS); logger.info(" Starting WS connection to url:"+wsClients); if(wsClients!=null){ for(Json client: wsClients.asJsonList()){ logger.info(" Starting WS connection to url:ahc-ws://"+client.asString()); startWsClient(client.asString()); } } //TCP Json tcpClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_TCP); if(tcpClients!=null){ for(Object client: tcpClients.asList()){ from("netty4:tcp://"+client+"?clientMode=true&textline=true").id("TCP Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.tcp?level=ERROR&showException=true&showStackTrace=true") .end() .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("stomp."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); } } //MQTT Json mqttClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_MQTT); if(mqttClients!=null){ for(Object client: mqttClients.asList()){ from("mqtt://"+client).id("MQTT Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.mqtt?level=ERROR&showException=true&showStackTrace=true") .end() .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("mqtt."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); } } //STOMP //TODO: test stomp client actually works! Json stompClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_STOMP); if(stompClients!=null){ for(Object client: stompClients.asList()){ from("stomp://"+client).id("STOMP Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.stomp?level=ERROR&showException=true&showStackTrace=true") .end() .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("stomp."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); } } //Demo mode if (Util.getConfigPropertyBoolean(ConfigConstants.DEMO)) { String streamUrl = Util.getConfigProperty(ConfigConstants.STREAM_URL); logger.info(" Demo streaming url:"+Util.getConfigProperty(ConfigConstants.STREAM_URL)); from("file://./src/test/resources/samples/?move=done&fileName=" + streamUrl).id("demo feed") .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.model.receive?level=ERROR&showException=true&showStackTrace=true") .end() .split(body().tokenize("\n")).streaming() .convertBodyTo(String.class) .throttle(2).timePeriodMillis(1000) .setHeader(MSG_SRC_BUS, constant("demo")) .to(SEDA_INPUT).id(SignalkRouteFactory.getName("SEDA_INPUT")) .end(); //and copy it back again to rerun it from("file://./src/test/resources/samples/done?fileName=" + streamUrl).id("demo restart") .onException(Exception.class).handled(true).maximumRedeliveries(0) .end() .to("file://./src/test/resources/samples/?fileName=" + streamUrl); } SignalkRouteFactory.startLogRoutes(this, JETTY_HTTP_0_0_0_0, restPort); if (Util.getConfigPropertyBoolean(ConfigConstants.ZEROCONF_AUTO)) { startMdnsAutoconnect(); } } private void startMdnsAutoconnect() { //now listen and report other services logger.info("Starting jmdns listener.."); jmdns.addServiceListener(_SIGNALK_WS_TCP_LOCAL, new ServiceListener() { @Override public void serviceResolved(ServiceEvent evt) { try { //if(evt.getInfo().getInet4Addresses().length==0){ String name = evt.getName(); String thisHost = evt.getDNS().getInetAddress().getHostAddress(); logger.info("Resolved mDns service:"+name+" at "+thisHost); logger.debug(name+" Server:"+evt.getInfo().getServer()); String[] remoteHost = evt.getInfo().getHostAddresses(); logger.debug(name+" Remotehost:"+remoteHost[0]); //logger.error(name+" Type:"+evt.getInfo().getType()); //logger.error(name+" Port:"+evt.getInfo().getPort()); //logger.error(name+" Protocol:"+evt.getInfo().getProtocol()); //logger.error(name+" IPV4s:"+Arrays.toString(evt.getInfo().getInet4Addresses())); //int port = evt.getInfo().getPort(); //logger.error(name+" Port:"+port); //logger.error(name+" QName:"+evt.getInfo().getQualifiedName()); logger.debug(name+" URLs:"+Arrays.toString(evt.getInfo().getURLs())); if(thisHost.startsWith(remoteHost[0]) || evt.getDNS().getInetAddress().isLinkLocalAddress() || evt.getDNS().getInetAddress().isLoopbackAddress()){ logger.info(name+" Found own host: "+remoteHost[0]+", ignoring.."); return; } if(remoteHost[0].startsWith("[fe80") || evt.getDNS().getInetAddress().isLinkLocalAddress()){ logger.info(name+" Found ipv6 host: "+remoteHost[0]+", ignoring.."); return; } //we want to connect here String url =evt.getInfo().getURLs()[0]; if(StringUtils.isNotBlank(url)){ logger.info(name+" Connecting to: "+url); url=url.substring(url.indexOf("://")+3); url=url+"/v1/stream"; logger.info(" Starting WS connection to url:ahc-ws://"+url); startWsClient(url); } } catch (Exception e) { logger.error(e); } } @Override public void serviceRemoved(ServiceEvent evt) { logger.info("Lost mDns service:"+evt.getName()); //String url =evt.getInfo().getURLs()[0]; logger.info("Lost service url:"+evt.toString()); } @Override public void serviceAdded(ServiceEvent evt) { logger.info("Found mDns service:"+evt.getName()+" at "+evt.getType()); } }); logger.info("Started jmdns listener"); } private void startWsClient(String client) throws Exception { WsEndpoint wsEndpoint = (WsEndpoint)getContext().getEndpoint("ahc-ws://"+client); RouteDefinition route = from(wsEndpoint); route.onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.ws?level=ERROR&showException=true&showStackTrace=true") .end() .to("log:nz.co.fortytwo.signalk.client.ws?level=DEBUG") .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("ws."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); route.setId("Websocket Client:"+client); ((DefaultCamelContext)CamelContextFactory.getInstance()).addRouteDefinition(route); ((DefaultCamelContext)CamelContextFactory.getInstance()).startRoute(route.getId()); wsEndpoint.connect(); } public void stopNettyServers(){ if(skServer!=null){ skServer.shutdownServer(); skServer=null; } if(nmeaServer!=null){ nmeaServer.shutdownServer(); nmeaServer=null; } } /** * When the serial port is used to read from the arduino this must be called to shut * down the readers, which are in their own threads. */ public void stopSerial() { serialPortManager.stopSerial(); serialPortManager=null; } /** * Stop the DNS-SD server. * @throws IOException */ public void stopMdns() throws IOException { if(jmdns!=null){ jmdns.unregisterAllServices(); jmdns.close(); jmdns=null; } } private void startMdns() { //DNS-SD //NetworkTopologyDiscovery netTop = NetworkTopologyDiscovery.Factory.getInstance(); Runnable r = new Runnable() { @Override public void run() { jmdns = JmmDNS.Factory.getInstance(); jmdns.registerServiceType(_SIGNALK_WS_TCP_LOCAL); jmdns.registerServiceType(_SIGNALK_HTTP_TCP_LOCAL); ServiceInfo wsInfo = ServiceInfo.create(_SIGNALK_WS_TCP_LOCAL,"signalk-ws",wsPort, 0,0, getMdnsTxt()); try { jmdns.registerService(wsInfo); ServiceInfo httpInfo = ServiceInfo .create(_SIGNALK_HTTP_TCP_LOCAL, "signalk-http",restPort,0,0, getMdnsTxt()); jmdns.registerService(httpInfo); } catch (IOException e) { e.printStackTrace(); } } }; Thread t = new Thread(r); t.setDaemon(true); t.start(); } private Map<String,String> getMdnsTxt() { Map<String,String> txtSet = new HashMap<String, String>(); txtSet.put("path", SIGNALK_DISCOVERY); txtSet.put("server","signalk-server"); txtSet.put("version",Util.getConfigProperty(ConfigConstants.VERSION)); txtSet.put("vessel_name",Util.getConfigProperty(ConfigConstants.UUID)); txtSet.put("vessel_mmsi",Util.getConfigProperty(ConfigConstants.UUID)); txtSet.put("vessel_uuid",Util.getConfigProperty(ConfigConstants.UUID)); return txtSet; } }
src/main/java/nz/co/fortytwo/signalk/server/RouteManager.java
/* * * Copyright (C) 2012-2014 R T Huitema. All Rights Reserved. * Web: www.42.co.nz * Email: [email protected] * Author: R T Huitema * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package nz.co.fortytwo.signalk.server; import static nz.co.fortytwo.signalk.util.SignalKConstants.MSG_SRC_BUS; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_API; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_AUTH; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_CONFIG; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_DISCOVERY; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_INSTALL; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_LOGGER; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_UPGRADE; import static nz.co.fortytwo.signalk.util.SignalKConstants.SIGNALK_UPLOAD; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import javax.jmdns.JmmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import org.apache.activemq.camel.component.ActiveMQComponent; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.ahc.ws.WsEndpoint; import org.apache.camel.component.stomp.SkStompComponent; import org.apache.camel.component.websocket.SignalkWebsocketComponent; import org.apache.camel.component.websocket.WebsocketEndpoint; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.impl.PropertyPlaceholderDelegateRegistry; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.server.handler.ResourceHandler; import mjson.Json; import nz.co.fortytwo.signalk.model.SignalKModel; import nz.co.fortytwo.signalk.model.impl.SignalKModelFactory; import nz.co.fortytwo.signalk.util.ConfigConstants; import nz.co.fortytwo.signalk.util.SignalKConstants; import nz.co.fortytwo.signalk.util.Util; /** * Main camel route definition to handle input to signalk * * * <ul> * <li>Basically all input is added to seda:input * <li>Message is converted to hashmap, processed,added to signalk model * <li>Output is sent out 1 sec. * </ul> * * * @author robert * */ public class RouteManager extends RouteBuilder { protected static final String JETTY_HTTP_0_0_0_0 = "jetty:http://0.0.0.0:"; public static final String _SIGNALK_HTTP_TCP_LOCAL = "_signalk-http._tcp.local."; public static final String _SIGNALK_WS_TCP_LOCAL = "_signalk-ws._tcp.local."; private static Logger logger = LogManager.getLogger(RouteManager.class); //public static final String SEDA_INPUT = "seda:inputData?purgeWhenStopping=true&size=1000"; public static final String SEDA_INPUT = "activemq:queue:inputData?jmsMessageType=Text&timeToLive=10000&asyncConsumer=true&acceptMessagesWhileStopping=true"; public static final String SEDA_WEBSOCKETS = "seda:websockets?purgeWhenStopping=true&size=1000"; public static final String DIRECT_STOMP = "direct:stomp"; public static final String DIRECT_MQTT = "direct:mqtt"; public static final String DIRECT_TCP = "seda:tcp?purgeWhenStopping=true&size=1000"; public static final String SEDA_NMEA = "seda:nmeaOutput?purgeWhenStopping=true&size=100"; public static final String SEDA_COMMON_OUT = "seda:commonOut?purgeWhenStopping=true&size=100"; public static final String STOMP = "skStomp:queue:signalk?brokerURL=tcp://0.0.0.0:"+Util.getConfigPropertyInt(ConfigConstants.STOMP_PORT); public static final String MQTT = "mqtt:signalk?host=tcp://0.0.0.0:"+Util.getConfigPropertyInt(ConfigConstants.MQTT_PORT); private JmmDNS jmdns = null; private int wsPort = 3000; private int restPort = 8080; //private String streamUrl; private SerialPortManager serialPortManager; private SignalKModel signalkModel=SignalKModelFactory.getInstance(); private NettyServer skServer; private NettyServer nmeaServer; protected RouteManager() { // web socket on port 3000 logger.info(" Websocket port:"+Util.getConfigPropertyInt(ConfigConstants.WEBSOCKET_PORT)); wsPort=Util.getConfigPropertyInt(ConfigConstants.WEBSOCKET_PORT); logger.info(" Signalk REST API port:"+Util.getConfigPropertyInt(ConfigConstants.REST_PORT)); restPort=Util.getConfigPropertyInt(ConfigConstants.REST_PORT); } @Override public void configure() throws Exception { configure0(); } public void configure0() throws Exception { //restConfiguration().component("jetty").port(8080); //sessionSupport=true&matchOnUriPrefix=true&handlers=#staticHandler&enableJMX=true //.componentProperty("handlers", "#staticHandler"); errorHandler(deadLetterChannel("direct:fail") .useOriginalMessage() .maximumRedeliveries(1) .redeliveryDelay(1000)); from ("direct:fail").id("Fail") .to("log:log:nz.co.fortytwo.signalk.error?level=ERROR&showAll=true"); SignalKModelFactory.load(signalkModel); //set shutdown quickly, 5 min is too long CamelContextFactory.getInstance().getShutdownStrategy().setShutdownNowOnTimeout(true); CamelContextFactory.getInstance().getShutdownStrategy().setTimeout(10); //CamelContextFactory.getInstance().addComponent("activemq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false")); //DNS-SD, zeroconf mDNS startMdns(); //Netty tcp server skServer = new NettyServer(null, ConfigConstants.OUTPUT_TCP); skServer.setTcpPort(Util.getConfigPropertyInt(ConfigConstants.TCP_PORT)); skServer.setUdpPort(Util.getConfigPropertyInt(ConfigConstants.UDP_PORT)); skServer.run(); nmeaServer = new NettyServer(null, ConfigConstants.OUTPUT_NMEA); nmeaServer.setTcpPort(Util.getConfigPropertyInt(ConfigConstants.TCP_NMEA_PORT)); nmeaServer.setUdpPort(Util.getConfigPropertyInt(ConfigConstants.UDP_NMEA_PORT)); nmeaServer.run(); // start a serial port manager if(serialPortManager==null){ serialPortManager = new SerialPortManager(); } new Thread(serialPortManager).start(); // main input to destination route // put all input into signalk model SignalkRouteFactory.configureInputRoute(this, SEDA_INPUT); File htmlRoot = new File(Util.getConfigProperty(ConfigConstants.STATIC_DIR)); log.info("Serving static files from "+htmlRoot.getAbsolutePath()); //restlet //bind in registry PropertyPlaceholderDelegateRegistry registry = (PropertyPlaceholderDelegateRegistry) CamelContextFactory.getInstance().getRegistry(); JndiRegistry reg = (JndiRegistry)registry.getRegistry(); if(reg.lookup("staticHandler")==null){ ResourceHandler staticHandler = new ResourceHandler(); staticHandler.setResourceBase(Util.getConfigProperty(ConfigConstants.STATIC_DIR)); staticHandler.setDirectoriesListed(false); MimeTypes mimeTypes = staticHandler.getMimeTypes(); mimeTypes.addMimeMapping("log", MimeTypes.TEXT_HTML_UTF_8); staticHandler.setMimeTypes(mimeTypes); //static files reg.bind("staticHandler",staticHandler ); } restConfiguration().component("jetty") .consumerProperty("matchOnUriPrefix", "true") .componentProperty("matchOnUriPrefix", "true") .host("0.0.0.0").port(8080); //websockets if(CamelContextFactory.getInstance().getComponent("skWebsocket")==null){ SignalkWebsocketComponent skws = new SignalkWebsocketComponent(); CamelContextFactory.getInstance().addComponent("skWebsocket", skws); } //STOMP if(CamelContextFactory.getInstance().getComponent("skStomp")==null){ CamelContextFactory.getInstance().addComponent("skStomp", new SkStompComponent()); } //setup routes SignalkRouteFactory.configureWebsocketTxRoute(this, SEDA_WEBSOCKETS, wsPort); SignalkRouteFactory.configureWebsocketRxRoute(this, SEDA_INPUT, wsPort); SignalkRouteFactory.configureTcpServerRoute(this, DIRECT_TCP, skServer, ConfigConstants.OUTPUT_TCP); SignalkRouteFactory.configureTcpServerRoute(this, SEDA_NMEA, nmeaServer, ConfigConstants.OUTPUT_NMEA); SignalkRouteFactory.configureCommonOut(this); SignalkRouteFactory.configureHeartbeatRoute(this,"timer://heartbeat?fixedRate=true&period=1000"); SignalkRouteFactory.configureAuthRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_AUTH+"?sessionSupport=true&matchOnUriPrefix=true&handlers=#staticHandler&enableJMX=true&enableCORS=true"); SignalkRouteFactory.configureRestRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_DISCOVERY+"?sessionSupport=true&matchOnUriPrefix=false&enableJMX=true&enableCORS=true","REST Discovery"); SignalkRouteFactory.configureRestRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_API+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true&enableCORS=true","REST Api"); SignalkRouteFactory.configureRestConfigRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_CONFIG+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true&enableCORS=false","Config Api"); SignalkRouteFactory.configureRestLoggerRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_LOGGER+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true&enableCORS=false","Logger"); SignalkRouteFactory.configureRestUploadRoute(this, SIGNALK_UPLOAD,"Upload"); if(Util.getConfigPropertyBoolean(ConfigConstants.ALLOW_INSTALL)){ SignalkRouteFactory.configureInstallRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_INSTALL+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true", "REST Install"); } if(Util.getConfigPropertyBoolean(ConfigConstants.ALLOW_UPGRADE)){ SignalkRouteFactory.configureInstallRoute(this, JETTY_HTTP_0_0_0_0 + restPort + SIGNALK_UPGRADE+"?sessionSupport=true&matchOnUriPrefix=true&enableJMX=true", "REST Upgrade"); } // timed actions SignalkRouteFactory.configureBackgroundTimer(this, "timer://background?fixedRate=true&period=60000"); SignalkRouteFactory.configureWindTimer(this, "timer://wind?fixedRate=true&period=1000"); SignalkRouteFactory.configureAnchorWatchTimer(this, "timer://anchorWatch?fixedRate=true&period=5000"); SignalkRouteFactory.configureAlarmsTimer(this, "timer://alarms?fixedRate=true&period=1000"); if(Util.getConfigPropertyBoolean(ConfigConstants.GENERATE_NMEA0183)){ SignalkRouteFactory.configureNMEA0183Timer(this, "timer://nmea0183?fixedRate=true&period=1000"); } //STOMP if(Util.getConfigPropertyBoolean(ConfigConstants.START_STOMP)){ from("skStomp:queue:signalk.put").id("STOMP In") .setHeader(ConfigConstants.OUTPUT_TYPE, constant(ConfigConstants.OUTPUT_STOMP)) .setHeader(MSG_SRC_BUS, constant("stomp.queue:signalk.put")) .to(SEDA_INPUT).id(SignalkRouteFactory.getName("SEDA_INPUT")); } //MQTT if(Util.getConfigPropertyBoolean(ConfigConstants.START_MQTT)){ from(MQTT+"&subscribeTopicName=signalk.put").id("MQTT In") .transform(body().convertToString()) .setHeader(ConfigConstants.OUTPUT_TYPE, constant(ConfigConstants.OUTPUT_MQTT)) .setHeader(MSG_SRC_BUS, constant("mqtt.queue:signalk.put")) .to(SEDA_INPUT).id(SignalkRouteFactory.getName("SEDA_INPUT")); } //start any clients if they exist //WS Json wsClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_WS); logger.info(" Starting WS connection to url:"+wsClients); if(wsClients!=null){ for(Json client: wsClients.asJsonList()){ logger.info(" Starting WS connection to url:ahc-ws://"+client.asString()); startWsClient(client.asString()); } } //TCP Json tcpClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_TCP); if(tcpClients!=null){ for(Object client: tcpClients.asList()){ from("netty4:tcp://"+client+"?clientMode=true&textline=true").id("TCP Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.tcp?level=ERROR&showException=true&showStackTrace=true") .end() .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("stomp."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); } } //MQTT Json mqttClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_MQTT); if(mqttClients!=null){ for(Object client: mqttClients.asList()){ from("mqtt://"+client).id("MQTT Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.mqtt?level=ERROR&showException=true&showStackTrace=true") .end() .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("mqtt."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); } } //STOMP //TODO: test stomp client actually works! Json stompClients = Util.getConfigJsonArray(ConfigConstants.CLIENT_STOMP); if(stompClients!=null){ for(Object client: stompClients.asList()){ from("stomp://"+client).id("STOMP Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.stomp?level=ERROR&showException=true&showStackTrace=true") .end() .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("stomp."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); } } //Demo mode if (Util.getConfigPropertyBoolean(ConfigConstants.DEMO)) { String streamUrl = Util.getConfigProperty(ConfigConstants.STREAM_URL); logger.info(" Demo streaming url:"+Util.getConfigProperty(ConfigConstants.STREAM_URL)); from("file://./src/test/resources/samples/?move=done&fileName=" + streamUrl).id("demo feed") .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.model.receive?level=ERROR&showException=true&showStackTrace=true") .end() .split(body().tokenize("\n")).streaming() .convertBodyTo(String.class) .throttle(2).timePeriodMillis(1000) .setHeader(MSG_SRC_BUS, constant("demo")) .to(SEDA_INPUT).id(SignalkRouteFactory.getName("SEDA_INPUT")) .end(); //and copy it back again to rerun it from("file://./src/test/resources/samples/done?fileName=" + streamUrl).id("demo restart") .onException(Exception.class).handled(true).maximumRedeliveries(0) .end() .to("file://./src/test/resources/samples/?fileName=" + streamUrl); } SignalkRouteFactory.startLogRoutes(this, JETTY_HTTP_0_0_0_0, restPort); if (Util.getConfigPropertyBoolean(ConfigConstants.ZEROCONF_AUTO)) { startMdnsAutoconnect(); } } private void startMdnsAutoconnect() { //now listen and report other services logger.info("Starting jmdns listener.."); jmdns.addServiceListener(_SIGNALK_WS_TCP_LOCAL, new ServiceListener() { @Override public void serviceResolved(ServiceEvent evt) { try { //if(evt.getInfo().getInet4Addresses().length==0){ String name = evt.getName(); String thisHost = evt.getDNS().getInetAddress().getHostAddress(); logger.info("Resolved mDns service:"+name+" at "+thisHost); logger.debug(name+" Server:"+evt.getInfo().getServer()); String[] remoteHost = evt.getInfo().getHostAddresses(); logger.debug(name+" Remotehost:"+remoteHost[0]); //logger.error(name+" Type:"+evt.getInfo().getType()); //logger.error(name+" Port:"+evt.getInfo().getPort()); //logger.error(name+" Protocol:"+evt.getInfo().getProtocol()); //logger.error(name+" IPV4s:"+Arrays.toString(evt.getInfo().getInet4Addresses())); //int port = evt.getInfo().getPort(); //logger.error(name+" Port:"+port); //logger.error(name+" QName:"+evt.getInfo().getQualifiedName()); logger.debug(name+" URLs:"+Arrays.toString(evt.getInfo().getURLs())); if(thisHost.startsWith(remoteHost[0]) || evt.getDNS().getInetAddress().isLinkLocalAddress() || evt.getDNS().getInetAddress().isLoopbackAddress()){ logger.info(name+" Found own host: "+remoteHost[0]+", ignoring.."); return; } if(remoteHost[0].startsWith("[fe80") || evt.getDNS().getInetAddress().isLinkLocalAddress()){ logger.info(name+" Found ipv6 host: "+remoteHost[0]+", ignoring.."); return; } //we want to connect here String url =evt.getInfo().getURLs()[0]; if(StringUtils.isNotBlank(url)){ logger.info(name+" Connecting to: "+url); url=url.substring(url.indexOf("://")+3); url=url+"/v1/stream"; logger.info(" Starting WS connection to url:ahc-ws://"+url); startWsClient(url); } } catch (Exception e) { logger.error(e); } } @Override public void serviceRemoved(ServiceEvent evt) { logger.info("Lost mDns service:"+evt.getName()); } @Override public void serviceAdded(ServiceEvent evt) { logger.info("Found mDns service:"+evt.getName()+" at "+evt.getType()); } }); logger.info("Started jmdns listener"); } private void startWsClient(String client) throws InterruptedException, ExecutionException, IOException { WsEndpoint wsEndpoint = (WsEndpoint)getContext().getEndpoint("ahc-ws://"+client); from(wsEndpoint).id("Websocket Client:"+client) .onException(Exception.class).handled(true).maximumRedeliveries(0) .to("log:nz.co.fortytwo.signalk.client.ws?level=ERROR&showException=true&showStackTrace=true") .end() .to("log:nz.co.fortytwo.signalk.client.ws?level=DEBUG") .convertBodyTo(String.class) .setHeader(MSG_SRC_BUS, constant("ws."+client.toString().replace('.', '_'))) .to(SEDA_INPUT); wsEndpoint.connect(); } public void stopNettyServers(){ if(skServer!=null){ skServer.shutdownServer(); skServer=null; } if(nmeaServer!=null){ nmeaServer.shutdownServer(); nmeaServer=null; } } /** * When the serial port is used to read from the arduino this must be called to shut * down the readers, which are in their own threads. */ public void stopSerial() { serialPortManager.stopSerial(); serialPortManager=null; } /** * Stop the DNS-SD server. * @throws IOException */ public void stopMdns() throws IOException { if(jmdns!=null){ jmdns.unregisterAllServices(); jmdns.close(); jmdns=null; } } private void startMdns() { //DNS-SD //NetworkTopologyDiscovery netTop = NetworkTopologyDiscovery.Factory.getInstance(); Runnable r = new Runnable() { @Override public void run() { jmdns = JmmDNS.Factory.getInstance(); jmdns.registerServiceType(_SIGNALK_WS_TCP_LOCAL); jmdns.registerServiceType(_SIGNALK_HTTP_TCP_LOCAL); ServiceInfo wsInfo = ServiceInfo.create(_SIGNALK_WS_TCP_LOCAL,"signalk-ws",wsPort, 0,0, getMdnsTxt()); try { jmdns.registerService(wsInfo); ServiceInfo httpInfo = ServiceInfo .create(_SIGNALK_HTTP_TCP_LOCAL, "signalk-http",restPort,0,0, getMdnsTxt()); jmdns.registerService(httpInfo); } catch (IOException e) { e.printStackTrace(); } } }; Thread t = new Thread(r); t.setDaemon(true); t.start(); } private Map<String,String> getMdnsTxt() { Map<String,String> txtSet = new HashMap<String, String>(); txtSet.put("path", SIGNALK_DISCOVERY); txtSet.put("server","signalk-server"); txtSet.put("version",Util.getConfigProperty(ConfigConstants.VERSION)); txtSet.put("vessel_name",Util.getConfigProperty(ConfigConstants.UUID)); txtSet.put("vessel_mmsi",Util.getConfigProperty(ConfigConstants.UUID)); txtSet.put("vessel_uuid",Util.getConfigProperty(ConfigConstants.UUID)); return txtSet; } }
mDns websockets now start properly
src/main/java/nz/co/fortytwo/signalk/server/RouteManager.java
mDns websockets now start properly
<ide><path>rc/main/java/nz/co/fortytwo/signalk/server/RouteManager.java <ide> import org.apache.camel.component.stomp.SkStompComponent; <ide> import org.apache.camel.component.websocket.SignalkWebsocketComponent; <ide> import org.apache.camel.component.websocket.WebsocketEndpoint; <add>import org.apache.camel.impl.DefaultCamelContext; <ide> import org.apache.camel.impl.JndiRegistry; <ide> import org.apache.camel.impl.PropertyPlaceholderDelegateRegistry; <add>import org.apache.camel.model.RouteDefinition; <ide> import org.apache.commons.lang3.StringUtils; <ide> import org.apache.logging.log4j.LogManager; <ide> import org.apache.logging.log4j.Logger; <ide> //we want to connect here <ide> String url =evt.getInfo().getURLs()[0]; <ide> if(StringUtils.isNotBlank(url)){ <del> logger.info(name+" Connecting to: "+url); <del> <del> url=url.substring(url.indexOf("://")+3); <del> url=url+"/v1/stream"; <del> logger.info(" Starting WS connection to url:ahc-ws://"+url); <del> <del> startWsClient(url); <del> <del> } <add> logger.info(name+" Connecting to: "+url); <add> <add> url=url.substring(url.indexOf("://")+3); <add> url=url+"/v1/stream"; <add> logger.info(" Starting WS connection to url:ahc-ws://"+url); <add> <add> startWsClient(url); <add> <add> } <ide> <ide> } catch (Exception e) { <ide> <ide> @Override <ide> public void serviceRemoved(ServiceEvent evt) { <ide> logger.info("Lost mDns service:"+evt.getName()); <del> <add> //String url =evt.getInfo().getURLs()[0]; <add> logger.info("Lost service url:"+evt.toString()); <ide> } <ide> <ide> @Override <ide> <ide> } <ide> <del> private void startWsClient(String client) throws InterruptedException, ExecutionException, IOException { <add> private void startWsClient(String client) throws Exception { <ide> WsEndpoint wsEndpoint = (WsEndpoint)getContext().getEndpoint("ahc-ws://"+client); <del> from(wsEndpoint).id("Websocket Client:"+client) <del> .onException(Exception.class).handled(true).maximumRedeliveries(0) <add> RouteDefinition route = from(wsEndpoint); <add> <add> route.onException(Exception.class).handled(true).maximumRedeliveries(0) <ide> .to("log:nz.co.fortytwo.signalk.client.ws?level=ERROR&showException=true&showStackTrace=true") <ide> .end() <ide> .to("log:nz.co.fortytwo.signalk.client.ws?level=DEBUG") <ide> .convertBodyTo(String.class) <ide> .setHeader(MSG_SRC_BUS, constant("ws."+client.toString().replace('.', '_'))) <ide> .to(SEDA_INPUT); <del> <add> route.setId("Websocket Client:"+client); <add> ((DefaultCamelContext)CamelContextFactory.getInstance()).addRouteDefinition(route); <add> ((DefaultCamelContext)CamelContextFactory.getInstance()).startRoute(route.getId()); <ide> wsEndpoint.connect(); <ide> <ide> }
JavaScript
mpl-2.0
bbfa047639bc475b0a0e72bc1d6d1a1043538804
0
ThosRTanner/inforss,ThosRTanner/inforss
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is infoRSS. * * The Initial Developer of the Original Code is * Didier Ernotte <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Didier Ernotte <[email protected]>. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //------------------------------------------------------------------------------ // inforssFeedManager // Author : Didier Ernotte 2005 // Inforss extension //------------------------------------------------------------------------------ /* globals inforssDebug, inforssTraceIn, inforssTraceOut */ Components.utils.import("chrome://inforss/content/modules/inforssDebug.jsm"); var gPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch(null); /* globals inforssRDFRepository, inforssXMLRepository */ /* globals inforssRead, inforssAddItemToMenu, inforssRelocateBar, inforssInformation */ //FIXME get rid of all the 2 phase initialisation //FIXME get rid of all the global function calls function inforssFeedManager(mediator) { this.mediator = mediator; this.rdfRepository = new inforssRDFRepository(); this.schedule_timeout = null; this.cycle_timeout = null; this.feed_list = []; this.selectedInfo = null; return this; } inforssFeedManager.prototype = { //------------------------------------------------------------------------------------------------------------- init: function() { inforssTraceIn(this); try { /* This feels uncomfy here */ inforssRead(); for (let item of inforssXMLRepository.get_all()) { inforssAddItemToMenu(item); } inforssRelocateBar(); //And should this be somewhere else? /* down to here */ //Among other things, I think the global mediator should pass the inforssXmlRepository //to all of these. this.rdfRepository.init(); var oldSelected = this.selectedInfo; this.selectedInfo = null; for (let feed of this.feed_list) { feed.reset(); } window.clearTimeout(this.schedule_timeout); window.clearTimeout(this.cycle_timeout); //Possibly the wrong one. Why in any case do we force this arbitrarily to //the first feed. If we don't have a selected one, maybe just not have one? var selectedInfo = this.getSelectedInfo(true); if (selectedInfo != null) { if (oldSelected != null && oldSelected.getUrl() != selectedInfo.getUrl()) { oldSelected.deactivate(); } //FIXME This is pretty much identical to setSelected //why both? //See line 316 //inforssHeadlineDisplay.apply_recent_headline_style(selectedInfo.menuItem, false); // selectedInfo.reset(); // if (inforssXMLRepository.headline_bar_enabled()) { selectedInfo.activate(); this.schedule_fetch(0); if (inforssXMLRepository.headline_bar_cycle_feeds) { this.schedule_cycle(); } if (selectedInfo.getType() == "group") { this.mediator.updateMenuIcon(selectedInfo); } } else { selectedInfo.deactivate(); } } this.mediator.refreshBar(); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //Start the next fetch as soon as we've finished here. //Clear any existing fetch. schedule_fetch : function(timeout) { window.clearTimeout(this.schedule_timeout); this.schedule_timeout = window.setTimeout(this.fetch_feed.bind(this), timeout); }, //Cycling timer. When this times out we select the next group/feed schedule_cycle : function() { window.clearTimeout(this.cycle_timeout); this.cycle_timeout = window.setTimeout( this.cycle_feed.bind(this), inforssXMLRepository.headline_bar_cycle_interval * 60 * 1000); }, //---------------------------------------------------------------------------- fetch_feed : function() { const item = this.selectedInfo; if (!this.isBrowserOffLine()) { item.fetchFeed(); } const expected = item.get_next_refresh(); if (expected == null) { /**/console.log("Empty group", item) return; } const now = new Date(); let next = expected - now; if (next < 0) { /**/console.log("fetchfeed overdue", expected, now, next, item) next = 0; } this.schedule_fetch(next); }, //cycle to the next feed or group cycle_feed : function() { //FIXME Does this do anything useful? This used to be in getNextGroupOrFeed but //I don't see you could have a tooltip active whilst pressing a button. if (this.mediator.isActiveTooltip()) { this.cycle_timeout = window.setTimeout(this.cycle_feed.bind(this), 1000); return; } this.getNextGroupOrFeed(1); this.schedule_cycle(); }, //---------------------------------------------------------------------------- //returns true if the browser is in offline mode, in which case we go through //the motions but don't actually fetch any data isBrowserOffLine() { return gPrefs.prefHasUserValue("browser.offline") && gPrefs.getBoolPref("browser.offline"); }, //------------------------------------------------------------------------------------------------------------- //WTF does all this stuff do? //it seems to be getting the currently stored headlines and then populating //the thing with said currently stored headlines. sync: function(url) { inforssTraceIn(this); try { var info = this.locateFeed(url).info; if (info != null && info.insync == false && info.headlines.length > 0 && info.reload == false) { var data = info.getXmlHeadlines(); var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); observerService.notifyObservers(null, "syncBack", data); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- syncBack: function(data) { inforssTraceIn(this); try { var objDOMParser = new DOMParser(); var objDoc = objDOMParser.parseFromString(data, "text/xml"); var url = objDoc.firstChild.getAttribute("url"); var info = this.locateFeed(url).info; if ((info != null) && (info.insync)) { info.synchronize(objDoc); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- //FIXME Do we really need findDefault? How many places need to either have //or not have a default? Also this blanky sets it... getSelectedInfo: function(findDefault) { inforssTraceIn(this); try { if (this.selectedInfo == null) { var info = null; var find = false; var i = 0; while ((i < this.feed_list.length) && (find == false)) { if (this.feed_list[i].isSelected()) { find = true; info = this.feed_list[i]; info.select(); //dump("getSelectedInfo=" + info.getUrl() + "\n"); } else { i++; } } if ((find == false) && (this.feed_list.length > 0) && (findDefault)) { //alert("getSelectedInfo find == false"); info = this.feed_list[0]; info.select(); } this.selectedInfo = info; } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); return this.selectedInfo; }, //------------------------------------------------------------------------------------------------------------- signalReadEnd: function(feed) { this.rdfRepository.flush(); this.mediator.updateBar(feed); }, //------------------------------------------------------------------------------------------------------------- passivateOldSelected: function() { try { window.clearTimeout(this.schedule_timeout); var selectedInfo = this.getSelectedInfo(false); if (selectedInfo != null) { selectedInfo.unselect(); //see 311 //inforssHeadlineDisplay.apply_default_headline_style(selectedInfo.menuItem, false); selectedInfo.deactivate(); } } catch (e) { inforssDebug(e, this); } }, //------------------------------------------------------------------------------------------------------------- addFeed: function(feedXML, menuItem) { inforssTraceIn(this); try { var oldFeed = this.locateFeed(feedXML.getAttribute("url")).info; if (oldFeed == null) { var info = inforssInformation.createInfoFactory(feedXML, this, menuItem); this.feed_list.push(info); } else { oldFeed.feedXML = feedXML; oldFeed.menuItem = menuItem; } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- locateFeed: function(url) { inforssTraceIn(this); try { var find = false; var info = null; var i = 0; while ((i < this.feed_list.length) && (find == false)) { if (this.feed_list[i].getUrl() == url) { find = true; info = this.feed_list[i]; } else { i++; } } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); return { info: info, index: i }; }, //------------------------------------------------------------------------------------------------------------- setSelected: function(url) { inforssTraceIn(this); try { if (inforssXMLRepository.headline_bar_enabled()) { this.passivateOldSelected(); var info = this.locateFeed(url).info; this.selectedInfo = info; //apparently this is trying to set the colour of the currently selected //feed to the default headline colour. Unfortunately (a) it doesn't //change back the original and (b) it's a bit useless if your headlines //are default text and default background. //inforssHeadlineDisplay.apply_recent_headline_style(info.menuItem, false); //FIXME This code is same as init. info.select(); info.activate(); this.schedule_fetch(0); if (inforssXMLRepository.headline_bar_cycle_feeds) { this.schedule_cycle(); } if (info.getType() == "group") { this.mediator.updateMenuIcon(info); } } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- ack: function(url) { inforssTraceIn(this); try { var info = this.locateFeed(url).info; info.setAcknowledgeDate(new Date()); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- setPopup: function(url, flag) { inforssTraceIn(this); try { var info = this.locateFeed(url).info; info.setPopup(flag); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- openTab: function(url) { inforssTraceIn(this); try { this.mediator.openTab(url); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- deleteAllRss: function() { inforssTraceIn(this); try { var urls = []; for (var i = 0; i < this.feed_list.length; i++) { urls.push(this.feed_list[i].getUrl()); } for (var i = 0; i < urls.length; i++) { this.deleteRss(urls[i]); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- deleteRss: function(url) { inforssTraceIn(this); try { var deletedInfo = this.locateFeed(url); this.feed_list.splice(deletedInfo.index, 1); for (var i = 0; i < this.feed_list.length; i++) { this.feed_list[i].removeRss(url); } var selectedInfo = this.getSelectedInfo(true); var deleteSelected = (selectedInfo.getUrl() == url); deletedInfo.info.remove(); if (selectedInfo != null) { if (deleteSelected) { this.selectedInfo = null; if (this.feed_list.length > 0) { //FIXME Why not just call myself? this.mediator.setSelected(this.feed_list[0].getUrl()); } else { this.mediator.resetHeadlines(); } } } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- publishFeed: function(feed) { this.mediator.publishFeed(feed); }, //------------------------------------------------------------------------------------------------------------- unpublishFeed: function(feed) { this.mediator.unpublishFeed(feed); }, //------------------------------------------------------------------------------------------------------------- updateMenuIcon: function(feed) { this.mediator.updateMenuIcon(feed); }, //------------------------------------------------------------------------------------------------------------- goHome: function() { var selectedInfo = this.getSelectedInfo(false); if ((selectedInfo != null) && (selectedInfo.getType() != "group")) { this.mediator.openTab(selectedInfo.getLinkAddress()); } }, //------------------------------------------------------------------------------------------------------------- getNextGroupOrFeed: function(direction) { const info = this.selectedInfo; try { if (this.selectedInfo.isPlayList() && !inforssXMLRepository.headline_bar_cycle_feeds) { //If this is a playlist, just select the next element in the playlist info.playlist_cycle(direction); return; } else if (inforssXMLRepository.headline_bar_cycle_feeds && inforssXMLRepository.headline_bar_cycle_in_group && info.getType() == "group") { //If we're cycling in a group, let the group deal with things. info.feed_cycle(direction); return; } const i = inforssFeedManager.find_next_feed( info.getType(), this.feed_list, this.locateFeed(info.getUrl()).index, direction); //FIXME Optimisation needed it we cycle right back to the same one? this.setSelected(this.feed_list[i].getUrl()); } catch (e) { inforssDebug(e, this); } }, //------------------------------------------------------------------------------------------------------------- createNewRDFEntry: function(url, title, receivedDate, feedUrl) { try { this.rdfRepository.createNewRDFEntry(url, title, receivedDate, feedUrl); } catch (e) { inforssDebug(e, this); } }, //------------------------------------------------------------------------------------------------------------- exists: function(url, title, checkHistory, feedUrl) { return this.rdfRepository.exists(url, title, checkHistory, feedUrl); }, //------------------------------------------------------------------------------------------------------------- getAttribute: function(url, title, attribute) { return this.rdfRepository.getAttribute(url, title, attribute); }, //------------------------------------------------------------------------------------------------------------- setAttribute: function(url, title, attribute, value) { return this.rdfRepository.setAttribute(url, title, attribute, value); }, //------------------------------------------------------------------------------------------------------------- newRDF: function() { this.rdfRepository.init(); }, //------------------------------------------------------------------------------------------------------------- purgeRdf: function() { this.rdfRepository.purged = false; this.rdfRepository.purge(); }, //------------------------------------------------------------------------------------------------------------- clearRdf: function() { this.rdfRepository.clearRdf(); }, //------------------------------------------------------------------------------------------------------------- manualRefresh: function() { inforssTraceIn(this); try { var selectedInfo = this.getSelectedInfo(false); if (selectedInfo != null) { selectedInfo.manualRefresh(); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, }; //Find the next feed to display when doing next/previous button or cycling. //Takes into account feeds being disabled (annoyingly known as getFeedActivity) //If there are no feeds enabled, this will return the selected input //type - if null, doest check type. if not null, then it is used to ensure that // either both or neither the new and currently selected items are a group. //feeds - array of feeds to step through //pos - position in array of currently selected feed (or -1 if no selection) //direction - step direction (+1 or -1) inforssFeedManager.find_next_feed = function(type, feeds, pos, direction) { const length = feeds.length; let i = 0; let counter = 0; let posn = pos; //This (min(10, length)) is a very questionable interpretation of random const count = pos == -1 || inforssXMLRepository.headline_bar_cycle_type == "next" ? 1 : Math.floor(Math.random() * Math.min(10, length)) + 1; while (i < count && counter < length) { ++counter; posn = (length + posn + direction) % length; if (type != null && (feeds[posn].getType() == "group") != (type == "group")) { continue; } if (!feeds[posn].getFeedActivity()) { continue; } pos = posn; ++i; } return pos; };
source/content/inforss/inforssFeedManager.js
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is infoRSS. * * The Initial Developer of the Original Code is * Didier Ernotte <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Didier Ernotte <[email protected]>. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //------------------------------------------------------------------------------ // inforssFeedManager // Author : Didier Ernotte 2005 // Inforss extension //------------------------------------------------------------------------------ /* globals inforssDebug, inforssTraceIn, inforssTraceOut */ Components.utils.import("chrome://inforss/content/modules/inforssDebug.jsm"); var gPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch(null); /* globals inforssRDFRepository, inforssXMLRepository */ /* globals inforssRead, inforssAddItemToMenu, inforssRelocateBar, inforssInformation */ //FIXME get rid of all the 2 phase initialisation //FIXME get rid of all the global function calls function inforssFeedManager(mediator) { this.mediator = mediator; this.rdfRepository = new inforssRDFRepository(); this.schedule_timeout = null; this.cycle_timeout = null; this.feed_list = []; this.selectedInfo = null; return this; } inforssFeedManager.prototype = { //------------------------------------------------------------------------------------------------------------- init: function() { inforssTraceIn(this); try { /* This feels uncomfy here */ inforssRead(); for (let item of inforssXMLRepository.get_all()) { inforssAddItemToMenu(item); } inforssRelocateBar(); //And should this be somewhere else? /* down to here */ //Among other things, I think the global mediator should pass the inforssXmlRepository //to all of these. this.rdfRepository.init(); var oldSelected = this.selectedInfo; this.selectedInfo = null; for (let feed of this.feed_list) { feed.reset(); } window.clearTimeout(this.schedule_timeout); window.clearTimeout(this.cycle_timeout); //Possibly the wrong one. Why in any case do we force this arbitrarily to //the first feed. If we don't have a selected one, maybe just not have one? var selectedInfo = this.getSelectedInfo(true); if (selectedInfo != null) { if (oldSelected != null && oldSelected.getUrl() != selectedInfo.getUrl()) { oldSelected.deactivate(); } //FIXME This is pretty much identical to setSelected //why both? //See line 316 //inforssHeadlineDisplay.apply_recent_headline_style(selectedInfo.menuItem, false); // selectedInfo.reset(); // if (inforssXMLRepository.headline_bar_enabled()) { selectedInfo.activate(); this.schedule_fetch(0); if (inforssXMLRepository.headline_bar_cycle_feeds) { this.schedule_cycle(); } if (selectedInfo.getType() == "group") { this.mediator.updateMenuIcon(selectedInfo); } } else { selectedInfo.deactivate(); } } this.mediator.refreshBar(); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //Start the next fetch as soon as we've finished here. //Clear any existing fetch. schedule_fetch : function(timeout) { window.clearTimeout(this.schedule_timeout); this.schedule_timeout = window.setTimeout(this.fetch_feed.bind(this), timeout); }, //Cycling timer. When this times out we select the next group/feed schedule_cycle : function() { window.clearTimeout(this.cycle_timeout); this.cycle_timeout = window.setTimeout( this.cycle_feed.bind(this), inforssXMLRepository.headline_bar_cycle_interval * 60 * 1000); }, //---------------------------------------------------------------------------- fetch_feed : function() { const item = this.selectedInfo; if (!this.isBrowserOffLine()) { item.fetchFeed(); } const expected = item.get_next_refresh(); if (expected == null) { /**/console.log("Empty group", item) return; } const now = new Date(); let next = expected - now; if (next < 0) { /**/console.log("fetchfeed overdue", expected, now, next, item) next = 0; } this.schedule_fetch(next); }, //cycle to the next feed or group cycle_feed : function() { //FIXME Does this do anything useful? This used to be in getNextGroupOrFeed but //I don't see you could have a tooltip active whilst pressing a button. if (this.mediator.isActiveTooltip()) { this.cycle_timeout = window.setTimeout(this.cycle_feed.bind(this), 1000); return; } this.getNextGroupOrFeed(1); this.schedule_cycle(); }, //---------------------------------------------------------------------------- //returns true if the browser is in offline mode, in which case we go through //the motions but don't actually fetch any data isBrowserOffLine() { return gPrefs.prefHasUserValue("browser.offline") && gPrefs.getBoolPref("browser.offline"); }, //------------------------------------------------------------------------------------------------------------- //WTF does all this stuff do? //it seems to be getting the currently stored headlines and then populating //the thing with said currently stored headlines. sync: function(url) { inforssTraceIn(this); try { var info = this.locateFeed(url).info; if (info != null && info.insync == false && info.headlines.length > 0 && info.reload == false) { var data = info.getXmlHeadlines(); var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); observerService.notifyObservers(null, "syncBack", data); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- syncBack: function(data) { inforssTraceIn(this); try { var objDOMParser = new DOMParser(); var objDoc = objDOMParser.parseFromString(data, "text/xml"); var url = objDoc.firstChild.getAttribute("url"); var info = this.locateFeed(url).info; if ((info != null) && (info.insync)) { info.synchronize(objDoc); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- //FIXME Do we really need findDefault? How many places need to either have //or not have a default? Also this blanky sets it... getSelectedInfo: function(findDefault) { inforssTraceIn(this); try { if (this.selectedInfo == null) { var info = null; var find = false; var i = 0; while ((i < this.feed_list.length) && (find == false)) { if (this.feed_list[i].isSelected()) { find = true; info = this.feed_list[i]; info.select(); //dump("getSelectedInfo=" + info.getUrl() + "\n"); } else { i++; } } if ((find == false) && (this.feed_list.length > 0) && (findDefault)) { //alert("getSelectedInfo find == false"); info = this.feed_list[0]; info.select(); } this.selectedInfo = info; } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); return this.selectedInfo; }, //------------------------------------------------------------------------------------------------------------- signalReadEnd: function(feed) { this.rdfRepository.flush(); this.mediator.updateBar(feed); }, //------------------------------------------------------------------------------------------------------------- passivateOldSelected: function() { try { window.clearTimeout(this.schedule_timeout); var selectedInfo = this.getSelectedInfo(false); if (selectedInfo != null) { selectedInfo.unselect(); //see 311 //inforssHeadlineDisplay.apply_default_headline_style(selectedInfo.menuItem, false); selectedInfo.deactivate(); } } catch (e) { inforssDebug(e, this); } }, //------------------------------------------------------------------------------------------------------------- addFeed: function(feedXML, menuItem) { inforssTraceIn(this); try { var oldFeed = this.locateFeed(feedXML.getAttribute("url")).info; if (oldFeed == null) { var info = inforssInformation.createInfoFactory(feedXML, this, menuItem); this.feed_list.push(info); } else { oldFeed.feedXML = feedXML; oldFeed.menuItem = menuItem; } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- locateFeed: function(url) { inforssTraceIn(this); try { var find = false; var info = null; var i = 0; while ((i < this.feed_list.length) && (find == false)) { if (this.feed_list[i].getUrl() == url) { find = true; info = this.feed_list[i]; } else { i++; } } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); return { info: info, index: i }; }, //------------------------------------------------------------------------------------------------------------- setSelected: function(url) { inforssTraceIn(this); try { if (inforssXMLRepository.headline_bar_enabled()) { this.passivateOldSelected(); var info = this.locateFeed(url).info; this.selectedInfo = info; //apparently this is trying to set the colour of the currently selected //feed to the default headline colour. Unfortunately (a) it doesn't //change back the original and (b) it's a bit useless if your headlines //are default text and default background. //inforssHeadlineDisplay.apply_recent_headline_style(info.menuItem, false); //FIXME This code is same as init. info.select(); info.activate(); this.schedule_fetch(0); if (inforssXMLRepository.headline_bar_cycle_feeds) { this.schedule_cycle(); } if (info.getType() == "group") { this.mediator.updateMenuIcon(info); } } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- ack: function(url) { inforssTraceIn(this); try { var info = this.locateFeed(url).info; info.setAcknowledgeDate(new Date()); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- setPopup: function(url, flag) { inforssTraceIn(this); try { var info = this.locateFeed(url).info; info.setPopup(flag); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- openTab: function(url) { inforssTraceIn(this); try { this.mediator.openTab(url); } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- deleteAllRss: function() { inforssTraceIn(this); try { var urls = []; for (var i = 0; i < this.feed_list.length; i++) { urls.push(this.feed_list[i].getUrl()); } for (var i = 0; i < urls.length; i++) { this.deleteRss(urls[i]); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- deleteRss: function(url) { inforssTraceIn(this); try { var deletedInfo = this.locateFeed(url); this.feed_list.splice(deletedInfo.index, 1); for (var i = 0; i < this.feed_list.length; i++) { this.feed_list[i].removeRss(url); } var selectedInfo = this.getSelectedInfo(true); var deleteSelected = (selectedInfo.getUrl() == url); deletedInfo.info.remove(); if (selectedInfo != null) { if (deleteSelected) { this.selectedInfo = null; if (this.feed_list.length > 0) { //FIXME Why not just call myself? this.mediator.setSelected(this.feed_list[0].getUrl()); } else { this.mediator.resetHeadlines(); } } } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, //------------------------------------------------------------------------------------------------------------- publishFeed: function(feed) { this.mediator.publishFeed(feed); }, //------------------------------------------------------------------------------------------------------------- unpublishFeed: function(feed) { this.mediator.unpublishFeed(feed); }, //------------------------------------------------------------------------------------------------------------- updateMenuIcon: function(feed) { this.mediator.updateMenuIcon(feed); }, //------------------------------------------------------------------------------------------------------------- goHome: function() { var selectedInfo = this.getSelectedInfo(false); if ((selectedInfo != null) && (selectedInfo.getType() != "group")) { this.mediator.openTab(selectedInfo.getLinkAddress()); } }, //------------------------------------------------------------------------------------------------------------- getNextGroupOrFeed: function(direction) { const info = this.selectedInfo; try { if (this.selectedInfo.isPlayList() && !inforssXMLRepository.headline_bar_cycle_feeds) { //If this is a playlist, just select the next element in the playlist info.playlist_cycle(direction); return; } else if (inforssXMLRepository.headline_bar_cycle_feeds && inforssXMLRepository.headline_bar_cycle_in_group && info.getType() == "group") { //If we're cycling in a group, let the group deal with things. info.feed_cycle(direction); return; } const i = inforssFeedManager.find_next_feed( info.getType(), this.feed_list, this.locateFeed(info.getUrl()).index, direction); //FIXME Optimisation needed it we cycle right back to the same one? this.setSelected(informationList[i].getUrl()); } catch (e) { inforssDebug(e, this); } }, //------------------------------------------------------------------------------------------------------------- createNewRDFEntry: function(url, title, receivedDate, feedUrl) { try { this.rdfRepository.createNewRDFEntry(url, title, receivedDate, feedUrl); } catch (e) { inforssDebug(e, this); } }, //------------------------------------------------------------------------------------------------------------- exists: function(url, title, checkHistory, feedUrl) { return this.rdfRepository.exists(url, title, checkHistory, feedUrl); }, //------------------------------------------------------------------------------------------------------------- getAttribute: function(url, title, attribute) { return this.rdfRepository.getAttribute(url, title, attribute); }, //------------------------------------------------------------------------------------------------------------- setAttribute: function(url, title, attribute, value) { return this.rdfRepository.setAttribute(url, title, attribute, value); }, //------------------------------------------------------------------------------------------------------------- newRDF: function() { this.rdfRepository.init(); }, //------------------------------------------------------------------------------------------------------------- purgeRdf: function() { this.rdfRepository.purged = false; this.rdfRepository.purge(); }, //------------------------------------------------------------------------------------------------------------- clearRdf: function() { this.rdfRepository.clearRdf(); }, //------------------------------------------------------------------------------------------------------------- manualRefresh: function() { inforssTraceIn(this); try { var selectedInfo = this.getSelectedInfo(false); if (selectedInfo != null) { selectedInfo.manualRefresh(); } } catch (e) { inforssDebug(e, this); } inforssTraceOut(this); }, }; //Find the next feed to display when doing next/previous button or cycling. //Takes into account feeds being disabled (annoyingly known as getFeedActivity) //If there are no feeds enabled, this will return the selected input //type - if null, doest check type. if not null, then it is used to ensure that // either both or neither the new and currently selected items are a group. //feeds - array of feeds to step through //pos - position in array of currently selected feed (or -1 if no selection) //direction - step direction (+1 or -1) inforssFeedManager.find_next_feed = function(type, feeds, pos, direction) { const length = feeds.length; let i = 0; let counter = 0; let posn = pos; //This (min(10, length)) is a very questionable interpretation of random const count = pos == -1 || inforssXMLRepository.headline_bar_cycle_type == "next" ? 1 : Math.floor(Math.random() * Math.min(10, length)) + 1; while (i < count && counter < length) { ++counter; posn = (length + posn + direction) % length; if (type != null && (feeds[posn].getType() == "group") != (type == "group")) { continue; } if (!feeds[posn].getFeedActivity()) { continue; } pos = posn; ++i; } return pos; }
Err. Oops. Broke cycling
source/content/inforss/inforssFeedManager.js
Err. Oops. Broke cycling
<ide><path>ource/content/inforss/inforssFeedManager.js <ide> direction); <ide> <ide> //FIXME Optimisation needed it we cycle right back to the same one? <del> this.setSelected(informationList[i].getUrl()); <add> this.setSelected(this.feed_list[i].getUrl()); <ide> } <ide> catch (e) <ide> { <ide> ++i; <ide> } <ide> return pos; <del>} <add>};
Java
apache-2.0
b32b7f9901cde8bb2a6b592292d96e7a8e3068f1
0
freakynit/caliper,freakynit/caliper,cmelchior/caliper,Aexyn/caliper,google/caliper,santoshsahoo/caliper,Euphrates-Media/caliper,cmelchior/caliper,cmelchior/spanner,umakanta75/caliper,Euphrates-Media/caliper,pjq/caliper,cmelchior/spanner,pjq/caliper,slachiewicz/caliper,umakanta75/caliper,cmelchior/caliper,ccristian/caliper,cmelchior/spanner,slachiewicz/caliper,ccristian/caliper,Aexyn/caliper,santoshsahoo/caliper
/* * Copyright (C) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.caliper.runner; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.caliper.bridge.LogMessage; import com.google.caliper.bridge.OpenedSocket; import com.google.caliper.runner.FakeWorkers.DummyLogMessage; import com.google.caliper.runner.StreamService.StreamItem; import com.google.caliper.runner.StreamService.StreamItem.Kind; import com.google.caliper.util.Parser; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFutureTask; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.Service.Listener; import com.google.common.util.concurrent.Service.State; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.ServerSocket; import java.net.SocketException; import java.text.ParseException; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Tests for {@link StreamService}. */ @RunWith(JUnit4.class) public class StreamServiceTest { private ServerSocket serverSocket; private final StringWriter writer = new StringWriter(); private final PrintWriter stdout = new PrintWriter(writer, true); private final Parser<LogMessage> parser = new Parser<LogMessage>() { @Override public LogMessage parse(final CharSequence text) throws ParseException { return new DummyLogMessage(text.toString()); } }; private StreamService service; private final CountDownLatch terminalLatch = new CountDownLatch(1); private static final int TRIAL_NUMBER = 3; @Before public void setUp() throws IOException { serverSocket = new ServerSocket(0); } @After public void closeSocket() throws IOException { serverSocket.close(); } @After public void stopService() { if (service != null && service.state() != State.FAILED && service.state() != State.TERMINATED) { service.stopAsync().awaitTerminated(); } } @Test public void testReadOutput() throws Exception { makeService(FakeWorkers.PrintClient.class, "foo", "bar"); service.startAsync().awaitRunning(); StreamItem item1 = readItem(); assertEquals(Kind.DATA, item1.kind()); Set<String> lines = Sets.newHashSet(); lines.add(item1.content().toString()); StreamItem item2 = readItem(); assertEquals(Kind.DATA, item2.kind()); lines.add(item2.content().toString()); assertEquals(Sets.newHashSet("foo", "bar"), lines); assertEquals(State.RUNNING, service.state()); StreamItem item3 = readItem(); assertEquals(Kind.EOF, item3.kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertTerminated(); } @Test public void failingProcess() throws Exception { makeService(FakeWorkers.Exit.class, "1"); service.startAsync().awaitRunning(); assertEquals(Kind.EOF, readItem().kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertEquals(State.FAILED, service.state()); } @Test public void processDoesntExit() throws Exception { // close all fds and then sleep makeService(FakeWorkers.CloseAndSleep.class); service.startAsync().awaitRunning(); assertEquals(Kind.EOF, readItem().kind()); awaitStopped(200, TimeUnit.MILLISECONDS); // we assertEquals(State.FAILED, service.state()); } @Test public void testSocketInputOutput() throws Exception { int localport = serverSocket.getLocalPort(); // read from the socket and echo it back makeService(FakeWorkers.SocketEchoClient.class, Integer.toString(localport)); service.startAsync().awaitRunning(); assertEquals(new DummyLogMessage("start"), readItem().content()); service.sendMessage(new DummyLogMessage("hello socket world")); assertEquals(new DummyLogMessage("hello socket world"), readItem().content()); service.closeWriter(); assertEquals(State.RUNNING, service.state()); StreamItem nextItem = readItem(); assertEquals("Expected EOF " + nextItem, Kind.EOF, nextItem.kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertTerminated(); } @Test public void testSocketClosesBeforeProcess() throws Exception { int localport = serverSocket.getLocalPort(); // read from the socket and echo it back makeService(FakeWorkers.SocketEchoClient.class, Integer.toString(localport), "foo"); service.startAsync().awaitRunning(); assertEquals(new DummyLogMessage("start"), readItem().content()); service.sendMessage(new DummyLogMessage("hello socket world")); assertEquals(new DummyLogMessage("hello socket world"), readItem().content()); service.closeWriter(); assertEquals("foo", readItem().content().toString()); assertEquals(State.RUNNING, service.state()); assertEquals(Kind.EOF, readItem().kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertTerminated(); } @Test public void failsToAcceptConnection() throws Exception { serverSocket.close(); // This will force serverSocket.accept to throw a SocketException makeService(FakeWorkers.Sleeper.class, Long.toString(TimeUnit.MINUTES.toMillis(10))); try { service.startAsync().awaitRunning(); fail(); } catch (IllegalStateException expected) {} assertEquals(SocketException.class, service.failureCause().getClass()); } /** Reads an item, asserting that there was no timeout. */ private StreamItem readItem() throws InterruptedException { StreamItem item = service.readItem(10, TimeUnit.SECONDS); assertNotSame("Timed out while reading item from worker", Kind.TIMEOUT, item.kind()); return item; } /** * Wait for the service to reach a terminal state without calling stop. */ private void awaitStopped(long time, TimeUnit unit) throws InterruptedException { assertTrue(terminalLatch.await(time, unit)); } private void assertTerminated() { State state = service.state(); if (state != State.TERMINATED) { if (state == State.FAILED) { throw new AssertionError(service.failureCause()); } fail("Expected service to be terminated but was: " + state); } } @SuppressWarnings("resource") private void makeService(Class<?> main, String ...args) { checkState(service == null, "You can only make one StreamService per test"); UUID trialId = UUID.randomUUID(); TrialOutputLogger trialOutput = new TrialOutputLogger(new TrialOutputFactory() { @Override public FileAndWriter getTrialOutputFile(int trialNumber) throws FileNotFoundException { checkArgument(trialNumber == TRIAL_NUMBER); return new FileAndWriter(new File("/tmp/not-a-file"), stdout); } @Override public void persistFile(File f) { throw new UnsupportedOperationException(); } }, TRIAL_NUMBER, trialId, null /* experiment */); try { // normally the TrialRunLoop opens/closes the logger trialOutput.open(); } catch (IOException e) { throw new RuntimeException(e); } service = new StreamService( new WorkerProcess(FakeWorkers.createProcessBuilder(main, args), trialId, getSocketFuture(), new RuntimeShutdownHookRegistrar()), parser, trialOutput); service.addListener(new Listener() { @Override public void starting() {} @Override public void running() {} @Override public void stopping(State from) {} @Override public void terminated(State from) { terminalLatch.countDown(); } @Override public void failed(State from, Throwable failure) { terminalLatch.countDown(); } }, MoreExecutors.directExecutor()); } private ListenableFuture<OpenedSocket> getSocketFuture() { ListenableFutureTask<OpenedSocket> openSocketTask = ListenableFutureTask.create( new Callable<OpenedSocket>() { @Override public OpenedSocket call() throws Exception { return OpenedSocket.fromSocket(serverSocket.accept()); } }); // N.B. this thread will block on serverSocket.accept until a connection is accepted or the // socket is closed, so no matter what this thread will die with the test. Thread opener = new Thread(openSocketTask, "SocketOpener"); opener.setDaemon(true); opener.start(); return openSocketTask; } }
caliper/src/test/java/com/google/caliper/runner/StreamServiceTest.java
/* * Copyright (C) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.caliper.runner; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.caliper.bridge.LogMessage; import com.google.caliper.bridge.OpenedSocket; import com.google.caliper.runner.FakeWorkers.DummyLogMessage; import com.google.caliper.runner.StreamService.StreamItem; import com.google.caliper.runner.StreamService.StreamItem.Kind; import com.google.caliper.util.Parser; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFutureTask; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.Service.Listener; import com.google.common.util.concurrent.Service.State; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.ServerSocket; import java.net.SocketException; import java.text.ParseException; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Tests for {@link StreamService}. */ @RunWith(JUnit4.class) public class StreamServiceTest { private ServerSocket serverSocket; private final StringWriter writer = new StringWriter(); private final PrintWriter stdout = new PrintWriter(writer, true); private final Parser<LogMessage> parser = new Parser<LogMessage>() { @Override public LogMessage parse(final CharSequence text) throws ParseException { return new DummyLogMessage(text.toString()); } }; private StreamService service; private final CountDownLatch terminalLatch = new CountDownLatch(1); private static final int TRIAL_NUMBER = 3; @Before public void setUp() throws IOException { serverSocket = new ServerSocket(0); } @After public void closeSocket() throws IOException { serverSocket.close(); } @After public void stopService() { if (service != null && service.state() != State.FAILED && service.state() != State.TERMINATED) { service.stopAsync().awaitTerminated(); } } @Test public void testReadOutput() throws Exception { makeService(FakeWorkers.PrintClient.class, "foo", "bar"); service.startAsync().awaitRunning(); StreamItem item1 = readItem(); assertEquals(Kind.DATA, item1.kind()); Set<String> lines = Sets.newHashSet(); lines.add(item1.content().toString()); StreamItem item2 = readItem(); assertEquals(Kind.DATA, item2.kind()); lines.add(item2.content().toString()); assertEquals(Sets.newHashSet("foo", "bar"), lines); assertEquals(State.RUNNING, service.state()); StreamItem item3 = readItem(); assertEquals(Kind.EOF, item3.kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertTerminated(); } @Test public void failingProcess() throws Exception { makeService(FakeWorkers.Exit.class, "1"); service.startAsync().awaitRunning(); assertEquals(Kind.EOF, readItem().kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertEquals(State.FAILED, service.state()); } @Test public void processDoesntExit() throws Exception { // close all fds and then sleep makeService(FakeWorkers.CloseAndSleep.class); service.startAsync().awaitRunning(); assertEquals(Kind.EOF, readItem().kind()); awaitStopped(200, TimeUnit.MILLISECONDS); // we assertEquals(State.FAILED, service.state()); } @Test public void testSocketInputOutput() throws Exception { int localport = serverSocket.getLocalPort(); // read from the socket and echo it back makeService(FakeWorkers.SocketEchoClient.class, Integer.toString(localport)); service.startAsync().awaitRunning(); assertEquals(new DummyLogMessage("start"), readItem().content()); service.sendMessage(new DummyLogMessage("hello socket world")); assertEquals(new DummyLogMessage("hello socket world"), readItem().content()); service.closeWriter(); assertEquals(State.RUNNING, service.state()); StreamItem nextItem = readItem(); assertEquals("Expected EOF " + nextItem, Kind.EOF, nextItem.kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertTerminated(); } @Test public void testSocketClosesBeforeProcess() throws Exception { int localport = serverSocket.getLocalPort(); // read from the socket and echo it back makeService(FakeWorkers.SocketEchoClient.class, Integer.toString(localport), "foo"); service.startAsync().awaitRunning(); assertEquals(new DummyLogMessage("start"), readItem().content()); service.sendMessage(new DummyLogMessage("hello socket world")); assertEquals(new DummyLogMessage("hello socket world"), readItem().content()); service.closeWriter(); assertEquals("foo", readItem().content().toString()); assertEquals(State.RUNNING, service.state()); assertEquals(Kind.EOF, readItem().kind()); awaitStopped(100, TimeUnit.MILLISECONDS); assertTerminated(); } @Test public void failsToAcceptConnection() throws Exception { serverSocket.close(); // This will force serverSocket.accept to throw a SocketException makeService(FakeWorkers.Sleeper.class, Long.toString(TimeUnit.MINUTES.toMillis(10))); try { service.startAsync().awaitRunning(); fail(); } catch (IllegalStateException expected) {} assertEquals(SocketException.class, service.failureCause().getClass()); } /** Reads an item, asserting that there was no timeout. */ private StreamItem readItem() throws InterruptedException { StreamItem item = service.readItem(10, TimeUnit.SECONDS); assertNotSame("Timed out while reading item from worker", Kind.TIMEOUT, item.kind()); return item; } /** * Wait for the service to reach a terminal state without calling stop. */ private void awaitStopped(long time, TimeUnit unit) throws InterruptedException { assertTrue(terminalLatch.await(time, unit)); } private void assertTerminated() { State state = service.state(); if (state != State.TERMINATED) { if (state == State.FAILED) { throw new AssertionError(service.failureCause()); } fail("Expected service to be terminated but was: " + state); } } @SuppressWarnings("resource") private void makeService(Class<?> main, String ...args) { checkState(service == null, "You can only make one StreamService per test"); UUID trialId = UUID.randomUUID(); TrialOutputLogger trialOutput = new TrialOutputLogger(new TrialOutputFactory() { @Override public FileAndWriter getTrialOutputFile(int trialNumber) throws FileNotFoundException { checkArgument(trialNumber == TRIAL_NUMBER); return new FileAndWriter(new File("/tmp/not-a-file"), stdout); } @Override public void persistFile(File f) { throw new UnsupportedOperationException(); } }, TRIAL_NUMBER, trialId, null /* experiment */); try { // normally the TrialRunLoop opens/closes the logger trialOutput.open(); } catch (IOException e) { throw new RuntimeException(e); } service = new StreamService( new WorkerProcess(FakeWorkers.createProcessBuilder(main, args), trialId, getSocketFuture(), new RuntimeShutdownHookRegistrar()), parser, trialOutput); service.addListener(new Listener() { @Override public void starting() {} @Override public void running() {} @Override public void stopping(State from) {} @Override public void terminated(State from) { terminalLatch.countDown(); } @Override public void failed(State from, Throwable failure) { terminalLatch.countDown(); } }, MoreExecutors.sameThreadExecutor()); } private ListenableFuture<OpenedSocket> getSocketFuture() { ListenableFutureTask<OpenedSocket> openSocketTask = ListenableFutureTask.create( new Callable<OpenedSocket>() { @Override public OpenedSocket call() throws Exception { return OpenedSocket.fromSocket(serverSocket.accept()); } }); // N.B. this thread will block on serverSocket.accept until a connection is accepted or the // socket is closed, so no matter what this thread will die with the test. Thread opener = new Thread(openSocketTask, "SocketOpener"); opener.setDaemon(true); opener.start(); return openSocketTask; } }
Change usage of MoreExecutors.sameThreadExecutor() to directExecutor(). ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=87854846
caliper/src/test/java/com/google/caliper/runner/StreamServiceTest.java
Change usage of MoreExecutors.sameThreadExecutor() to directExecutor(). ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=87854846
<ide><path>aliper/src/test/java/com/google/caliper/runner/StreamServiceTest.java <ide> @Override public void failed(State from, Throwable failure) { <ide> terminalLatch.countDown(); <ide> } <del> }, MoreExecutors.sameThreadExecutor()); <add> }, MoreExecutors.directExecutor()); <ide> } <ide> <ide> private ListenableFuture<OpenedSocket> getSocketFuture() {
JavaScript
mit
162bf20ab5977028f35ed761d56c9843729bb2ea
0
AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV
var karyo = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null} } }; var filters = {'karyo': { 'order': ['c1', 'c2'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var karyo2 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c3': {'genome_id': 1, 'length': 1000, 'seq': null} } }; var filters2 = {'karyo': { 'order': ['c1', 'c2', 'c3'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var karyo3 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c3': {'genome_id': 2, 'length': 1000, 'seq': null} } }; var filters3 = {'karyo': { 'order': ['c1', 'c2', 'c3'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var karyo4 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c3': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c4': {'genome_id': 2, 'length': 1000, 'seq': null} } }; var karyo5 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c4': {'genome_id': 2, 'length': 1000, 'seq': null} } }; var karyo6 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null} } }; var karyo7 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 2000, 'seq': null}, 'c3': {'genome_id': 2, 'length': 2000, 'seq': null}, 'c4': {'genome_id': 3, 'length': 2000, 'seq': null} } }; var filters4 = {'karyo': { 'order': ['c1', 'c2', 'c3', 'c4'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true}, 'c4': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var filters5 = {'karyo': { 'order': ['c1', 'c2', 'c4'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c4': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var filters4_reverse = {'karyo': { 'order': ['c1', 'c2', 'c3', 'c4'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': true, 'visible': true}, 'c3': {'reverse': false, 'visible': true}, 'c4': {'reverse': true, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var filters6 = {'karyo': { 'order': ['c1'], 'genome_order': [0], 'chromosomes': { 'c1': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var filters7 = {'karyo': { 'order': ['c1', 'c2'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var filters8 = {'karyo': { 'order': ['c1', 'c2', 'c3', 'c4'], 'genome_order': [0, 1, 2, 3], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true}, 'c4': {'reverse': false, 'visible': true} } } }; var filters9 = {'karyo': { 'order': ['c1', 'c2', 'c3'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': false}, 'c3': {'reverse': false, 'visible': true} } } }; var features = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600} }; var features2 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c4', 'start': 400, 'end': 900}, 'f4': {'karyo': 'c3', 'start': 900, 'end': 800}, 'f5': {'karyo': 'c1', 'start': 1800, 'end': 1900} }; var features3 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c4', 'start': 400, 'end': 900} }; var features4 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c4', 'start': 400, 'end': 900}, 'f4': {'karyo': 'c1', 'start': 1800, 'end': 1900} } var features5 = { 'f1': {'karyo': 'c1', 'start': 200, 'end': 300}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 700} }; var features6 = { 'f1': {'karyo': 'c1', 'start': 200, 'end': 300}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 700}, 'f3': {'karyo': 'c3', 'start': 600, 'end': 700} }; var features7 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c3', 'start': 400, 'end': 900}, 'f4': {'karyo': 'c4', 'start': 800, 'end': 900} }; var links = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90} }; var links2 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f3', 'target': 'f2', 'identity': 86} }; var links3 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f5', 'target': 'f4', 'identity': 86} }; var links4 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f2', 'target': 'f3', 'identity': 86}, "l3": {'source': 'f1', 'target': 'f3', 'identity': 94} }; var links5 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f2', 'target': 'f3', 'identity': 86} }; var links6 = { "l3": {'source': 'f1', 'target': 'f3', 'identity': 90}, "l5": {'source': 'f4', 'target': 'f2', 'identity': 86} }; var links7 = { "l1": {'source': 'f1', 'target': 'f3', 'identity': 40}, "l2": {'source': 'f2', 'target': 'f3', 'identity': 50}, "l3": {'source': 'f2', 'target': 'f4', 'identity': 60}, "l4": {'source': 'f1', 'target': 'f4', 'identity': 70}, "l5": {'source': 'f4', 'target': 'f2', 'identity': 90} }; var links8 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 75} }; var links9 = { "l1": {'source': 'f1', 'target': 'f3', 'identity': 80} }; var links10 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f2', 'target': 'f4', 'identity': 100} }; var data = {'karyo': karyo, 'features': features, 'links': links}; var data2 = {'karyo': karyo2, 'features': features, 'links': links}; var data3 = {'karyo': karyo3, 'features': features, 'links': links}; var data4 = {'karyo': karyo4, 'features': features, 'links': links};
d3/test/data/testData.js
var karyo = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null} } }; var filters = {'karyo': { 'order': ['c1', 'c2'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var karyo2 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c3': {'genome_id': 1, 'length': 1000, 'seq': null} } }; var filters2 = {'karyo': { 'order': ['c1', 'c2', 'c3'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var karyo3 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c3': {'genome_id': 2, 'length': 1000, 'seq': null} } }; var filters3 = {'karyo': { 'order': ['c1', 'c2', 'c3'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var karyo4 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c3': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c4': {'genome_id': 2, 'length': 1000, 'seq': null} } }; var karyo5 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 1000, 'seq': null}, 'c4': {'genome_id': 2, 'length': 1000, 'seq': null} } }; var karyo6 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null} } }; var karyo7 = { 'chromosomes': { 'c1': {'genome_id': 0, 'length': 2000, 'seq': null}, 'c2': {'genome_id': 1, 'length': 2000, 'seq': null}, 'c3': {'genome_id': 2, 'length': 2000, 'seq': null}, 'c4': {'genome_id': 3, 'length': 2000, 'seq': null} } }; var filters4 = {'karyo': { 'order': ['c1', 'c2', 'c3', 'c4'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true}, 'c4': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var filters5 = {'karyo': { 'order': ['c1', 'c2', 'c4'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c4': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var filters4_reverse = {'karyo': { 'order': ['c1', 'c2', 'c3', 'c4'], 'genome_order': [0, 1, 2], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': true, 'visible': true}, 'c3': {'reverse': false, 'visible': true}, 'c4': {'reverse': true, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} }; var filters6 = {'karyo': { 'order': ['c1'], 'genome_order': [0], 'chromosomes': { 'c1': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var filters7 = {'karyo': { 'order': ['c1', 'c2'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true} }}, "links": {"minLinkIdentity": 0, "maxLinkIdentity": 100, "minLinkLength": 100, "maxLinkLength": 10000} } var filters8 = {'karyo': { 'order': ['c1', 'c2', 'c3', 'c4'], 'genome_order': [0, 1, 2, 3], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': true}, 'c3': {'reverse': false, 'visible': true}, 'c4': {'reverse': false, 'visible': true} } } }; var filters9 = {'karyo': { 'order': ['c1', 'c2', 'c3'], 'genome_order': [0, 1], 'chromosomes': { 'c1': {'reverse': false, 'visible': true}, 'c2': {'reverse': false, 'visible': false}, 'c3': {'reverse': false, 'visible': true} } } }; var features = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600} }; var features2 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c4', 'start': 400, 'end': 900}, 'f4': {'karyo': 'c3', 'start': 900, 'end': 800}, 'f5': {'karyo': 'c1', 'start': 1800, 'end': 1900} }; var features3 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c4', 'start': 400, 'end': 900} }; var features4 = { 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, 'f3': {'karyo': 'c4', 'start': 400, 'end': 900}, 'f4': {'karyo': 'c1', 'start': 1800, 'end': 1900} } var features5 = { 'f1': {'karyo': 'c1', 'start': 200, 'end': 300}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 700} }; var features6 = { 'f1': {'karyo': 'c1', 'start': 200, 'end': 300}, 'f2': {'karyo': 'c2', 'start': 100, 'end': 700}, 'f3': {'karyo': 'c3', 'start': 600, 'end': 700} }; var links = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90} }; var links2 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f3', 'target': 'f2', 'identity': 86} }; var links3 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f5', 'target': 'f4', 'identity': 86} }; var links4 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f2', 'target': 'f3', 'identity': 86}, "l3": {'source': 'f1', 'target': 'f3', 'identity': 94} }; var links5 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, "l2": {'source': 'f2', 'target': 'f3', 'identity': 86} }; var links6 = { "l3": {'source': 'f1', 'target': 'f3', 'identity': 90}, "l5": {'source': 'f4', 'target': 'f2', 'identity': 86} }; var links7 = { "l1": {'source': 'f1', 'target': 'f3', 'identity': 40}, "l2": {'source': 'f2', 'target': 'f3', 'identity': 50}, "l3": {'source': 'f2', 'target': 'f4', 'identity': 60}, "l4": {'source': 'f1', 'target': 'f4', 'identity': 70}, "l5": {'source': 'f4', 'target': 'f2', 'identity': 90} }; var links8 = { "l1": {'source': 'f1', 'target': 'f2', 'identity': 75} }; var links9 = { "l1": {'source': 'f1', 'target': 'f3', 'identity': 80} }; var data = {'karyo': karyo, 'features': features, 'links': links}; var data2 = {'karyo': karyo2, 'features': features, 'links': links}; var data3 = {'karyo': karyo3, 'features': features, 'links': links}; var data4 = {'karyo': karyo4, 'features': features, 'links': links};
Add more test data in order to test filterVisibleChromosomes
d3/test/data/testData.js
Add more test data in order to test filterVisibleChromosomes
<ide><path>3/test/data/testData.js <ide> 'f2': {'karyo': 'c2', 'start': 100, 'end': 700}, <ide> 'f3': {'karyo': 'c3', 'start': 600, 'end': 700} <ide> }; <del> <add>var features7 = { <add> 'f1': {'karyo': 'c1', 'start': 300, 'end': 800}, <add> 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}, <add> 'f3': {'karyo': 'c3', 'start': 400, 'end': 900}, <add> 'f4': {'karyo': 'c4', 'start': 800, 'end': 900} <add>}; <ide> var links = { <ide> "l1": {'source': 'f1', 'target': 'f2', 'identity': 90} <ide> }; <ide> "l1": {'source': 'f1', 'target': 'f3', 'identity': 80} <ide> }; <ide> <add>var links10 = { <add> "l1": {'source': 'f1', 'target': 'f2', 'identity': 90}, <add> "l2": {'source': 'f2', 'target': 'f4', 'identity': 100} <add>}; <ide> <ide> var data = {'karyo': karyo, 'features': features, 'links': links}; <ide> var data2 = {'karyo': karyo2, 'features': features, 'links': links};
Java
mit
6b99b64fd73bec61dd1b618dd25dacfcec9387d5
0
devnull-tools/boteco,devnull-tools/boteco
/* * The MIT License * * Copyright (c) 2016 Marcelo "Ataxexe" Guimarães <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package tools.devnull.boteco.channel.telegram; import tools.devnull.boteco.Channel; import tools.devnull.boteco.Command; import tools.devnull.boteco.CommandExtractor; import tools.devnull.boteco.message.IncomeMessage; import tools.devnull.boteco.ServiceLocator; import tools.devnull.boteco.message.MessageSender; import tools.devnull.boteco.message.Sender; class TelegramIncomeMessage implements IncomeMessage { private static final long serialVersionUID = -7037612529067018573L; private final CommandExtractor extractor; private final TelegramPolling.Message message; private final Channel channel = new TelegramChannel(); private final ServiceLocator serviceLocator; TelegramIncomeMessage(CommandExtractor extractor, TelegramPolling.Message message, ServiceLocator serviceLocator) { this.extractor = extractor; this.message = message; this.serviceLocator = serviceLocator; } @Override public Channel channel() { return channel; } @Override public String content() { String text = message.getText(); return text == null ? "" : text; } @Override public boolean isPrivate() { return message.getChat().getId() > 0; } @Override public boolean isGroup() { return message.getChat().getId() < 0; } @Override public Sender sender() { return message.getFrom(); } @Override public String target() { return message.getChat().getId().toString(); } @Override public boolean hasCommand() { return extractor.isCommand(this); } @Override public Command command() { return extractor.extract(this); } @Override public void reply(String content) { if (isPrivate()) { replyMessage(String.valueOf(message.getFrom().id()), content); } else { replyMessage(String.valueOf(message.getChat().getId()), sender().mention() + ": " + content); } } @Override public void sendBack(String content) { replyMessage(String.valueOf(message.getChat().getId()), content); } private void replyMessage(String id, String content) { serviceLocator.locate(MessageSender.class).send(content).to(id).through(channel().id()); } }
channels/boteco-channel-telegram/src/main/java/tools/devnull/boteco/channel/telegram/TelegramIncomeMessage.java
/* * The MIT License * * Copyright (c) 2016 Marcelo "Ataxexe" Guimarães <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package tools.devnull.boteco.channel.telegram; import tools.devnull.boteco.Channel; import tools.devnull.boteco.Command; import tools.devnull.boteco.CommandExtractor; import tools.devnull.boteco.message.IncomeMessage; import tools.devnull.boteco.ServiceLocator; import tools.devnull.boteco.message.MessageSender; import tools.devnull.boteco.message.Sender; class TelegramIncomeMessage implements IncomeMessage { private static final long serialVersionUID = -7037612529067018573L; private final CommandExtractor extractor; private final TelegramPolling.Message message; private final Channel channel = new TelegramChannel(); private final ServiceLocator serviceLocator; TelegramIncomeMessage(CommandExtractor extractor, TelegramPolling.Message message, ServiceLocator serviceLocator) { this.extractor = extractor; this.message = message; this.serviceLocator = serviceLocator; } @Override public Channel channel() { return channel; } @Override public String content() { String text = message.getText(); return text == null ? "" : text; } @Override public boolean isPrivate() { return message.getChat().getId() > 0; } @Override public boolean isGroup() { return message.getChat().getId() < 0; } @Override public Sender sender() { return message.getFrom(); } @Override public String target() { return message.getChat().getId().toString(); } @Override public boolean hasCommand() { return extractor.isCommand(this); } @Override public Command command() { return extractor.extract(this); } @Override public void reply(String content) { if (isPrivate()) { replyMessage(String.valueOf(message.getChat().getId()), content); } else { replyMessage(String.valueOf(message.getChat().getId()), sender().mention() + ": " + content); } } @Override public void sendBack(String content) { replyMessage(message.getFrom().id(), content); } private void replyMessage(String id, String content) { serviceLocator.locate(MessageSender.class).send(content).to(id).through(channel().id()); } }
fix reply and sendback methods
channels/boteco-channel-telegram/src/main/java/tools/devnull/boteco/channel/telegram/TelegramIncomeMessage.java
fix reply and sendback methods
<ide><path>hannels/boteco-channel-telegram/src/main/java/tools/devnull/boteco/channel/telegram/TelegramIncomeMessage.java <ide> @Override <ide> public void reply(String content) { <ide> if (isPrivate()) { <del> replyMessage(String.valueOf(message.getChat().getId()), content); <add> replyMessage(String.valueOf(message.getFrom().id()), content); <ide> } else { <ide> replyMessage(String.valueOf(message.getChat().getId()), sender().mention() + ": " + content); <ide> } <ide> <ide> @Override <ide> public void sendBack(String content) { <del> replyMessage(message.getFrom().id(), content); <add> replyMessage(String.valueOf(message.getChat().getId()), content); <ide> } <ide> <ide> private void replyMessage(String id, String content) {
JavaScript
apache-2.0
7a4b8fbe62ba5823bd5c69478fc51b70bdc91565
0
gopro/forgejs
/** * Media class. * * @constructor FORGE.Media * @param {FORGE.Viewer} viewer {@link FORGE.Viewer} reference. * @param {FORGE.SceneParser} config input media configuration from json * @extends {FORGE.BaseObject} * */ FORGE.Media = function(viewer, config) { /** * The viewer reference. * @name FORGE.Media#_viewer * @type {FORGE.Viewer} * @private */ this._viewer = viewer; /** * Input scene and media config * @name FORGE.Media#_config * @type {FORGE.SceneParser} * @private */ this._config = config; /** * Media options * @name FORGE.Media#_options * @type {Object} * @private */ this._options = null; /** * Image reference. * @name FORGE.Media#_displayObject * @type {FORGE.DisplayObject} * @private */ this._displayObject = null; /** * Ready flag * @name FORGE.Media#_ready * @type {boolean} * @private */ this._ready = false; /** * On load complete event dispatcher. * @name FORGE.Media#_onLoadComplete * @type {FORGE.EventDispatcher} * @private */ this._onLoadComplete = null; FORGE.BaseObject.call(this, "Media"); this._boot(); }; FORGE.Media.prototype = Object.create(FORGE.BaseObject.prototype); FORGE.Media.prototype.constructor = FORGE.Media; /** * Init routine * @method FORGE.Media#_boot * @private */ FORGE.Media.prototype._boot = function() { this._parseConfig(this._config); }; /** * Configuration parsing. * @method FORGE.Media#_parseConfig * @param {FORGE.SceneParser} config input media configuration * @private */ FORGE.Media.prototype._parseConfig = function(config) { this.warn("FORGE.Media config validator not implemented"); // media configuration var mediaConfig = config.media; if (typeof mediaConfig === "undefined") { return; } // Warning : UID is not registered and applied to the FORGE.ImageScalable|FORGE.Image|FORGE.VideoHTML5|FORGE.VideoDash objects for registration this._uid = mediaConfig.uid; var source = mediaConfig.source; if (typeof mediaConfig.source !== "undefined" && typeof mediaConfig.source.format === "undefined") { mediaConfig.source.format = FORGE.MediaFormat.FLAT; } if (mediaConfig.type === FORGE.MediaType.GRID) { this._ready = true; } else if (mediaConfig.type === FORGE.MediaType.IMAGE) { var imageConfig; // If there isn't an URL set, it means that this is a multi resolution image. if (!source.url) { throw "Multi resolution not implemented yet !"; } if (source.format === FORGE.MediaFormat.EQUIRECTANGULAR) { imageConfig = { key: this._uid, url: source.url }; this._displayObject = new FORGE.Image(this._viewer, imageConfig); } else if (source.format === FORGE.MediaFormat.CUBE || source.format === FORGE.MediaFormat.FLAT) { imageConfig = { key: this._uid, url: source.url }; this._displayObject = new FORGE.Image(this._viewer, imageConfig); } else { throw "Media format not supported"; } this._displayObject.onLoadComplete.addOnce(this._onImageLoadComplete, this); } else if (mediaConfig.type === FORGE.MediaType.VIDEO) { // If the levels property is present, we get all urls from it and put it // inside source.url: it means that there is multi-quality. It is way // easier to handle for video than for image, as it can never be video // tiles to display. if (Array.isArray(source.levels)) { source.url = []; for (var i = 0, ii = source.levels.length; i < ii; i++) { source.url.push(source.levels[i].url); } } if (typeof source.streaming !== "undefined" && source.streaming.toLowerCase() === FORGE.VideoFormat.DASH) { this._displayObject = new FORGE.VideoDash(this._viewer, this._uid); } else { // check of the ambisonic state of the video sound prior to the video instanciation this._displayObject = new FORGE.VideoHTML5(this._viewer, this._uid, null, null, (this._config.hasSoundTarget(this._uid) === true && this._config.isAmbisonic() === true ? true : false)); } // At this point, source.url is either a streaming address, a simple // url, or an array of url this._displayObject.load(source.url); this._displayObject.onLoadedMetaData.addOnce(this._onLoadedMetaDataHandler, this); } this._options = (typeof mediaConfig.options !== "undefined") ? mediaConfig.options : null; }; /** * Internal handler on image ready. * @method FORGE.Media#_onImageLoadComplete * @private */ FORGE.Media.prototype._onImageLoadComplete = function() { this._ready = true; if (this._onLoadComplete !== null) { this._onLoadComplete.dispatch(); } }; /** * Internal handler on video metadata loaded. * @method FORGE.Media#_onLoadedMetaDataHandler * @private */ FORGE.Media.prototype._onLoadedMetaDataHandler = function() { this._ready = true; if (this._options !== null) { this._displayObject.volume = (typeof this._options.volume === "number") ? this._options.volume : 1; this._displayObject.loop = (typeof this._options.loop === "boolean") ? this._options.loop : true; if (this._options.autoPlay === true) { this._displayObject.play(); } } if (this._onLoadComplete !== null) { this._onLoadComplete.dispatch(); } }; /** * Media destroy sequence * * @method FORGE.Media#destroy */ FORGE.Media.prototype.destroy = function() { if (this._displayObject !== null) { this._displayObject.destroy(); this._displayObject = null; } if (this._onLoadComplete !== null) { this._onLoadComplete.destroy(); this._onLoadComplete = null; } this._viewer = null; this._config = null; }; /** * Get the displayObject. * @name FORGE.Media#displayObject * @readonly * @type {FORGE.DisplayObject} * * @todo This is temporary */ Object.defineProperty(FORGE.Media.prototype, "displayObject", { /** @this {FORGE.Media} */ get: function() { return this._displayObject; } }); /** * Get the ready flag * @name FORGE.Media#ready * @readonly * @type boolean */ Object.defineProperty(FORGE.Media.prototype, "ready", { /** @this {FORGE.Media} */ get: function() { return this._ready; } }); /** * Get the onLoadComplete {@link FORGE.EventDispatcher}. * @name FORGE.Media#onLoadComplete * @readonly * @type {FORGE.EventDispatcher} */ Object.defineProperty(FORGE.Media.prototype, "onLoadComplete", { /** @this {FORGE.Media} */ get: function() { if (this._onLoadComplete === null) { this._onLoadComplete = new FORGE.EventDispatcher(this); } return this._onLoadComplete; } });
src/media/Media.js
/** * Media class. * * @constructor FORGE.Media * @param {FORGE.Viewer} viewer {@link FORGE.Viewer} reference. * @param {FORGE.SceneParser} config input media configuration from json * @extends {FORGE.BaseObject} * */ FORGE.Media = function(viewer, config) { /** * The viewer reference. * @name FORGE.Media#_viewer * @type {FORGE.Viewer} * @private */ this._viewer = viewer; /** * Input scene and media config * @name FORGE.Media#_config * @type {FORGE.SceneParser} * @private */ this._config = config; /** * Media options * @name FORGE.Media#_options * @type {Object} * @private */ this._options = null; /** * Image reference. * @name FORGE.Media#_displayObject * @type {FORGE.DisplayObject} * @private */ this._displayObject = null; /** * Ready flag * @name FORGE.Media#_ready * @type {boolean} * @private */ this._ready = false; /** * On load complete event dispatcher. * @name FORGE.Media#_onLoadComplete * @type {FORGE.EventDispatcher} * @private */ this._onLoadComplete = null; FORGE.BaseObject.call(this, "Media"); this._boot(); }; FORGE.Media.prototype = Object.create(FORGE.BaseObject.prototype); FORGE.Media.prototype.constructor = FORGE.Media; /** * Init routine * @method FORGE.Media#_boot * @private */ FORGE.Media.prototype._boot = function() { this._parseConfig(this._config); }; /** * Configuration parsing. * @method FORGE.Media#_parseConfig * @param {FORGE.SceneParser} config input media configuration * @private */ FORGE.Media.prototype._parseConfig = function(config) { this.warn("FORGE.Media config validator not implemented"); // media configuration var mediaConfig = config.media; if (typeof mediaConfig === "undefined") { return; } // Warning : UID is not registered and applied to the FORGE.ImageScalable|FORGE.Image|FORGE.VideoHTML5|FORGE.VideoDash objects for registration this._uid = mediaConfig.uid; var source = mediaConfig.source; if (mediaConfig.type === FORGE.MediaType.GRID) { this._ready = true; } else if (mediaConfig.type === FORGE.MediaType.IMAGE) { var imageConfig; // If there isn't an URL set, it means that this is a multi resolution image. if (!source.url) { throw "Multi resolution not implemented yet !"; } if (source.format === FORGE.MediaFormat.EQUIRECTANGULAR) { imageConfig = { key: this._uid, url: source.url }; this._displayObject = new FORGE.Image(this._viewer, imageConfig); } else if (source.format === FORGE.MediaFormat.CUBE || source.format === FORGE.MediaFormat.FLAT) { imageConfig = { key: this._uid, url: source.url }; this._displayObject = new FORGE.Image(this._viewer, imageConfig); } else { throw "Flat media not supported yet !"; } this._displayObject.onLoadComplete.addOnce(this._onImageLoadComplete, this); } else if (mediaConfig.type === FORGE.MediaType.VIDEO) { // If the levels property is present, we get all urls from it and put it // inside source.url: it means that there is multi-quality. It is way // easier to handle for video than for image, as it can never be video // tiles to display. if (Array.isArray(source.levels)) { source.url = []; for (var i = 0, ii = source.levels.length; i < ii; i++) { source.url.push(source.levels[i].url); } } if (typeof source.streaming !== "undefined" && source.streaming.toLowerCase() === FORGE.VideoFormat.DASH) { this._displayObject = new FORGE.VideoDash(this._viewer, this._uid); } else { // check of the ambisonic state of the video sound prior to the video instanciation this._displayObject = new FORGE.VideoHTML5(this._viewer, this._uid, null, null, (this._config.hasSoundTarget(this._uid) === true && this._config.isAmbisonic() === true ? true : false)); } // At this point, source.url is either a streaming address, a simple // url, or an array of url this._displayObject.load(source.url); this._displayObject.onLoadedMetaData.addOnce(this._onLoadedMetaDataHandler, this); } this._options = (typeof mediaConfig.options !== "undefined") ? mediaConfig.options : null; }; /** * Internal handler on image ready. * @method FORGE.Media#_onImageLoadComplete * @private */ FORGE.Media.prototype._onImageLoadComplete = function() { this._ready = true; if (this._onLoadComplete !== null) { this._onLoadComplete.dispatch(); } }; /** * Internal handler on video metadata loaded. * @method FORGE.Media#_onLoadedMetaDataHandler * @private */ FORGE.Media.prototype._onLoadedMetaDataHandler = function() { this._ready = true; if (this._options !== null) { this._displayObject.volume = (typeof this._options.volume === "number") ? this._options.volume : 1; this._displayObject.loop = (typeof this._options.loop === "boolean") ? this._options.loop : true; if (this._options.autoPlay === true) { this._displayObject.play(); } } if (this._onLoadComplete !== null) { this._onLoadComplete.dispatch(); } }; /** * Media destroy sequence * * @method FORGE.Media#destroy */ FORGE.Media.prototype.destroy = function() { if (this._displayObject !== null) { this._displayObject.destroy(); this._displayObject = null; } if (this._onLoadComplete !== null) { this._onLoadComplete.destroy(); this._onLoadComplete = null; } this._viewer = null; this._config = null; }; /** * Get the displayObject. * @name FORGE.Media#displayObject * @readonly * @type {FORGE.DisplayObject} * * @todo This is temporary */ Object.defineProperty(FORGE.Media.prototype, "displayObject", { /** @this {FORGE.Media} */ get: function() { return this._displayObject; } }); /** * Get the ready flag * @name FORGE.Media#ready * @readonly * @type boolean */ Object.defineProperty(FORGE.Media.prototype, "ready", { /** @this {FORGE.Media} */ get: function() { return this._ready; } }); /** * Get the onLoadComplete {@link FORGE.EventDispatcher}. * @name FORGE.Media#onLoadComplete * @readonly * @type {FORGE.EventDispatcher} */ Object.defineProperty(FORGE.Media.prototype, "onLoadComplete", { /** @this {FORGE.Media} */ get: function() { if (this._onLoadComplete === null) { this._onLoadComplete = new FORGE.EventDispatcher(this); } return this._onLoadComplete; } });
Media - prepare support of flat view
src/media/Media.js
Media - prepare support of flat view
<ide><path>rc/media/Media.js <ide> <ide> var source = mediaConfig.source; <ide> <add> if (typeof mediaConfig.source !== "undefined" && <add> typeof mediaConfig.source.format === "undefined") <add> { <add> mediaConfig.source.format = FORGE.MediaFormat.FLAT; <add> } <add> <ide> if (mediaConfig.type === FORGE.MediaType.GRID) <ide> { <ide> this._ready = true; <ide> <ide> this._displayObject = new FORGE.Image(this._viewer, imageConfig); <ide> } <del> else if (source.format === FORGE.MediaFormat.CUBE || source.format === FORGE.MediaFormat.FLAT) <add> else if (source.format === FORGE.MediaFormat.CUBE || <add> source.format === FORGE.MediaFormat.FLAT) <ide> { <ide> imageConfig = { <ide> key: this._uid, <ide> <ide> this._displayObject = new FORGE.Image(this._viewer, imageConfig); <ide> } <add> <ide> else <ide> { <del> throw "Flat media not supported yet !"; <add> throw "Media format not supported"; <ide> } <ide> <ide> this._displayObject.onLoadComplete.addOnce(this._onImageLoadComplete, this);
Java
apache-2.0
cb96c08a71a3d02bdd7f7ae282bfd647c11a506f
0
ol-loginov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ernestp/consulo,mglukhikh/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,signed/intellij-community,blademainer/intellij-community,kdwink/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ryano144/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,amith01994/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,joewalnes/idea-community,blademainer/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,consulo/consulo,izonder/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ernestp/consulo,salguarnieri/intellij-community,tmpgit/intellij-community,signed/intellij-community,jagguli/intellij-community,diorcety/intellij-community,blademainer/intellij-community,slisson/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,samthor/intellij-community,ernestp/consulo,asedunov/intellij-community,adedayo/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,semonte/intellij-community,orekyuu/intellij-community,kool79/intellij-community,izonder/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,allotria/intellij-community,samthor/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,caot/intellij-community,petteyg/intellij-community,adedayo/intellij-community,fnouama/intellij-community,clumsy/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,holmes/intellij-community,holmes/intellij-community,jagguli/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,caot/intellij-community,holmes/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,allotria/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ibinti/intellij-community,joewalnes/idea-community,adedayo/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,asedunov/intellij-community,hurricup/intellij-community,caot/intellij-community,jagguli/intellij-community,hurricup/intellij-community,signed/intellij-community,xfournet/intellij-community,amith01994/intellij-community,diorcety/intellij-community,allotria/intellij-community,kdwink/intellij-community,izonder/intellij-community,jagguli/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ibinti/intellij-community,hurricup/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,da1z/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,consulo/consulo,vvv1559/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,vladmm/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,signed/intellij-community,pwoodworth/intellij-community,signed/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,slisson/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ernestp/consulo,retomerz/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,joewalnes/idea-community,fnouama/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,consulo/consulo,samthor/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,supersven/intellij-community,caot/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ryano144/intellij-community,da1z/intellij-community,blademainer/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,blademainer/intellij-community,orekyuu/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,semonte/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ibinti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,jexp/idea2,muntasirsyed/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,izonder/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,slisson/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,signed/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,consulo/consulo,joewalnes/idea-community,tmpgit/intellij-community,Lekanich/intellij-community,semonte/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,da1z/intellij-community,xfournet/intellij-community,caot/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,signed/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,allotria/intellij-community,signed/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,caot/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,vladmm/intellij-community,holmes/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,consulo/consulo,samthor/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,dslomov/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,slisson/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,asedunov/intellij-community,slisson/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,allotria/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,retomerz/intellij-community,supersven/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,supersven/intellij-community,allotria/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,supersven/intellij-community,fnouama/intellij-community,kool79/intellij-community,FHannes/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,holmes/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,retomerz/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,semonte/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,samthor/intellij-community,retomerz/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,izonder/intellij-community,ibinti/intellij-community,FHannes/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,da1z/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,FHannes/intellij-community,izonder/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,jexp/idea2,alphafoobar/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,vladmm/intellij-community,hurricup/intellij-community,slisson/intellij-community,da1z/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,diorcety/intellij-community,amith01994/intellij-community,fitermay/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,slisson/intellij-community,semonte/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,kdwink/intellij-community,caot/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,slisson/intellij-community,hurricup/intellij-community,adedayo/intellij-community,supersven/intellij-community,jexp/idea2,fitermay/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,allotria/intellij-community,xfournet/intellij-community,ernestp/consulo,diorcety/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,ernestp/consulo,gnuhub/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,jexp/idea2,xfournet/intellij-community,petteyg/intellij-community,kool79/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,Distrotech/intellij-community,jexp/idea2,ryano144/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,blademainer/intellij-community,amith01994/intellij-community,supersven/intellij-community,clumsy/intellij-community,fnouama/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,dslomov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,signed/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,signed/intellij-community,robovm/robovm-studio,allotria/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ryano144/intellij-community,consulo/consulo,ibinti/intellij-community,caot/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,diorcety/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,suncycheng/intellij-community,allotria/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,vladmm/intellij-community,xfournet/intellij-community,joewalnes/idea-community,supersven/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,supersven/intellij-community,slisson/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community
package com.intellij.psi.impl.source.tree.injected; import com.intellij.injected.editor.*; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.LanguageParserDefinitions; import com.intellij.lang.ParserDefinition; import com.intellij.lang.injection.MultiHostInjector; import com.intellij.lang.injection.MultiHostRegistrar; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.psi.*; import com.intellij.psi.impl.ParameterizedCachedValueImpl; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.*; import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * @author cdr */ public class InjectedLanguageUtil { private static final Key<ParameterizedCachedValue<Places, PsiElement>> INJECTED_PSI_KEY = Key.create("INJECTED_PSI"); private static final Key<List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>>> HIGHLIGHT_TOKENS = Key.create("HIGHLIGHT_TOKENS"); public static void forceInjectionOnElement(@NotNull final PsiElement host) { enumerate(host, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { } }); } @Nullable public static List<Pair<PsiElement, TextRange>> getInjectedPsiFiles(@NotNull final PsiElement host) { final List<Pair<PsiElement, TextRange>> result = new SmartList<Pair<PsiElement, TextRange>>(); enumerate(host, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { for (PsiLanguageInjectionHost.Shred place : places) { if (place.host == host) { result.add(new Pair<PsiElement, TextRange>(injectedPsi, place.getRangeInsideHost())); } } } }); return result.isEmpty() ? null : result; } public static TextRange toTextRange(RangeMarker marker) { return new ProperTextRange(marker.getStartOffset(), marker.getEndOffset()); } public static List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> getHighlightTokens(PsiFile file) { return file.getUserData(HIGHLIGHT_TOKENS); } private static List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> obtainHighlightTokensFromLexer(Language language, StringBuilder outChars, List<LiteralTextEscaper<? extends PsiLanguageInjectionHost>> escapers, List<PsiLanguageInjectionHost.Shred> shreds, VirtualFileWindow virtualFile, DocumentWindowImpl documentWindow, Project project) { List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> tokens = new ArrayList<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>>(10); SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, (VirtualFile)virtualFile); Lexer lexer = syntaxHighlighter.getHighlightingLexer(); lexer.start(outChars, 0, outChars.length(), 0); int hostNum = 0; int prevHostsCombinedLength = 0; nextToken: for (IElementType tokenType = lexer.getTokenType(); tokenType != null; lexer.advance(), tokenType = lexer.getTokenType()) { TextRange range = new ProperTextRange(lexer.getTokenStart(), lexer.getTokenEnd()); while (!range.isEmpty()) { if (range.getStartOffset() >= shreds.get(hostNum).range.getEndOffset()) { hostNum++; prevHostsCombinedLength = range.getStartOffset(); } TextRange editable = documentWindow.intersectWithEditable(range); if (editable == null || editable.getLength() == 0) continue nextToken; editable = editable.intersection(shreds.get(hostNum).range); if (editable == null || editable.getLength() == 0) continue nextToken; range = new ProperTextRange(editable.getEndOffset(), range.getEndOffset()); PsiLanguageInjectionHost host = shreds.get(hostNum).host; LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = escapers.get(hostNum); TextRange rangeInsideHost = shreds.get(hostNum).getRangeInsideHost(); int prefixLength = shreds.get(hostNum).prefix.length(); int start = escaper.getOffsetInHost(editable.getStartOffset() - prevHostsCombinedLength - prefixLength, rangeInsideHost); int end = escaper.getOffsetInHost(editable.getEndOffset() - prevHostsCombinedLength - prefixLength, rangeInsideHost); if (end == -1) { end = rangeInsideHost.getEndOffset(); tokens.add(Trinity.<IElementType, PsiLanguageInjectionHost, TextRange>create(tokenType, host, new ProperTextRange(start, end))); prevHostsCombinedLength = shreds.get(hostNum).range.getEndOffset(); range = new ProperTextRange(shreds.get(hostNum).range.getEndOffset(), range.getEndOffset()); } else { TextRange rangeInHost = new ProperTextRange(start, end); tokens.add(Trinity.create(tokenType, host, rangeInHost)); } } } return tokens; } private static boolean isInjectedFragment(final PsiFile file) { return file.getViewProvider() instanceof MyFileViewProvider; } private static class Place { private final PsiFile myInjectedPsi; private final List<PsiLanguageInjectionHost.Shred> myShreds; public Place(PsiFile injectedPsi, List<PsiLanguageInjectionHost.Shred> shreds) { myShreds = shreds; myInjectedPsi = injectedPsi; } } private static interface Places extends List<Place> {} private static class PlacesImpl extends SmartList<Place> implements Places {} public static void enumerate(@NotNull PsiElement host, @NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) { PsiFile containingFile = host.getContainingFile(); enumerate(host, containingFile, visitor, true); } public static void enumerate(@NotNull PsiElement host, @NotNull PsiFile containingFile, @NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor, boolean probeUp) { //do not inject into nonphysical files except during completion if (!containingFile.isPhysical() && containingFile.getOriginalFile() == null) { final PsiElement context = containingFile.getContext(); if (context == null) return; final PsiFile file = context.getContainingFile(); if (file == null || !file.isPhysical() && file.getOriginalFile() == null) return; } Places places = probeElementsUp(host, containingFile, probeUp); if (places == null) return; for (Place place : places) { PsiFile injectedPsi = place.myInjectedPsi; List<PsiLanguageInjectionHost.Shred> pairs = place.myShreds; visitor.visit(injectedPsi, pairs); } } private static class MyFileViewProvider extends SingleRootFileViewProvider { private PsiLanguageInjectionHost[] myHosts; private Project myProject; private MyFileViewProvider(@NotNull Project project, @NotNull VirtualFileWindow virtualFile, List<PsiLanguageInjectionHost> hosts) { super(PsiManager.getInstance(project), (VirtualFile)virtualFile); myHosts = hosts.toArray(new PsiLanguageInjectionHost[hosts.size()]); myProject = myHosts[0].getProject(); } public void rootChanged(PsiFile psiFile) { super.rootChanged(psiFile); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getManager().getProject()); DocumentWindowImpl documentWindow = (DocumentWindowImpl)documentManager.getDocument(psiFile); String[] changes = documentWindow.calculateMinEditSequence(psiFile.getText()); RangeMarker[] hostRanges = documentWindow.getHostRanges(); assert changes.length == myHosts.length; for (int i = 0; i < myHosts.length; i++) { String change = changes[i]; if (change != null) { PsiLanguageInjectionHost host = myHosts[i]; RangeMarker hostRange = hostRanges[i]; TextRange hostTextRange = host.getTextRange(); TextRange rangeInsideHost = hostTextRange.intersection(toTextRange(hostRange)).shiftRight(-hostTextRange.getStartOffset()); String newHostText = StringUtil.replaceSubstring(host.getText(), rangeInsideHost, change); host.fixText(newHostText); } } } public FileViewProvider clone() { final FileViewProvider copy = super.clone(); final PsiFile psi = copy.getPsi(getBaseLanguage()); psi.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, getPsi(getBaseLanguage()).getUserData(FileContextUtil.INJECTED_IN_ELEMENT)); return copy; } @Nullable protected PsiFile getPsiInner(Language target) { // when FileManager rebuilds file map, all files temporarily become invalid, so this check is doomed PsiFile file = super.getPsiInner(target); //if (file == null || file.getContext() == null) return null; return file; } private void replace(PsiFile injectedPsi, List<PsiLanguageInjectionHost.Shred> shreds) { setVirtualFile(injectedPsi.getVirtualFile()); myHosts = new PsiLanguageInjectionHost[shreds.size()]; for (int i = 0; i < shreds.size(); i++) { PsiLanguageInjectionHost.Shred shred = shreds.get(i); myHosts[i] = shred.host; } myProject = myHosts[0].getProject(); } private boolean isValid() { return !myProject.isDisposed(); } } private static void patchLeafs(final ASTNode parsedNode, final List<LiteralTextEscaper<? extends PsiLanguageInjectionHost>> escapers, final List<PsiLanguageInjectionHost.Shred> shreds) { final Map<LeafElement, String> newTexts = new THashMap<LeafElement, String>(); final StringBuilder catLeafs = new StringBuilder(); ((TreeElement)parsedNode).acceptTree(new RecursiveTreeElementVisitor(){ int currentHostNum = -1; LeafElement prevElement; String prevElementTail; int prevHostsCombinedLength; TextRange shredHostRange; TextRange rangeInsideHost; String hostText; PsiLanguageInjectionHost.Shred shred; int prefixLength; { incHostNum(0); } protected boolean visitNode(TreeElement element) { return true; } @Override public void visitLeaf(LeafElement leaf) { String leafText = leaf.getText(); catLeafs.append(leafText); TextRange range = leaf.getTextRange(); int startOffsetInHost; while (true) { if (prefixLength > range.getStartOffset() && prefixLength < range.getEndOffset()) { //LOG.error("Prefix must not contain text that will be glued with the element body after parsing. " + // "However, parsed element of "+leaf.getClass()+" contains "+(prefixLength-range.getStartOffset()) + " characters from the prefix. " + // "Parsed text is '"+leaf.getText()+"'"); } if (range.getStartOffset() < shredHostRange.getEndOffset() && shredHostRange.getEndOffset() < range.getEndOffset()) { //LOG.error("Suffix must not contain text that will be glued with the element body after parsing. " + // "However, parsed element of "+leaf.getClass()+" contains "+(range.getEndOffset()-shredHostRange.getEndOffset()) + " characters from the suffix. " + // "Parsed text is '"+leaf.getText()+"'"); } int start = range.getStartOffset() - prevHostsCombinedLength; if (start < prefixLength) return; int end = range.getEndOffset(); if (end > shred.range.getEndOffset() - shred.suffix.length() && end <= shred.range.getEndOffset()) return; startOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(start - prefixLength, rangeInsideHost); if (startOffsetInHost != -1 && startOffsetInHost != rangeInsideHost.getEndOffset()) { break; } // no way next leaf might stand more than one shred apart incHostNum(range.getStartOffset()); } String leafEncodedText = ""; while (true) { if (range.getEndOffset() <= shred.range.getEndOffset()) { int end = range.getEndOffset() - prevHostsCombinedLength; if (end < prefixLength) { leafEncodedText += shred.prefix.substring(0, end); } else { int endOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(end - prefixLength, rangeInsideHost); assert endOffsetInHost != -1; leafEncodedText += hostText.substring(startOffsetInHost, endOffsetInHost); } break; } String rest = hostText.substring(startOffsetInHost, rangeInsideHost.getEndOffset()); leafEncodedText += rest; incHostNum(shred.range.getEndOffset()); startOffsetInHost = shred.getRangeInsideHost().getStartOffset(); } if (leaf.getElementType() == TokenType.WHITE_SPACE && prevElementTail != null) { // optimization: put all garbage into whitespace leafEncodedText = prevElementTail + leafEncodedText; newTexts.remove(prevElement); storeUnescapedTextFor(prevElement, null); } if (!Comparing.strEqual(leafText, leafEncodedText)) { newTexts.put(leaf, leafEncodedText); storeUnescapedTextFor(leaf, leafText); } if (leafEncodedText.startsWith(leafText) && leafEncodedText.length() != leafText.length()) { prevElementTail = leafEncodedText.substring(leafText.length()); } else { prevElementTail = null; } prevElement = leaf; } private void incHostNum(int startOffset) { currentHostNum++; prevHostsCombinedLength = startOffset; shred = shreds.get(currentHostNum); shredHostRange = new ProperTextRange(TextRange.from(shred.prefix.length(), shred.getRangeInsideHost().getLength())); rangeInsideHost = shred.getRangeInsideHost(); hostText = shred.host.getText(); prefixLength = shredHostRange.getStartOffset(); } }); String nodeText = parsedNode.getText(); assert nodeText.equals(catLeafs.toString()) : "Malformed PSI structure: leaf texts do not add up to the whole file text." + "\nFile text (from tree) :'"+nodeText+"'" + "\nFile text (from PSI) :'"+parsedNode.getPsi().getText()+"'" + "\nLeaf texts concatenated:'"+catLeafs+"';" + "\nFile root: "+parsedNode+ "\nLanguage: "+parsedNode.getPsi().getLanguage()+ "\nHost file: "+shreds.get(0).host.getContainingFile().getVirtualFile() ; for (LeafElement leaf : newTexts.keySet()) { String newText = newTexts.get(leaf); leaf.setText(newText); } ((TreeElement)parsedNode).acceptTree(new RecursiveTreeElementVisitor(){ protected boolean visitNode(TreeElement element) { element.clearCaches(); return true; } }); } private static void storeUnescapedTextFor(final LeafElement leaf, final String leafText) { PsiElement psi = leaf.getPsi(); if (psi != null) { psi.putUserData(InjectedLanguageManagerImpl.UNESCAPED_TEXT, leafText); } } public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable PsiFile file) { if (editor == null || file == null || editor instanceof EditorWindow) return editor; int offset = editor.getCaretModel().getOffset(); return getEditorForInjectedLanguageNoCommit(editor, file, offset); } public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable PsiFile file, final int offset) { if (editor == null || file == null || editor instanceof EditorWindow) return editor; PsiFile injectedFile = findInjectedPsiNoCommit(file, offset); return getInjectedEditorForInjectedFile(editor, injectedFile); } @NotNull public static Editor getInjectedEditorForInjectedFile(@NotNull Editor editor, final PsiFile injectedFile) { if (injectedFile == null || editor instanceof EditorWindow) return editor; Document document = PsiDocumentManager.getInstance(editor.getProject()).getDocument(injectedFile); if (!(document instanceof DocumentWindowImpl)) return editor; DocumentWindowImpl documentWindow = (DocumentWindowImpl)document; SelectionModel selectionModel = editor.getSelectionModel(); if (selectionModel.hasSelection()) { int selstart = selectionModel.getSelectionStart(); int selend = selectionModel.getSelectionEnd(); if (!documentWindow.containsRange(selstart, selend)) { // selection spreads out the injected editor range return editor; } } return EditorWindow.create(documentWindow, (EditorImpl)editor, injectedFile); } public static PsiFile findInjectedPsiNoCommit(@NotNull PsiFile host, int offset) { PsiElement injected = findInjectedElementNoCommit(host, offset); if (injected != null) { return injected.getContainingFile(); } return null; } // consider injected elements public static PsiElement findElementAtNoCommit(@NotNull PsiFile file, int offset) { if (!isInjectedFragment(file)) { PsiElement injected = findInjectedElementNoCommit(file, offset); if (injected != null) { return injected; } } //PsiElement at = file.findElementAt(offset); FileViewProvider viewProvider = file.getViewProvider(); return viewProvider.findElementAt(offset, viewProvider.getBaseLanguage()); } private static final InjectedPsiProvider INJECTED_PSI_PROVIDER = new InjectedPsiProvider(); private static Places probeElementsUp(@NotNull PsiElement element, @NotNull PsiFile hostPsiFile, boolean probeUp) { PsiManager psiManager = hostPsiFile.getManager(); final Project project = psiManager.getProject(); InjectedLanguageManagerImpl injectedManager = InjectedLanguageManagerImpl.getInstanceImpl(project); if (injectedManager == null) return null; //for tests for (PsiElement current = element; current != null && current != hostPsiFile; current = current.getParent()) { if ("EL".equals(current.getLanguage().getID())) break; ParameterizedCachedValue<Places,PsiElement> data = current.getUserData(INJECTED_PSI_KEY); if (data != null) { Places value = data.getValue(current); if (value != null) { return value; } } Places places = InjectedPsiProvider.doCompute(current, injectedManager, project, hostPsiFile); if (places != null) { ParameterizedCachedValue<Places,PsiElement> cachedValue = psiManager.getCachedValuesManager().createParameterizedCachedValue(INJECTED_PSI_PROVIDER, false); Document hostDocument = hostPsiFile.getViewProvider().getDocument(); CachedValueProvider.Result<Places> result = new CachedValueProvider.Result<Places>(places, PsiModificationTracker.MODIFICATION_COUNT, hostDocument); ((ParameterizedCachedValueImpl<Places,PsiElement>)cachedValue).setValue(result); for (Place place : places) { for (PsiLanguageInjectionHost.Shred pair : place.myShreds) { pair.host.putUserData(INJECTED_PSI_KEY, cachedValue); } } current.putUserData(INJECTED_PSI_KEY, cachedValue); return places; } if (!probeUp) break; } return null; } public static PsiElement findInjectedElementNoCommitWithOffset(@NotNull PsiFile file, final int offset) { if (isInjectedFragment(file)) return null; final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject()); PsiElement element = file.getViewProvider().findElementAt(offset, file.getLanguage()); return element == null ? null : findInside(element, file, offset, documentManager); } public static PsiElement findInjectedElementNoCommit(@NotNull PsiFile file, final int offset) { PsiElement inj = findInjectedElementNoCommitWithOffset(file, offset); if (inj != null) return inj; if (offset != 0) { inj = findInjectedElementNoCommitWithOffset(file, offset - 1); } return inj; } private static PsiElement findInside(@NotNull PsiElement element, @NotNull PsiFile file, final int offset, @NotNull final PsiDocumentManager documentManager) { final Ref<PsiElement> out = new Ref<PsiElement>(); enumerate(element, file, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { for (PsiLanguageInjectionHost.Shred place : places) { TextRange hostRange = place.host.getTextRange(); if (hostRange.cutOut(place.getRangeInsideHost()).grown(1).contains(offset)) { DocumentWindowImpl document = (DocumentWindowImpl)documentManager.getCachedDocument(injectedPsi); int injectedOffset = document.hostToInjected(offset); PsiElement injElement = injectedPsi.findElementAt(injectedOffset); out.set(injElement == null ? injectedPsi : injElement); } } } }, true); return out.get(); } private static class InjectedPsiProvider implements ParameterizedCachedValueProvider<Places, PsiElement> { public CachedValueProvider.Result<Places> compute(PsiElement element) { PsiFile hostPsiFile = element.getContainingFile(); if (hostPsiFile == null) return null; FileViewProvider viewProvider = hostPsiFile.getViewProvider(); final DocumentEx hostDocument = (DocumentEx)viewProvider.getDocument(); if (hostDocument == null) return null; PsiManager psiManager = viewProvider.getManager(); final Project project = psiManager.getProject(); InjectedLanguageManagerImpl injectedManager = InjectedLanguageManagerImpl.getInstanceImpl(project); if (injectedManager == null) return null; //for tests final Places result = doCompute(element, injectedManager, project, hostPsiFile); if (result == null) return null; return new CachedValueProvider.Result<Places>(result, PsiModificationTracker.MODIFICATION_COUNT, hostDocument); } @Nullable private static Places doCompute(final PsiElement element, InjectedLanguageManagerImpl injectedManager, Project project, PsiFile hostPsiFile) { MyInjProcessor processor = new MyInjProcessor(injectedManager, project, hostPsiFile); injectedManager.processInPlaceInjectorsFor(element, processor); return processor.hostRegistrar == null ? null : processor.hostRegistrar.result; } private static class MyInjProcessor implements InjectedLanguageManagerImpl.InjProcessor { private MyMultiHostRegistrar hostRegistrar; private final InjectedLanguageManagerImpl myInjectedManager; private final Project myProject; private final PsiFile myHostPsiFile; public MyInjProcessor(InjectedLanguageManagerImpl injectedManager, Project project, PsiFile hostPsiFile) { myInjectedManager = injectedManager; myProject = project; myHostPsiFile = hostPsiFile; } public boolean process(PsiElement element, MultiHostInjector injector) { if (hostRegistrar == null) { hostRegistrar = new MyMultiHostRegistrar(myProject, myInjectedManager, myHostPsiFile); } injector.getLanguagesToInject(hostRegistrar, element); return hostRegistrar.result == null; } } private static class MyMultiHostRegistrar implements MultiHostRegistrar { private Places result; private Language myLanguage; private List<TextRange> relevantRangesInHostDocument; private List<String> prefixes; private List<String> suffixes; private List<PsiLanguageInjectionHost> injectionHosts; private List<LiteralTextEscaper<? extends PsiLanguageInjectionHost>> escapers; private List<PsiLanguageInjectionHost.Shred> shreds; private StringBuilder outChars; boolean isOneLineEditor; boolean cleared; private final Project myProject; private final PsiManager myPsiManager; private DocumentEx myHostDocument; private VirtualFile myHostVirtualFile; private final InjectedLanguageManagerImpl myInjectedManager; private final PsiFile myHostPsiFile; public MyMultiHostRegistrar(Project project, InjectedLanguageManagerImpl injectedManager, PsiFile hostPsiFile) { myProject = project; myInjectedManager = injectedManager; myHostPsiFile = PsiUtilBase.getTemplateLanguageFile(hostPsiFile); myPsiManager = myHostPsiFile.getManager(); cleared = true; } @NotNull public MultiHostRegistrar startInjecting(@NotNull Language language) { relevantRangesInHostDocument = new SmartList<TextRange>(); prefixes = new SmartList<String>(); suffixes = new SmartList<String>(); injectionHosts = new SmartList<PsiLanguageInjectionHost>(); escapers = new SmartList<LiteralTextEscaper<? extends PsiLanguageInjectionHost>>(); shreds = new SmartList<PsiLanguageInjectionHost.Shred>(); outChars = new StringBuilder(); if (!cleared) { clear(); throw new IllegalStateException("Seems you haven't called doneInjecting()"); } if (LanguageParserDefinitions.INSTANCE.forLanguage(language) == null) { throw new UnsupportedOperationException("Cannot inject language '" + language + "' since its getParserDefinition() returns null"); } myLanguage = language; FileViewProvider viewProvider = myHostPsiFile.getViewProvider(); myHostVirtualFile = viewProvider.getVirtualFile(); myHostDocument = (DocumentEx)viewProvider.getDocument(); assert myHostDocument != null : myHostPsiFile + "; " + viewProvider; return this; } private void clear() { relevantRangesInHostDocument.clear(); prefixes.clear(); suffixes.clear(); injectionHosts.clear(); escapers.clear(); shreds.clear(); outChars.setLength(0); isOneLineEditor = false; myLanguage = null; cleared = true; } @NotNull public MultiHostRegistrar addPlace(@NonNls @Nullable String prefix, @NonNls @Nullable String suffix, @NotNull PsiLanguageInjectionHost host, @NotNull TextRange rangeInsideHost) { ProperTextRange.assertProperRange(rangeInsideHost); PsiFile containingFile = PsiUtilBase.getTemplateLanguageFile(host); assert containingFile == myHostPsiFile : "Trying to inject into foreign file: "+containingFile+" while processing injections for "+myHostPsiFile; TextRange hostTextRange = host.getTextRange(); if (!hostTextRange.contains(rangeInsideHost.shiftRight(hostTextRange.getStartOffset()))) { clear(); throw new IllegalArgumentException("rangeInsideHost must lie within host text range. rangeInsideHost:"+rangeInsideHost+"; host textRange:"+ hostTextRange); } if (myLanguage == null) { clear(); throw new IllegalStateException("Seems you haven't called startInjecting()"); } if (prefix == null) prefix = ""; if (suffix == null) suffix = ""; prefixes.add(prefix); suffixes.add(suffix); cleared = false; injectionHosts.add(host); int startOffset = outChars.length(); outChars.append(prefix); LiteralTextEscaper<? extends PsiLanguageInjectionHost> textEscaper = host.createLiteralTextEscaper(); escapers.add(textEscaper); isOneLineEditor |= textEscaper.isOneLine(); TextRange relevantRange = textEscaper.getRelevantTextRange().intersection(rangeInsideHost); if (relevantRange == null) { relevantRange = TextRange.from(textEscaper.getRelevantTextRange().getStartOffset(), 0); } else { boolean result = textEscaper.decode(relevantRange, outChars); if (!result) { // if there are invalid chars, adjust the range int offsetInHost = textEscaper.getOffsetInHost(outChars.length() - startOffset, rangeInsideHost); relevantRange = relevantRange.intersection(new TextRange(0, offsetInHost)); } } outChars.append(suffix); int endOffset = outChars.length(); TextRange relevantRangeInHost = relevantRange.shiftRight(hostTextRange.getStartOffset()); relevantRangesInHostDocument.add(relevantRangeInHost); RangeMarker relevantMarker = myHostDocument.createRangeMarker(relevantRangeInHost); relevantMarker.setGreedyToLeft(true); relevantMarker.setGreedyToRight(true); shreds.add(new PsiLanguageInjectionHost.Shred(host, relevantMarker, prefix, suffix, new ProperTextRange(startOffset, endOffset))); return this; } public void doneInjecting() { try { if (shreds.isEmpty()) { throw new IllegalStateException("Seems you haven't called addPlace()"); } PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); assert ArrayUtil.indexOf(documentManager.getUncommittedDocuments(), myHostDocument) == -1; assert myHostPsiFile.getText().equals(myHostDocument.getText()); DocumentWindowImpl documentWindow = new DocumentWindowImpl(myHostDocument, isOneLineEditor, prefixes, suffixes, relevantRangesInHostDocument); VirtualFileWindowImpl virtualFile = (VirtualFileWindowImpl)myInjectedManager.createVirtualFile(myLanguage, myHostVirtualFile, documentWindow, outChars); myLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(myLanguage, virtualFile, myProject); virtualFile.setLanguage(myLanguage); DocumentImpl decodedDocument = new DocumentImpl(outChars); FileDocumentManagerImpl.registerDocument(decodedDocument, virtualFile); SingleRootFileViewProvider viewProvider = new MyFileViewProvider(myProject, virtualFile, injectionHosts); ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(myLanguage); assert parserDefinition != null; PsiFile psiFile = parserDefinition.createFile(viewProvider); assert isInjectedFragment(psiFile) : psiFile.getViewProvider(); SmartPsiElementPointer<PsiLanguageInjectionHost> pointer = createHostSmartPointer(injectionHosts.get(0)); psiFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, pointer); final ASTNode parsedNode = psiFile.getNode(); assert parsedNode instanceof FileElement : parsedNode; String documentText = documentWindow.getText(); assert outChars.toString().equals(parsedNode.getText()) : "Before patch: doc:\n" + documentText + "\n---PSI:\n" + parsedNode.getText() + "\n---chars:\n"+outChars; try { patchLeafs(parsedNode, escapers, shreds); } catch (ProcessCanceledException e) { throw e; } catch (RuntimeException e) { throw new RuntimeException("Patch error, lang="+myLanguage+";\n "+myHostVirtualFile+"; places:"+injectionHosts+";\n ranges:"+relevantRangesInHostDocument, e); } assert parsedNode.getText().equals(documentText) : "After patch: doc:\n" + documentText + "\n---PSI:\n" + parsedNode.getText() + "\n---chars:\n"+outChars; ((FileElement)parsedNode).setManager((PsiManagerEx)myPsiManager); virtualFile.setContent(null, documentWindow.getText(), false); FileDocumentManagerImpl.registerDocument(documentWindow, virtualFile); synchronized (PsiLock.LOCK) { psiFile = registerDocument(documentWindow, psiFile, shreds, myHostPsiFile, documentManager); MyFileViewProvider myFileViewProvider = (MyFileViewProvider)psiFile.getViewProvider(); myFileViewProvider.setVirtualFile(virtualFile); myFileViewProvider.forceCachedPsi(psiFile); } List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> tokens = obtainHighlightTokensFromLexer(myLanguage, outChars, escapers, shreds, virtualFile, documentWindow, myProject); psiFile.putUserData(HIGHLIGHT_TOKENS, tokens); PsiDocumentManagerImpl.checkConsistency(psiFile, documentWindow); Place place = new Place(psiFile, new ArrayList<PsiLanguageInjectionHost.Shred>(shreds)); if (result == null) { result = new PlacesImpl(); } result.add(place); } finally { clear(); } } } } private static <T extends PsiLanguageInjectionHost> SmartPsiElementPointer<T> createHostSmartPointer(final T host) { return host.isPhysical() ? SmartPointerManager.getInstance(host.getProject()).createSmartPsiElementPointer(host) : new SmartPsiElementPointer<T>() { public T getElement() { return host; } public PsiFile getContainingFile() { return host.getContainingFile(); } }; } private static final Key<List<DocumentWindow>> INJECTED_DOCS_KEY = Key.create("INJECTED_DOCS_KEY"); private static final Key<List<RangeMarker>> INJECTED_REGIONS_KEY = Key.create("INJECTED_REGIONS_KEY"); @NotNull public static List<DocumentWindow> getCachedInjectedDocuments(@NotNull PsiFile hostPsiFile) { List<DocumentWindow> injected = hostPsiFile.getUserData(INJECTED_DOCS_KEY); if (injected == null) { injected = ((UserDataHolderEx)hostPsiFile).putUserDataIfAbsent(INJECTED_DOCS_KEY, new CopyOnWriteArrayList<DocumentWindow>()); } return injected; } public static void commitAllInjectedDocuments(Document hostDocument, Project project) { List<RangeMarker> injected = getCachedInjectedRegions(hostDocument); if (injected.isEmpty()) return; PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); PsiFile hostPsiFile = documentManager.getPsiFile(hostDocument); assert hostPsiFile != null; for (RangeMarker rangeMarker : injected) { PsiElement element = rangeMarker.isValid() ? hostPsiFile.findElementAt(rangeMarker.getStartOffset()) : null; if (element == null) { injected.remove(rangeMarker); continue; } // it is here reparse happens and old file contents replaced enumerate(element, hostPsiFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { PsiDocumentManagerImpl.checkConsistency(injectedPsi, injectedPsi.getViewProvider().getDocument()); } }, true); } PsiDocumentManagerImpl.checkConsistency(hostPsiFile, hostDocument); } public static void clearCaches(PsiFile injected) { VirtualFileWindow virtualFile = (VirtualFileWindow)injected.getVirtualFile(); PsiManagerEx psiManagerEx = (PsiManagerEx)injected.getManager(); psiManagerEx.getFileManager().setViewProvider((VirtualFile)virtualFile, null); Project project = psiManagerEx.getProject(); if (!project.isDisposed()) { InjectedLanguageManagerImpl.getInstanceImpl(project).clearCaches(virtualFile); } } private static PsiFile registerDocument(final DocumentWindowImpl documentWindow, final PsiFile injectedPsi, List<PsiLanguageInjectionHost.Shred> shreds, final PsiFile hostPsiFile, PsiDocumentManager documentManager) { DocumentEx hostDocument = documentWindow.getDelegate(); List<DocumentWindow> injected = getCachedInjectedDocuments(hostPsiFile); for (int i = injected.size()-1; i>=0; i--) { DocumentWindowImpl oldDocument = (DocumentWindowImpl)injected.get(i); PsiFileImpl oldFile = (PsiFileImpl)documentManager.getCachedPsiFile(oldDocument); FileViewProvider oldViewProvider; if (oldFile == null || !oldFile.isValid() || !((oldViewProvider = oldFile.getViewProvider()) instanceof MyFileViewProvider) || !((MyFileViewProvider)oldViewProvider).isValid()) { injected.remove(i); oldDocument.dispose(); continue; } ASTNode injectedNode = injectedPsi.getNode(); ASTNode oldFileNode = oldFile.getNode(); assert injectedNode != null; assert oldFileNode != null; if (oldDocument.areRangesEqual(documentWindow)) { if (oldFile.getFileType() != injectedPsi.getFileType() || oldFile.getLanguage() != injectedPsi.getLanguage()) { injected.remove(i); oldDocument.dispose(); continue; } oldFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, injectedPsi.getUserData(FileContextUtil.INJECTED_IN_ELEMENT)); if (!injectedNode.getText().equals(oldFileNode.getText())) { // replace psi FileElement newFileElement = (FileElement)injectedNode; FileElement oldFileElement = oldFile.getTreeElement(); if (oldFileElement.getFirstChildNode() != null) { TreeUtil.removeRange(oldFileElement.getFirstChildNode(), null); } final ASTNode firstChildNode = newFileElement.getFirstChildNode(); if (firstChildNode != null) { TreeUtil.addChildren(oldFileElement, (TreeElement)firstChildNode); } oldFileElement.setCharTable(newFileElement.getCharTable()); FileDocumentManagerImpl.registerDocument(documentWindow, oldFile.getVirtualFile()); oldFile.subtreeChanged(); MyFileViewProvider viewProvider = (MyFileViewProvider)oldViewProvider; viewProvider.replace(injectedPsi, shreds); } return oldFile; } } injected.add(documentWindow); List<RangeMarker> injectedRegions = getCachedInjectedRegions(hostDocument); RangeMarker newMarker = documentWindow.getHostRanges()[0]; TextRange newRange = toTextRange(newMarker); for (int i = 0; i < injectedRegions.size(); i++) { RangeMarker stored = injectedRegions.get(i); TextRange storedRange = toTextRange(stored); if (storedRange.intersects(newRange)) { injectedRegions.set(i, newMarker); break; } if (storedRange.getStartOffset() > newRange.getEndOffset()) { injectedRegions.add(i, newMarker); break; } } if (injectedRegions.isEmpty() || newRange.getStartOffset() > injectedRegions.get(injectedRegions.size()-1).getEndOffset()) { injectedRegions.add(newMarker); } return injectedPsi; } private static List<RangeMarker> getCachedInjectedRegions(Document hostDocument) { List<RangeMarker> injectedRegions = hostDocument.getUserData(INJECTED_REGIONS_KEY); if (injectedRegions == null) { injectedRegions = ((UserDataHolderEx)hostDocument).putUserDataIfAbsent(INJECTED_REGIONS_KEY, new CopyOnWriteArrayList<RangeMarker>()); } return injectedRegions; } public static Editor openEditorFor(PsiFile file, Project project) { Document document = PsiDocumentManager.getInstance(project).getDocument(file); // may return editor injected in current selection in the host editor, not for the file passed as argument VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { return null; } if (virtualFile instanceof VirtualFileWindow) { virtualFile = ((VirtualFileWindow)virtualFile).getDelegate(); } Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile, -1), false); if (editor == null || editor instanceof EditorWindow) return editor; if (document instanceof DocumentWindowImpl) { return EditorWindow.create((DocumentWindowImpl)document, (EditorImpl)editor, file); } return editor; } public static PsiFile getTopLevelFile(PsiElement element) { PsiFile containingFile = element.getContainingFile(); Document document = PsiDocumentManager.getInstance(element.getProject()).getCachedDocument(containingFile); if (document instanceof DocumentWindow) { PsiElement host = containingFile.getContext(); if (host != null) containingFile = host.getContainingFile(); } return containingFile; } public static boolean isInInjectedLanguagePrefixSuffix(final PsiElement element) { PsiFile injectedFile = element.getContainingFile(); if (injectedFile == null) return false; Document document = PsiDocumentManager.getInstance(element.getProject()).getCachedDocument(injectedFile); if (!(document instanceof DocumentWindowImpl)) return false; DocumentWindowImpl documentWindow = (DocumentWindowImpl)document; TextRange elementRange = element.getTextRange(); TextRange editable = documentWindow.intersectWithEditable(elementRange); return !elementRange.equals(editable); //) throw new IncorrectOperationException("Can't change "+ UsageViewUtil.createNodeText(element, true)); } public static boolean isSelectionIsAboutToOverflowInjectedFragment(EditorWindow injectedEditor) { int selStart = injectedEditor.getSelectionModel().getSelectionStart(); int selEnd = injectedEditor.getSelectionModel().getSelectionEnd(); DocumentWindow document = injectedEditor.getDocument(); boolean isStartOverflows = selStart == 0; if (!isStartOverflows) { int hostPrev = document.injectedToHost(selStart - 1); isStartOverflows = document.hostToInjected(hostPrev) == selStart; } boolean isEndOverflows = selEnd == document.getTextLength(); if (!isEndOverflows) { int hostNext = document.injectedToHost(selEnd + 1); isEndOverflows = document.hostToInjected(hostNext) == selEnd; } return isStartOverflows && isEndOverflows; } }
lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java
package com.intellij.psi.impl.source.tree.injected; import com.intellij.injected.editor.*; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.LanguageParserDefinitions; import com.intellij.lang.ParserDefinition; import com.intellij.lang.injection.MultiHostInjector; import com.intellij.lang.injection.MultiHostRegistrar; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.psi.*; import com.intellij.psi.impl.ParameterizedCachedValueImpl; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.*; import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * @author cdr */ public class InjectedLanguageUtil { private static final Key<ParameterizedCachedValue<Places, PsiElement>> INJECTED_PSI_KEY = Key.create("INJECTED_PSI"); private static final Key<List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>>> HIGHLIGHT_TOKENS = Key.create("HIGHLIGHT_TOKENS"); public static void forceInjectionOnElement(@NotNull final PsiElement host) { enumerate(host, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { } }); } @Nullable public static List<Pair<PsiElement, TextRange>> getInjectedPsiFiles(@NotNull final PsiElement host) { final List<Pair<PsiElement, TextRange>> result = new SmartList<Pair<PsiElement, TextRange>>(); enumerate(host, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { for (PsiLanguageInjectionHost.Shred place : places) { if (place.host == host) { result.add(new Pair<PsiElement, TextRange>(injectedPsi, place.getRangeInsideHost())); } } } }); return result.isEmpty() ? null : result; } public static TextRange toTextRange(RangeMarker marker) { return new ProperTextRange(marker.getStartOffset(), marker.getEndOffset()); } public static List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> getHighlightTokens(PsiFile file) { return file.getUserData(HIGHLIGHT_TOKENS); } private static List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> obtainHighlightTokensFromLexer(Language language, StringBuilder outChars, List<LiteralTextEscaper<? extends PsiLanguageInjectionHost>> escapers, List<PsiLanguageInjectionHost.Shred> shreds, VirtualFileWindow virtualFile, DocumentWindowImpl documentWindow, Project project) { List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> tokens = new ArrayList<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>>(10); SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, (VirtualFile)virtualFile); Lexer lexer = syntaxHighlighter.getHighlightingLexer(); lexer.start(outChars, 0, outChars.length(), 0); int hostNum = 0; int prevHostsCombinedLength = 0; nextToken: for (IElementType tokenType = lexer.getTokenType(); tokenType != null; lexer.advance(), tokenType = lexer.getTokenType()) { TextRange range = new ProperTextRange(lexer.getTokenStart(), lexer.getTokenEnd()); while (!range.isEmpty()) { if (range.getStartOffset() >= shreds.get(hostNum).range.getEndOffset()) { hostNum++; prevHostsCombinedLength = range.getStartOffset(); } TextRange editable = documentWindow.intersectWithEditable(range); if (editable == null || editable.getLength() == 0) continue nextToken; editable = editable.intersection(shreds.get(hostNum).range); if (editable == null || editable.getLength() == 0) continue nextToken; range = new ProperTextRange(editable.getEndOffset(), range.getEndOffset()); PsiLanguageInjectionHost host = shreds.get(hostNum).host; LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = escapers.get(hostNum); TextRange rangeInsideHost = shreds.get(hostNum).getRangeInsideHost(); int prefixLength = shreds.get(hostNum).prefix.length(); int start = escaper.getOffsetInHost(editable.getStartOffset() - prevHostsCombinedLength - prefixLength, rangeInsideHost); int end = escaper.getOffsetInHost(editable.getEndOffset() - prevHostsCombinedLength - prefixLength, rangeInsideHost); if (end == -1) { end = rangeInsideHost.getEndOffset(); tokens.add(Trinity.<IElementType, PsiLanguageInjectionHost, TextRange>create(tokenType, host, new ProperTextRange(start, end))); prevHostsCombinedLength = shreds.get(hostNum).range.getEndOffset(); range = new ProperTextRange(shreds.get(hostNum).range.getEndOffset(), range.getEndOffset()); } else { TextRange rangeInHost = new ProperTextRange(start, end); tokens.add(Trinity.create(tokenType, host, rangeInHost)); } } } return tokens; } private static boolean isInjectedFragment(final PsiFile file) { return file.getViewProvider() instanceof MyFileViewProvider; } private static class Place { private final PsiFile myInjectedPsi; private final List<PsiLanguageInjectionHost.Shred> myShreds; public Place(PsiFile injectedPsi, List<PsiLanguageInjectionHost.Shred> shreds) { myShreds = shreds; myInjectedPsi = injectedPsi; } } private static interface Places extends List<Place> {} private static class PlacesImpl extends SmartList<Place> implements Places {} public static void enumerate(@NotNull PsiElement host, @NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) { PsiFile containingFile = host.getContainingFile(); enumerate(host, containingFile, visitor, true); } public static void enumerate(@NotNull PsiElement host, @NotNull PsiFile containingFile, @NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor, boolean probeUp) { //do not inject into nonphysical files except during completion if (!containingFile.isPhysical() && containingFile.getOriginalFile() == null) { final PsiElement context = containingFile.getContext(); if (context == null) return; final PsiFile file = context.getContainingFile(); if (file == null || !file.isPhysical() && file.getOriginalFile() == null) return; } Places places = probeElementsUp(host, containingFile, probeUp); if (places == null) return; for (Place place : places) { PsiFile injectedPsi = place.myInjectedPsi; List<PsiLanguageInjectionHost.Shred> pairs = place.myShreds; visitor.visit(injectedPsi, pairs); } } private static class MyFileViewProvider extends SingleRootFileViewProvider { private PsiLanguageInjectionHost[] myHosts; private Project myProject; private MyFileViewProvider(@NotNull Project project, @NotNull VirtualFileWindow virtualFile, List<PsiLanguageInjectionHost> hosts) { super(PsiManager.getInstance(project), (VirtualFile)virtualFile); myHosts = hosts.toArray(new PsiLanguageInjectionHost[hosts.size()]); myProject = myHosts[0].getProject(); } public void rootChanged(PsiFile psiFile) { super.rootChanged(psiFile); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getManager().getProject()); DocumentWindowImpl documentWindow = (DocumentWindowImpl)documentManager.getDocument(psiFile); String[] changes = documentWindow.calculateMinEditSequence(psiFile.getText()); RangeMarker[] hostRanges = documentWindow.getHostRanges(); assert changes.length == myHosts.length; for (int i = 0; i < myHosts.length; i++) { String change = changes[i]; if (change != null) { PsiLanguageInjectionHost host = myHosts[i]; RangeMarker hostRange = hostRanges[i]; TextRange hostTextRange = host.getTextRange(); TextRange rangeInsideHost = hostTextRange.intersection(toTextRange(hostRange)).shiftRight(-hostTextRange.getStartOffset()); String newHostText = StringUtil.replaceSubstring(host.getText(), rangeInsideHost, change); host.fixText(newHostText); } } } public FileViewProvider clone() { final FileViewProvider copy = super.clone(); final PsiFile psi = copy.getPsi(getBaseLanguage()); psi.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, getPsi(getBaseLanguage()).getUserData(FileContextUtil.INJECTED_IN_ELEMENT)); return copy; } @Nullable protected PsiFile getPsiInner(Language target) { // when FileManager rebuilds file map, all files temporarily become invalid, so this check is doomed PsiFile file = super.getPsiInner(target); //if (file == null || file.getContext() == null) return null; return file; } private void replace(PsiFile injectedPsi, List<PsiLanguageInjectionHost.Shred> shreds) { setVirtualFile(injectedPsi.getVirtualFile()); myHosts = new PsiLanguageInjectionHost[shreds.size()]; for (int i = 0; i < shreds.size(); i++) { PsiLanguageInjectionHost.Shred shred = shreds.get(i); myHosts[i] = shred.host; } myProject = myHosts[0].getProject(); } private boolean isValid() { return !myProject.isDisposed(); } } private static void patchLeafs(final ASTNode parsedNode, final List<LiteralTextEscaper<? extends PsiLanguageInjectionHost>> escapers, final List<PsiLanguageInjectionHost.Shred> shreds) { final Map<LeafElement, String> newTexts = new THashMap<LeafElement, String>(); final StringBuilder catLeafs = new StringBuilder(); ((TreeElement)parsedNode).acceptTree(new RecursiveTreeElementVisitor(){ int currentHostNum = -1; LeafElement prevElement; String prevElementTail; int prevHostsCombinedLength = 0; TextRange shredHostRange; TextRange rangeInsideHost; String hostText; PsiLanguageInjectionHost.Shred shred; { incHostNum(0); } protected boolean visitNode(TreeElement element) { return true; } @Override public void visitLeaf(LeafElement leaf) { String leafText = leaf.getText(); catLeafs.append(leafText); TextRange range = leaf.getTextRange(); int prefixLength; int startOffsetInHost; while (true) { prefixLength = shredHostRange.getStartOffset(); if (prefixLength > range.getStartOffset() && prefixLength < range.getEndOffset()) { //LOG.error("Prefix must not contain text that will be glued with the element body after parsing. " + // "However, parsed element of "+leaf.getClass()+" contains "+(prefixLength-range.getStartOffset()) + " characters from the prefix. " + // "Parsed text is '"+leaf.getText()+"'"); } if (range.getStartOffset() < shredHostRange.getEndOffset() && shredHostRange.getEndOffset() < range.getEndOffset()) { //LOG.error("Suffix must not contain text that will be glued with the element body after parsing. " + // "However, parsed element of "+leaf.getClass()+" contains "+(range.getEndOffset()-shredHostRange.getEndOffset()) + " characters from the suffix. " + // "Parsed text is '"+leaf.getText()+"'"); } int start = range.getStartOffset() - prevHostsCombinedLength; if (start < prefixLength) return; int end = range.getEndOffset() - prevHostsCombinedLength; if (end > shred.range.getEndOffset() - shred.suffix.length() && end <= shred.range.getEndOffset()) return; startOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(start - prefixLength, rangeInsideHost); if (startOffsetInHost == -1 || startOffsetInHost == rangeInsideHost.getEndOffset()) { // no way next leaf might stand more than one shred apart incHostNum(range.getStartOffset()); start = range.getStartOffset() - prevHostsCombinedLength; startOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(start - prefixLength, rangeInsideHost); assert startOffsetInHost != -1; } else break; } String leafEncodedText = ""; while (true) { if (range.getEndOffset() <= shred.range.getEndOffset()) { int end = range.getEndOffset() - prevHostsCombinedLength; if (end < prefixLength) { leafEncodedText += shred.prefix.substring(0, end); } else { int endOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(end - prefixLength, rangeInsideHost); assert endOffsetInHost != -1; leafEncodedText += hostText.substring(startOffsetInHost, endOffsetInHost); } break; } String rest = hostText.substring(startOffsetInHost, rangeInsideHost.getEndOffset()); leafEncodedText += rest; incHostNum(shred.range.getEndOffset()); startOffsetInHost = shred.getRangeInsideHost().getStartOffset(); prefixLength = shredHostRange.getStartOffset(); } if (leaf.getElementType() == TokenType.WHITE_SPACE && prevElementTail != null) { // optimization: put all garbage into whitespace leafEncodedText = prevElementTail + leafEncodedText; newTexts.remove(prevElement); storeUnescapedTextFor(prevElement, null); } if (!Comparing.strEqual(leafText, leafEncodedText)) { newTexts.put(leaf, leafEncodedText); storeUnescapedTextFor(leaf, leafText); } if (leafEncodedText.startsWith(leafText) && leafEncodedText.length() != leafText.length()) { prevElementTail = leafEncodedText.substring(leafText.length()); } else { prevElementTail = null; } prevElement = leaf; } private void incHostNum(int startOffset) { currentHostNum++; prevHostsCombinedLength = startOffset; shred = shreds.get(currentHostNum); shredHostRange = new ProperTextRange(TextRange.from(shred.prefix.length(), shred.getRangeInsideHost().getLength())); rangeInsideHost = shred.getRangeInsideHost(); hostText = shred.host.getText(); } }); String nodeText = parsedNode.getText(); assert nodeText.equals(catLeafs.toString()) : "Malformed PSI structure: leaf texts do not added up to the whole file text." + "\nFile text (from tree) :'"+nodeText+"'" + "\nFile text (from PSI) :'"+parsedNode.getPsi().getText()+"'" + "\nLeaf texts concatenated:'"+catLeafs+"';" + "\nFile root:"+parsedNode+ "\nlanguage="+parsedNode.getPsi().getLanguage(); for (LeafElement leaf : newTexts.keySet()) { String newText = newTexts.get(leaf); leaf.setText(newText); } ((TreeElement)parsedNode).acceptTree(new RecursiveTreeElementVisitor(){ protected boolean visitNode(TreeElement element) { element.clearCaches(); return true; } }); } private static void storeUnescapedTextFor(final LeafElement leaf, final String leafText) { PsiElement psi = leaf.getPsi(); if (psi != null) { psi.putUserData(InjectedLanguageManagerImpl.UNESCAPED_TEXT, leafText); } } public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable PsiFile file) { if (editor == null || file == null || editor instanceof EditorWindow) return editor; int offset = editor.getCaretModel().getOffset(); return getEditorForInjectedLanguageNoCommit(editor, file, offset); } public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable PsiFile file, final int offset) { if (editor == null || file == null || editor instanceof EditorWindow) return editor; PsiFile injectedFile = findInjectedPsiNoCommit(file, offset); return getInjectedEditorForInjectedFile(editor, injectedFile); } @NotNull public static Editor getInjectedEditorForInjectedFile(@NotNull Editor editor, final PsiFile injectedFile) { if (injectedFile == null || editor instanceof EditorWindow) return editor; Document document = PsiDocumentManager.getInstance(editor.getProject()).getDocument(injectedFile); if (!(document instanceof DocumentWindowImpl)) return editor; DocumentWindowImpl documentWindow = (DocumentWindowImpl)document; SelectionModel selectionModel = editor.getSelectionModel(); if (selectionModel.hasSelection()) { int selstart = selectionModel.getSelectionStart(); int selend = selectionModel.getSelectionEnd(); if (!documentWindow.containsRange(selstart, selend)) { // selection spreads out the injected editor range return editor; } } return EditorWindow.create(documentWindow, (EditorImpl)editor, injectedFile); } public static PsiFile findInjectedPsiNoCommit(@NotNull PsiFile host, int offset) { PsiElement injected = findInjectedElementNoCommit(host, offset); if (injected != null) { return injected.getContainingFile(); } return null; } // consider injected elements public static PsiElement findElementAtNoCommit(@NotNull PsiFile file, int offset) { if (!isInjectedFragment(file)) { PsiElement injected = findInjectedElementNoCommit(file, offset); if (injected != null) { return injected; } } //PsiElement at = file.findElementAt(offset); FileViewProvider viewProvider = file.getViewProvider(); return viewProvider.findElementAt(offset, viewProvider.getBaseLanguage()); } private static final InjectedPsiProvider INJECTED_PSI_PROVIDER = new InjectedPsiProvider(); private static Places probeElementsUp(@NotNull PsiElement element, @NotNull PsiFile hostPsiFile, boolean probeUp) { PsiManager psiManager = hostPsiFile.getManager(); final Project project = psiManager.getProject(); InjectedLanguageManagerImpl injectedManager = InjectedLanguageManagerImpl.getInstanceImpl(project); if (injectedManager == null) return null; //for tests for (PsiElement current = element; current != null && current != hostPsiFile; current = current.getParent()) { if ("EL".equals(current.getLanguage().getID())) break; ParameterizedCachedValue<Places,PsiElement> data = current.getUserData(INJECTED_PSI_KEY); if (data != null) { Places value = data.getValue(current); if (value != null) { return value; } } Places places = InjectedPsiProvider.doCompute(current, injectedManager, project, hostPsiFile); if (places != null) { ParameterizedCachedValue<Places,PsiElement> cachedValue = psiManager.getCachedValuesManager().createParameterizedCachedValue(INJECTED_PSI_PROVIDER, false); Document hostDocument = hostPsiFile.getViewProvider().getDocument(); CachedValueProvider.Result<Places> result = new CachedValueProvider.Result<Places>(places, PsiModificationTracker.MODIFICATION_COUNT, hostDocument); ((ParameterizedCachedValueImpl<Places,PsiElement>)cachedValue).setValue(result); for (Place place : places) { for (PsiLanguageInjectionHost.Shred pair : place.myShreds) { pair.host.putUserData(INJECTED_PSI_KEY, cachedValue); } } current.putUserData(INJECTED_PSI_KEY, cachedValue); return places; } if (!probeUp) break; } return null; } public static PsiElement findInjectedElementNoCommitWithOffset(@NotNull PsiFile file, final int offset) { return findInjectedElementNoCommit2(file, offset, true); } public static PsiElement findInjectedElementNoCommit(@NotNull PsiFile file, final int offset) { return findInjectedElementNoCommit2(file, offset, false); } private static PsiElement findInjectedElementNoCommit2(final PsiFile file, final int offset, boolean accuratelyPlease) { if (isInjectedFragment(file)) return null; final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject()); PsiElement element = file.getViewProvider().findElementAt(offset, file.getLanguage()); PsiElement inj = element == null ? null : findInside(element, file, offset, documentManager); if (inj != null) return inj; if (offset != 0 && !accuratelyPlease) { PsiElement element1 = file.findElementAt(offset - 1); if (element1 != element && element1 != null) return findInside(element1, file, offset, documentManager); } return null; } private static PsiElement findInside(@NotNull PsiElement element, @NotNull PsiFile file, final int offset, @NotNull final PsiDocumentManager documentManager) { final Ref<PsiElement> out = new Ref<PsiElement>(); enumerate(element, file, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { for (PsiLanguageInjectionHost.Shred place : places) { TextRange hostRange = place.host.getTextRange(); if (hostRange.cutOut(place.getRangeInsideHost()).grown(1).contains(offset)) { DocumentWindowImpl document = (DocumentWindowImpl)documentManager.getCachedDocument(injectedPsi); int injectedOffset = document.hostToInjected(offset); PsiElement injElement = injectedPsi.findElementAt(injectedOffset); out.set(injElement == null ? injectedPsi : injElement); } } } }, true); return out.get(); } private static class InjectedPsiProvider implements ParameterizedCachedValueProvider<Places, PsiElement> { public CachedValueProvider.Result<Places> compute(PsiElement element) { PsiFile hostPsiFile = element.getContainingFile(); if (hostPsiFile == null) return null; FileViewProvider viewProvider = hostPsiFile.getViewProvider(); final DocumentEx hostDocument = (DocumentEx)viewProvider.getDocument(); if (hostDocument == null) return null; PsiManager psiManager = viewProvider.getManager(); final Project project = psiManager.getProject(); InjectedLanguageManagerImpl injectedManager = InjectedLanguageManagerImpl.getInstanceImpl(project); if (injectedManager == null) return null; //for tests final Places result = doCompute(element, injectedManager, project, hostPsiFile); if (result == null) return null; return new CachedValueProvider.Result<Places>(result, PsiModificationTracker.MODIFICATION_COUNT, hostDocument); } @Nullable private static Places doCompute(final PsiElement element, InjectedLanguageManagerImpl injectedManager, Project project, PsiFile hostPsiFile) { MyInjProcessor processor = new MyInjProcessor(injectedManager, project, hostPsiFile); injectedManager.processInPlaceInjectorsFor(element, processor); return processor.hostRegistrar == null ? null : processor.hostRegistrar.result; } private static class MyInjProcessor implements InjectedLanguageManagerImpl.InjProcessor { private MyMultiHostRegistrar hostRegistrar; private final InjectedLanguageManagerImpl myInjectedManager; private final Project myProject; private final PsiFile myHostPsiFile; public MyInjProcessor(InjectedLanguageManagerImpl injectedManager, Project project, PsiFile hostPsiFile) { myInjectedManager = injectedManager; myProject = project; myHostPsiFile = hostPsiFile; } public boolean process(PsiElement element, MultiHostInjector injector) { if (hostRegistrar == null) { hostRegistrar = new MyMultiHostRegistrar(myProject, myInjectedManager, myHostPsiFile); } injector.getLanguagesToInject(hostRegistrar, element); return hostRegistrar.result == null; } } private static class MyMultiHostRegistrar implements MultiHostRegistrar { private Places result; private Language myLanguage; private List<TextRange> relevantRangesInHostDocument; private List<String> prefixes; private List<String> suffixes; private List<PsiLanguageInjectionHost> injectionHosts; private List<LiteralTextEscaper<? extends PsiLanguageInjectionHost>> escapers; private List<PsiLanguageInjectionHost.Shred> shreds; private StringBuilder outChars; boolean isOneLineEditor; boolean cleared; private final Project myProject; private final PsiManager myPsiManager; private DocumentEx myHostDocument; private VirtualFile myHostVirtualFile; private final InjectedLanguageManagerImpl myInjectedManager; private final PsiFile myHostPsiFile; public MyMultiHostRegistrar(Project project, InjectedLanguageManagerImpl injectedManager, PsiFile hostPsiFile) { myProject = project; myInjectedManager = injectedManager; myHostPsiFile = PsiUtilBase.getTemplateLanguageFile(hostPsiFile); myPsiManager = myHostPsiFile.getManager(); cleared = true; } @NotNull public MultiHostRegistrar startInjecting(@NotNull Language language) { relevantRangesInHostDocument = new SmartList<TextRange>(); prefixes = new SmartList<String>(); suffixes = new SmartList<String>(); injectionHosts = new SmartList<PsiLanguageInjectionHost>(); escapers = new SmartList<LiteralTextEscaper<? extends PsiLanguageInjectionHost>>(); shreds = new SmartList<PsiLanguageInjectionHost.Shred>(); outChars = new StringBuilder(); if (!cleared) { clear(); throw new IllegalStateException("Seems you haven't called doneInjecting()"); } if (LanguageParserDefinitions.INSTANCE.forLanguage(language) == null) { throw new UnsupportedOperationException("Cannot inject language '" + language + "' since its getParserDefinition() returns null"); } myLanguage = language; FileViewProvider viewProvider = myHostPsiFile.getViewProvider(); myHostVirtualFile = viewProvider.getVirtualFile(); myHostDocument = (DocumentEx)viewProvider.getDocument(); assert myHostDocument != null : myHostPsiFile + "; " + viewProvider; return this; } private void clear() { relevantRangesInHostDocument.clear(); prefixes.clear(); suffixes.clear(); injectionHosts.clear(); escapers.clear(); shreds.clear(); outChars.setLength(0); isOneLineEditor = false; myLanguage = null; cleared = true; } @NotNull public MultiHostRegistrar addPlace(@NonNls @Nullable String prefix, @NonNls @Nullable String suffix, @NotNull PsiLanguageInjectionHost host, @NotNull TextRange rangeInsideHost) { ProperTextRange.assertProperRange(rangeInsideHost); PsiFile containingFile = PsiUtilBase.getTemplateLanguageFile(host); assert containingFile == myHostPsiFile : "Trying to inject into foreign file: "+containingFile+" while processing injections for "+myHostPsiFile; TextRange hostTextRange = host.getTextRange(); if (!hostTextRange.contains(rangeInsideHost.shiftRight(hostTextRange.getStartOffset()))) { clear(); throw new IllegalArgumentException("rangeInsideHost must lie within host text range. rangeInsideHost:"+rangeInsideHost+"; host textRange:"+ hostTextRange); } if (myLanguage == null) { clear(); throw new IllegalStateException("Seems you haven't called startInjecting()"); } if (prefix == null) prefix = ""; if (suffix == null) suffix = ""; prefixes.add(prefix); suffixes.add(suffix); cleared = false; injectionHosts.add(host); outChars.append(prefix); LiteralTextEscaper<? extends PsiLanguageInjectionHost> textEscaper = host.createLiteralTextEscaper(); escapers.add(textEscaper); isOneLineEditor |= textEscaper.isOneLine(); TextRange relevantRange = textEscaper.getRelevantTextRange().intersection(rangeInsideHost); int startOffset = outChars.length(); if (relevantRange == null) { relevantRange = TextRange.from(textEscaper.getRelevantTextRange().getStartOffset(), 0); } else { boolean result = textEscaper.decode(relevantRange, outChars); if (!result) { // if there are invalid chars, adjust the range int offsetInHost = textEscaper.getOffsetInHost(outChars.length() - startOffset, rangeInsideHost); relevantRange = relevantRange.intersection(new TextRange(0, offsetInHost)); } } outChars.append(suffix); int endOffset = outChars.length(); TextRange relevantRangeInHost = relevantRange.shiftRight(hostTextRange.getStartOffset()); relevantRangesInHostDocument.add(relevantRangeInHost); RangeMarker relevantMarker = myHostDocument.createRangeMarker(relevantRangeInHost); relevantMarker.setGreedyToLeft(true); relevantMarker.setGreedyToRight(true); shreds.add(new PsiLanguageInjectionHost.Shred(host, relevantMarker, prefix, suffix, new ProperTextRange(startOffset, endOffset))); return this; } public void doneInjecting() { try { if (shreds.isEmpty()) { throw new IllegalStateException("Seems you haven't called addPlace()"); } PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); assert ArrayUtil.indexOf(documentManager.getUncommittedDocuments(), myHostDocument) == -1; assert myHostPsiFile.getText().equals(myHostDocument.getText()); DocumentWindowImpl documentWindow = new DocumentWindowImpl(myHostDocument, isOneLineEditor, prefixes, suffixes, relevantRangesInHostDocument); VirtualFileWindowImpl virtualFile = (VirtualFileWindowImpl)myInjectedManager.createVirtualFile(myLanguage, myHostVirtualFile, documentWindow, outChars); myLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(myLanguage, virtualFile, myProject); virtualFile.setLanguage(myLanguage); DocumentImpl decodedDocument = new DocumentImpl(outChars); FileDocumentManagerImpl.registerDocument(decodedDocument, virtualFile); SingleRootFileViewProvider viewProvider = new MyFileViewProvider(myProject, virtualFile, injectionHosts); ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(myLanguage); assert parserDefinition != null; PsiFile psiFile = parserDefinition.createFile(viewProvider); assert isInjectedFragment(psiFile) : psiFile.getViewProvider(); SmartPsiElementPointer<PsiLanguageInjectionHost> pointer = createHostSmartPointer(injectionHosts.get(0)); psiFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, pointer); final ASTNode parsedNode = psiFile.getNode(); assert parsedNode instanceof FileElement : parsedNode; String documentText = documentWindow.getText(); assert outChars.toString().equals(parsedNode.getText()) : "Before patch: doc:\n" + documentText + "\n---PSI:\n" + parsedNode.getText() + "\n---chars:\n"+outChars; try { patchLeafs(parsedNode, escapers, shreds); } catch (ProcessCanceledException e) { throw e; } catch (RuntimeException e) { throw new RuntimeException("Patch error, lang="+myLanguage+";\n "+myHostVirtualFile+"; places:"+injectionHosts+";\n ranges:"+relevantRangesInHostDocument, e); } assert parsedNode.getText().equals(documentText) : "After patch: doc:\n" + documentText + "\n---PSI:\n" + parsedNode.getText() + "\n---chars:\n"+outChars; ((FileElement)parsedNode).setManager((PsiManagerEx)myPsiManager); virtualFile.setContent(null, documentWindow.getText(), false); FileDocumentManagerImpl.registerDocument(documentWindow, virtualFile); synchronized (PsiLock.LOCK) { psiFile = registerDocument(documentWindow, psiFile, shreds, myHostPsiFile, documentManager); MyFileViewProvider myFileViewProvider = (MyFileViewProvider)psiFile.getViewProvider(); myFileViewProvider.setVirtualFile(virtualFile); myFileViewProvider.forceCachedPsi(psiFile); } List<Trinity<IElementType, PsiLanguageInjectionHost, TextRange>> tokens = obtainHighlightTokensFromLexer(myLanguage, outChars, escapers, shreds, virtualFile, documentWindow, myProject); psiFile.putUserData(HIGHLIGHT_TOKENS, tokens); PsiDocumentManagerImpl.checkConsistency(psiFile, documentWindow); Place place = new Place(psiFile, new ArrayList<PsiLanguageInjectionHost.Shred>(shreds)); if (result == null) { result = new PlacesImpl(); } result.add(place); } finally { clear(); } } } } private static <T extends PsiLanguageInjectionHost> SmartPsiElementPointer<T> createHostSmartPointer(final T host) { return host.isPhysical() ? SmartPointerManager.getInstance(host.getProject()).createSmartPsiElementPointer(host) : new SmartPsiElementPointer<T>() { public T getElement() { return host; } public PsiFile getContainingFile() { return host.getContainingFile(); } }; } private static final Key<List<DocumentWindow>> INJECTED_DOCS_KEY = Key.create("INJECTED_DOCS_KEY"); private static final Key<List<RangeMarker>> INJECTED_REGIONS_KEY = Key.create("INJECTED_REGIONS_KEY"); @NotNull public static List<DocumentWindow> getCachedInjectedDocuments(@NotNull PsiFile hostPsiFile) { List<DocumentWindow> injected = hostPsiFile.getUserData(INJECTED_DOCS_KEY); if (injected == null) { injected = ((UserDataHolderEx)hostPsiFile).putUserDataIfAbsent(INJECTED_DOCS_KEY, new CopyOnWriteArrayList<DocumentWindow>()); } return injected; } public static void commitAllInjectedDocuments(Document hostDocument, Project project) { List<RangeMarker> injected = getCachedInjectedRegions(hostDocument); if (injected.isEmpty()) return; PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); PsiFile hostPsiFile = documentManager.getPsiFile(hostDocument); assert hostPsiFile != null; for (RangeMarker rangeMarker : injected) { PsiElement element = rangeMarker.isValid() ? hostPsiFile.findElementAt(rangeMarker.getStartOffset()) : null; if (element == null) { injected.remove(rangeMarker); continue; } // it is here reparse happens and old file contents replaced enumerate(element, hostPsiFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { PsiDocumentManagerImpl.checkConsistency(injectedPsi, injectedPsi.getViewProvider().getDocument()); } }, true); } PsiDocumentManagerImpl.checkConsistency(hostPsiFile, hostDocument); } public static void clearCaches(PsiFile injected) { VirtualFileWindow virtualFile = (VirtualFileWindow)injected.getVirtualFile(); PsiManagerEx psiManagerEx = (PsiManagerEx)injected.getManager(); psiManagerEx.getFileManager().setViewProvider((VirtualFile)virtualFile, null); Project project = psiManagerEx.getProject(); if (!project.isDisposed()) { InjectedLanguageManagerImpl.getInstanceImpl(project).clearCaches(virtualFile); } } private static PsiFile registerDocument(final DocumentWindowImpl documentWindow, final PsiFile injectedPsi, List<PsiLanguageInjectionHost.Shred> shreds, final PsiFile hostPsiFile, PsiDocumentManager documentManager) { DocumentEx hostDocument = documentWindow.getDelegate(); List<DocumentWindow> injected = getCachedInjectedDocuments(hostPsiFile); for (int i = injected.size()-1; i>=0; i--) { DocumentWindowImpl oldDocument = (DocumentWindowImpl)injected.get(i); PsiFileImpl oldFile = (PsiFileImpl)documentManager.getCachedPsiFile(oldDocument); FileViewProvider oldViewProvider; if (oldFile == null || !oldFile.isValid() || !((oldViewProvider = oldFile.getViewProvider()) instanceof MyFileViewProvider) || !((MyFileViewProvider)oldViewProvider).isValid()) { injected.remove(i); oldDocument.dispose(); continue; } ASTNode injectedNode = injectedPsi.getNode(); ASTNode oldFileNode = oldFile.getNode(); assert injectedNode != null; assert oldFileNode != null; if (oldDocument.areRangesEqual(documentWindow)) { if (oldFile.getFileType() != injectedPsi.getFileType() || oldFile.getLanguage() != injectedPsi.getLanguage()) { injected.remove(i); oldDocument.dispose(); continue; } oldFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, injectedPsi.getUserData(FileContextUtil.INJECTED_IN_ELEMENT)); if (!injectedNode.getText().equals(oldFileNode.getText())) { // replace psi FileElement newFileElement = (FileElement)injectedNode; FileElement oldFileElement = oldFile.getTreeElement(); if (oldFileElement.getFirstChildNode() != null) { TreeUtil.removeRange(oldFileElement.getFirstChildNode(), null); } final ASTNode firstChildNode = newFileElement.getFirstChildNode(); if (firstChildNode != null) { TreeUtil.addChildren(oldFileElement, (TreeElement)firstChildNode); } oldFileElement.setCharTable(newFileElement.getCharTable()); FileDocumentManagerImpl.registerDocument(documentWindow, oldFile.getVirtualFile()); oldFile.subtreeChanged(); MyFileViewProvider viewProvider = (MyFileViewProvider)oldViewProvider; viewProvider.replace(injectedPsi, shreds); } return oldFile; } } injected.add(documentWindow); List<RangeMarker> injectedRegions = getCachedInjectedRegions(hostDocument); RangeMarker newMarker = documentWindow.getHostRanges()[0]; TextRange newRange = toTextRange(newMarker); for (int i = 0; i < injectedRegions.size(); i++) { RangeMarker stored = injectedRegions.get(i); TextRange storedRange = toTextRange(stored); if (storedRange.intersects(newRange)) { injectedRegions.set(i, newMarker); break; } if (storedRange.getStartOffset() > newRange.getEndOffset()) { injectedRegions.add(i, newMarker); break; } } if (injectedRegions.isEmpty() || newRange.getStartOffset() > injectedRegions.get(injectedRegions.size()-1).getEndOffset()) { injectedRegions.add(newMarker); } return injectedPsi; } private static List<RangeMarker> getCachedInjectedRegions(Document hostDocument) { List<RangeMarker> injectedRegions = hostDocument.getUserData(INJECTED_REGIONS_KEY); if (injectedRegions == null) { injectedRegions = ((UserDataHolderEx)hostDocument).putUserDataIfAbsent(INJECTED_REGIONS_KEY, new CopyOnWriteArrayList<RangeMarker>()); } return injectedRegions; } public static Editor openEditorFor(PsiFile file, Project project) { Document document = PsiDocumentManager.getInstance(project).getDocument(file); // may return editor injected in current selection in the host editor, not for the file passed as argument VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { return null; } if (virtualFile instanceof VirtualFileWindow) { virtualFile = ((VirtualFileWindow)virtualFile).getDelegate(); } Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile, -1), false); if (editor == null || editor instanceof EditorWindow) return editor; if (document instanceof DocumentWindowImpl) { return EditorWindow.create((DocumentWindowImpl)document, (EditorImpl)editor, file); } return editor; } public static PsiFile getTopLevelFile(PsiElement element) { PsiFile containingFile = element.getContainingFile(); Document document = PsiDocumentManager.getInstance(element.getProject()).getCachedDocument(containingFile); if (document instanceof DocumentWindow) { PsiElement host = containingFile.getContext(); if (host != null) containingFile = host.getContainingFile(); } return containingFile; } public static boolean isInInjectedLanguagePrefixSuffix(final PsiElement element) { PsiFile injectedFile = element.getContainingFile(); if (injectedFile == null) return false; Document document = PsiDocumentManager.getInstance(element.getProject()).getCachedDocument(injectedFile); if (!(document instanceof DocumentWindowImpl)) return false; DocumentWindowImpl documentWindow = (DocumentWindowImpl)document; TextRange elementRange = element.getTextRange(); TextRange editable = documentWindow.intersectWithEditable(elementRange); return !elementRange.equals(editable); //) throw new IncorrectOperationException("Can't change "+ UsageViewUtil.createNodeText(element, true)); } public static boolean isSelectionIsAboutToOverflowInjectedFragment(EditorWindow injectedEditor) { int selStart = injectedEditor.getSelectionModel().getSelectionStart(); int selEnd = injectedEditor.getSelectionModel().getSelectionEnd(); DocumentWindow document = injectedEditor.getDocument(); boolean isStartOverflows = selStart == 0; if (!isStartOverflows) { int hostPrev = document.injectedToHost(selStart - 1); isStartOverflows = document.hostToInjected(hostPrev) == selStart; } boolean isEndOverflows = selEnd == document.getTextLength(); if (!isEndOverflows) { int hostNext = document.injectedToHost(selEnd + 1); isEndOverflows = document.hostToInjected(hostNext) == selEnd; } return isStartOverflows && isEndOverflows; } }
exception haunting INSPECTIONS fixed
lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java
exception haunting INSPECTIONS fixed
<ide><path>ang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java <ide> int currentHostNum = -1; <ide> LeafElement prevElement; <ide> String prevElementTail; <del> int prevHostsCombinedLength = 0; <add> int prevHostsCombinedLength; <ide> TextRange shredHostRange; <ide> TextRange rangeInsideHost; <ide> String hostText; <ide> PsiLanguageInjectionHost.Shred shred; <add> int prefixLength; <ide> { <ide> incHostNum(0); <ide> } <ide> String leafText = leaf.getText(); <ide> catLeafs.append(leafText); <ide> TextRange range = leaf.getTextRange(); <del> int prefixLength; <ide> int startOffsetInHost; <ide> while (true) { <del> prefixLength = shredHostRange.getStartOffset(); <ide> if (prefixLength > range.getStartOffset() && prefixLength < range.getEndOffset()) { <ide> //LOG.error("Prefix must not contain text that will be glued with the element body after parsing. " + <ide> // "However, parsed element of "+leaf.getClass()+" contains "+(prefixLength-range.getStartOffset()) + " characters from the prefix. " + <ide> <ide> int start = range.getStartOffset() - prevHostsCombinedLength; <ide> if (start < prefixLength) return; <del> int end = range.getEndOffset() - prevHostsCombinedLength; <add> int end = range.getEndOffset(); <ide> if (end > shred.range.getEndOffset() - shred.suffix.length() && end <= shred.range.getEndOffset()) return; <ide> startOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(start - prefixLength, rangeInsideHost); <ide> <del> if (startOffsetInHost == -1 || startOffsetInHost == rangeInsideHost.getEndOffset()) { <del> // no way next leaf might stand more than one shred apart <del> incHostNum(range.getStartOffset()); <del> start = range.getStartOffset() - prevHostsCombinedLength; <del> startOffsetInHost = escapers.get(currentHostNum).getOffsetInHost(start - prefixLength, rangeInsideHost); <del> assert startOffsetInHost != -1; <del> } <del> else break; <add> if (startOffsetInHost != -1 && startOffsetInHost != rangeInsideHost.getEndOffset()) { <add> break; <add> } <add> // no way next leaf might stand more than one shred apart <add> incHostNum(range.getStartOffset()); <ide> } <ide> String leafEncodedText = ""; <ide> while (true) { <ide> leafEncodedText += rest; <ide> incHostNum(shred.range.getEndOffset()); <ide> startOffsetInHost = shred.getRangeInsideHost().getStartOffset(); <del> prefixLength = shredHostRange.getStartOffset(); <ide> } <ide> <ide> if (leaf.getElementType() == TokenType.WHITE_SPACE && prevElementTail != null) { <ide> shredHostRange = new ProperTextRange(TextRange.from(shred.prefix.length(), shred.getRangeInsideHost().getLength())); <ide> rangeInsideHost = shred.getRangeInsideHost(); <ide> hostText = shred.host.getText(); <add> prefixLength = shredHostRange.getStartOffset(); <ide> } <ide> }); <ide> <ide> String nodeText = parsedNode.getText(); <del> assert nodeText.equals(catLeafs.toString()) : "Malformed PSI structure: leaf texts do not added up to the whole file text." + <add> assert nodeText.equals(catLeafs.toString()) : "Malformed PSI structure: leaf texts do not add up to the whole file text." + <ide> "\nFile text (from tree) :'"+nodeText+"'" + <ide> "\nFile text (from PSI) :'"+parsedNode.getPsi().getText()+"'" + <ide> "\nLeaf texts concatenated:'"+catLeafs+"';" + <del> "\nFile root:"+parsedNode+ <del> "\nlanguage="+parsedNode.getPsi().getLanguage(); <add> "\nFile root: "+parsedNode+ <add> "\nLanguage: "+parsedNode.getPsi().getLanguage()+ <add> "\nHost file: "+shreds.get(0).host.getContainingFile().getVirtualFile() <add> ; <ide> for (LeafElement leaf : newTexts.keySet()) { <ide> String newText = newTexts.get(leaf); <ide> leaf.setText(newText); <ide> } <ide> <ide> public static PsiElement findInjectedElementNoCommitWithOffset(@NotNull PsiFile file, final int offset) { <del> return findInjectedElementNoCommit2(file, offset, true); <del> } <del> <del> public static PsiElement findInjectedElementNoCommit(@NotNull PsiFile file, final int offset) { <del> return findInjectedElementNoCommit2(file, offset, false); <del> } <del> <del> private static PsiElement findInjectedElementNoCommit2(final PsiFile file, final int offset, boolean accuratelyPlease) { <ide> if (isInjectedFragment(file)) return null; <ide> final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject()); <ide> <ide> PsiElement element = file.getViewProvider().findElementAt(offset, file.getLanguage()); <del> PsiElement inj = element == null ? null : findInside(element, file, offset, documentManager); <add> return element == null ? null : findInside(element, file, offset, documentManager); <add> } <add> <add> public static PsiElement findInjectedElementNoCommit(@NotNull PsiFile file, final int offset) { <add> PsiElement inj = findInjectedElementNoCommitWithOffset(file, offset); <ide> if (inj != null) return inj; <del> <del> if (offset != 0 && !accuratelyPlease) { <del> PsiElement element1 = file.findElementAt(offset - 1); <del> if (element1 != element && element1 != null) return findInside(element1, file, offset, documentManager); <del> } <del> <del> return null; <add> if (offset != 0) { <add> inj = findInjectedElementNoCommitWithOffset(file, offset - 1); <add> } <add> return inj; <ide> } <ide> <ide> private static PsiElement findInside(@NotNull PsiElement element, @NotNull PsiFile file, final int offset, @NotNull final PsiDocumentManager documentManager) { <ide> suffixes.add(suffix); <ide> cleared = false; <ide> injectionHosts.add(host); <add> int startOffset = outChars.length(); <ide> outChars.append(prefix); <ide> LiteralTextEscaper<? extends PsiLanguageInjectionHost> textEscaper = host.createLiteralTextEscaper(); <ide> escapers.add(textEscaper); <ide> isOneLineEditor |= textEscaper.isOneLine(); <ide> TextRange relevantRange = textEscaper.getRelevantTextRange().intersection(rangeInsideHost); <del> int startOffset = outChars.length(); <ide> if (relevantRange == null) { <ide> relevantRange = TextRange.from(textEscaper.getRelevantTextRange().getStartOffset(), 0); <ide> }
Java
mit
6971bf9adf48281b075e75350581378211f3d8a2
0
parkm/SignDoctor
package signeditor; import java.util.*; import java.util.regex.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.command.*; import org.bukkit.configuration.file.*; import org.bukkit.entity.*; import org.bukkit.event.block.*; import org.bukkit.metadata.*; import org.bukkit.plugin.*; import org.bukkit.plugin.java.*; /** * Sign Editor Plugin Class. * * @author Parker Miller * */ public class SignEditor extends JavaPlugin { public static Plugin plugin; //Metadata keys public static final String SIGN_EDIT = "SignEditor_editSign"; public static final String SIGN = "SignEditor_activeSign"; public static final String SIGN_LINES = "SignEditor_signLinesArray"; public static final String PREV_LOCATION = "SignEditor_previousLocation"; //Messages public static final String MSG_EDIT_DISABLED = "Sign editing is not enabled. To enable, use the command: toggleSignEdit"; public static final String MSG_NO_ACTIVE_SIGN = "No sign is active."; public static final String PERM_EDIT = "signediting"; public static FileConfiguration config; public static boolean enableEditing = false; public static String spacingStr = "_"; public static String blankStr = "\\n"; public static String selectorItem = "FEATHER"; public static boolean noSelector = false; @Override public void onEnable() { plugin = this; config = this.getConfig(); enableEditing = config.getBoolean("enableEditingByDefault"); spacingStr = config.getString("spacingStr"); blankStr = config.getString("blankStr"); selectorItem = config.getString("selectorItem").toUpperCase(); noSelector = (selectorItem.isEmpty() || selectorItem.equalsIgnoreCase("NULL")); getServer().getPluginManager().registerEvents(new SignEditorEvents(), this); } @Override public void onDisable() { } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof Player) { Player p = (Player) sender; boolean editing = (boolean) getMetadata(p, SIGN_EDIT, this); Sign sign = (Sign) getMetadata(p, SignEditor.SIGN, this); if (!p.hasPermission(PERM_EDIT)) { say(p, "You do not have permission to edit signs."); return true; } //tpToSign command if (cmd.getName().equalsIgnoreCase("tpToSign")) { if (sign != null) { p.setMetadata(PREV_LOCATION, new FixedMetadataValue(this, p.getLocation())); p.teleport(sign.getLocation()); } else { say(p, MSG_NO_ACTIVE_SIGN); } return true; } //tpBackFromSign command if (cmd.getName().equalsIgnoreCase("tpBackFromSign")) { Location previousLocation = (Location) getMetadata(p, PREV_LOCATION, this); if (previousLocation != null) { p.teleport(previousLocation); } else { say(p, "No location has been logged. You must first use 'tpToSign'."); } return true; } if (editing) { if (sign != null) { try { //Toggle sign edit command. if (cmd.getName().equalsIgnoreCase("toggleSignEdit")) { setEditing(p, !editing); say(p, !editing ? "Editing has been enabled." : "Editing has been disabled."); return true; } //Edit sign command. if (cmd.getName().equalsIgnoreCase("editSign")) { editSign(sign, args); updateSign(p, sign); return true; } //Edit sign line command. if (cmd.getName().equalsIgnoreCase("editSignln")) { if (args.length < 1) return false; int line = Integer.parseInt(args[0]) - 1; editSignln(sign, line, Arrays.copyOfRange(args, 1, args.length)); updateSign(p, sign); return true; } //appendToSign command if (cmd.getName().equalsIgnoreCase("appendToSign")) { if (args.length < 2) return false; int line = Integer.parseInt(args[0]) - 1; appendToSign(sign, line, Arrays.copyOfRange(args, 1, args.length)); updateSign(p, sign); return true; } //replaceln command if (cmd.getName().equalsIgnoreCase("replaceln")) { if (args.length < 3) return false; boolean replaceAll = false; int line = Integer.parseInt(args[0]) - 1; if (args.length >= 4) { replaceAll = Boolean.parseBoolean(args[3]); } try { replaceln(sign, line, args[1], args[2], replaceAll); } catch (PatternSyntaxException e) { say(p, "Regex syntax is incorrect."); return true; } updateSign(p, sign); return true; } //switchln command if (cmd.getName().equalsIgnoreCase("switchln")) { if (args.length < 2) { return false; } int lineTargetNum = Integer.parseInt(args[0]) - 1; int lineDestNum = Integer.parseInt(args[1]) - 1; switchln(sign, lineTargetNum, lineDestNum); updateSign(p, sign); return true; } //Clear sign command. if (cmd.getName().equalsIgnoreCase("clearSign")) { clearSign(sign); updateSign(p, sign); return true; } //Copy sign command. if (cmd.getName().equalsIgnoreCase("copySign")) { copySign(p, sign); say(p, "Sign has been copied."); return true; } //Cut sign command. if (cmd.getName().equalsIgnoreCase("cutSign")) { copySign(p, sign); clearSign(sign); updateSign(p, sign); say(p, "Sign has been cut."); return true; } //Paste sign command. if (cmd.getName().equalsIgnoreCase("pasteSign")) { pasteSign(sign, (String[]) getMetadata(p, SIGN_LINES, this)); updateSign(p, sign); return true; } } catch (NumberFormatException e) { return false; } catch (InvalidLineException e) { say(p, e.getMessage()); return true; } } else { say(p, MSG_NO_ACTIVE_SIGN); return true; } } else { say(p, MSG_EDIT_DISABLED); return true; } } else { sender.sendMessage("Sign Editor: You must be a player for this to work."); return true; } return false; } public static void setEditing(Player p, boolean val) { p.setMetadata(SIGN_EDIT, new FixedMetadataValue(plugin, val)); } public static boolean isEditing(Player p) { return (boolean) getMetadata(p, SIGN_EDIT, plugin); } /** * Copies a sign and stores it into the player's clipboard. * * @param p * @param s */ public static void copySign(Player p, Sign s) { String[] sl = new String[4]; for (int i = 0; i < sl.length; i++) { sl[i] = s.getLine(i); } p.setMetadata(SIGN_LINES, new FixedMetadataValue(plugin, sl)); } public static void clearSign(Sign s) { for (int i = 0; i < 4; ++i) { s.setLine(i, ""); } } public static void pasteSign(Sign s, String lines[]) { for (int i = 0; i < lines.length; i++) { s.setLine(i, lines[i]); } } /** * Checks if a integer is a valid line number. (0-3) * * @param line The line number you want to check, starting from 0 ending at 3. * @return */ public static boolean isValidLine(int line) { return (line >= 0 && line <= 3); } /** * Merges an array of strings into one string. It also formats it to use spacingStr and spaces after each element. * * @param args * @return The merged string */ public static String mergeStrings(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; ++i) { Bukkit.getServer().getLogger().info(args[i]); sb.append(args[i]); //Add a space if it is not the last element. if (i < args.length - 1) sb.append(" "); } return sb.toString().replaceAll(spacingStr, " "); } /** * Updates a sign and calls a SignChangeEvent. * * @param p The player who updated the sign. * @param s The sign you want to update. */ public static void updateSign(Player p, Sign s) { //The first update is used to change the text of the sign just in case the SignChangeEvent blocks it. This is used mostly to support Lockette. s.update(); Bukkit.getServer().getPluginManager().callEvent(new SignChangeEvent(s.getBlock(), p, s.getLines())); //We must update again after the SignChangeEvent for colors to work. This also allows other plugins to be compatible. s.update(); } public static void say(Player p, String s) { p.sendMessage(ChatColor.GOLD + "[Sign Editor] " + ChatColor.WHITE + s); } public static void editSign(Sign s, String lines[]) { for (int i = 0; i < Math.min(lines.length, 4); ++i) { if (!lines[i].equals(blankStr)) { String text = lines[i].replaceAll(spacingStr, " "); s.setLine(i, text); } } } public static void editSignln(Sign s, int line, String args[]) throws InvalidLineException { if (isValidLine(line)) { String mergedStr = mergeStrings(args); s.setLine(line, mergedStr); } else { throw new InvalidLineException(); } } public static void appendToSign(Sign s, int line, String args[]) throws InvalidLineException { if (isValidLine(line)) { String lineText = s.getLine(line); String appendText = mergeStrings(args); s.setLine(line, lineText + appendText); } else { throw new InvalidLineException(); } } public static void replaceln(Sign s, int line, String regex, String replacement, boolean replaceAll) throws InvalidLineException, PatternSyntaxException { if (isValidLine(line)) { String lineText = s.getLine(line); regex = regex.replaceAll(spacingStr, " "); if (replaceAll) { lineText = lineText.replaceAll(regex, replacement); } else { lineText = lineText.replaceFirst(regex, replacement); } s.setLine(line, lineText); } else { throw new InvalidLineException(); } } public static void switchln(Sign s, int lineTargetNum, int lineDestNum) throws InvalidLineException { if (isValidLine(lineTargetNum) && isValidLine(lineDestNum)) { String lineTarget = s.getLine(lineTargetNum); String lineDest = s.getLine(lineDestNum); s.setLine(lineDestNum, lineTarget); s.setLine(lineTargetNum, lineDest); } else { throw new InvalidLineException(); } } public static Object getMetadata(Player player, String key, Plugin plugin) { List<MetadataValue> values = player.getMetadata(key); for (MetadataValue value : values) { if (value.getOwningPlugin().getDescription().getName().equals(plugin.getDescription().getName())) { return value.value(); } } return null; } }
src/signeditor/SignEditor.java
package signeditor; import java.util.*; import java.util.regex.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.command.*; import org.bukkit.configuration.file.*; import org.bukkit.entity.*; import org.bukkit.event.block.*; import org.bukkit.metadata.*; import org.bukkit.plugin.*; import org.bukkit.plugin.java.*; /** * Sign Editor Plugin Class. * * @author Parker Miller * */ public class SignEditor extends JavaPlugin { public static Plugin plugin; //Metadata keys public static final String SIGN_EDIT = "SignEditor_editSign"; public static final String SIGN = "SignEditor_activeSign"; public static final String SIGN_LINES = "SignEditor_signLinesArray"; public static final String PREV_LOCATION = "SignEditor_previousLocation"; //Messages public static final String MSG_EDIT_DISABLED = "Sign editing is not enabled. To enable, use the command: toggleSignEdit"; public static final String MSG_NO_ACTIVE_SIGN = "No sign is active."; public static final String PERM_EDIT = "signediting"; public static FileConfiguration config; public static boolean enableEditing = false; public static String spacingStr = "_"; public static String blankStr = "\\n"; public static String selectorItem = "FEATHER"; public static boolean noSelector = false; @Override public void onEnable() { plugin = this; config = this.getConfig(); enableEditing = config.getBoolean("enableEditingByDefault"); spacingStr = config.getString("spacingStr"); blankStr = config.getString("blankStr"); selectorItem = config.getString("selectorItem").toUpperCase(); noSelector = (selectorItem.isEmpty() || selectorItem.equalsIgnoreCase("NULL")); getServer().getPluginManager().registerEvents(new SignEditorEvents(), this); } @Override public void onDisable() { } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof Player) { Player p = (Player) sender; boolean editing = (boolean) getMetadata(p, SIGN_EDIT, this); Sign sign = (Sign) getMetadata(p, SignEditor.SIGN, this); if (!p.hasPermission(PERM_EDIT)) { say(p, "You do not have permission to edit signs."); return true; } //tpToSign command if (cmd.getName().equalsIgnoreCase("tpToSign")) { if (sign != null) { p.setMetadata(PREV_LOCATION, new FixedMetadataValue(this, p.getLocation())); p.teleport(sign.getLocation()); } else { say(p, MSG_NO_ACTIVE_SIGN); } return true; } //tpBackFromSign command if (cmd.getName().equalsIgnoreCase("tpBackFromSign")) { Location previousLocation = (Location) getMetadata(p, PREV_LOCATION, this); if (previousLocation != null) { p.teleport(previousLocation); } else { say(p, "No location has been logged. You must first use 'tpToSign'."); } return true; } if (editing) { if (sign != null) { //Toggle sign edit command. if (cmd.getName().equalsIgnoreCase("toggleSignEdit")) { setEditing(p, !editing); say(p, !editing ? "Editing has been enabled." : "Editing has been disabled."); return true; } //Edit sign command. if (cmd.getName().equalsIgnoreCase("editSign")) { editSign(sign, args); updateSign(p, sign); return true; } //Edit sign line command. if (cmd.getName().equalsIgnoreCase("editSignln")) { if (args.length < 1) return false; try { int line = Integer.parseInt(args[0]) - 1; editSignln(sign, line, Arrays.copyOfRange(args, 1, args.length)); updateSign(p, sign); return true; } catch (NumberFormatException e) { return false; } catch (InvalidLineException e) { say(p, e.getMessage()); return true; } } //appendToSign command if (cmd.getName().equalsIgnoreCase("appendToSign")) { if (args.length < 2) return false; try { int line = Integer.parseInt(args[0]) - 1; appendToSign(sign, line, Arrays.copyOfRange(args, 1, args.length)); updateSign(p, sign); return true; } catch (NumberFormatException e) { return false; } catch (InvalidLineException e) { say(p, e.getMessage()); return true; } } //replaceln command if (cmd.getName().equalsIgnoreCase("replaceln")) { if (args.length < 3) return false; int line = 0; boolean replaceAll = false; try { line = Integer.parseInt(args[0]) - 1; if (args.length >= 4) { replaceAll = Boolean.parseBoolean(args[3]); } } catch (NumberFormatException e) { return false; } try { replaceln(sign, line, args[1], args[2], replaceAll); } catch (PatternSyntaxException e) { say(p, "Regex syntax is incorrect."); return true; } catch (InvalidLineException e) { say(p, e.getMessage()); return true; } updateSign(p, sign); return true; } //switchln command if (cmd.getName().equalsIgnoreCase("switchln")) { if (args.length < 2) { return false; } try { int lineTargetNum = Integer.parseInt(args[0]) - 1; int lineDestNum = Integer.parseInt(args[1]) - 1; switchln(sign, lineTargetNum, lineDestNum); updateSign(p, sign); return true; } catch (NumberFormatException e) { return false; } catch (InvalidLineException e) { say(p, e.getMessage()); return true; } } //Clear sign command. if (cmd.getName().equalsIgnoreCase("clearSign")) { clearSign(sign); updateSign(p, sign); return true; } //Copy sign command. if (cmd.getName().equalsIgnoreCase("copySign")) { copySign(p, sign); say(p, "Sign has been copied."); return true; } //Cut sign command. if (cmd.getName().equalsIgnoreCase("cutSign")) { copySign(p, sign); clearSign(sign); updateSign(p, sign); say(p, "Sign has been cut."); return true; } //Paste sign command. if (cmd.getName().equalsIgnoreCase("pasteSign")) { pasteSign(sign, (String[]) getMetadata(p, SIGN_LINES, this)); updateSign(p, sign); return true; } } else { say(p, MSG_NO_ACTIVE_SIGN); return true; } } else { say(p, MSG_EDIT_DISABLED); return true; } } else { sender.sendMessage("Sign Editor: You must be a player for this to work."); return true; } return false; } public static void setEditing(Player p, boolean val) { p.setMetadata(SIGN_EDIT, new FixedMetadataValue(plugin, val)); } public static boolean isEditing(Player p) { return (boolean) getMetadata(p, SIGN_EDIT, plugin); } /** * Copies a sign and stores it into the player's clipboard. * * @param p * @param s */ public static void copySign(Player p, Sign s) { String[] sl = new String[4]; for (int i = 0; i < sl.length; i++) { sl[i] = s.getLine(i); } p.setMetadata(SIGN_LINES, new FixedMetadataValue(plugin, sl)); } public static void clearSign(Sign s) { for (int i = 0; i < 4; ++i) { s.setLine(i, ""); } } public static void pasteSign(Sign s, String lines[]) { for (int i = 0; i < lines.length; i++) { s.setLine(i, lines[i]); } } /** * Checks if a integer is a valid line number. (0-3) * * @param line The line number you want to check, starting from 0 ending at 3. * @return */ public static boolean isValidLine(int line) { return (line >= 0 && line <= 3); } /** * Merges an array of strings into one string. It also formats it to use spacingStr and spaces after each element. * * @param args * @return The merged string */ public static String mergeStrings(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; ++i) { Bukkit.getServer().getLogger().info(args[i]); sb.append(args[i]); //Add a space if it is not the last element. if (i < args.length - 1) sb.append(" "); } return sb.toString().replaceAll(spacingStr, " "); } /** * Updates a sign and calls a SignChangeEvent. * * @param p The player who updated the sign. * @param s The sign you want to update. */ public static void updateSign(Player p, Sign s) { //The first update is used to change the text of the sign just in case the SignChangeEvent blocks it. This is used mostly to support Lockette. s.update(); Bukkit.getServer().getPluginManager().callEvent(new SignChangeEvent(s.getBlock(), p, s.getLines())); //We must update again after the SignChangeEvent for colors to work. This also allows other plugins to be compatible. s.update(); } public static void say(Player p, String s) { p.sendMessage(ChatColor.GOLD + "[Sign Editor] " + ChatColor.WHITE + s); } public static void editSign(Sign s, String lines[]) { for (int i = 0; i < Math.min(lines.length, 4); ++i) { if (!lines[i].equals(blankStr)) { String text = lines[i].replaceAll(spacingStr, " "); s.setLine(i, text); } } } public static void editSignln(Sign s, int line, String args[]) throws InvalidLineException { if (isValidLine(line)) { String mergedStr = mergeStrings(args); s.setLine(line, mergedStr); } else { throw new InvalidLineException(); } } public static void appendToSign(Sign s, int line, String args[]) throws InvalidLineException { if (isValidLine(line)) { String lineText = s.getLine(line); String appendText = mergeStrings(args); s.setLine(line, lineText + appendText); } else { throw new InvalidLineException(); } } public static void replaceln(Sign s, int line, String regex, String replacement, boolean replaceAll) throws InvalidLineException, PatternSyntaxException { if (isValidLine(line)) { String lineText = s.getLine(line); regex = regex.replaceAll(spacingStr, " "); if (replaceAll) { lineText = lineText.replaceAll(regex, replacement); } else { lineText = lineText.replaceFirst(regex, replacement); } s.setLine(line, lineText); } else { throw new InvalidLineException(); } } public static void switchln(Sign s, int lineTargetNum, int lineDestNum) throws InvalidLineException { if (isValidLine(lineTargetNum) && isValidLine(lineDestNum)) { String lineTarget = s.getLine(lineTargetNum); String lineDest = s.getLine(lineDestNum); s.setLine(lineDestNum, lineTarget); s.setLine(lineTargetNum, lineDest); } else { throw new InvalidLineException(); } } public static Object getMetadata(Player player, String key, Plugin plugin) { List<MetadataValue> values = player.getMetadata(key); for (MetadataValue value : values) { if (value.getOwningPlugin().getDescription().getName().equals(plugin.getDescription().getName())) { return value.value(); } } return null; } }
Removed duplicate try catches.
src/signeditor/SignEditor.java
Removed duplicate try catches.
<ide><path>rc/signeditor/SignEditor.java <ide> <ide> if (editing) { <ide> if (sign != null) { <del> //Toggle sign edit command. <del> if (cmd.getName().equalsIgnoreCase("toggleSignEdit")) { <del> setEditing(p, !editing); <del> say(p, !editing ? "Editing has been enabled." : "Editing has been disabled."); <del> return true; <del> } <del> <del> //Edit sign command. <del> if (cmd.getName().equalsIgnoreCase("editSign")) { <del> editSign(sign, args); <del> updateSign(p, sign); <del> return true; <del> } <del> <del> //Edit sign line command. <del> if (cmd.getName().equalsIgnoreCase("editSignln")) { <del> if (args.length < 1) <del> return false; <del> <del> try { <add> try { <add> //Toggle sign edit command. <add> if (cmd.getName().equalsIgnoreCase("toggleSignEdit")) { <add> setEditing(p, !editing); <add> say(p, !editing ? "Editing has been enabled." : "Editing has been disabled."); <add> return true; <add> } <add> <add> //Edit sign command. <add> if (cmd.getName().equalsIgnoreCase("editSign")) { <add> editSign(sign, args); <add> updateSign(p, sign); <add> return true; <add> } <add> <add> //Edit sign line command. <add> if (cmd.getName().equalsIgnoreCase("editSignln")) { <add> if (args.length < 1) <add> return false; <add> <ide> int line = Integer.parseInt(args[0]) - 1; <ide> editSignln(sign, line, Arrays.copyOfRange(args, 1, args.length)); <ide> updateSign(p, sign); <ide> return true; <del> } catch (NumberFormatException e) { <del> return false; <del> } catch (InvalidLineException e) { <del> say(p, e.getMessage()); <del> return true; <del> } <del> } <del> <del> //appendToSign command <del> if (cmd.getName().equalsIgnoreCase("appendToSign")) { <del> if (args.length < 2) <del> return false; <del> <del> try { <add> } <add> <add> //appendToSign command <add> if (cmd.getName().equalsIgnoreCase("appendToSign")) { <add> if (args.length < 2) <add> return false; <add> <ide> int line = Integer.parseInt(args[0]) - 1; <ide> appendToSign(sign, line, Arrays.copyOfRange(args, 1, args.length)); <ide> updateSign(p, sign); <ide> return true; <del> } catch (NumberFormatException e) { <del> return false; <del> } catch (InvalidLineException e) { <del> say(p, e.getMessage()); <del> return true; <del> } <del> } <del> <del> //replaceln command <del> if (cmd.getName().equalsIgnoreCase("replaceln")) { <del> if (args.length < 3) <del> return false; <del> <del> int line = 0; <del> boolean replaceAll = false; <del> <del> try { <del> line = Integer.parseInt(args[0]) - 1; <add> } <add> <add> //replaceln command <add> if (cmd.getName().equalsIgnoreCase("replaceln")) { <add> if (args.length < 3) <add> return false; <add> <add> boolean replaceAll = false; <add> int line = Integer.parseInt(args[0]) - 1; <add> <ide> if (args.length >= 4) { <ide> replaceAll = Boolean.parseBoolean(args[3]); <ide> } <del> } catch (NumberFormatException e) { <del> return false; <del> } <del> <del> try { <del> replaceln(sign, line, args[1], args[2], replaceAll); <del> } catch (PatternSyntaxException e) { <del> say(p, "Regex syntax is incorrect."); <del> return true; <del> } catch (InvalidLineException e) { <del> say(p, e.getMessage()); <del> return true; <del> } <del> <del> updateSign(p, sign); <del> return true; <del> } <del> <del> //switchln command <del> if (cmd.getName().equalsIgnoreCase("switchln")) { <del> if (args.length < 2) { <del> return false; <del> } <del> <del> try { <add> <add> try { <add> replaceln(sign, line, args[1], args[2], replaceAll); <add> } catch (PatternSyntaxException e) { <add> say(p, "Regex syntax is incorrect."); <add> return true; <add> } <add> <add> updateSign(p, sign); <add> return true; <add> } <add> <add> //switchln command <add> if (cmd.getName().equalsIgnoreCase("switchln")) { <add> if (args.length < 2) { <add> return false; <add> } <add> <ide> int lineTargetNum = Integer.parseInt(args[0]) - 1; <ide> int lineDestNum = Integer.parseInt(args[1]) - 1; <ide> switchln(sign, lineTargetNum, lineDestNum); <ide> updateSign(p, sign); <ide> return true; <del> } catch (NumberFormatException e) { <del> return false; <del> } catch (InvalidLineException e) { <del> say(p, e.getMessage()); <del> return true; <del> } <del> } <del> <del> //Clear sign command. <del> if (cmd.getName().equalsIgnoreCase("clearSign")) { <del> clearSign(sign); <del> updateSign(p, sign); <del> return true; <del> } <del> <del> //Copy sign command. <del> if (cmd.getName().equalsIgnoreCase("copySign")) { <del> copySign(p, sign); <del> say(p, "Sign has been copied."); <del> return true; <del> } <del> <del> //Cut sign command. <del> if (cmd.getName().equalsIgnoreCase("cutSign")) { <del> copySign(p, sign); <del> clearSign(sign); <del> updateSign(p, sign); <del> <del> say(p, "Sign has been cut."); <del> return true; <del> } <del> <del> //Paste sign command. <del> if (cmd.getName().equalsIgnoreCase("pasteSign")) { <del> pasteSign(sign, (String[]) getMetadata(p, SIGN_LINES, this)); <del> updateSign(p, sign); <add> } <add> <add> //Clear sign command. <add> if (cmd.getName().equalsIgnoreCase("clearSign")) { <add> clearSign(sign); <add> updateSign(p, sign); <add> return true; <add> } <add> <add> //Copy sign command. <add> if (cmd.getName().equalsIgnoreCase("copySign")) { <add> copySign(p, sign); <add> say(p, "Sign has been copied."); <add> return true; <add> } <add> <add> //Cut sign command. <add> if (cmd.getName().equalsIgnoreCase("cutSign")) { <add> copySign(p, sign); <add> clearSign(sign); <add> updateSign(p, sign); <add> <add> say(p, "Sign has been cut."); <add> return true; <add> } <add> <add> //Paste sign command. <add> if (cmd.getName().equalsIgnoreCase("pasteSign")) { <add> pasteSign(sign, (String[]) getMetadata(p, SIGN_LINES, this)); <add> updateSign(p, sign); <add> return true; <add> } <add> } catch (NumberFormatException e) { <add> return false; <add> } catch (InvalidLineException e) { <add> say(p, e.getMessage()); <ide> return true; <ide> } <ide> } else {
JavaScript
isc
8f999be83441d7fa96ce15594bae64675df0b454
0
Fickle-Piglet/ficklePiglet,jphuangjr/ficklePiglet,Fickle-Piglet/ficklePiglet,DzoYee/ficklePiglet,Fickle-Piglet/ficklePiglet,Fickle-Piglet/ficklePiglet,DzoYee/ficklePiglet,DzoYee/ficklePiglet,jphuangjr/ficklePiglet,jphuangjr/ficklePiglet,Fickle-Piglet/ficklePiglet,Fickle-Piglet/ficklePiglet,jphuangjr/ficklePiglet,DzoYee/ficklePiglet,jphuangjr/ficklePiglet,Fickle-Piglet/ficklePiglet,DzoYee/ficklePiglet,jphuangjr/ficklePiglet,jphuangjr/ficklePiglet,DzoYee/ficklePiglet,jphuangjr/ficklePiglet,DzoYee/ficklePiglet,DzoYee/ficklePiglet,Fickle-Piglet/ficklePiglet,Fickle-Piglet/ficklePiglet,jphuangjr/ficklePiglet,DzoYee/ficklePiglet
var resourceController = require("../controllers/resourceController"); var loginController = require("../../server/controllers/loginController"); var userResourceController = require("../../server/controllers/userResourceController"); var userController = require("../../server/controllers/userController"); var elastic = require("../../server/controllers/esearch"); module.exports = function(app, express){ //Insert Resource into Database app.post("/insert", resourceController.insertResource); /* GET suggestions */ app.get('/suggest/:input', function (req, res, next) { // console.log("hit this route",req.params.input) elastic.getSuggestions(req.params.input).then(function (result) { res.json(result) }); }); /* POST document to be indexed */ app.post('/create', function (req, res, next) { elastic.addDocument(req.body).then(function (result) { res.json(result) }); }); //Insert Episode into Database app.post("/insertEp", resourceController.insertEpisode); //Edit episodes app.post("/editEp", resourceController.editEpisode); //GetResource //EX: // [ { name: '60-Second Space', // url: 'https://itunes.apple.com/us/podcast/60-second-space/id434439476?mt=2&uo=4', // _id: 4091 }, // { name: 'Chalk Talk Physics Podcast', // url: 'https://itunes.apple.com/us/podcast/chalk-talk-physics-podcast/id262782016?mt=2&uo=4', // _id: 4054 }] app.post('/getResource', resourceController.getResource); app.post('/likeResource', userResourceController.likeResource); app.post('/dislikeResource', userResourceController.dislikeResource); app.post('/resourceHistory', userResourceController.markAsSeen); app.post('/removeRelationship', userResourceController.removeRelationship); //Tags //Returns Array of Tag objects //EX: [ { name: 'Business News', _id: 4030 }, // { name: 'Philosophy', _id: 4033 }, // { name: 'Judaism', _id: 4034 },] app.get('/tags', resourceController.getTags); app.get('/user/:user', userController.getUser); app.get('/userlike/:user', userController.getLikes); app.get('/userDislike/:user', userController.getDislikes); app.post('/getRec', resourceController.getRec); //Signup/Signin Stuff app.post("/signin", loginController.signin); app.post("/signup", loginController.signup); app.post("/logout", loginController.logout); };
server/config/routes.js
var resourceController = require("../controllers/resourceController"); var loginController = require("../../server/controllers/loginController"); var userResourceController = require("../../server/controllers/userResourceController"); var userController = require("../../server/controllers/userController"); var elastic = require("../../server/controllers/esearch"); module.exports = function(app, express){ //Insert Resource into Database app.post("/insert", resourceController.insertResource); /* GET suggestions */ app.get('/suggest/:input', function (req, res, next) { console.log("hit this route",req.params.input) elastic.getSuggestions(req.params.input).then(function (result) { res.json(result) }); }); /* POST document to be indexed */ app.post('/create', function (req, res, next) { elastic.addDocument(req.body).then(function (result) { res.json(result) }); }); //Insert Episode into Database app.post("/insertEp", resourceController.insertEpisode); //Edit episodes app.post("/editEp", resourceController.editEpisode); //GetResource //EX: // [ { name: '60-Second Space', // url: 'https://itunes.apple.com/us/podcast/60-second-space/id434439476?mt=2&uo=4', // _id: 4091 }, // { name: 'Chalk Talk Physics Podcast', // url: 'https://itunes.apple.com/us/podcast/chalk-talk-physics-podcast/id262782016?mt=2&uo=4', // _id: 4054 }] app.post('/getResource', resourceController.getResource); app.post('/likeResource', userResourceController.likeResource); app.post('/dislikeResource', userResourceController.dislikeResource); app.post('/resourceHistory', userResourceController.markAsSeen); app.post('/removeRelationship', userResourceController.removeRelationship); //Tags //Returns Array of Tag objects //EX: [ { name: 'Business News', _id: 4030 }, // { name: 'Philosophy', _id: 4033 }, // { name: 'Judaism', _id: 4034 },] app.get('/tags', resourceController.getTags); app.get('/user/:user', userController.getUser); app.get('/userlike/:user', userController.getLikes); app.get('/userDislike/:user', userController.getDislikes); app.post('/getRec', resourceController.getRec); //Signup/Signin Stuff app.post("/signin", loginController.signin); app.post("/signup", loginController.signup); app.post("/logout", loginController.logout); };
removing comsole log
server/config/routes.js
removing comsole log
<ide><path>erver/config/routes.js <ide> <ide> /* GET suggestions */ <ide> app.get('/suggest/:input', function (req, res, next) { <del> console.log("hit this route",req.params.input) <add> // console.log("hit this route",req.params.input) <ide> elastic.getSuggestions(req.params.input).then(function (result) { res.json(result) }); <ide> }); <ide>
Java
mit
496a649eb1b99cd230c6d42257c046a728f3714c
0
kg6/aig2qbf,kg6/aig2qbf,kg6/aig2qbf
package at.jku.aig2qbf.test.reduction; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import at.jku.aig2qbf.FileIO; import at.jku.aig2qbf.component.And; import at.jku.aig2qbf.component.Component; import at.jku.aig2qbf.component.Input; import at.jku.aig2qbf.component.Latch; import at.jku.aig2qbf.component.Not; import at.jku.aig2qbf.component.Or; import at.jku.aig2qbf.component.Output; import at.jku.aig2qbf.component.Tree; import at.jku.aig2qbf.parser.AAG; import at.jku.aig2qbf.reduction.SimplePathReduction; import at.jku.aig2qbf.test.TestUtil; public class TestSimplePathReduction { private final String TEMP_QDIMACS_FILE = "./output/temp.qbf"; @Before public void setUp() throws Exception { Component.Reset(); } @After public void tearDown() { FileIO.RemoveFile(TEMP_QDIMACS_FILE); } @Test public void SATnot() { { // 0 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Not not = new Not(); o.addInput(not); not.addInput(t.cFalse); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 1 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Not not = new Not(); o.addInput(not); not.addInput(t.cTrue); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } } @Test public void SATor() { { // 00 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cFalse); or.addInput(t.cFalse); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 10 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cTrue); or.addInput(t.cFalse); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 01 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cFalse); or.addInput(t.cTrue); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 11 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cTrue); or.addInput(t.cTrue); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } } @Test public void SATand() { { // 00 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cFalse); and.addInput(t.cFalse); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 10 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cTrue); and.addInput(t.cFalse); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 01 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cFalse); and.addInput(t.cTrue); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 11 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cTrue); and.addInput(t.cTrue); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } } @Test public void testSat0() { List<String> inputFiles = new ArrayList<String>(); inputFiles.add("input/basic/meetingsample1.aag"); final int max_k = 10; for (String inputFilePath : inputFiles) { Tree tree = new AAG().parse(inputFilePath); SimplePathReduction reduction = new SimplePathReduction(); for (int k = 1; k <= max_k; k++) { final long startTime = System.currentTimeMillis(); Tree unrolledTree = tree.unroll(k); unrolledTree.mergeToOneOutput(); Tree tseitinTree = unrolledTree.toTseitinCNF(); Tree reducedTree = reduction.reduceTree(tseitinTree, k); final boolean sat = TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, reducedTree); System.out.println(String.format("testSat0: Test simple path constraint using %s and k=%s (%s%%, %sms)", inputFilePath, k, k * 100 / max_k, System.currentTimeMillis() - startTime)); if (k <= 2) { assertEquals(true, sat); } else { assertEquals(false, sat); } } } } @Test public void testSat1() { final int max_k = 5; // Create a tree with max_k latches in a row Component a = new Input("a"); Output b = new Output("b"); Component parent = a; for (int k = 0; k < max_k; k++) { Latch latch = new Latch(); latch.addInput(parent); parent = latch; } b.addInput(parent); Tree tree = new Tree(); tree.outputs.add(b); // It is expected that the tree needs to be unrolled max_k + 1 in order // to be sat once SimplePathReduction reduction = new SimplePathReduction(); final int max_check = max_k * 2; for (int k = 1; k <= max_check; k++) { final long startTime = System.currentTimeMillis(); Tree unrolledTree = tree.unroll(k); unrolledTree.mergeToOneOutput(); Tree tseitinTree = unrolledTree.toTseitinCNF(); Tree reducedTree = reduction.reduceTree(tseitinTree, k); final boolean sat = TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, reducedTree); System.out.println(String.format("testSat1: Test simple path constraint k=%s (%s%%, %sms)", k, k * 100 / max_check, System.currentTimeMillis() - startTime)); if (k < max_k + 1) { assertFalse(sat); } else { assertTrue(sat); } } } }
src/at/jku/aig2qbf/test/reduction/TestSimplePathReduction.java
package at.jku.aig2qbf.test.reduction; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import at.jku.aig2qbf.FileIO; import at.jku.aig2qbf.component.And; import at.jku.aig2qbf.component.Component; import at.jku.aig2qbf.component.Input; import at.jku.aig2qbf.component.Latch; import at.jku.aig2qbf.component.Not; import at.jku.aig2qbf.component.Or; import at.jku.aig2qbf.component.Output; import at.jku.aig2qbf.component.Tree; import at.jku.aig2qbf.parser.AAG; import at.jku.aig2qbf.reduction.SimplePathReduction; import at.jku.aig2qbf.test.TestUtil; public class TestSimplePathReduction { private final String TEMP_QDIMACS_FILE = "./output/temp.qbf"; @Before public void setUp() throws Exception { Component.Reset(); } @After public void tearDown() { FileIO.RemoveFile(TEMP_QDIMACS_FILE); } @Test public void SATnot() { { // 0 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Not not = new Not(); o.addInput(not); not.addInput(t.cFalse); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 1 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Not not = new Not(); o.addInput(not); not.addInput(t.cTrue); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } } @Test public void SATor() { { // 00 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cFalse); or.addInput(t.cFalse); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 10 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cTrue); or.addInput(t.cFalse); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 01 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cFalse); or.addInput(t.cTrue); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 11 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); Or or = new Or(); o.addInput(or); or.addInput(t.cTrue); or.addInput(t.cTrue); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } } @Test public void SATand() { { // 00 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cFalse); and.addInput(t.cFalse); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 10 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cTrue); and.addInput(t.cFalse); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 01 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cFalse); and.addInput(t.cTrue); t = t.toTseitinCNF(); assertFalse(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } { // 11 Tree t = new Tree(); Output o = new Output("a"); t.outputs.add(o); And and = new And(); o.addInput(and); and.addInput(t.cTrue); and.addInput(t.cTrue); t = t.toTseitinCNF(); assertTrue(TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, t)); } } @Test public void testSat0() { List<String> inputFiles = new ArrayList<String>(); inputFiles.add("input/basic/meetingsample1.aag"); final int max_k = 10; for (String inputFilePath : inputFiles) { Tree tree = new AAG().parse(inputFilePath); SimplePathReduction reduction = new SimplePathReduction(); for (int k = 1; k <= max_k; k++) { final long startTime = System.currentTimeMillis(); Tree unrolledTree = tree.unroll(k); unrolledTree.mergeToOneOutput(); Tree tseitinTree = unrolledTree.toTseitinCNF(); Tree reducedTree = reduction.reduceTree(tseitinTree, k); final boolean sat = TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, reducedTree); System.out.println(String.format("testSat0: Test simple path constraint using %s and k=%s (%s%%, %sms)", inputFilePath, k, k * 100 / max_k, System.currentTimeMillis() - startTime)); if (k <= 2) { assertEquals(true, sat); } else { assertEquals(false, sat); } } } } @Test public void testSat1() { final int max_k = 5; // Create a tree with max_k latches in a row Component a = new Input("a"); Output b = new Output("b"); Component parent = a; for (int k = 0; k < max_k; k++) { Latch latch = new Latch(); latch.addInput(parent); parent = latch; } b.addInput(parent); Tree tree = new Tree(); tree.outputs.add(b); // It is expected that the tree needs to be unrolled max_k + 1 in order // to be sat once SimplePathReduction reduction = new SimplePathReduction(); final int max_check = max_k * 2; for (int k = 1; k <= max_check; k++) { final long startTime = System.currentTimeMillis(); Tree unrolledTree = tree.unroll(k); unrolledTree.mergeToOneOutput(); Tree tseitinTree = unrolledTree.toTseitinCNF(); Tree reducedTree = reduction.reduceTree(tseitinTree, k); final boolean sat = TestUtil.CheckSatisfiablity(TEMP_QDIMACS_FILE, reducedTree); System.out.println(String.format("testSat1: Test simple path constraint k=%s (%s%%, %sms)", k, k * 100 / max_check, System.currentTimeMillis() - startTime)); if (k <= max_k + 1) { assertFalse(sat); } else { assertTrue(sat); } } } }
Fixed simplepath reduction test
src/at/jku/aig2qbf/test/reduction/TestSimplePathReduction.java
Fixed simplepath reduction test
<ide><path>rc/at/jku/aig2qbf/test/reduction/TestSimplePathReduction.java <ide> <ide> System.out.println(String.format("testSat1: Test simple path constraint k=%s (%s%%, %sms)", k, k * 100 / max_check, System.currentTimeMillis() - startTime)); <ide> <del> if (k <= max_k + 1) { <add> if (k < max_k + 1) { <ide> assertFalse(sat); <ide> } <ide> else {
Java
apache-2.0
e0a6a9c375c49e15a22ddb0a22ba54567a3ac4e0
0
speedment/speedment,speedment/speedment
/** * * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.runtime.core.internal.db.postgresql; import com.speedment.runtime.config.Column; import com.speedment.runtime.core.db.JavaTypeMap; import com.speedment.runtime.core.db.metadata.ColumnMetaData; import com.speedment.runtime.core.internal.db.AbstractDbmsMetadataHandler; import java.sql.Blob; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Optional; /** * Created by fdirlikl on 11/13/2015. * * @author Fatih Dirlikli * @author Emil Forslund */ public final class PostgresqlDbmsMetadataHandler extends AbstractDbmsMetadataHandler { @Override protected JavaTypeMap newJavaTypeMap() { final JavaTypeMap javaTypeMap = super.newJavaTypeMap(); javaTypeMap.put("bytea", Blob.class); // https://www.postgresql.org/docs/9.2/static/infoschema-datatypes.html javaTypeMap.put("cardinal_number", Integer.class); javaTypeMap.put("character_data", String.class); javaTypeMap.put("sql_identifier", String.class); javaTypeMap.put("time_stamp", Timestamp.class); javaTypeMap.put("yes_or_no", String.class); javaTypeMap.addRule((sqlTypeMapping, md) -> { // Map a BIT(1) to boolean if ("BIT".equalsIgnoreCase(md.getTypeName()) && md.getColumnSize() == 1) { return Optional.of(Boolean.class); } else return Optional.empty(); }); return javaTypeMap; } @Override protected void setAutoIncrement(Column column, ColumnMetaData md) throws SQLException { super.setAutoIncrement(column, md); final String defaultValue = md.getColumnDef(); if (defaultValue != null && defaultValue.startsWith("nextval(")) { column.mutator().setAutoIncrement(true); } } }
runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/db/postgresql/PostgresqlDbmsMetadataHandler.java
/** * * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.runtime.core.internal.db.postgresql; import com.speedment.runtime.config.Column; import com.speedment.runtime.core.db.JavaTypeMap; import com.speedment.runtime.core.db.metadata.ColumnMetaData; import com.speedment.runtime.core.internal.db.AbstractDbmsMetadataHandler; import java.sql.Blob; import java.sql.SQLException; import java.util.Optional; /** * Created by fdirlikl on 11/13/2015. * * @author Fatih Dirlikli * @author Emil Forslund */ public final class PostgresqlDbmsMetadataHandler extends AbstractDbmsMetadataHandler { @Override protected JavaTypeMap newJavaTypeMap() { final JavaTypeMap javaTypeMap = super.newJavaTypeMap(); javaTypeMap.put("bytea", Blob.class); javaTypeMap.addRule((sqlTypeMapping, md) -> { // Map a BIT(1) to boolean if ("BIT".equalsIgnoreCase(md.getTypeName()) && md.getColumnSize() == 1) { return Optional.of(Boolean.class); } else return Optional.empty(); }); return javaTypeMap; } @Override protected void setAutoIncrement(Column column, ColumnMetaData md) throws SQLException { super.setAutoIncrement(column, md); final String defaultValue = md.getColumnDef(); if (defaultValue != null && defaultValue.startsWith("nextval(")) { column.mutator().setAutoIncrement(true); } } }
runtime-core: Document postgres type mappings
runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/db/postgresql/PostgresqlDbmsMetadataHandler.java
runtime-core: Document postgres type mappings
<ide><path>untime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/db/postgresql/PostgresqlDbmsMetadataHandler.java <ide> <ide> import java.sql.Blob; <ide> import java.sql.SQLException; <add>import java.sql.Timestamp; <ide> import java.util.Optional; <ide> <ide> /** <ide> final JavaTypeMap javaTypeMap = super.newJavaTypeMap(); <ide> <ide> javaTypeMap.put("bytea", Blob.class); <add> <add> // https://www.postgresql.org/docs/9.2/static/infoschema-datatypes.html <add> javaTypeMap.put("cardinal_number", Integer.class); <add> javaTypeMap.put("character_data", String.class); <add> javaTypeMap.put("sql_identifier", String.class); <add> javaTypeMap.put("time_stamp", Timestamp.class); <add> javaTypeMap.put("yes_or_no", String.class); <ide> <ide> javaTypeMap.addRule((sqlTypeMapping, md) -> { <ide> // Map a BIT(1) to boolean
JavaScript
apache-2.0
fa13a0b4b74091ef2c864e11783341682a20ea35
0
atomjump/medimage,atomjump/medimage
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var deleteThisFile = {}; //Global object for image taken, to be deleted var centralPairingUrl = "https://atomjump.com/med-genid.php"; var errorThis = {}; //Used as a global error handler var retryIfNeeded = []; //A global pushable list with the repeat attempts var retryNum = 0; var app = { // Application Constructor initialize: function() { this.bindEvents(); //Set display name - TODO: check this is valid here this.displayServerName(); errorThis = this; }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); }, takePicture: function() { var _this = this; navigator.camera.getPicture( function( imageURI ) { errorThis.uploadPhoto(imageURI); }, function( message ) { errorThis.notify( message ); }, { quality: 100, destinationType: Camera.DestinationType.FILE_URI }); }, get: function(url, cb) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200 || request.status == 0) { cb(url, request.responseText); // -> request.responseText <- is a result } } } request.send(); }, scanlan: function(port, cb) { var _this = this; if(this.lan) { var lan = this.lan; for(var cnt=0; cnt< 255; cnt++){ var machine = cnt.toString(); var url = 'http://' + lan + machine + ':' + port; this.get(url, function(goodurl, resp) { if(resp) { //Save the first TODO: if more than one, open another screen here localStorage.setItem("currentWifiServer", goodurl); clearTimeout(scanning); cb(goodurl, null); } }); } //timeout after 5 secs var scanning = setTimeout(function() { _this.notify('Timeout finding your Wifi server.'); //old: document.getElementById('override-form').style.display = 'block'; }, 4000); } else { //No lan detected cb(null,'Do you have a 4 digit code?'); } }, notify: function(msg) { //Set the user message document.getElementById("notify").innerHTML = msg; }, uploadPhoto: function(imageURIin) { var _this = this; var usingServer = localStorage.getItem("usingServer"); if((!usingServer)||(usingServer == null)) { //No remove server already connected to, find the server now. And then call upload again _this.findServer(function(err) { if(err) { errorThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds."); //Search again in 10 seconds: setTimeout(function() { errorThis.uploadPhoto(imageURIin) }, 10000); } else { //Now we are connected, upload the photo again errorThis.uploadPhoto(imageURIin); } }); return; } else { //Have connected OK to a server window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) { deleteThisFile = fileEntry; //Store globally var imageURI = fileEntry.toURL(); var options = new FileUploadOptions(); options.fileKey="file1"; var tempName = document.getElementById("id-entered").value; if((tempName == '')||(tempName == null)) { tempName = 'image'; } if(_this.defaultDir) { //A hash code signifies a directory to write to tempName = "#" + _this.defaultDir + " " + tempName; } var myoutFile = tempName.replace(/ /g,'-'); navigator.globalization.dateToString( new Date(), function (date) { var mydt = date.value.replace(/:/g,'-'); mydt = mydt.replace(/ /g,'-'); mydt = mydt.replace(/\//g,'-'); var aDate = new Date(); var seconds = aDate.getSeconds(); mydt = mydt + "-" + seconds; mydt = mydt.replace(/,/g,''); //remove any commas from iphone options.fileName = myoutFile + '-' + mydt + '.jpg'; options.mimeType="image/jpeg"; var params = new Object(); params.title = document.getElementById("id-entered").value; if((params.title == '')||(params.title == null)) { params.title = 'image'; } options.params = params; options.chunkedMode = false; var ft = new FileTransfer(); _this.notify("Uploading " + params.title); ft.onprogress = _this.progress; var serverReq = usingServer + '/api/photo'; var repeatIfNeeded = { "imageURI" : imageURI, "serverReq" : serverReq, "options" :options, "failureCount": 0 }; retryIfNeeded.push(repeatIfNeeded); ft.upload(imageURI, serverReq, _this.win, _this.fail, options); }, function () { navigator.notification.alert('Error getting dateString\n'); }, { formatLength:'medium', selector:'date and time'} ); //End of function in globalization date to string }); //End of resolveLocalFileSystemURI } //End of connected to a server OK }, progress: function(progressEvent) { var statusDom = document.querySelector('#status'); if (progressEvent.lengthComputable) { var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); statusDom.innerHTML = perc + "% uploaded..."; } else { if(statusDom.innerHTML == "") { statusDom.innerHTML = "Uploading"; } else { statusDom.innerHTML += "."; } } }, retry: function(existingText) { var repeatIfNeeded = retryIfNeeded.pop(); if(repeatIfNeeded) { //Resend within a minute here errorThis.notify(existingText + " Retrying " + repeatIfNeeded.options.params.title + " in 10 seconds."); repeatIfNeeded.failureCount += 1; //Increase this if(repeatIfNeeded.failureCount > 3) { //Have tried too many attempts - try to reconnect completely (i.e. go //from wifi to network and vica versa localStorage.setItem("usingServer", null); //This will force a reconnection errorThis.uploadPhoto(repeatIfNeeded.imageURI); } else { //OK in the first few attempts - keep the current connection and try again setTimeout(function() { var ft = new FileTransfer(); ft.onprogress = errorThis.progress; errorThis.notify("Trying to upload " + repeatIfNeeded.options.params.title); retryIfNeeded.push(repeatIfNeeded); ft.upload(repeatIfNeeded.imageURI, repeatIfNeeded.serverReq, errorThis.win, errorThis.fail, repeatIfNeeded.options); }, 10000); //Wait 10 seconds before trying again } } }, win: function(r) { document.querySelector('#status').innerHTML = ""; //Clear progress status console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); if((r.responseCode == 200)||(r.response.indexOf("200") != -1)) { document.getElementById("notify").innerHTML = 'Image transferred. Success!'; //Save the current server settings for future reuse errorThis.saveServer(); //and delete phone version deleteThisFile.remove(); } else { //Retry sending errorThis.retry(""); } }, fail: function(error) { document.querySelector('#status').innerHTML = ""; //Clear progress status switch(error.code) { case 1: errorThis.notify("Sorry the photo file was not found on your phone."); break; case 2: errorThis.notify("Sorry you have tried to send it to an invalid URL."); break; case 3: errorThis.notify("You cannot connect to the server at this time."); errorThis.retry("You cannot connect to the server at this time.</br>"); break; case 4: errorThis.notify("Sorry, your image transfer was aborted."); errorThis.retry("Sorry, your image transfer was aborted.</br>"); break; default: errorThis.notify("An error has occurred: Code = " + error.code); break; } }, getip: function(cb) { var _this = this; //timeout after 3 secs -rerun this.findServer() var iptime = setTimeout(function() { var err = "You don't appear to be connected to your wifi. Please connect and try again."; cb(err); }, 5000); networkinterface.getIPAddress(function(ip) { _this.ip = ip; var len = ip.lastIndexOf('\.') + 1; _this.lan = ip.substr(0,len); clearTimeout(iptime); cb(null); }); }, factoryReset: function() { //We have connected to a server OK var _this = this; navigator.notification.confirm( 'Are you sure? All your saved PCs and other settings will be cleared.', // message function(buttonIndex) { if(buttonIndex == 1) { localStorage.clear(); localStorage.setItem("usingServer", null); //Init it localStorage.setItem("currentRemoteServer", null); localStorage.setItem("currentWifiServer", null); //Now refresh the current server display document.getElementById("currentPC").innerHTML = ""; alert("Cleared all saved PCs."); errorThis.openSettings(); } }, // callback to invoke 'Clear Settings', // title ['Ok','Cancel'] // buttonLabels ); return false; }, checkDefaultDir: function(server) { //Check if the default server has a default dir eg. input: // http://123.123.123.123:5566/write/fshoreihtskhfv //Where the defaultDir would be set to 'fshoreihtskhfv' //Returns 'http://123.123.123.123:5566' var requiredStr = "/write/"; var startsAt = server.indexOf(requiredStr); if(startsAt >= 0) { //Get the default dir after the /write/ string var startFrom = startsAt + requiredStr.length; this.defaultDir = server.substr(startFrom); var properServer = server.substr(0, startsAt); return properServer; } else { return server; } }, connect: function(results) { //Save the server with a name //Get existing settings array switch(results.buttonIndex) { case 1: //Clicked on 'Ok' //Start the pairing process var pairUrl = centralPairingUrl + '?compare=' + results.input1; errorThis.notify("Pairing.."); errorThis.get(pairUrl, function(url, resp) { resp = resp.replace('\n', '') if(resp == 'nomatch') { errorThis.notify("Sorry, there was no match for that code."); return; } else { errorThis.notify("Pairing success."); var server = resp; //And save this server localStorage.setItem("currentRemoteServer",server); navigator.notification.confirm( 'Do you want to connect via Wifi, if it is available, also?', // message function(buttonIndex) { if(buttonIndex == 1) { //yes, we also want to connect via wifi errorThis.checkWifi(function(err) { if(err) { //An error finding wifi errorThis.notify(err); } else { //Ready to take a picture, rerun with this //wifi server errorThis.notify("Wifi paired successfully."); errorThis.bigButton(); } }); } else { errorThis.notify("Pairing success. No wifi."); } }, // callback to invoke 'Pairing Success!', // title ['Yes','No'] // buttonLabels ); return; } }); //end of get break; case 2: //Clicked on 'Wifi only' //Otherwise, first time we are running the app this session errorThis.checkWifi(function(err) { if(err) { //An error finding server - likely need to enter a pairing code. Warn the user errorThis.notify(err); } else { //Ready to take a picture, rerun errorThis.notify("Wifi paired successfully."); errorThis.bigButton(); } }); return; break; default: //Clicked on 'Cancel' break; } }, bigButton: function() { //Called when pushing the big button var _this = this; _this.findServer(function(err) { if(err) { //An error finding server - likely need to enter a pairing code. Warn the user //No current server - first time with this new connection //We have connected to a server OK navigator.notification.prompt( 'Please enter the 4 letter pairing code from your PC.', // message errorThis.connect, // callback to invoke 'New Connection', // title ['Ok','Use Wifi Only','Cancel'], // buttonLabels '' // defaultText ); } else { //Ready to take a picture _this.takePicture(); } }); }, checkWifi: function(cb) { errorThis.notify("Checking Wifi connection"); this.getip(function(ip, err) { if(err) { cb(err); return; } errorThis.notify("Scanning Wifi"); errorThis.scanlan('5566', function(url, err) { if(err) { cb(err); } else { cb(null); } }); }); }, findServer: function(cb) { //Check storage for any saved current servers, and set the remote and wifi servers //along with splitting any subdirectories, ready for use by the the uploader. //Then actually try to connect - if wifi is an option, use that first var _this = this; var found = false; //Clear off var foundRemoteServer = null; var foundWifiServer = null; var usingServer = null; //Early out usingServer = localStorage.getItem("usingServer"); if((usingServer)&&(usingServer != null)) { alert("usingServer=" + usingServer); cb(null); return; } foundRemoteServer = localStorage.getItem("currentRemoteServer"); foundWifiServer = localStorage.getItem("currentWifiServer"); if((foundRemoteServer)&&(foundRemoteServer != null)) { //Already found a remote server //Generate the directory split, if any. Setting RAM foundServer and defaultDir foundRemoteServer = this.checkDefaultDir(foundRemoteServer); } //Check if we have a Wifi option if((foundWifiServer)&&(foundWifiServer != null)) { //Already found wifi //Generate the directory split, if any. Setting RAM foundServer and defaultDir foundWifiServer = this.checkDefaultDir(foundWifiServer); } //Early out: if((foundWifiServer == null)&&(foundRemoteServer == null)) { cb('No known server.'); return; } //Now try the wifi server as the first option to use if it exists: if((foundWifiServer)&&(foundWifiServer != null)) { //Ping the wifi server errorThis.notify('Trying to connect to the wifi server..'); //Timeout after 5 secs for the following ping var scanning = setTimeout(function() { errorThis.notify('Timeout finding your wifi server. Trying remote server..'); //Else can't communicate with the wifi server at this time. //Try the remote server if((foundRemoteServer)&&(foundRemoteServer != null)) { var scanning = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.setItem("usingServer", null); cb('No server found'); }, 4000); errorThis.get(foundRemoteServer, function(url, resp) { //Success, got a connection to the remote server clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundRemoteServer); cb(null); }); } else { //Only wifi existed localStorage.setItem("usingServer", null); cb('No server found'); } }, 2000); //Ping the wifi server errorThis.get(foundWifiServer, function(url, resp) { //Success, got a connection to the wifi clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundWifiServer); cb(null); //Success found server }); } else { //OK - no wifi option - go straight to the remote server //Try the remote server errorThis.notify('Trying to connect to the remote server....'); var scanning = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.setItem("usingServer", null); cb('No server found'); }, 4000); _this.get(foundRemoteServer, function(url, resp) { //Success, got a connection to the remote server clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundRemoteServer); cb(null); }); } }, /* Settings Functions */ /* localStorage.clear(); this.foundServer = null; this.defaultDir = null; this.overrideServer = null; document.getElementById("override").value = ""; alert("Cleared default server."); return false; */ openSettings: function() { //Open the settings screen var html = this.listServers(); document.getElementById("settings").innerHTML = html; document.getElementById("settings-popup").style.display = "block"; }, closeSettings: function() { //Close the settings screen document.getElementById("settings-popup").style.display = "none"; }, listServers: function() { //List the available servers var settings = this.getArrayLocalStorage("settings"); if(settings) { var html = "<ons-list><ons-list-header>Select a PC to use now:</ons-list-header>"; //Convert the array into html for(var cnt=0; cnt< settings.length; cnt++) { html = html + "<ons-list-item><ons-list-item onclick='app.setServer(" + cnt + ");'>" + settings[cnt].name + "</ons-list-item><div class='right'><ons-icon icon='md-delete' onclick='app.deleteServer(" + cnt + ");'></ons-icon></div></ons-list-item>"; } html = html + "</ons-list>"; } else { var html = "<ons-list><ons-list-header>PCs Stored</ons-list-header>"; var html = html + "<ons-list-item><ons-list-item>Default</ons-list-item><div class='right'><ons-icon icon='md-delete'style='color:#AAA></ons-icon></div></ons-list-item>"; html = html + "</ons-list>"; } return html; }, setServer: function(serverId) { //Set the server to the input server id var settings = this.getArrayLocalStorage("settings"); var currentRemoteServer = settings[serverId].currentRemoteServer; var currentWifiServer = settings[serverId].currentWifiServer; localStorage.setItem("usingServer", null); //reset the currently used server //Save the current server TODO: null handling here? localStorage.setItem("currentRemoteServer", currentRemoteServer); localStorage.setItem("currentWifiServer", currentWifiServer); navigator.notification.alert("Switched to: " + settings[serverId].name, function() {}, "Changing PC"); //Now refresh the current server display document.getElementById("currentPC").innerHTML = settings[serverId].name; this.closeSettings(); return false; }, newServer: function() { //Create a new server. //This is actually effectively resetting, and we will allow the normal functions to input a new one localStorage.setItem("usingServer", null); //Remove the current one var exists = localStorage.getItem("currentRemoteServer"); if((exists)&&(exists != null)) { localStorage.removeItem("currentRemoteServer"); } var exists = localStorage.getItem("currentWifiServer"); if((exists)&&(exists != null)) { localStorage.removeItem("currentWifiServer"); } //Ask for a name of the current Server: navigator.notification.prompt( 'Please enter a name for this PC', // message this.saveServerName, // callback to invoke 'PC Name', // title ['Ok','Cancel'], // buttonLabels 'Main' // defaultText ); }, deleteServer: function(serverId) { //Delete an existing server this.myServerId = serverId; navigator.notification.confirm( 'Are you sure? This PC will be removed from memory.', // message function(buttonIndex) { if(buttonIndex == 1) { var settings = errorThis.getArrayLocalStorage("settings"); if((settings == null)|| (settings == '')) { //Nothing to delete } else { settings.splice(errorThis.myServerId, 1); //Remove the entry entirely from array errorThis.setArrayLocalStorage("settings", settings); } errorThis.openSettings(); //refresh } }, // callback to invoke 'Remove PC', // title ['Ok','Exit'] // buttonLabels ); }, saveServerName: function(results) { //Save the server with a name - but since this is new, //Get existing settings array if(results.buttonIndex == 1) { //Clicked on 'Ok' localStorage.setItem("currentServerName", results.input1); //Now refresh the current server display document.getElementById("currentPC").innerHTML = results.input1; errorThis.closeSettings(); return; } else { //Clicked on 'Exit'. Do nothing. return; } }, displayServerName: function() { //Call this during initialisation on app startup var currentServerName = localStorage.getItem("currentServerName"); if((currentServerName) && (currentServerName != null)) { //Now refresh the current server display document.getElementById("currentPC").innerHTML = currentServerName; } else { document.getElementById("currentPC").innerHTML = ""; } }, saveServer: function() { //Run this after a successful upload var currentServerName = localStorage.getItem("currentServerName"); var currentRemoteServer = localStorage.getItem("currentRemoteServer"); var currentWifiServer = localStorage.getItem("currentWifiServer"); if((!currentServerName) ||(currentServerName == null)) currentServerName = "Default"; if((!currentRemoteServer) ||(currentRemoteServer == null)) currentRemoteServer = null; if((!currentWifiServer) ||(currentWifiServer == null)) currentWifiServer = null; var settings = errorThis.getArrayLocalStorage("settings"); //Create a new entry - which will be blank to being with var newSetting = { "name": currentServerName, //As input by the user "currentRemoteServer": currentRemoteServer, "currentWifiServer": currentWifiServer }; if((settings == null)|| (settings == '')) { //Creating an array for the first time var settings = []; settings.push(newSetting); //Save back to the array } else { //Check if we are writing over the existing entries var writeOver = false; for(cnt = 0; cnt< settings.length; cnt++) { if(settings[cnt].name == currentServerName) { writeOver = true; settings[cnt] = newSetting; } } if(writeOver == false) { settings.push(newSetting); //Save back to the array } } //Save back to the persistent settings errorThis.setArrayLocalStorage("settings", settings); return; }, //Array storage for app permanent settings (see http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/) setArrayLocalStorage: function(mykey, myobj) { return localStorage.setItem(mykey, JSON.stringify(myobj)); }, getArrayLocalStorage: function(mykey) { return JSON.parse(localStorage.getItem(mykey)); } };
www/js/index.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var deleteThisFile = {}; //Global object for image taken, to be deleted var centralPairingUrl = "https://atomjump.com/med-genid.php"; var errorThis = {}; //Used as a global error handler var retryIfNeeded = []; //A global pushable list with the repeat attempts var retryNum = 0; var app = { // Application Constructor initialize: function() { this.bindEvents(); //Set display name - TODO: check this is valid here this.displayServerName(); errorThis = this; }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); }, takePicture: function() { var _this = this; navigator.camera.getPicture( function( imageURI ) { errorThis.uploadPhoto(imageURI); }, function( message ) { errorThis.notify( message ); }, { quality: 100, destinationType: Camera.DestinationType.FILE_URI }); }, get: function(url, cb) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200 || request.status == 0) { cb(url, request.responseText); // -> request.responseText <- is a result } } } request.send(); }, scanlan: function(port, cb) { var _this = this; if(this.lan) { var lan = this.lan; for(var cnt=0; cnt< 255; cnt++){ var machine = cnt.toString(); var url = 'http://' + lan + machine + ':' + port; this.get(url, function(goodurl, resp) { if(resp) { //Save the first TODO: if more than one, open another screen here localStorage.setItem("currentWifiServer", goodurl); clearTimeout(scanning); cb(goodurl, null); } }); } //timeout after 5 secs var scanning = setTimeout(function() { _this.notify('Timeout finding your Wifi server.'); //old: document.getElementById('override-form').style.display = 'block'; }, 4000); } else { //No lan detected cb(null,'Do you have a 4 digit code?'); } }, notify: function(msg) { //Set the user message document.getElementById("notify").innerHTML = msg; }, uploadPhoto: function(imageURIin) { var _this = this; var usingServer = localStorage.getItem("usingServer"); if((!usingServer)||(usingServer == null)) { //No remove server already connected to, find the server now. And then call upload again _this.findServer(function(err) { if(err) { errorThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds."); //Search again in 10 seconds: setTimeout(function() { errorThis.uploadPhoto(imageURIin) }, 10000); } else { //Now we are connected, upload the photo again errorThis.uploadPhoto(imageURIin); } }); return; } else { //Have connected OK to a server window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) { deleteThisFile = fileEntry; //Store globally var imageURI = fileEntry.toURL(); var options = new FileUploadOptions(); options.fileKey="file1"; var tempName = document.getElementById("id-entered").value; if((tempName == '')||(tempName == null)) { tempName = 'image'; } if(_this.defaultDir) { //A hash code signifies a directory to write to tempName = "#" + _this.defaultDir + " " + tempName; } var myoutFile = tempName.replace(/ /g,'-'); navigator.globalization.dateToString( new Date(), function (date) { var mydt = date.value.replace(/:/g,'-'); mydt = mydt.replace(/ /g,'-'); mydt = mydt.replace(/\//g,'-'); var aDate = new Date(); var seconds = aDate.getSeconds(); mydt = mydt + "-" + seconds; mydt = mydt.replace(/,/g,''); //remove any commas from iphone options.fileName = myoutFile + '-' + mydt + '.jpg'; options.mimeType="image/jpeg"; var params = new Object(); params.title = document.getElementById("id-entered").value; if((params.title == '')||(params.title == null)) { params.title = 'image'; } options.params = params; options.chunkedMode = false; var ft = new FileTransfer(); _this.notify("Uploading " + params.title); ft.onprogress = _this.progress; var serverReq = usingServer + '/api/photo'; var repeatIfNeeded = { "imageURI" : imageURI, "serverReq" : serverReq, "options" :options, "failureCount": 0 }; retryIfNeeded.push(repeatIfNeeded); ft.upload(imageURI, serverReq, _this.win, _this.fail, options); }, function () { navigator.notification.alert('Error getting dateString\n'); }, { formatLength:'medium', selector:'date and time'} ); //End of function in globalization date to string }); //End of resolveLocalFileSystemURI } //End of connected to a server OK }, progress: function(progressEvent) { var statusDom = document.querySelector('#status'); if (progressEvent.lengthComputable) { var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); statusDom.innerHTML = perc + "% uploaded..."; } else { if(statusDom.innerHTML == "") { statusDom.innerHTML = "Uploading"; } else { statusDom.innerHTML += "."; } } }, retry: function(existingText) { var repeatIfNeeded = retryIfNeeded.pop(); if(repeatIfNeeded) { //Resend within a minute here errorThis.notify(existingText + " Retrying " + repeatIfNeeded.options.params.title + " in 10 seconds."); repeatIfNeeded.failureCount += 1; //Increase this if(repeatIfNeeded.failureCount > 3) { //Have tried too many attempts - try to reconnect completely (i.e. go //from wifi to network and vica versa localStorage.setItem("usingServer", null); //This will force a reconnection errorThis.uploadPhoto(repeatIfNeeded.imageURI); } else { //OK in the first few attempts - keep the current connection and try again setTimeout(function() { var ft = new FileTransfer(); ft.onprogress = errorThis.progress; errorThis.notify("Trying to upload " + repeatIfNeeded.options.params.title); retryIfNeeded.push(repeatIfNeeded); ft.upload(repeatIfNeeded.imageURI, repeatIfNeeded.serverReq, errorThis.win, errorThis.fail, repeatIfNeeded.options); }, 10000); //Wait 10 seconds before trying again } } }, win: function(r) { document.querySelector('#status').innerHTML = ""; //Clear progress status console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); if((r.responseCode == 200)||(r.response.indexOf("200") != -1)) { document.getElementById("notify").innerHTML = 'Image transferred. Success!'; //Save the current server settings for future reuse errorThis.saveServer(); //and delete phone version deleteThisFile.remove(); } else { //Retry sending errorThis.retry(""); } }, fail: function(error) { document.querySelector('#status').innerHTML = ""; //Clear progress status switch(error.code) { case 1: errorThis.notify("Sorry the photo file was not found on your phone."); break; case 2: errorThis.notify("Sorry you have tried to send it to an invalid URL."); break; case 3: errorThis.notify("You cannot connect to the server at this time."); errorThis.retry("You cannot connect to the server at this time.</br>"); break; case 4: errorThis.notify("Sorry, your image transfer was aborted."); errorThis.retry("Sorry, your image transfer was aborted.</br>"); break; default: errorThis.notify("An error has occurred: Code = " + error.code); break; } }, getip: function(cb) { var _this = this; //timeout after 3 secs -rerun this.findServer() var iptime = setTimeout(function() { var err = "You don't appear to be connected to your wifi. Please connect and try again."; cb(err); }, 5000); networkinterface.getIPAddress(function(ip) { _this.ip = ip; var len = ip.lastIndexOf('\.') + 1; _this.lan = ip.substr(0,len); clearTimeout(iptime); cb(null); }); }, factoryReset: function() { //We have connected to a server OK var _this = this; navigator.notification.confirm( 'Are you sure? All your saved PCs and other settings will be cleared.', // message function(buttonIndex) { if(buttonIndex == 1) { localStorage.clear(); localStorage.setItem("usingServer", null); //Init it localStorage.setItem("currentRemoteServer", null); localStorage.setItem("currentWifiServer", null); //Now refresh the current server display document.getElementById("currentPC").innerHTML = ""; alert("Cleared all saved PCs."); errorThis.openSettings(); } }, // callback to invoke 'Clear Settings', // title ['Ok','Cancel'] // buttonLabels ); return false; }, checkDefaultDir: function(server) { //Check if the default server has a default dir eg. input: // http://123.123.123.123:5566/write/fshoreihtskhfv //Where the defaultDir would be set to 'fshoreihtskhfv' //Returns 'http://123.123.123.123:5566' var requiredStr = "/write/"; var startsAt = server.indexOf(requiredStr); if(startsAt >= 0) { //Get the default dir after the /write/ string var startFrom = startsAt + requiredStr.length; this.defaultDir = server.substr(startFrom); var properServer = server.substr(0, startsAt); return properServer; } else { return server; } }, connect: function(results) { //Save the server with a name //Get existing settings array switch(results.buttonIndex) { case 1: //Clicked on 'Ok' //Start the pairing process var pairUrl = centralPairingUrl + '?compare=' + results.input1; errorThis.notify("Pairing.."); errorThis.get(pairUrl, function(url, resp) { resp = resp.replace('\n', '') if(resp == 'nomatch') { errorThis.notify("Sorry, there was no match for that code."); return; } else { errorThis.notify("Pairing success."); var server = resp; //And save this server localStorage.setItem("currentRemoteServer",server); navigator.notification.confirm( 'Do you want to connect via Wifi, if it is available, also?', // message function(buttonIndex) { if(buttonIndex == 1) { //yes, we also want to connect via wifi errorThis.checkWifi(function(err) { if(err) { //An error finding wifi errorThis.notify(err); } else { //Ready to take a picture, rerun with this //wifi server errorThis.notify("Wifi paired successfully."); errorThis.bigButton(); } }); } else { errorThis.notify("Pairing success. No wifi."); } }, // callback to invoke 'Pairing Success!', // title ['Yes','No'] // buttonLabels ); return; } }); //end of get break; case 2: //Clicked on 'Wifi only' //Otherwise, first time we are running the app this session errorThis.checkWifi(function(err) { if(err) { //An error finding server - likely need to enter a pairing code. Warn the user errorThis.notify(err); } else { //Ready to take a picture, rerun errorThis.notify("Wifi paired successfully."); errorThis.bigButton(); } }); return; break; default: //Clicked on 'Cancel' break; } }, bigButton: function() { //Called when pushing the big button var _this = this; _this.findServer(function(err) { if(err) { //An error finding server - likely need to enter a pairing code. Warn the user //No current server - first time with this new connection //We have connected to a server OK navigator.notification.prompt( 'Please enter the 4 letter pairing code from your PC.', // message errorThis.connect, // callback to invoke 'New Connection', // title ['Ok','Use Wifi Only','Cancel'], // buttonLabels '' // defaultText ); } else { //Ready to take a picture _this.takePicture(); } }); }, checkWifi: function(cb) { errorThis.notify("Checking Wifi connection"); this.getip(function(ip, err) { if(err) { cb(err); return; } errorThis.notify("Scanning Wifi"); errorThis.scanlan('5566', function(url, err) { if(err) { cb(err); } else { cb(null); } }); }); }, findServer: function(cb) { //Check storage for any saved current servers, and set the remote and wifi servers //along with splitting any subdirectories, ready for use by the the uploader. //Then actually try to connect - if wifi is an option, use that first var _this = this; var found = false; //Clear off var foundRemoteServer = null; var foundWifiServer = null; //Early out var usingServer = localStorage.getItem("usingServer"); if((usingServer)&&(usingServer != null)) { cb(null); return; } var foundRemoteServer = localStorage.getItem("currentRemoteServer"); var foundWifiServer = localStorage.getItem("currentWifiServer"); if((foundRemoteServer)&&(foundRemoteServer != null)) { //Already found a remote server //Generate the directory split, if any. Setting RAM foundServer and defaultDir foundRemoteServer = this.checkDefaultDir(foundRemoteServer); } //Check if we have a Wifi option if((foundWifiServer)&&(foundWifiServer != null)) { //Already found wifi //Generate the directory split, if any. Setting RAM foundServer and defaultDir foundWifiServer = this.checkDefaultDir(foundWifiServer); } //Early out: if((foundWifiServer == null)&&(foundRemoteServer == null)) { cb('No known server.'); return; } //Now try the wifi server as the first option to use if it exists: if((foundWifiServer)&&(foundWifiServer != null)) { //Ping the wifi server errorThis.notify('Trying to connect to the wifi server..'); //Timeout after 5 secs for the following ping var scanning = setTimeout(function() { errorThis.notify('Timeout finding your wifi server. Trying remote server..'); //Else can't communicate with the wifi server at this time. //Try the remote server if((foundRemoteServer)&&(foundRemoteServer != null)) { var scanning = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.setItem("usingServer", null); cb('No server found'); }, 4000); errorThis.get(foundRemoteServer, function(url, resp) { //Success, got a connection to the remote server clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundRemoteServer); cb(null); }); } else { //Only wifi existed localStorage.setItem("usingServer", null); cb('No server found'); } }, 2000); //Ping the wifi server errorThis.get(foundWifiServer, function(url, resp) { //Success, got a connection to the wifi clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundWifiServer); cb(null); //Success found server }); } else { //OK - no wifi option - go straight to the remote server //Try the remote server errorThis.notify('Trying to connect to the remote server....'); var scanning = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.setItem("usingServer", null); cb('No server found'); }, 4000); _this.get(foundRemoteServer, function(url, resp) { //Success, got a connection to the remote server clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundRemoteServer); cb(null); }); } }, /* Settings Functions */ /* localStorage.clear(); this.foundServer = null; this.defaultDir = null; this.overrideServer = null; document.getElementById("override").value = ""; alert("Cleared default server."); return false; */ openSettings: function() { //Open the settings screen var html = this.listServers(); document.getElementById("settings").innerHTML = html; document.getElementById("settings-popup").style.display = "block"; }, closeSettings: function() { //Close the settings screen document.getElementById("settings-popup").style.display = "none"; }, listServers: function() { //List the available servers var settings = this.getArrayLocalStorage("settings"); if(settings) { var html = "<ons-list><ons-list-header>Select a PC to use now:</ons-list-header>"; //Convert the array into html for(var cnt=0; cnt< settings.length; cnt++) { html = html + "<ons-list-item><ons-list-item onclick='app.setServer(" + cnt + ");'>" + settings[cnt].name + "</ons-list-item><div class='right'><ons-icon icon='md-delete' onclick='app.deleteServer(" + cnt + ");'></ons-icon></div></ons-list-item>"; } html = html + "</ons-list>"; } else { var html = "<ons-list><ons-list-header>PCs Stored</ons-list-header>"; var html = html + "<ons-list-item><ons-list-item>Default</ons-list-item><div class='right'><ons-icon icon='md-delete'style='color:#AAA></ons-icon></div></ons-list-item>"; html = html + "</ons-list>"; } return html; }, setServer: function(serverId) { //Set the server to the input server id var settings = this.getArrayLocalStorage("settings"); var currentRemoteServer = settings[serverId].currentRemoteServer; var currentWifiServer = settings[serverId].currentWifiServer; localStorage.setItem("usingServer", null); //reset the currently used server //Save the current server TODO: null handling here? localStorage.setItem("currentRemoteServer", currentRemoteServer); localStorage.setItem("currentWifiServer", currentWifiServer); navigator.notification.alert("Switched to: " + settings[serverId].name, function() {}, "Changing PC"); //Now refresh the current server display document.getElementById("currentPC").innerHTML = settings[serverId].name; this.closeSettings(); return false; }, newServer: function() { //Create a new server. //This is actually effectively resetting, and we will allow the normal functions to input a new one localStorage.setItem("usingServer", null); //Remove the current one var exists = localStorage.getItem("currentRemoteServer"); if((exists)&&(exists != null)) { localStorage.removeItem("currentRemoteServer"); } var exists = localStorage.getItem("currentWifiServer"); if((exists)&&(exists != null)) { localStorage.removeItem("currentWifiServer"); } //Ask for a name of the current Server: navigator.notification.prompt( 'Please enter a name for this PC', // message this.saveServerName, // callback to invoke 'PC Name', // title ['Ok','Cancel'], // buttonLabels 'Main' // defaultText ); }, deleteServer: function(serverId) { //Delete an existing server this.myServerId = serverId; navigator.notification.confirm( 'Are you sure? This PC will be removed from memory.', // message function(buttonIndex) { if(buttonIndex == 1) { var settings = errorThis.getArrayLocalStorage("settings"); if((settings == null)|| (settings == '')) { //Nothing to delete } else { settings.splice(errorThis.myServerId, 1); //Remove the entry entirely from array errorThis.setArrayLocalStorage("settings", settings); } errorThis.openSettings(); //refresh } }, // callback to invoke 'Remove PC', // title ['Ok','Exit'] // buttonLabels ); }, saveServerName: function(results) { //Save the server with a name - but since this is new, //Get existing settings array if(results.buttonIndex == 1) { //Clicked on 'Ok' localStorage.setItem("currentServerName", results.input1); //Now refresh the current server display document.getElementById("currentPC").innerHTML = results.input1; errorThis.closeSettings(); return; } else { //Clicked on 'Exit'. Do nothing. return; } }, displayServerName: function() { //Call this during initialisation on app startup var currentServerName = localStorage.getItem("currentServerName"); if((currentServerName) && (currentServerName != null)) { //Now refresh the current server display document.getElementById("currentPC").innerHTML = currentServerName; } else { document.getElementById("currentPC").innerHTML = ""; } }, saveServer: function() { //Run this after a successful upload var currentServerName = localStorage.getItem("currentServerName"); var currentRemoteServer = localStorage.getItem("currentRemoteServer"); var currentWifiServer = localStorage.getItem("currentWifiServer"); if((!currentServerName) ||(currentServerName == null)) currentServerName = "Default"; if((!currentRemoteServer) ||(currentRemoteServer == null)) currentRemoteServer = null; if((!currentWifiServer) ||(currentWifiServer == null)) currentWifiServer = null; var settings = errorThis.getArrayLocalStorage("settings"); //Create a new entry - which will be blank to being with var newSetting = { "name": currentServerName, //As input by the user "currentRemoteServer": currentRemoteServer, "currentWifiServer": currentWifiServer }; if((settings == null)|| (settings == '')) { //Creating an array for the first time var settings = []; settings.push(newSetting); //Save back to the array } else { //Check if we are writing over the existing entries var writeOver = false; for(cnt = 0; cnt< settings.length; cnt++) { if(settings[cnt].name == currentServerName) { writeOver = true; settings[cnt] = newSetting; } } if(writeOver == false) { settings.push(newSetting); //Save back to the array } } //Save back to the persistent settings errorThis.setArrayLocalStorage("settings", settings); return; }, //Array storage for app permanent settings (see http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/) setArrayLocalStorage: function(mykey, myobj) { return localStorage.setItem(mykey, JSON.stringify(myobj)); }, getArrayLocalStorage: function(mykey) { return JSON.parse(localStorage.getItem(mykey)); } };
reset properly
www/js/index.js
reset properly
<ide><path>ww/js/index.js <ide> //Clear off <ide> var foundRemoteServer = null; <ide> var foundWifiServer = null; <add> var usingServer = null; <ide> <ide> //Early out <del> var usingServer = localStorage.getItem("usingServer"); <add> usingServer = localStorage.getItem("usingServer"); <add> <ide> if((usingServer)&&(usingServer != null)) { <add> alert("usingServer=" + usingServer); <ide> cb(null); <ide> return; <ide> <ide> } <ide> <ide> <del> var foundRemoteServer = localStorage.getItem("currentRemoteServer"); <del> var foundWifiServer = localStorage.getItem("currentWifiServer"); <add> foundRemoteServer = localStorage.getItem("currentRemoteServer"); <add> foundWifiServer = localStorage.getItem("currentWifiServer"); <ide> <ide> if((foundRemoteServer)&&(foundRemoteServer != null)) { <ide> //Already found a remote server
Java
mit
a9605415da2153729f375cefa155230d402ab29a
0
sigopt/sigopt-java,sigopt/sigopt-java
package com.sigopt.example; public class Franke { public Franke() { } // http://www.sfu.ca/~ssurjano/franke2d.html public static Double evaluate(double x, double y) { return ( 0.75 * Math.exp(-Math.pow((9 * x - 2), 2.0) / 4.0 - Math.pow((9 * y - 2), 2.0) / 4.0) + 0.75 * Math.exp(-Math.pow((9 * x + 1), 2.0) / 49.0 - (9 * y + 1) / 10.0) + 0.5 * Math.exp(-Math.pow((9 * x - 7), 2.0) / 4.0 - Math.pow((9 * y - 3), 2.0) / 4.0) - 0.2 * Math.exp(-Math.pow((9 * x - 4), 2.0) - Math.pow((9 * y - 7), 2.0)) ); } }
src/main/java/com/sigopt/example/Franke.java
package com.sigopt.example; public class Franke { public Franke() { } public static Double evaluate(double x, double y) { return ( 0.75 * Math.exp(-Math.pow((9 * x - 2), 2.0) / 4.0 - Math.pow((9 * y - 2), 2.0) / 4.0) + 0.75 * Math.exp(-Math.pow((9 * x + 1), 2.0) / 49.0 - (9 * y + 1) / 10.0) + 0.5 * Math.exp(-Math.pow((9 * x - 7), 2.0) / 4.0 - Math.pow((9 * y - 3), 2.0) / 4.0) - 0.2 * Math.exp(-Math.pow((9 * x - 4), 2.0) - Math.pow((9 * y - 7), 2.0)) ); } }
comment
src/main/java/com/sigopt/example/Franke.java
comment
<ide><path>rc/main/java/com/sigopt/example/Franke.java <ide> public Franke() { <ide> } <ide> <add> // http://www.sfu.ca/~ssurjano/franke2d.html <ide> public static Double evaluate(double x, double y) { <ide> return ( <ide> 0.75 * Math.exp(-Math.pow((9 * x - 2), 2.0) / 4.0 - Math.pow((9 * y - 2), 2.0) / 4.0) +
JavaScript
mpl-2.0
3ff22084b1701662c18119e5389a4d45e7237714
0
mozilla/webmaker-app-cordova,mozilla/webmaker-app-cordova
#!/usr/bin/env node var fs = require('fs-extra'); var async = require('async'); var exec = require('child_process').exec; var colors = require('colors'); function doExec(text) { return function (done) { exec(text, function (err, stdout, stderr) { if (stdout) console.log(stdout.grey); if (stderr) console.log(stderr.red); done(err); }); }; } // Let's get started console.log('starting build...'.bgMagenta); // Copy assets to www require('./copy-assets'); // Clean fs.removeSync('./platforms'); fs.removeSync('./plugins'); async.series([ doExec('cordova platform add android'), doExec('cordova platform add firefoxos'), doExec('cordova platform add ios'), doExec('cordova plugin add org.apache.cordova.contacts'), // bug fix in progress for com.rjfun.cordova.sms doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-sms.git'), doExec('cordova plugin add org.apache.cordova.camera') ], function (err) { // Done! if (err) return console.log('finished build, but there were errors!'.bgMagenta); console.log('finished build with no errors.'.bgMagenta); });
scripts/build.js
#!/usr/bin/env node var fs = require('fs-extra'); var async = require('async'); var exec = require('child_process').exec; var colors = require('colors'); function doExec(text) { return function (done) { exec(text, function (err, stdout, stderr) { if (stdout) console.log(stdout.grey); if (stderr) console.log(stderr.red); done(err); }); }; } // Let's get started console.log('starting build...'.bgMagenta); // Copy assets to www require('./copy-assets'); // Clean fs.removeSync('./platforms'); fs.removeSync('./plugins'); async.series([ doExec('cordova platform add android'), doExec('cordova platform add firefoxos'), doExec('cordova platform add ios'), doExec('cordova plugin add org.apache.cordova.contacts'), // bug fix in progress for com.rjfun.cordova.sms doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-sms.git') ], function (err) { // Done! if (err) return console.log('finished build, but there were errors!'.bgMagenta); console.log('finished build with no errors.'.bgMagenta); });
add photo plugin
scripts/build.js
add photo plugin
<ide><path>cripts/build.js <ide> doExec('cordova platform add ios'), <ide> doExec('cordova plugin add org.apache.cordova.contacts'), <ide> // bug fix in progress for com.rjfun.cordova.sms <del> doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-sms.git') <add> doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-sms.git'), <add> doExec('cordova plugin add org.apache.cordova.camera') <ide> ], function (err) { <ide> // Done! <ide> if (err) return console.log('finished build, but there were errors!'.bgMagenta);
Java
apache-2.0
79ed705cbb37d5ed7c12bebf98776c65e33b2b74
0
sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,tharindu1st/carbon-apimgt,harsha89/carbon-apimgt,pubudu538/carbon-apimgt,prasa7/carbon-apimgt,nuwand/carbon-apimgt,ruks/carbon-apimgt,praminda/carbon-apimgt,Rajith90/carbon-apimgt,tharindu1st/carbon-apimgt,fazlan-nazeem/carbon-apimgt,praminda/carbon-apimgt,ruks/carbon-apimgt,ruks/carbon-apimgt,jaadds/carbon-apimgt,prasa7/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Rajith90/carbon-apimgt,jaadds/carbon-apimgt,Rajith90/carbon-apimgt,wso2/carbon-apimgt,uvindra/carbon-apimgt,nuwand/carbon-apimgt,malinthaprasan/carbon-apimgt,fazlan-nazeem/carbon-apimgt,pubudu538/carbon-apimgt,ruks/carbon-apimgt,isharac/carbon-apimgt,uvindra/carbon-apimgt,bhathiya/carbon-apimgt,chamilaadhi/carbon-apimgt,uvindra/carbon-apimgt,bhathiya/carbon-apimgt,isharac/carbon-apimgt,praminda/carbon-apimgt,jaadds/carbon-apimgt,wso2/carbon-apimgt,pubudu538/carbon-apimgt,malinthaprasan/carbon-apimgt,tharindu1st/carbon-apimgt,chamindias/carbon-apimgt,harsha89/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharindu1st/carbon-apimgt,jaadds/carbon-apimgt,bhathiya/carbon-apimgt,malinthaprasan/carbon-apimgt,wso2/carbon-apimgt,nuwand/carbon-apimgt,chamindias/carbon-apimgt,fazlan-nazeem/carbon-apimgt,nuwand/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharikaGitHub/carbon-apimgt,bhathiya/carbon-apimgt,chamindias/carbon-apimgt,malinthaprasan/carbon-apimgt,chamilaadhi/carbon-apimgt,prasa7/carbon-apimgt,harsha89/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamindias/carbon-apimgt,pubudu538/carbon-apimgt,uvindra/carbon-apimgt,isharac/carbon-apimgt,Rajith90/carbon-apimgt,chamilaadhi/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,wso2/carbon-apimgt,harsha89/carbon-apimgt,tharikaGitHub/carbon-apimgt,fazlan-nazeem/carbon-apimgt,prasa7/carbon-apimgt,isharac/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.impl.workflow; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.AxisFault; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl; import org.wso2.carbon.apimgt.impl.TestUtils; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.SelfSignUpUtil; import org.wso2.carbon.apimgt.impl.workflow.events.APIMgtWorkflowDataPublisher; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.user.mgt.stub.UserAdminStub; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import javax.xml.stream.XMLStreamException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Map; /** * UserSignUpWSWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ServiceReferenceHolder.class, UserSignUpWSWorkflowExecutor.class, ApiMgtDAO.class, APIUtil.class, AXIOMUtil.class, SelfSignUpUtil.class, CarbonUtils.class}) public class UserSignUpWSWorkflowExecutorTest { private UserSignUpWSWorkflowExecutor userSignUpWSWorkflowExecutor; private ServiceClient serviceClient; private ApiMgtDAO apiMgtDAO; private WorkflowDTO workflowDTO; private APIManagerConfiguration apiManagerConfiguration; private UserAdminStub userAdminStub; private UserStoreManager userStoreManager; private String callBackURL = "https://localhost:8243/services/WorkflowCallbackService"; private String tenantDomain = "carbon.super"; private String externalWFReference = UUIDGenerator.generateUUID(); private String username = "admin"; private String password = "admin"; private String signUpRole = "subscriber"; private int tenantID = -1234; private String testUsername = "PRIMARY/testuser"; @Before public void init() throws Exception { ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder(); ConfigurationContextService configurationContextService = Mockito.mock(ConfigurationContextService.class); ConfigurationContext configurationContext = Mockito.mock(ConfigurationContext.class); RealmService realmService = Mockito.mock(RealmService.class); UserRealm userRealm = Mockito.mock(UserRealm.class); userStoreManager = Mockito.mock(UserStoreManager.class); userAdminStub = Mockito.mock(UserAdminStub.class); TenantManager tenantManager = Mockito.mock(TenantManager.class); apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); serviceClient = Mockito.mock(ServiceClient.class); APIManagerConfigurationService apiManagerConfigurationService = new APIManagerConfigurationServiceImpl (apiManagerConfiguration); PowerMockito.mockStatic(SelfSignUpUtil.class); PowerMockito.mockStatic(CarbonUtils.class); PowerMockito.mockStatic(APIUtil.class); PowerMockito.when(APIUtil.isAnalyticsEnabled()).thenReturn(true); PowerMockito.doNothing().when(CarbonUtils.class, "setBasicAccessSecurityHeaders", Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), (ServiceClient) Mockito.anyObject()); PowerMockito.when(serviceReferenceHolder.getContextService()).thenReturn(configurationContextService); PowerMockito.when(configurationContextService.getClientConfigContext()).thenReturn(configurationContext); PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn (apiManagerConfigurationService); PowerMockito.whenNew(ServiceClient.class).withAnyArguments().thenReturn(serviceClient); Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService); Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager); Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID); Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID); Mockito.when(realmService.getTenantUserRealm(tenantID)).thenReturn(userRealm); Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); APIMgtWorkflowDataPublisher apiMgtWorkflowDataPublisher = Mockito.mock(APIMgtWorkflowDataPublisher.class); PowerMockito.whenNew(APIMgtWorkflowDataPublisher.class).withNoArguments().thenReturn (apiMgtWorkflowDataPublisher); PowerMockito.whenNew(UserAdminStub.class).withAnyArguments().thenReturn(userAdminStub); apiMgtDAO = TestUtils.getApiMgtDAO(); userSignUpWSWorkflowExecutor = new UserSignUpWSWorkflowExecutor(); workflowDTO = new WorkflowDTO(); workflowDTO.setCallbackUrl(callBackURL); workflowDTO.setTenantDomain(tenantDomain); workflowDTO.setExternalWorkflowReference(externalWFReference); workflowDTO.setWorkflowReference(testUsername + "@carbon.super"); } @Test public void testRetrievingWorkflowType() { Assert.assertEquals(userSignUpWSWorkflowExecutor.getWorkflowType(), "AM_USER_SIGNUP"); } @Test public void testExecutingUserSignUpWorkflow() throws Exception { userSignUpWSWorkflowExecutor.setUsername(username); userSignUpWSWorkflowExecutor.setPassword(password.toCharArray()); userSignUpWSWorkflowExecutor.setContentType("text/xml"); PowerMockito.doNothing().when(apiMgtDAO).addWorkflowEntry(workflowDTO); try { Assert.assertNotNull(userSignUpWSWorkflowExecutor.execute(workflowDTO)); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while executing user sign up workflow"); } } @Test public void testFailureToExecuteUserSignUpWSWorkflow() throws Exception { userSignUpWSWorkflowExecutor.setUsername(username); userSignUpWSWorkflowExecutor.setPassword(password.toCharArray()); PowerMockito.doNothing().when(apiMgtDAO).addWorkflowEntry(workflowDTO); //Test failure to execute user sign up workflow, when APIManagementException has been thrown while persisting // workflow entry in database PowerMockito.doThrow(new APIManagementException("Error while persisting workflow")).when(apiMgtDAO) .addWorkflowEntry(workflowDTO); try { userSignUpWSWorkflowExecutor.execute(workflowDTO); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while persisting workflow"); } //Test failure to execute user sign up workflow, when AxisFault has been thrown while sending the message out PowerMockito.doThrow(new AxisFault("Error sending out message")).when(serviceClient).fireAndForget( (OMElement) Mockito.anyObject()); try { userSignUpWSWorkflowExecutor.execute(workflowDTO); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error sending out message"); } //Test failure to execute user sign up workflow, when XMLStreamException has been thrown while building payload PowerMockito.mockStatic(AXIOMUtil.class); PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " + "converting String to OMElement")); try { userSignUpWSWorkflowExecutor.execute(workflowDTO); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error converting String to OMElement"); } } @Test public void testCompletingUserSignUpWorkflowApprovedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod(); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); try { Assert.assertNotNull(userSignUpWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while completing 'APPROVED' user sign up workflow"); } } @Test public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod(); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); //Test failure to complete workflow execution when AuthManager server url is not configured try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when auth manager url is not configured"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Can't connect to the authentication manager. serverUrl is missing"); } //Set AuthManager endpoint url PowerMockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); //Test failure to complete workflow execution when tenant admin username is not found try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when admin username is not found"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Can't connect to the authentication manager. adminUsername is " + "missing"); } //Test failure to complete workflow execution when tenant admin password is not found userRegistrationConfigDTO.setAdminUserName(username); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been occurred when admin password is not found"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Can't connect to the authentication manager. adminPassword is " + "missing"); } //Set tenant admin credentials userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); //Test failure to complete workflow execution, when error has been occurred while updating user with signup roles Mockito.doThrow(new RemoteException()).when(userAdminStub).updateRolesOfUser(Mockito.anyString(), new String[]{Mockito.anyString()}); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while assigning role to user"); } //Test failure to complete workflow execution, when sign up roles are not existing in user realm Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while assigning role to user"); } //Test failure to complete workflow execution, when error has been occurred while retrieving signup config PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException ("Error occurred while retrieving signup configuration")); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration"); } } @Test public void testCompletingUserSignUpWorkflowRejectedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); try { Assert.assertNotNull(userSignUpWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while completing 'REJECTED' user sign up workflow"); } } @Test public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); Mockito.doThrow(new AxisFault("Error occurred while deleting user")).when(userAdminStub).deleteUser(Mockito .anyString()); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when user deletion failed"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while deleting the user"); } } @Test public void testCleaningUpPendingTasks() { try { userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while cleaning up pending tasks"); } } @Test public void testFailuresToCleanUpPendingTasks() throws AxisFault, XMLStreamException { //Test failure to clean up pending tasks when AxisFault has been thrown while sending the message out PowerMockito.doThrow(new AxisFault("Error sending out message")).when(serviceClient).fireAndForget( (OMElement) Mockito.anyObject()); try { userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertTrue(e.getMessage().contains("Error sending out message")); } //Test failure to clean up pending tasks, when XMLStreamException has been thrown while building payload PowerMockito.mockStatic(AXIOMUtil.class); PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " + "converting String to OMElement")); try { userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertTrue(e.getMessage().contains("Error converting String to OMElement")); } } }
components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.impl.workflow; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.AxisFault; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl; import org.wso2.carbon.apimgt.impl.TestUtils; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.SelfSignUpUtil; import org.wso2.carbon.apimgt.impl.workflow.events.APIMgtWorkflowDataPublisher; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.user.mgt.stub.UserAdminStub; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import javax.xml.stream.XMLStreamException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Map; /** * UserSignUpWSWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ServiceReferenceHolder.class, UserSignUpWSWorkflowExecutor.class, ApiMgtDAO.class, APIUtil.class, AXIOMUtil.class, SelfSignUpUtil.class, CarbonUtils.class}) public class UserSignUpWSWorkflowExecutorTest { private UserSignUpWSWorkflowExecutor userSignUpWSWorkflowExecutor; private ServiceClient serviceClient; private ApiMgtDAO apiMgtDAO; private WorkflowDTO workflowDTO; private APIManagerConfiguration apiManagerConfiguration; private UserAdminStub userAdminStub; private UserStoreManager userStoreManager; private String callBackURL = "https://localhost:8243/services/WorkflowCallbackService"; private String tenantDomain = "carbon.super"; private String externalWFReference = UUIDGenerator.generateUUID(); private String username = "admin"; private String password = "admin"; private String signUpRole = "subscriber"; private int tenantID = -1234; private String testUsername = "PRIMARY/testuser"; @Before public void init() throws Exception { ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder(); ConfigurationContextService configurationContextService = Mockito.mock(ConfigurationContextService.class); ConfigurationContext configurationContext = Mockito.mock(ConfigurationContext.class); RealmService realmService = Mockito.mock(RealmService.class); UserRealm userRealm = Mockito.mock(UserRealm.class); userStoreManager = Mockito.mock(UserStoreManager.class); userAdminStub = Mockito.mock(UserAdminStub.class); TenantManager tenantManager = Mockito.mock(TenantManager.class); apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); serviceClient = Mockito.mock(ServiceClient.class); APIManagerConfigurationService apiManagerConfigurationService = new APIManagerConfigurationServiceImpl (apiManagerConfiguration); PowerMockito.mockStatic(SelfSignUpUtil.class); PowerMockito.mockStatic(CarbonUtils.class); PowerMockito.mockStatic(APIUtil.class); PowerMockito.when(APIUtil.isAnalyticsEnabled()).thenReturn(true); PowerMockito.doNothing().when(CarbonUtils.class, "setBasicAccessSecurityHeaders", Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), (ServiceClient) Mockito.anyObject()); PowerMockito.when(serviceReferenceHolder.getContextService()).thenReturn(configurationContextService); PowerMockito.when(configurationContextService.getClientConfigContext()).thenReturn(configurationContext); PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn (apiManagerConfigurationService); PowerMockito.whenNew(ServiceClient.class).withAnyArguments().thenReturn(serviceClient); Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService); Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager); Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID); Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID); Mockito.when(realmService.getTenantUserRealm(tenantID)).thenReturn(userRealm); Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); APIMgtWorkflowDataPublisher apiMgtWorkflowDataPublisher = Mockito.mock(APIMgtWorkflowDataPublisher.class); PowerMockito.whenNew(APIMgtWorkflowDataPublisher.class).withNoArguments().thenReturn (apiMgtWorkflowDataPublisher); PowerMockito.whenNew(UserAdminStub.class).withAnyArguments().thenReturn(userAdminStub); apiMgtDAO = TestUtils.getApiMgtDAO(); userSignUpWSWorkflowExecutor = new UserSignUpWSWorkflowExecutor(); workflowDTO = new WorkflowDTO(); workflowDTO.setCallbackUrl(callBackURL); workflowDTO.setTenantDomain(tenantDomain); workflowDTO.setExternalWorkflowReference(externalWFReference); workflowDTO.setWorkflowReference(testUsername + "@carbon.super"); } @Test public void testRetrievingWorkflowType() { Assert.assertEquals(userSignUpWSWorkflowExecutor.getWorkflowType(), "AM_USER_SIGNUP"); } @Test public void testExecutingUserSignUpWorkflow() throws Exception { userSignUpWSWorkflowExecutor.setUsername(username); userSignUpWSWorkflowExecutor.setPassword(password.toCharArray()); userSignUpWSWorkflowExecutor.setContentType("text/xml"); PowerMockito.doNothing().when(apiMgtDAO).addWorkflowEntry(workflowDTO); try { Assert.assertNotNull(userSignUpWSWorkflowExecutor.execute(workflowDTO)); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while executing user sign up workflow"); } } @Test public void testFailureToExecuteUserSignUpWSWorkflow() throws Exception { userSignUpWSWorkflowExecutor.setUsername(username); userSignUpWSWorkflowExecutor.setPassword(password.toCharArray()); PowerMockito.doNothing().when(apiMgtDAO).addWorkflowEntry(workflowDTO); //Test failure to execute user sign up workflow, when APIManagementException has been thrown while persisting // workflow entry in database PowerMockito.doThrow(new APIManagementException("Error while persisting workflow")).when(apiMgtDAO) .addWorkflowEntry(workflowDTO); try { userSignUpWSWorkflowExecutor.execute(workflowDTO); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while persisting workflow"); } //Test failure to execute user sign up workflow, when AxisFault has been thrown while sending the message out PowerMockito.doThrow(new AxisFault("Error sending out message")).when(serviceClient).fireAndForget( (OMElement) Mockito.anyObject()); try { userSignUpWSWorkflowExecutor.execute(workflowDTO); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error sending out message"); } //Test failure to execute user sign up workflow, when XMLStreamException has been thrown while building payload PowerMockito.mockStatic(AXIOMUtil.class); PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " + "converting String to OMElement")); try { userSignUpWSWorkflowExecutor.execute(workflowDTO); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error converting String to OMElement"); } } @Test public void testCompletingUserSignUpWorkflowApprovedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod(); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); try { Assert.assertNotNull(userSignUpWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while completing 'APPROVED' user sign up workflow"); } } @Test public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod(); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); //Test failure to complete workflow execution when AuthManager server url is not configured try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when auth manager url is not configured"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Can't connect to the authentication manager. serverUrl is missing"); } //Set AuthManager endpoint url PowerMockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); //Test failure to complete workflow execution when tenant admin username is not found try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when admin username is not found"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Can't connect to the authentication manager. adminUsername is " + "missing"); } //Test failure to complete workflow execution when tenant admin password is not found userRegistrationConfigDTO.setAdminUserName(username); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been occurred when admin password is not found"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Can't connect to the authentication manager. adminPassword is " + "missing"); } //Set tenant admin credentials userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); //Test failure to complete workflow execution, when error has been occurred while updating user with signup roles Mockito.doThrow(new RemoteException()).when(userAdminStub).updateRolesOfUser(Mockito.anyString(), new String[]{Mockito.anyString()}); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been occ while signup user role update failed"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while assigning role to user"); } //Test failure to complete workflow execution, when sign up roles are not existing in user realm Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while assigning role to user"); } //Test failure to complete workflow execution, when error has been occurred while retrieving signup config PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException ("Error occurred while retrieving signup configuration")); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration"); } } @Test public void testCompletingUserSignUpWorkflowRejectedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); try { Assert.assertNotNull(userSignUpWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { Assert.fail("Unexpected WorkflowException occurred while completing 'REJECTED' user sign up workflow"); } } @Test public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exception { Map<String, Boolean> roleMap = new HashMap<String, Boolean>(); roleMap.put(signUpRole, false); UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO(); userRegistrationConfigDTO.setAdminUserName("admin"); userRegistrationConfigDTO.setAdminPassword("admin"); userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.AUTH_MANAGER_URL)).thenReturn ("https://localhost:9443/services/"); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); Mockito.doThrow(new AxisFault("Error occurred while deleting user")).when(userAdminStub).deleteUser(Mockito .anyString()); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when user deletion failed"); } catch (WorkflowException e) { Assert.assertEquals(e.getMessage(), "Error while deleting the user"); } } @Test public void testCleaningUpPendingTasks(){ try{ userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); }catch (WorkflowException e){ Assert.fail("Unexpected WorkflowException occurred while cleaning up pending tasks"); } } @Test public void testFailuresToCleanUpPendingTasks() throws AxisFault, XMLStreamException { //Test failure to clean up pending tasks when AxisFault has been thrown while sending the message out PowerMockito.doThrow(new AxisFault("Error sending out message")).when(serviceClient).fireAndForget( (OMElement) Mockito.anyObject()); try{ userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); }catch (WorkflowException e){ Assert.assertTrue(e.getMessage().contains("Error sending out message")); } //Test failure to clean up pending tasks, when XMLStreamException has been thrown while building payload PowerMockito.mockStatic(AXIOMUtil.class); PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " + "converting String to OMElement")); try { userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); } catch (WorkflowException e) { Assert.assertTrue(e.getMessage().contains("Error converting String to OMElement")); } } }
Fix assert fail messages
components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java
Fix assert fail messages
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java <ide> String[]{Mockito.anyString()}); <ide> try { <ide> userSignUpWSWorkflowExecutor.complete(workflowDTO); <del> Assert.fail("Expected WorkflowException has not been occ while signup user role update failed"); <add> Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed"); <ide> } catch (WorkflowException e) { <ide> Assert.assertEquals(e.getMessage(), "Error while assigning role to user"); <ide> } <ide> Mockito.doThrow(new AxisFault("Error occurred while deleting user")).when(userAdminStub).deleteUser(Mockito <ide> .anyString()); <ide> try { <del> userSignUpWSWorkflowExecutor.complete(workflowDTO); <add> userSignUpWSWorkflowExecutor.complete(workflowDTO); <ide> Assert.fail("Expected WorkflowException has not been thrown when user deletion failed"); <ide> } catch (WorkflowException e) { <ide> Assert.assertEquals(e.getMessage(), "Error while deleting the user"); <ide> } <ide> <ide> @Test <del> public void testCleaningUpPendingTasks(){ <del> try{ <del> userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); <del> }catch (WorkflowException e){ <add> public void testCleaningUpPendingTasks() { <add> try { <add> userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); <add> } catch (WorkflowException e) { <ide> Assert.fail("Unexpected WorkflowException occurred while cleaning up pending tasks"); <ide> } <ide> } <ide> //Test failure to clean up pending tasks when AxisFault has been thrown while sending the message out <ide> PowerMockito.doThrow(new AxisFault("Error sending out message")).when(serviceClient).fireAndForget( <ide> (OMElement) Mockito.anyObject()); <del> try{ <add> try { <ide> userSignUpWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getWorkflowReference()); <ide> Assert.fail("Expected WorkflowException has not occurred while executing user sign up workflow"); <del> }catch (WorkflowException e){ <add> } catch (WorkflowException e) { <ide> Assert.assertTrue(e.getMessage().contains("Error sending out message")); <ide> } <ide> <ide> } catch (WorkflowException e) { <ide> Assert.assertTrue(e.getMessage().contains("Error converting String to OMElement")); <ide> } <del> <del> <ide> } <ide> } <ide>
Java
mpl-2.0
f463173aa6d7df4d8e4a6d6ad8c9afdbb3bbae4c
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************ * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TestStream.java,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-07-13 09:15:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ package org.openoffice.xmerge.xmergebridge; import com.sun.star.io.XInputStream; import com.sun.star.io.XOutputStream; import com.sun.star.io.NotConnectedException; import com.sun.star.io.BufferSizeExceededException; import com.sun.star.io.IOException; class TestStream implements XInputStream, XOutputStream { /** An array of bytes to be returned when the XInputStream read() method * is called */ private byte [] isBytes; /** * A backup buffer where data sent to the XOutputStream write() method * is placed, used for verification purposes. */ private byte [] bytesBak; /** * Maximum length of data returned by XInputStream read(). */ private static int inputLength = 256; /** * Keeps track of how far into the XInputStream has been read. */ private int currentLoc; /** * Constructor. Sets up the isBytes array. */ public TestStream() { currentLoc = 0; isBytes = new byte [inputLength]; for (int i=0; i < inputLength; i++) { isBytes[i] = (byte)i; } } /* XInputStream interfaces */ public int readBytes(byte[][] aData, int toRead) throws NotConnectedException, BufferSizeExceededException, IOException { int checkSize = inputLength - currentLoc; if (checkSize <= 0) { return -1; } else if (toRead > checkSize) { System.arraycopy(isBytes, currentLoc, aData[0], 0, checkSize); currentLoc += checkSize; return checkSize; } else { System.arraycopy(isBytes, currentLoc, aData[0], 0, toRead); currentLoc += toRead; return toRead; } } public int readSomeBytes(byte[][] aData, int nMaxBytesToRead) throws NotConnectedException, BufferSizeExceededException, IOException { return(readBytes(aData, nMaxBytesToRead)); } public void skipBytes(int nBytesToSkip) throws NotConnectedException, BufferSizeExceededException, IOException { currentLoc += nBytesToSkip; } public int available() throws NotConnectedException, IOException { int checkSize = inputLength - currentLoc; if (checkSize < 0) { return -1; } else { return checkSize; } } public void closeInput() throws NotConnectedException, IOException { // Set currentLoc to the max, so read calls will return -1. // currentLoc = inputLength + 1; System.out.println("Closed XInputStream."); } /* XOutputStream Interfaces */ public void writeBytes(byte [] aData) throws NotConnectedException, BufferSizeExceededException, IOException { // Set backup array, used for verification purposes. // bytesBak = aData; System.out.println("Wrote out the following data to XOutputStream:"); for (int i=0; i < aData.length; i++) { System.out.println(" <" + aData[i] + ">"); } } public void flush() throws NotConnectedException, BufferSizeExceededException, IOException { System.out.println("Flushed XOutputStream."); } public void closeOutput() throws NotConnectedException, BufferSizeExceededException, IOException { System.out.println("Closed XOutputStream."); } /** * Returns the last data passed into the write function, used for * verification purposes. */ public byte [] getBytesBak() { return bytesBak; } public static void main(String args[]) { System.out.println("\nInputStream Test:"); System.out.println("Testing read(), bytes value 1-256:"); TestStream ts = new TestStream(); XInputStreamToInputStreamAdapter is = new XInputStreamToInputStreamAdapter(ts); int rc = 0, avail; boolean testStatus = true; int cnt = 0; do { try { rc = is.read(); avail = is.available(); System.out.println(" Read value <" + rc + ">, avail <" + avail + ">"); if (cnt < inputLength && rc != cnt) { System.out.println("Read wrong value <" + rc + ">, expecting <" + cnt + ">"); testStatus = false; } cnt++; } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nInputStream Test:"); System.out.println("Testing read(), bytes value 1-256 with skips of 3 bytes:"); ts = new TestStream(); is = new XInputStreamToInputStreamAdapter(ts); cnt = 0; do { try { rc = is.read(); avail = is.available(); System.out.println(" Read value <" + rc + ">, avail <" + avail + ">"); is.skip(3); if (cnt < inputLength && rc != cnt) { System.out.println("Read wrong value <" + rc + ">, expecting <" + cnt + ">"); testStatus = false; } cnt += 4; } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nInputStream Test:"); System.out.println("Testing read() in chunks of 5 bytes."); byte [] bi1 = new byte [5]; ts = new TestStream(); is = new XInputStreamToInputStreamAdapter(ts); cnt = 0; do { try { rc = is.read(bi1); avail = is.available(); System.out.print("Read value <"); for (int i=0; i < bi1.length; i++) { if (i == (bi1.length - 1)) { System.out.print((int)bi1[i]); } else { System.out.print((int)bi1[i] + ","); } if ((cnt) < inputLength && bi1[i] != (byte)cnt) { System.out.println("\nRead wrong value <" + (int)bi1[i] + ">, expecting <" + (cnt) + ">"); testStatus = false; } cnt++; } System.out.print("> read rc <" + rc + ">, avail <" + avail + ">\n"); } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nInputStream Test:"); System.out.println("Testing read() in chunks of 6 bytes, offset=2, length=3."); byte [] bi2 = new byte [6]; ts = new TestStream(); is = new XInputStreamToInputStreamAdapter(ts); cnt = 0; int offset = 2; int length = 3; do { try { rc = is.read(bi2, offset, length); avail = is.available(); System.out.print("Read value <"); for (int i=0; i < bi2.length; i++) { if (i == (bi2.length - 1)) { System.out.print((int)bi2[i]); } else { System.out.print((int)bi2[i] + ","); } if (cnt < inputLength) { if (i < offset || i >= (offset + length)) { // Check values that should stay 0 // if ((int)bi2[i] != 0) { System.out.println("\nRead wrong value <" + (int)bi2[i] + ">, expecting <0>"); testStatus = false; } } else if (bi2[i] != (byte)cnt) { // Check actually read values. // System.out.println("\nRead wrong value <" + (int)bi2[i] + ">, expecting <" + cnt + ">"); testStatus = false; } else { cnt++; } } } System.out.print("> read rc <" + rc + ">, avail <" + avail + ">\n"); } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nOutputStream Test:"); System.out.println("Testing write() and flush()"); ts = new TestStream(); XOutputStreamToOutputStreamAdapter os = new XOutputStreamToOutputStreamAdapter(ts); for (int i=0; i < 5; i++) { try { os.write((byte)i); byte [] testBytes = ts.getBytesBak(); if (testBytes[0] != i) { System.out.println("Wrote wrong value <" + testBytes[0] + ">, expecting <i>"); testStatus = false; } os.flush(); } catch (Exception e) { System.out.println("Error writing to OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } try { os.close(); } catch (Exception e) { System.out.println("Error closing OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nOutputStream Test:"); System.out.println("Testing write() with a chunk of 5 bytes"); ts = new TestStream(); os = new XOutputStreamToOutputStreamAdapter(ts); byte [] bo1 = new byte [5]; for (int i=0; i < bo1.length; i++) { bo1[i] = (byte)i; } try { os.write(bo1); byte [] testBytes = ts.getBytesBak(); for (int i=0; i < bo1.length; i++) { if (testBytes[i] != bo1[i]) { System.out.println("Wrote wrong value <" + testBytes[i] + ">, expecting <" + bo1[i] + ">"); testStatus = false; } } os.flush(); } catch (Exception e) { System.out.println("Error writing to OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } try { os.close(); } catch (Exception e) { System.out.println("Error closing OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nOutputStream Test:"); System.out.println("Testing write() with a chunk of 6 bytes, offset=2, length=3."); ts = new TestStream(); os = new XOutputStreamToOutputStreamAdapter(ts); byte [] bo2 = new byte [6]; for (int i=0; i < bo2.length; i++) { bo2[i] = (byte)i; } offset = 2; length = 3; try { os.write(bo2, offset, length); byte [] testBytes = ts.getBytesBak(); for (int i=0; i < bo2.length; i++) { if ((i >= offset && i < (offset + length)) && testBytes[i-offset] != bo2[i]) { System.out.println("Wrote wrong value <" + testBytes[i-offset] + ">, expecting <" + bo2[i] + ">"); testStatus = false; } } os.flush(); } catch (Exception e) { System.out.println("Error writing to OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } try { os.close(); } catch (Exception e) { System.out.println("Error closing OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } if (testStatus == true) { System.out.println("\nAll tests passed...\n"); System.exit(0); } else { System.out.println("\nSome tests failed...\n"); System.exit(-1); } } }
xmerge/java/org/openoffice/xmerge/xmergebridge/TestStream.java
/************************************************************************ * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TestStream.java,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 11:45:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ import com.sun.star.io.XInputStream; import com.sun.star.io.XOutputStream; import com.sun.star.io.NotConnectedException; import com.sun.star.io.BufferSizeExceededException; import com.sun.star.io.IOException; class TestStream implements XInputStream, XOutputStream { /** An array of bytes to be returned when the XInputStream read() method * is called */ private byte [] isBytes; /** * A backup buffer where data sent to the XOutputStream write() method * is placed, used for verification purposes. */ private byte [] bytesBak; /** * Maximum length of data returned by XInputStream read(). */ private static int inputLength = 256; /** * Keeps track of how far into the XInputStream has been read. */ private int currentLoc; /** * Constructor. Sets up the isBytes array. */ public TestStream() { currentLoc = 0; isBytes = new byte [inputLength]; for (int i=0; i < inputLength; i++) { isBytes[i] = (byte)i; } } /* XInputStream interfaces */ public int readBytes(byte[][] aData, int toRead) throws NotConnectedException, BufferSizeExceededException, IOException { int checkSize = inputLength - currentLoc; if (checkSize <= 0) { return -1; } else if (toRead > checkSize) { System.arraycopy(isBytes, currentLoc, aData[0], 0, checkSize); currentLoc += checkSize; return checkSize; } else { System.arraycopy(isBytes, currentLoc, aData[0], 0, toRead); currentLoc += toRead; return toRead; } } public int readSomeBytes(byte[][] aData, int nMaxBytesToRead) throws NotConnectedException, BufferSizeExceededException, IOException { return(readBytes(aData, nMaxBytesToRead)); } public void skipBytes(int nBytesToSkip) throws NotConnectedException, BufferSizeExceededException, IOException { currentLoc += nBytesToSkip; } public int available() throws NotConnectedException, IOException { int checkSize = inputLength - currentLoc; if (checkSize < 0) { return -1; } else { return checkSize; } } public void closeInput() throws NotConnectedException, IOException { // Set currentLoc to the max, so read calls will return -1. // currentLoc = inputLength + 1; System.out.println("Closed XInputStream."); } /* XOutputStream Interfaces */ public void writeBytes(byte [] aData) throws NotConnectedException, BufferSizeExceededException, IOException { // Set backup array, used for verification purposes. // bytesBak = aData; System.out.println("Wrote out the following data to XOutputStream:"); for (int i=0; i < aData.length; i++) { System.out.println(" <" + aData[i] + ">"); } } public void flush() throws NotConnectedException, BufferSizeExceededException, IOException { System.out.println("Flushed XOutputStream."); } public void closeOutput() throws NotConnectedException, BufferSizeExceededException, IOException { System.out.println("Closed XOutputStream."); } /** * Returns the last data passed into the write function, used for * verification purposes. */ public byte [] getBytesBak() { return bytesBak; } public static void main(String args[]) { System.out.println("\nInputStream Test:"); System.out.println("Testing read(), bytes value 1-256:"); TestStream ts = new TestStream(); XInputStreamToInputStreamAdapter is = new XInputStreamToInputStreamAdapter(ts); int rc = 0, avail; boolean testStatus = true; int cnt = 0; do { try { rc = is.read(); avail = is.available(); System.out.println(" Read value <" + rc + ">, avail <" + avail + ">"); if (cnt < inputLength && rc != cnt) { System.out.println("Read wrong value <" + rc + ">, expecting <" + cnt + ">"); testStatus = false; } cnt++; } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nInputStream Test:"); System.out.println("Testing read(), bytes value 1-256 with skips of 3 bytes:"); ts = new TestStream(); is = new XInputStreamToInputStreamAdapter(ts); cnt = 0; do { try { rc = is.read(); avail = is.available(); System.out.println(" Read value <" + rc + ">, avail <" + avail + ">"); is.skip(3); if (cnt < inputLength && rc != cnt) { System.out.println("Read wrong value <" + rc + ">, expecting <" + cnt + ">"); testStatus = false; } cnt += 4; } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nInputStream Test:"); System.out.println("Testing read() in chunks of 5 bytes."); byte [] bi1 = new byte [5]; ts = new TestStream(); is = new XInputStreamToInputStreamAdapter(ts); cnt = 0; do { try { rc = is.read(bi1); avail = is.available(); System.out.print("Read value <"); for (int i=0; i < bi1.length; i++) { if (i == (bi1.length - 1)) { System.out.print((int)bi1[i]); } else { System.out.print((int)bi1[i] + ","); } if ((cnt) < inputLength && bi1[i] != (byte)cnt) { System.out.println("\nRead wrong value <" + (int)bi1[i] + ">, expecting <" + (cnt) + ">"); testStatus = false; } cnt++; } System.out.print("> read rc <" + rc + ">, avail <" + avail + ">\n"); } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nInputStream Test:"); System.out.println("Testing read() in chunks of 6 bytes, offset=2, length=3."); byte [] bi2 = new byte [6]; ts = new TestStream(); is = new XInputStreamToInputStreamAdapter(ts); cnt = 0; int offset = 2; int length = 3; do { try { rc = is.read(bi2, offset, length); avail = is.available(); System.out.print("Read value <"); for (int i=0; i < bi2.length; i++) { if (i == (bi2.length - 1)) { System.out.print((int)bi2[i]); } else { System.out.print((int)bi2[i] + ","); } if (cnt < inputLength) { if (i < offset || i >= (offset + length)) { // Check values that should stay 0 // if ((int)bi2[i] != 0) { System.out.println("\nRead wrong value <" + (int)bi2[i] + ">, expecting <0>"); testStatus = false; } } else if (bi2[i] != (byte)cnt) { // Check actually read values. // System.out.println("\nRead wrong value <" + (int)bi2[i] + ">, expecting <" + cnt + ">"); testStatus = false; } else { cnt++; } } } System.out.print("> read rc <" + rc + ">, avail <" + avail + ">\n"); } catch (Exception e) { System.out.println("Error reading from InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } while (rc >= 0); try { is.close(); } catch (Exception e) { System.out.println("Error closing InputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nOutputStream Test:"); System.out.println("Testing write() and flush()"); ts = new TestStream(); XOutputStreamToOutputStreamAdapter os = new XOutputStreamToOutputStreamAdapter(ts); for (int i=0; i < 5; i++) { try { os.write((byte)i); byte [] testBytes = ts.getBytesBak(); if (testBytes[0] != i) { System.out.println("Wrote wrong value <" + testBytes[0] + ">, expecting <i>"); testStatus = false; } os.flush(); } catch (Exception e) { System.out.println("Error writing to OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } } try { os.close(); } catch (Exception e) { System.out.println("Error closing OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nOutputStream Test:"); System.out.println("Testing write() with a chunk of 5 bytes"); ts = new TestStream(); os = new XOutputStreamToOutputStreamAdapter(ts); byte [] bo1 = new byte [5]; for (int i=0; i < bo1.length; i++) { bo1[i] = (byte)i; } try { os.write(bo1); byte [] testBytes = ts.getBytesBak(); for (int i=0; i < bo1.length; i++) { if (testBytes[i] != bo1[i]) { System.out.println("Wrote wrong value <" + testBytes[i] + ">, expecting <" + bo1[i] + ">"); testStatus = false; } } os.flush(); } catch (Exception e) { System.out.println("Error writing to OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } try { os.close(); } catch (Exception e) { System.out.println("Error closing OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } System.out.println("\nOutputStream Test:"); System.out.println("Testing write() with a chunk of 6 bytes, offset=2, length=3."); ts = new TestStream(); os = new XOutputStreamToOutputStreamAdapter(ts); byte [] bo2 = new byte [6]; for (int i=0; i < bo2.length; i++) { bo2[i] = (byte)i; } offset = 2; length = 3; try { os.write(bo2, offset, length); byte [] testBytes = ts.getBytesBak(); for (int i=0; i < bo2.length; i++) { if ((i >= offset && i < (offset + length)) && testBytes[i-offset] != bo2[i]) { System.out.println("Wrote wrong value <" + testBytes[i-offset] + ">, expecting <" + bo2[i] + ">"); testStatus = false; } } os.flush(); } catch (Exception e) { System.out.println("Error writing to OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } try { os.close(); } catch (Exception e) { System.out.println("Error closing OutputStream"); System.out.println("Error msg: " + e.getMessage()); testStatus = false; } if (testStatus == true) { System.out.println("Test passed...\n"); } else { System.out.println("Test failed...\n"); } if (testStatus == true) { System.out.println("\nAll tests passed...\n"); System.exit(0); } else { System.out.println("\nSome tests failed...\n"); System.exit(-1); } } }
INTEGRATION: CWS latex (1.2.12); FILE MERGED 2006/04/06 14:45:40 sus 1.2.12.1: #i24813# Added packagename
xmerge/java/org/openoffice/xmerge/xmergebridge/TestStream.java
INTEGRATION: CWS latex (1.2.12); FILE MERGED 2006/04/06 14:45:40 sus 1.2.12.1: #i24813# Added packagename
<ide><path>merge/java/org/openoffice/xmerge/xmergebridge/TestStream.java <ide> * <ide> * $RCSfile: TestStream.java,v $ <ide> * <del> * $Revision: 1.2 $ <del> * <del> * last change: $Author: rt $ $Date: 2005-09-09 11:45:38 $ <add> * $Revision: 1.3 $ <add> * <add> * last change: $Author: obo $ $Date: 2006-07-13 09:15:21 $ <ide> * <ide> * The Contents of this file are made available subject to <ide> * the terms of GNU Lesser General Public License Version 2.1. <ide> * MA 02111-1307 USA <ide> * <ide> ************************************************************************/ <add>package org.openoffice.xmerge.xmergebridge; <add> <ide> import com.sun.star.io.XInputStream; <ide> import com.sun.star.io.XOutputStream; <ide> import com.sun.star.io.NotConnectedException;
Java
lgpl-2.1
9a77eb800a60fec76d92c241758a7777344edc8c
0
cacheonix/cacheonix-core,cacheonix/cacheonix-core,cacheonix/cacheonix-core
/* * Cacheonix systems licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cacheonix.impl.cache.distributed.partitioned.subscriber; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import org.cacheonix.cache.subscriber.EntryModifiedSubscriber; import org.cacheonix.impl.cache.distributed.partitioned.CacheProcessor; import org.cacheonix.impl.cache.distributed.partitioned.LocalCacheRequest; import org.cacheonix.impl.cache.distributed.partitioned.PartitionedCache; import org.cacheonix.impl.cache.item.Binary; import org.cacheonix.impl.cache.item.BinaryUtils; import org.cacheonix.impl.cache.store.AsynchronousEntryModifiedSubscriberAdapter; import org.cacheonix.impl.cache.store.BinaryEntryModifiedSubscriberAdapter; import org.cacheonix.impl.cache.store.SafeEntryUpdateSubscriber; import org.cacheonix.impl.net.ClusterNodeAddress; import org.cacheonix.impl.net.processor.Response; import org.cacheonix.impl.net.processor.RouteByReferenceRequest; import org.cacheonix.impl.net.processor.SimpleWaiter; import org.cacheonix.impl.net.processor.Waiter; import org.cacheonix.impl.net.serializer.Wireable; import org.cacheonix.impl.net.serializer.WireableBuilder; import org.cacheonix.impl.util.StringUtils; import org.cacheonix.impl.util.array.HashSet; /** * A <b>local</b> cache request to register a subscriber in the local <code>CacheProcessor</code> and to initiate * subscription sequence. * <p/> * This request initiates the subscription sequence by posting a reliable mcast message * <code>AddEntryModifiedSubscriptionAnnouncement</code>/ * <p/> * This request is sent by <code>PartitionedCache.addEventSubscriber()</code>. * * @see PartitionedCache#addEventSubscriber(Set, EntryModifiedSubscriber) * @see AddEntryModifiedSubscriptionAnnouncement */ @SuppressWarnings("RedundantIfStatement") public final class AddEntryModifiedSubscriberRequest extends LocalCacheRequest implements RouteByReferenceRequest { /** * Maker used by WireableFactory. */ public static final WireableBuilder BUILDER = new Builder(); private HashSet<Binary> keys = null; // NOPMD /** * A local subscriber as provided by the client. This is a transient field. */ private EntryModifiedSubscriber localSubscriber; private ClusterNodeAddress subscriberAddress; public AddEntryModifiedSubscriberRequest() { } public AddEntryModifiedSubscriberRequest(final String cacheName) { super(TYPE_CACHE_ADD_ENTRY_MODIFIED_SUBSCRIBER_REQUEST, cacheName); } public void setKeys(final HashSet<Binary> keys) { // NOPMD this.keys = BinaryUtils.copy(keys); } HashSet<Binary> getKeys() { // NOPMD return keys; } /** * Sets the local subscriber as provided by the client. * * @param localSubscriber the local subscriber as provided by the client. */ public void setLocalSubscriber(final EntryModifiedSubscriber localSubscriber) { this.localSubscriber = localSubscriber; } /** * Returns the local subscriber as provided by the client. * * @return the local subscriber as provided by the client. */ EntryModifiedSubscriber getLocalSubscriber() { return localSubscriber; } public void setSubscriberAddress(final ClusterNodeAddress subscriberAddress) { this.subscriberAddress = subscriberAddress; } ClusterNodeAddress getSubscriberAddress() { return subscriberAddress; } protected void executeOperational() { final CacheProcessor processor = getCacheProcessor(); // // Register local receiver of notification messages // final Executor eventNotificationExecutor = processor.getEventNotificationExecutor(); final SafeEntryUpdateSubscriber safeSubscriber = new SafeEntryUpdateSubscriber(localSubscriber); final AsynchronousEntryModifiedSubscriberAdapter asynchronousSubscriber = new AsynchronousEntryModifiedSubscriberAdapter( eventNotificationExecutor, safeSubscriber); final BinaryEntryModifiedSubscriberAdapter binarySubscriber = new BinaryEntryModifiedSubscriberAdapter( asynchronousSubscriber); final int subscriberIdentity = System.identityHashCode(localSubscriber); final Map<Integer, LocalSubscription> localSubscriptions = processor.getLocalEntryModifiedSubscriptions(); LocalSubscription localSubscription = localSubscriptions.get(subscriberIdentity); if (localSubscription == null) { // Subscriber not found, create subscription localSubscription = new LocalSubscription(); localSubscription.setSubscriber(binarySubscriber); localSubscriptions.put(subscriberIdentity, localSubscription); } localSubscription.addKeys(keys); // // Send reliable mcast announcement to begin subscription process // // Create subscription information final EntryModifiedSubscription subscription = new EntryModifiedSubscription(subscriberIdentity, subscriberAddress, localSubscriber.getNotificationMode(), localSubscriber.getEventContentFlags(), localSubscriber.getModificationTypes()); // Create announcement final AddEntryModifiedSubscriptionAnnouncement announcement = new AddEntryModifiedSubscriptionAnnouncement( getCacheName()); ((AddEntryModifiedSubscriptionAnnouncement.Waiter) announcement.getWaiter()).setParentRequest(this); announcement.setSubscription(subscription); announcement.setKeySet(keys); // Post announcement processor.post(announcement); } /** * {@inheritDoc} * <p/> * This implementation simply posts <code>Response.RESULT_RETRY</code>. */ protected void executeBlocked() { // If the CacheProcessor is in Blocked state, there is a good chance // the reliable multicast is disabled, so it is better simply to wait. getProcessor().post(createResponse(Response.RESULT_RETRY)); } /** * {@inheritDoc} * <p/> * This implementation returns {@link SimpleWaiter}. */ protected Waiter createWaiter() { return new SimpleWaiter(this); } public String toString() { return "AddEntryModifiedSubscriberRequest{" + "keys=" + StringUtils.sizeToString((Collection) keys) + ", subscriber=" + localSubscriber + ", subscriberAddress=" + subscriberAddress + "} " + super.toString(); } /** * A class factory. */ final static class Builder implements WireableBuilder { public Wireable create() { return new AddEntryModifiedSubscriberRequest(); } } }
src/org/cacheonix/impl/cache/distributed/partitioned/subscriber/AddEntryModifiedSubscriberRequest.java
/* * Cacheonix systems licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cacheonix.impl.cache.distributed.partitioned.subscriber; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import org.cacheonix.cache.subscriber.EntryModifiedSubscriber; import org.cacheonix.impl.cache.distributed.partitioned.CacheProcessor; import org.cacheonix.impl.cache.distributed.partitioned.LocalCacheRequest; import org.cacheonix.impl.cache.distributed.partitioned.PartitionedCache; import org.cacheonix.impl.cache.item.Binary; import org.cacheonix.impl.cache.item.BinaryUtils; import org.cacheonix.impl.cache.store.AsynchronousEntryModifiedSubscriberAdapter; import org.cacheonix.impl.cache.store.BinaryEntryModifiedSubscriberAdapter; import org.cacheonix.impl.cache.store.SafeEntryUpdateSubscriber; import org.cacheonix.impl.net.ClusterNodeAddress; import org.cacheonix.impl.net.processor.Response; import org.cacheonix.impl.net.processor.RouteByReferenceRequest; import org.cacheonix.impl.net.processor.SimpleWaiter; import org.cacheonix.impl.net.processor.Waiter; import org.cacheonix.impl.net.serializer.Wireable; import org.cacheonix.impl.net.serializer.WireableBuilder; import org.cacheonix.impl.util.StringUtils; import org.cacheonix.impl.util.array.HashSet; /** * A <b>local</b> cache request to register a subscriber in the local <code>CacheProcessor</code> and to initiate * subscription sequence. * <p/> * This request initiates the subscription sequence by posting a reliable mcast message * <code>AddEntryModifiedSubscriptionAnnouncement</code>/ * <p/> * This request is sent by <code>PartitionedCache.addEventSubscriber()</code>. * * @see PartitionedCache#addEventSubscriber(Set, EntryModifiedSubscriber) * @see AddEntryModifiedSubscriptionAnnouncement */ @SuppressWarnings("RedundantIfStatement") public final class AddEntryModifiedSubscriberRequest extends LocalCacheRequest implements RouteByReferenceRequest { /** * Maker used by WireableFactory. */ public static final WireableBuilder BUILDER = new Builder(); private HashSet<Binary> keys = null; // NOPMD /** * A local subscriber as provided by the client. */ private transient EntryModifiedSubscriber localSubscriber; private ClusterNodeAddress subscriberAddress; public AddEntryModifiedSubscriberRequest() { } public AddEntryModifiedSubscriberRequest(final String cacheName) { super(TYPE_CACHE_ADD_ENTRY_MODIFIED_SUBSCRIBER_REQUEST, cacheName); } public void setKeys(final HashSet<Binary> keys) { // NOPMD this.keys = BinaryUtils.copy(keys); } HashSet<Binary> getKeys() { // NOPMD return keys; } /** * Sets the local subscriber as provided by the client. * * @param localSubscriber the local subscriber as provided by the client. */ public void setLocalSubscriber(final EntryModifiedSubscriber localSubscriber) { this.localSubscriber = localSubscriber; } /** * Returns the local subscriber as provided by the client. * * @return the local subscriber as provided by the client. */ EntryModifiedSubscriber getLocalSubscriber() { return localSubscriber; } public void setSubscriberAddress(final ClusterNodeAddress subscriberAddress) { this.subscriberAddress = subscriberAddress; } ClusterNodeAddress getSubscriberAddress() { return subscriberAddress; } protected void executeOperational() { final CacheProcessor processor = getCacheProcessor(); // // Register local receiver of notification messages // final Executor eventNotificationExecutor = processor.getEventNotificationExecutor(); final SafeEntryUpdateSubscriber safeSubscriber = new SafeEntryUpdateSubscriber(localSubscriber); final AsynchronousEntryModifiedSubscriberAdapter asynchronousSubscriber = new AsynchronousEntryModifiedSubscriberAdapter( eventNotificationExecutor, safeSubscriber); final BinaryEntryModifiedSubscriberAdapter binarySubscriber = new BinaryEntryModifiedSubscriberAdapter( asynchronousSubscriber); final int subscriberIdentity = System.identityHashCode(localSubscriber); final Map<Integer, LocalSubscription> localSubscriptions = processor.getLocalEntryModifiedSubscriptions(); LocalSubscription localSubscription = localSubscriptions.get(subscriberIdentity); if (localSubscription == null) { // Subscriber not found, create subscription localSubscription = new LocalSubscription(); localSubscription.setSubscriber(binarySubscriber); localSubscriptions.put(subscriberIdentity, localSubscription); } localSubscription.addKeys(keys); // // Send reliable mcast announcement to begin subscription process // // Create subscription information final EntryModifiedSubscription subscription = new EntryModifiedSubscription(subscriberIdentity, subscriberAddress, localSubscriber.getNotificationMode(), localSubscriber.getEventContentFlags(), localSubscriber.getModificationTypes()); // Create announcement final AddEntryModifiedSubscriptionAnnouncement announcement = new AddEntryModifiedSubscriptionAnnouncement( getCacheName()); ((AddEntryModifiedSubscriptionAnnouncement.Waiter) announcement.getWaiter()).setParentRequest(this); announcement.setSubscription(subscription); announcement.setKeySet(keys); // Post announcement processor.post(announcement); } /** * {@inheritDoc} * <p/> * This implementation simply posts <code>Response.RESULT_RETRY</code>. */ protected void executeBlocked() { // If the CacheProcessor is in Blocked state, there is a good chance // the reliable multicast is disabled, so it is better simply to wait. getProcessor().post(createResponse(Response.RESULT_RETRY)); } /** * {@inheritDoc} * <p/> * This implementation returns {@link SimpleWaiter}. */ protected Waiter createWaiter() { return new SimpleWaiter(this); } public String toString() { return "AddEntryModifiedSubscriberRequest{" + "keys=" + StringUtils.sizeToString((Collection) keys) + ", subscriber=" + localSubscriber + ", subscriberAddress=" + subscriberAddress + "} " + super.toString(); } /** * A class factory. */ final static class Builder implements WireableBuilder { public Wireable create() { return new AddEntryModifiedSubscriberRequest(); } } }
Code quality: Removed a reference to transient field in a class that is not serializable.
src/org/cacheonix/impl/cache/distributed/partitioned/subscriber/AddEntryModifiedSubscriberRequest.java
Code quality: Removed a reference to transient field in a class that is not serializable.
<ide><path>rc/org/cacheonix/impl/cache/distributed/partitioned/subscriber/AddEntryModifiedSubscriberRequest.java <ide> private HashSet<Binary> keys = null; // NOPMD <ide> <ide> /** <del> * A local subscriber as provided by the client. <del> */ <del> private transient EntryModifiedSubscriber localSubscriber; <add> * A local subscriber as provided by the client. This is a transient field. <add> */ <add> private EntryModifiedSubscriber localSubscriber; <ide> <ide> private ClusterNodeAddress subscriberAddress; <ide>
JavaScript
mit
640ac5f313a5441b742c584ea890e2a31f52e40f
0
cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, fillIn } from '@ember/test-helpers'; import EmberObject from '@ember/object'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | field editors/integer editor', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { this.setProperties({ model: EmberObject.create({ rating: 3 }), onchange() {} }); await render(hbs` {{field-editors/integer-editor content=model field="rating" onchange=onchange }}`); assert.dom('input[type=number]').hasValue('3', 'number input has correct value'); assert.dom('input').isNotDisabled(); }); test('it updates the value correctly', async function(assert) { this.setProperties({ model: EmberObject.create({ rating: 3 }), onchange() {} }); await render(hbs` {{field-editors/integer-editor content=model field="rating" onchange=onchange }}`); await fillIn('.field-editor > input', '5'); assert.dom('input[type=number]').hasValue('5', 'input is updated'); assert.dom('input').isNotDisabled(); assert.equal(this.get('model.rating'), '5', 'model attribute is updated'); }); test('it can be disabled', async function(assert) { this.setProperties({ model: EmberObject.create({ rating: 3 }), onchange() {} }); await render(hbs` {{field-editors/integer-editor content=model field="rating" onchange=onchange disabled=true }}`); assert.dom('input').isDisabled(); }); });
packages/core-types/tests/integration/components/field-editors/integer-editor-test.js
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, triggerEvent, fillIn } from '@ember/test-helpers'; import EmberObject from '@ember/object'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | field editors/integer editor', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { this.setProperties({ model: EmberObject.create({ rating: 3 }), onchange() {} }); await render(hbs` {{field-editors/integer-editor content=model field="rating" onchange=onchange }}`); assert.dom('input[type=number]').hasValue('3', 'number input has correct value'); assert.dom('input').isNotDisabled(); }); test('it updates the value correctly', async function(assert) { this.setProperties({ model: EmberObject.create({ rating: 3 }), onchange() {} }); await render(hbs` {{field-editors/integer-editor content=model field="rating" onchange=onchange }}`); await fillIn('.field-editor > input', '5'); assert.dom('input[type=number]').hasValue('5', 'input is updated'); assert.dom('input').isNotDisabled(); assert.equal(this.get('model.rating'), '5', 'model attribute is updated'); }); test('it can be disabled', async function(assert) { this.setProperties({ model: EmberObject.create({ rating: 3 }), onchange() {} }); await render(hbs` {{field-editors/integer-editor content=model field="rating" onchange=onchange disabled=true }}`); assert.dom('input').isDisabled(); }); });
Remove unused triggerEvent
packages/core-types/tests/integration/components/field-editors/integer-editor-test.js
Remove unused triggerEvent
<ide><path>ackages/core-types/tests/integration/components/field-editors/integer-editor-test.js <ide> import { module, test } from 'qunit'; <ide> import { setupRenderingTest } from 'ember-qunit'; <del>import { render, triggerEvent, fillIn } from '@ember/test-helpers'; <add>import { render, fillIn } from '@ember/test-helpers'; <ide> import EmberObject from '@ember/object'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide>
JavaScript
agpl-3.0
068b47060b315b903ea2097fca9df480c84de261
0
ssbc/patchwork,ssbc/patchwork
var {remote, shell, clipboard, ipcRenderer} = require('electron') var {SpellCheckHandler, ContextMenuListener, ContextMenuBuilder} = require('electron-spellchecker') var {MenuItem, Menu} = remote var ref = require('ssb-ref') var navigateHandler = null module.exports = setupContextMenuAndSpellCheck function setupContextMenuAndSpellCheck (config, navigate) { navigateHandler = navigate window.spellCheckHandler = new SpellCheckHandler() window.spellCheckHandler.attachToInput() // Start off as US English, America #1 (lol) window.spellCheckHandler.switchLanguage('en-US') var contextMenuBuilder = new ContextMenuBuilder(window.spellCheckHandler, null, true) contextMenuBuilder.buildMenuForLink = function (menuInfo) { var menu = new Menu() var isEmailAddress = menuInfo.linkURL.startsWith('mailto:') var isFile = menuInfo.linkURL.startsWith('file:') var extractedRef = ref.extract(menuInfo.linkURL) if (!isFile) { var copyLink = new MenuItem({ label: isEmailAddress ? this.stringTable.copyMail() : this.stringTable.copyLinkUrl(), click: () => { // Omit the mailto: portion of the link; we just want the address clipboard.writeText(isEmailAddress ? menuInfo.linkText : menuInfo.linkURL) } }) var openLink = new MenuItem({ label: this.stringTable.openLinkUrl(), click: () => { shell.openExternal(menuInfo.linkURL) } }) menu.append(copyLink) menu.append(openLink) } if (extractedRef) { if (navigateHandler) { menu.append(new MenuItem({ label: 'Find Link References', click: function () { navigateHandler('?' + extractedRef) } })) this.addSeparator(menu) } var copyRef = new MenuItem({ label: `Copy Link Ref (${extractedRef.slice(0, 10)}...)`, click: () => { // Omit the mailto: portion of the link; we just want the address clipboard.writeText(extractedRef) } }) menu.append(copyRef) if (ref.isBlob(extractedRef) && menuInfo.hasImageContents) { var copyEmbed = new MenuItem({ label: `Copy Embed Markdown`, click: () => { // Omit the mailto: portion of the link; we just want the address clipboard.writeText(`![${menuInfo.titleText}](${extractedRef})`) } }) menu.append(copyEmbed) } } if (this.isSrcUrlValid(menuInfo)) { if (!isFile) this.addSeparator(menu) this.addImageItems(menu, menuInfo) } this.addInspectElement(menu, menuInfo) this.processMenu(menu, menuInfo) return menu } module.exports.menu = new ContextMenuListener((info) => { contextMenuBuilder.buildMenuForElement(info).then((menu) => { var element = document.elementFromPoint(info.x, info.y) while (element && !element.msg) { element = element.parentNode } menu.append(new MenuItem({ label: 'Inspect Server Process', click: function () { ipcRenderer.send('open-background-devtools') } })) menu.append(new MenuItem({ type: 'separator' })) menu.append(new MenuItem({ label: 'Reload', click: function (item, focusedWindow) { if (focusedWindow) { focusedWindow.reload() } } })) if (element && element.msg) { menu.append(new MenuItem({ type: 'separator' })) menu.append(new MenuItem({ label: 'Copy Message ID', click: function () { clipboard.writeText(element.msg.key) } })) if (element.msg.value.content && element.msg.value.content.text) { menu.append(new MenuItem({ label: 'Copy Message Text', click: function () { clipboard.writeText(element.msg.value.content.text) } })) } menu.append(new MenuItem({ label: 'Copy External Link', click: function () { const key = element.msg.key const gateway = config.gateway || 'https://viewer.scuttlebot.io' const url = `${gateway}/${encodeURIComponent(key)}` clipboard.writeText(url) } })) } menu.popup(remote.getCurrentWindow()) }).catch((err) => { throw err }) }) }
lib/context-menu-and-spellcheck.js
var {remote, shell, clipboard, ipcRenderer} = require('electron') var {SpellCheckHandler, ContextMenuListener, ContextMenuBuilder} = require('electron-spellchecker') var {MenuItem, Menu} = remote var ref = require('ssb-ref') var navigateHandler = null module.exports = setupContextMenuAndSpellCheck function setupContextMenuAndSpellCheck (config, navigate) { navigateHandler = navigate window.spellCheckHandler = new SpellCheckHandler() window.spellCheckHandler.attachToInput() // Start off as US English, America #1 (lol) window.spellCheckHandler.switchLanguage('en-US') var contextMenuBuilder = new ContextMenuBuilder(window.spellCheckHandler, null, true) contextMenuBuilder.buildMenuForLink = function (menuInfo) { var menu = new Menu() var isEmailAddress = menuInfo.linkURL.startsWith('mailto:') var isFile = menuInfo.linkURL.startsWith('file:') var extractedRef = ref.extract(menuInfo.linkURL) if (!isFile) { var copyLink = new MenuItem({ label: isEmailAddress ? this.stringTable.copyMail() : this.stringTable.copyLinkUrl(), click: () => { // Omit the mailto: portion of the link; we just want the address clipboard.writeText(isEmailAddress ? menuInfo.linkText : menuInfo.linkURL) } }) var openLink = new MenuItem({ label: this.stringTable.openLinkUrl(), click: () => { shell.openExternal(menuInfo.linkURL) } }) menu.append(copyLink) menu.append(openLink) } if (extractedRef) { if (navigateHandler) { menu.append(new MenuItem({ label: 'Find Link References', click: function () { navigateHandler('?' + extractedRef) } })) this.addSeparator(menu) } var copyRef = new MenuItem({ label: `Copy Link Ref (${extractedRef.slice(0, 10)}...)`, click: () => { // Omit the mailto: portion of the link; we just want the address clipboard.writeText(extractedRef) } }) menu.append(copyRef) } if (this.isSrcUrlValid(menuInfo)) { if (!isFile) this.addSeparator(menu) this.addImageItems(menu, menuInfo) } this.addInspectElement(menu, menuInfo) this.processMenu(menu, menuInfo) return menu } module.exports.menu = new ContextMenuListener((info) => { contextMenuBuilder.buildMenuForElement(info).then((menu) => { var element = document.elementFromPoint(info.x, info.y) while (element && !element.msg) { element = element.parentNode } menu.append(new MenuItem({ label: 'Inspect Server Process', click: function () { ipcRenderer.send('open-background-devtools') } })) menu.append(new MenuItem({ type: 'separator' })) menu.append(new MenuItem({ label: 'Reload', click: function (item, focusedWindow) { if (focusedWindow) { focusedWindow.reload() } } })) if (element && element.msg) { menu.append(new MenuItem({ type: 'separator' })) menu.append(new MenuItem({ label: 'Copy Message ID', click: function () { clipboard.writeText(element.msg.key) } })) if (element.msg.value.content && element.msg.value.content.text) { menu.append(new MenuItem({ label: 'Copy Message Text', click: function () { clipboard.writeText(element.msg.value.content.text) } })) } menu.append(new MenuItem({ label: 'Copy External Link', click: function () { const key = element.msg.key const gateway = config.gateway || 'https://viewer.scuttlebot.io' const url = `${gateway}/${encodeURIComponent(key)}` clipboard.writeText(url) } })) } menu.popup(remote.getCurrentWindow()) }).catch((err) => { throw err }) }) }
right click copy embed on images
lib/context-menu-and-spellcheck.js
right click copy embed on images
<ide><path>ib/context-menu-and-spellcheck.js <ide> } <ide> }) <ide> menu.append(copyRef) <add> <add> if (ref.isBlob(extractedRef) && menuInfo.hasImageContents) { <add> var copyEmbed = new MenuItem({ <add> label: `Copy Embed Markdown`, <add> click: () => { <add> // Omit the mailto: portion of the link; we just want the address <add> clipboard.writeText(`![${menuInfo.titleText}](${extractedRef})`) <add> } <add> }) <add> menu.append(copyEmbed) <add> } <ide> } <ide> <ide> if (this.isSrcUrlValid(menuInfo)) {
Java
lgpl-2.1
2e9a2bdbef05a3a3e67186e98e6fea2345a65a9c
0
SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer
/* * Copyright (C) 2022 tobid. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.ine.telluride.jaer.tell2022; import com.github.sh0nk.matplotlib4j.Plot; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import gnu.io.NRSerialPort; import java.awt.Color; import java.awt.Point; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Random; import java.util.Set; import javafx.geometry.Point2D; import javax.swing.JFrame; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.EventFilter2DMouseROI; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.SpatioTemporalCorrelationFilter; import net.sf.jaer.eventprocessing.filter.XYTypeFilter; import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker; import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker.Cluster; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.util.DrawGL; import net.sf.jaer.util.SoundWavFilePlayer; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; /** * Going fishing game from Under the sea Lets go Fishing from Pressman. It uses * an Arduino Nano to generate the PWM servo output for the rod pan tilt and to * read the ADC connected to the current sense amplifier reading the FSR402 * (https://www.amazon.com/dp/B074QLDCXQ?psc=1&ref=ppx_yo2ov_dt_b_product_details) * conductance that senses the fish hanging on the hook. An LP38841T-1.5 * regulator * (https://www.ti.com/general/docs/suppproductinfo.tsp?distId=26&gotoUrl=https://www.ti.com/lit/gpn/lp38841) * controls when the table pond turns. * * See https://youtu.be/AgESLgcEE7o for video of Gone Fishing robot. * * @author tobid, Julie Hasler (juliehsler) */ @Description("Let's go fishing (going fishing) game from Telluride 2022 with Tobi Delbruck and Julie Hasler") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class GoingFishing extends EventFilter2DMouseROI implements FrameAnnotater { FilterChain chain = null; RectangularClusterTracker tracker = null; Random random = new Random(); // serial port stuff NRSerialPort serialPort = null; private String serialPortName = getString("serialPortName", "COM3"); private int serialBaudRate = getInt("serialBaudRate", 115200); private DataOutputStream serialPortOutputStream = null; private DataInputStream serialPortInputStream = null; private AdcReader adcReader = null; private boolean disableServos = false; private boolean enableFishing = getBoolean("enableFishing", false); private final int SERIAL_WARNING_INTERVAL = 100; private int serialWarningCount = 0; // ADC for FSR that might detect caught fish private int lastAdcValue = -1; private int caughtFishDetectorThreshold = getInt("caughtFishDetectorThreshold", 550); // PropertyChange events public static final String EVENT_ROD_POSITION = "rodPosition", EVENT_ROD_SEQUENCE = "rodSequence", EVENT_CLEAR_SEQUENCES = "clearSequences"; // rod control private int zMin = getInt("zMin", 80); private int zMax = getInt("zMax", 100); // fishing rod dips RodDipper rodDipper = null; RodSequence[] rodSequences = {new RodSequence(0), new RodSequence(1)}; private int currentRodsequenceIdx = 0; private float fishingHoleSwitchProbability = getFloat("fishingHoleSwitchProbability", 0.1f); private int fishingAttemptHoldoffMs = getInt("fishingAttemptHoldoffMs", 3000); private long lastFishingAttemptTimeMs = 0; private int rodReturnDurationMs = getInt("rodReturnDurationMs", 1000); private boolean treatSigmasAsOffsets = getBoolean("treatSigmasAsOffsets", false); private float rodDipSpeedUpFactor = getFloat("rodDipSpeedUpFactor", 1f); // marking rod tip private boolean markRodTip = false; private Point2D rodTipLocation; private boolean markFishingPoleCenter = false; private Point2D fishingPoolCenterLocation; // measuring speed of fish DescriptiveStatistics fishSpeedStats; // reinforcement learning private float rodThetaOffset = getFloat("rodThetaOffset", 0); private int rodDipDelayMs = getInt("rodDipDelayMs", 0); private float rodThetaSamplingSigmaDeg = getFloat("rodThetaSamplingSigmaDeg", 2); private int rodDipDelaySamplingSigmaMs = getInt("rodDipDelaySamplingSigmaMs", 100); private long lastManualRodControlTime = 0; private static final long HOLDOFF_AFTER_MANUAL_CONTROL_MS = 1000; private int lastRodTheta = -1; private int lastRodZ = -1; // warnings private final int WARNING_INTERVAL = 100; private int missingRoiWarningCounter = 0; private int missingMarkedLocationsWarningCounter = 0; // results of fishing attempt private class FishingResult { boolean succeeded; float thetaOffsetDeg; long delayMs; public FishingResult(boolean succeeded, float thetaOffsetDeg, long delayMs) { this.succeeded = succeeded; this.thetaOffsetDeg = thetaOffsetDeg; this.delayMs = delayMs; } } // collected results private class FishingResults { private int rodDipTotalCount = 0, rodDipSuccessCount = 0, rodDipFailureCount = 0; private ArrayList<FishingResult> fishingResultsList = new ArrayList(); private ArrayList<Float> sucTheta = new ArrayList(), failTheta = new ArrayList(), sucDelay = new ArrayList(), failDelay = new ArrayList(); void clear() { rodDipTotalCount = 0; rodDipSuccessCount = 0; rodDipFailureCount = 0; fishingResultsList.clear(); sucTheta.clear(); failTheta.clear(); sucDelay.clear(); failDelay.clear(); } /** * add fishing result * * @param b true for success, false for failure * @param randomThetaOffsetDeg * @param randomDelayMs */ private void add(boolean b, float randomThetaOffsetDeg, int randomDelayMs) { rodDipTotalCount++; fishingResultsList.add(new FishingResult(b, randomThetaOffsetDeg, randomDelayMs)); if (b) { rodDipSuccessCount++; sucTheta.add(randomThetaOffsetDeg); sucDelay.add((float) randomDelayMs); } else { rodDipFailureCount++; failTheta.add(randomThetaOffsetDeg); failDelay.add((float) randomDelayMs); } } private void plot() { Plot plt = Plot.create(); // see https://github.com/sh0nk/matplotlib4j plt.subplot(1, 1, 1); plt.title("Fishing results"); plt.xlabel("delay (ms)"); plt.ylabel("angle (deg)"); plt.plot().add(sucDelay, sucTheta, "go").linewidth(1).linestyle("None"); plt.plot().add(failDelay, failTheta, "rx").linewidth(1).linestyle("None"); plt.legend(); try { plt.show(); } catch (Exception ex) { log.warning("cannot show the plot with pyplot - did you install python and matplotlib on path? " + ex.toString()); showWarningDialogInSwingThread("<html>Cannot show the plot with pyplot - did you install python and matplotlib on path? <p>" + ex.toString(), "Cannot plot"); } } } private FishingResults fishingResults = new FishingResults(); // sounds SoundWavFilePlayer beepFishDetectedPlayer = null, beepDipStartedPlayer = null, beepFailurePlayer = null, beepSucessPlayer = null; public GoingFishing(AEChip chip) { super(chip); chain = new FilterChain(chip); tracker = new RectangularClusterTracker(chip); chain.add(new XYTypeFilter(chip)); chain.add(new SpatioTemporalCorrelationFilter(chip)); chain.add(tracker); setEnclosedFilterChain(chain); String ser = "Serial port", rod = "Rod control", ler = "Learning", enb = "Enable/Disable"; setPropertyTooltip(ser, "serialPortName", "Name of serial port to send robot commands to"); setPropertyTooltip(ser, "serialBaudRate", "Baud rate (default 115200), upper limit 12000000"); setPropertyTooltip(rod, "showFishingRodControlPanel", "show control panel for fishing rod"); setPropertyTooltip(rod, "dipRod", "make a fishing movement"); setPropertyTooltip(rod, "abortDip", "abort rod dipping if active"); setPropertyTooltip(rod, "resetLearning", "reset learned theta and delay parameters"); setPropertyTooltip(rod, "rodDipSpeedUpFactor", "factor by which to speed up rod dip sequence over recorded speed"); setPropertyTooltip(rod, "markRodTipLocation", "Mark the location of rod tip and hook with next left mouse click"); setPropertyTooltip(rod, "markFishingPoolCenter", "Mark the location of center of fishing pool with next left mouse click"); setPropertyTooltip(rod, "zMin", "min rod tilt angle in deg"); setPropertyTooltip(rod, "zMax", "max rod tilt angle in deg"); setPropertyTooltip(enb, "runPond", "Turn on the pond motor via 1.5V regulator"); setPropertyTooltip(rod, "fishingAttemptHoldoffMs", "holdoff time in ms between automatic fishing attempts"); setPropertyTooltip(rod, "rodReturnDurationMs", "duration in ms of minimum-jerk movement back to starting point of fishing rod sequence"); setPropertyTooltip(enb, "disableServos", "disable servos"); setPropertyTooltip(enb, "enableFishing", "enable automatic fishing"); setPropertyTooltip(ler, "fishingHoleSwitchProbability", "chance of switching spots after each attempt"); setPropertyTooltip(ler, "caughtFishDetectorThreshold", "threshold ADC count from FSR to detect that we caught a fish"); setPropertyTooltip(ler, "rodDipDelaySamplingSigmaMs", "spread of uniformly-sampled delay in ms to sample new rod dip starting delay"); setPropertyTooltip(ler, "rodThetaSamplingSigmaDeg", "sigma in deg to sample new rod dip pan offsets"); setPropertyTooltip(ler, "treatSigmasAsOffsets", "Use the sigma values for theta and delay as fixed offsets to manually tune the fishing"); setPropertyTooltip(ler, "plotFishingResults", "(needs python and matplotlib installed) Plot the fishing results as scatter plot."); try { for (int i = 0; i < 2; i++) { rodSequences[i].load(i); log.info("loaded " + rodSequences.toString()); } } catch (Exception e) { log.warning("Could not load fishing rod movement sequence: " + e.toString()); } Object o = null; o = getObject("rodTipLocation", null); if (o instanceof java.awt.Point) { Point p = (java.awt.Point) o; rodTipLocation = new Point2D(p.x, p.y); } else { rodTipLocation = null; } o = getObject("fishingPoolCenterLocation", null); if (o instanceof java.awt.Point) { Point p = (java.awt.Point) o; fishingPoolCenterLocation = new Point2D(p.x, p.y); } else { fishingPoolCenterLocation = null; } try { String s; // https://www.soundjay.com/beep-sounds-1.html#google_vignette s = "src/org/ine/telluride/jaer/tell2022/beeps/beep-07a.wav"; beepFishDetectedPlayer = new SoundWavFilePlayer(s); s = "src/org/ine/telluride/jaer/tell2022/beeps/beep-08b.wav"; beepDipStartedPlayer = new SoundWavFilePlayer(s); s = "src/org/ine/telluride/jaer/tell2022/beeps/beep-03-fail.wav"; beepFailurePlayer = new SoundWavFilePlayer(s); s = "src/org/ine/telluride/jaer/tell2022/beeps/success.wav"; beepSucessPlayer = new SoundWavFilePlayer(s); } catch (Exception e) { log.warning("Could not load beep sound: " + e.toString()); } fishSpeedStats = new DescriptiveStatistics(30); } @Override public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) { in = getEnclosedFilterChain().filterPacket(in); checkForFishingAttempt(); return in; } private void checkForFishingAttempt() { long currentTimeMs = System.currentTimeMillis(); if (roiRects == null || roiRects.isEmpty()) { if (missingRoiWarningCounter % WARNING_INTERVAL == 0) { log.warning("draw at least 1 or at most 2 ROIs for detecting fish before it comes to rod tip"); } missingRoiWarningCounter++; return; } if (rodDipper != null && rodDipper.isAlive()) { return; } if (currentTimeMs - lastManualRodControlTime > HOLDOFF_AFTER_MANUAL_CONTROL_MS) { LinkedList<Cluster> clusterList = tracker.getVisibleClusters(); for (Cluster c : clusterList) { Point p = new Point((int) c.getLocation().x, (int) c.getLocation().y); int roi = isInsideWhichROI(p); long delay = 0; if (roi >= 0 && roi == currentRodsequenceIdx) { // The ROI entered matches the current fishing rod sequence ROI // this ROI we drew contains a fish cluster if (rodTipLocation == null || fishingPoolCenterLocation == null) { if (missingMarkedLocationsWarningCounter % WARNING_INTERVAL == 0) { log.warning("Set rod tip and center of pool locations to estimate delay for fishing motion"); } missingMarkedLocationsWarningCounter++; } else { float fishSpeedPps = c.getSpeedPPS(); fishSpeedStats.addValue(fishSpeedPps); // filter fishSpeedPps = (float) fishSpeedStats.getPercentile(50); // get median value of speed to filter outliers final Point2D clusterLoc = new Point2D(c.getLocation().x, c.getLocation().y); Point2D rodTipRay = rodTipLocation.subtract(fishingPoolCenterLocation); final float radius = (float) rodTipRay.magnitude(); Point2D clusterRay = clusterLoc.subtract(fishingPoolCenterLocation); final double angleDegFishToTip = rodTipRay.angle(clusterRay); final double angularSpeedDegPerS = (180 / Math.PI) * (fishSpeedPps / radius); final int msForFishToReachRodTip = (int) (1000 * angleDegFishToTip / angularSpeedDegPerS); final long timeToMinZMs = Math.round(rodSequences[currentRodsequenceIdx].timeToMinZMs / rodDipSpeedUpFactor); if (msForFishToReachRodTip < timeToMinZMs) { log.warning(String.format("msForFishToReachRodTip=%,d ms is less than rod sequence timeToMinZMs=%,d ms;\n" + "Speed=%.1f px/s, radius=%.1f px, angularSpeed=%.1f deg/s angleDegFishToTip=%.1f deg", msForFishToReachRodTip, timeToMinZMs, fishSpeedPps, radius, angularSpeedDegPerS, angleDegFishToTip)); } else { delay = msForFishToReachRodTip - timeToMinZMs - rodDipDelaySamplingSigmaMs; // log.info(String.format("msForFishToReachRodTip=%,d ms is more than rod sequence timeToMinZMs=%,d ms;\n" // + "Speed=%.1f px/s, radius=%.1f px, angularSpeed=%.1f deg/s angleDegFishToTip=%.1f deg", msForFishToReachRodTip, timeToMinZMs, // fishSpeedPps, radius, angularSpeedDegPerS, angleDegFishToTip)); } } if (rodDipper == null || !rodDipper.isAlive()) { // log.info(String.format("Detected fish in ROI at location %s becoming contained by ROI rectangle %s", c.getLocation(), roiRects.get(roi))); if (!enableFishing) { dipRodWithHoldoffAndDelay(delay); break; } } } } } } /** * Annotates the display with GoingFishing stuff. * * @param drawable */ public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); GL2 gl = drawable.getGL().getGL2(); if (rodTipLocation != null) { gl.glPushMatrix(); gl.glColor3f(1, 0, 0); DrawGL.drawCross(gl, (float) rodTipLocation.getX(), (float) rodTipLocation.getY(), 6, 0); DrawGL.drawStrinDropShadow(gl, 12, 0, 0, 0, Color.red, "Tip"); gl.glPopMatrix(); } if (fishingPoolCenterLocation != null) { gl.glPushMatrix(); gl.glColor3f(1, 0, 0); DrawGL.drawCross(gl, (float) fishingPoolCenterLocation.getX(), (float) fishingPoolCenterLocation.getY(), 6, 0); DrawGL.drawStrinDropShadow(gl, 12, 0, 0, 0, Color.red, "Center"); gl.glPopMatrix(); } gl.glPushMatrix(); final float adcY = chip.getSizeY() / 10; final float adcStartX = 2; if (lastAdcValue != -1) { gl.glLineWidth(5); gl.glColor3f(1, 1, 1); final float adcLen = .9f * chip.getSizeX() * (lastAdcValue / 1024f); DrawGL.drawLine(gl, adcStartX, adcY, adcLen, 0, 1); DrawGL.drawStrinDropShadow(gl, 12, adcStartX + adcLen + 2, adcY, 0, Color.white, Integer.toString(lastAdcValue)); } else { DrawGL.drawStrinDropShadow(gl, 12, adcStartX, adcY, 0, Color.white, "ADC: N/A"); } if (isFishCaught()) { gl.glColor3f(1, 1, 1); DrawGL.drawStrinDropShadow(gl, 36, chip.getSizeX() / 2, chip.getSizeY() / 2, .5f, Color.white, "Caught!"); } final float statsY = 2 * chip.getSizeY() / 10; String s = String.format("Tries: %d, Success: %d (%.1f%%); thetaOffset=%.1f deg, delayMs=%d ms", fishingResults.rodDipTotalCount, fishingResults.rodDipSuccessCount, (100 * (float) fishingResults.rodDipSuccessCount / fishingResults.rodDipTotalCount), rodThetaOffset, rodDipDelayMs); DrawGL.drawStrinDropShadow(gl, 10, adcStartX, statsY, 0, Color.white, s); gl.glPopMatrix(); } @Override public void resetFilter() { fishingResults.clear(); fishSpeedStats.clear(); } @Override public void initFilter() { } public void doDipRod() { dipRodNow(0); } public void doAbortDip() { if (rodDipper != null) { rodDipper.abort(); } } public void doToggleOnRunPond() { enablePond(true); } public void doToggleOffRunPond() { enablePond(false); } public void doToggleOnEnableFishing() { setEnableFishing(false); } public void doToggleOffEnableFishing() { setEnableFishing(true); } public void doPlotFishingResults() { fishingResults.plot(); } private void enablePond(boolean enable) { if (!checkSerialPort()) { log.warning("serial port not open"); return; } byte[] bytes = new byte[3]; bytes[0] = enable ? (byte) 2 : (byte) 3; // send 2 to run, 3 to stop synchronized (serialPortOutputStream) { try { serialPortOutputStream.write(bytes); serialPortOutputStream.flush(); log.info(enable ? "Turned on pong" : "Turned off pond"); } catch (IOException ex) { log.warning(ex.toString()); } } } public void doResetLearning() { rodDipDelayMs = 0; rodThetaOffset = 0; putInt("rodDipDelayMs", 0); putFloat("rodThetaOffset", 0); fishingResults.clear(); } public void doMarkRodTipLocation() { markRodTip = true; markFishingPoleCenter = false; } public void doMarkFishingPoolCenter() { markFishingPoleCenter = true; markRodTip = false; } @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (markRodTip) { markRodTip = false; rodTipLocation = new Point2D(clickedPoint.x, clickedPoint.y); putObject("rodTipLocation", new Point((int) rodTipLocation.getX(), (int) rodTipLocation.getY())); } else if (markFishingPoleCenter) { markFishingPoleCenter = false; fishingPoolCenterLocation = new Point2D(clickedPoint.x, clickedPoint.y); putObject("fishingPoolCenterLocation", new Point((int) fishingPoolCenterLocation.getX(), (int) fishingPoolCenterLocation.getY())); } } private void openSerial() throws IOException { if (serialPort != null) { closeSerial(); } checkBaudRate(serialBaudRate); StringBuilder sb = new StringBuilder("List of all available serial ports: "); final Set<String> availableSerialPorts = NRSerialPort.getAvailableSerialPorts(); if (availableSerialPorts.isEmpty()) { sb.append("\nNo ports found, sorry. If you are on linux, serial port support may suffer"); } else { for (String s : availableSerialPorts) { sb.append(s).append(" "); } } if (!availableSerialPorts.contains(serialPortName)) { final String warningString = serialPortName + " is not in avaiable " + sb.toString(); throw new IOException(warningString); } serialPort = new NRSerialPort(serialPortName, serialBaudRate); if (serialPort == null) { final String warningString = "null serial port returned when trying to open " + serialPortName + "; available " + sb.toString(); throw new IOException(warningString); } if (serialPort.connect()) { serialPortOutputStream = new DataOutputStream(serialPort.getOutputStream()); serialPortInputStream = new DataInputStream(serialPort.getInputStream()); while (serialPortInputStream.available() > 0) { serialPortInputStream.read(); } adcReader = new AdcReader(serialPortInputStream); adcReader.start(); log.info("opened serial port " + serialPortName + " with baud rate=" + serialBaudRate); } else { log.warning("cannot connect serial port" + serialPortName); } } private void closeSerial() { if (serialPortOutputStream != null) { try { serialPortOutputStream.write((byte) '0'); // rest; turn off servos serialPortOutputStream.close(); } catch (IOException ex) { log.warning(ex.toString()); } serialPortOutputStream = null; } if (adcReader != null && adcReader.isAlive()) { adcReader.shutdown(); try { adcReader.join(200); } catch (InterruptedException e) { } } if ((serialPort != null) && serialPort.isConnected()) { serialPort.disconnect(); serialPort = null; } lastRodTheta = -1; lastRodZ = -1; lastAdcValue = -1; } synchronized private boolean checkSerialPort() { if ((serialPort == null)) { try { openSerial(); } catch (IOException ex) { if (serialWarningCount++ == SERIAL_WARNING_INTERVAL) { log.warning("couldn't open serial port " + serialPortName); serialWarningCount = 0; } return false; } } return true; } @Override public void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (!yes) { disableServos(); closeSerial(); } else { try { openSerial(); } catch (IOException ex) { log.warning("couldn't open serial port " + serialPortName); } } } @Override public void cleanup() { disableServos(); } /** * @return the serialBaudRate */ public int getSerialBaudRate() { return serialBaudRate; } /** * @param serialBaudRate the serialBaudRate to set */ public void setSerialBaudRate(int serialBaudRate) { try { checkBaudRate(serialBaudRate); this.serialBaudRate = serialBaudRate; putInt("serialBaudRate", serialBaudRate); openSerial(); } catch (IOException ex) { log.warning(ex.toString()); } } private void checkBaudRate(int serialBaudRate1) { if (serialBaudRate1 != 9600 && serialBaudRate1 != 115200) { showWarningDialogInSwingThread(String.format("Selected baud rate of %,d baud is neither 9600 or 115200, please check it", serialBaudRate1), "Invalid baud rate?"); log.warning(String.format("Possible invalid baud rate %,d", serialBaudRate1)); } } /** * @return the serialPortName */ public String getSerialPortName() { return serialPortName; } /** * @param serialPortName the serialPortName to set */ public void setSerialPortName(String serialPortName) { try { this.serialPortName = serialPortName; putString("serialPortName", serialPortName); openSerial(); } catch (IOException ex) { log.warning("couldn't open serial port: " + ex.toString()); } } /** * Either turns off servos or sets servo positions * * @param disable true to turn off servos * @param theta otherwise the angle of pan (in degrees, 0-180) * @param z and tilt (in degrees, 0-180) */ private void sendRodPosition(boolean disable, int theta, int z) { if (disableServos) { return; } if (checkSerialPort()) { int zSent = (int) Math.floor(zMin + (((float) (zMax - zMin)) / 180) * z); try { // write theta (pan) and z (tilt) of fishing pole as two unsigned byte servo angles and degrees byte[] bytes = new byte[3]; bytes[0] = disable ? (byte) 1 : (byte) 0; bytes[1] = (byte) (theta); bytes[2] = (byte) (zSent); synchronized (serialPortOutputStream) { serialPortOutputStream.write(bytes); serialPortOutputStream.flush(); } this.lastRodTheta = theta; this.lastRodZ = z; } catch (IOException ex) { log.warning(ex.toString()); } } } private void disableServos() { setDisableServos(true); } public void doShowFishingRodControlPanel() { showFishingRodControPanel(); } private JFrame fishingRodControlFrame = null; private void showFishingRodControPanel() { if (fishingRodControlFrame == null) { fishingRodControlFrame = new GoingFishingFishingRodControlFrame(); fishingRodControlFrame.addPropertyChangeListener(EVENT_ROD_POSITION, this); fishingRodControlFrame.addPropertyChangeListener(EVENT_ROD_SEQUENCE, this); fishingRodControlFrame.addPropertyChangeListener(EVENT_CLEAR_SEQUENCES, this); } fishingRodControlFrame.setVisible(true); } /** * Do the fishing move * * @param holdoff set true to enforce a holdoff of fishingAttemptHoldoffMs, * false to dip unconditionally if servos are enabled and dip is not already * running since the end of the last attempt */ private void dipRodWithHoldoffAndDelay(long delayMs) { final long dt = System.currentTimeMillis() - lastFishingAttemptTimeMs; if (dt < 0 || dt > fishingAttemptHoldoffMs) { beepFishDetectedPlayer.play(); dipRodNow(delayMs); } } /** * Do the fishing move * * @param delayMs delay to set at start of dip in ms */ private void dipRodNow(long delayMs) { if (disableServos) { log.warning("servos disabled, will not run " + rodSequences); return; } if (rodDipper != null && rodDipper.isAlive()) { log.warning("aborting running rod sequence"); rodDipper.abort(); try { rodDipper.join(100); } catch (InterruptedException e) { } } int nextSeq = (currentRodsequenceIdx + 1) % 2; if (rodSequences[nextSeq].size() > 0 && random.nextFloat() <= fishingHoleSwitchProbability) { currentRodsequenceIdx = nextSeq; log.info("switched to " + rodSequences[currentRodsequenceIdx]); } RodSequence seq = rodSequences[currentRodsequenceIdx]; rodDipper = new RodDipper(seq, delayMs, false); // log.info("running " + rodSequences.toString()); rodDipper.start(); } private boolean isFishCaught() { return lastAdcValue > caughtFishDetectorThreshold; } private class AdcReader extends Thread { DataInputStream stream; public AdcReader(DataInputStream stream) { this.stream = stream; } synchronized public void shutdown() { try { serialPortInputStream.close(); } catch (IOException e) { } serialPortInputStream = null; return; } public void run() { while (serialPortInputStream != null) { try { byte[] buf = new byte[2]; serialPortInputStream.readFully(buf); lastAdcValue = (int) ((buf[0] & 0xff) * 256 + (0xff & buf[1])); // System.out.println(String.format("ADC: available=%d val=%d", navail, lastAdcValue)); } catch (IOException ex) { log.warning("serial port error while reading ADC value: " + ex.toString()); closeSerial(); } } } } private class RodDipper extends Thread { RodSequence rodSequence = null; volatile boolean aborted = false; private long initialDelayMs = 0; private boolean returnToStart = false; /** * Make a new thread for dipping rod * * @param rodSequence the sequence to play out * @param initialDelayMs some initial delay in ms * @param returnToStart whether to skip dip and just return smoothly to * starting point of sequence from current location */ public RodDipper(RodSequence rodSequence, long initialDelayMs, boolean returnToStart) { setName("RodDipper"); this.rodSequence = rodSequence; this.initialDelayMs = initialDelayMs; this.returnToStart = returnToStart; } public void run() { if (rodSequence == null || rodSequence.size() == 0) { log.warning("no sequence to play to dip rod"); return; } if (returnToStart) { returnToStart(); return; } lastFishingAttemptTimeMs = System.currentTimeMillis(); if (initialDelayMs > 0) { try { log.info("initial delay of " + initialDelayMs + " ms"); sleep(initialDelayMs); } catch (InterruptedException e) { log.info(String.format("Initial delay of %,d ms intettupted", initialDelayMs)); return; } } // Samples an angle variation with normal dist sigma of rodThetaSamplingSigmaDeg final double thetaSample = rodThetaSamplingSigmaDeg * (treatSigmasAsOffsets ? 1 : random.nextGaussian()); // Samples a delay around 0 with Gaussian spread of rodDipDelaySamplingSigmaMs around 0. // This delay reduces or increases time we wait to dip the rod after detecting fish and computing // the time it will take the fish to reach the rod tip location final double delaySamp = rodDipDelaySamplingSigmaMs * (treatSigmasAsOffsets ? 1 : (random.nextGaussian())); float randomThetaOffsetDeg = (float) (rodThetaOffset + thetaSample); int randomDelayMs = (int) Math.round(rodDipDelayMs + delaySamp); log.info(String.format("Theta offset learned+sample=%.1f + %.1f deg; Delay learned+sample=%d + %.0f", rodThetaOffset, thetaSample, rodDipDelayMs, delaySamp)); if (randomDelayMs > 0) { try { log.info("delaying additional random of fixed delay of " + randomDelayMs + " ms"); Thread.sleep(randomDelayMs); } catch (InterruptedException e) { log.info("Interrupted rod sequence during initial delay"); return; } } beepDipStartedPlayer.play(); boolean fishCaught = false; // flag set if we ever detect we caught a fish int counter = 0; for (RodPosition p : rodSequence) { if (aborted) { log.info("rod sequence aborted"); break; } if (p.delayMsToNext > 0) { try { long delMs = Math.round(p.delayMsToNext / rodDipSpeedUpFactor); sleep(delMs); // sleep before move, first sleep is zero ms } catch (InterruptedException e) { log.info("rod sequence interrupted"); break; } } sendRodPosition(false, (int) Math.round(p.thetaDeg + randomThetaOffsetDeg), p.zDeg); if (!fishCaught && isFishCaught()) { fishCaught = true; log.info(String.format("***** Detected fish caught at rod position # %d", counter)); break; // break out of loop here so we can raise the fish up } counter++; } // evaluate if we caught the fish if (fishCaught) { fishingResults.add(true, randomThetaOffsetDeg, randomDelayMs); sendRodPosition(false, lastRodTheta, 180); // raise rod high log.info(String.format("***** Success! Storing new values rodThetaOffset=%.2f deg, rodDipDelayMs=%,d ms\n Fishing disabled until fish removed", randomThetaOffsetDeg, randomDelayMs)); rodThetaOffset = randomThetaOffsetDeg; rodDipDelayMs = randomDelayMs; putFloat("rodThetaOffset", randomThetaOffsetDeg); putInt("rodDipDelayMs", randomDelayMs); setEnableFishing(true); beepSucessPlayer.play(); return; } else { fishingResults.add(false, randomThetaOffsetDeg, randomDelayMs); beepFailurePlayer.play(); } if (aborted) { return; } returnToStart(); // log.info("done returning"); lastFishingAttemptTimeMs = System.currentTimeMillis(); } private void returnToStart() { // move smoothly with minimum jerk back to starting position final RodPosition startingPosition = new RodPosition(0, lastRodTheta, lastRodZ); final RodPosition endingPosition = rodSequence.get(0); final Point2D start = new Point2D(startingPosition.thetaDeg, startingPosition.zDeg); final Point2D end = new Point2D(endingPosition.thetaDeg, endingPosition.zDeg); final double sampleRateHz = 25; final double dtS = 1 / sampleRateHz; final int dtMs = (int) Math.floor(dtS * 1000); final int dtRemNs = (int) (1e9 * (dtS - dtMs / 1000.)); final ArrayList<Point2D> traj = minimumJerkTrajectory(start, end, sampleRateHz, rodReturnDurationMs); // log.info(String.format("returning to starting position in %,d ms with minimum jerk trajectory of %d points", rodReturnDurationMs, traj.size())); for (Point2D p : traj) { int theta = (int) p.getX(); int z = (int) p.getY(); sendRodPosition(false, theta, z); try { Thread.sleep(dtMs, dtRemNs); } catch (InterruptedException ex) { return; } } sendRodPosition(false, endingPosition.thetaDeg, endingPosition.zDeg); } private void abort() { aborted = true; interrupt(); } /** * https://mika-s.github.io/python/control-theory/trajectory-generation/2017/12/06/trajectory-generation-with-a-minimum-jerk-trajectory.html */ private ArrayList<Point2D> minimumJerkTrajectory(Point2D start, Point2D end, double sampleRateHz, int moveDurationMs) { int nPoints = (int) ((moveDurationMs / 1000.) * sampleRateHz); ArrayList<Point2D> trajectory = new ArrayList<Point2D>(nPoints); Point2D diff = end.subtract(start); for (int i = 1; i <= nPoints; i++) { double f = (double) i / nPoints; double fac = 10.0 * Math.pow(f, 3) - 15.0 * Math.pow(f, 4) + 6.0 * Math.pow(f, 5); Point2D d = diff.multiply(fac); Point2D nextPoint = start.add(d); trajectory.add(nextPoint); } return trajectory; } }// end of rod dipper thread /** * @return the zMin */ public int getzMin() { return zMin; } /** * @param zMin the zMin to set */ public void setzMin(int zMin) { if (zMin < 0) { zMin = 0; } else if (zMin > 180) { zMin = 180; } this.zMin = zMin; putInt("zMin", zMin); resendRodPosition(); } private void resendRodPosition() { if (lastRodTheta != -1 && lastRodZ != -1) { sendRodPosition(false, lastRodTheta, lastRodZ); } } /** * @return the zMax */ public int getzMax() { return zMax; } /** * @param zMax the zMax to set */ public void setzMax(int zMax) { if (zMax < 0) { zMax = 0; } else if (zMax > 180) { zMax = 180; } this.zMax = zMax; putInt("zMax", zMax); resendRodPosition(); } /** * Base method to handle PropertyChangeEvent. It call super.propertyChange() * and then initFilter() when the AEChip size is changed, allowing filters * to allocate memory or do other initialization. Subclasses can override to * add more PropertyChangeEvent handling e.g from AEViewer or * AEFileInputStream. * * @param evt the PropertyChangeEvent, by jAER convention it is a constant * starting with EVENT_ */ @Override public void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); switch (evt.getPropertyName()) { case EVENT_ROD_POSITION: RodPosition rodPosition = (RodPosition) evt.getNewValue(); log.info("rodPosition=" + rodPosition.toString()); lastManualRodControlTime = System.currentTimeMillis(); sendRodPosition(false, rodPosition.thetaDeg, rodPosition.zDeg); break; case EVENT_ROD_SEQUENCE: RodSequence newSequnce = (RodSequence) evt.getNewValue(); newSequnce.save(); rodSequences[newSequnce.getIndex()] = newSequnce; log.info("got new " + rodSequences); showPlainMessageDialogInSwingThread(newSequnce.toString(), "New rod sequence"); break; case EVENT_CLEAR_SEQUENCES: for (RodSequence r : rodSequences) { r.clear(); r.save(); } log.info("Sequnces cleared"); break; default: } } /** * @return the disableServos */ public boolean isDisableServos() { return disableServos; } /** * @param disableServos the disableServos to set */ public void setDisableServos(boolean disableServos) { boolean old = this.disableServos; if (disableServos) { if (rodDipper != null) { rodDipper.abort(); } sendRodPosition(true, 0, 0); } this.disableServos = disableServos; getSupport().firePropertyChange("disableServos", old, disableServos); } /** * @return the enableFishing */ public boolean isEnableFishing() { return enableFishing; } /** * @param enableFishing the enableFishing to set */ public void setEnableFishing(boolean enableFishing) { boolean old = this.enableFishing; this.enableFishing = enableFishing; putBoolean("enableFishing", enableFishing); getSupport().firePropertyChange("enableFishing", old, this.enableFishing); if (!enableFishing) { RodSequence seq = rodSequences[currentRodsequenceIdx]; rodDipper = new RodDipper(seq, 0, true); log.info("moving rod to current sequence starting position"); rodDipper.start(); } } /** * @return the fishingHoleSwitchProbability */ public float getFishingHoleSwitchProbability() { return fishingHoleSwitchProbability; } /** * @param fishingHoleSwitchProbability the fishingHoleSwitchProbability to * set */ public void setFishingHoleSwitchProbability(float fishingHoleSwitchProbability) { if (fishingHoleSwitchProbability > 1) { fishingHoleSwitchProbability = 1; } else if (fishingHoleSwitchProbability < 0) { fishingHoleSwitchProbability = 0; } this.fishingHoleSwitchProbability = fishingHoleSwitchProbability; putFloat("fishingHoleSwitchProbability", fishingHoleSwitchProbability); } /** * @return the fishingAttemptHoldoffMs */ public int getFishingAttemptHoldoffMs() { return fishingAttemptHoldoffMs; } /** * @param fishingAttemptHoldoffMs the fishingAttemptHoldoffMs to set */ public void setFishingAttemptHoldoffMs(int fishingAttemptHoldoffMs) { this.fishingAttemptHoldoffMs = fishingAttemptHoldoffMs; putInt("fishingAttemptHoldoffMs", fishingAttemptHoldoffMs); } /** * @return the rodReturnDurationMs */ public int getRodReturnDurationMs() { return rodReturnDurationMs; } /** * @param rodReturnDurationMs the rodReturnDurationMs to set */ public void setRodReturnDurationMs(int rodReturnDurationMs) { this.rodReturnDurationMs = rodReturnDurationMs; putInt("rodReturnDurationMs", rodReturnDurationMs); } /** * @return the caughtFishDetectorThreshold */ public int getCaughtFishDetectorThreshold() { return caughtFishDetectorThreshold; } /** * @param caughtFishDetectorThreshold the caughtFishDetectorThreshold to set */ public void setCaughtFishDetectorThreshold(int caughtFishDetectorThreshold) { this.caughtFishDetectorThreshold = caughtFishDetectorThreshold; putInt("caughtFishDetectorThreshold", caughtFishDetectorThreshold); } /** * @return the rodThetaSamplingSigmaDeg */ public float getRodThetaSamplingSigmaDeg() { return rodThetaSamplingSigmaDeg; } /** * @param rodThetaSamplingSigmaDeg the rodThetaSamplingSigmaDeg to set */ public void setRodThetaSamplingSigmaDeg(float rodThetaSamplingSigmaDeg) { this.rodThetaSamplingSigmaDeg = rodThetaSamplingSigmaDeg; putFloat("rodThetaSamplingSigmaDeg", rodThetaSamplingSigmaDeg); } /** * @return the rodDipDelaySamplingSigmaMs */ public int getRodDipDelaySamplingSigmaMs() { return rodDipDelaySamplingSigmaMs; } /** * @param rodDipDelaySamplingSigmaMs the rodDipDelaySamplingSigmaMs to set */ public void setRodDipDelaySamplingSigmaMs(int rodDipDelaySamplingSigmaMs) { this.rodDipDelaySamplingSigmaMs = rodDipDelaySamplingSigmaMs; putInt("rodDipDelaySamplingSigmaMs", rodDipDelaySamplingSigmaMs); } /** * @return the treatSigmasAsOffsets */ public boolean isTreatSigmasAsOffsets() { return treatSigmasAsOffsets; } /** * @param treatSigmasAsOffsets the treatSigmasAsOffsets to set */ public void setTreatSigmasAsOffsets(boolean treatSigmasAsOffsets) { this.treatSigmasAsOffsets = treatSigmasAsOffsets; } /** * @return the rodDipSpeedUpFactor */ public float getRodDipSpeedUpFactor() { return rodDipSpeedUpFactor; } /** * @param rodDipSpeedUpFactor the rodDipSpeedUpFactor to set */ public void setRodDipSpeedUpFactor(float rodDipSpeedUpFactor) { this.rodDipSpeedUpFactor = rodDipSpeedUpFactor; putFloat("rodDipSpeedUpFactor", rodDipSpeedUpFactor); } }
src/org/ine/telluride/jaer/tell2022/GoingFishing.java
/* * Copyright (C) 2022 tobid. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.ine.telluride.jaer.tell2022; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import gnu.io.NRSerialPort; import java.awt.Color; import java.awt.Point; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Random; import java.util.Set; import javafx.geometry.Point2D; import javax.swing.JFrame; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.EventFilter2DMouseROI; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.SpatioTemporalCorrelationFilter; import net.sf.jaer.eventprocessing.filter.XYTypeFilter; import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker; import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker.Cluster; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.util.DrawGL; import net.sf.jaer.util.SoundWavFilePlayer; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; /** * Going fishing game from Under the sea Lets go Fishing from Pressman. It uses * an Arduino Nano to generate the PWM servo output for the rod pan tilt and to * read the ADC connected to the current sense amplifier reading the FSR402 * (https://www.amazon.com/dp/B074QLDCXQ?psc=1&ref=ppx_yo2ov_dt_b_product_details) * conductance that senses the fish hanging on the hook. An LP38841T-1.5 * regulator * (https://www.ti.com/general/docs/suppproductinfo.tsp?distId=26&gotoUrl=https://www.ti.com/lit/gpn/lp38841) * controls when the table pond turns. * * See https://youtu.be/AgESLgcEE7o for video of Gone Fishing robot. * * @author tobid, Julie Hasler (juliehsler) */ @Description("Let's go fishing (going fishing) game from Telluride 2022 with Tobi Delbruck and Julie Hasler") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class GoingFishing extends EventFilter2DMouseROI implements FrameAnnotater { FilterChain chain = null; RectangularClusterTracker tracker = null; Random random = new Random(); // serial port stuff NRSerialPort serialPort = null; private String serialPortName = getString("serialPortName", "COM3"); private int serialBaudRate = getInt("serialBaudRate", 115200); private DataOutputStream serialPortOutputStream = null; private DataInputStream serialPortInputStream = null; private AdcReader adcReader = null; private boolean disableServos = false; private boolean disableFishing = getBoolean("disableFishing", false); private final int SERIAL_WARNING_INTERVAL = 100; private int serialWarningCount = 0; // ADC for FSR that might detect caught fish private int lastAdcValue = -1; private int caughtFishDetectorThreshold = getInt("caughtFishDetectorThreshold", 550); // PropertyChange events public static final String EVENT_ROD_POSITION = "rodPosition", EVENT_ROD_SEQUENCE = "rodSequence", EVENT_CLEAR_SEQUENCES = "clearSequences"; // rod control private int zMin = getInt("zMin", 80); private int zMax = getInt("zMax", 100); // fishing rod dips RodDipper rodDipper = null; RodSequence[] rodSequences = {new RodSequence(0), new RodSequence(1)}; private int currentRodsequenceIdx = 0; private float fishingHoleSwitchProbability = getFloat("fishingHoleSwitchProbability", 0.1f); private int fishingAttemptHoldoffMs = getInt("fishingAttemptHoldoffMs", 3000); private long lastFishingAttemptTimeMs = 0; private int rodReturnDurationMs = getInt("rodReturnDurationMs", 1000); private boolean treatSigmasAsOffsets = getBoolean("treatSigmasAsOffsets", false); private float rodDipSpeedUpFactor = getFloat("rodDipSpeedUpFactor", 1f); // marking rod tip private boolean markRodTip = false; private Point2D rodTipLocation; private boolean markFishingPoleCenter = false; private Point2D fishingPoolCenterLocation; // measuring speed of fish DescriptiveStatistics fishSpeedStats; // reinforcement learning private float rodThetaOffset = getFloat("rodThetaOffset", 0); private int rodDipDelayMs = getInt("rodDipDelayMs", 0); private float rodThetaSamplingSigmaDeg = getFloat("rodThetaSamplingSigmaDeg", 2); private int rodDipDelaySamplingSigmaMs = getInt("rodDipDelaySamplingSigmaMs", 100); private long lastManualRodControlTime = 0; private static final long HOLDOFF_AFTER_MANUAL_CONTROL_MS = 1000; private int lastRodTheta = -1; private int lastRodZ = -1; // warnings private final int WARNING_INTERVAL = 100; private int missingRoiWarningCounter = 0; private int missingMarkedLocationsWarningCounter = 0; // results of fishing attempt private class FishingResult { boolean succeeded; float thetaOffsetDeg; long delayMs; public FishingResult(boolean succeeded, float thetaOffsetDeg, long delayMs) { this.succeeded = succeeded; this.thetaOffsetDeg = thetaOffsetDeg; this.delayMs = delayMs; } } // collected results private class FishingResults { private int rodDipTotalCount = 0, rodDipSuccessCount = 0, rodDipFailureCount = 0; private ArrayList<FishingResult> fishingResultsList = new ArrayList(); void clear() { rodDipTotalCount = 0; rodDipSuccessCount = 0; rodDipFailureCount = 0; fishingResultsList.clear(); } private void add(boolean b, float randomThetaOffsetDeg, int randomDelayMs) { rodDipTotalCount++; fishingResultsList.add(new FishingResult(b, randomThetaOffsetDeg, randomDelayMs)); if (b) { rodDipSuccessCount++; } else { rodDipFailureCount++; } } } private FishingResults fishingResults = new FishingResults(); // sounds SoundWavFilePlayer beepFishDetectedPlayer = null, beepDipStartedPlayer = null, beepFailurePlayer = null, beepSucessPlayer = null; public GoingFishing(AEChip chip) { super(chip); chain = new FilterChain(chip); tracker = new RectangularClusterTracker(chip); chain.add(new XYTypeFilter(chip)); chain.add(new SpatioTemporalCorrelationFilter(chip)); chain.add(tracker); setEnclosedFilterChain(chain); String ser = "Serial port", rod = "Rod control", ler = "Learning",enb="Enable/Disable"; setPropertyTooltip(ser, "serialPortName", "Name of serial port to send robot commands to"); setPropertyTooltip(ser, "serialBaudRate", "Baud rate (default 115200), upper limit 12000000"); setPropertyTooltip(rod, "showFishingRodControlPanel", "show control panel for fishing rod"); setPropertyTooltip(rod, "dipRod", "make a fishing movement"); setPropertyTooltip(rod, "abortDip", "abort rod dipping if active"); setPropertyTooltip(rod, "resetLearning", "reset learned theta and delay parameters"); setPropertyTooltip(rod, "rodDipSpeedUpFactor", "factor by which to speed up rod dip sequence over recorded speed"); setPropertyTooltip(rod, "markRodTipLocation", "Mark the location of rod tip and hook with next left mouse click"); setPropertyTooltip(rod, "markFishingPoolCenter", "Mark the location of center of fishing pool with next left mouse click"); setPropertyTooltip(rod, "zMin", "min rod tilt angle in deg"); setPropertyTooltip(rod, "zMax", "max rod tilt angle in deg"); setPropertyTooltip(enb,"runPond", "Turn on the pond motor via 1.5V regulator"); setPropertyTooltip(rod, "fishingAttemptHoldoffMs", "holdoff time in ms between automatic fishing attempts"); setPropertyTooltip(rod, "rodReturnDurationMs", "duration in ms of minimum-jerk movement back to starting point of fishing rod sequence"); setPropertyTooltip(enb,"disableServos", "turn off servos"); setPropertyTooltip(enb,"disableFishing", "disable automatic fishing"); setPropertyTooltip(enb,"enableFishing", "disable automatic fishing"); setPropertyTooltip(ler, "fishingHoleSwitchProbability", "chance of switching spots after each attempt"); setPropertyTooltip(ler, "caughtFishDetectorThreshold", "threshold ADC count from FSR to detect that we caught a fish"); setPropertyTooltip(ler, "rodDipDelaySamplingSigmaMs", "spread of uniformly-sampled delay in ms to sample new rod dip starting delay"); setPropertyTooltip(ler, "rodThetaSamplingSigmaDeg", "sigma in deg to sample new rod dip pan offsets"); setPropertyTooltip(ler, "treatSigmasAsOffsets", "Use the sigma values for theta and delay as fixed offsets to manually tune the fishing"); try { for (int i = 0; i < 2; i++) { rodSequences[i].load(i); log.info("loaded " + rodSequences.toString()); } } catch (Exception e) { log.warning("Could not load fishing rod movement sequence: " + e.toString()); } Object o = null; o = getObject("rodTipLocation", null); if (o instanceof java.awt.Point) { Point p = (java.awt.Point) o; rodTipLocation = new Point2D(p.x, p.y); } else { rodTipLocation = null; } o = getObject("fishingPoolCenterLocation", null); if (o instanceof java.awt.Point) { Point p = (java.awt.Point) o; fishingPoolCenterLocation = new Point2D(p.x, p.y); } else { fishingPoolCenterLocation = null; } try { String s; // https://www.soundjay.com/beep-sounds-1.html#google_vignette s = "src/org/ine/telluride/jaer/tell2022/beeps/beep-07a.wav"; beepFishDetectedPlayer = new SoundWavFilePlayer(s); s = "src/org/ine/telluride/jaer/tell2022/beeps/beep-08b.wav"; beepDipStartedPlayer = new SoundWavFilePlayer(s); s = "src/org/ine/telluride/jaer/tell2022/beeps/beep-03-fail.wav"; beepFailurePlayer = new SoundWavFilePlayer(s); s = "src/org/ine/telluride/jaer/tell2022/beeps/success.wav"; beepSucessPlayer = new SoundWavFilePlayer(s); } catch (Exception e) { log.warning("Could not load beep sound: " + e.toString()); } fishSpeedStats = new DescriptiveStatistics(30); } @Override public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) { in = getEnclosedFilterChain().filterPacket(in); checkForFishingAttempt(); return in; } private void checkForFishingAttempt() { long currentTimeMs = System.currentTimeMillis(); if (roiRects == null || roiRects.isEmpty()) { if (missingRoiWarningCounter % WARNING_INTERVAL == 0) { log.warning("draw at least 1 or at most 2 ROIs for detecting fish before it comes to rod tip"); } missingRoiWarningCounter++; return; } if (rodDipper != null && rodDipper.isAlive()) { return; } if (currentTimeMs - lastManualRodControlTime > HOLDOFF_AFTER_MANUAL_CONTROL_MS) { LinkedList<Cluster> clusterList = tracker.getVisibleClusters(); for (Cluster c : clusterList) { Point p = new Point((int) c.getLocation().x, (int) c.getLocation().y); int roi = isInsideWhichROI(p); long delay = 0; if (roi >= 0 && roi == currentRodsequenceIdx) { // The ROI entered matches the current fishing rod sequence ROI // this ROI we drew contains a fish cluster if (rodTipLocation == null || fishingPoolCenterLocation == null) { if (missingMarkedLocationsWarningCounter % WARNING_INTERVAL == 0) { log.warning("Set rod tip and center of pool locations to estimate delay for fishing motion"); } missingMarkedLocationsWarningCounter++; } else { float fishSpeedPps = c.getSpeedPPS(); fishSpeedStats.addValue(fishSpeedPps); // filter fishSpeedPps = (float) fishSpeedStats.getPercentile(50); // get median value of speed to filter outliers final Point2D clusterLoc = new Point2D(c.getLocation().x, c.getLocation().y); Point2D rodTipRay = rodTipLocation.subtract(fishingPoolCenterLocation); final float radius = (float) rodTipRay.magnitude(); Point2D clusterRay = clusterLoc.subtract(fishingPoolCenterLocation); final double angleDegFishToTip = rodTipRay.angle(clusterRay); final double angularSpeedDegPerS = (180 / Math.PI) * (fishSpeedPps / radius); final int msForFishToReachRodTip = (int) (1000 * angleDegFishToTip / angularSpeedDegPerS); final long timeToMinZMs = Math.round(rodSequences[currentRodsequenceIdx].timeToMinZMs / rodDipSpeedUpFactor); if (msForFishToReachRodTip < timeToMinZMs) { log.warning(String.format("msForFishToReachRodTip=%,d ms is less than rod sequence timeToMinZMs=%,d ms;\n" + "Speed=%.1f px/s, radius=%.1f px, angularSpeed=%.1f deg/s angleDegFishToTip=%.1f deg", msForFishToReachRodTip, timeToMinZMs, fishSpeedPps, radius, angularSpeedDegPerS, angleDegFishToTip)); } else { delay = msForFishToReachRodTip - timeToMinZMs - rodDipDelaySamplingSigmaMs; // log.info(String.format("msForFishToReachRodTip=%,d ms is more than rod sequence timeToMinZMs=%,d ms;\n" // + "Speed=%.1f px/s, radius=%.1f px, angularSpeed=%.1f deg/s angleDegFishToTip=%.1f deg", msForFishToReachRodTip, timeToMinZMs, // fishSpeedPps, radius, angularSpeedDegPerS, angleDegFishToTip)); } } if (rodDipper == null || !rodDipper.isAlive()) { // log.info(String.format("Detected fish in ROI at location %s becoming contained by ROI rectangle %s", c.getLocation(), roiRects.get(roi))); if (!disableFishing) { dipRodWithHoldoffAndDelay(delay); break; } } } } } } /** * Annotates the display with GoingFishing stuff. * * @param drawable */ public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); GL2 gl = drawable.getGL().getGL2(); if (rodTipLocation != null) { gl.glPushMatrix(); gl.glColor3f(1, 0, 0); DrawGL.drawCross(gl, (float) rodTipLocation.getX(), (float) rodTipLocation.getY(), 6, 0); DrawGL.drawStrinDropShadow(gl, 12, 0, 0, 0, Color.red, "Tip"); gl.glPopMatrix(); } if (fishingPoolCenterLocation != null) { gl.glPushMatrix(); gl.glColor3f(1, 0, 0); DrawGL.drawCross(gl, (float) fishingPoolCenterLocation.getX(), (float) fishingPoolCenterLocation.getY(), 6, 0); DrawGL.drawStrinDropShadow(gl, 12, 0, 0, 0, Color.red, "Center"); gl.glPopMatrix(); } gl.glPushMatrix(); final float adcY = chip.getSizeY() / 10; final float adcStartX = 2; if (lastAdcValue != -1) { gl.glLineWidth(5); gl.glColor3f(1, 1, 1); final float adcLen = .9f * chip.getSizeX() * (lastAdcValue / 1024f); DrawGL.drawLine(gl, adcStartX, adcY, adcLen, 0, 1); DrawGL.drawStrinDropShadow(gl, 12, adcStartX + adcLen + 2, adcY, 0, Color.white, Integer.toString(lastAdcValue)); } else { DrawGL.drawStrinDropShadow(gl, 12, adcStartX, adcY, 0, Color.white, "ADC: N/A"); } if (isFishCaught()) { gl.glColor3f(1, 1, 1); DrawGL.drawStrinDropShadow(gl, 36, chip.getSizeX() / 2, chip.getSizeY() / 2, .5f, Color.white, "Caught!"); } final float statsY = 2 * chip.getSizeY() / 10; String s = String.format("Tries: %d, Success: %d (%.1f%%); thetaOffset=%.1f deg, delayMs=%d ms", fishingResults.rodDipTotalCount, fishingResults.rodDipSuccessCount, (100 * (float) fishingResults.rodDipSuccessCount / fishingResults.rodDipTotalCount), rodThetaOffset, rodDipDelayMs); DrawGL.drawStrinDropShadow(gl, 10, adcStartX, statsY, 0, Color.white, s); gl.glPopMatrix(); } @Override public void resetFilter() { fishingResults.clear(); fishSpeedStats.clear(); } @Override public void initFilter() { } public void doDipRod() { dipRodNow(0); } public void doAbortDip() { if (rodDipper != null) { rodDipper.abort(); } } public void doToggleOnRunPond() { enablePond(true); } public void doToggleOffRunPond() { enablePond(false); } public void doToggleOnEnableFishing(){ setDisableFishing(false); } public void doToggleOffEnableFishing(){ setDisableFishing(true); } private void enablePond(boolean enable) { if (!checkSerialPort()) { log.warning("serial port not open"); return; } byte[] bytes = new byte[3]; bytes[0] = enable ? (byte) 2 : (byte) 3; // send 2 to run, 3 to stop synchronized (serialPortOutputStream) { try { serialPortOutputStream.write(bytes); serialPortOutputStream.flush(); log.info(enable ? "Turned on pong" : "Turned off pond"); } catch (IOException ex) { log.warning(ex.toString()); } } } public void doResetLearning() { rodDipDelayMs = 0; rodThetaOffset = 0; putInt("rodDipDelayMs", 0); putFloat("rodThetaOffset", 0); fishingResults.clear(); } public void doMarkRodTipLocation() { markRodTip = true; markFishingPoleCenter = false; } public void doMarkFishingPoolCenter() { markFishingPoleCenter = true; markRodTip = false; } @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (markRodTip) { markRodTip = false; rodTipLocation = new Point2D(clickedPoint.x, clickedPoint.y); putObject("rodTipLocation", new Point((int) rodTipLocation.getX(), (int) rodTipLocation.getY())); } else if (markFishingPoleCenter) { markFishingPoleCenter = false; fishingPoolCenterLocation = new Point2D(clickedPoint.x, clickedPoint.y); putObject("fishingPoolCenterLocation", new Point((int) fishingPoolCenterLocation.getX(), (int) fishingPoolCenterLocation.getY())); } } private void openSerial() throws IOException { if (serialPort != null) { closeSerial(); } checkBaudRate(serialBaudRate); StringBuilder sb = new StringBuilder("List of all available serial ports: "); final Set<String> availableSerialPorts = NRSerialPort.getAvailableSerialPorts(); if (availableSerialPorts.isEmpty()) { sb.append("\nNo ports found, sorry. If you are on linux, serial port support may suffer"); } else { for (String s : availableSerialPorts) { sb.append(s).append(" "); } } if (!availableSerialPorts.contains(serialPortName)) { final String warningString = serialPortName + " is not in avaiable " + sb.toString(); throw new IOException(warningString); } serialPort = new NRSerialPort(serialPortName, serialBaudRate); if (serialPort == null) { final String warningString = "null serial port returned when trying to open " + serialPortName + "; available " + sb.toString(); throw new IOException(warningString); } if (serialPort.connect()) { serialPortOutputStream = new DataOutputStream(serialPort.getOutputStream()); serialPortInputStream = new DataInputStream(serialPort.getInputStream()); while (serialPortInputStream.available() > 0) { serialPortInputStream.read(); } adcReader = new AdcReader(serialPortInputStream); adcReader.start(); log.info("opened serial port " + serialPortName + " with baud rate=" + serialBaudRate); } else { log.warning("cannot connect serial port" + serialPortName); } } private void closeSerial() { if (serialPortOutputStream != null) { try { serialPortOutputStream.write((byte) '0'); // rest; turn off servos serialPortOutputStream.close(); } catch (IOException ex) { log.warning(ex.toString()); } serialPortOutputStream = null; } if (adcReader != null && adcReader.isAlive()) { adcReader.shutdown(); try { adcReader.join(200); } catch (InterruptedException e) { } } if ((serialPort != null) && serialPort.isConnected()) { serialPort.disconnect(); serialPort = null; } lastRodTheta = -1; lastRodZ = -1; lastAdcValue = -1; } synchronized private boolean checkSerialPort() { if ((serialPort == null)) { try { openSerial(); } catch (IOException ex) { if (serialWarningCount++ == SERIAL_WARNING_INTERVAL) { log.warning("couldn't open serial port " + serialPortName); serialWarningCount = 0; } return false; } } return true; } @Override public void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (!yes) { disableServos(); closeSerial(); } else { try { openSerial(); } catch (IOException ex) { log.warning("couldn't open serial port " + serialPortName); } } } @Override public void cleanup() { disableServos(); } /** * @return the serialBaudRate */ public int getSerialBaudRate() { return serialBaudRate; } /** * @param serialBaudRate the serialBaudRate to set */ public void setSerialBaudRate(int serialBaudRate) { try { checkBaudRate(serialBaudRate); this.serialBaudRate = serialBaudRate; putInt("serialBaudRate", serialBaudRate); openSerial(); } catch (IOException ex) { log.warning(ex.toString()); } } private void checkBaudRate(int serialBaudRate1) { if (serialBaudRate1 != 9600 && serialBaudRate1 != 115200) { showWarningDialogInSwingThread(String.format("Selected baud rate of %,d baud is neither 9600 or 115200, please check it", serialBaudRate1), "Invalid baud rate?"); log.warning(String.format("Possible invalid baud rate %,d", serialBaudRate1)); } } /** * @return the serialPortName */ public String getSerialPortName() { return serialPortName; } /** * @param serialPortName the serialPortName to set */ public void setSerialPortName(String serialPortName) { try { this.serialPortName = serialPortName; putString("serialPortName", serialPortName); openSerial(); } catch (IOException ex) { log.warning("couldn't open serial port: " + ex.toString()); } } /** * Either turns off servos or sets servo positions * * @param disable true to turn off servos * @param theta otherwise the angle of pan (in degrees, 0-180) * @param z and tilt (in degrees, 0-180) */ private void sendRodPosition(boolean disable, int theta, int z) { if (disableServos) { return; } if (checkSerialPort()) { int zSent = (int) Math.floor(zMin + (((float) (zMax - zMin)) / 180) * z); try { // write theta (pan) and z (tilt) of fishing pole as two unsigned byte servo angles and degrees byte[] bytes = new byte[3]; bytes[0] = disable ? (byte) 1 : (byte) 0; bytes[1] = (byte) (theta); bytes[2] = (byte) (zSent); synchronized (serialPortOutputStream) { serialPortOutputStream.write(bytes); serialPortOutputStream.flush(); } this.lastRodTheta = theta; this.lastRodZ = z; } catch (IOException ex) { log.warning(ex.toString()); } } } private void disableServos() { setDisableServos(true); } public void doShowFishingRodControlPanel() { showFishingRodControPanel(); } private JFrame fishingRodControlFrame = null; private void showFishingRodControPanel() { if (fishingRodControlFrame == null) { fishingRodControlFrame = new GoingFishingFishingRodControlFrame(); fishingRodControlFrame.addPropertyChangeListener(EVENT_ROD_POSITION, this); fishingRodControlFrame.addPropertyChangeListener(EVENT_ROD_SEQUENCE, this); fishingRodControlFrame.addPropertyChangeListener(EVENT_CLEAR_SEQUENCES, this); } fishingRodControlFrame.setVisible(true); } /** * Do the fishing move * * @param holdoff set true to enforce a holdoff of fishingAttemptHoldoffMs, * false to dip unconditionally if servos are enabled and dip is not already * running since the end of the last attempt */ private void dipRodWithHoldoffAndDelay(long delayMs) { final long dt = System.currentTimeMillis() - lastFishingAttemptTimeMs; if (dt < 0 || dt > fishingAttemptHoldoffMs) { beepFishDetectedPlayer.play(); dipRodNow(delayMs); } } /** * Do the fishing move * * @param delayMs delay to set at start of dip in ms */ private void dipRodNow(long delayMs) { if (disableServos) { log.warning("servos disabled, will not run " + rodSequences); return; } if (rodDipper != null && rodDipper.isAlive()) { log.warning("aborting running rod sequence"); rodDipper.abort(); try { rodDipper.join(100); } catch (InterruptedException e) { } } int nextSeq = (currentRodsequenceIdx + 1) % 2; if (rodSequences[nextSeq].size() > 0 && random.nextFloat() <= fishingHoleSwitchProbability) { currentRodsequenceIdx = nextSeq; log.info("switched to " + rodSequences[currentRodsequenceIdx]); } RodSequence seq = rodSequences[currentRodsequenceIdx]; rodDipper = new RodDipper(seq, delayMs, false); // log.info("running " + rodSequences.toString()); rodDipper.start(); } private boolean isFishCaught() { return lastAdcValue > caughtFishDetectorThreshold; } private class AdcReader extends Thread { DataInputStream stream; public AdcReader(DataInputStream stream) { this.stream = stream; } synchronized public void shutdown() { try { serialPortInputStream.close(); } catch (IOException e) { } serialPortInputStream = null; return; } public void run() { while (serialPortInputStream != null) { try { byte[] buf = new byte[2]; serialPortInputStream.readFully(buf); lastAdcValue = (int) ((buf[0] & 0xff) * 256 + (0xff & buf[1])); // System.out.println(String.format("ADC: available=%d val=%d", navail, lastAdcValue)); } catch (IOException ex) { log.warning("serial port error while reading ADC value: " + ex.toString()); closeSerial(); } } } } private class RodDipper extends Thread { RodSequence rodSequence = null; volatile boolean aborted = false; private long initialDelayMs = 0; private boolean returnToStart = false; /** * Make a new thread for dipping rod * * @param rodSequence the sequence to play out * @param initialDelayMs some initial delay in ms * @param returnToStart whether to skip dip and just return smoothly to * starting point of sequence from current location */ public RodDipper(RodSequence rodSequence, long initialDelayMs, boolean returnToStart) { setName("RodDipper"); this.rodSequence = rodSequence; this.initialDelayMs = initialDelayMs; this.returnToStart = returnToStart; } public void run() { if (rodSequence == null || rodSequence.size() == 0) { log.warning("no sequence to play to dip rod"); return; } if (returnToStart) { returnToStart(); return; } lastFishingAttemptTimeMs = System.currentTimeMillis(); if (initialDelayMs > 0) { try { log.info("initial delay of " + initialDelayMs + " ms"); sleep(initialDelayMs); } catch (InterruptedException e) { log.info(String.format("Initial delay of %,d ms intettupted", initialDelayMs)); return; } } // Samples an angle variation with normal dist sigma of rodThetaSamplingSigmaDeg final double thetaSample = rodThetaSamplingSigmaDeg * (treatSigmasAsOffsets ? 1 : random.nextGaussian()); // Samples a delay around 0 with Gaussian spread of rodDipDelaySamplingSigmaMs around 0. // This delay reduces or increases time we wait to dip the rod after detecting fish and computing // the time it will take the fish to reach the rod tip location final double delaySamp = rodDipDelaySamplingSigmaMs * (treatSigmasAsOffsets ? 1 : (random.nextGaussian())); float randomThetaOffsetDeg = (float) (rodThetaOffset + thetaSample); int randomDelayMs = (int) Math.round(rodDipDelayMs + delaySamp); log.info(String.format("Theta offset learned+sample=%.1f + %.1f deg; Delay learned+sample=%d + %.0f", rodThetaOffset, thetaSample, rodDipDelayMs, delaySamp)); if (randomDelayMs > 0) { try { log.info("delaying additional random of fixed delay of " + randomDelayMs + " ms"); Thread.sleep(randomDelayMs); } catch (InterruptedException e) { log.info("Interrupted rod sequence during initial delay"); return; } } beepDipStartedPlayer.play(); boolean fishCaught = false; // flag set if we ever detect we caught a fish int counter = 0; for (RodPosition p : rodSequence) { if (aborted) { log.info("rod sequence aborted"); break; } if (p.delayMsToNext > 0) { try { long delMs = Math.round(p.delayMsToNext / rodDipSpeedUpFactor); sleep(delMs); // sleep before move, first sleep is zero ms } catch (InterruptedException e) { log.info("rod sequence interrupted"); break; } } sendRodPosition(false, (int) Math.round(p.thetaDeg + randomThetaOffsetDeg), p.zDeg); if (!fishCaught && isFishCaught()) { fishCaught = true; log.info(String.format("***** Detected fish caught at rod position # %d", counter)); break; // break out of loop here so we can raise the fish up } counter++; } // evaluate if we caught the fish if (fishCaught) { fishingResults.add(true, randomThetaOffsetDeg, randomDelayMs); sendRodPosition(false, lastRodTheta, 180); // raise rod high log.info(String.format("***** Success! Storing new values rodThetaOffset=%.2f deg, rodDipDelayMs=%,d ms\n Fishing disabled until fish removed", randomThetaOffsetDeg, randomDelayMs)); rodThetaOffset = randomThetaOffsetDeg; rodDipDelayMs = randomDelayMs; putFloat("rodThetaOffset", randomThetaOffsetDeg); putInt("rodDipDelayMs", randomDelayMs); setDisableFishing(true); beepSucessPlayer.play(); return; } else { fishingResults.add(false, randomThetaOffsetDeg, randomDelayMs); beepFailurePlayer.play(); } if (aborted) { return; } returnToStart(); // log.info("done returning"); lastFishingAttemptTimeMs = System.currentTimeMillis(); } private void returnToStart() { // move smoothly with minimum jerk back to starting position final RodPosition startingPosition = new RodPosition(0, lastRodTheta, lastRodZ); final RodPosition endingPosition = rodSequence.get(0); final Point2D start = new Point2D(startingPosition.thetaDeg, startingPosition.zDeg); final Point2D end = new Point2D(endingPosition.thetaDeg, endingPosition.zDeg); final double sampleRateHz = 100; final double dtS = 1 / sampleRateHz; final int dtMs = (int) Math.floor(dtS * 1000); final int dtRemNs = (int) (1e9 * (dtS - dtMs / 1000.)); final ArrayList<Point2D> traj = minimumJerkTrajectory(start, end, sampleRateHz, rodReturnDurationMs); // log.info(String.format("returning to starting position in %,d ms with minimum jerk trajectory of %d points", rodReturnDurationMs, traj.size())); for (Point2D p : traj) { int theta = (int) p.getX(); int z = (int) p.getY(); sendRodPosition(false, theta, z); try { Thread.sleep(dtMs, dtRemNs); } catch (InterruptedException ex) { return; } } sendRodPosition(false, endingPosition.thetaDeg, endingPosition.zDeg); } private void abort() { aborted = true; interrupt(); } /** * https://mika-s.github.io/python/control-theory/trajectory-generation/2017/12/06/trajectory-generation-with-a-minimum-jerk-trajectory.html */ private ArrayList<Point2D> minimumJerkTrajectory(Point2D start, Point2D end, double sampleRateHz, int moveDurationMs) { int nPoints = (int) ((moveDurationMs / 1000.) * sampleRateHz); ArrayList<Point2D> trajectory = new ArrayList<Point2D>(nPoints); Point2D diff = end.subtract(start); for (int i = 1; i <= nPoints; i++) { double f = (double) i / nPoints; double fac = 10.0 * Math.pow(f, 3) - 15.0 * Math.pow(f, 4) + 6.0 * Math.pow(f, 5); Point2D d = diff.multiply(fac); Point2D nextPoint = start.add(d); trajectory.add(nextPoint); } return trajectory; } }// end of rod dipper thread /** * @return the zMin */ public int getzMin() { return zMin; } /** * @param zMin the zMin to set */ public void setzMin(int zMin) { if (zMin < 0) { zMin = 0; } else if (zMin > 180) { zMin = 180; } this.zMin = zMin; putInt("zMin", zMin); resendRodPosition(); } private void resendRodPosition() { if (lastRodTheta != -1 && lastRodZ != -1) { sendRodPosition(false, lastRodTheta, lastRodZ); } } /** * @return the zMax */ public int getzMax() { return zMax; } /** * @param zMax the zMax to set */ public void setzMax(int zMax) { if (zMax < 0) { zMax = 0; } else if (zMax > 180) { zMax = 180; } this.zMax = zMax; putInt("zMax", zMax); resendRodPosition(); } /** * Base method to handle PropertyChangeEvent. It call super.propertyChange() * and then initFilter() when the AEChip size is changed, allowing filters * to allocate memory or do other initialization. Subclasses can override to * add more PropertyChangeEvent handling e.g from AEViewer or * AEFileInputStream. * * @param evt the PropertyChangeEvent, by jAER convention it is a constant * starting with EVENT_ */ @Override public void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); switch (evt.getPropertyName()) { case EVENT_ROD_POSITION: RodPosition rodPosition = (RodPosition) evt.getNewValue(); log.info("rodPosition=" + rodPosition.toString()); lastManualRodControlTime = System.currentTimeMillis(); sendRodPosition(false, rodPosition.thetaDeg, rodPosition.zDeg); break; case EVENT_ROD_SEQUENCE: RodSequence newSequnce = (RodSequence) evt.getNewValue(); newSequnce.save(); rodSequences[newSequnce.getIndex()] = newSequnce; log.info("got new " + rodSequences); showPlainMessageDialogInSwingThread(newSequnce.toString(), "New rod sequence"); break; case EVENT_CLEAR_SEQUENCES: for (RodSequence r : rodSequences) { r.clear(); r.save(); } log.info("Sequnces cleared"); break; default: } } /** * @return the disableServos */ public boolean isDisableServos() { return disableServos; } /** * @param disableServos the disableServos to set */ public void setDisableServos(boolean disableServos) { boolean old = this.disableServos; if (disableServos) { if (rodDipper != null) { rodDipper.abort(); } sendRodPosition(true, 0, 0); } this.disableServos = disableServos; getSupport().firePropertyChange("disableServos", old, disableServos); } /** * @return the disableFishing */ public boolean isDisableFishing() { return disableFishing; } /** * @param disableFishing the disableFishing to set */ public void setDisableFishing(boolean disableFishing) { boolean old = this.disableFishing; this.disableFishing = disableFishing; putBoolean("disableFishing", disableFishing); getSupport().firePropertyChange("disableFishing", old, this.disableFishing); if (!disableFishing) { RodSequence seq = rodSequences[currentRodsequenceIdx]; rodDipper = new RodDipper(seq, 0, true); log.info("moving rod to current sequence starting position"); rodDipper.start(); } } /** * @return the fishingHoleSwitchProbability */ public float getFishingHoleSwitchProbability() { return fishingHoleSwitchProbability; } /** * @param fishingHoleSwitchProbability the fishingHoleSwitchProbability to * set */ public void setFishingHoleSwitchProbability(float fishingHoleSwitchProbability) { if (fishingHoleSwitchProbability > 1) { fishingHoleSwitchProbability = 1; } else if (fishingHoleSwitchProbability < 0) { fishingHoleSwitchProbability = 0; } this.fishingHoleSwitchProbability = fishingHoleSwitchProbability; putFloat("fishingHoleSwitchProbability", fishingHoleSwitchProbability); } /** * @return the fishingAttemptHoldoffMs */ public int getFishingAttemptHoldoffMs() { return fishingAttemptHoldoffMs; } /** * @param fishingAttemptHoldoffMs the fishingAttemptHoldoffMs to set */ public void setFishingAttemptHoldoffMs(int fishingAttemptHoldoffMs) { this.fishingAttemptHoldoffMs = fishingAttemptHoldoffMs; putInt("fishingAttemptHoldoffMs", fishingAttemptHoldoffMs); } /** * @return the rodReturnDurationMs */ public int getRodReturnDurationMs() { return rodReturnDurationMs; } /** * @param rodReturnDurationMs the rodReturnDurationMs to set */ public void setRodReturnDurationMs(int rodReturnDurationMs) { this.rodReturnDurationMs = rodReturnDurationMs; putInt("rodReturnDurationMs", rodReturnDurationMs); } /** * @return the caughtFishDetectorThreshold */ public int getCaughtFishDetectorThreshold() { return caughtFishDetectorThreshold; } /** * @param caughtFishDetectorThreshold the caughtFishDetectorThreshold to set */ public void setCaughtFishDetectorThreshold(int caughtFishDetectorThreshold) { this.caughtFishDetectorThreshold = caughtFishDetectorThreshold; putInt("caughtFishDetectorThreshold", caughtFishDetectorThreshold); } /** * @return the rodThetaSamplingSigmaDeg */ public float getRodThetaSamplingSigmaDeg() { return rodThetaSamplingSigmaDeg; } /** * @param rodThetaSamplingSigmaDeg the rodThetaSamplingSigmaDeg to set */ public void setRodThetaSamplingSigmaDeg(float rodThetaSamplingSigmaDeg) { this.rodThetaSamplingSigmaDeg = rodThetaSamplingSigmaDeg; putFloat("rodThetaSamplingSigmaDeg", rodThetaSamplingSigmaDeg); } /** * @return the rodDipDelaySamplingSigmaMs */ public int getRodDipDelaySamplingSigmaMs() { return rodDipDelaySamplingSigmaMs; } /** * @param rodDipDelaySamplingSigmaMs the rodDipDelaySamplingSigmaMs to set */ public void setRodDipDelaySamplingSigmaMs(int rodDipDelaySamplingSigmaMs) { this.rodDipDelaySamplingSigmaMs = rodDipDelaySamplingSigmaMs; putInt("rodDipDelaySamplingSigmaMs", rodDipDelaySamplingSigmaMs); } /** * @return the treatSigmasAsOffsets */ public boolean isTreatSigmasAsOffsets() { return treatSigmasAsOffsets; } /** * @param treatSigmasAsOffsets the treatSigmasAsOffsets to set */ public void setTreatSigmasAsOffsets(boolean treatSigmasAsOffsets) { this.treatSigmasAsOffsets = treatSigmasAsOffsets; } /** * @return the rodDipSpeedUpFactor */ public float getRodDipSpeedUpFactor() { return rodDipSpeedUpFactor; } /** * @param rodDipSpeedUpFactor the rodDipSpeedUpFactor to set */ public void setRodDipSpeedUpFactor(float rodDipSpeedUpFactor) { this.rodDipSpeedUpFactor = rodDipSpeedUpFactor; putFloat("rodDipSpeedUpFactor", rodDipSpeedUpFactor); } }
added plotting of successes and failures of fishing tries.
src/org/ine/telluride/jaer/tell2022/GoingFishing.java
added plotting of successes and failures of fishing tries.
<ide><path>rc/org/ine/telluride/jaer/tell2022/GoingFishing.java <ide> */ <ide> package org.ine.telluride.jaer.tell2022; <ide> <add>import com.github.sh0nk.matplotlib4j.Plot; <ide> import com.jogamp.opengl.GL2; <ide> import com.jogamp.opengl.GLAutoDrawable; <ide> import gnu.io.NRSerialPort; <ide> private DataInputStream serialPortInputStream = null; <ide> private AdcReader adcReader = null; <ide> private boolean disableServos = false; <del> private boolean disableFishing = getBoolean("disableFishing", false); <add> private boolean enableFishing = getBoolean("enableFishing", false); <ide> private final int SERIAL_WARNING_INTERVAL = 100; <ide> private int serialWarningCount = 0; <ide> <ide> private int rodDipTotalCount = 0, rodDipSuccessCount = 0, rodDipFailureCount = 0; <ide> <ide> private ArrayList<FishingResult> fishingResultsList = new ArrayList(); <add> private ArrayList<Float> sucTheta = new ArrayList(), failTheta = new ArrayList(), sucDelay = new ArrayList(), failDelay = new ArrayList(); <ide> <ide> void clear() { <ide> rodDipTotalCount = 0; <ide> rodDipSuccessCount = 0; <ide> rodDipFailureCount = 0; <ide> fishingResultsList.clear(); <del> } <del> <add> sucTheta.clear(); <add> failTheta.clear(); <add> sucDelay.clear(); <add> failDelay.clear(); <add> } <add> <add> /** <add> * add fishing result <add> * <add> * @param b true for success, false for failure <add> * @param randomThetaOffsetDeg <add> * @param randomDelayMs <add> */ <ide> private void add(boolean b, float randomThetaOffsetDeg, int randomDelayMs) { <ide> rodDipTotalCount++; <ide> fishingResultsList.add(new FishingResult(b, randomThetaOffsetDeg, randomDelayMs)); <ide> if (b) { <ide> rodDipSuccessCount++; <add> sucTheta.add(randomThetaOffsetDeg); <add> sucDelay.add((float) randomDelayMs); <ide> } else { <ide> rodDipFailureCount++; <add> failTheta.add(randomThetaOffsetDeg); <add> failDelay.add((float) randomDelayMs); <add> } <add> } <add> <add> private void plot() { <add> <add> Plot plt = Plot.create(); // see https://github.com/sh0nk/matplotlib4j <add> plt.subplot(1, 1, 1); <add> plt.title("Fishing results"); <add> plt.xlabel("delay (ms)"); <add> plt.ylabel("angle (deg)"); <add> plt.plot().add(sucDelay, sucTheta, "go").linewidth(1).linestyle("None"); <add> plt.plot().add(failDelay, failTheta, "rx").linewidth(1).linestyle("None"); <add> plt.legend(); <add> <add> try { <add> plt.show(); <add> } catch (Exception ex) { <add> log.warning("cannot show the plot with pyplot - did you install python and matplotlib on path? " + ex.toString()); <add> showWarningDialogInSwingThread("<html>Cannot show the plot with pyplot - did you install python and matplotlib on path? <p>" + ex.toString(), "Cannot plot"); <ide> } <ide> } <ide> } <ide> chain.add(new SpatioTemporalCorrelationFilter(chip)); <ide> chain.add(tracker); <ide> setEnclosedFilterChain(chain); <del> String ser = "Serial port", rod = "Rod control", ler = "Learning",enb="Enable/Disable"; <add> String ser = "Serial port", rod = "Rod control", ler = "Learning", enb = "Enable/Disable"; <ide> setPropertyTooltip(ser, "serialPortName", "Name of serial port to send robot commands to"); <ide> setPropertyTooltip(ser, "serialBaudRate", "Baud rate (default 115200), upper limit 12000000"); <ide> setPropertyTooltip(rod, "showFishingRodControlPanel", "show control panel for fishing rod"); <ide> setPropertyTooltip(rod, "markFishingPoolCenter", "Mark the location of center of fishing pool with next left mouse click"); <ide> setPropertyTooltip(rod, "zMin", "min rod tilt angle in deg"); <ide> setPropertyTooltip(rod, "zMax", "max rod tilt angle in deg"); <del> setPropertyTooltip(enb,"runPond", "Turn on the pond motor via 1.5V regulator"); <add> setPropertyTooltip(enb, "runPond", "Turn on the pond motor via 1.5V regulator"); <ide> setPropertyTooltip(rod, "fishingAttemptHoldoffMs", "holdoff time in ms between automatic fishing attempts"); <ide> setPropertyTooltip(rod, "rodReturnDurationMs", "duration in ms of minimum-jerk movement back to starting point of fishing rod sequence"); <del> setPropertyTooltip(enb,"disableServos", "turn off servos"); <del> setPropertyTooltip(enb,"disableFishing", "disable automatic fishing"); <del> setPropertyTooltip(enb,"enableFishing", "disable automatic fishing"); <add> setPropertyTooltip(enb, "disableServos", "disable servos"); <add> setPropertyTooltip(enb, "enableFishing", "enable automatic fishing"); <ide> setPropertyTooltip(ler, "fishingHoleSwitchProbability", "chance of switching spots after each attempt"); <ide> setPropertyTooltip(ler, "caughtFishDetectorThreshold", "threshold ADC count from FSR to detect that we caught a fish"); <ide> setPropertyTooltip(ler, "rodDipDelaySamplingSigmaMs", "spread of uniformly-sampled delay in ms to sample new rod dip starting delay"); <ide> setPropertyTooltip(ler, "rodThetaSamplingSigmaDeg", "sigma in deg to sample new rod dip pan offsets"); <ide> setPropertyTooltip(ler, "treatSigmasAsOffsets", "Use the sigma values for theta and delay as fixed offsets to manually tune the fishing"); <add> setPropertyTooltip(ler, "plotFishingResults", "(needs python and matplotlib installed) Plot the fishing results as scatter plot."); <ide> try { <ide> for (int i = 0; i < 2; i++) { <ide> rodSequences[i].load(i); <ide> } <ide> if (rodDipper == null || !rodDipper.isAlive()) { <ide> // log.info(String.format("Detected fish in ROI at location %s becoming contained by ROI rectangle %s", c.getLocation(), roiRects.get(roi))); <del> if (!disableFishing) { <add> if (!enableFishing) { <ide> dipRodWithHoldoffAndDelay(delay); <ide> break; <ide> } <ide> enablePond(false); <ide> } <ide> <del> <del> public void doToggleOnEnableFishing(){ <del> setDisableFishing(false); <del> } <del> <del> public void doToggleOffEnableFishing(){ <del> setDisableFishing(true); <del> } <del> <add> public void doToggleOnEnableFishing() { <add> setEnableFishing(false); <add> } <add> <add> public void doToggleOffEnableFishing() { <add> setEnableFishing(true); <add> } <add> <add> public void doPlotFishingResults() { <add> fishingResults.plot(); <add> } <add> <ide> private void enablePond(boolean enable) { <ide> if (!checkSerialPort()) { <ide> log.warning("serial port not open"); <ide> log.info(String.format("Theta offset learned+sample=%.1f + %.1f deg; Delay learned+sample=%d + %.0f", <ide> rodThetaOffset, thetaSample, <ide> rodDipDelayMs, delaySamp)); <del> <ide> <ide> if (randomDelayMs > 0) { <ide> try { <ide> rodDipDelayMs = randomDelayMs; <ide> putFloat("rodThetaOffset", randomThetaOffsetDeg); <ide> putInt("rodDipDelayMs", randomDelayMs); <del> setDisableFishing(true); <add> setEnableFishing(true); <ide> beepSucessPlayer.play(); <ide> return; <ide> } else { <ide> final RodPosition endingPosition = rodSequence.get(0); <ide> final Point2D start = new Point2D(startingPosition.thetaDeg, startingPosition.zDeg); <ide> final Point2D end = new Point2D(endingPosition.thetaDeg, endingPosition.zDeg); <del> final double sampleRateHz = 100; <add> final double sampleRateHz = 25; <ide> final double dtS = 1 / sampleRateHz; <ide> final int dtMs = (int) Math.floor(dtS * 1000); <ide> final int dtRemNs = (int) (1e9 * (dtS - dtMs / 1000.)); <ide> } <ide> <ide> /** <del> * @return the disableFishing <del> */ <del> public boolean isDisableFishing() { <del> return disableFishing; <del> } <del> <del> /** <del> * @param disableFishing the disableFishing to set <del> */ <del> public void setDisableFishing(boolean disableFishing) { <del> boolean old = this.disableFishing; <del> this.disableFishing = disableFishing; <del> putBoolean("disableFishing", disableFishing); <del> getSupport().firePropertyChange("disableFishing", old, this.disableFishing); <del> if (!disableFishing) { <add> * @return the enableFishing <add> */ <add> public boolean isEnableFishing() { <add> return enableFishing; <add> } <add> <add> /** <add> * @param enableFishing the enableFishing to set <add> */ <add> public void setEnableFishing(boolean enableFishing) { <add> boolean old = this.enableFishing; <add> this.enableFishing = enableFishing; <add> putBoolean("enableFishing", enableFishing); <add> getSupport().firePropertyChange("enableFishing", old, this.enableFishing); <add> if (!enableFishing) { <ide> RodSequence seq = rodSequences[currentRodsequenceIdx]; <ide> rodDipper = new RodDipper(seq, 0, true); <ide> log.info("moving rod to current sequence starting position");
Java
mit
d8edec82e819b7d3b6d65eead899eba6dee1a61e
0
archimatetool/archi,archimatetool/archi,archimatetool/archi
/******************************************************************************* * Copyright (c) 2011-12 Bolton University, UK. * All rights reserved. This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt *******************************************************************************/ package uk.ac.bolton.archimate.editor.diagram.actions; import java.util.ArrayList; import java.util.List; import org.eclipse.gef.DefaultEditDomain; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.gef.ui.actions.WorkbenchPartAction; import org.eclipse.gef.ui.palette.PaletteViewer; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.bindings.keys.KeySequence; import org.eclipse.jface.bindings.keys.KeyStroke; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.keys.IBindingService; import uk.ac.bolton.archimate.editor.diagram.FloatingPalette; import uk.ac.bolton.archimate.editor.diagram.IDiagramModelEditor; import uk.ac.bolton.archimate.editor.ui.IArchimateImages; import uk.ac.bolton.archimate.editor.ui.components.PartListenerAdapter; /** * Full Screen Action * * Works on Windows and Linux but not Mac >= 10.7 * Mac's own full screen action conflicts starting from Eclipse 3.8 since Shell.setFullScreen(boolean) was changed * to use Mac's full screen. * * @author Phillip Beauvoir */ public class FullScreenAction extends WorkbenchPartAction { public static final String ID = "uk.ac.bolton.archimate.editor.action.fullScreen"; //$NON-NLS-1$ public static final String TEXT = Messages.FullScreenAction_0; private GraphicalViewer fGraphicalViewer; private Shell fNewShell; private Composite fOldParent; private PaletteViewer fOldPaletteViewer; private FloatingPalette fFloatingPalette; private class KeyBinding { public KeyBinding(int modKeys, int key, IAction action) { this.modKeys = modKeys; this.key = key; this.action = action; } int modKeys; int key; IAction action; } private List<KeyBinding> keyBindings = new ArrayList<KeyBinding>(); private KeyListener keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // Escape pressed, close this Shell if(e.keyCode == SWT.ESC) { e.doit = false; // Stop OS X Lion receiving this for its Full Screen close(); } // Other key, find the action IAction action = getKeyAction(e); if(action != null && action.isEnabled()) { action.run(); } } private IAction getKeyAction(KeyEvent e) { int mod = e.stateMask; int key = Character.toLowerCase(e.keyCode); for(KeyBinding kb : keyBindings) { if(mod == kb.modKeys && key == kb.key) { return kb.action; } } return null; } }; private IMenuListener contextMenuListener = new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { // Remove Actions that lead to loss of Shell focus manager.remove(SelectElementInTreeAction.ID); manager.remove(ActionFactory.PROPERTIES.getId()); if(!fFloatingPalette.isOpen()) { manager.add(new Action(Messages.FullScreenAction_1) { @Override public void run() { fFloatingPalette.open(); }; }); } manager.add(new Action(Messages.FullScreenAction_2) { @Override public void run() { close(); }; @Override public int getAccelerator() { return SWT.ESC; }; }); } }; /* * If the workbench part that was closed (typically from an "Undo New View" Action) is this part then close full screen. * Important to use partDeactivated event rather than partClosed event so we can regain proper focus so that the Undo stack is reset. */ private IPartListener partListener = new PartListenerAdapter() { @Override public void partDeactivated(IWorkbenchPart part) { if(part == getWorkbenchPart()) { close(); } } }; public FullScreenAction(IWorkbenchPart part) { super(part); setText(TEXT); setId(ID); setActionDefinitionId(getId()); // register key binding } @Override public void run() { fGraphicalViewer = (GraphicalViewer)getWorkbenchPart().getAdapter(GraphicalViewer.class); fOldParent = fGraphicalViewer.getControl().getParent(); fOldPaletteViewer = fGraphicalViewer.getEditDomain().getPaletteViewer(); // Set Property so clients know this is in full screen mode fGraphicalViewer.setProperty("full_screen", true); //$NON-NLS-1$ addKeyBindings(); // Add key and menu listeners fGraphicalViewer.getContextMenu().addMenuListener(contextMenuListener); fGraphicalViewer.getControl().addKeyListener(keyListener); // Create new Shell // SWT.SHELL_TRIM is best option for all platforms. GTK needs it for a full-size shell int style = SWT.APPLICATION_MODAL | SWT.SHELL_TRIM ; fNewShell = new Shell(Display.getCurrent(), style); fNewShell.setFullScreen(true); fNewShell.setMaximized(true); fNewShell.setLayout(new FillLayout()); fNewShell.setImage(IArchimateImages.ImageFactory.getImage(IArchimateImages.ICON_APP_128)); // On Ubuntu the min/max/close buttons are shown, so trap close button fNewShell.addShellListener(new ShellAdapter() { @Override public void shellClosed(ShellEvent e) { close(); } }); // Set the Viewer's control's parent to be the new Shell fGraphicalViewer.getControl().setParent(fNewShell); fNewShell.layout(); fNewShell.open(); fFloatingPalette = new FloatingPalette((IDiagramModelEditor)((DefaultEditDomain)fGraphicalViewer.getEditDomain()).getEditorPart(), fNewShell); if(fFloatingPalette.getPaletteState().isOpen) { fFloatingPalette.open(); } // Hide the old Shell fOldParent.getShell().setVisible(false); // Listen to Parts being closed getWorkbenchPart().getSite().getWorkbenchWindow().getPartService().addPartListener(partListener); // Set Focus on new Shell fNewShell.setFocus(); } private void close() { fFloatingPalette.close(); fGraphicalViewer.getContextMenu().removeMenuListener(contextMenuListener); fGraphicalViewer.getControl().removeKeyListener(keyListener); // Remove Listen to Parts being closed getWorkbenchPart().getSite().getWorkbenchWindow().getPartService().removePartListener(partListener); fGraphicalViewer.getEditDomain().setPaletteViewer(fOldPaletteViewer); fGraphicalViewer.getControl().setParent(fOldParent); fOldParent.layout(); fNewShell.dispose(); // Reset Property fGraphicalViewer.setProperty("full_screen", null); //$NON-NLS-1$ // Visible & Focus fOldParent.getShell().setVisible(true); getWorkbenchPart().getSite().getWorkbenchWindow().getShell().setFocus(); } /** * Add common Key bindings to Actions */ private void addKeyBindings() { if(keyBindings.isEmpty()) { ActionRegistry registry = (ActionRegistry)getWorkbenchPart().getAdapter(ActionRegistry.class); IBindingService service = (IBindingService)getWorkbenchPart().getSite().getService(IBindingService.class); addKeyBinding(registry, service, ActionFactory.SELECT_ALL); addKeyBinding(registry, service, ActionFactory.UNDO); addKeyBinding(registry, service, ActionFactory.REDO); addKeyBinding(registry, service, ActionFactory.DELETE); addKeyBinding(registry, service, ActionFactory.CUT); addKeyBinding(registry, service, ActionFactory.COPY); addKeyBinding(registry, service, ActionFactory.PASTE); addKeyBinding(registry, service, ActionFactory.RENAME); } } /** * Add a Key binding mapped to an Action */ private void addKeyBinding(ActionRegistry registry, IBindingService service, ActionFactory actionFactory) { KeySequence seq = (KeySequence)service.getBestActiveBindingFor(actionFactory.getCommandId()); if(seq != null && seq.getKeyStrokes().length > 0) { KeyStroke ks = seq.getKeyStrokes()[0]; keyBindings.add(new KeyBinding(ks.getModifierKeys(), Character.toLowerCase(ks.getNaturalKey()), registry.getAction(actionFactory.getId()))); } } @Override protected boolean calculateEnabled() { return true; } @Override public void dispose() { fGraphicalViewer = null; keyBindings = null; fNewShell = null; fOldParent = null; } }
uk.ac.bolton.archimate.editor/src/uk/ac/bolton/archimate/editor/diagram/actions/FullScreenAction.java
/******************************************************************************* * Copyright (c) 2011-12 Bolton University, UK. * All rights reserved. This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt *******************************************************************************/ package uk.ac.bolton.archimate.editor.diagram.actions; import java.util.ArrayList; import java.util.List; import org.eclipse.gef.DefaultEditDomain; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.gef.ui.actions.WorkbenchPartAction; import org.eclipse.gef.ui.palette.PaletteViewer; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.bindings.keys.KeySequence; import org.eclipse.jface.bindings.keys.KeyStroke; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.keys.IBindingService; import uk.ac.bolton.archimate.editor.diagram.FloatingPalette; import uk.ac.bolton.archimate.editor.diagram.IDiagramModelEditor; import uk.ac.bolton.archimate.editor.ui.IArchimateImages; import uk.ac.bolton.archimate.editor.ui.components.PartListenerAdapter; import uk.ac.bolton.archimate.editor.utils.PlatformUtils; /** * Full Screen Action * * Works on Windows and Linux but not Mac >= 10.7 * Mac's own full screen action conflicts starting from Eclipse 3.8 since Shell.setFullScreen(boolean) was changed * to use Mac's full screen. * * @author Phillip Beauvoir */ public class FullScreenAction extends WorkbenchPartAction { public static final String ID = "uk.ac.bolton.archimate.editor.action.fullScreen"; //$NON-NLS-1$ public static final String TEXT = Messages.FullScreenAction_0; private GraphicalViewer fGraphicalViewer; private Shell fNewShell; private Composite fOldParent; private PaletteViewer fOldPaletteViewer; private FloatingPalette fFloatingPalette; private class KeyBinding { public KeyBinding(int modKeys, int key, IAction action) { this.modKeys = modKeys; this.key = key; this.action = action; } int modKeys; int key; IAction action; } private List<KeyBinding> keyBindings = new ArrayList<KeyBinding>(); private KeyListener keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // Escape pressed, close this Shell if(e.keyCode == SWT.ESC) { e.doit = false; // Stop OS X Lion receiving this for its Full Screen close(); } // Other key, find the action IAction action = getKeyAction(e); if(action != null && action.isEnabled()) { action.run(); } } private IAction getKeyAction(KeyEvent e) { int mod = e.stateMask; int key = Character.toLowerCase(e.keyCode); for(KeyBinding kb : keyBindings) { if(mod == kb.modKeys && key == kb.key) { return kb.action; } } return null; } }; private IMenuListener contextMenuListener = new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { // Remove Actions that lead to loss of Shell focus manager.remove(SelectElementInTreeAction.ID); manager.remove(ActionFactory.PROPERTIES.getId()); if(!fFloatingPalette.isOpen()) { manager.add(new Action(Messages.FullScreenAction_1) { @Override public void run() { fFloatingPalette.open(); }; }); } manager.add(new Action(Messages.FullScreenAction_2) { @Override public void run() { close(); }; @Override public int getAccelerator() { return SWT.ESC; }; }); } }; /* * If the workbench part that was closed (typically from an "Undo New View" Action) is this part then close full screen. * Important to use partDeactivated event rather than partClosed event so we can regain proper focus so that the Undo stack is reset. */ private IPartListener partListener = new PartListenerAdapter() { @Override public void partDeactivated(IWorkbenchPart part) { if(part == getWorkbenchPart()) { close(); } } }; public FullScreenAction(IWorkbenchPart part) { super(part); setText(TEXT); setId(ID); setActionDefinitionId(getId()); // register key binding } @Override public void run() { fGraphicalViewer = (GraphicalViewer)getWorkbenchPart().getAdapter(GraphicalViewer.class); fOldParent = fGraphicalViewer.getControl().getParent(); fOldPaletteViewer = fGraphicalViewer.getEditDomain().getPaletteViewer(); // Set Property so clients know this is in full screen mode fGraphicalViewer.setProperty("full_screen", true); //$NON-NLS-1$ addKeyBindings(); // Add key and menu listeners fGraphicalViewer.getContextMenu().addMenuListener(contextMenuListener); fGraphicalViewer.getControl().addKeyListener(keyListener); // Create new Shell // SWT.SHELL_TRIM is best option for all platforms. GTK needs it for full-size shell and OS X Lion has a bug with SWT.RESIZE int style = SWT.APPLICATION_MODAL | SWT.SHELL_TRIM ; if(PlatformUtils.isMac()) { style |= SWT.ON_TOP; // SWT.ON_TOP is needed on Mac to ensure Focus click-through } fNewShell = new Shell(Display.getCurrent(), style); fNewShell.setFullScreen(true); fNewShell.setMaximized(true); fNewShell.setLayout(new FillLayout()); fNewShell.setImage(IArchimateImages.ImageFactory.getImage(IArchimateImages.ICON_APP_128)); // Set the Viewer's control's parent to be the new Shell fGraphicalViewer.getControl().setParent(fNewShell); fNewShell.layout(); fNewShell.open(); fFloatingPalette = new FloatingPalette((IDiagramModelEditor)((DefaultEditDomain)fGraphicalViewer.getEditDomain()).getEditorPart(), fNewShell); if(fFloatingPalette.getPaletteState().isOpen) { fFloatingPalette.open(); } // Hide the old Shell fOldParent.getShell().setVisible(false); // Listen to Parts being closed getWorkbenchPart().getSite().getWorkbenchWindow().getPartService().addPartListener(partListener); // Set Focus on new Shell fNewShell.setFocus(); } private void close() { fFloatingPalette.close(); fGraphicalViewer.getContextMenu().removeMenuListener(contextMenuListener); fGraphicalViewer.getControl().removeKeyListener(keyListener); // Remove Listen to Parts being closed getWorkbenchPart().getSite().getWorkbenchWindow().getPartService().removePartListener(partListener); fGraphicalViewer.getEditDomain().setPaletteViewer(fOldPaletteViewer); fGraphicalViewer.getControl().setParent(fOldParent); fOldParent.layout(); fNewShell.dispose(); // Reset Property fGraphicalViewer.setProperty("full_screen", null); //$NON-NLS-1$ // Visible & Focus fOldParent.getShell().setVisible(true); getWorkbenchPart().getSite().getWorkbenchWindow().getShell().setFocus(); } /** * Add common Key bindings to Actions */ private void addKeyBindings() { if(keyBindings.isEmpty()) { ActionRegistry registry = (ActionRegistry)getWorkbenchPart().getAdapter(ActionRegistry.class); IBindingService service = (IBindingService)getWorkbenchPart().getSite().getService(IBindingService.class); addKeyBinding(registry, service, ActionFactory.SELECT_ALL); addKeyBinding(registry, service, ActionFactory.UNDO); addKeyBinding(registry, service, ActionFactory.REDO); addKeyBinding(registry, service, ActionFactory.DELETE); addKeyBinding(registry, service, ActionFactory.CUT); addKeyBinding(registry, service, ActionFactory.COPY); addKeyBinding(registry, service, ActionFactory.PASTE); addKeyBinding(registry, service, ActionFactory.RENAME); } } /** * Add a Key binding mapped to an Action */ private void addKeyBinding(ActionRegistry registry, IBindingService service, ActionFactory actionFactory) { KeySequence seq = (KeySequence)service.getBestActiveBindingFor(actionFactory.getCommandId()); if(seq != null && seq.getKeyStrokes().length > 0) { KeyStroke ks = seq.getKeyStrokes()[0]; keyBindings.add(new KeyBinding(ks.getModifierKeys(), Character.toLowerCase(ks.getNaturalKey()), registry.getAction(actionFactory.getId()))); } } @Override protected boolean calculateEnabled() { return true; } @Override public void dispose() { fGraphicalViewer = null; keyBindings = null; fNewShell = null; fOldParent = null; } }
Full Screen Action responds to Shell close event * This is needed on Ubuntu where it's possible to close the full screen window with the close button
uk.ac.bolton.archimate.editor/src/uk/ac/bolton/archimate/editor/diagram/actions/FullScreenAction.java
Full Screen Action responds to Shell close event
<ide><path>k.ac.bolton.archimate.editor/src/uk/ac/bolton/archimate/editor/diagram/actions/FullScreenAction.java <ide> import org.eclipse.swt.events.KeyAdapter; <ide> import org.eclipse.swt.events.KeyEvent; <ide> import org.eclipse.swt.events.KeyListener; <add>import org.eclipse.swt.events.ShellAdapter; <add>import org.eclipse.swt.events.ShellEvent; <ide> import org.eclipse.swt.layout.FillLayout; <ide> import org.eclipse.swt.widgets.Composite; <ide> import org.eclipse.swt.widgets.Display; <ide> import uk.ac.bolton.archimate.editor.diagram.IDiagramModelEditor; <ide> import uk.ac.bolton.archimate.editor.ui.IArchimateImages; <ide> import uk.ac.bolton.archimate.editor.ui.components.PartListenerAdapter; <del>import uk.ac.bolton.archimate.editor.utils.PlatformUtils; <ide> <ide> <ide> /** <ide> fGraphicalViewer.getControl().addKeyListener(keyListener); <ide> <ide> // Create new Shell <del> // SWT.SHELL_TRIM is best option for all platforms. GTK needs it for full-size shell and OS X Lion has a bug with SWT.RESIZE <add> // SWT.SHELL_TRIM is best option for all platforms. GTK needs it for a full-size shell <ide> int style = SWT.APPLICATION_MODAL | SWT.SHELL_TRIM ; <del> if(PlatformUtils.isMac()) { <del> style |= SWT.ON_TOP; // SWT.ON_TOP is needed on Mac to ensure Focus click-through <del> } <ide> fNewShell = new Shell(Display.getCurrent(), style); <ide> fNewShell.setFullScreen(true); <ide> fNewShell.setMaximized(true); <ide> fNewShell.setLayout(new FillLayout()); <ide> fNewShell.setImage(IArchimateImages.ImageFactory.getImage(IArchimateImages.ICON_APP_128)); <add> <add> // On Ubuntu the min/max/close buttons are shown, so trap close button <add> fNewShell.addShellListener(new ShellAdapter() { <add> @Override <add> public void shellClosed(ShellEvent e) { <add> close(); <add> } <add> }); <ide> <ide> // Set the Viewer's control's parent to be the new Shell <ide> fGraphicalViewer.getControl().setParent(fNewShell);
JavaScript
mit
9b7936ee3a2f15d4e5fe891312e118249c6c19f9
0
wmantly/lxc_manager_node,wmantly/lxc_manager_node,wmantly/lxc_manager_node
'use strict'; var express = require('express'); var router = express.Router(); var util = require('util'); var request = require('request'); var lxc = require('../lxc'); var doapi = require('../doapi')(); var workerSnapID = 'V1' // console.log = function(){}; var label2runner = {}; var workers = []; var isCheckingWorkers = false; var dopletNewID = 0; var workers = (function(){ var workers = []; workers.checkDroplet = function(id, time){ time = time || 5000; doapi.dropletInfo(id, function(data){ var worker = JSON.parse(data)['droplet']; if(worker.status == 'active'){ console.log('Droplet is now active, starting runners in 20 seconds') setTimeout(function(worker){ console.log('Ready to start runners!') workers.startRunners(workers[workers.push(workers.makeWorkerObj(worker))-1]) isCheckingWorkers = false; }, 20000, worker); return true; }else{ console.log('Worker not ready, check again in ', time, 'MS'); setTimeout(function(){ workers.checkDroplet(id); }, time); } }); }; workers.create = function(){ doapi.dropletCreate({ name: 'clw'+workerSnapID+'-'+(Math.random()*100).toString().replace('.',''), image: '17575764' }, function(data){ data = JSON.parse(data); setTimeout(function(dopletNewID){ workers.checkDroplet(dopletNewID); }, 60000, data.droplet.id); doapi.dropletSetTag('clworker', data.droplet.id, function(){}); }); }; workers.destroy = function(worker){ worker = worker || workers.pop(); doapi.dropletDestroy(worker.id, function(){}); workers.checkBalance(); }; workers.makeWorkerObj = function(worker){ worker.networks.v4.forEach(function(value){ worker[value.type+'IP'] = value.ip_address; }); worker.availrunners = []; worker.ip = worker.privateIP; worker.usedrunner = 0; worker.index = workers.length, worker.getRunner = function(){ if(this.availrunners.length === 0) return false; console.log('geting runner from ', worker.name, ' aval length ', this.availrunners.length); var runner = this.availrunners.pop(); this.usedrunner++; label2runner[runner.label] = runner; return runner; } return worker; }; workers.destroyOld = function(){ doapi.dropletsByTag('clworker', function(data){ data = JSON.parse(data); data['droplets'].forEach(function(worker){ console.log('found old droplet, killing it'); doapi.dropletDestroy(worker.id, function(){}); }); workers.checkBalance(); }); }; workers.startRunners = function(worker, stopPercent){ console.log('starting runners on', worker.name) stopPercent = stopPercent || 80; ramPercentUsed(worker.ip, function(usedMemPercent){ if(usedMemPercent < stopPercent ){ var name = 'crunner-'+(Math.random()*100).toString().replace('.',''); return lxc.startEphemeral(name, 'crunner0', worker.ip, function(data){ if( !data.ip ) return setTimeout(workers.startRunners(worker),0); console.log('started runner') worker.availrunners.push({ ip: data.ip, name: name, worker: worker, label: worker.name + ':' + name }); return setTimeout(workers.startRunners(worker, stopPercent), 0); }); }else{ setTimeout(workers.checkBalance, 10000); console.log('using', usedMemPercent, 'percent memory, stopping runner creation!', worker.availrunners.length, 'created on ', worker.name); } }); }; workers.checkBalance = function(){ if(isCheckingWorkers) return false; isCheckingWorkers = true; var changed = false; console.log('checking balance'); if(workers.length < 2){ console.log('less then 2 workers, starting a droplet'); for(var i=2; i--;) workers.create(); return ; } if(workers[workers.length-1].usedrunner !== 0){ console.log('last droplet has no free runners, starting droplet'); return workers.create(); } if(workers.length > 2 && workers[workers.length-1].usedrunner === 0 && workers[workers.length-2].usedrunner === 0){ console.log('Last 2 runners not used, killing last runner'); workers.destroy(); } for(let worker of workers){ if(worker.availrunners.length === 0 && worker.usedrunner === 0){ workers.destroy(worker); changed = true; } } console.log('stopping workers balancing check'); isCheckingWorkers = false; if(changed) setTimeout(function(){ workers.checkBalance(); }, 3000); }; return workers; })(); var ramPercentUsed = function(ip, callback){ return lxc.exec( "python3 -c \"a=`head /proc/meminfo|grep MemAvail|grep -Po '\\d+'`;t=`head /proc/meminfo|grep MemTotal|grep -Po '\\d+'`;print(round(((t-a)/t)*100, 2))\"", ip, callback ); }; var runnerFree = function(runner){ lxc.stop(runner.name, runner.worker.ip); runner.worker.usedrunner--; if(runner.hasOwnProperty('timeout')){ clearTimeout(runner.timeout); } delete label2runner[runner.label]; workers.startRunners(runner.worker); }; var lxcTimeout = function(runner, time){ time = time || 60000 // 900000; // 15 minutes if(runner.hasOwnProperty('timeout')){ clearTimeout(runner.timeout); } return runner.timeout = setTimeout(function(){ runnerFree(runner); }, time); }; var run = function(req, res, runner){ var httpOptions = { url: 'http://' + runner.worker.ip, headers: { Host: runner.name }, body: JSON.stringify({ code: req.body.code }) }; return request.post(httpOptions, function(error, response, body){ // console.log('runner response:', arguments) if(res.statusCode !== 200 || error) return run(req, res, getAvailrunner()); console.log('body', body); body = JSON.parse(body); body['ip'] = getAvailrunner(runner).label; lxcTimeout(runner); return res.json(body); }); }; var getAvailrunner = function(runner){ for(let worker of workers){ console.log('checking ', worker.name, ' with ', worker.availrunners.length, ' free workers'); if(worker.availrunners.length === 0) continue; if(runner && runner.worker.index <= worker.index) break; if(runner) runnerFree(runner); return worker.getRunner(); } if(runner) return runner; return false; }; workers.destroyOld(); // router.get('/start/:name', function(req, res, next){ // return lxc.start(req.params.name, function(data){ // if(!data){ // return res.json({ // status: 500, // name: req.params.name, // message: data // }); // }else{ // res.json({}); // } // }); // }); // router.get('/live/:template/:name', function(req, res, next){ // return lxc.startEphemeral(req.params.name, req.params.template, function (data) { // console.log('live', arguments); // return res.json(data); // }); // }); // router.get('/clone/:template/:name', function(req, res, next){ // return lxc.clone(req.params.name, req.params.template, function(data){ // console.log('clone', arguments); // if( data.match(/Created runner/) ){ // return res.json({status: 200}); // }else{ // return res.json({status: 500, message: data}); // } // }); // }); // router.get('/destroy/:name', function(req, res, next){ // return lxc.destroy(req.params.name, function(data){ // console.log('destroy', arguments); // if(data){ // return res.json({status: 500, message: data}); // }else{ // return res.json({status: 200}); // } // }); // }); // router.get('/info/:name', function(req, res, next){ // return lxc.info(req.params.name, function(data){ // return res.json(data); // }); // }); // router.get('/list', function(req, res, next) { // return lxc.list(workers.clworker0.ip, function(data){ // return res.json(data); // }); // }); router.get('/stop/:name', function(req, res, next){ return lxc.stop(req.params.name, function(data){ console.log('stop', arguments); if(data){ return res.json({status: 500, name: req.params.name, message: data}); }else{ return res.json({status: 200}); } }); }); router.get('/liststuff', function(req, res, next){ var obj = util.inspect(workers, {depth: 4}); res.send("<pre>"+obj+"</pre>"); }); router.post('/run/:ip?', function doRun(req, res, next){ console.log('hit runner route') var runner = label2runner[req.params.ip] || getAvailrunner(); console.log('') return run(req, res, runner); }); module.exports = router;
routes/api.js
'use strict'; var express = require('express'); var router = express.Router(); var util = require('util'); var request = require('request'); var lxc = require('../lxc'); var doapi = require('../doapi')(); var workerSnapID = 'V1' // console.log = function(){}; var label2runner = {}; var workers = []; var isCheckingWorkers = false; var dopletNewID = 0; var workers = (function(){ var workers = []; workers.checkDroplet = function(id, time){ time = time || 5000; doapi.dropletInfo(id, function(data){ var worker = JSON.parse(data)['droplet']; if(worker.status == 'active'){ console.log('Droplet is now active, starting runners in 20 seconds') setTimeout(function(worker){ console.log('Ready to start runners!') workers.startRunners(workers[workers.push(workers.makeWorkerObj(worker))-1]) isCheckingWorkers = false; }, 20000, worker); return true; }else{ console.log('Worker not ready, check again in ', time, 'MS'); setTimeout(function(){ workers.checkDroplet(id); }, time); } }); }; workers.create = function(){ doapi.dropletCreate({ name: 'clw'+workerSnapID+'-'+(Math.random()*100).toString().replace('.',''), image: '17575764' }, function(data){ data = JSON.parse(data); setTimeout(function(dopletNewID){ workers.checkDroplet(dopletNewID); }, 60000, data.droplet.id); doapi.dropletSetTag('clworker', data.droplet.id, function(){}); }); }; workers.destroy = function(worker){ worker = worker || workers.pop(); doapi.dropletDestroy(worker.id, function(){}); workers.checkBalance(); }; workers.makeWorkerObj = function(worker){ worker.networks.v4.forEach(function(value){ worker[value.type+'IP'] = value.ip_address; }); worker.availrunners = []; worker.ip = worker.privateIP; worker.usedrunner = 0; worker.index = workers.length, worker.getRunner = function(){ if(this.availrunners.length === 0) return false; console.log('geting runner from ', worker.name, ' aval length ', this.availrunners.length); var runner = this.availrunners.pop(); this.usedrunner++; label2runner[runner.label] = runner; return runner; } return worker; }; workers.destroyOld = function(){ doapi.dropletsByTag('clworker', function(data){ data = JSON.parse(data); data['droplets'].forEach(function(worker){ console.log('found old droplet, killing it'); doapi.dropletDestroy(worker.id, function(){}); }); workers.checkBalance(); }); }; workers.startRunners = function(worker, stopPercent){ console.log('starting runners on', worker.name) stopPercent = stopPercent || 80; ramPercentUsed(worker.ip, function(usedMemPercent){ if(usedMemPercent < stopPercent ){ var name = 'crunner-'+(Math.random()*100).toString().replace('.',''); return lxc.startEphemeral(name, 'crunner0', worker.ip, function(data){ if( !data.ip ) return setTimeout(workers.startRunners(worker),0); console.log('started runner') worker.availrunners.push({ ip: data.ip, name: name, worker: worker, label: worker.name + ':' + name }); return setTimeout(workers.startRunners(worker, stopPercent), 0); }); }else{ setTimeout(workers.checkBalance, 10000); console.log('using', usedMemPercent, 'percent memory, stopping runner creation!', worker.availrunners.length, 'created on ', worker.name); } }); }; workers.checkBalance = function(){ if(isCheckingWorkers) return false; isCheckingWorkers = true; var changed = false; console.log('checking balance'); if(workers.length < 2){ console.log('less then 2 workers, starting a droplet'); for(var i=2; i--;) workers.create(); return ; } if(workers[workers.length-1].usedrunner !== 0){ console.log('last droplet has no free runners, starting droplet'); return workers.create(); } if(workers.length > 2 && workers[workers.length-1].usedrunner === 0 && workers[workers.length-2].usedrunner === 0){ console.log('Last 2 runners not used, killing last runner'); workers.destroy(); } for(let worker of workers){ if(worker.availrunners.length === 0 && worker.usedrunner === 0){ workers.destroy(worker); changed = true; } } console.log('stopping workers balancing check'); isCheckingWorkers = false; if(changed) setTimeout(function(){ workers.checkBalance(); }, 3000); }; return workers; })(); var ramPercentUsed = function(ip, callback){ return lxc.exec( "python3 -c \"a=`head /proc/meminfo|grep MemAvail|grep -Po '\\d+'`;t=`head /proc/meminfo|grep MemTotal|grep -Po '\\d+'`;print(round(((t-a)/t)*100, 2))\"", ip, callback ); }; var runnerFree = function(runner){ lxc.stop(runner.name, runner.worker.ip); runner.worker.usedrunner--; if(runner.hasOwnProperty('timeout')){ clearTimeout(runner.timeout); } delete label2runner[runner.label]; workers.startRunners(runner.worker); }; var lxcTimeout = function(runner, time){ time = time || 60000 // 900000; // 15 minutes if(runner.hasOwnProperty('timeout')){ clearTimeout(runner.timeout); } return runner.timeout = setTimeout(function(){ runnerFree(runner); }, time); }; var run = function(req, res, runner){ var httpOptions = { url: 'http://' + runner.worker.ip, headers: { Host: runner.name }, body: JSON.stringify({ code: req.body.code }) }; return request.post(httpOptions, function(error, response, body){ // console.log('runner response:', arguments) if(error) return false; console.log('body', body); body = JSON.parse(body); body['ip'] = getAvailrunner(runner).label; lxcTimeout(runner); return res.json(body); }); }; var getAvailrunner = function(runner){ for(let worker of workers){ console.log('checking ', worker.name, ' with ', worker.availrunners.length, ' free workers'); if(worker.availrunners.length === 0) continue; if(runner && runner.worker.index <= worker.index) break; if(runner) runnerFree(runner); return worker.getRunner(); } if(runner) return runner; return false; }; workers.destroyOld(); // router.get('/start/:name', function(req, res, next){ // return lxc.start(req.params.name, function(data){ // if(!data){ // return res.json({ // status: 500, // name: req.params.name, // message: data // }); // }else{ // res.json({}); // } // }); // }); // router.get('/live/:template/:name', function(req, res, next){ // return lxc.startEphemeral(req.params.name, req.params.template, function (data) { // console.log('live', arguments); // return res.json(data); // }); // }); // router.get('/clone/:template/:name', function(req, res, next){ // return lxc.clone(req.params.name, req.params.template, function(data){ // console.log('clone', arguments); // if( data.match(/Created runner/) ){ // return res.json({status: 200}); // }else{ // return res.json({status: 500, message: data}); // } // }); // }); // router.get('/destroy/:name', function(req, res, next){ // return lxc.destroy(req.params.name, function(data){ // console.log('destroy', arguments); // if(data){ // return res.json({status: 500, message: data}); // }else{ // return res.json({status: 200}); // } // }); // }); // router.get('/info/:name', function(req, res, next){ // return lxc.info(req.params.name, function(data){ // return res.json(data); // }); // }); // router.get('/list', function(req, res, next) { // return lxc.list(workers.clworker0.ip, function(data){ // return res.json(data); // }); // }); router.get('/stop/:name', function(req, res, next){ return lxc.stop(req.params.name, function(data){ console.log('stop', arguments); if(data){ return res.json({status: 500, name: req.params.name, message: data}); }else{ return res.json({status: 200}); } }); }); router.get('/liststuff', function(req, res, next){ var obj = util.inspect(workers, {depth: 4}); res.send("<pre>"+obj+"</pre>"); }); router.post('/run/:ip?', function doRun(req, res, next){ console.log('hit runner route') var runner = label2runner[req.params.ip] || getAvailrunner(); console.log('') return run(req, res, runner); }); module.exports = router;
stuff
routes/api.js
stuff
<ide><path>outes/api.js <ide> <ide> return request.post(httpOptions, function(error, response, body){ <ide> // console.log('runner response:', arguments) <del> if(error) return false; <add> if(res.statusCode !== 200 || error) return run(req, res, getAvailrunner()); <ide> console.log('body', body); <ide> body = JSON.parse(body); <ide>
Java
mpl-2.0
c9f277ce6567f01bae6830010a5194ba198b5bfa
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.plugins.eveplugin.events.model; import java.awt.Point; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import org.helioviewer.base.logging.Log; import org.helioviewer.base.math.Interval; import org.helioviewer.jhv.data.datatype.event.JHVEvent; import org.helioviewer.plugins.eveplugin.EVEState; import org.helioviewer.plugins.eveplugin.controller.DrawController; import org.helioviewer.plugins.eveplugin.controller.ZoomControllerListener; import org.helioviewer.plugins.eveplugin.events.data.EventRequesterListener; import org.helioviewer.plugins.eveplugin.events.gui.EventPanel; import org.helioviewer.plugins.eveplugin.events.gui.EventsSelectorElement; import org.helioviewer.plugins.eveplugin.settings.EVEAPI.API_RESOLUTION_AVERAGES; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.plugins.eveplugin.view.plot.PlotsContainerPanel; /** * * * @author Bram Bourgoignie ([email protected]) * */ public class EventModel implements ZoomControllerListener, EventRequesterListener { /** Singleton instance of the Event model */ private static EventModel instance; /** the current selected interval */ private Interval<Date> selectedInterval; /** the current available interval */ private Interval<Date> availableInterval; /** event plot configurations */ private EventTypePlotConfiguration eventPlotConfiguration; /** the interval lock */ private final Object intervalLock; /** events visible */ private boolean eventsVisible; /** current events */ private Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> events; /** plotIdentifier */ private String plot; /** The event panel */ private final EventPanel eventPanel; /** The swing worker creating the event type plot configurations */ private SwingWorker<EventTypePlotConfiguration, Void> currentSwingWorker; private final EventsSelectorElement eventSelectorElement; private final List<EventModelListener> listeners; private boolean eventsActivated; /** * Private default constructor. */ private EventModel() { intervalLock = new Object(); eventPlotConfiguration = new EventTypePlotConfiguration(); events = new HashMap<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>>(); eventsVisible = false; plot = PlotsContainerPanel.PLOT_IDENTIFIER_MASTER; eventPanel = new EventPanel(); currentSwingWorker = null; eventSelectorElement = new EventsSelectorElement(this); listeners = new ArrayList<EventModelListener>(); eventsActivated = false; } /** * Gets the singleton instance of the EventModel. * * @return the singleton instance of the event model */ public static EventModel getSingletonInstance() { if (instance == null) { instance = new EventModel(); } return instance; } /** * Adds an event model listener to the event model. * * @param listener * the listener to add */ public void addEventModelListener(EventModelListener listener) { listeners.add(listener); } @Override public void availableIntervalChanged(Interval<Date> newInterval) { synchronized (intervalLock) { availableInterval = newInterval; } } @Override public void selectedIntervalChanged(final Interval<Date> newInterval, boolean keepFullValueSpace) { selectedInterval = newInterval; if (!EVEState.getSingletonInstance().isMouseTimeIntervalDragging()) { createEventPlotConfiguration(); } } @Override public void selectedResolutionChanged(API_RESOLUTION_AVERAGES newResolution) { synchronized (intervalLock) { } } @Override public void newEventsReceived(Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> events) { synchronized (intervalLock) { this.events = events; if (selectedInterval != null && availableInterval != null) { createEventPlotConfiguration(); } } } public EventTypePlotConfiguration getEventTypePlotConfiguration() { synchronized (intervalLock) { if (eventPlotConfiguration != null) { return eventPlotConfiguration; } else { return new EventTypePlotConfiguration(); } } } public boolean isEventsVisible() { return eventsVisible; } public void setEventsVisible(boolean visible) { if (eventsVisible != visible) { eventsVisible = visible; DrawController.getSingletonInstance().updateDrawableElement(eventPanel, plot); LineDataSelectorModel.getSingletonInstance().lineDataElementUpdated(eventSelectorElement); } } public void deactivateEvents() { if (eventsActivated) { eventsVisible = false; eventsActivated = false; DrawController.getSingletonInstance().removeDrawableElement(eventPanel, plot); // LineDataSelectorModel.getSingletonInstance().removeLineData(eventSelectorElement); fireEventsDeactivated(); } } public void activateEvents() { if (!eventsActivated) { eventsVisible = true; eventsActivated = true; DrawController.getSingletonInstance().updateDrawableElement(eventPanel, plot); // LineDataSelectorModel.getSingletonInstance().addLineData(eventSelectorElement); } } public void setPlotIdentifier(String plotIdentifier) { if (!plot.equals(plotIdentifier)) { if (eventsActivated) { DrawController.getSingletonInstance().removeDrawableElement(eventPanel, plot); DrawController.getSingletonInstance().addDrawableElement(eventPanel, plotIdentifier); LineDataSelectorModel.getSingletonInstance().removeLineData(eventSelectorElement); plot = plotIdentifier; LineDataSelectorModel.getSingletonInstance().addLineData(eventSelectorElement); } else { plot = plotIdentifier; } } } public JHVEvent getEventAtPosition(Point point) { if (eventPlotConfiguration != null) { return eventPlotConfiguration.getEventOnLocation(point); } else { return null; } } private void createEventPlotConfiguration() { if (currentSwingWorker != null) { currentSwingWorker.cancel(true); } currentSwingWorker = new SwingWorker<EventTypePlotConfiguration, Void>() { @Override public EventTypePlotConfiguration doInBackground() { Thread.currentThread().setName("EventModel--EVE"); Set<String> uniqueIDs = new HashSet<String>(); int maxNrLines = 0; Map<String, Integer> linesPerEventType = new HashMap<String, Integer>(); Map<String, List<EventPlotConfiguration>> eventPlotConfigPerEventType = new HashMap<String, List<EventPlotConfiguration>>(); Date tempLastDateWithData = null; if (events.size() > 0) { for (String eventType : events.keySet()) { ArrayList<Date> endDates = new ArrayList<Date>(); List<EventPlotConfiguration> plotConfig = new ArrayList<EventPlotConfiguration>(); Date minimalEndDate = null; Date maximumEndDate = null; int minimalDateLine = 0; int maximumDateLine = 0; int nrLines = 0; int maxEventLines = 0; for (Date sDate : events.get(eventType).keySet()) { for (Date eDate : events.get(eventType).get(sDate).keySet()) { for (JHVEvent event : events.get(eventType).get(sDate).get(eDate)) { if (!uniqueIDs.contains(event.getUniqueID())) { uniqueIDs.add(event.getUniqueID()); int eventPosition = 0; if (minimalEndDate == null || minimalEndDate.compareTo(event.getStartDate()) >= 0) { // first event or event start before // minimal end // date so next line minimalEndDate = event.getEndDate(); endDates.add(event.getEndDate()); eventPosition = nrLines; nrLines++; } else { if (event.getStartDate().after(maximumEndDate)) { // After all other events so // start // new line // and // reset everything eventPosition = 0; nrLines = 1; endDates = new ArrayList<Date>(); endDates.add(event.getEndDate()); } else { // After minimal date so after // minimal end // date eventPosition = minimalDateLine; endDates.set(minimalDateLine, event.getEndDate()); } } minimalDateLine = defineMinimalDateLine(endDates); minimalEndDate = endDates.get(minimalDateLine); maximumDateLine = defineMaximumDateLine(endDates); maximumEndDate = endDates.get(maximumDateLine); double scaledX0 = defineScaledValue(event.getStartDate()); double scaledX1 = defineScaledValue(event.getEndDate()); if (nrLines > maxEventLines) { maxEventLines = nrLines; } if (tempLastDateWithData == null || tempLastDateWithData.before(event.getEndDate())) { tempLastDateWithData = event.getEndDate(); } event.addHighlightListener(DrawController.getSingletonInstance()); plotConfig.add(new EventPlotConfiguration(event, scaledX0, scaledX1, eventPosition)); } else { // Log.debug("Event with unique ID : " + // event.getUniqueID() + "not drawn"); } } } } linesPerEventType.put(eventType, maxEventLines); maxNrLines += maxEventLines; eventPlotConfigPerEventType.put(eventType, plotConfig); } return new EventTypePlotConfiguration(events.size(), maxNrLines, linesPerEventType, eventPlotConfigPerEventType, tempLastDateWithData); } else { return null; } } @Override public void done() { try { if (!isCancelled()) { eventPlotConfiguration = get(); // if // (eventPlotConfiguration.getEventPlotConfigurations().size() // > 0) { if (eventPlotConfiguration != null && EventModel.getSingletonInstance().isEventsVisible()) { DrawController.getSingletonInstance().updateDrawableElement(eventPanel, plot); } // } } else { // Log.info("Worker was cancelled"); } } catch (InterruptedException e) { Log.error("Could not create the event type plot configurations" + e.getMessage()); Log.error("The error" + e.getMessage()); } catch (ExecutionException e) { Log.error("Could not create the event type plot configurations" + e.getMessage()); Log.error("The error" + e.getMessage()); } } }; currentSwingWorker.execute(); } private int defineMaximumDateLine(ArrayList<Date> endDates) { Date maxDate = null; int maxLine = 0; for (Date d : endDates) { if (maxDate == null) { // first case maxDate = d; maxLine = 0; } else { // the rest if (d.after(maxDate)) { maxDate = d; maxLine = endDates.indexOf(d); } } } return maxLine; } private int defineMinimalDateLine(ArrayList<Date> endDates) { Date minDate = null; int minLine = 0; for (Date d : endDates) { if (minDate == null) { // first case minDate = d; minLine = 0; } else { // the rest if (d.before(minDate)) { minDate = d; minLine = endDates.indexOf(d); } } } return minLine; } private double defineScaledValue(Date date) { double selectedDuration = 1.0 * (selectedInterval.getEnd().getTime() - selectedInterval.getStart().getTime()); double position = 1.0 * (date.getTime() - selectedInterval.getStart().getTime()); return position / selectedDuration; } public String getPlotIdentifier() { return plot; } private void fireEventsDeactivated() { for (EventModelListener l : listeners) { l.eventsDeactivated(); } } }
src/plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/events/model/EventModel.java
package org.helioviewer.plugins.eveplugin.events.model; import java.awt.Point; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import org.helioviewer.base.logging.Log; import org.helioviewer.base.math.Interval; import org.helioviewer.jhv.data.datatype.event.JHVEvent; import org.helioviewer.plugins.eveplugin.EVEState; import org.helioviewer.plugins.eveplugin.controller.DrawController; import org.helioviewer.plugins.eveplugin.controller.ZoomControllerListener; import org.helioviewer.plugins.eveplugin.events.data.EventRequesterListener; import org.helioviewer.plugins.eveplugin.events.gui.EventPanel; import org.helioviewer.plugins.eveplugin.events.gui.EventsSelectorElement; import org.helioviewer.plugins.eveplugin.settings.EVEAPI.API_RESOLUTION_AVERAGES; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.plugins.eveplugin.view.plot.PlotsContainerPanel; /** * * * @author Bram Bourgoignie ([email protected]) * */ public class EventModel implements ZoomControllerListener, EventRequesterListener { /** Singleton instance of the Event model */ private static EventModel instance; /** the current selected interval */ private Interval<Date> selectedInterval; /** the current available interval */ private Interval<Date> availableInterval; /** event plot configurations */ private EventTypePlotConfiguration eventPlotConfiguration; /** the interval lock */ private final Object intervalLock; /** events visible */ private boolean eventsVisible; /** current events */ private Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> events; /** plotIdentifier */ private String plot; /** The event panel */ private final EventPanel eventPanel; /** The swing worker creating the event type plot configurations */ private SwingWorker<EventTypePlotConfiguration, Void> currentSwingWorker; private final EventsSelectorElement eventSelectorElement; private final List<EventModelListener> listeners; private boolean eventsActivated; /** * Private default constructor. */ private EventModel() { intervalLock = new Object(); eventPlotConfiguration = new EventTypePlotConfiguration(); events = new HashMap<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>>(); eventsVisible = false; plot = PlotsContainerPanel.PLOT_IDENTIFIER_MASTER; eventPanel = new EventPanel(); currentSwingWorker = null; eventSelectorElement = new EventsSelectorElement(this); listeners = new ArrayList<EventModelListener>(); eventsActivated = false; } /** * Gets the singleton instance of the EventModel. * * @return the singleton instance of the event model */ public static EventModel getSingletonInstance() { if (instance == null) { instance = new EventModel(); } return instance; } /** * Adds an event model listener to the event model. * * @param listener * the listener to add */ public void addEventModelListener(EventModelListener listener) { listeners.add(listener); } @Override public void availableIntervalChanged(Interval<Date> newInterval) { synchronized (intervalLock) { availableInterval = newInterval; } } @Override public void selectedIntervalChanged(final Interval<Date> newInterval, boolean keepFullValueSpace) { selectedInterval = newInterval; if (!EVEState.getSingletonInstance().isMouseTimeIntervalDragging()) { createEventPlotConfiguration(); } } @Override public void selectedResolutionChanged(API_RESOLUTION_AVERAGES newResolution) { synchronized (intervalLock) { } } @Override public void newEventsReceived(Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> events) { synchronized (intervalLock) { this.events = events; if (selectedInterval != null && availableInterval != null) { createEventPlotConfiguration(); } } } public EventTypePlotConfiguration getEventTypePlotConfiguration() { synchronized (intervalLock) { if (eventPlotConfiguration != null) { return eventPlotConfiguration; } else { return new EventTypePlotConfiguration(); } } } public boolean isEventsVisible() { return eventsVisible; } public void setEventsVisible(boolean visible) { if (eventsVisible != visible) { eventsVisible = visible; DrawController.getSingletonInstance().updateDrawableElement(eventPanel, plot); LineDataSelectorModel.getSingletonInstance().lineDataElementUpdated(eventSelectorElement); } } public void deactivateEvents() { if (eventsActivated) { eventsVisible = false; eventsActivated = false; DrawController.getSingletonInstance().removeDrawableElement(eventPanel, plot); // LineDataSelectorModel.getSingletonInstance().removeLineData(eventSelectorElement); fireEventsDeactivated(); } } public void activateEvents() { if (!eventsActivated) { eventsVisible = true; eventsActivated = true; DrawController.getSingletonInstance().updateDrawableElement(eventPanel, plot); // LineDataSelectorModel.getSingletonInstance().addLineData(eventSelectorElement); } } public void setPlotIdentifier(String plotIdentifier) { if (!plot.equals(plotIdentifier)) { if (eventsActivated) { DrawController.getSingletonInstance().removeDrawableElement(eventPanel, plot); DrawController.getSingletonInstance().addDrawableElement(eventPanel, plotIdentifier); LineDataSelectorModel.getSingletonInstance().removeLineData(eventSelectorElement); plot = plotIdentifier; LineDataSelectorModel.getSingletonInstance().addLineData(eventSelectorElement); } else { plot = plotIdentifier; } } } public JHVEvent getEventAtPosition(Point point) { if (eventPlotConfiguration != null) { return eventPlotConfiguration.getEventOnLocation(point); } else { return null; } } private void createEventPlotConfiguration() { if (currentSwingWorker != null) { currentSwingWorker.cancel(true); } currentSwingWorker = new SwingWorker<EventTypePlotConfiguration, Void>() { @Override public EventTypePlotConfiguration doInBackground() { Thread.currentThread().setName("EventModel--EVE"); Set<String> uniqueIDs = new HashSet<String>(); int maxNrLines = 0; Map<String, Integer> linesPerEventType = new HashMap<String, Integer>(); Map<String, List<EventPlotConfiguration>> eventPlotConfigPerEventType = new HashMap<String, List<EventPlotConfiguration>>(); Date tempLastDateWithData = null; if (events.size() > 0) { for (String eventType : events.keySet()) { ArrayList<Date> endDates = new ArrayList<Date>(); List<EventPlotConfiguration> plotConfig = new ArrayList<EventPlotConfiguration>(); Date minimalEndDate = null; Date maximumEndDate = null; int minimalDateLine = 0; int maximumDateLine = 0; int nrLines = 0; int maxEventLines = 0; for (Date sDate : events.get(eventType).keySet()) { for (Date eDate : events.get(eventType).get(sDate).keySet()) { for (JHVEvent event : events.get(eventType).get(sDate).get(eDate)) { if (!uniqueIDs.contains(event.getUniqueID())) { uniqueIDs.add(event.getUniqueID()); int eventPosition = 0; if (minimalEndDate == null || minimalEndDate.compareTo(event.getStartDate()) >= 0) { // first event or event start before // minimal end // date so next line minimalEndDate = event.getEndDate(); endDates.add(event.getEndDate()); eventPosition = nrLines; nrLines++; } else { if (event.getStartDate().after(maximumEndDate)) { // After all other events so // start // new line // and // reset everything eventPosition = 0; nrLines = 1; endDates = new ArrayList<Date>(); endDates.add(event.getEndDate()); } else { // After minimal date so after // minimal end // date eventPosition = minimalDateLine; endDates.set(minimalDateLine, event.getEndDate()); } } minimalDateLine = defineMinimalDateLine(endDates); minimalEndDate = endDates.get(minimalDateLine); maximumDateLine = defineMaximumDateLine(endDates); maximumEndDate = endDates.get(maximumDateLine); double scaledX0 = defineScaledValue(event.getStartDate()); double scaledX1 = defineScaledValue(event.getEndDate()); if (nrLines > maxEventLines) { maxEventLines = nrLines; } if (tempLastDateWithData == null || tempLastDateWithData.before(event.getEndDate())) { tempLastDateWithData = event.getEndDate(); } event.addHighlightListener(DrawController.getSingletonInstance()); plotConfig.add(new EventPlotConfiguration(event, scaledX0, scaledX1, eventPosition)); } else { // Log.debug("Event with unique ID : " + // event.getUniqueID() + "not drawn"); } } } } linesPerEventType.put(eventType, maxEventLines); maxNrLines += maxEventLines; eventPlotConfigPerEventType.put(eventType, plotConfig); } return new EventTypePlotConfiguration(events.size(), maxNrLines, linesPerEventType, eventPlotConfigPerEventType, tempLastDateWithData); } else { return null; } } @Override public void done() { try { if (!isCancelled()) { eventPlotConfiguration = get(); // if // (eventPlotConfiguration.getEventPlotConfigurations().size() // > 0) { if (eventPlotConfiguration != null && EventModel.getSingletonInstance().isEventsVisible()) { DrawController.getSingletonInstance().updateDrawableElement(eventPanel, plot); } // } } else { // Log.info("Worker was cancelled"); } } catch (InterruptedException e) { Log.error("Could not create the event type plot configurations" + e.getMessage()); Log.error("The error" + e.getMessage()); } catch (ExecutionException e) { Log.error("Could not create the event type plot configurations" + e.getMessage()); Log.error("The error" + e.getMessage()); } } }; currentSwingWorker.execute(); } private int defineMaximumDateLine(ArrayList<Date> endDates) { Date maxDate = null; int maxLine = 0; for (Date d : endDates) { if (maxDate == null) { // first case maxDate = d; maxLine = 0; } else { // the rest if (d.after(maxDate)) { maxDate = d; maxLine = endDates.indexOf(d); } } } return maxLine; } private int defineMinimalDateLine(ArrayList<Date> endDates) { Date minDate = null; int minLine = 0; for (Date d : endDates) { if (minDate == null) { // first case minDate = d; minLine = 0; } else { // the rest if (d.before(minDate)) { minDate = d; minLine = endDates.indexOf(d); } } } return minLine; } private double defineScaledValue(Date date) { double selectedDuration = 1.0 * (selectedInterval.getEnd().getTime() - selectedInterval.getStart().getTime()); double position = 1.0 * (date.getTime() - selectedInterval.getStart().getTime()); return position / selectedDuration; } public String getPlotIdentifier() { return plot; } private void fireEventsDeactivated() { for (EventModelListener l : listeners) { l.eventsDeactivated(); } } }
Code cleanup git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@3744 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/events/model/EventModel.java
Code cleanup
<ide><path>rc/plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/events/model/EventModel.java <ide> import org.helioviewer.plugins.eveplugin.view.plot.PlotsContainerPanel; <ide> <ide> /** <del> * <del> * <add> * <add> * <ide> * @author Bram Bourgoignie ([email protected]) <del> * <add> * <ide> */ <ide> public class EventModel implements ZoomControllerListener, EventRequesterListener { <ide> <ide> <ide> /** <ide> * Gets the singleton instance of the EventModel. <del> * <add> * <ide> * @return the singleton instance of the event model <ide> */ <ide> public static EventModel getSingletonInstance() { <ide> <ide> /** <ide> * Adds an event model listener to the event model. <del> * <add> * <ide> * @param listener <ide> * the listener to add <ide> */
JavaScript
mit
2273d389f0ae06a4dcf29cbc9c0a9ec6b2fe2d15
0
LefterisJP/mix,LianaHus/mix,ethereum/mix,yann300/mix,yann300/mix,LefterisJP/mix,LefterisJP/mix,chriseth/mix,tomthebuzz/mix,chriseth/mix,vaporry/mix,tomthebuzz/mix,tomthebuzz/mix,ethereum/mix,vaporry/mix,ethereum/mix,LianaHus/mix,yann300/mix,chriseth/mix,LianaHus/mix,vaporry/mix
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file NetworkDeployment.js * @author Arkadiy Paronyan [email protected] * @author Yann [email protected] * @date 2015 * Ethereum IDE client. */ .import org.ethereum.qml.QSolidityType 1.0 as QSolidityType Qt.include("TransactionHelper.js") Qt.include("QEtherHelper.js") var jsonRpcRequestId = 1; function deployProject(force) { saveAll(); //TODO: ask user deploymentDialog.open(); } function deployContracts(gas, gasPrice, callback) { deploymentGas = gas; deploymentGasPrice = gasPrice deploymentStarted(); var ctrAddresses = {}; var state = retrieveState(projectModel.deployedScenarioIndex); if (!state) { var txt = qsTr("Unable to find this scenario"); deploymentError(txt); console.log(txt); return; } var trHashes = {} executeTr(0, 0, state, ctrAddresses, trHashes, function(){ projectModel.deploymentAddresses = ctrAddresses; deploymentStepChanged(qsTr("Scenario deployed. Please wait for verifications")) if (callback) callback(ctrAddresses, trHashes) }); } function checkPathCreationCost(ethUrl, callBack) { var dappUrl = formatAppUrl(ethUrl); checkEthPath(dappUrl, true, function(success, cause) { if (!success) { switch (cause) { case "rootownedregistrar_notexist": deploymentError(qsTr("Owned registrar does not exist under the global registrar. Please create one using DApp registration.")); break; case "ownedregistrar_creationfailed": deploymentError(qsTr("The creation of your new owned registrar fails. Please use DApp registration to create one.")); break; case "ownedregistrar_notowner": deploymentError(qsTr("You are not the owner of this registrar. You cannot register your Dapp here.")); break; default: break; } } else callBack((dappUrl.length - 1) * (deploymentDialog.registerStep.ownedRegistrarDeployGas + deploymentDialog.registerStep.ownedRegistrarSetSubRegistrarGas) + deploymentDialog.registerStep.ownedRegistrarSetContentHashGas); }); } function gasUsed() { var gas = 0; var gasCosts = clientModel.gasCosts; for (var g in gasCosts) { gas += gasCosts[g]; } return gas; } function retrieveState(stateIndex) { return projectModel.stateListModel.get(stateIndex); } function replaceParamToken(paramsDef, params, ctrAddresses) { var retParams = {}; for (var k in paramsDef) { var value = ""; if (params[paramsDef[k].name] !== undefined) { value = params[paramsDef[k].name]; if (paramsDef[k].type.category === 4 && value.indexOf("<") === 0) { value = value.replace("<", "").replace(">", ""); value = ctrAddresses[value]; } } retParams[paramsDef[k].name] = value; } return retParams; } function getFunction(ctrName, functionId) { ctrName = contractFromToken(ctrName) if (codeModel.contracts[ctrName] === undefined) return null; if (ctrName === functionId) return codeModel.contracts[ctrName].contract.constructor; else { for (var j in codeModel.contracts[ctrName].contract.functions) { if (codeModel.contracts[ctrName].contract.functions[j].name === functionId) return codeModel.contracts[ctrName].contract.functions[j]; } } } var deploymentGas var deploymentGasPrice var trRealIndex = -1 function executeTr(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) { trRealIndex++; var tr = state.blocks.get(blockIndex).transactions.get(trIndex); if (!tr) callBack() var func = getFunction(tr.contractId, tr.functionId); if (!func) executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack); else { var gasCost = clientModel.toHex(deploymentGas[trRealIndex]); var rpcParams = { "from": deploymentDialog.worker.currentAccount, "gas": "0x" + gasCost, "gasPrice": deploymentGasPrice }; var params = replaceParamToken(func.parameters, tr.parameters, ctrAddresses); var encodedParams = clientModel.encodeParams(params, contractFromToken(tr.contractId), tr.functionId); if (tr.contractId === tr.functionId) rpcParams.code = codeModel.contracts[tr.contractId].codeHex + encodedParams.join(""); else { rpcParams.data = "0x" + func.qhash() + encodedParams.join(""); rpcParams.to = ctrAddresses[tr.contractId]; } var requests = [{ jsonrpc: "2.0", method: "eth_sendTransaction", params: [ rpcParams ], id: jsonRpcRequestId }]; rpcCall(requests, function (httpCall, response){ var txt = qsTr(tr.contractId + "." + tr.functionId + "() ...") deploymentStepChanged(txt); console.log(txt); var hash = JSON.parse(response)[0].result trHashes[tr.contractId + "." + tr.functionId + "()"] = hash deploymentDialog.worker.waitForTrReceipt(hash, function(status, receipt){ if (status === -1) trCountIncrementTimeOut(); else { if (tr.contractId === tr.functionId) { ctrAddresses[tr.contractId] = receipt.contractAddress ctrAddresses["<" + tr.contractId + " - " + trIndex + ">"] = receipt.contractAddress //get right ctr address if deploy more than one contract of same type. } executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) } }) }); } } function retrieveContractAddress(trHash, callback) { var requests = [{ jsonrpc: "2.0", method: "eth_getTransactionReceipt", params: [ trHash ], id: jsonRpcRequestId }]; rpcCall(requests, function (httpCall, response){ callback(JSON.parse(response)[0].contractAddress) }) } function executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) { trIndex++; if (trIndex < state.blocks.get(blockIndex).transactions.count) executeTr(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack); else { blockIndex++ if (blockIndex < state.blocks.count) executeTr(blockIndex, 0, state, ctrAddresses, trHashes, callBack); else callBack(); } } function gasPrice(callBack, error) { var requests = [{ jsonrpc: "2.0", method: "eth_gasPrice", params: [], id: jsonRpcRequestId }]; rpcCall(requests, function (httpCall, response){ callBack(JSON.parse(response)[0].result) }, function(message){ error(message) }); } function packageDapp(addresses) { var date = new Date(); var deploymentId = date.toLocaleString(Qt.locale(), "ddMMyyHHmmsszzz"); deploymentDialog.packageStep.deploymentId = deploymentId deploymentStepChanged(qsTr("Packaging application ...")); var deploymentDir = projectPath + deploymentId + "/"; if (deploymentDialog.packageStep.packageDir !== "") deploymentDir = deploymentDialog.packageStep.packageDir else deploymentDir = projectPath + "package/" projectModel.deploymentDir = deploymentDir; fileIo.makeDir(deploymentDir); for (var i = 0; i < projectListModel.count; i++) { var doc = projectListModel.get(i); if (doc.isContract) continue; if (doc.isHtml) { //inject the script to access contract API //TODO: use a template var html = fileIo.readFile(doc.path); var insertAt = html.indexOf("<head>") if (insertAt < 0) insertAt = 0; else insertAt += 6; html = html.substr(0, insertAt) + "<script src=\"deployment.js\"></script>" + html.substr(insertAt); fileIo.writeFile(deploymentDir + doc.fileName, html); } else fileIo.copyFile(doc.path, deploymentDir + doc.fileName); } //write deployment js var deploymentJs = "// Autogenerated by Mix\n" + "contracts = {};\n"; for (var c in codeModel.contracts) { var contractAccessor = "contracts[\"" + codeModel.contracts[c].contract.name + "\"]"; deploymentJs += contractAccessor + " = {\n" + "\tinterface: " + codeModel.contracts[c].contractInterface + ",\n" + "\taddress: \"" + addresses[c] + "\"\n" + "};\n" + contractAccessor + ".contractClass = web3.eth.contract(" + contractAccessor + ".interface);\n" + contractAccessor + ".contract = " + contractAccessor + ".contractClass.at(" + contractAccessor + ".address);\n"; } fileIo.writeFile(deploymentDir + "deployment.js", deploymentJs); deploymentAddresses = addresses; saveProject(); var packageRet = fileIo.makePackage(deploymentDir); deploymentDialog.packageStep.packageHash = packageRet[0]; deploymentDialog.packageStep.packageBase64 = packageRet[1]; deploymentDialog.packageStep.localPackageUrl = packageRet[2] + "?hash=" + packageRet[0]; deploymentDialog.packageStep.lastDeployDate = date deploymentStepChanged(qsTr("Dapp is Packaged")) } function registerDapp(url, gasPrice, callback) { deploymentGasPrice = gasPrice deploymentStepChanged(qsTr("Registering application on the Ethereum network ...")); checkEthPath(url, false, function (success) { if (!success) return; deploymentStepChanged(qsTr("Dapp has been registered. Please wait for verifications.")); if (callback) callback() }); } function checkEthPath(dappUrl, checkOnly, callBack) { if (dappUrl.length === 1) { // convenient for dev purpose, should not be possible in normal env. if (!checkOnly) reserve(deploymentDialog.registerStep.eth, function() { registerContentHash(deploymentDialog.registerStep.eth, callBack); // we directly create a dapp under the root registrar. }); else callBack(true); } else { // the first owned registrar must have been created to follow the path. var str = clientModel.encodeStringParam(dappUrl[0]); var requests = []; requests.push({ //subRegistrar() jsonrpc: "2.0", method: "eth_call", params: [ { "gas": "0xffff", "from": deploymentDialog.worker.currentAccount, "to": '0x' + deploymentDialog.registerStep.eth, "data": "0xe1fa8e84" + str }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); var addr = normalizeAddress(res[0].result); if (addr.replace(/0+/g, "") === "") { var errorTxt = qsTr("Path does not exists " + JSON.stringify(dappUrl) + ". Please register using Registration Dapp. Aborting."); deploymentError(errorTxt); console.log(errorTxt); callBack(false, "rootownedregistrar_notexist"); } else { dappUrl.splice(0, 1); checkRegistration(dappUrl, addr, callBack, checkOnly); } }); } } function isOwner(addr, callBack) { var requests = []; requests.push({ //getOwner() jsonrpc: "2.0", method: "eth_call", params: [ { "from": deploymentDialog.worker.currentAccount, "to": '0x' + addr, "data": "0xb387ef92" }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); callBack(normalizeAddress(deploymentDialog.worker.currentAccount) === normalizeAddress(res[0].result)); }); } function checkRegistration(dappUrl, addr, callBack, checkOnly) { isOwner(addr, function(ret){ if (!ret) { var errorTxt = qsTr("You are not the owner of " + dappUrl[0] + ". Aborting"); deploymentError(errorTxt); console.log(errorTxt); callBack(false, "ownedregistrar_notowner"); } else continueRegistration(dappUrl, addr, callBack, checkOnly); }); } function continueRegistration(dappUrl, addr, callBack, checkOnly) { if (dappUrl.length === 1) { if (!checkOnly) registerContentHash(addr, callBack); // We do not create the register for the last part, just registering the content hash. else callBack(true); } else { var txt = qsTr("Checking " + JSON.stringify(dappUrl)); deploymentStepChanged(txt); console.log(txt); var requests = []; var registrar = {} var str = clientModel.encodeStringParam(dappUrl[0]); requests.push({ //register() jsonrpc: "2.0", method: "eth_call", params: [ { "from": deploymentDialog.worker.currentAccount, "to": '0x' + addr, "data": "0x5a3a05bd" + str }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); var nextAddr = normalizeAddress(res[0].result); var errorTxt; if (res[0].result === "0x") { errorTxt = qsTr("Error when creating new owned registrar. Please use the registration Dapp. Aborting"); deploymentError(errorTxt); console.log(errorTxt); callBack(false, "ownedregistrar_creationfailed"); } else if (nextAddr.replace(/0+/g, "") !== "") { dappUrl.splice(0, 1); checkRegistration(dappUrl, nextAddr, callBack, checkOnly); } else { if (checkOnly) { callBack(true); return; } var txt = qsTr("Registering sub domain " + dappUrl[0] + " ..."); console.log(txt); deploymentStepChanged(txt); //current registrar is owned => ownedregistrar creation and continue. requests = []; var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarDeployGas); requests.push({ jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "code": "0x600080547fffffffffffffffffffffffff000000000000000000000000000000000000000016331781556105cd90819061003990396000f3007c010000000000000000000000000000000000000000000000000000000060003504630198489281146100b257806321f8a721146100e45780632dff6941146100ee5780633b3b57de1461010e5780635a3a05bd1461013e5780635fd4b08a146101715780637dd564111461017d57806389a69c0e14610187578063b387ef92146101bb578063b5c645bd146101f4578063be99a98014610270578063c3d014d6146102a8578063d93e7573146102dc57005b73ffffffffffffffffffffffffffffffffffffffff600435166000908152600160205260409020548060005260206000f35b6000808052602081f35b600435600090815260026020819052604090912001548060005260206000f35b600435600090815260026020908152604082205473ffffffffffffffffffffffffffffffffffffffff1680835291f35b600435600090815260026020908152604082206001015473ffffffffffffffffffffffffffffffffffffffff1680835291f35b60008060005260206000f35b6000808052602081f35b60005461030c9060043590602435903373ffffffffffffffffffffffffffffffffffffffff908116911614610569576105c9565b60005473ffffffffffffffffffffffffffffffffffffffff168073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b600435600090815260026020819052604090912080546001820154919092015473ffffffffffffffffffffffffffffffffffffffff9283169291909116908273ffffffffffffffffffffffffffffffffffffffff166000528173ffffffffffffffffffffffffffffffffffffffff166020528060405260606000f35b600054610312906004359060243590604435903373ffffffffffffffffffffffffffffffffffffffff90811691161461045457610523565b6000546103189060043590602435903373ffffffffffffffffffffffffffffffffffffffff90811691161461052857610565565b60005461031e90600435903373ffffffffffffffffffffffffffffffffffffffff90811691161461032457610451565b60006000f35b60006000f35b60006000f35b60006000f35b60008181526002602090815260408083205473ffffffffffffffffffffffffffffffffffffffff16835260019091529020548114610361576103e1565b6000818152600260205260408082205473ffffffffffffffffffffffffffffffffffffffff169183917ff63780e752c6a54a94fc52715dbc5518a3b4c3c2833d301a204226548a2a85459190a360008181526002602090815260408083205473ffffffffffffffffffffffffffffffffffffffff16835260019091528120555b600081815260026020819052604080832080547fffffffffffffffffffffffff00000000000000000000000000000000000000009081168255600182018054909116905590910182905582917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b50565b600083815260026020526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001683179055806104bb57827fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc60006040a2610522565b73ffffffffffffffffffffffffffffffffffffffff8216837ff63780e752c6a54a94fc52715dbc5518a3b4c3c2833d301a204226548a2a854560006040a373ffffffffffffffffffffffffffffffffffffffff821660009081526001602052604090208390555b5b505050565b600082815260026020819052604080832090910183905583917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b5050565b60008281526002602052604080822060010180547fffffffffffffffffffffffff0000000000000000000000000000000000000000168417905583917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b505056" } ], id: jsonRpcRequestId++ }); rpcCall(requests, function(httpRequest, response) { var newCtrAddress = normalizeAddress(JSON.parse(response)[0].result); requests = []; var txt = qsTr("Please wait " + dappUrl[0] + " is registering ..."); deploymentStepChanged(txt); console.log(txt); deploymentDialog.worker.waitForTrCountToIncrement(function(status) { if (status === -1) { trCountIncrementTimeOut(); return; } var crLevel = clientModel.encodeStringParam(dappUrl[0]); var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarSetSubRegistrarGas); requests.push({ //setRegister() jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "to": '0x' + addr, "data": "0x89a69c0e" + crLevel + newCtrAddress } ], id: jsonRpcRequestId++ }); rpcCall(requests, function(request, response){ dappUrl.splice(0, 1); checkRegistration(dappUrl, newCtrAddress, callBack); }); }); }); } }); } } function trCountIncrementTimeOut() { var error = qsTr("Something went wrong during the deployment. Please verify the amount of gas for this transaction and check your balance.") console.log(error); deploymentError(error); } function reserve(registrar, callBack) { var txt = qsTr("Making reservation in the root registrar..."); deploymentStepChanged(txt); console.log(txt); var requests = []; var paramTitle = clientModel.encodeStringParam(projectModel.projectTitle); requests.push({ //reserve() jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0xfffff", "to": '0x' + registrar, "data": "0x432ced04" + paramTitle } ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { callBack(); }); } function registerContentHash(registrar, callBack) { var txt = qsTr("Finalizing Dapp registration ..."); deploymentStepChanged(txt); console.log(txt); console.log("register url " + deploymentDialog.packageStep.packageHash + " " + projectModel.projectTitle) projectModel.registerContentHashTrHash = "" var requests = []; var paramTitle = clientModel.encodeStringParam(projectModel.projectTitle); var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarSetContentHashGas); requests.push({ //setContent() jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "to": '0x' + registrar, "data": "0xc3d014d6" + paramTitle + deploymentDialog.packageStep.packageHash } ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { projectModel.registerContentHashTrHash = JSON.parse(response)[0].result callBack(true); }); } function registerToUrlHint(url, gasPrice, callback) { console.log("register url " + deploymentDialog.packageStep.packageHash + " " + url) deploymentGasPrice = gasPrice deploymentStepChanged(qsTr("Registering application Resources...")) urlHintAddress(function(urlHint){ var requests = []; var paramUrlHttp = clientModel.encodeStringParam(url) var gasCost = clientModel.toHex(deploymentDialog.registerStep.urlHintSuggestUrlGas); requests.push({ //urlHint => suggestUrl jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "to": '0x' + urlHint, "gasPrice": deploymentGasPrice, "from": deploymentDialog.worker.currentAccount, "gas": "0x" + gasCost, "data": "0x584e86ad" + deploymentDialog.packageStep.packageHash + paramUrlHttp } ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { projectModel.registerUrlTrHash = JSON.parse(response)[0].result deploymentStepChanged(qsTr("Dapp resources has been registered. Please wait for verifications.")); if (callback) callback() }); }); } function urlHintAddress(callBack) { var requests = []; var urlHint = clientModel.encodeStringParam("urlhint"); requests.push({ //registrar: get UrlHint addr jsonrpc: "2.0", method: "eth_call", params: [ { "to": '0x' + deploymentDialog.registerStep.eth, "from": deploymentDialog.worker.currentAccount, "data": "0x3b3b57de" + urlHint }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); callBack(normalizeAddress(res[0].result)); }); } function normalizeAddress(addr) { addr = addr.replace('0x', ''); if (addr.length <= 40) return addr; var left = addr.length - 40; return addr.substring(left); } function formatAppUrl(url) { if (!url) return [projectModel.projectTitle]; if (url.toLowerCase().lastIndexOf("/") === url.length - 1) url = url.substring(0, url.length - 1); if (url.toLowerCase().indexOf("eth://") === 0) url = url.substring(6); if (url.toLowerCase().indexOf(projectModel.projectTitle + ".") === 0) url = url.substring(projectModel.projectTitle.length + 1); if (url === "") return [projectModel.projectTitle]; var ret; if (url.indexOf("/") === -1) ret = url.split('.').reverse(); else { var slash = url.indexOf("/"); var left = url.substring(0, slash); var leftA = left.split("."); leftA.reverse(); var right = url.substring(slash + 1); var rightA = right.split('/'); ret = leftA.concat(rightA); } if (ret[0].toLowerCase() === "eth") ret.splice(0, 1); ret.push(projectModel.projectTitle); return ret; }
qml/js/NetworkDeployment.js
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file NetworkDeployment.js * @author Arkadiy Paronyan [email protected] * @author Yann [email protected] * @date 2015 * Ethereum IDE client. */ .import org.ethereum.qml.QSolidityType 1.0 as QSolidityType Qt.include("TransactionHelper.js") Qt.include("QEtherHelper.js") var jsonRpcRequestId = 1; function deployProject(force) { saveAll(); //TODO: ask user deploymentDialog.open(); } function deployContracts(gas, gasPrice, callback) { deploymentGas = gas; deploymentGasPrice = gasPrice deploymentStarted(); var ctrAddresses = {}; var state = retrieveState(projectModel.deployedScenarioIndex); if (!state) { var txt = qsTr("Unable to find this scenario"); deploymentError(txt); console.log(txt); return; } var trHashes = {} executeTr(0, 0, state, ctrAddresses, trHashes, function(){ projectModel.deploymentAddresses = ctrAddresses; deploymentStepChanged(qsTr("Scenario deployed. Please wait for verifications")) if (callback) callback(ctrAddresses, trHashes) }); } function checkPathCreationCost(ethUrl, callBack) { var dappUrl = formatAppUrl(ethUrl); checkEthPath(dappUrl, true, function(success, cause) { if (!success) { switch (cause) { case "rootownedregistrar_notexist": deploymentError(qsTr("Owned registrar does not exist under the global registrar. Please create one using DApp registration.")); break; case "ownedregistrar_creationfailed": deploymentError(qsTr("The creation of your new owned registrar fails. Please use DApp registration to create one.")); break; case "ownedregistrar_notowner": deploymentError(qsTr("You are not the owner of this registrar. You cannot register your Dapp here.")); break; default: break; } } else callBack((dappUrl.length - 1) * (deploymentDialog.registerStep.ownedRegistrarDeployGas + deploymentDialog.registerStep.ownedRegistrarSetSubRegistrarGas) + deploymentDialog.registerStep.ownedRegistrarSetContentHashGas); }); } function gasUsed() { var gas = 0; var gasCosts = clientModel.gasCosts; for (var g in gasCosts) { gas += gasCosts[g]; } return gas; } function retrieveState(stateIndex) { return projectModel.stateListModel.get(stateIndex); } function replaceParamToken(paramsDef, params, ctrAddresses) { var retParams = {}; for (var k in paramsDef) { var value = ""; if (params[paramsDef[k].name] !== undefined) { value = params[paramsDef[k].name]; if (paramsDef[k].type.category === 4 && value.indexOf("<") === 0) { value = value.replace("<", "").replace(">", ""); value = ctrAddresses[value]; } } retParams[paramsDef[k].name] = value; } return retParams; } function getFunction(ctrName, functionId) { ctrName = contractFromToken(ctrName) if (codeModel.contracts[ctrName] === undefined) return null; if (ctrName === functionId) return codeModel.contracts[ctrName].contract.constructor; else { for (var j in codeModel.contracts[ctrName].contract.functions) { if (codeModel.contracts[ctrName].contract.functions[j].name === functionId) return codeModel.contracts[ctrName].contract.functions[j]; } } } var deploymentGas var deploymentGasPrice var trRealIndex = -1 function executeTr(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) { trRealIndex++; var tr = state.blocks.get(blockIndex).transactions.get(trIndex); if (!tr) callBack() var func = getFunction(tr.contractId, tr.functionId); if (!func) executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack); else { var gasCost = clientModel.toHex(deploymentGas[trRealIndex]); var rpcParams = { "from": deploymentDialog.worker.currentAccount, "gas": "0x" + gasCost, "gasPrice": deploymentGasPrice }; var params = replaceParamToken(func.parameters, tr.parameters, ctrAddresses); var encodedParams = clientModel.encodeParams(params, contractFromToken(tr.contractId), tr.functionId); if (tr.contractId === tr.functionId) rpcParams.code = codeModel.contracts[tr.contractId].codeHex + encodedParams.join(""); else { rpcParams.data = "0x" + func.qhash() + encodedParams.join(""); rpcParams.to = ctrAddresses[tr.contractId]; } var requests = [{ jsonrpc: "2.0", method: "eth_sendTransaction", params: [ rpcParams ], id: jsonRpcRequestId }]; rpcCall(requests, function (httpCall, response){ var txt = qsTr(tr.contractId + "." + tr.functionId + "() ...") deploymentStepChanged(txt); console.log(txt); var hash = JSON.parse(response)[0].result trHashes[tr.contractId + "." + tr.functionId + "()"] = hash deploymentDialog.worker.waitForTrReceipt(hash, function(status, receipt){ if (status === -1) trCountIncrementTimeOut(); else { if (tr.contractId === tr.functionId) { ctrAddresses[tr.contractId] = receipt.contractAddress ctrAddresses["<" + tr.contractId + " - " + trIndex + ">"] = receipt.contractAddress //get right ctr address if deploy more than one contract of same type. } executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) } }) }); } } function retrieveContractAddress(trHash, callback) { var requests = [{ jsonrpc: "2.0", method: "eth_getTransactionReceipt", params: [ trHash ], id: jsonRpcRequestId }]; rpcCall(requests, function (httpCall, response){ callback(JSON.parse(response)[0].contractAddress) }) } function executeTrNextStep(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack) { trIndex++; if (trIndex < state.blocks.get(blockIndex).transactions.count) executeTr(blockIndex, trIndex, state, ctrAddresses, trHashes, callBack); else { blockIndex++ if (blockIndex < state.blocks.count) executeTr(blockIndex, 0, state, ctrAddresses, trHashes, callBack); else callBack(); } } function gasPrice(callBack, error) { var requests = [{ jsonrpc: "2.0", method: "eth_gasPrice", params: [], id: jsonRpcRequestId }]; rpcCall(requests, function (httpCall, response){ callBack(JSON.parse(response)[0].result) }, function(message){ error(message) }); } function packageDapp(addresses) { var date = new Date(); var deploymentId = date.toLocaleString(Qt.locale(), "ddMMyyHHmmsszzz"); deploymentDialog.packageStep.deploymentId = deploymentId deploymentStepChanged(qsTr("Packaging application ...")); var deploymentDir = projectPath + deploymentId + "/"; if (deploymentDialog.packageStep.packageDir !== "") deploymentDir = deploymentDialog.packageStep.packageDir else deploymentDir = projectPath + "package/" projectModel.deploymentDir = deploymentDir; fileIo.makeDir(deploymentDir); for (var i = 0; i < projectListModel.count; i++) { var doc = projectListModel.get(i); if (doc.isContract) continue; if (doc.isHtml) { //inject the script to access contract API //TODO: use a template var html = fileIo.readFile(doc.path); var insertAt = html.indexOf("<head>") if (insertAt < 0) insertAt = 0; else insertAt += 6; html = html.substr(0, insertAt) + "<script src=\"deployment.js\"></script>" + html.substr(insertAt); fileIo.writeFile(deploymentDir + doc.fileName, html); } else fileIo.copyFile(doc.path, deploymentDir + doc.fileName); } //write deployment js var deploymentJs = "// Autogenerated by Mix\n" + "contracts = {};\n"; for (var c in codeModel.contracts) { var contractAccessor = "contracts[\"" + codeModel.contracts[c].contract.name + "\"]"; deploymentJs += contractAccessor + " = {\n" + "\tinterface: " + codeModel.contracts[c].contractInterface + ",\n" + "\taddress: \"" + addresses[c] + "\"\n" + "};\n" + contractAccessor + ".contractClass = web3.eth.contract(" + contractAccessor + ".interface);\n" + contractAccessor + ".contract = " + contractAccessor + ".contractClass.at(" + contractAccessor + ".address);\n"; } fileIo.writeFile(deploymentDir + "deployment.js", deploymentJs); deploymentAddresses = addresses; saveProject(); var packageRet = fileIo.makePackage(deploymentDir); deploymentDialog.packageStep.packageHash = packageRet[0]; deploymentDialog.packageStep.packageBase64 = packageRet[1]; deploymentDialog.packageStep.localPackageUrl = packageRet[2] + "?hash=" + packageRet[0]; deploymentDialog.packageStep.lastDeployDate = date deploymentStepChanged(qsTr("Dapp is Packaged")) } function registerDapp(url, gasPrice, callback) { deploymentGasPrice = gasPrice deploymentStepChanged(qsTr("Registering application on the Ethereum network ...")); checkEthPath(url, false, function (success) { if (!success) return; deploymentStepChanged(qsTr("Dapp has been registered. Please wait for verifications.")); if (callback) callback() }); } function checkEthPath(dappUrl, checkOnly, callBack) { if (dappUrl.length === 1) { // convenient for dev purpose, should not be possible in normal env. if (!checkOnly) reserve(deploymentDialog.registerStep.eth, function() { registerContentHash(deploymentDialog.registerStep.eth, callBack); // we directly create a dapp under the root registrar. }); else callBack(true); } else { // the first owned registrar must have been created to follow the path. var str = clientModel.encodeStringParam(dappUrl[0]); var requests = []; requests.push({ //subRegistrar() jsonrpc: "2.0", method: "eth_call", params: [ { "gas": "0xffff", "from": deploymentDialog.worker.currentAccount, "to": '0x' + deploymentDialog.registerStep.eth, "data": "0xe1fa8e84" + str }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); var addr = normalizeAddress(res[0].result); if (addr.replace(/0+/g, "") === "") { var errorTxt = qsTr("Path does not exists " + JSON.stringify(dappUrl) + ". Please register using Registration Dapp. Aborting."); deploymentError(errorTxt); console.log(errorTxt); callBack(false, "rootownedregistrar_notexist"); } else { dappUrl.splice(0, 1); checkRegistration(dappUrl, addr, callBack, checkOnly); } }); } } function isOwner(addr, callBack) { var requests = []; requests.push({ //getOwner() jsonrpc: "2.0", method: "eth_call", params: [ { "from": deploymentDialog.worker.currentAccount, "to": '0x' + addr, "data": "0xb387ef92" }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); callBack(normalizeAddress(deploymentDialog.worker.currentAccount) === normalizeAddress(res[0].result)); }); } function checkRegistration(dappUrl, addr, callBack, checkOnly) { isOwner(addr, function(ret){ if (!ret) { var errorTxt = qsTr("You are not the owner of " + dappUrl[0] + ". Aborting"); deploymentError(errorTxt); console.log(errorTxt); callBack(false, "ownedregistrar_notowner"); } else continueRegistration(dappUrl, addr, callBack, checkOnly); }); } function continueRegistration(dappUrl, addr, callBack, checkOnly) { if (dappUrl.length === 1) { if (!checkOnly) registerContentHash(addr, callBack); // We do not create the register for the last part, just registering the content hash. else callBack(true); } else { var txt = qsTr("Checking " + JSON.stringify(dappUrl)); deploymentStepChanged(txt); console.log(txt); var requests = []; var registrar = {} var str = clientModel.encodeStringParam(dappUrl[0]); requests.push({ //register() jsonrpc: "2.0", method: "eth_call", params: [ { "from": deploymentDialog.worker.currentAccount, "to": '0x' + addr, "data": "0x5a3a05bd" + str }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); var nextAddr = normalizeAddress(res[0].result); var errorTxt; if (res[0].result === "0x") { errorTxt = qsTr("Error when creating new owned registrar. Please use the registration Dapp. Aborting"); deploymentError(errorTxt); console.log(errorTxt); callBack(false, "ownedregistrar_creationfailed"); } else if (nextAddr.replace(/0+/g, "") !== "") { dappUrl.splice(0, 1); checkRegistration(dappUrl, nextAddr, callBack, checkOnly); } else { if (checkOnly) { callBack(true); return; } var txt = qsTr("Registering sub domain " + dappUrl[0] + " ..."); console.log(txt); deploymentStepChanged(txt); //current registrar is owned => ownedregistrar creation and continue. requests = []; var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarDeployGas); requests.push({ jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "code": "0x600080547fffffffffffffffffffffffff000000000000000000000000000000000000000016331781556105cd90819061003990396000f3007c010000000000000000000000000000000000000000000000000000000060003504630198489281146100b257806321f8a721146100e45780632dff6941146100ee5780633b3b57de1461010e5780635a3a05bd1461013e5780635fd4b08a146101715780637dd564111461017d57806389a69c0e14610187578063b387ef92146101bb578063b5c645bd146101f4578063be99a98014610270578063c3d014d6146102a8578063d93e7573146102dc57005b73ffffffffffffffffffffffffffffffffffffffff600435166000908152600160205260409020548060005260206000f35b6000808052602081f35b600435600090815260026020819052604090912001548060005260206000f35b600435600090815260026020908152604082205473ffffffffffffffffffffffffffffffffffffffff1680835291f35b600435600090815260026020908152604082206001015473ffffffffffffffffffffffffffffffffffffffff1680835291f35b60008060005260206000f35b6000808052602081f35b60005461030c9060043590602435903373ffffffffffffffffffffffffffffffffffffffff908116911614610569576105c9565b60005473ffffffffffffffffffffffffffffffffffffffff168073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b600435600090815260026020819052604090912080546001820154919092015473ffffffffffffffffffffffffffffffffffffffff9283169291909116908273ffffffffffffffffffffffffffffffffffffffff166000528173ffffffffffffffffffffffffffffffffffffffff166020528060405260606000f35b600054610312906004359060243590604435903373ffffffffffffffffffffffffffffffffffffffff90811691161461045457610523565b6000546103189060043590602435903373ffffffffffffffffffffffffffffffffffffffff90811691161461052857610565565b60005461031e90600435903373ffffffffffffffffffffffffffffffffffffffff90811691161461032457610451565b60006000f35b60006000f35b60006000f35b60006000f35b60008181526002602090815260408083205473ffffffffffffffffffffffffffffffffffffffff16835260019091529020548114610361576103e1565b6000818152600260205260408082205473ffffffffffffffffffffffffffffffffffffffff169183917ff63780e752c6a54a94fc52715dbc5518a3b4c3c2833d301a204226548a2a85459190a360008181526002602090815260408083205473ffffffffffffffffffffffffffffffffffffffff16835260019091528120555b600081815260026020819052604080832080547fffffffffffffffffffffffff00000000000000000000000000000000000000009081168255600182018054909116905590910182905582917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b50565b600083815260026020526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001683179055806104bb57827fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc60006040a2610522565b73ffffffffffffffffffffffffffffffffffffffff8216837ff63780e752c6a54a94fc52715dbc5518a3b4c3c2833d301a204226548a2a854560006040a373ffffffffffffffffffffffffffffffffffffffff821660009081526001602052604090208390555b5b505050565b600082815260026020819052604080832090910183905583917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b5050565b60008281526002602052604080822060010180547fffffffffffffffffffffffff0000000000000000000000000000000000000000168417905583917fa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc91a25b505056" } ], id: jsonRpcRequestId++ }); rpcCall(requests, function(httpRequest, response) { var newCtrAddress = normalizeAddress(JSON.parse(response)[0].result); requests = []; var txt = qsTr("Please wait " + dappUrl[0] + " is registering ..."); deploymentStepChanged(txt); console.log(txt); deploymentDialog.worker.waitForTrCountToIncrement(function(status) { if (status === -1) { trCountIncrementTimeOut(); return; } var crLevel = clientModel.encodeStringParam(dappUrl[0]); var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarSetSubRegistrarGas); requests.push({ //setRegister() jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "to": '0x' + addr, "data": "0x89a69c0e" + crLevel + newCtrAddress } ], id: jsonRpcRequestId++ }); rpcCall(requests, function(request, response){ dappUrl.splice(0, 1); checkRegistration(dappUrl, newCtrAddress, callBack); }); }); }); } }); } } function trCountIncrementTimeOut() { var error = qsTr("Something went wrong during the deployment. Please verify the amount of gas for this transaction and check your balance.") console.log(error); deploymentError(error); } function reserve(registrar, callBack) { var txt = qsTr("Making reservation in the root registrar..."); deploymentStepChanged(txt); console.log(txt); var requests = []; var paramTitle = clientModel.encodeStringParam(projectModel.projectTitle); requests.push({ //reserve() jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0xfffff", "to": '0x' + registrar, "data": "0x432ced04" + paramTitle } ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { callBack(); }); } function registerContentHash(registrar, callBack) { var txt = qsTr("Finalizing Dapp registration ..."); deploymentStepChanged(txt); console.log(txt); console.log("register url " + deploymentDialog.packageStep.packageHash + " " + projectModel.projectTitle) projectModel.registerContentHashTrHash = "" var requests = []; var paramTitle = clientModel.encodeStringParam(projectModel.projectTitle); var gasCost = clientModel.toHex(deploymentDialog.registerStep.ownedRegistrarSetContentHashGas); requests.push({ //setContent() jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "from": deploymentDialog.worker.currentAccount, "gasPrice": deploymentGasPrice, "gas": "0x" + gasCost, "to": '0x' + registrar, "data": "0xc3d014d6" + paramTitle + deploymentDialog.packageStep.packageHash } ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { projectModel.registerContentHashTrHash = JSON.parse(response)[0].result callBack(true); }); } function registerToUrlHint(url, gasPrice, callback) { console.log("register url " + deploymentDialog.packageStep.packageHash + " " + url) deploymentGasPrice = gasPrice deploymentStepChanged(qsTr("Registering application Resources...")) urlHintAddress(function(urlHint){ var requests = []; var paramUrlHttp = clientModel.encodeStringParam(url) var gasCost = clientModel.toHex(deploymentDialog.registerStep.urlHintSuggestUrlGas); requests.push({ //urlHint => suggestUrl jsonrpc: "2.0", method: "eth_sendTransaction", params: [ { "to": '0x' + urlHint, "gasPrice": deploymentGasPrice, "from": deploymentDialog.worker.currentAccount, "gas": "0x" + gasCost, "data": "0x584e86ad" + deploymentDialog.packageStep.packageHash + paramUrlHttp } ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { projectModel.registerUrlTrHash = JSON.parse(response)[0].result deploymentStepChanged(qsTr("Dapp resources has been registered. Please wait for verifications.")); if (callback) callback() }); }); } function urlHintAddress(callBack) { var requests = []; var urlHint = clientModel.encodeStringParam("urlhint"); requests.push({ //registrar: get UrlHint addr jsonrpc: "2.0", method: "eth_call", params: [ { "to": '0x' + deploymentDialog.registerStep.eth, "from": deploymentDialog.worker.currentAccount, "data": "0x3b3b57de" + urlHint }, "pending" ], id: jsonRpcRequestId++ }); rpcCall(requests, function (httpRequest, response) { var res = JSON.parse(response); callBack(normalizeAddress(res[0].result)); }); } function normalizeAddress(addr) { addr = addr.replace('0x', ''); if (addr.length <= 40) return addr; var left = addr.length - 40; return addr.substring(left); } function formatAppUrl(url) { if (!url) return [projectModel.projectTitle]; if (url.toLowerCase().lastIndexOf("/") === url.length - 1) url = url.substring(0, url.length - 1); if (url.toLowerCase().indexOf("eth://") === 0) url = url.substring(6); if (url.toLowerCase().indexOf(projectModel.projectTitle + ".") === 0) url = url.substring(projectModel.projectTitle.length + 1); if (url === "") return [projectModel.projectTitle]; var ret; if (url.indexOf("/") === -1) ret = url.split('.').reverse(); else { var slash = url.indexOf("/"); var left = url.substring(0, slash); var leftA = left.split("."); leftA.reverse(); var right = url.substring(slash + 1); var rightA = right.split('/'); ret = leftA.concat(rightA); } if (ret[0].toLowerCase() === "eth") ret.splice(0, 1); ret.push(projectModel.projectTitle); return ret; }
indentation
qml/js/NetworkDeployment.js
indentation
<ide><path>ml/js/NetworkDeployment.js <ide> if (tr.contractId === tr.functionId) <ide> rpcParams.code = codeModel.contracts[tr.contractId].codeHex + encodedParams.join(""); <ide> else <del> { <del> rpcParams.data = "0x" + func.qhash() + encodedParams.join(""); <del> rpcParams.to = ctrAddresses[tr.contractId]; <del> } <del> <del> <add> { <add> rpcParams.data = "0x" + func.qhash() + encodedParams.join(""); <add> rpcParams.to = ctrAddresses[tr.contractId]; <add> } <add> <ide> var requests = [{ <ide> jsonrpc: "2.0", <ide> method: "eth_sendTransaction",
Java
apache-2.0
20e6f5f400d04408d3d4e0ca6fe9331ef07e17fd
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.event.orche.state; import lombok.Getter; import lombok.RequiredArgsConstructor; import java.util.Collection; /** * Disabled event bus event. * * @author panjuan */ @RequiredArgsConstructor @Getter public final class DisabledStateEventBusEvent { private final Collection<String> disabledDataSourceNames; }
sharding-core/src/main/java/io/shardingsphere/core/event/orche/state/DisabledStateEventBusEvent.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.event.orche.state; import lombok.Getter; import lombok.RequiredArgsConstructor; import java.util.Collection; /** * JDBC disabled event bus event. * * @author panjuan */ @RequiredArgsConstructor @Getter public final class DisabledStateEventBusEvent { private final Collection<String> disabledDataSourceNames; }
modify java doc
sharding-core/src/main/java/io/shardingsphere/core/event/orche/state/DisabledStateEventBusEvent.java
modify java doc
<ide><path>harding-core/src/main/java/io/shardingsphere/core/event/orche/state/DisabledStateEventBusEvent.java <ide> import java.util.Collection; <ide> <ide> /** <del> * JDBC disabled event bus event. <add> * Disabled event bus event. <ide> * <ide> * @author panjuan <ide> */
JavaScript
mit
2d0618d46d8429c3a5f8ee2c75e739948878591d
0
vampiricwulf/tanoshiine,vampiricwulf/ex-tanoshiine,vampiricwulf/ex-tanoshiine,vampiricwulf/tanoshiine,vampiricwulf/tanoshiine,vampiricwulf/ex-tanoshiine,vampiricwulf/tanoshiine,vampiricwulf/ex-tanoshiine,vampiricwulf/ex-tanoshiine,vampiricwulf/tanoshiine
(function() { $('.catalogLink').click(function() { fetchJSON(render); }); function fetchJSON(cb) { $.getJSON(config.API_URL + 'catalog/' + BOARD, function(data) { if (!data) alert('Error'); cb(data); }); } function render(json) { // If not synced yet, try again in 0.1s if (connSM.state != 'synced') return setTimeout(function() { render(json); }, 100 ); var $start = $('hr.sectionHr').first(); var $el = $('<div/>', { id: 'catalog', }); // Remove threads $start.nextUntil($('hr.sectionHr').last()).remove(); $('.pagination').html('<a onclick="location.reload();">Return</a>'); var data,$post, html; for (var i = 0; i < json.length; i++) { data = json[i]; $post = $('<article/>'); html = []; data.dims = data.dims.split(','); // Downscale thumbnail data.dims[2] /= 1.66; data.dims[3] /= 1.66; // Render thumbnail html.push(oneeSama.gazou_img(data, false, './' + data.num).html, safe('<br>')); html.push(safe('<small>R: ' + data.replies + ' I: ' + data.imgctr + ' B: ' + data.bullyctr + ' ' + oneeSama.expansion_links_html(data.num) + '<br></small>')); if (data.subject) html.push(safe('<h3>「' + data.subject + '」</h3>')); // Render text body html.push(oneeSama.karada(data.body)); $post.append(flatten(html).join('')); // Prevent image hover preview $post.find('img').addClass('expanded'); $el.append($post); } // Prevent insertion of new threads BUMP = false; CATALOG = true; $start.after($el); // Thread creation can currently be done only on the 'live' page of the board // There are some more deaply-rooted issues in posting.js that prevent this on the // other pages if (PAGE == -1) $start.after('<aside class="act"><a>New thread</a></aside>'); } })();
client/catalog.js
(function() { $('.catalogLink').click(function() { fetchJSON(render); }); function fetchJSON(cb) { $.getJSON(config.API_URL + 'catalog/' + BOARD, function(data) { if (!data) alert('Error'); cb(data); }); } function render(json) { // If not synced yet, try again in 0.1s if (connSM.state != 'synced') return setTimeout(function() { render(json); }, 100 ); var $start = $('hr.sectionHr').first(); var $el = $('<div/>', { id: 'catalog', }); // Remove threads $start.nextUntil($('hr.sectionHr').last()).remove(); $('.pagination').html('<a onclick="location.reload();">Return</a>'); var data,$post, html; for (var i = 0; i < json.length; i++) { data = json[i]; $post = $('<article/>'); html = []; data.dims = data.dims.split(','); // Downscale thumbnail data.dims[2] /= 1.66; data.dims[3] /= 1.66; // Render thumbnail html.push(oneeSama.gazou_img(data, false, './' + data.num).html, safe('<br>')); html.push(safe('<small>R: ' + data.replies + ' ' + oneeSama.expansion_links_html(data.num) + '<br></small>')); if (data.subject) html.push(safe('<h3>「' + data.subject + '」</h3>')); // Render text body html.push(oneeSama.karada(data.body)); $post.append(flatten(html).join('')); // Prevent image hover preview $post.find('img').addClass('expanded'); $el.append($post); } // Prevent insertion of new threads BUMP = false; CATALOG = true; $start.after($el); // Thread creation can currently be done only on the 'live' page of the board // There are some more deaply-rooted issues in posting.js that prevent this on the // other pages if (PAGE == -1) $start.after('<aside class="act"><a>New thread</a></aside>'); } })();
more info in catalog
client/catalog.js
more info in catalog
<ide><path>lient/catalog.js <ide> data.dims[3] /= 1.66; <ide> // Render thumbnail <ide> html.push(oneeSama.gazou_img(data, false, './' + data.num).html, safe('<br>')); <del> html.push(safe('<small>R: ' + data.replies + ' ' + oneeSama.expansion_links_html(data.num) + '<br></small>')); <add> html.push(safe('<small>R: ' + data.replies + ' I: ' + data.imgctr + ' B: ' + data.bullyctr + ' ' + oneeSama.expansion_links_html(data.num) + '<br></small>')); <ide> if (data.subject) <ide> html.push(safe('<h3>「' + data.subject + '」</h3>')); <ide> // Render text body
Java
apache-2.0
07cd44a06e4b16d38330d443fc771ada187d537f
0
xnslong/logging-log4j2,lqbweb/logging-log4j2,xnslong/logging-log4j2,lqbweb/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,lqbweb/logging-log4j2,codescale/logging-log4j2
package org.apache.logging.log4j.core.impl; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.ReusableMessage; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.util.PropertiesUtil; import org.apache.logging.log4j.util.Strings; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.util.Map; /** * Mutable implementation of the {@code LogEvent} interface. * @since 2.6 */ public class MutableLogEvent implements LogEvent, ReusableMessage { private static final int INITIAL_REUSABLE_MESSAGE_SIZE = size("log4j.initialReusableMsgSize", 128); private static final int MAX_REUSABLE_MESSAGE_SIZE = size("log4j.maxReusableMsgSize", (128 * 2 + 2) * 2 + 2); private static final Object[] PARAMS = new Object[0]; private static final Message EMPTY = new SimpleMessage(Strings.EMPTY); private String loggerFqcn; private Marker marker; private Level level; private String loggerName; private Message message; private long timeMillis; private Throwable thrown; private ThrowableProxy thrownProxy; private Map<String, String> contextMap; private ThreadContext.ContextStack contextStack; private long threadId; private String threadName; private int threadPriority; private StackTraceElement source; private boolean includeLocation; private boolean endOfBatch = false; private long nanoTime; private StringBuilder messageText; private static int size(final String property, final int defaultValue) { return PropertiesUtil.getProperties().getIntegerProperty(property, defaultValue); } /** * Initialize the fields of this {@code MutableLogEvent} from another event. * Similar in purpose and usage as {@link org.apache.logging.log4j.core.impl.Log4jLogEvent.LogEventProxy}, * but a mutable version. * <p> * This method is used on async logger ringbuffer slots holding MutableLogEvent objects in each slot. * </p> * * @param event the event to copy data from */ public void initFrom(final LogEvent event) { this.loggerFqcn = event.getLoggerFqcn(); this.marker = event.getMarker(); this.level = event.getLevel(); this.loggerName = event.getLoggerName(); this.timeMillis = event.getTimeMillis(); this.thrown = event.getThrown(); this.thrownProxy = event.getThrownProxy(); this.contextMap = event.getContextMap(); this.contextStack = event.getContextStack(); this.source = event.isIncludeLocation() ? event.getSource() : null; this.threadId = event.getThreadId(); this.threadName = event.getThreadName(); this.threadPriority = event.getThreadPriority(); this.endOfBatch = event.isEndOfBatch(); this.nanoTime = event.getNanoTime(); setMessage(event.getMessage()); } public void clear() { loggerFqcn = null; marker = null; level = null; loggerName = null; message = null; thrown = null; thrownProxy = null; source = null; contextMap = null; contextStack = null; // threadName = null; // THreadName should not be cleared // primitive fields that cannot be cleared: //timeMillis; //threadId; //threadPriority; //includeLocation; //endOfBatch; //nanoTime; } @Override public String getLoggerFqcn() { return loggerFqcn; } public void setLoggerFqcn(String loggerFqcn) { this.loggerFqcn = loggerFqcn; } @Override public Marker getMarker() { return marker; } public void setMarker(Marker marker) { this.marker = marker; } @Override public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } @Override public String getLoggerName() { return loggerName; } public void setLoggerName(String loggerName) { this.loggerName = loggerName; } @Override public Message getMessage() { if (message == null) { return (messageText == null) ? EMPTY : this; } return message; } public void setMessage(final Message msg) { if (msg instanceof ReusableMessage) { ((ReusableMessage) msg).formatTo(getMessageTextForWriting()); // init messageText } else { // if the Message instance is reused, there is no point in freezing its message here if (!Constants.FORMAT_MESSAGES_IN_BACKGROUND && msg != null) { // LOG4J2-898: user may choose msg.getFormattedMessage(); // LOG4J2-763: ask message to freeze parameters } this.message = msg; } } private StringBuilder getMessageTextForWriting() { if (messageText == null) { // Should never happen: // only happens if user logs a custom reused message when Constants.ENABLE_THREADLOCALS is false messageText = new StringBuilder(INITIAL_REUSABLE_MESSAGE_SIZE); } messageText.setLength(0); return messageText; } /** * @see ReusableMessage#getFormattedMessage() */ @Override public String getFormattedMessage() { return messageText.toString(); } /** * @see ReusableMessage#getFormat() */ @Override public String getFormat() { return null; } /** * @see ReusableMessage#getParameters() */ @Override public Object[] getParameters() { return PARAMS; } /** * @see ReusableMessage#getThrowable() */ @Override public Throwable getThrowable() { return getThrown(); } /** * @see ReusableMessage#formatTo(StringBuilder) */ @Override public void formatTo(final StringBuilder buffer) { buffer.append(messageText); } @Override public Throwable getThrown() { return thrown; } public void setThrown(Throwable thrown) { this.thrown = thrown; } @Override public long getTimeMillis() { return timeMillis; } public void setTimeMillis(long timeMillis) { this.timeMillis = timeMillis; } /** * Returns the ThrowableProxy associated with the event, or null. * @return The ThrowableProxy associated with the event. */ @Override public ThrowableProxy getThrownProxy() { if (thrownProxy == null && thrown != null) { thrownProxy = new ThrowableProxy(thrown); } return thrownProxy; } /** * Returns the StackTraceElement for the caller. This will be the entry that occurs right * before the first occurrence of FQCN as a class name. * @return the StackTraceElement for the caller. */ @Override public StackTraceElement getSource() { if (source != null) { return source; } if (loggerFqcn == null || !includeLocation) { return null; } source = Log4jLogEvent.calcLocation(loggerFqcn); return source; } @Override public Map<String, String> getContextMap() { return contextMap; } public void setContextMap(Map<String, String> contextMap) { this.contextMap = contextMap; } @Override public ThreadContext.ContextStack getContextStack() { return contextStack; } public void setContextStack(ThreadContext.ContextStack contextStack) { this.contextStack = contextStack; } @Override public long getThreadId() { return threadId; } public void setThreadId(long threadId) { this.threadId = threadId; } @Override public String getThreadName() { return threadName; } public void setThreadName(String threadName) { this.threadName = threadName; } @Override public int getThreadPriority() { return threadPriority; } public void setThreadPriority(int threadPriority) { this.threadPriority = threadPriority; } @Override public boolean isIncludeLocation() { return includeLocation; } @Override public void setIncludeLocation(boolean includeLocation) { this.includeLocation = includeLocation; } @Override public boolean isEndOfBatch() { return endOfBatch; } @Override public void setEndOfBatch(boolean endOfBatch) { this.endOfBatch = endOfBatch; } @Override public long getNanoTime() { return nanoTime; } public void setNanoTime(long nanoTime) { this.nanoTime = nanoTime; } /** * Creates a LogEventProxy that can be serialized. * @return a LogEventProxy. */ protected Object writeReplace() { return new Log4jLogEvent.LogEventProxy(this, this.includeLocation); } private void readObject(final ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Proxy required"); } }
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/MutableLogEvent.java
package org.apache.logging.log4j.core.impl; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.ReusableMessage; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.util.PropertiesUtil; import org.apache.logging.log4j.util.Strings; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.util.Map; /** * Mutable implementation of the {@code LogEvent} interface. */ public class MutableLogEvent implements LogEvent, ReusableMessage { private static final int INITIAL_REUSABLE_MESSAGE_SIZE = size("log4j.initialReusableMsgSize", 128); private static final int MAX_REUSABLE_MESSAGE_SIZE = size("log4j.maxReusableMsgSize", (128 * 2 + 2) * 2 + 2); private static final Object[] PARAMS = new Object[0]; private static final Message EMPTY = new SimpleMessage(Strings.EMPTY); private String loggerFqcn; private Marker marker; private Level level; private String loggerName; private Message message; private Throwable thrown; private long timeMillis; private Map<String, String> contextMap; private ThreadContext.ContextStack contextStack; private long threadId; private String threadName; private int threadPriority; private boolean includeLocation; private boolean endOfBatch = false; private long nanoTime; private ThrowableProxy thrownProxy; private StackTraceElement source; private StringBuilder messageText; private static int size(final String property, final int defaultValue) { return PropertiesUtil.getProperties().getIntegerProperty(property, defaultValue); } /** * Initialize the fields of this {@code MutableLogEvent} from another event. * Similar in purpose and usage as {@link org.apache.logging.log4j.core.impl.Log4jLogEvent.LogEventProxy}, * but a mutable version. * <p> * This method is used on async logger ringbuffer slots holding MutableLogEvent objects in each slot. * </p> * * @param event the event to copy data from */ public void initFrom(final LogEvent event) { this.loggerFqcn = event.getLoggerFqcn(); this.marker = event.getMarker(); this.level = event.getLevel(); this.loggerName = event.getLoggerName(); this.timeMillis = event.getTimeMillis(); this.thrown = event.getThrown(); this.thrownProxy = event.getThrownProxy(); this.contextMap = event.getContextMap(); this.contextStack = event.getContextStack(); this.source = event.isIncludeLocation() ? event.getSource() : null; this.threadId = event.getThreadId(); this.threadName = event.getThreadName(); this.threadPriority = event.getThreadPriority(); this.endOfBatch = event.isEndOfBatch(); this.nanoTime = event.getNanoTime(); setMessage(event.getMessage()); } public void clear() { loggerFqcn = null; marker = null; level = null; loggerName = null; message = null; thrown = null; thrownProxy = null; source = null; contextMap = null; contextStack = null; threadName = null; // primitive fields that cannot be cleared: //timeMillis; //threadId; //threadPriority; //includeLocation; //endOfBatch; //nanoTime; } @Override public String getLoggerFqcn() { return loggerFqcn; } public void setLoggerFqcn(String loggerFqcn) { this.loggerFqcn = loggerFqcn; } @Override public Marker getMarker() { return marker; } public void setMarker(Marker marker) { this.marker = marker; } @Override public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } @Override public String getLoggerName() { return loggerName; } public void setLoggerName(String loggerName) { this.loggerName = loggerName; } @Override public Message getMessage() { if (message == null) { return (messageText == null) ? EMPTY : this; } return message; } public void setMessage(final Message msg) { if (msg instanceof ReusableMessage) { ((ReusableMessage) msg).formatTo(getMessageTextForWriting()); } else { // if the Message instance is reused, there is no point in freezing its message here if (!Constants.FORMAT_MESSAGES_IN_BACKGROUND && msg != null) { // LOG4J2-898: user may choose msg.getFormattedMessage(); // LOG4J2-763: ask message to freeze parameters } this.message = msg; } } private StringBuilder getMessageTextForWriting() { if (messageText == null) { // Should never happen: // only happens if user logs a custom reused message when Constants.ENABLE_THREADLOCALS is false messageText = new StringBuilder(INITIAL_REUSABLE_MESSAGE_SIZE); } messageText.setLength(0); return messageText; } /** * @see ReusableMessage#getFormattedMessage() */ @Override public String getFormattedMessage() { return messageText.toString(); } /** * @see ReusableMessage#getFormat() */ @Override public String getFormat() { return null; } /** * @see ReusableMessage#getParameters() */ @Override public Object[] getParameters() { return PARAMS; } /** * @see ReusableMessage#getThrowable() */ @Override public Throwable getThrowable() { return getThrown(); } /** * @see ReusableMessage#formatTo(StringBuilder) */ @Override public void formatTo(final StringBuilder buffer) { buffer.append(messageText); } @Override public Throwable getThrown() { return thrown; } public void setThrown(Throwable thrown) { this.thrown = thrown; } @Override public long getTimeMillis() { return timeMillis; } public void setTimeMillis(long timeMillis) { this.timeMillis = timeMillis; } /** * Returns the ThrowableProxy associated with the event, or null. * @return The ThrowableProxy associated with the event. */ @Override public ThrowableProxy getThrownProxy() { if (thrownProxy == null && thrown != null) { thrownProxy = new ThrowableProxy(thrown); } return thrownProxy; } /** * Returns the StackTraceElement for the caller. This will be the entry that occurs right * before the first occurrence of FQCN as a class name. * @return the StackTraceElement for the caller. */ @Override public StackTraceElement getSource() { if (source != null) { return source; } if (loggerFqcn == null || !includeLocation) { return null; } source = Log4jLogEvent.calcLocation(loggerFqcn); return source; } @Override public Map<String, String> getContextMap() { return contextMap; } public void setContextMap(Map<String, String> contextMap) { this.contextMap = contextMap; } @Override public ThreadContext.ContextStack getContextStack() { return contextStack; } public void setContextStack(ThreadContext.ContextStack contextStack) { this.contextStack = contextStack; } @Override public long getThreadId() { return threadId; } public void setThreadId(long threadId) { this.threadId = threadId; } @Override public String getThreadName() { return threadName; } public void setThreadName(String threadName) { this.threadName = threadName; } @Override public int getThreadPriority() { return threadPriority; } public void setThreadPriority(int threadPriority) { this.threadPriority = threadPriority; } @Override public boolean isIncludeLocation() { return includeLocation; } @Override public void setIncludeLocation(boolean includeLocation) { this.includeLocation = includeLocation; } @Override public boolean isEndOfBatch() { return endOfBatch; } @Override public void setEndOfBatch(boolean endOfBatch) { this.endOfBatch = endOfBatch; } @Override public long getNanoTime() { return nanoTime; } public void setNanoTime(long nanoTime) { this.nanoTime = nanoTime; } /** * Creates a LogEventProxy that can be serialized. * @return a LogEventProxy. */ protected Object writeReplace() { return new Log4jLogEvent.LogEventProxy(this, this.includeLocation); } private void readObject(final ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Proxy required"); } }
LOG4J2-1334 MutableLogEvent bugfix: don't clear thread name
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/MutableLogEvent.java
LOG4J2-1334 MutableLogEvent bugfix: don't clear thread name
<ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/impl/MutableLogEvent.java <ide> <ide> /** <ide> * Mutable implementation of the {@code LogEvent} interface. <add> * @since 2.6 <ide> */ <ide> public class MutableLogEvent implements LogEvent, ReusableMessage { <ide> private static final int INITIAL_REUSABLE_MESSAGE_SIZE = size("log4j.initialReusableMsgSize", 128); <ide> private Level level; <ide> private String loggerName; <ide> private Message message; <add> private long timeMillis; <ide> private Throwable thrown; <del> private long timeMillis; <add> private ThrowableProxy thrownProxy; <ide> private Map<String, String> contextMap; <ide> private ThreadContext.ContextStack contextStack; <ide> private long threadId; <ide> private String threadName; <ide> private int threadPriority; <add> private StackTraceElement source; <ide> private boolean includeLocation; <ide> private boolean endOfBatch = false; <ide> private long nanoTime; <del> private ThrowableProxy thrownProxy; <del> private StackTraceElement source; <ide> private StringBuilder messageText; <ide> <ide> private static int size(final String property, final int defaultValue) { <ide> source = null; <ide> contextMap = null; <ide> contextStack = null; <del> threadName = null; <add> // threadName = null; // THreadName should not be cleared <ide> // primitive fields that cannot be cleared: <ide> //timeMillis; <ide> //threadId; <ide> <ide> public void setMessage(final Message msg) { <ide> if (msg instanceof ReusableMessage) { <del> ((ReusableMessage) msg).formatTo(getMessageTextForWriting()); <add> ((ReusableMessage) msg).formatTo(getMessageTextForWriting()); // init messageText <ide> } else { <ide> // if the Message instance is reused, there is no point in freezing its message here <ide> if (!Constants.FORMAT_MESSAGES_IN_BACKGROUND && msg != null) { // LOG4J2-898: user may choose
Java
mit
fd475a293e6f315c06de9d1f4ec1ee7011b5f164
0
BBN-E/bue-common-open,rgabbard-bbn/bue-common-open,BBN-E/bue-common-open,rgabbard-bbn/bue-common-open
package com.bbn.bue.common; import com.bbn.bue.common.collections.CollectionUtils; import com.bbn.bue.common.files.FileUtils; import com.bbn.bue.common.parameters.Parameters; import com.bbn.bue.common.symbols.Symbol; import com.bbn.bue.common.symbols.SymbolUtils; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.Set; import java.util.SortedMap; import static com.google.common.base.Predicates.in; /** * Given a list of files and a number of splits, creates training/test file lists for * cross-validation. When the files cannot be evenly divided across all splits, extra files are * distributed as evenly as possible, starting with the first folds. For example, dividing 11 items * into three folds will result in folds of size (4, 4, 3). * * Normally, cross-validation batches are made such that as much data as possible is used in * training. However, if the {@code singleFoldTraining} parameter is set to true, train and test * are swapped: a small (single fold) size data is used for the training data for that batch with * all other data used for testing, and each data point appears exactly once across test folds. */ public final class MakeCrossValidationBatches { private static final Logger log = LoggerFactory.getLogger(MakeCrossValidationBatches.class); private static final String PARAM_NAMESPACE = "com.bbn.bue.common.crossValidation."; private static final String PARAM_FILE_LIST = PARAM_NAMESPACE + "fileList"; private static final String PARAM_FILE_MAP = PARAM_NAMESPACE + "fileMap"; private static final String PARAM_NUM_BATCHES = PARAM_NAMESPACE + "numBatches"; private static final String PARAM_RANDOM_SEED = PARAM_NAMESPACE + "randomSeed"; private static final String PARAM_OUTPUT_DIR = PARAM_NAMESPACE + "outputDir"; private static final String PARAM_OUTPUT_NAME = PARAM_NAMESPACE + "outputName"; private static final String PARAM_SINGLE_FOLD_TRAINING = PARAM_NAMESPACE + "singleFoldTraining"; private MakeCrossValidationBatches() { throw new UnsupportedOperationException(); } public static void main(String[] argv) { // we wrap the main method in this way to // ensure a non-zero return value on failure try { trueMain(argv); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void errorExit(final String msg) { System.err.println("Error: " + msg); System.exit(1); } private static void trueMain(String[] argv) throws IOException { if (argv.length != 1) { errorExit("Usage: MakeCrossValidationBatches params"); } final Parameters parameters = Parameters.loadSerifStyle(new File(argv[0])); // Can run on map or list, but only one of the two. parameters.assertExactlyOneDefined(PARAM_FILE_LIST, PARAM_FILE_MAP); // Configure for map/list boolean useFileMap = false; final File sourceFiles; if (parameters.isPresent(PARAM_FILE_LIST)) { sourceFiles = parameters.getExistingFile(PARAM_FILE_LIST); } else if (parameters.isPresent(PARAM_FILE_MAP)) { useFileMap = true; sourceFiles = parameters.getExistingFile(PARAM_FILE_MAP); } else { throw new IllegalArgumentException("Impossible state reached"); } // Configure for single fold training. boolean singleFoldTraining = parameters.getOptionalBoolean(PARAM_SINGLE_FOLD_TRAINING).or(false); final File outputDirectory = parameters.getCreatableDirectory(PARAM_OUTPUT_DIR); final String outputName = parameters.getString(PARAM_OUTPUT_NAME); final int numBatches = parameters.getPositiveInteger(PARAM_NUM_BATCHES); final int randomSeed = parameters.getInteger(PARAM_RANDOM_SEED); if (numBatches < 1) { errorExit("Bad numBatches value: Need one or more batches to divide data into"); } final int maxBatch = numBatches - 1; final ImmutableMap<Symbol, File> docIdMap; if (useFileMap) { docIdMap = FileUtils.loadSymbolToFileMap(Files.asCharSource(sourceFiles, Charsets.UTF_8)); } else { // We load a file list but coerce it into a map final ImmutableList<File> inputFiles = FileUtils.loadFileList(sourceFiles); docIdMap = Maps.uniqueIndex(inputFiles, FileToSymbolFunction.INSTANCE); // Check that nothing was lost in the conversion if (docIdMap.size() != inputFiles.size()) { errorExit("Input file list contains duplicate entries"); } } // Get the list of docids and shuffle them. In the case of using a file list, these are just // paths, not document ids, but they serve the same purpose. final ImmutableList<Symbol> docIds = shuffledDocIds(randomSeed, docIdMap); if (numBatches > docIds.size()) { errorExit("Bad numBatches value: Cannot create more batches than there are input files"); } // Divide into folds final ImmutableList<ImmutableList<Symbol>> testFolds = CollectionUtils.partitionAlmostEvenly(docIds, numBatches); // Write out training/test data for each fold final ImmutableList.Builder<File> foldLists = ImmutableList.builder(); final ImmutableList.Builder<File> foldMaps = ImmutableList.builder(); int batchNum = 0; int totalDocs = 0; // Set up train folds final ImmutableList<ImmutableList<Symbol>> trainFolds = createTrainFolds(testFolds, docIds, singleFoldTraining); // Loop over train/test folds Preconditions.checkState(trainFolds.size() == testFolds.size()); for (int i = 0; i < testFolds.size(); i++) { final ImmutableList<Symbol> testDocIds = testFolds.get(i); final ImmutableList<Symbol> trainDocIds = trainFolds.get(i); // Track the total test documents across folds to make sure nothing is lost. totalDocs += testDocIds.size(); // Create maps for training and test. These are sorted to avoid arbitrary ordering. final SortedMap<Symbol, File> trainDocIdMap = ImmutableSortedMap.copyOf(Maps.filterKeys(docIdMap, in(trainDocIds)), SymbolUtils.byStringOrdering()); final SortedMap<Symbol, File> testDocIdMap = ImmutableSortedMap.copyOf(Maps.filterKeys(docIdMap, in(testDocIds)), SymbolUtils.byStringOrdering()); // Don't write out the maps for file lists as the keys are not actually document IDs if (useFileMap) { final File trainingMapOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".training.docIDToFileMap"); FileUtils.writeSymbolToFileMap(trainDocIdMap, Files.asCharSink(trainingMapOutputFile, Charsets.UTF_8)); final File testMapOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".test.docIDToFileMap"); FileUtils.writeSymbolToFileMap(testDocIdMap, Files.asCharSink(testMapOutputFile, Charsets.UTF_8)); foldMaps.add(testMapOutputFile); } // Write out file lists final ImmutableList<File> trainingFilesForBatch = ImmutableList.copyOf(trainDocIdMap.values()); final ImmutableList<File> testFilesForBatch = ImmutableList.copyOf(testDocIdMap.values()); final File trainingOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".training.list"); FileUtils.writeFileList(trainingFilesForBatch, Files.asCharSink(trainingOutputFile, Charsets.UTF_8)); final File testOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".test.list"); FileUtils.writeFileList(testFilesForBatch, Files.asCharSink(testOutputFile, Charsets.UTF_8)); foldLists.add(testOutputFile); ++batchNum; } if (totalDocs != docIdMap.size()) { errorExit("Test files created are not the same length as the input"); } // Write out lists of files/maps created FileUtils.writeFileList(foldLists.build(), Files.asCharSink(new File(outputDirectory, "folds.list"), Charsets.UTF_8)); if (useFileMap) { FileUtils.writeFileList(foldMaps.build(), Files.asCharSink(new File(outputDirectory, "folds.maplist"), Charsets.UTF_8)); } log.info("Wrote {} cross validation batches from {} to directory {}", numBatches, sourceFiles.getAbsoluteFile(), outputDirectory.getAbsolutePath()); } private static ImmutableList<Symbol> shuffledDocIds(final int randomSeed, final ImmutableMap<Symbol, File> docIdMap) { final ArrayList<Symbol> docIds = Lists.newArrayList(docIdMap.keySet()); Collections.shuffle(docIds, new Random(randomSeed)); return ImmutableList.copyOf(docIds); } private static ImmutableList<ImmutableList<Symbol>> createTrainFolds( final ImmutableList<ImmutableList<Symbol>> testFolds, final ImmutableList<Symbol> docIds, final boolean singleFoldTraining) { final ImmutableList.Builder<ImmutableList<Symbol>> ret = ImmutableList.builder(); for (int i = 0; i < testFolds.size(); i++) { final Set<Symbol> testDocIds = ImmutableSet.copyOf(testFolds.get(i)); final ImmutableList<Symbol> trainDocIds = singleFoldTraining // In the single fold training case, use the "next" fold as the training data. We use // the modulus to wrap around the list. ? testFolds.get((i + 1) % testFolds.size()) // In the normal case, just use all the remaining data for training. : Sets.difference(ImmutableSet.copyOf(docIds), testDocIds).immutableCopy().asList(); ret.add(trainDocIds); } return ret.build(); } private enum FileToSymbolFunction implements Function<File, Symbol> { INSTANCE; @Override public Symbol apply(final File input) { return Symbol.from(input.getAbsolutePath()); } } }
common-core-open/src/main/java/com/bbn/bue/common/MakeCrossValidationBatches.java
package com.bbn.bue.common; import com.bbn.bue.common.collections.CollectionUtils; import com.bbn.bue.common.files.FileUtils; import com.bbn.bue.common.parameters.Parameters; import com.bbn.bue.common.symbols.Symbol; import com.bbn.bue.common.symbols.SymbolUtils; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.Set; import java.util.SortedMap; import static com.google.common.base.Predicates.in; /** * Given a list of files and a number of splits, creates training/test file lists for * cross-validation. When the files cannot be evenly divided across all splits, extra files are * distributed as evenly as possible, starting with the first folds. For example, dividing 11 items * into three folds will result in folds of size (4, 4, 3). */ public final class MakeCrossValidationBatches { private static final Logger log = LoggerFactory.getLogger(MakeCrossValidationBatches.class); private static final String PARAM_FILE_LIST = "com.bbn.bue.common.crossValidation.fileList"; private static final String PARAM_FILE_MAP = "com.bbn.bue.common.crossValidation.fileMap"; private static final String PARAM_NUM_BATCHES = "com.bbn.bue.common.crossValidation.numBatches"; private static final String PARAM_RANDOM_SEED = "com.bbn.bue.common.crossValidation.randomSeed"; private static final String PARAM_OUTPUT_DIR = "com.bbn.bue.common.crossValidation.outputDir"; private static final String PARAM_OUTPUT_NAME = "com.bbn.bue.common.crossValidation.outputName"; private MakeCrossValidationBatches() { throw new UnsupportedOperationException(); } public static void main(String[] argv) { // we wrap the main method in this way to // ensure a non-zero return value on failure try { trueMain(argv); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void errorExit(final String msg) { System.err.println("Error: " + msg); System.exit(1); } private static void trueMain(String[] argv) throws IOException { if (argv.length != 1) { errorExit("Usage: MakeCrossValidationBatches params"); } final Parameters parameters = Parameters.loadSerifStyle(new File(argv[0])); // Can run on map or list, but only one of the two. parameters.assertExactlyOneDefined(PARAM_FILE_LIST, PARAM_FILE_MAP); // Configure for map/list boolean useFileMap = false; final File sourceFiles; if (parameters.isPresent(PARAM_FILE_LIST)) { sourceFiles = parameters.getExistingFile(PARAM_FILE_LIST); } else if (parameters.isPresent(PARAM_FILE_MAP)) { useFileMap = true; sourceFiles = parameters.getExistingFile(PARAM_FILE_MAP); } else { throw new IllegalArgumentException("Impossible state reached"); } final File outputDirectory = parameters.getCreatableDirectory(PARAM_OUTPUT_DIR); final String outputName = parameters.getString(PARAM_OUTPUT_NAME); final int numBatches = parameters.getPositiveInteger(PARAM_NUM_BATCHES); final int randomSeed = parameters.getInteger(PARAM_RANDOM_SEED); if (numBatches < 1) { errorExit("Bad numBatches value: Need one or more batches to divide data into"); } final int maxBatch = numBatches - 1; final ImmutableMap<Symbol, File> docIdMap; if (useFileMap) { docIdMap = FileUtils.loadSymbolToFileMap(Files.asCharSource(sourceFiles, Charsets.UTF_8)); } else { // We load a file list but coerce it into a map final ImmutableList<File> inputFiles = FileUtils.loadFileList(sourceFiles); docIdMap = Maps.uniqueIndex(inputFiles, FileToSymbolFunction.INSTANCE); // Check that nothing was lost in the conversion if (docIdMap.size() != inputFiles.size()) { errorExit("Input file list contains duplicate entries"); } } // Get the list of docids and shuffle them. In the case of using a file list, these are just // paths, not document ids, but they serve the same purpose. final ArrayList<Symbol> docIds = Lists.newArrayList(docIdMap.keySet()); if (numBatches > docIds.size()) { errorExit("Bad numBatches value: Cannot create more batches than there are input files"); } Collections.shuffle(docIds, new Random(randomSeed)); // Divide into folds final ImmutableList<ImmutableList<Symbol>> folds = CollectionUtils.partitionAlmostEvenly(docIds, numBatches); // Write out training/test data for each fold final ImmutableList.Builder<File> foldLists = ImmutableList.builder(); final ImmutableList.Builder<File> foldMaps = ImmutableList.builder(); int batchNum = 0; int totalTest = 0; for (final ImmutableList<Symbol> docIdsForBatch : folds) { final Set<Symbol> testDocIds = ImmutableSet.copyOf(docIdsForBatch); final Set<Symbol> trainDocIds = Sets.difference(ImmutableSet.copyOf(docIds), testDocIds).immutableCopy(); // Create maps for training and test. These are sorted to avoid arbitrary ordering. final SortedMap<Symbol, File> trainDocIdMap = ImmutableSortedMap.copyOf(Maps.filterKeys(docIdMap, in(trainDocIds)), SymbolUtils.byStringOrdering()); final SortedMap<Symbol, File> testDocIdMap = ImmutableSortedMap.copyOf(Maps.filterKeys(docIdMap, in(testDocIds)), SymbolUtils.byStringOrdering()); // Don't write out the maps for file lists as the keys are not actually document IDs if (useFileMap) { final File trainingMapOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".training.docIDToFileMap"); FileUtils.writeSymbolToFileMap(trainDocIdMap, Files.asCharSink(trainingMapOutputFile, Charsets.UTF_8)); final File testMapOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".test.docIDToFileMap"); FileUtils.writeSymbolToFileMap(testDocIdMap, Files.asCharSink(testMapOutputFile, Charsets.UTF_8)); foldMaps.add(testMapOutputFile); } // Write out file lists final ImmutableList<File> trainingFilesForBatch = ImmutableList.copyOf(trainDocIdMap.values()); final ImmutableList<File> testFilesForBatch = ImmutableList.copyOf(testDocIdMap.values()); final File trainingOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".training.list"); FileUtils.writeFileList(trainingFilesForBatch, Files.asCharSink(trainingOutputFile, Charsets.UTF_8)); final File testOutputFile = new File(outputDirectory, outputName + "." + StringUtils.padWithMax(batchNum, maxBatch) + ".test.list"); FileUtils.writeFileList(testFilesForBatch, Files.asCharSink(testOutputFile, Charsets.UTF_8)); foldLists.add(testOutputFile); ++batchNum; totalTest += testDocIdMap.size(); } if(totalTest != docIdMap.size()) { errorExit("Test files created are not the same length as the input"); } // Write out lists of files/maps created FileUtils.writeFileList(foldLists.build(), Files.asCharSink(new File(outputDirectory, "folds.list"), Charsets.UTF_8)); if (useFileMap) { FileUtils.writeFileList(foldMaps.build(), Files.asCharSink(new File(outputDirectory, "folds.maplist"), Charsets.UTF_8)); } log.info("Wrote {} cross validation batches from {} to directory {}", numBatches, sourceFiles.getAbsoluteFile(), outputDirectory.getAbsolutePath()); } private enum FileToSymbolFunction implements Function<File, Symbol> { INSTANCE; @Override public Symbol apply(final File input) { return Symbol.from(input.getAbsolutePath()); } } }
Add singleFoldTraining mode
common-core-open/src/main/java/com/bbn/bue/common/MakeCrossValidationBatches.java
Add singleFoldTraining mode
<ide><path>ommon-core-open/src/main/java/com/bbn/bue/common/MakeCrossValidationBatches.java <ide> import com.bbn.bue.common.parameters.Parameters; <ide> import com.bbn.bue.common.symbols.Symbol; <ide> import com.bbn.bue.common.symbols.SymbolUtils; <add> <ide> import com.google.common.base.Charsets; <ide> import com.google.common.base.Function; <add>import com.google.common.base.Preconditions; <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableMap; <ide> import com.google.common.collect.ImmutableSet; <ide> import com.google.common.collect.Maps; <ide> import com.google.common.collect.Sets; <ide> import com.google.common.io.Files; <add> <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> * cross-validation. When the files cannot be evenly divided across all splits, extra files are <ide> * distributed as evenly as possible, starting with the first folds. For example, dividing 11 items <ide> * into three folds will result in folds of size (4, 4, 3). <add> * <add> * Normally, cross-validation batches are made such that as much data as possible is used in <add> * training. However, if the {@code singleFoldTraining} parameter is set to true, train and test <add> * are swapped: a small (single fold) size data is used for the training data for that batch with <add> * all other data used for testing, and each data point appears exactly once across test folds. <ide> */ <ide> public final class MakeCrossValidationBatches { <ide> <ide> private static final Logger log = LoggerFactory.getLogger(MakeCrossValidationBatches.class); <ide> <del> private static final String PARAM_FILE_LIST = "com.bbn.bue.common.crossValidation.fileList"; <del> private static final String PARAM_FILE_MAP = "com.bbn.bue.common.crossValidation.fileMap"; <del> private static final String PARAM_NUM_BATCHES = "com.bbn.bue.common.crossValidation.numBatches"; <del> private static final String PARAM_RANDOM_SEED = "com.bbn.bue.common.crossValidation.randomSeed"; <del> private static final String PARAM_OUTPUT_DIR = "com.bbn.bue.common.crossValidation.outputDir"; <del> private static final String PARAM_OUTPUT_NAME = "com.bbn.bue.common.crossValidation.outputName"; <add> private static final String PARAM_NAMESPACE = "com.bbn.bue.common.crossValidation."; <add> private static final String PARAM_FILE_LIST = PARAM_NAMESPACE + "fileList"; <add> private static final String PARAM_FILE_MAP = PARAM_NAMESPACE + "fileMap"; <add> private static final String PARAM_NUM_BATCHES = PARAM_NAMESPACE + "numBatches"; <add> private static final String PARAM_RANDOM_SEED = PARAM_NAMESPACE + "randomSeed"; <add> private static final String PARAM_OUTPUT_DIR = PARAM_NAMESPACE + "outputDir"; <add> private static final String PARAM_OUTPUT_NAME = PARAM_NAMESPACE + "outputName"; <add> private static final String PARAM_SINGLE_FOLD_TRAINING = PARAM_NAMESPACE + "singleFoldTraining"; <ide> <ide> private MakeCrossValidationBatches() { <ide> throw new UnsupportedOperationException(); <ide> throw new IllegalArgumentException("Impossible state reached"); <ide> } <ide> <add> // Configure for single fold training. <add> boolean singleFoldTraining = <add> parameters.getOptionalBoolean(PARAM_SINGLE_FOLD_TRAINING).or(false); <add> <ide> final File outputDirectory = parameters.getCreatableDirectory(PARAM_OUTPUT_DIR); <ide> final String outputName = parameters.getString(PARAM_OUTPUT_NAME); <ide> final int numBatches = parameters.getPositiveInteger(PARAM_NUM_BATCHES); <ide> <ide> // Get the list of docids and shuffle them. In the case of using a file list, these are just <ide> // paths, not document ids, but they serve the same purpose. <del> final ArrayList<Symbol> docIds = Lists.newArrayList(docIdMap.keySet()); <add> final ImmutableList<Symbol> docIds = shuffledDocIds(randomSeed, docIdMap); <ide> if (numBatches > docIds.size()) { <ide> errorExit("Bad numBatches value: Cannot create more batches than there are input files"); <ide> } <del> Collections.shuffle(docIds, new Random(randomSeed)); <ide> <ide> // Divide into folds <del> final ImmutableList<ImmutableList<Symbol>> folds = <add> final ImmutableList<ImmutableList<Symbol>> testFolds = <ide> CollectionUtils.partitionAlmostEvenly(docIds, numBatches); <ide> <ide> // Write out training/test data for each fold <ide> final ImmutableList.Builder<File> foldLists = ImmutableList.builder(); <ide> final ImmutableList.Builder<File> foldMaps = ImmutableList.builder(); <ide> int batchNum = 0; <del> int totalTest = 0; <del> for (final ImmutableList<Symbol> docIdsForBatch : folds) { <del> final Set<Symbol> testDocIds = ImmutableSet.copyOf(docIdsForBatch); <del> final Set<Symbol> trainDocIds = <del> Sets.difference(ImmutableSet.copyOf(docIds), testDocIds).immutableCopy(); <add> int totalDocs = 0; <add> <add> // Set up train folds <add> final ImmutableList<ImmutableList<Symbol>> trainFolds = <add> createTrainFolds(testFolds, docIds, singleFoldTraining); <add> <add> // Loop over train/test folds <add> Preconditions.checkState(trainFolds.size() == testFolds.size()); <add> for (int i = 0; i < testFolds.size(); i++) { <add> final ImmutableList<Symbol> testDocIds = testFolds.get(i); <add> final ImmutableList<Symbol> trainDocIds = trainFolds.get(i); <add> // Track the total test documents across folds to make sure nothing is lost. <add> totalDocs += testDocIds.size(); <ide> <ide> // Create maps for training and test. These are sorted to avoid arbitrary ordering. <ide> final SortedMap<Symbol, File> trainDocIdMap = <ide> foldLists.add(testOutputFile); <ide> <ide> ++batchNum; <del> totalTest += testDocIdMap.size(); <del> } <del> if(totalTest != docIdMap.size()) { <add> } <add> if (totalDocs != docIdMap.size()) { <ide> errorExit("Test files created are not the same length as the input"); <ide> } <ide> <ide> sourceFiles.getAbsoluteFile(), outputDirectory.getAbsolutePath()); <ide> } <ide> <add> private static ImmutableList<Symbol> shuffledDocIds(final int randomSeed, <add> final ImmutableMap<Symbol, File> docIdMap) { <add> final ArrayList<Symbol> docIds = Lists.newArrayList(docIdMap.keySet()); <add> Collections.shuffle(docIds, new Random(randomSeed)); <add> return ImmutableList.copyOf(docIds); <add> } <add> <add> private static ImmutableList<ImmutableList<Symbol>> createTrainFolds( <add> final ImmutableList<ImmutableList<Symbol>> testFolds, <add> final ImmutableList<Symbol> docIds, final boolean singleFoldTraining) { <add> final ImmutableList.Builder<ImmutableList<Symbol>> ret = ImmutableList.builder(); <add> <add> for (int i = 0; i < testFolds.size(); i++) { <add> final Set<Symbol> testDocIds = ImmutableSet.copyOf(testFolds.get(i)); <add> final ImmutableList<Symbol> trainDocIds = <add> singleFoldTraining <add> // In the single fold training case, use the "next" fold as the training data. We use <add> // the modulus to wrap around the list. <add> ? testFolds.get((i + 1) % testFolds.size()) <add> // In the normal case, just use all the remaining data for training. <add> : Sets.difference(ImmutableSet.copyOf(docIds), testDocIds).immutableCopy().asList(); <add> ret.add(trainDocIds); <add> } <add> return ret.build(); <add> } <add> <ide> private enum FileToSymbolFunction implements Function<File, Symbol> { <ide> INSTANCE; <ide>
Java
apache-2.0
db29cc16507719dde6690a72f95a0319b0584178
0
skmbw/dubbox,skmbw/dubbox,skmbw/dubbox
package com.alibaba.dubbo.common.serialize.support.protostuff; import com.alibaba.dubbo.common.compiler.support.ClassUtils; import io.protostuff.*; import io.protostuff.runtime.RuntimeSchema; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.*; /** * 1、基于Protostuff的序列化和反序列化工具。简化版,主要的改进在于,反序列化时,不需要传递对象了。 * 性能稍差,主要的损失在于反射构造对象。以及一些数组拷贝。<br> * 2、另外方法要成对使用toBytes-fromBytes,serialize-deserialize.<br> * 3、建议使用对象包装集合和map,这样性能会好。<br> * 4、对于List会反序列化成ArrayList,Set会反序列成HashSet<br> * 5、对于Map只支持Map&lt;String, Object&gt;,反序列化成HashMap&lt;String, Object&gt; * @author yinlei * @since 2013-12-12 17:32 */ public class ProtoUtils { private static final Charset UTF8 = Charset.forName("UTF-8"); /** * 将对象序列化成字节数组 * @param object 要被序列化的对象 * @return 序列化后的字节数组 */ @SuppressWarnings("unchecked") public static byte[] toBytes(Object object) { if (object == null) { return null; } byte[] bytes; Class<Object> clazz; if (object instanceof List) { List<Object> list = (List<Object>) object; if (list.size() == 0) { return null; } clazz = (Class<Object>) list.get(0).getClass(); bytes = collectToBytes(clazz, list); return build(bytes, clazz, 1); } else if (object instanceof Set) { Set<Object> set = (Set<Object>) object; if (set.size() == 0) { return null; } clazz = (Class<Object>) set.iterator().next().getClass(); bytes = collectToBytes(clazz, set); return build(bytes, clazz, 2); } else if (object instanceof Map) { Map<String, Object> map = (Map<String, Object>) object; if (map.size() == 0) { return null; } clazz = (Class<Object>) map.values().iterator().next().getClass(); bytes = mapToBytes(clazz, map); return build(bytes, clazz, 3); } else if (object instanceof Number) { bytes = object.toString().getBytes(UTF8); // int byteLength = bytes.length; // byte[] destBytes = new byte[byteLength + 1]; // byte[] destBytes = new byte[1]; int type = 0; if (object instanceof Integer) { // destBytes[0] = 4; type = 4; } else if (object instanceof Long) { // destBytes[0] = 5; type = 5; } else if (object instanceof Double) { // destBytes[0] = 6; type = 6; } else if (object instanceof BigInteger) { // destBytes[0] = 7; type = 7; } else if (object instanceof BigDecimal) { // destBytes[0] = 8; type = 8; } else if (object instanceof Byte) { // destBytes[0] = 9; type = 9; } else if (object instanceof Float) { // destBytes[0] = 10; type = 10; } else if (object instanceof Short) { // destBytes[0] = 11; type = 11; } else { throw new RuntimeException("不支持的数字类型:[" + object.getClass().getName()); } // System.arraycopy(bytes, 0, destBytes, 1, byteLength); // return destBytes; return build(bytes, type); } else if (object instanceof String) { bytes = object.toString().getBytes(UTF8); // int byteLength = bytes.length; // byte[] destBytes = new byte[byteLength + 1]; // destBytes[0] = 12; // System.arraycopy(bytes, 0, destBytes, 1, byteLength); // return destBytes; return build(bytes, 12); } else if (object instanceof Boolean) { byte[] destBytes = new byte[2]; destBytes[0] = 13; if ((Boolean) object) { destBytes[1] = 1; } return destBytes; } else { clazz = (Class<Object>) object.getClass(); Schema<Object> schema = RuntimeSchema.getSchema(clazz); LinkedBuffer buffer = LinkedBuffer.allocate(); bytes = ProtostuffIOUtil.toByteArray(object, schema, buffer); return build(bytes, clazz, 0); } } private static byte[] mapToBytes(Class<Object> clazz, Map<String, Object> map) { Schema<Object> schema = RuntimeSchema.getSchema(clazz); StringMapSchema<Object> collectionSchema = new StringMapSchema<>(schema); LinkedBuffer buffer = LinkedBuffer.allocate(1024); return ProtostuffIOUtil.toByteArray(map, collectionSchema, buffer); } private static byte[] collectToBytes(Class<Object> clazz, Collection<Object> list) { Schema<Object> schema = RuntimeSchema.getSchema(clazz); MessageCollectionSchema<Object> collectionSchema = new MessageCollectionSchema<>(schema); LinkedBuffer buffer = LinkedBuffer.allocate(1024); return ProtostuffIOUtil.toByteArray(list, collectionSchema, buffer); } public static byte[] build(byte[] bytes, Class<Object> clazz, int type) { int byteLength = bytes.length; byte[] nameBytes = clazz.getName().getBytes(); int length = nameBytes.length; byte[] destBytes = new byte[byteLength + length + 5]; destBytes[0] = (byte) type; mergeBytes(length, destBytes, 1, 4); System.arraycopy(nameBytes, 0, destBytes, 5, length); System.arraycopy(bytes, 0, destBytes, length + 5, byteLength); return destBytes; } public static byte[] build(byte[] bytes, int type) { int byteLength = bytes.length; byte[] destBytes = new byte[byteLength + 5]; destBytes[0] = (byte) type; int length = bytes.length; mergeBytes(length, destBytes, 1, 4); System.arraycopy(bytes, 0, destBytes, 5, byteLength); return destBytes; } /** * 将int转为byte数组,字节数组的低位是整型的低字节位 * @param source 要转换的int值 * @param dests 目标数组 * @param from 目标数组起始位置(含) * @param end 目标数组结束位置(含) */ public static void mergeBytes(int source, byte[] dests, int from, int end) { int j = 0; for (int i = from; i <= end; i++) { dests[i] = (byte) (source >> 8 * j & 0xFF); j++; } } /** * 将字节数组反序列化成对象 * @param bytes 字节数组 * @return 反序列化后的对象 */ @SuppressWarnings("unchecked") public static <T> T fromBytes(byte[] bytes) { if (bytes == null || bytes.length == 0) { return null; } int byteLength = bytes.length; int type = bytes[0]; if (4 <= type && type <= 13) { int length; String args = null; if (type != 13) { length = getLength(bytes); args = new String(bytes, 5, length, UTF8); } // 处理基本类型,protobuf处理基本类型慢 switch (type) { // switch比if else快很多 case 4: // String args = new String(bytes, 1, byteLength - 1, UTF8); Integer i = new Integer(args); return (T) i; case 5: // args = new String(bytes, 1, byteLength - 1, UTF8); Long l = new Long(args); return (T) l; case 6: // args = new String(bytes, 1, byteLength - 1, UTF8); Double d = new Double(args); return (T) d; case 7: // args = new String(bytes, 1, byteLength - 1, UTF8); BigInteger bi = new BigInteger(args); return (T) bi; case 8: // args = new String(bytes, 1, byteLength - 1, UTF8); BigDecimal bd = new BigDecimal(args); return (T) bd; case 9: // args = new String(bytes, 1, byteLength - 1, UTF8); Byte b = new Byte(args); return (T) b; case 10: // args = new String(bytes, 1, byteLength - 1, UTF8); Float f = new Float(args); return (T) f; case 11: // args = new String(bytes, 1, byteLength - 1, UTF8); Short s = new Short(args); return (T) s; case 12: // args = new String(bytes, 1, byteLength - 1, UTF8); return (T) args; case 13: byte bb = bytes[1]; if (bb == 1) { return (T) Boolean.TRUE; } else { return (T) Boolean.FALSE; } default: break; } } int length = getLength(bytes); String className = new String(bytes, 5, length, UTF8); Class clazz = ClassUtils.forName(className); Schema schema = RuntimeSchema.getSchema(clazz); int offset = length + 5; int destLength = byteLength - offset; switch (type) { case 0: Object entity = null; try { entity = clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); } ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, entity, schema); return (T) entity; case 1: MessageCollectionSchema<Object> collectionSchema = new MessageCollectionSchema<>(schema); List<Object> list = new ArrayList<>(); ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, list, collectionSchema); return (T) list; case 2: collectionSchema = new MessageCollectionSchema<>(schema); Set<Object> set = new HashSet<>(); ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, set, collectionSchema); return (T) set; case 3: StringMapSchema<Object> stringSchema = new StringMapSchema<>(schema); Map<String, Object> map = new HashMap<>(); ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, map, stringSchema); return (T) map; default: throw new RuntimeException("未知类型protos:" + type); } } public static int getLength(byte[] res) { return (res[1] & 0xff) | ((res[2] << 8) & 0xff00) | ((res[3] << 24) >>> 8) | (res[4] << 24); } }
dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/protostuff/ProtoUtils.java
package com.alibaba.dubbo.common.serialize.support.protostuff; import com.alibaba.dubbo.common.compiler.support.ClassUtils; import io.protostuff.*; import io.protostuff.runtime.RuntimeSchema; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.*; /** * 1、基于Protostuff的序列化和反序列化工具。简化版,主要的改进在于,反序列化时,不需要传递对象了。 * 性能稍差,主要的损失在于反射构造对象。以及一些数组拷贝。<br> * 2、另外方法要成对使用toBytes-fromBytes,serialize-deserialize.<br> * 3、建议使用对象包装集合和map,这样性能会好。<br> * 4、对于List会反序列化成ArrayList,Set会反序列成HashSet<br> * 5、对于Map只支持Map&lt;String, Object&gt;,反序列化成HashMap&lt;String, Object&gt; * @author yinlei * @since 2013-12-12 17:32 */ public class ProtoUtils { private static final Charset UTF8 = Charset.forName("UTF-8"); /** * 将对象序列化成字节数组 * @param object 要被序列化的对象 * @return 序列化后的字节数组 */ @SuppressWarnings("unchecked") public static byte[] toBytes(Object object) { if (object == null) { return null; } byte[] bytes; Class<Object> clazz; if (object instanceof List) { List<Object> list = (List<Object>) object; if (list.size() == 0) { return null; } clazz = (Class<Object>) list.get(0).getClass(); bytes = collectToBytes(clazz, list); return build(bytes, clazz, 1); } else if (object instanceof Set) { Set<Object> set = (Set<Object>) object; if (set.size() == 0) { return null; } clazz = (Class<Object>) set.iterator().next().getClass(); bytes = collectToBytes(clazz, set); return build(bytes, clazz, 2); } else if (object instanceof Map) { Map<String, Object> map = (Map<String, Object>) object; if (map.size() == 0) { return null; } clazz = (Class<Object>) map.values().iterator().next().getClass(); bytes = mapToBytes(clazz, map); return build(bytes, clazz, 3); } else if (object instanceof Number) { bytes = object.toString().getBytes(UTF8); // int byteLength = bytes.length; // byte[] destBytes = new byte[byteLength + 1]; // byte[] destBytes = new byte[1]; int type = 0; if (object instanceof Integer) { // destBytes[0] = 4; type = 4; } else if (object instanceof Long) { // destBytes[0] = 5; type = 5; } else if (object instanceof Double) { // destBytes[0] = 6; type = 6; } else if (object instanceof BigInteger) { // destBytes[0] = 7; type = 7; } else if (object instanceof BigDecimal) { // destBytes[0] = 8; type = 8; } else if (object instanceof Byte) { // destBytes[0] = 9; type = 9; } else if (object instanceof Float) { // destBytes[0] = 10; type = 10; } else if (object instanceof Short) { // destBytes[0] = 11; type = 11; } else { throw new RuntimeException("不支持的数字类型:[" + object.getClass().getName()); } // System.arraycopy(bytes, 0, destBytes, 1, byteLength); // return destBytes; return build(bytes, type); } else if (object instanceof String) { bytes = object.toString().getBytes(UTF8); // int byteLength = bytes.length; // byte[] destBytes = new byte[byteLength + 1]; // destBytes[0] = 12; // System.arraycopy(bytes, 0, destBytes, 1, byteLength); // return destBytes; return build(bytes, 12); } else if (object instanceof Boolean) { byte[] destBytes = new byte[2]; destBytes[0] = 13; if ((Boolean) object) { destBytes[1] = 1; } return destBytes; } else { clazz = (Class<Object>) object.getClass(); Schema<Object> schema = RuntimeSchema.getSchema(clazz); LinkedBuffer buffer = LinkedBuffer.allocate(); bytes = ProtobufIOUtil.toByteArray(object, schema, buffer); return build(bytes, clazz, 0); } } private static byte[] mapToBytes(Class<Object> clazz, Map<String, Object> map) { Schema<Object> schema = RuntimeSchema.getSchema(clazz); StringMapSchema<Object> collectionSchema = new StringMapSchema<>(schema); LinkedBuffer buffer = LinkedBuffer.allocate(1024); return ProtobufIOUtil.toByteArray(map, collectionSchema, buffer); } private static byte[] collectToBytes(Class<Object> clazz, Collection<Object> list) { Schema<Object> schema = RuntimeSchema.getSchema(clazz); MessageCollectionSchema<Object> collectionSchema = new MessageCollectionSchema<>(schema); LinkedBuffer buffer = LinkedBuffer.allocate(1024); return ProtobufIOUtil.toByteArray(list, collectionSchema, buffer); } public static byte[] build(byte[] bytes, Class<Object> clazz, int type) { int byteLength = bytes.length; byte[] nameBytes = clazz.getName().getBytes(); int length = nameBytes.length; byte[] destBytes = new byte[byteLength + length + 5]; destBytes[0] = (byte) type; mergeBytes(length, destBytes, 1, 4); System.arraycopy(nameBytes, 0, destBytes, 5, length); System.arraycopy(bytes, 0, destBytes, length + 5, byteLength); return destBytes; } public static byte[] build(byte[] bytes, int type) { int byteLength = bytes.length; byte[] destBytes = new byte[byteLength + 5]; destBytes[0] = (byte) type; int length = bytes.length; mergeBytes(length, destBytes, 1, 4); System.arraycopy(bytes, 0, destBytes, 5, byteLength); return destBytes; } /** * 将int转为byte数组,字节数组的低位是整型的低字节位 * @param source 要转换的int值 * @param dests 目标数组 * @param from 目标数组起始位置(含) * @param end 目标数组结束位置(含) */ public static void mergeBytes(int source, byte[] dests, int from, int end) { int j = 0; for (int i = from; i <= end; i++) { dests[i] = (byte) (source >> 8 * j & 0xFF); j++; } } /** * 将字节数组反序列化成对象 * @param bytes 字节数组 * @return 反序列化后的对象 */ @SuppressWarnings("unchecked") public static <T> T fromBytes(byte[] bytes) { if (bytes == null || bytes.length == 0) { return null; } int byteLength = bytes.length; int type = bytes[0]; if (4 <= type && type <= 13) { int length; String args = null; if (type != 13) { length = getLength(bytes); args = new String(bytes, 5, length, UTF8); } // 处理基本类型,protobuf处理基本类型慢 switch (type) { // switch比if else快很多 case 4: // String args = new String(bytes, 1, byteLength - 1, UTF8); Integer i = new Integer(args); return (T) i; case 5: // args = new String(bytes, 1, byteLength - 1, UTF8); Long l = new Long(args); return (T) l; case 6: // args = new String(bytes, 1, byteLength - 1, UTF8); Double d = new Double(args); return (T) d; case 7: // args = new String(bytes, 1, byteLength - 1, UTF8); BigInteger bi = new BigInteger(args); return (T) bi; case 8: // args = new String(bytes, 1, byteLength - 1, UTF8); BigDecimal bd = new BigDecimal(args); return (T) bd; case 9: // args = new String(bytes, 1, byteLength - 1, UTF8); Byte b = new Byte(args); return (T) b; case 10: // args = new String(bytes, 1, byteLength - 1, UTF8); Float f = new Float(args); return (T) f; case 11: // args = new String(bytes, 1, byteLength - 1, UTF8); Short s = new Short(args); return (T) s; case 12: // args = new String(bytes, 1, byteLength - 1, UTF8); return (T) args; case 13: byte bb = bytes[1]; if (bb == 1) { return (T) Boolean.TRUE; } else { return (T) Boolean.FALSE; } default: break; } } int length = getLength(bytes); String className = new String(bytes, 5, length, UTF8); Class clazz = ClassUtils.forName(className); Schema schema = RuntimeSchema.getSchema(clazz); int offset = length + 5; int destLength = byteLength - offset; switch (type) { case 0: Object entity = null; try { entity = clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); } ProtobufIOUtil.mergeFrom(bytes, offset, destLength, entity, schema); return (T) entity; case 1: MessageCollectionSchema<Object> collectionSchema = new MessageCollectionSchema<>(schema); List<Object> list = new ArrayList<>(); ProtobufIOUtil.mergeFrom(bytes, offset, destLength, list, collectionSchema); return (T) list; case 2: collectionSchema = new MessageCollectionSchema<>(schema); Set<Object> set = new HashSet<>(); ProtobufIOUtil.mergeFrom(bytes, offset, destLength, set, collectionSchema); return (T) set; case 3: StringMapSchema<Object> stringSchema = new StringMapSchema<>(schema); Map<String, Object> map = new HashMap<>(); ProtobufIOUtil.mergeFrom(bytes, offset, destLength, map, stringSchema); return (T) map; default: throw new RuntimeException("未知类型protos:" + type); } } public static int getLength(byte[] res) { return (res[1] & 0xff) | ((res[2] << 8) & 0xff00) | ((res[3] << 24) >>> 8) | (res[4] << 24); } }
全部使用protostuff的ioutil,可能是两边使用的RuntimeSchema不一样导致的
dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/protostuff/ProtoUtils.java
全部使用protostuff的ioutil,可能是两边使用的RuntimeSchema不一样导致的
<ide><path>ubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/protostuff/ProtoUtils.java <ide> clazz = (Class<Object>) object.getClass(); <ide> Schema<Object> schema = RuntimeSchema.getSchema(clazz); <ide> LinkedBuffer buffer = LinkedBuffer.allocate(); <del> bytes = ProtobufIOUtil.toByteArray(object, schema, buffer); <add> bytes = ProtostuffIOUtil.toByteArray(object, schema, buffer); <ide> <ide> return build(bytes, clazz, 0); <ide> } <ide> Schema<Object> schema = RuntimeSchema.getSchema(clazz); <ide> StringMapSchema<Object> collectionSchema = new StringMapSchema<>(schema); <ide> LinkedBuffer buffer = LinkedBuffer.allocate(1024); <del> return ProtobufIOUtil.toByteArray(map, collectionSchema, buffer); <add> return ProtostuffIOUtil.toByteArray(map, collectionSchema, buffer); <ide> } <ide> <ide> private static byte[] collectToBytes(Class<Object> clazz, Collection<Object> list) { <ide> Schema<Object> schema = RuntimeSchema.getSchema(clazz); <ide> MessageCollectionSchema<Object> collectionSchema = new MessageCollectionSchema<>(schema); <ide> LinkedBuffer buffer = LinkedBuffer.allocate(1024); <del> return ProtobufIOUtil.toByteArray(list, collectionSchema, buffer); <add> return ProtostuffIOUtil.toByteArray(list, collectionSchema, buffer); <ide> } <ide> <ide> public static byte[] build(byte[] bytes, Class<Object> clazz, int type) { <ide> } catch (Exception e) { <ide> e.printStackTrace(); <ide> } <del> ProtobufIOUtil.mergeFrom(bytes, offset, destLength, entity, schema); <add> ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, entity, schema); <ide> return (T) entity; <ide> case 1: <ide> MessageCollectionSchema<Object> collectionSchema = new MessageCollectionSchema<>(schema); <ide> List<Object> list = new ArrayList<>(); <del> ProtobufIOUtil.mergeFrom(bytes, offset, destLength, list, collectionSchema); <add> ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, list, collectionSchema); <ide> return (T) list; <ide> case 2: <ide> collectionSchema = new MessageCollectionSchema<>(schema); <ide> Set<Object> set = new HashSet<>(); <del> ProtobufIOUtil.mergeFrom(bytes, offset, destLength, set, collectionSchema); <add> ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, set, collectionSchema); <ide> return (T) set; <ide> case 3: <ide> StringMapSchema<Object> stringSchema = new StringMapSchema<>(schema); <ide> Map<String, Object> map = new HashMap<>(); <del> ProtobufIOUtil.mergeFrom(bytes, offset, destLength, map, stringSchema); <add> ProtostuffIOUtil.mergeFrom(bytes, offset, destLength, map, stringSchema); <ide> return (T) map; <ide> default: <ide> throw new RuntimeException("未知类型protos:" + type);
Java
apache-2.0
5348d62a58ef3f675074a88af5b2e2bf607660db
0
sanjeewa-malalgoda/carbon-apimgt,fazlan-nazeem/carbon-apimgt,Rajith90/carbon-apimgt,wso2/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharikaGitHub/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamindias/carbon-apimgt,fazlan-nazeem/carbon-apimgt,Rajith90/carbon-apimgt,isharac/carbon-apimgt,chamindias/carbon-apimgt,praminda/carbon-apimgt,chamilaadhi/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,uvindra/carbon-apimgt,fazlan-nazeem/carbon-apimgt,fazlan-nazeem/carbon-apimgt,praminda/carbon-apimgt,jaadds/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,tharindu1st/carbon-apimgt,malinthaprasan/carbon-apimgt,malinthaprasan/carbon-apimgt,malinthaprasan/carbon-apimgt,wso2/carbon-apimgt,Rajith90/carbon-apimgt,tharindu1st/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,ruks/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt,uvindra/carbon-apimgt,Rajith90/carbon-apimgt,prasa7/carbon-apimgt,jaadds/carbon-apimgt,wso2/carbon-apimgt,chamindias/carbon-apimgt,malinthaprasan/carbon-apimgt,isharac/carbon-apimgt,prasa7/carbon-apimgt,praminda/carbon-apimgt,wso2/carbon-apimgt,prasa7/carbon-apimgt,uvindra/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharindu1st/carbon-apimgt,jaadds/carbon-apimgt,bhathiya/carbon-apimgt,jaadds/carbon-apimgt,tharindu1st/carbon-apimgt,bhathiya/carbon-apimgt,ruks/carbon-apimgt,bhathiya/carbon-apimgt,uvindra/carbon-apimgt,tharikaGitHub/carbon-apimgt,ruks/carbon-apimgt,prasa7/carbon-apimgt,chamindias/carbon-apimgt
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.rest.api.publisher.v1.common.mappings; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.parser.ParseException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.carbon.apimgt.api.APIDefinition; import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException; import org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.ExceptionCodes; import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.api.model.APIProductResource; import org.wso2.carbon.apimgt.api.model.APIStatus; import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper; import org.wso2.carbon.apimgt.api.model.Documentation; import org.wso2.carbon.apimgt.api.model.Identifier; import org.wso2.carbon.apimgt.api.model.ResourceFile; import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode; import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportConstants; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException; import org.wso2.carbon.apimgt.impl.importexport.ImportExportConstants; import org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle; import org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycleTransition; import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse; import org.wso2.carbon.apimgt.impl.wsdl.util.SOAPToRESTConstants; import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO; import org.wso2.carbon.core.util.CryptoException; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class ImportUtils { private static final Log log = LogFactory.getLog(ImportUtils.class); private static final String IN = "in"; private static final String OUT = "out"; private static final String SOAPTOREST = "SoapToRest"; /** * This method imports an API. * * @param extractedFolderPath Location of the extracted folder of the API * @param importedApiDTO API DTO of the importing API * (This will not be null when importing dependent APIs with API Products) * @param preserveProvider Decision to keep or replace the provider * @param overwrite Whether to update the API or not * @param tokenScopes Scopes of the token * @throws APIImportExportException If there is an error in importing an API * @@return Imported API */ public static API importApi(String extractedFolderPath, APIDTO importedApiDTO, Boolean preserveProvider, Boolean overwrite, String[] tokenScopes) throws APIManagementException { String userName = RestApiCommonUtil.getLoggedInUsername(); APIDefinitionValidationResponse swaggerDefinitionValidationResponse = null; String graphQLSchema = null; API importedApi = null; String currentStatus; String targetStatus; String lifecycleAction; int tenantId = 0; try { if (importedApiDTO == null) { JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName); importedApiDTO = new Gson().fromJson(jsonObject, APIDTO.class); } // Get API params Definition as JSON and resolve them JsonObject paramsConfigObject = APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath); if (paramsConfigObject != null) { importedApiDTO = APIControllerUtil.injectEnvParamsToAPI(importedApiDTO, paramsConfigObject, extractedFolderPath); } String apiType = importedApiDTO.getType().toString(); APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiDTO.getProvider()); // Validate swagger content except for WebSocket APIs if (!APIConstants.APITransportType.WS.toString().equalsIgnoreCase(apiType) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { swaggerDefinitionValidationResponse = retrieveValidatedSwaggerDefinitionFromArchive( extractedFolderPath); } // Validate the GraphQL schema if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { graphQLSchema = retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath); } // Validate the WSDL of SOAP/SOAPTOREST APIs if (APIConstants.API_TYPE_SOAP.equalsIgnoreCase(apiType) || APIConstants.API_TYPE_SOAPTOREST .equalsIgnoreCase(apiType)) { validateWSDLFromArchive(extractedFolderPath, importedApiDTO); } String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName)); // The status of the importing API should be stored separately to do the lifecycle change at the end targetStatus = importedApiDTO.getLifeCycleStatus(); API targetApi = retrieveApiToOverwrite(importedApiDTO.getName(), importedApiDTO.getVersion(), currentTenantDomain, apiProvider, Boolean.TRUE); // If the overwrite is set to true (which means an update), retrieve the existing API if (Boolean.TRUE.equals(overwrite) && targetApi != null) { log.info("Existing API found, attempting to update it..."); currentStatus = targetApi.getStatus(); // Set the status of imported API to current status of target API when updating importedApiDTO.setLifeCycleStatus(currentStatus); // If the set of operations are not set in the DTO, those should be set explicitly. Otherwise when // updating a "No resources found" error will be thrown. This is not a problem in the UI, since // when updating an API from the UI there is at least one resource (operation) inside the DTO. if (importedApiDTO.getOperations().isEmpty()) { setOperationsToDTO(importedApiDTO, swaggerDefinitionValidationResponse); } importedApi = PublisherCommonUtils .updateApi(targetApi, importedApiDTO, RestApiCommonUtil.getLoggedInUserProvider(), tokenScopes); } else { if (targetApi == null && Boolean.TRUE.equals(overwrite)) { log.info("Cannot find : " + importedApiDTO.getName() + "-" + importedApiDTO.getVersion() + ". Creating it."); } // Initialize to CREATED when import currentStatus = APIStatus.CREATED.toString(); importedApiDTO.setLifeCycleStatus(currentStatus); importedApi = PublisherCommonUtils .addAPIWithGeneratedSwaggerDefinition(importedApiDTO, ImportExportConstants.OAS_VERSION_3, importedApiDTO.getProvider()); } // Retrieving the life cycle action to do the lifecycle state change explicitly later lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider); // Add/update swagger content except for WebSocket APIs if (!APIConstants.APITransportType.WS.toString().equalsIgnoreCase(apiType) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { // Add the validated swagger separately since the UI does the same procedure PublisherCommonUtils.updateSwagger(importedApi.getUUID(), swaggerDefinitionValidationResponse); } // Add the GraphQL schema if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { PublisherCommonUtils.addGraphQLSchema(importedApi, graphQLSchema, apiProvider); } tenantId = APIUtil.getTenantId(RestApiCommonUtil.getLoggedInUsername()); UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService() .getGovernanceSystemRegistry(tenantId); // Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in implementation ApiTypeWrapper apiTypeWrapperWithUpdatedApi = new ApiTypeWrapper(importedApi); addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider); addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider); addAPISequences(extractedFolderPath, importedApi, registry); addAPISpecificSequences(extractedFolderPath, registry, importedApi.getId()); addAPIWsdl(extractedFolderPath, importedApi, apiProvider, registry); addEndpointCertificates(extractedFolderPath, importedApi, apiProvider, tenantId); addSOAPToREST(extractedFolderPath, importedApi, registry); if (apiProvider.isClientCertificateBasedAuthenticationConfigured()) { if (log.isDebugEnabled()) { log.debug("Mutual SSL enabled. Importing client certificates."); } addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApi.getId().getProviderName()); } // Change API lifecycle if state transition is required if (StringUtils.isNotEmpty(lifecycleAction)) { apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus); if (StringUtils.equals(lifecycleAction, APIConstants.LC_PUBLISH_LC_STATE)) { apiProvider.changeAPILCCheckListItems(importedApi.getId(), ImportExportConstants.REFER_REQUIRE_RE_SUBSCRIPTION_CHECK_ITEM, true); } apiProvider.changeLifeCycleStatus(importedApi.getId(), lifecycleAction); } importedApi.setStatus(targetStatus); return importedApi; } catch (CryptoException | IOException e) { throw new APIManagementException( "Error while reading API meta information from path: " + extractedFolderPath, e, ExceptionCodes.ERROR_READING_META_DATA); } catch (FaultGatewaysException e) { throw new APIManagementException("Error while updating API: " + importedApi.getId().getApiName(), e); } catch (RegistryException e) { throw new APIManagementException("Error while getting governance registry for tenant: " + tenantId, e); } catch (APIMgtAuthorizationFailedException e) { throw new APIManagementException("Please enable preserveProvider property for cross tenant API Import.", e, ExceptionCodes.TENANT_MISMATCH); } catch (ParseException e) { throw new APIManagementException("Error while parsing the endpoint configuration of the API", ExceptionCodes.JSON_PARSE_ERROR); } catch (APIManagementException e) { String errorMessage = "Error while importing API: "; if (importedApi != null) { errorMessage += importedApi.getId().getApiName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApi.getId().getVersion(); } throw new APIManagementException(errorMessage + StringUtils.SPACE + e.getMessage(), e); } } /** * This method sets the operations which were retrieved from the swagger definition to the API DTO. * * @param apiDto API DTO * @param response API Validation Response * @throws APIManagementException If an error occurs when retrieving the URI templates */ private static void setOperationsToDTO(APIDTO apiDto, APIDefinitionValidationResponse response) throws APIManagementException { List<URITemplate> uriTemplates = new ArrayList<>(); uriTemplates.addAll(response.getParser().getURITemplates(response.getJsonContent())); List<APIOperationsDTO> apiOperationsDtos = APIMappingUtil.fromURITemplateListToOprationList(uriTemplates); apiDto.setOperations(apiOperationsDtos); } /** * This method retrieves an API to overwrite in the current tenant domain. * * @param apiName API Name * @param apiVersion API Version * @param currentTenantDomain Current tenant domain * @param apiProvider API Provider * @param ignoreAndImport This should be true if the exception should be ignored * @throws APIManagementException If an error occurs when retrieving the API to overwrite */ private static API retrieveApiToOverwrite(String apiName, String apiVersion, String currentTenantDomain, APIProvider apiProvider, Boolean ignoreAndImport) throws APIManagementException { String provider = APIUtil.getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain); APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(provider), apiName, apiVersion); // Checking whether the API exists if (!apiProvider.isAPIAvailable(apiIdentifier)) { if (ignoreAndImport) { return null; } throw new APIMgtResourceNotFoundException( "Error occurred while retrieving the API. API: " + apiName + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiVersion + " not found", ExceptionCodes .from(ExceptionCodes.API_NOT_FOUND, apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion())); } return apiProvider.getAPI(apiIdentifier); } /** * Extract the imported archive to a temporary folder and return the folder path of it * * @param uploadedInputStream Input stream from the REST request * @return Path to the extracted directory * @throws APIImportExportException If an error occurs while creating the directory, transferring files or * extracting the content */ public static String getArchivePathOfExtractedDirectory(InputStream uploadedInputStream) throws APIImportExportException { // Temporary directory is used to create the required folders File importFolder = CommonUtil.createTempDirectory(null); String uploadFileName = ImportExportConstants.UPLOAD_FILE_NAME; String absolutePath = importFolder.getAbsolutePath() + File.separator; CommonUtil.transferFile(uploadedInputStream, uploadFileName, absolutePath); String extractedFolderName = CommonUtil.extractArchive(new File(absolutePath + uploadFileName), absolutePath); return absolutePath + extractedFolderName; } /** * Validate API/API Product configuration (api.yaml/api.json) and return it. * * @param pathToArchive Path to the extracted folder * @param isDefaultProviderAllowed Preserve provider flag value * @param currentUser Username of the current user * @throws APIMgtAuthorizationFailedException If an error occurs while authorizing the provider */ private static JsonElement retrieveValidatedDTOObject(String pathToArchive, Boolean isDefaultProviderAllowed, String currentUser) throws IOException, APIMgtAuthorizationFailedException { // Get API Definition as JSON String jsonContent = getAPIDefinitionAsJson(pathToArchive); String apiVersion; if (jsonContent == null) { throw new IOException("Cannot find API definition. api.json or api.yaml should present"); } // Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA); JsonObject configObject = configElement.getAsJsonObject(); configObject = preProcessEndpointConfig(configObject); // Locate the "provider" within the "id" and set it as the current user String apiName = configObject.get(ImportExportConstants.API_NAME_ELEMENT).getAsString(); // The "version" may not be available for an API Product if (configObject.has(ImportExportConstants.VERSION_ELEMENT)) { apiVersion = configObject.get(ImportExportConstants.VERSION_ELEMENT).getAsString(); } else { apiVersion = ImportExportConstants.DEFAULT_API_PRODUCT_VERSION; } // Remove spaces of API Name/version if present if (apiName != null && apiVersion != null) { configObject.remove(apiName); configObject.addProperty(ImportExportConstants.API_NAME_ELEMENT, apiName.replace(" ", "")); if (configObject.has(ImportExportConstants.VERSION_ELEMENT)) { configObject.remove(ImportExportConstants.VERSION_ELEMENT); configObject.addProperty(ImportExportConstants.VERSION_ELEMENT, apiVersion.replace(" ", "")); } } else { throw new IOException("API name and version must be provided in api.yaml"); } configObject = validatePreserveProvider(configObject, isDefaultProviderAllowed, currentUser); return configObject; } /** * This function will preprocess endpoint config security. * * @param configObject Data object from the API/API Product configuration * @return API config object with pre processed endpoint config */ private static JsonObject preProcessEndpointConfig(JsonObject configObject) { if (configObject.has(ImportExportConstants.ENDPOINT_CONFIG)) { JsonObject endpointConfig = configObject.get(ImportExportConstants.ENDPOINT_CONFIG).getAsJsonObject(); if (endpointConfig.has(APIConstants.ENDPOINT_SECURITY)) { JsonObject endpointSecurity = endpointConfig.get(APIConstants.ENDPOINT_SECURITY).getAsJsonObject(); if (endpointSecurity.has(APIConstants.ENDPOINT_SECURITY_SANDBOX)) { JsonObject endpointSecuritySandbox = endpointSecurity.get(APIConstants.ENDPOINT_SECURITY_SANDBOX) .getAsJsonObject(); if (endpointSecuritySandbox.has(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS)) { String customParameters = endpointSecuritySandbox .get(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS).toString(); endpointSecuritySandbox.remove(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS); endpointSecuritySandbox .addProperty(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS, customParameters); } } if (endpointSecurity.has(APIConstants.ENDPOINT_SECURITY_PRODUCTION)) { JsonObject endpointSecuritySandbox = endpointSecurity.get(APIConstants.ENDPOINT_SECURITY_PRODUCTION) .getAsJsonObject(); if (endpointSecuritySandbox.has(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS)) { String customParameters = endpointSecuritySandbox .get(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS).toString(); endpointSecuritySandbox.remove(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS); endpointSecuritySandbox .addProperty(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS, customParameters); } } } } return configObject; } /** * Validate the provider of the API and modify the provider based on the preserveProvider flag value. * * @param configObject Data object from the API/API Product configuration * @param isDefaultProviderAllowed Preserve provider flag value * @throws APIMgtAuthorizationFailedException If an error occurs while authorizing the provider */ private static JsonObject validatePreserveProvider(JsonObject configObject, Boolean isDefaultProviderAllowed, String currentUser) throws APIMgtAuthorizationFailedException { String prevProvider = configObject.get(ImportExportConstants.PROVIDER_ELEMENT).getAsString(); String prevTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(prevProvider)); String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)); if (isDefaultProviderAllowed) { if (!StringUtils.equals(prevTenantDomain, currentTenantDomain)) { throw new APIMgtAuthorizationFailedException( "Tenant mismatch! Please enable preserveProvider property for cross tenant API Import."); } } else { String prevProviderWithDomain = APIUtil.replaceEmailDomain(prevProvider); String currentUserWithDomain = APIUtil.replaceEmailDomain(currentUser); configObject.remove(ImportExportConstants.PROVIDER_ELEMENT); configObject.addProperty(ImportExportConstants.PROVIDER_ELEMENT, currentUser); if (configObject.get(ImportExportConstants.WSDL_URL) != null) { // If original provider is not preserved, replace provider name in the wsdl URL // with the current user with domain name configObject.addProperty(ImportExportConstants.WSDL_URL, configObject.get(ImportExportConstants.WSDL_URL).getAsString() .replace(prevProviderWithDomain, currentUserWithDomain)); } configObject = setCurrentProviderToContext(configObject, currentTenantDomain, prevTenantDomain); } return configObject; } /** * Replace original provider name from imported API/API Product context with the logged in username * This method is used when "preserveProvider" property is set to false. * * @param jsonObject Imported API or API Product * @param currentDomain Current domain name * @param previousDomain Original domain name */ public static JsonObject setCurrentProviderToContext(JsonObject jsonObject, String currentDomain, String previousDomain) { String context = jsonObject.get(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT).getAsString(); if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(currentDomain) && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(previousDomain)) { jsonObject.remove(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); jsonObject.addProperty(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT, context.replace(APIConstants.TENANT_PREFIX + previousDomain, StringUtils.EMPTY)); } else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(currentDomain) && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(previousDomain)) { jsonObject.remove(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); jsonObject.addProperty(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT, APIConstants.TENANT_PREFIX + currentDomain + context); } else if (!StringUtils.equalsIgnoreCase(currentDomain, previousDomain)) { jsonObject.remove(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); jsonObject.addProperty(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT, context.replace(previousDomain, currentDomain)); } return jsonObject; } /** * Retrieve API Definition as JSON. * * @param pathToArchive Path to API or API Product archive * @throws IOException If an error occurs while reading the file */ public static String getAPIDefinitionAsJson(String pathToArchive) throws IOException { String jsonContent = null; String pathToYamlFile = pathToArchive + ImportExportConstants.YAML_API_FILE_LOCATION; String pathToJsonFile = pathToArchive + ImportExportConstants.JSON_API_FILE_LOCATION; // Load yaml representation first if it is present if (CommonUtil.checkFileExistence(pathToYamlFile)) { if (log.isDebugEnabled()) { log.debug("Found api definition file " + pathToYamlFile); } String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { // load as a json fallback if (log.isDebugEnabled()) { log.debug("Found api definition file " + pathToJsonFile); } jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } return jsonContent; } /** * Validate GraphQL Schema definition from the archive directory and return it. * * @param pathToArchive Path to API archive * @throws APIImportExportException If an error occurs while reading the file */ private static String retrieveValidatedGraphqlSchemaFromArchive(String pathToArchive) throws APIManagementException { File file = new File(pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION); try { String schemaDefinition = loadGraphqlSDLFile(pathToArchive); GraphQLValidationResponseDTO graphQLValidationResponseDTO = PublisherCommonUtils .validateGraphQLSchema(file.getName(), schemaDefinition); if (!graphQLValidationResponseDTO.isIsValid()) { throw new APIManagementException( "Error occurred while importing the API. Invalid GraphQL schema definition found. " + graphQLValidationResponseDTO.getErrorMessage()); } return schemaDefinition; } catch (IOException e) { throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA); } } /** * Validate WSDL definition from the archive directory and return it. * * @param pathToArchive Path to API archive * @throws APIImportExportException If an error due to an invalid WSDL definition */ private static void validateWSDLFromArchive(String pathToArchive, APIDTO apiDto) throws APIManagementException { try { byte[] wsdlDefinition = loadWsdlFile(pathToArchive, apiDto); WSDLValidationResponse wsdlValidationResponse = APIMWSDLReader. getWsdlValidationResponse(APIMWSDLReader.getWSDLProcessor(wsdlDefinition)); if (!wsdlValidationResponse.isValid()) { throw new APIManagementException( "Error occurred while importing the API. Invalid WSDL definition found. " + wsdlValidationResponse.getError()); } } catch (IOException | APIManagementException e) { throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA); } } /** * Load the graphQL schema definition from archive. * * @param pathToArchive Path to archive * @return Schema definition content * @throws IOException When SDL file not found */ private static String loadGraphqlSDLFile(String pathToArchive) throws IOException { if (CommonUtil.checkFileExistence(pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION)) { if (log.isDebugEnabled()) { log.debug("Found graphQL sdl file " + pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION); } return FileUtils.readFileToString( new File(pathToArchive, ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION)); } throw new IOException("Missing graphQL schema definition file. schema.graphql should be present."); } /** * Load the WSDL definition from archive. * * @param pathToArchive Path to archive * @param apiDto API DTO to add * @return Schema definition content * @throws IOException When WSDL file not found */ private static byte[] loadWsdlFile(String pathToArchive, APIDTO apiDto) throws IOException { String wsdlFileName = apiDto.getName() + "-" + apiDto.getVersion() + APIConstants.WSDL_FILE_EXTENSION; String pathToFile = pathToArchive + ImportExportConstants.WSDL_LOCATION + wsdlFileName; if (CommonUtil.checkFileExistence(pathToFile)) { if (log.isDebugEnabled()) { log.debug("Found WSDL file " + pathToFile); } return FileUtils.readFileToByteArray(new File(pathToFile)); } throw new IOException("Missing WSDL file. It should be present."); } /** * Validate swagger definition from the archive directory and return it. * * @param pathToArchive Path to API or API Product archive * @throws APIImportExportException If an error occurs while reading the file */ private static APIDefinitionValidationResponse retrieveValidatedSwaggerDefinitionFromArchive(String pathToArchive) throws APIManagementException { try { String swaggerContent = loadSwaggerFile(pathToArchive); APIDefinitionValidationResponse validationResponse = OASParserUtil .validateAPIDefinition(swaggerContent, Boolean.TRUE); if (!validationResponse.isValid()) { throw new APIManagementException( "Error occurred while importing the API. Invalid Swagger definition found. " + validationResponse.getErrorItems(), ExceptionCodes.ERROR_READING_META_DATA); } return validationResponse; } catch (IOException e) { throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA); } } /** * Load a swagger document from archive. This method lookup for swagger as YAML or JSON. * * @param pathToArchive Path to archive * @return Swagger content as a JSON * @throws IOException When swagger document not found */ public static String loadSwaggerFile(String pathToArchive) throws IOException { if (CommonUtil.checkFileExistence(pathToArchive + ImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION)) { if (log.isDebugEnabled()) { log.debug( "Found swagger file " + pathToArchive + ImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION); } String yamlContent = FileUtils .readFileToString(new File(pathToArchive + ImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION)); return CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil .checkFileExistence(pathToArchive + ImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION)) { if (log.isDebugEnabled()) { log.debug( "Found swagger file " + pathToArchive + ImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION); } return FileUtils .readFileToString(new File(pathToArchive + ImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION)); } throw new IOException("Missing swagger file. Either swagger.json or swagger.yaml should present"); } /** * This method update the API or API Product with the icon to be displayed at the API store. * * @param pathToArchive Location of the extracted folder of the API or API Product * @param apiTypeWrapper The imported API object */ private static void addThumbnailImage(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) { //Adding image icon to the API if there is any File imageFolder = new File(pathToArchive + ImportExportConstants.IMAGE_FILE_LOCATION); File[] fileArray = imageFolder.listFiles(); if (imageFolder.isDirectory() && fileArray != null) { //This loop locates the icon of the API for (File imageFile : fileArray) { if (imageFile != null) { updateWithThumbnail(imageFile, apiTypeWrapper, apiProvider); //the loop is terminated after successfully locating the icon break; } } } } /** * This method update the API Product with the thumbnail image from imported API Product. * * @param imageFile Image file * @param apiTypeWrapper API or API Product to update * @param apiProvider API Provider */ private static void updateWithThumbnail(File imageFile, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) { Identifier identifier = apiTypeWrapper.getId(); String fileName = imageFile.getName(); String mimeType = URLConnection.guessContentTypeFromName(fileName); if (StringUtils.isBlank(mimeType)) { try { // Check whether the icon is in .json format (UI icons are stored as .json) new JsonParser().parse(new FileReader(imageFile)); mimeType = APIConstants.APPLICATION_JSON_MEDIA_TYPE; } catch (JsonParseException e) { // Here the exceptions were handled and logged that may arise when parsing the .json file, // and this will not break the flow of importing the API. // If the .json is wrong or cannot be found the API import process will still be carried out. log.error("Failed to read the thumbnail file. ", e); } catch (FileNotFoundException e) { log.error("Failed to find the thumbnail file. ", e); } } try (FileInputStream inputStream = new FileInputStream(imageFile.getAbsolutePath())) { ResourceFile apiImage = new ResourceFile(inputStream, mimeType); String thumbPath = APIUtil.getIconPath(identifier); String thumbnailUrl = apiProvider.addResourceFile(identifier, thumbPath, apiImage); apiTypeWrapper.setThumbnailUrl(APIUtil.prependTenantPrefix(thumbnailUrl, identifier.getProviderName())); APIUtil.setResourcePermissions(identifier.getProviderName(), null, null, thumbPath); if (apiTypeWrapper.isAPIProduct()) { apiProvider.updateAPIProduct(apiTypeWrapper.getApiProduct()); } else { apiProvider.updateAPI(apiTypeWrapper.getApi()); } } catch (FaultGatewaysException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to update API/API Product after adding icon. ", e); } catch (APIManagementException e) { log.error("Failed to add icon to the API/API Product: " + identifier.getName(), e); } catch (FileNotFoundException e) { log.error("Icon for API/API Product: " + identifier.getName() + " is not found.", e); } catch (IOException e) { log.error("Failed to import icon for API/API Product:" + identifier.getName()); } } /** * This method adds the documents to the imported API or API Product. * * @param pathToArchive Location of the extracted folder of the API or API Product * @param apiTypeWrapper Imported API or API Product */ private static void addDocumentation(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) { String jsonContent = null; Identifier identifier = apiTypeWrapper.getId(); String docDirectoryPath = pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY; File documentsFolder = new File(docDirectoryPath); File[] fileArray = documentsFolder.listFiles(); try { // Remove all documents associated with the API before update List<Documentation> documents = apiProvider.getAllDocumentation(identifier); if (documents != null) { for (Documentation documentation : documents) { apiProvider.removeDocumentation(identifier, documentation.getId()); } } if (documentsFolder.isDirectory() && fileArray != null) { //This loop locates the documents inside each repo for (File documentFile : fileArray) { String folderName = documentFile.getName(); String individualDocumentFilePath = docDirectoryPath + File.separator + folderName; String pathToYamlFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.YAML_EXTENSION; String pathToJsonFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.JSON_EXTENSION; // Load document file if exists if (CommonUtil.checkFileExistence(pathToYamlFile)) { if (log.isDebugEnabled()) { log.debug("Found documents definition file " + pathToYamlFile); } String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { //load as a json fallback if (log.isDebugEnabled()) { log.debug("Found documents definition file " + pathToJsonFile); } jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject() .get(APIConstants.DATA); DocumentDTO documentDTO = new Gson().fromJson(configElement.getAsJsonObject(), DocumentDTO.class); // Add the documentation DTO Documentation documentation = apiTypeWrapper.isAPIProduct() ? PublisherCommonUtils .addDocumentationToAPI(documentDTO, apiTypeWrapper.getApiProduct().getUuid()) : PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApi().getUUID()); // Adding doc content String docSourceType = documentation.getSourceType().toString(); boolean docContentExists = Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(docSourceType) || Documentation.DocumentSourceType.MARKDOWN.toString() .equalsIgnoreCase(docSourceType); if (docContentExists) { try (FileInputStream inputStream = new FileInputStream( individualDocumentFilePath + File.separator + folderName)) { String inlineContent = IOUtils.toString(inputStream, ImportExportConstants.CHARSET); if (!apiTypeWrapper.isAPIProduct()) { apiProvider.addDocumentationContent(apiTypeWrapper.getApi(), documentation.getName(), inlineContent); } else { apiProvider.addProductDocumentationContent(apiTypeWrapper.getApiProduct(), documentation.getName(), inlineContent); } } } else if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(docSourceType)) { String filePath = documentation.getFilePath(); try (FileInputStream inputStream = new FileInputStream( individualDocumentFilePath + File.separator + filePath)) { String docExtension = FilenameUtils.getExtension( pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY + File.separator + filePath); ResourceFile apiDocument = new ResourceFile(inputStream, docExtension); String visibleRolesList = apiTypeWrapper.getVisibleRoles(); String[] visibleRoles = new String[0]; if (visibleRolesList != null) { visibleRoles = visibleRolesList.split(","); } String filePathDoc = APIUtil.getDocumentationFilePath(identifier, filePath); APIUtil.setResourcePermissions(apiTypeWrapper.getId().getProviderName(), apiTypeWrapper.getVisibility(), visibleRoles, filePathDoc); documentation.setFilePath( apiProvider.addResourceFile(apiTypeWrapper.getId(), filePathDoc, apiDocument)); if (!apiTypeWrapper.isAPIProduct()) { apiProvider.updateDocumentation(apiTypeWrapper.getApi().getId(), documentation); } else { apiProvider.updateDocumentation(apiTypeWrapper.getApiProduct().getId(), documentation); } } catch (FileNotFoundException e) { //this error is logged and ignored because documents are optional in an API log.error("Failed to locate the document files of the API/API Product: " + apiTypeWrapper .getId().getName(), e); continue; } } } } } catch (FileNotFoundException e) { //this error is logged and ignored because documents are optional in an API log.error("Failed to locate the document files of the API/API Product: " + identifier.getName(), e); } catch (APIManagementException | IOException e) { //this error is logged and ignored because documents are optional in an API log.error("Failed to add Documentations to API/API Product: " + identifier.getName(), e); } } /** * This method adds API sequences to the imported API. If the sequence is a newly defined one, it is added. * * @param pathToArchive Location of the extracted folder of the API * @param importedApi The imported API object * @param registry Registry */ private static void addAPISequences(String pathToArchive, API importedApi, Registry registry) { String inSequenceFileName = importedApi.getInSequence() + APIConstants.XML_EXTENSION; String inSequenceFileLocation = pathToArchive + ImportExportConstants.IN_SEQUENCE_LOCATION + inSequenceFileName; String regResourcePath; //Adding in-sequence, if any if (CommonUtil.checkFileExistence(inSequenceFileLocation)) { regResourcePath = APIConstants.API_CUSTOM_INSEQUENCE_LOCATION + inSequenceFileName; addSequenceToRegistry(false, registry, inSequenceFileLocation, regResourcePath); } String outSequenceFileName = importedApi.getOutSequence() + APIConstants.XML_EXTENSION; String outSequenceFileLocation = pathToArchive + ImportExportConstants.OUT_SEQUENCE_LOCATION + outSequenceFileName; //Adding out-sequence, if any if (CommonUtil.checkFileExistence(outSequenceFileLocation)) { regResourcePath = APIConstants.API_CUSTOM_OUTSEQUENCE_LOCATION + outSequenceFileName; addSequenceToRegistry(false, registry, outSequenceFileLocation, regResourcePath); } String faultSequenceFileName = importedApi.getFaultSequence() + APIConstants.XML_EXTENSION; String faultSequenceFileLocation = pathToArchive + ImportExportConstants.FAULT_SEQUENCE_LOCATION + faultSequenceFileName; //Adding fault-sequence, if any if (CommonUtil.checkFileExistence(faultSequenceFileLocation)) { regResourcePath = APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION + faultSequenceFileName; addSequenceToRegistry(false, registry, faultSequenceFileLocation, regResourcePath); } } /** * This method adds API Specific sequences added through the Publisher to the imported API. If the specific * sequence already exists, it is updated. * * @param pathToArchive Location of the extracted folder of the API * @param registry Registry * @param apiIdentifier API Identifier */ private static void addAPISpecificSequences(String pathToArchive, Registry registry, APIIdentifier apiIdentifier) { String apiResourcePath = APIUtil.getAPIPath(apiIdentifier); // Getting registry API base path out of apiResourcePath apiResourcePath = apiResourcePath.substring(0, apiResourcePath.lastIndexOf("/")); String sequencesDirectoryPath = pathToArchive + File.separator + APIImportExportConstants.SEQUENCES_RESOURCE; // Add multiple custom sequences to registry for each type in/out/fault addCustomSequencesToRegistry(sequencesDirectoryPath, apiResourcePath, registry, ImportExportConstants.IN_SEQUENCE_PREFIX); addCustomSequencesToRegistry(sequencesDirectoryPath, apiResourcePath, registry, ImportExportConstants.OUT_SEQUENCE_PREFIX); addCustomSequencesToRegistry(sequencesDirectoryPath, apiResourcePath, registry, ImportExportConstants.FAULT_SEQUENCE_PREFIX); } /** * @param sequencesDirectoryPath Location of the sequences directory inside the extracted folder of the API * @param apiResourcePath API resource path in the registry * @param registry Registry * @param type Sequence type (in/out/fault) */ private static void addCustomSequencesToRegistry(String sequencesDirectoryPath, String apiResourcePath, Registry registry, String type) { String apiSpecificSequenceFilePath = sequencesDirectoryPath + File.separator + type + ImportExportConstants.SEQUENCE_LOCATION_POSTFIX + File.separator + ImportExportConstants.CUSTOM_TYPE; if (CommonUtil.checkFileExistence(apiSpecificSequenceFilePath)) { File apiSpecificSequencesDirectory = new File(apiSpecificSequenceFilePath); File[] apiSpecificSequencesDirectoryListing = apiSpecificSequencesDirectory.listFiles(); if (apiSpecificSequencesDirectoryListing != null) { for (File apiSpecificSequence : apiSpecificSequencesDirectoryListing) { String individualSequenceLocation = apiSpecificSequenceFilePath + File.separator + apiSpecificSequence.getName(); // Constructing mediation resource path String mediationResourcePath = apiResourcePath + RegistryConstants.PATH_SEPARATOR + type + RegistryConstants.PATH_SEPARATOR + apiSpecificSequence.getName(); addSequenceToRegistry(true, registry, individualSequenceLocation, mediationResourcePath); } } } } /** * This method adds the sequence files to the registry. This updates the API specific sequences if already exists. * * @param isAPISpecific Whether the adding sequence is API specific * @param registry The registry instance * @param sequenceFileLocation Location of the sequence file * @param regResourcePath Resource path in the registry */ private static void addSequenceToRegistry(Boolean isAPISpecific, Registry registry, String sequenceFileLocation, String regResourcePath) { try { if (registry.resourceExists(regResourcePath) && !isAPISpecific) { if (log.isDebugEnabled()) { log.debug("Sequence already exists in registry path: " + regResourcePath); } } else { if (log.isDebugEnabled()) { log.debug("Adding Sequence to the registry path : " + regResourcePath); } File sequenceFile = new File(sequenceFileLocation); try (InputStream seqStream = new FileInputStream(sequenceFile);) { byte[] inSeqData = IOUtils.toByteArray(seqStream); Resource inSeqResource = registry.newResource(); inSeqResource.setContent(inSeqData); registry.put(regResourcePath, inSeqResource); } } } catch (RegistryException e) { //this is logged and ignored because sequences are optional log.error("Failed to add sequences into the registry : " + regResourcePath, e); } catch (IOException e) { //this is logged and ignored because sequences are optional log.error("I/O error while writing sequence data to the registry : " + regResourcePath, e); } } /** * This method adds the WSDL to the registry, if there is a WSDL associated with the API. * * @param pathToArchive Location of the extracted folder of the API * @param importedApi The imported API object * @param apiProvider API Provider * @param registry Registry */ private static void addAPIWsdl(String pathToArchive, API importedApi, APIProvider apiProvider, Registry registry) { String wsdlFileName = importedApi.getId().getApiName() + "-" + importedApi.getId().getVersion() + APIConstants.WSDL_FILE_EXTENSION; String wsdlPath = pathToArchive + ImportExportConstants.WSDL_LOCATION + wsdlFileName; if (CommonUtil.checkFileExistence(wsdlPath)) { try { URL wsdlFileUrl = new File(wsdlPath).toURI().toURL(); importedApi.setWsdlUrl(wsdlFileUrl.toString()); APIUtil.createWSDL(registry, importedApi); apiProvider.updateAPI(importedApi); } catch (MalformedURLException e) { // this exception is logged and ignored since WSDL is optional for an API log.error("Error in getting WSDL URL. ", e); } catch (org.wso2.carbon.registry.core.exceptions.RegistryException e) { // this exception is logged and ignored since WSDL is optional for an API log.error("Error in putting the WSDL resource to registry. ", e); } catch (APIManagementException e) { // this exception is logged and ignored since WSDL is optional for an API log.error("Error in creating the WSDL resource in the registry. ", e); } catch (FaultGatewaysException e) { // This is logged and process is continued because WSDL is optional for an API log.error("Failed to update API after adding WSDL. ", e); } } } /** * This method import endpoint certificate. * * @param pathToArchive location of the extracted folder of the API * @param importedApi the imported API object * @throws APIImportExportException If an error occurs while importing endpoint certificates from file */ private static void addEndpointCertificates(String pathToArchive, API importedApi, APIProvider apiProvider, int tenantId) throws APIManagementException { String jsonContent = null; String pathToEndpointsCertificatesDirectory = pathToArchive + File.separator + ImportExportConstants.ENDPOINT_CERTIFICATES_DIRECTORY; String pathToYamlFile = pathToEndpointsCertificatesDirectory + ImportExportConstants.ENDPOINTS_CERTIFICATE_FILE + ImportExportConstants.YAML_EXTENSION; String pathToJsonFile = pathToEndpointsCertificatesDirectory + ImportExportConstants.ENDPOINTS_CERTIFICATE_FILE + ImportExportConstants.JSON_EXTENSION; try { // try loading file as YAML if (CommonUtil.checkFileExistence(pathToYamlFile)) { if (log.isDebugEnabled()) { log.debug("Found certificate file " + pathToYamlFile); } String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { // load as a json fallback if (log.isDebugEnabled()) { log.debug("Found certificate file " + pathToJsonFile); } jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } if (jsonContent == null) { log.debug("No certificate file found to be added, skipping certificate import."); return; } JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA); JsonArray certificates = addFileContentToCertificates(configElement.getAsJsonArray(), pathToEndpointsCertificatesDirectory); for (JsonElement certificate : certificates) { updateAPIWithCertificate(certificate, apiProvider, importedApi, tenantId); } } catch (IOException e) { throw new APIManagementException("Error in reading certificates file", e); } } /** * Add the certificate content to the object. * * @param certificates Certificates array * @param pathToCertificatesDirectory File path to the certificates directory * @throws IOException If an error occurs while retrieving the certificate content from the file */ private static JsonArray addFileContentToCertificates(JsonArray certificates, String pathToCertificatesDirectory) throws IOException { JsonArray modifiedCertificates = new JsonArray(); for (JsonElement certificate : certificates) { JsonObject certificateObject = certificate.getAsJsonObject(); String certificateFileName = certificateObject.get(ImportExportConstants.CERTIFICATE_FILE).getAsString(); // Get the content of the certificate file from the relevant certificate file inside the certificates // directory and add it to the certificate String certificateContent = getFileContentOfCertificate(certificateFileName, pathToCertificatesDirectory); if (certificateObject.has(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY)) { certificateObject.remove(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY); } certificateObject.addProperty(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY, certificateContent); modifiedCertificates.add(certificateObject); } return modifiedCertificates; } /** * Get the file content of a certificate in the Client-certificate directory. * * @param certificateFileName Certificate file name * @param pathToCertificatesDirectory Path to client certificates directory * @return content of the certificate */ private static String getFileContentOfCertificate(String certificateFileName, String pathToCertificatesDirectory) throws IOException { String certificateContent = null; File certificatesDirectory = new File(pathToCertificatesDirectory); File[] certificatesDirectoryListing = certificatesDirectory.listFiles(); // Iterate the Endpoints certificates directory to get the relevant cert file if (certificatesDirectoryListing != null) { for (File endpointsCertificate : certificatesDirectoryListing) { if (StringUtils.equals(certificateFileName, endpointsCertificate.getName())) { certificateContent = FileUtils.readFileToString( new File(pathToCertificatesDirectory + File.separator + certificateFileName)); certificateContent = StringUtils.substringBetween(certificateContent, APIConstants.BEGIN_CERTIFICATE_STRING, APIConstants.END_CERTIFICATE_STRING); } } } return certificateContent; } /** * Update API with the certificate. * If certificate alias already exists for tenant in database, certificate content will be * updated in trust store. If cert alias does not exits in database for that tenant, add the certificate to * publisher and gateway nodes. In such case if alias already exits in the trust store, update the certificate * content for that alias. * * @param certificate Certificate JSON element * @param apiProvider API Provider * @param importedApi API to import * @param tenantId Tenant Id */ private static void updateAPIWithCertificate(JsonElement certificate, APIProvider apiProvider, API importedApi, int tenantId) throws APIManagementException { String certificateFileName = certificate.getAsJsonObject().get(ImportExportConstants.CERTIFICATE_FILE) .getAsString(); String certificateContent = certificate.getAsJsonObject() .get(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY).getAsString(); if (certificateContent == null) { throw new APIManagementException("Certificate " + certificateFileName + "is null"); } String alias = certificate.getAsJsonObject().get(ImportExportConstants.ALIAS_JSON_KEY).getAsString(); String endpoint = certificate.getAsJsonObject().get(ImportExportConstants.ENDPOINT_JSON_KEY).getAsString(); try { if (apiProvider.isCertificatePresent(tenantId, alias) || ( ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == (apiProvider .addCertificate(APIUtil.replaceEmailDomainBack(importedApi.getId().getProviderName()), certificateContent, alias, endpoint)))) { apiProvider.updateCertificate(certificateContent, alias); } } catch (APIManagementException e) { log.error("Error while importing certificate endpoint [" + endpoint + " ]" + "alias [" + alias + " ] tenant user [" + APIUtil.replaceEmailDomainBack(importedApi.getId().getProviderName()) + "]", e); } } /** * Import client certificates for Mutual SSL related configuration * * @param pathToArchive Location of the extracted folder of the API * @param apiProvider API Provider * @throws APIImportExportException */ private static void addClientCertificates(String pathToArchive, APIProvider apiProvider, Boolean preserveProvider, String provider) throws APIManagementException { String jsonContent = null; String pathToClientCertificatesDirectory = pathToArchive + File.separator + ImportExportConstants.CLIENT_CERTIFICATES_DIRECTORY; String pathToYamlFile = pathToClientCertificatesDirectory + ImportExportConstants.CLIENT_CERTIFICATE_FILE + ImportExportConstants.YAML_EXTENSION; String pathToJsonFile = pathToClientCertificatesDirectory + ImportExportConstants.CLIENT_CERTIFICATE_FILE + ImportExportConstants.JSON_EXTENSION; try { // try loading file as YAML if (CommonUtil.checkFileExistence(pathToYamlFile)) { log.debug("Found client certificate file " + pathToYamlFile); String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { // load as a json fallback log.debug("Found client certificate file " + pathToJsonFile); jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } if (jsonContent == null) { log.debug("No client certificate file found to be added, skipping"); return; } JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA); JsonArray modifiedCertificatesData = addFileContentToCertificates(configElement.getAsJsonArray(), pathToClientCertificatesDirectory); Gson gson = new Gson(); List<ClientCertificateDTO> certificateMetadataDTOS = gson .fromJson(modifiedCertificatesData, new TypeToken<ArrayList<ClientCertificateDTO>>() { }.getType()); for (ClientCertificateDTO certDTO : certificateMetadataDTOS) { APIIdentifier apiIdentifier = !preserveProvider ? new APIIdentifier(provider, certDTO.getApiIdentifier().getApiName(), certDTO.getApiIdentifier().getVersion()) : certDTO.getApiIdentifier(); apiProvider.addClientCertificate(APIUtil.replaceEmailDomainBack(provider), apiIdentifier, certDTO.getCertificate(), certDTO.getAlias(), certDTO.getTierName()); } } catch (IOException e) { throw new APIManagementException("Error in reading certificates file", e); } catch (APIManagementException e) { throw new APIManagementException("Error while importing client certificate", e); } } /** * This method adds API sequences to the imported API. If the sequence is a newly defined one, it is added. * * @param pathToArchive Location of the extracted folder of the API * @param importedApi API * @param registry Registry * @throws APIImportExportException If an error occurs while importing mediation logic */ private static void addSOAPToREST(String pathToArchive, API importedApi, Registry registry) throws APIManagementException { String inFlowFileLocation = pathToArchive + File.separator + SOAPTOREST + File.separator + IN; String outFlowFileLocation = pathToArchive + File.separator + SOAPTOREST + File.separator + OUT; // Adding in-sequence, if any if (CommonUtil.checkFileExistence(inFlowFileLocation)) { APIIdentifier apiId = importedApi.getId(); String soapToRestLocationIn = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_IN_RESOURCE; String soapToRestLocationOut = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_OUT_RESOURCE; try { // Import inflow mediation logic Path inFlowDirectory = Paths.get(inFlowFileLocation); importMediationLogic(inFlowDirectory, registry, soapToRestLocationIn); // Import outflow mediation logic Path outFlowDirectory = Paths.get(outFlowFileLocation); importMediationLogic(outFlowDirectory, registry, soapToRestLocationOut); } catch (DirectoryIteratorException e) { throw new APIManagementException("Error in importing SOAP to REST mediation logic", e); } } } /** * Method created to add inflow and outflow mediation logic * * @param flowDirectory Inflow and outflow directory * @param registry Registry * @param soapToRestLocation Folder location * @throws APIImportExportException If an error occurs while importing/storing SOAP to REST mediation logic */ private static void importMediationLogic(Path flowDirectory, Registry registry, String soapToRestLocation) throws APIManagementException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(flowDirectory)) { for (Path file : stream) { String fileName = file.getFileName().toString(); String method = ""; if (fileName.split(".xml").length != 0) { method = fileName.split(".xml")[0].substring(file.getFileName().toString().lastIndexOf("_") + 1); } try (InputStream inputFlowStream = new FileInputStream(file.toFile())) { byte[] inSeqData = IOUtils.toByteArray(inputFlowStream); Resource inSeqResource = (Resource) registry.newResource(); inSeqResource.setContent(inSeqData); inSeqResource.addProperty(SOAPToRESTConstants.METHOD, method); inSeqResource.setMediaType("text/xml"); registry.put(soapToRestLocation + RegistryConstants.PATH_SEPARATOR + file.getFileName(), inSeqResource); } } } catch (IOException | DirectoryIteratorException e) { throw new APIManagementException("Error in importing SOAP to REST mediation logic", e); } catch (RegistryException e) { throw new APIManagementException("Error in storing imported SOAP to REST mediation logic", e); } } /** * This method returns the lifecycle action which can be used to transit from currentStatus to targetStatus. * * @param tenantDomain Tenant domain * @param currentStatus Current status to do status transition * @param targetStatus Target status to do status transition * @return Lifecycle action or null if target is not reachable * @throws APIImportExportException If getting lifecycle action failed */ public static String getLifeCycleAction(String tenantDomain, String currentStatus, String targetStatus, APIProvider provider) throws APIManagementException { // No need to change the lifecycle if both the statuses are same if (StringUtils.equalsIgnoreCase(currentStatus, targetStatus)) { return null; } LifeCycle lifeCycle = new LifeCycle(); // Parse DOM of APILifeCycle try { String data = provider.getLifecycleConfiguration(tenantDomain); DocumentBuilderFactory factory = APIUtil.getSecuredDocumentBuilder(); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); Document doc = builder.parse(inputStream); Element root = doc.getDocumentElement(); // Get all nodes with state NodeList states = root.getElementsByTagName("state"); int nStates = states.getLength(); for (int i = 0; i < nStates; i++) { Node node = states.item(i); Node id = node.getAttributes().getNamedItem("id"); if (id != null && !id.getNodeValue().isEmpty()) { LifeCycleTransition lifeCycleTransition = new LifeCycleTransition(); NodeList transitions = node.getChildNodes(); int nTransitions = transitions.getLength(); for (int j = 0; j < nTransitions; j++) { Node transition = transitions.item(j); // Add transitions if (ImportExportConstants.NODE_TRANSITION.equals(transition.getNodeName())) { Node target = transition.getAttributes().getNamedItem("target"); Node action = transition.getAttributes().getNamedItem("event"); if (target != null && action != null) { lifeCycleTransition .addTransition(target.getNodeValue().toLowerCase(), action.getNodeValue()); } } } lifeCycle.addLifeCycleState(id.getNodeValue().toLowerCase(), lifeCycleTransition); } } } catch (ParserConfigurationException | SAXException e) { throw new APIManagementException("Error parsing APILifeCycle for tenant: " + tenantDomain, e); } catch (UnsupportedEncodingException e) { throw new APIManagementException( "Error parsing unsupported encoding for APILifeCycle in tenant: " + tenantDomain, e); } catch (IOException e) { throw new APIManagementException("Error reading APILifeCycle for tenant: " + tenantDomain, e); } // Retrieve lifecycle action LifeCycleTransition transition = lifeCycle.getTransition(currentStatus.toLowerCase()); if (transition != null) { return transition.getAction(targetStatus.toLowerCase()); } return null; } /** * This method imports an API Product. * * @param extractedFolderPath Location of the extracted folder of the API Product * @param preserveProvider Decision to keep or replace the provider * @param overwriteAPIProduct Whether to update the API Product or not * @param overwriteAPIs Whether to update the dependent APIs or not * @param importAPIs Whether to import the dependent APIs or not * @throws APIImportExportException If there is an error in importing an API */ public static APIProduct importApiProduct(String extractedFolderPath, Boolean preserveProvider, Boolean overwriteAPIProduct, Boolean overwriteAPIs, Boolean importAPIs, String[] tokenScopes) throws APIManagementException { String userName = RestApiCommonUtil.getLoggedInUsername(); String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName)); APIProduct importedApiProduct = null; try { JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName); APIProductDTO importedApiProductDTO = new Gson().fromJson(jsonObject, APIProductDTO.class); APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiProductDTO.getProvider()); // Check whether the API resources are valid checkAPIProductResourcesValid(extractedFolderPath, userName, apiProvider, importedApiProductDTO, preserveProvider); if (importAPIs) { // Import dependent APIs only if it is asked (the UUIDs of the dependent APIs will be updated here if a // fresh import happens) importedApiProductDTO = importDependentAPIs(extractedFolderPath, userName, preserveProvider, apiProvider, overwriteAPIs, importedApiProductDTO, tokenScopes); } else { // Even we do not import APIs, the UUIDs of the dependent APIs should be updated if the APIs are already in the APIM importedApiProductDTO = updateDependentApiUuids(importedApiProductDTO, apiProvider, currentTenantDomain); } APIProduct targetApiProduct = retrieveApiProductToOverwrite(importedApiProductDTO.getName(), currentTenantDomain, apiProvider, Boolean.TRUE); // If the overwrite is set to true (which means an update), retrieve the existing API if (Boolean.TRUE.equals(overwriteAPIProduct) && targetApiProduct != null) { log.info("Existing API Product found, attempting to update it..."); importedApiProduct = PublisherCommonUtils.updateApiProduct(targetApiProduct, importedApiProductDTO, RestApiCommonUtil.getLoggedInUserProvider(), userName); } else { if (targetApiProduct == null && Boolean.TRUE.equals(overwriteAPIProduct)) { log.info("Cannot find : " + importedApiProductDTO.getName() + ". Creating it."); } importedApiProduct = PublisherCommonUtils .addAPIProductWithGeneratedSwaggerDefinition(importedApiProductDTO, importedApiProductDTO.getProvider(), importedApiProductDTO.getProvider()); } // Add/update swagger of API Product importedApiProduct = updateApiProductSwagger(extractedFolderPath, importedApiProduct, apiProvider); // Since Image, documents and client certificates are optional, exceptions are logged and ignored in implementation ApiTypeWrapper apiTypeWrapperWithUpdatedApiProduct = new ApiTypeWrapper(importedApiProduct); addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider); addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider); if (apiProvider.isClientCertificateBasedAuthenticationConfigured()) { if (log.isDebugEnabled()) { log.debug("Mutual SSL enabled. Importing client certificates."); } addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApiProduct.getId().getProviderName()); } return importedApiProduct; } catch (IOException e) { // Error is logged and APIImportExportException is thrown because adding API Product and swagger are // mandatory steps throw new APIManagementException( "Error while reading API Product meta information from path: " + extractedFolderPath, e); } catch (FaultGatewaysException e) { throw new APIManagementException( "Error while updating API Product: " + importedApiProduct.getId().getName(), e); } catch (APIManagementException e) { String errorMessage = "Error while importing API Product: "; if (importedApiProduct != null) { errorMessage += importedApiProduct.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApiProduct.getId().getVersion(); } throw new APIManagementException(errorMessage + " " + e.getMessage(), e); } } /** * This method checks whether the resources in the API Product are valid. * * @param path Location of the extracted folder of the API Product * @param currentUser The current logged in user * @param apiProvider API provider * @param apiProductDto API Product DTO * @throws IOException If there is an error while reading an API file * @throws APIManagementException If failed to get the API Provider of an API, * or failed when checking the existence of an API */ private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider) throws IOException, APIManagementException { // Get dependent APIs in the API Product List<ProductAPIDTO> apis = apiProductDto.getApis(); String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY; File apisDirectory = new File(apisDirectoryPath); File[] apisDirectoryListing = apisDirectory.listFiles(); if (apisDirectoryListing != null) { for (File apiDirectory : apisDirectoryListing) { String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory .getName(); JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser); APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class); String apiName = apiDto.getName(); String apiVersion = apiDto.getVersion(); String swaggerContent = loadSwaggerFile(apiDirectoryPath); APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent); Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent); for (ProductAPIDTO apiFromProduct : apis) { if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils .equals(apiFromProduct.getVersion(), apiVersion)) { List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources( apiFromProduct.getOperations(), apiUriTemplates); // If there are still product resources to be checked (which were not able to find in the // dependent APIs inside the directory) check whether those are already inside APIM if (!invalidApiOperations.isEmpty()) { // Get the provider of the API if the API is in current user's tenant domain. API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE); invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates()); } // invalidApiOperations is not empty means, at least one of the resources of the API // Product does not have corresponding API resources neither inside the importing directory nor // inside the APIM if (!invalidApiOperations.isEmpty()) { throw new APIMgtResourceNotFoundException( "Cannot find API resources for some API Product resources."); } } } } } } /** * This method filter the invalid resources in the API Product by matching with the URI Templates of a particular * dependent API. * * @param apiProductOperations Operations from API Product * @param apiUriTemplates URI Templates of the dependent API * (either inside the import directory or already inside the APIM) * @return Invalid API operations */ private static List<APIOperationsDTO> filterInvalidProductResources(List<APIOperationsDTO> apiProductOperations, Set<URITemplate> apiUriTemplates) { List<APIOperationsDTO> apiOperations = new ArrayList<>(apiProductOperations); for (URITemplate apiUriTemplate : apiUriTemplates) { // If the URI Template is Available in the API, remove it from the list since it is valid apiOperations.removeIf( apiOperation -> StringUtils.equals(apiOperation.getVerb(), apiUriTemplate.getHTTPVerb()) && StringUtils.equals(apiOperation.getTarget(), apiUriTemplate.getUriTemplate())); } return apiOperations; } /** * This method imports dependent APIs of the API Product. * * @param path Location of the extracted folder of the API Product * @param currentUser The current logged in user * @param isDefaultProviderAllowed Decision to keep or replace the provider * @param apiProvider API provider * @param overwriteAPIs Whether to overwrite the APIs or not * @param apiProductDto API Product DTO * @param tokenScopes Scopes of the token * @return Modified API Product DTO with the correct API UUIDs * @throws IOException If there is an error while reading an API file * @throws APIImportExportException If there is an error in importing an API * @throws APIManagementException If failed to get the API Provider of an API, or failed when * checking the existence of an API */ private static APIProductDTO importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed, APIProvider apiProvider, Boolean overwriteAPIs, APIProductDTO apiProductDto, String[] tokenScopes) throws IOException, APIManagementException { String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY; File apisDirectory = new File(apisDirectoryPath); File[] apisDirectoryListing = apisDirectory.listFiles(); if (apisDirectoryListing != null) { for (File apiDirectory : apisDirectoryListing) { String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory .getName(); JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, isDefaultProviderAllowed, currentUser); APIDTO apiDtoToImport = new Gson().fromJson(jsonObject, APIDTO.class); API importedApi = null; String apiName = apiDtoToImport.getName(); String apiVersion = apiDtoToImport.getVersion(); if (isDefaultProviderAllowed) { APIIdentifier apiIdentifier = new APIIdentifier( APIUtil.replaceEmailDomain(apiDtoToImport.getProvider()), apiName, apiVersion); // Checking whether the API exists if (apiProvider.isAPIAvailable(apiIdentifier)) { // If the API is already imported, update it if the overWriteAPIs flag is specified, // otherwise do not update the API. (Just skip it) if (Boolean.TRUE.equals(overwriteAPIs)) { importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.TRUE, tokenScopes); } } else { // If the API is not already imported, import it importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.FALSE, tokenScopes); } } else { // Retrieve the current tenant domain of the logged in user String currentTenantDomain = MultitenantUtils .getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)); // Get the provider of the API if the API is in current user's tenant domain. String apiProviderInCurrentTenantDomain = APIUtil .getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain); if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) { // If there is no API in the current tenant domain (which means the provider name is blank) // then the API should be imported freshly importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.FALSE, tokenScopes); } else { // If there is an API already in the current tenant domain, update it if the overWriteAPIs flag is specified, // otherwise do not import/update the API. (Just skip it) if (Boolean.TRUE.equals(overwriteAPIs)) { importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.TRUE, tokenScopes); } } } if (importedApi == null) { // Retrieve the API from the environment (This happens when you have not specified // the overwrite flag, so that we should retrieve the API from inside) importedApi = retrieveApiToOverwrite(apiDtoToImport.getName(), apiDtoToImport.getVersion(), MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE); } updateApiUuidInApiProduct(apiProductDto, importedApi); } } else { String msg = "No dependent APIs supplied. Continuing ..."; log.info(msg); } return apiProductDto; } /** * This method updates the UUID of the dependent API in an API Product. * * @param apiProductDto API Product DTO * @param importedApi Imported API */ private static APIProductDTO updateApiUuidInApiProduct(APIProductDTO apiProductDto, API importedApi) { APIIdentifier importedApiIdentifier = importedApi.getId(); List<ProductAPIDTO> apis = apiProductDto.getApis(); for (ProductAPIDTO api : apis) { if (StringUtils.equals(api.getName(), importedApiIdentifier.getName()) && StringUtils .equals(api.getVersion(), importedApiIdentifier.getVersion())) { api.setApiId(importedApi.getUUID()); break; } } return apiProductDto; } /** * This method updates the UUIDs of dependent APIs, when the dependent APIs are already inside APIM. * * @param importedApiProductDtO API Product DTO * @param apiProvider API Provider * @param currentTenantDomain Current tenant domain * @throws APIManagementException If failed failed when checking the existence of an API */ private static APIProductDTO updateDependentApiUuids(APIProductDTO importedApiProductDtO, APIProvider apiProvider, String currentTenantDomain) throws APIManagementException { List<ProductAPIDTO> apis = importedApiProductDtO.getApis(); for (ProductAPIDTO api : apis) { API targetApi = retrieveApiToOverwrite(api.getName(), api.getVersion(), currentTenantDomain, apiProvider, Boolean.FALSE); if (targetApi != null) { api.setApiId(targetApi.getUUID()); } } return importedApiProductDtO; } /** * This method retrieves an API Product to overwrite in the current tenant domain. * * @param apiProductName API Product Name * @param currentTenantDomain Current tenant domain * @param apiProvider API Provider * @param ignoreAndImport This should be true if the exception should be ignored * @throws APIManagementException If an error occurs when retrieving the API to overwrite */ private static APIProduct retrieveApiProductToOverwrite(String apiProductName, String currentTenantDomain, APIProvider apiProvider, Boolean ignoreAndImport) throws APIManagementException { String provider = APIUtil.getAPIProviderFromAPINameVersionTenant(apiProductName, ImportExportConstants.DEFAULT_API_PRODUCT_VERSION, currentTenantDomain); APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), apiProductName, ImportExportConstants.DEFAULT_API_PRODUCT_VERSION); // Checking whether the API exists if (!apiProvider.isAPIProductAvailable(apiProductIdentifier)) { if (ignoreAndImport) { return null; } throw new APIMgtResourceNotFoundException( "Error occurred while retrieving the API Product. API Product: " + apiProductName + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + ImportExportConstants.DEFAULT_API_PRODUCT_VERSION + " not found"); } return apiProvider.getAPIProduct(apiProductIdentifier); } /** * This method updates the API Product and the swagger with the correct scopes. * * @param pathToArchive Path to the extracted folder * @param importedApiProduct Imported API Product * @param apiProvider API Provider * @throws APIManagementException If an error occurs when retrieving the parser and updating the API Product * @throws FaultGatewaysException If an error occurs when updating the API to overwrite * @throws IOException If an error occurs when loading the swagger file */ private static APIProduct updateApiProductSwagger(String pathToArchive, APIProduct importedApiProduct, APIProvider apiProvider) throws APIManagementException, FaultGatewaysException, IOException { String swaggerContent = loadSwaggerFile(pathToArchive); // Load required properties from swagger to the API Product APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent); Set<Scope> scopes = apiDefinition.getScopes(swaggerContent); importedApiProduct.setScopes(scopes); // This is required to make scopes get effected Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider .updateAPIProduct(importedApiProduct); apiProvider.updateAPIProductSwagger(apiToProductResourceMapping, importedApiProduct); return importedApiProduct; } }
components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/common/mappings/ImportUtils.java
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.rest.api.publisher.v1.common.mappings; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.parser.ParseException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.carbon.apimgt.api.APIDefinition; import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException; import org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.ExceptionCodes; import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.api.model.APIProductResource; import org.wso2.carbon.apimgt.api.model.APIStatus; import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper; import org.wso2.carbon.apimgt.api.model.Documentation; import org.wso2.carbon.apimgt.api.model.Identifier; import org.wso2.carbon.apimgt.api.model.ResourceFile; import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode; import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportConstants; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException; import org.wso2.carbon.apimgt.impl.importexport.ImportExportConstants; import org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle; import org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycleTransition; import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse; import org.wso2.carbon.apimgt.impl.wsdl.util.SOAPToRESTConstants; import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseDTO; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO; import org.wso2.carbon.core.util.CryptoException; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class ImportUtils { private static final Log log = LogFactory.getLog(ImportUtils.class); private static final String IN = "in"; private static final String OUT = "out"; private static final String SOAPTOREST = "SoapToRest"; /** * This method imports an API. * * @param extractedFolderPath Location of the extracted folder of the API * @param importedApiDTO API DTO of the importing API * (This will not be null when importing dependent APIs with API Products) * @param preserveProvider Decision to keep or replace the provider * @param overwrite Whether to update the API or not * @param tokenScopes Scopes of the token * @throws APIImportExportException If there is an error in importing an API * @@return Imported API */ public static API importApi(String extractedFolderPath, APIDTO importedApiDTO, Boolean preserveProvider, Boolean overwrite, String[] tokenScopes) throws APIManagementException { String userName = RestApiCommonUtil.getLoggedInUsername(); APIDefinitionValidationResponse swaggerDefinitionValidationResponse = null; String graphQLSchema = null; API importedApi = null; String currentStatus; String targetStatus; String lifecycleAction; int tenantId = 0; try { if (importedApiDTO == null) { JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName); importedApiDTO = new Gson().fromJson(jsonObject, APIDTO.class); } // Get API params Definition as JSON and resolve them JsonObject paramsConfigObject = APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath); if (paramsConfigObject != null) { importedApiDTO = APIControllerUtil.injectEnvParamsToAPI(importedApiDTO, paramsConfigObject, extractedFolderPath); } String apiType = importedApiDTO.getType().toString(); APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiDTO.getProvider()); // Validate swagger content except for WebSocket APIs if (!APIConstants.APITransportType.WS.toString().equalsIgnoreCase(apiType) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { swaggerDefinitionValidationResponse = retrieveValidatedSwaggerDefinitionFromArchive( extractedFolderPath); } // Validate the GraphQL schema if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { graphQLSchema = retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath); } // Validate the WSDL of SOAP/SOAPTOREST APIs if (APIConstants.API_TYPE_SOAP.equalsIgnoreCase(apiType) || APIConstants.API_TYPE_SOAPTOREST .equalsIgnoreCase(apiType)) { validateWSDLFromArchive(extractedFolderPath, importedApiDTO); } String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName)); // The status of the importing API should be stored separately to do the lifecycle change at the end targetStatus = importedApiDTO.getLifeCycleStatus(); API targetApi = retrieveApiToOverwrite(importedApiDTO.getName(), importedApiDTO.getVersion(), currentTenantDomain, apiProvider, Boolean.TRUE); // If the overwrite is set to true (which means an update), retrieve the existing API if (Boolean.TRUE.equals(overwrite) && targetApi != null) { log.info("Existing API found, attempting to update it..."); currentStatus = targetApi.getStatus(); // Set the status of imported API to current status of target API when updating importedApiDTO.setLifeCycleStatus(currentStatus); // If the set of operations are not set in the DTO, those should be set explicitly. Otherwise when // updating a "No resources found" error will be thrown. This is not a problem in the UI, since // when updating an API from the UI there is at least one resource (operation) inside the DTO. if (importedApiDTO.getOperations().isEmpty()) { setOperationsToDTO(importedApiDTO, swaggerDefinitionValidationResponse); } importedApi = PublisherCommonUtils .updateApi(targetApi, importedApiDTO, RestApiCommonUtil.getLoggedInUserProvider(), tokenScopes); } else { if (targetApi == null && Boolean.TRUE.equals(overwrite)) { log.info("Cannot find : " + importedApiDTO.getName() + "-" + importedApiDTO.getVersion() + ". Creating it."); } // Initialize to CREATED when import currentStatus = APIStatus.CREATED.toString(); importedApiDTO.setLifeCycleStatus(currentStatus); importedApi = PublisherCommonUtils .addAPIWithGeneratedSwaggerDefinition(importedApiDTO, ImportExportConstants.OAS_VERSION_3, importedApiDTO.getProvider()); } // Retrieving the life cycle action to do the lifecycle state change explicitly later lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider); // Add/update swagger content except for WebSocket APIs if (!APIConstants.APITransportType.WS.toString().equalsIgnoreCase(apiType) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { // Add the validated swagger separately since the UI does the same procedure PublisherCommonUtils.updateSwagger(importedApi.getUUID(), swaggerDefinitionValidationResponse); } // Add the GraphQL schema if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) { PublisherCommonUtils.addGraphQLSchema(importedApi, graphQLSchema, apiProvider); } tenantId = APIUtil.getTenantId(RestApiCommonUtil.getLoggedInUsername()); UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService() .getGovernanceSystemRegistry(tenantId); // Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in implementation ApiTypeWrapper apiTypeWrapperWithUpdatedApi = new ApiTypeWrapper(importedApi); addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider); addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider); addAPISequences(extractedFolderPath, importedApi, registry); addAPISpecificSequences(extractedFolderPath, registry, importedApi.getId()); addAPIWsdl(extractedFolderPath, importedApi, apiProvider, registry); addEndpointCertificates(extractedFolderPath, importedApi, apiProvider, tenantId); addSOAPToREST(extractedFolderPath, importedApi, registry); if (apiProvider.isClientCertificateBasedAuthenticationConfigured()) { if (log.isDebugEnabled()) { log.debug("Mutual SSL enabled. Importing client certificates."); } addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApi.getId().getProviderName()); } // Change API lifecycle if state transition is required if (StringUtils.isNotEmpty(lifecycleAction)) { apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus); if (StringUtils.equals(lifecycleAction, APIConstants.LC_PUBLISH_LC_STATE)) { apiProvider.changeAPILCCheckListItems(importedApi.getId(), ImportExportConstants.REFER_REQUIRE_RE_SUBSCRIPTION_CHECK_ITEM, true); } apiProvider.changeLifeCycleStatus(importedApi.getId(), lifecycleAction); } importedApi.setStatus(targetStatus); return importedApi; } catch (CryptoException | IOException e) { throw new APIManagementException( "Error while reading API meta information from path: " + extractedFolderPath, e, ExceptionCodes.ERROR_READING_META_DATA); } catch (FaultGatewaysException e) { throw new APIManagementException("Error while updating API: " + importedApi.getId().getApiName(), e); } catch (RegistryException e) { throw new APIManagementException("Error while getting governance registry for tenant: " + tenantId, e); } catch (APIMgtAuthorizationFailedException e) { throw new APIManagementException("Please enable preserveProvider property for cross tenant API Import.", e, ExceptionCodes.TENANT_MISMATCH); } catch (ParseException e) { throw new APIManagementException("Error while parsing the endpoint configuration of the API", ExceptionCodes.JSON_PARSE_ERROR); } catch (APIManagementException e) { String errorMessage = "Error while importing API: "; if (importedApi != null) { errorMessage += importedApi.getId().getApiName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApi.getId().getVersion(); } throw new APIManagementException(errorMessage + StringUtils.SPACE + e.getMessage(), e); } } /** * This method sets the operations which were retrieved from the swagger definition to the API DTO. * * @param apiDto API DTO * @param response API Validation Response * @throws APIManagementException If an error occurs when retrieving the URI templates */ private static void setOperationsToDTO(APIDTO apiDto, APIDefinitionValidationResponse response) throws APIManagementException { List<URITemplate> uriTemplates = new ArrayList<>(); uriTemplates.addAll(response.getParser().getURITemplates(response.getJsonContent())); List<APIOperationsDTO> apiOperationsDtos =APIMappingUtil.fromURITemplateListToOprationList(uriTemplates); apiDto.setOperations(apiOperationsDtos); } /** * This method retrieves an API to overwrite in the current tenant domain. * * @param apiName API Name * @param apiVersion API Version * @param currentTenantDomain Current tenant domain * @param apiProvider API Provider * @param ignoreAndImport This should be true if the exception should be ignored * @throws APIManagementException If an error occurs when retrieving the API to overwrite */ private static API retrieveApiToOverwrite(String apiName, String apiVersion, String currentTenantDomain, APIProvider apiProvider, Boolean ignoreAndImport) throws APIManagementException { String provider = APIUtil.getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain); APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(provider), apiName, apiVersion); // Checking whether the API exists if (!apiProvider.isAPIAvailable(apiIdentifier)) { if (ignoreAndImport) { return null; } throw new APIMgtResourceNotFoundException( "Error occurred while retrieving the API. API: " + apiName + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiVersion + " not found", ExceptionCodes .from(ExceptionCodes.API_NOT_FOUND, apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion())); } return apiProvider.getAPI(apiIdentifier); } /** * Extract the imported archive to a temporary folder and return the folder path of it * * @param uploadedInputStream Input stream from the REST request * @return Path to the extracted directory * @throws APIImportExportException If an error occurs while creating the directory, transferring files or * extracting the content */ public static String getArchivePathOfExtractedDirectory(InputStream uploadedInputStream) throws APIImportExportException { // Temporary directory is used to create the required folders File importFolder = CommonUtil.createTempDirectory(null); String uploadFileName = ImportExportConstants.UPLOAD_FILE_NAME; String absolutePath = importFolder.getAbsolutePath() + File.separator; CommonUtil.transferFile(uploadedInputStream, uploadFileName, absolutePath); String extractedFolderName = CommonUtil.extractArchive(new File(absolutePath + uploadFileName), absolutePath); return absolutePath + extractedFolderName; } /** * Validate API/API Product configuration (api.yaml/api.json) and return it. * * @param pathToArchive Path to the extracted folder * @param isDefaultProviderAllowed Preserve provider flag value * @param currentUser Username of the current user * @throws APIMgtAuthorizationFailedException If an error occurs while authorizing the provider */ private static JsonElement retrieveValidatedDTOObject(String pathToArchive, Boolean isDefaultProviderAllowed, String currentUser) throws IOException, APIMgtAuthorizationFailedException { // Get API Definition as JSON String jsonContent = getAPIDefinitionAsJson(pathToArchive); String apiVersion; if (jsonContent == null) { throw new IOException("Cannot find API definition. api.json or api.yaml should present"); } // Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA); JsonObject configObject = configElement.getAsJsonObject(); configObject = preProcessEndpointConfig(configObject); // Locate the "provider" within the "id" and set it as the current user String apiName = configObject.get(ImportExportConstants.API_NAME_ELEMENT).getAsString(); // The "version" may not be available for an API Product if (configObject.has(ImportExportConstants.VERSION_ELEMENT)) { apiVersion = configObject.get(ImportExportConstants.VERSION_ELEMENT).getAsString(); } else { apiVersion = ImportExportConstants.DEFAULT_API_PRODUCT_VERSION; } // Remove spaces of API Name/version if present if (apiName != null && apiVersion != null) { configObject.remove(apiName); configObject.addProperty(ImportExportConstants.API_NAME_ELEMENT, apiName.replace(" ", "")); if (configObject.has(ImportExportConstants.VERSION_ELEMENT)) { configObject.remove(ImportExportConstants.VERSION_ELEMENT); configObject.addProperty(ImportExportConstants.VERSION_ELEMENT, apiVersion.replace(" ", "")); } } else { throw new IOException("API name and version must be provided in api.yaml"); } configObject = validatePreserveProvider(configObject, isDefaultProviderAllowed, currentUser); return configObject; } /** * This function will preprocess endpoint config security. * * @param configObject Data object from the API/API Product configuration * @return API config object with pre processed endpoint config */ private static JsonObject preProcessEndpointConfig(JsonObject configObject) { if (configObject.has(ImportExportConstants.ENDPOINT_CONFIG)) { JsonObject endpointConfig = configObject.get(ImportExportConstants.ENDPOINT_CONFIG).getAsJsonObject(); if (endpointConfig.has(APIConstants.ENDPOINT_SECURITY)) { JsonObject endpointSecurity = endpointConfig.get(APIConstants.ENDPOINT_SECURITY).getAsJsonObject(); if (endpointSecurity.has(APIConstants.ENDPOINT_SECURITY_SANDBOX)) { JsonObject endpointSecuritySandbox = endpointSecurity.get(APIConstants.ENDPOINT_SECURITY_SANDBOX) .getAsJsonObject(); if (endpointSecuritySandbox.has(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS)) { String customParameters = endpointSecuritySandbox .get(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS).toString(); endpointSecuritySandbox.remove(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS); endpointSecuritySandbox .addProperty(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS, customParameters); } } if (endpointSecurity.has(APIConstants.ENDPOINT_SECURITY_PRODUCTION)) { JsonObject endpointSecuritySandbox = endpointSecurity.get(APIConstants.ENDPOINT_SECURITY_PRODUCTION) .getAsJsonObject(); if (endpointSecuritySandbox.has(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS)) { String customParameters = endpointSecuritySandbox .get(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS).toString(); endpointSecuritySandbox.remove(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS); endpointSecuritySandbox .addProperty(ImportExportConstants.ENDPOINT_CUSTOM_PARAMETERS, customParameters); } } } } return configObject; } /** * Validate the provider of the API and modify the provider based on the preserveProvider flag value. * * @param configObject Data object from the API/API Product configuration * @param isDefaultProviderAllowed Preserve provider flag value * @throws APIMgtAuthorizationFailedException If an error occurs while authorizing the provider */ private static JsonObject validatePreserveProvider(JsonObject configObject, Boolean isDefaultProviderAllowed, String currentUser) throws APIMgtAuthorizationFailedException { String prevProvider = configObject.get(ImportExportConstants.PROVIDER_ELEMENT).getAsString(); String prevTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(prevProvider)); String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)); if (isDefaultProviderAllowed) { if (!StringUtils.equals(prevTenantDomain, currentTenantDomain)) { throw new APIMgtAuthorizationFailedException( "Tenant mismatch! Please enable preserveProvider property for cross tenant API Import."); } } else { String prevProviderWithDomain = APIUtil.replaceEmailDomain(prevProvider); String currentUserWithDomain = APIUtil.replaceEmailDomain(currentUser); configObject.remove(ImportExportConstants.PROVIDER_ELEMENT); configObject.addProperty(ImportExportConstants.PROVIDER_ELEMENT, currentUser); if (configObject.get(ImportExportConstants.WSDL_URL) != null) { // If original provider is not preserved, replace provider name in the wsdl URL // with the current user with domain name configObject.addProperty(ImportExportConstants.WSDL_URL, configObject.get(ImportExportConstants.WSDL_URL).getAsString() .replace(prevProviderWithDomain, currentUserWithDomain)); } configObject = setCurrentProviderToContext(configObject, currentTenantDomain, prevTenantDomain); } return configObject; } /** * Replace original provider name from imported API/API Product context with the logged in username * This method is used when "preserveProvider" property is set to false. * * @param jsonObject Imported API or API Product * @param currentDomain Current domain name * @param previousDomain Original domain name */ public static JsonObject setCurrentProviderToContext(JsonObject jsonObject, String currentDomain, String previousDomain) { String context = jsonObject.get(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT).getAsString(); if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(currentDomain) && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(previousDomain)) { jsonObject.remove(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); jsonObject.addProperty(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT, context.replace(APIConstants.TENANT_PREFIX + previousDomain, StringUtils.EMPTY)); } else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(currentDomain) && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(previousDomain)) { jsonObject.remove(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); jsonObject.addProperty(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT, APIConstants.TENANT_PREFIX + currentDomain + context); } else if (!StringUtils.equalsIgnoreCase(currentDomain, previousDomain)) { jsonObject.remove(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); jsonObject.addProperty(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT, context.replace(previousDomain, currentDomain)); } return jsonObject; } /** * Retrieve API Definition as JSON. * * @param pathToArchive Path to API or API Product archive * @throws IOException If an error occurs while reading the file */ public static String getAPIDefinitionAsJson(String pathToArchive) throws IOException { String jsonContent = null; String pathToYamlFile = pathToArchive + ImportExportConstants.YAML_API_FILE_LOCATION; String pathToJsonFile = pathToArchive + ImportExportConstants.JSON_API_FILE_LOCATION; // Load yaml representation first if it is present if (CommonUtil.checkFileExistence(pathToYamlFile)) { if (log.isDebugEnabled()) { log.debug("Found api definition file " + pathToYamlFile); } String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { // load as a json fallback if (log.isDebugEnabled()) { log.debug("Found api definition file " + pathToJsonFile); } jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } return jsonContent; } /** * Validate GraphQL Schema definition from the archive directory and return it. * * @param pathToArchive Path to API archive * @throws APIImportExportException If an error occurs while reading the file */ private static String retrieveValidatedGraphqlSchemaFromArchive(String pathToArchive) throws APIManagementException { File file = new File(pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION); try { String schemaDefinition = loadGraphqlSDLFile(pathToArchive); GraphQLValidationResponseDTO graphQLValidationResponseDTO = PublisherCommonUtils .validateGraphQLSchema(file.getName(), schemaDefinition); if (!graphQLValidationResponseDTO.isIsValid()) { throw new APIManagementException( "Error occurred while importing the API. Invalid GraphQL schema definition found. " + graphQLValidationResponseDTO.getErrorMessage()); } return schemaDefinition; } catch (IOException e) { throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA); } } /** * Validate WSDL definition from the archive directory and return it. * * @param pathToArchive Path to API archive * @throws APIImportExportException If an error due to an invalid WSDL definition */ private static void validateWSDLFromArchive(String pathToArchive, APIDTO apiDto) throws APIManagementException { try { byte[] wsdlDefinition = loadWsdlFile(pathToArchive, apiDto); WSDLValidationResponse wsdlValidationResponse = APIMWSDLReader. getWsdlValidationResponse(APIMWSDLReader.getWSDLProcessor(wsdlDefinition)); if (!wsdlValidationResponse.isValid()) { throw new APIManagementException( "Error occurred while importing the API. Invalid WSDL definition found. " + wsdlValidationResponse.getError()); } } catch (IOException | APIManagementException e) { throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA); } } /** * Load the graphQL schema definition from archive. * * @param pathToArchive Path to archive * @return Schema definition content * @throws IOException When SDL file not found */ private static String loadGraphqlSDLFile(String pathToArchive) throws IOException { if (CommonUtil.checkFileExistence(pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION)) { if (log.isDebugEnabled()) { log.debug("Found graphQL sdl file " + pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION); } return FileUtils.readFileToString( new File(pathToArchive, ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION)); } throw new IOException("Missing graphQL schema definition file. schema.graphql should be present."); } /** * Load the WSDL definition from archive. * * @param pathToArchive Path to archive * @param apiDto API DTO to add * @return Schema definition content * @throws IOException When WSDL file not found */ private static byte[] loadWsdlFile(String pathToArchive, APIDTO apiDto) throws IOException { String wsdlFileName = apiDto.getName() + "-" + apiDto.getVersion() + APIConstants.WSDL_FILE_EXTENSION; String pathToFile = pathToArchive + ImportExportConstants.WSDL_LOCATION + wsdlFileName; if (CommonUtil.checkFileExistence(pathToFile)) { if (log.isDebugEnabled()) { log.debug("Found WSDL file " + pathToFile); } return FileUtils.readFileToByteArray(new File(pathToFile)); } throw new IOException("Missing WSDL file. It should be present."); } /** * Validate swagger definition from the archive directory and return it. * * @param pathToArchive Path to API or API Product archive * @throws APIImportExportException If an error occurs while reading the file */ private static APIDefinitionValidationResponse retrieveValidatedSwaggerDefinitionFromArchive(String pathToArchive) throws APIManagementException { try { String swaggerContent = loadSwaggerFile(pathToArchive); APIDefinitionValidationResponse validationResponse = OASParserUtil .validateAPIDefinition(swaggerContent, Boolean.TRUE); if (!validationResponse.isValid()) { throw new APIManagementException( "Error occurred while importing the API. Invalid Swagger definition found. " + validationResponse.getErrorItems(), ExceptionCodes.ERROR_READING_META_DATA); } return validationResponse; } catch (IOException e) { throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA); } } /** * Load a swagger document from archive. This method lookup for swagger as YAML or JSON. * * @param pathToArchive Path to archive * @return Swagger content as a JSON * @throws IOException When swagger document not found */ public static String loadSwaggerFile(String pathToArchive) throws IOException { if (CommonUtil.checkFileExistence(pathToArchive + ImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION)) { if (log.isDebugEnabled()) { log.debug( "Found swagger file " + pathToArchive + ImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION); } String yamlContent = FileUtils .readFileToString(new File(pathToArchive + ImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION)); return CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil .checkFileExistence(pathToArchive + ImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION)) { if (log.isDebugEnabled()) { log.debug( "Found swagger file " + pathToArchive + ImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION); } return FileUtils .readFileToString(new File(pathToArchive + ImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION)); } throw new IOException("Missing swagger file. Either swagger.json or swagger.yaml should present"); } /** * This method update the API or API Product with the icon to be displayed at the API store. * * @param pathToArchive Location of the extracted folder of the API or API Product * @param apiTypeWrapper The imported API object */ private static void addThumbnailImage(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) { //Adding image icon to the API if there is any File imageFolder = new File(pathToArchive + ImportExportConstants.IMAGE_FILE_LOCATION); File[] fileArray = imageFolder.listFiles(); if (imageFolder.isDirectory() && fileArray != null) { //This loop locates the icon of the API for (File imageFile : fileArray) { if (imageFile != null) { updateWithThumbnail(imageFile, apiTypeWrapper, apiProvider); //the loop is terminated after successfully locating the icon break; } } } } /** * This method update the API Product with the thumbnail image from imported API Product. * * @param imageFile Image file * @param apiTypeWrapper API or API Product to update * @param apiProvider API Provider */ private static void updateWithThumbnail(File imageFile, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) { Identifier identifier = apiTypeWrapper.getId(); String fileName = imageFile.getName(); String mimeType = URLConnection.guessContentTypeFromName(fileName); if (StringUtils.isBlank(mimeType)) { try { // Check whether the icon is in .json format (UI icons are stored as .json) new JsonParser().parse(new FileReader(imageFile)); mimeType = APIConstants.APPLICATION_JSON_MEDIA_TYPE; } catch (JsonParseException e) { // Here the exceptions were handled and logged that may arise when parsing the .json file, // and this will not break the flow of importing the API. // If the .json is wrong or cannot be found the API import process will still be carried out. log.error("Failed to read the thumbnail file. ", e); } catch (FileNotFoundException e) { log.error("Failed to find the thumbnail file. ", e); } } try (FileInputStream inputStream = new FileInputStream(imageFile.getAbsolutePath())) { ResourceFile apiImage = new ResourceFile(inputStream, mimeType); String thumbPath = APIUtil.getIconPath(identifier); String thumbnailUrl = apiProvider.addResourceFile(identifier, thumbPath, apiImage); apiTypeWrapper.setThumbnailUrl(APIUtil.prependTenantPrefix(thumbnailUrl, identifier.getProviderName())); APIUtil.setResourcePermissions(identifier.getProviderName(), null, null, thumbPath); if (apiTypeWrapper.isAPIProduct()) { apiProvider.updateAPIProduct(apiTypeWrapper.getApiProduct()); } else { apiProvider.updateAPI(apiTypeWrapper.getApi()); } } catch (FaultGatewaysException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to update API/API Product after adding icon. ", e); } catch (APIManagementException e) { log.error("Failed to add icon to the API/API Product: " + identifier.getName(), e); } catch (FileNotFoundException e) { log.error("Icon for API/API Product: " + identifier.getName() + " is not found.", e); } catch (IOException e) { log.error("Failed to import icon for API/API Product:" + identifier.getName()); } } /** * This method adds the documents to the imported API or API Product. * * @param pathToArchive Location of the extracted folder of the API or API Product * @param apiTypeWrapper Imported API or API Product */ private static void addDocumentation(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) { String jsonContent = null; Identifier identifier = apiTypeWrapper.getId(); String docDirectoryPath = pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY; File documentsFolder = new File(docDirectoryPath); File[] fileArray = documentsFolder.listFiles(); try { // Remove all documents associated with the API before update List<Documentation> documents = apiProvider.getAllDocumentation(identifier); if (documents != null) { for (Documentation documentation : documents) { apiProvider.removeDocumentation(identifier, documentation.getId()); } } if (documentsFolder.isDirectory() && fileArray != null) { //This loop locates the documents inside each repo for (File documentFile : fileArray) { String folderName = documentFile.getName(); String individualDocumentFilePath = docDirectoryPath + File.separator + folderName; String pathToYamlFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.YAML_EXTENSION; String pathToJsonFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.JSON_EXTENSION; // Load document file if exists if (CommonUtil.checkFileExistence(pathToYamlFile)) { if (log.isDebugEnabled()) { log.debug("Found documents definition file " + pathToYamlFile); } String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { //load as a json fallback if (log.isDebugEnabled()) { log.debug("Found documents definition file " + pathToJsonFile); } jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject() .get(APIConstants.DATA); DocumentDTO documentDTO = new Gson().fromJson(configElement.getAsJsonObject(), DocumentDTO.class); // Add the documentation DTO Documentation documentation = apiTypeWrapper.isAPIProduct() ? PublisherCommonUtils .addDocumentationToAPI(documentDTO, apiTypeWrapper.getApiProduct().getUuid()) : PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApi().getUUID()); // Adding doc content String docSourceType = documentation.getSourceType().toString(); boolean docContentExists = Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(docSourceType) || Documentation.DocumentSourceType.MARKDOWN.toString() .equalsIgnoreCase(docSourceType); if (docContentExists) { try (FileInputStream inputStream = new FileInputStream( individualDocumentFilePath + File.separator + folderName)) { String inlineContent = IOUtils.toString(inputStream, ImportExportConstants.CHARSET); if (!apiTypeWrapper.isAPIProduct()) { apiProvider.addDocumentationContent(apiTypeWrapper.getApi(), documentation.getName(), inlineContent); } else { apiProvider.addProductDocumentationContent(apiTypeWrapper.getApiProduct(), documentation.getName(), inlineContent); } } } else if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(docSourceType)) { String filePath = documentation.getFilePath(); try (FileInputStream inputStream = new FileInputStream( individualDocumentFilePath + File.separator + filePath)) { String docExtension = FilenameUtils.getExtension( pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY + File.separator + filePath); ResourceFile apiDocument = new ResourceFile(inputStream, docExtension); String visibleRolesList = apiTypeWrapper.getVisibleRoles(); String[] visibleRoles = new String[0]; if (visibleRolesList != null) { visibleRoles = visibleRolesList.split(","); } String filePathDoc = APIUtil.getDocumentationFilePath(identifier, filePath); APIUtil.setResourcePermissions(apiTypeWrapper.getId().getProviderName(), apiTypeWrapper.getVisibility(), visibleRoles, filePathDoc); documentation.setFilePath( apiProvider.addResourceFile(apiTypeWrapper.getId(), filePathDoc, apiDocument)); if (!apiTypeWrapper.isAPIProduct()) { apiProvider.updateDocumentation(apiTypeWrapper.getApi().getId(), documentation); } else { apiProvider.updateDocumentation(apiTypeWrapper.getApiProduct().getId(), documentation); } } catch (FileNotFoundException e) { //this error is logged and ignored because documents are optional in an API log.error("Failed to locate the document files of the API/API Product: " + apiTypeWrapper .getId().getName(), e); continue; } } } } } catch (FileNotFoundException e) { //this error is logged and ignored because documents are optional in an API log.error("Failed to locate the document files of the API/API Product: " + identifier.getName(), e); } catch (APIManagementException | IOException e) { //this error is logged and ignored because documents are optional in an API log.error("Failed to add Documentations to API/API Product: " + identifier.getName(), e); } } /** * This method adds API sequences to the imported API. If the sequence is a newly defined one, it is added. * * @param pathToArchive Location of the extracted folder of the API * @param importedApi The imported API object * @param registry Registry */ private static void addAPISequences(String pathToArchive, API importedApi, Registry registry) { String inSequenceFileName = importedApi.getInSequence() + APIConstants.XML_EXTENSION; String inSequenceFileLocation = pathToArchive + ImportExportConstants.IN_SEQUENCE_LOCATION + inSequenceFileName; String regResourcePath; //Adding in-sequence, if any if (CommonUtil.checkFileExistence(inSequenceFileLocation)) { regResourcePath = APIConstants.API_CUSTOM_INSEQUENCE_LOCATION + inSequenceFileName; addSequenceToRegistry(false, registry, inSequenceFileLocation, regResourcePath); } String outSequenceFileName = importedApi.getOutSequence() + APIConstants.XML_EXTENSION; String outSequenceFileLocation = pathToArchive + ImportExportConstants.OUT_SEQUENCE_LOCATION + outSequenceFileName; //Adding out-sequence, if any if (CommonUtil.checkFileExistence(outSequenceFileLocation)) { regResourcePath = APIConstants.API_CUSTOM_OUTSEQUENCE_LOCATION + outSequenceFileName; addSequenceToRegistry(false, registry, outSequenceFileLocation, regResourcePath); } String faultSequenceFileName = importedApi.getFaultSequence() + APIConstants.XML_EXTENSION; String faultSequenceFileLocation = pathToArchive + ImportExportConstants.FAULT_SEQUENCE_LOCATION + faultSequenceFileName; //Adding fault-sequence, if any if (CommonUtil.checkFileExistence(faultSequenceFileLocation)) { regResourcePath = APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION + faultSequenceFileName; addSequenceToRegistry(false, registry, faultSequenceFileLocation, regResourcePath); } } /** * This method adds API Specific sequences added through the Publisher to the imported API. If the specific * sequence already exists, it is updated. * * @param pathToArchive Location of the extracted folder of the API * @param registry Registry * @param apiIdentifier API Identifier */ private static void addAPISpecificSequences(String pathToArchive, Registry registry, APIIdentifier apiIdentifier) { String apiResourcePath = APIUtil.getAPIPath(apiIdentifier); // Getting registry API base path out of apiResourcePath apiResourcePath = apiResourcePath.substring(0, apiResourcePath.lastIndexOf("/")); String sequencesDirectoryPath = pathToArchive + File.separator + APIImportExportConstants.SEQUENCES_RESOURCE; // Add multiple custom sequences to registry for each type in/out/fault addCustomSequencesToRegistry(sequencesDirectoryPath, apiResourcePath, registry, ImportExportConstants.IN_SEQUENCE_PREFIX); addCustomSequencesToRegistry(sequencesDirectoryPath, apiResourcePath, registry, ImportExportConstants.OUT_SEQUENCE_PREFIX); addCustomSequencesToRegistry(sequencesDirectoryPath, apiResourcePath, registry, ImportExportConstants.FAULT_SEQUENCE_PREFIX); } /** * @param sequencesDirectoryPath Location of the sequences directory inside the extracted folder of the API * @param apiResourcePath API resource path in the registry * @param registry Registry * @param type Sequence type (in/out/fault) */ private static void addCustomSequencesToRegistry(String sequencesDirectoryPath, String apiResourcePath, Registry registry, String type) { String apiSpecificSequenceFilePath = sequencesDirectoryPath + File.separator + type + ImportExportConstants.SEQUENCE_LOCATION_POSTFIX + File.separator + ImportExportConstants.CUSTOM_TYPE; if (CommonUtil.checkFileExistence(apiSpecificSequenceFilePath)) { File apiSpecificSequencesDirectory = new File(apiSpecificSequenceFilePath); File[] apiSpecificSequencesDirectoryListing = apiSpecificSequencesDirectory.listFiles(); if (apiSpecificSequencesDirectoryListing != null) { for (File apiSpecificSequence : apiSpecificSequencesDirectoryListing) { String individualSequenceLocation = apiSpecificSequenceFilePath + File.separator + apiSpecificSequence.getName(); // Constructing mediation resource path String mediationResourcePath = apiResourcePath + RegistryConstants.PATH_SEPARATOR + type + RegistryConstants.PATH_SEPARATOR + apiSpecificSequence.getName(); addSequenceToRegistry(true, registry, individualSequenceLocation, mediationResourcePath); } } } } /** * This method adds the sequence files to the registry. This updates the API specific sequences if already exists. * * @param isAPISpecific Whether the adding sequence is API specific * @param registry The registry instance * @param sequenceFileLocation Location of the sequence file * @param regResourcePath Resource path in the registry */ private static void addSequenceToRegistry(Boolean isAPISpecific, Registry registry, String sequenceFileLocation, String regResourcePath) { try { if (registry.resourceExists(regResourcePath) && !isAPISpecific) { if (log.isDebugEnabled()) { log.debug("Sequence already exists in registry path: " + regResourcePath); } } else { if (log.isDebugEnabled()) { log.debug("Adding Sequence to the registry path : " + regResourcePath); } File sequenceFile = new File(sequenceFileLocation); try (InputStream seqStream = new FileInputStream(sequenceFile);) { byte[] inSeqData = IOUtils.toByteArray(seqStream); Resource inSeqResource = registry.newResource(); inSeqResource.setContent(inSeqData); registry.put(regResourcePath, inSeqResource); } } } catch (RegistryException e) { //this is logged and ignored because sequences are optional log.error("Failed to add sequences into the registry : " + regResourcePath, e); } catch (IOException e) { //this is logged and ignored because sequences are optional log.error("I/O error while writing sequence data to the registry : " + regResourcePath, e); } } /** * This method adds the WSDL to the registry, if there is a WSDL associated with the API. * * @param pathToArchive Location of the extracted folder of the API * @param importedApi The imported API object * @param apiProvider API Provider * @param registry Registry */ private static void addAPIWsdl(String pathToArchive, API importedApi, APIProvider apiProvider, Registry registry) { String wsdlFileName = importedApi.getId().getApiName() + "-" + importedApi.getId().getVersion() + APIConstants.WSDL_FILE_EXTENSION; String wsdlPath = pathToArchive + ImportExportConstants.WSDL_LOCATION + wsdlFileName; if (CommonUtil.checkFileExistence(wsdlPath)) { try { URL wsdlFileUrl = new File(wsdlPath).toURI().toURL(); importedApi.setWsdlUrl(wsdlFileUrl.toString()); APIUtil.createWSDL(registry, importedApi); apiProvider.updateAPI(importedApi); } catch (MalformedURLException e) { // this exception is logged and ignored since WSDL is optional for an API log.error("Error in getting WSDL URL. ", e); } catch (org.wso2.carbon.registry.core.exceptions.RegistryException e) { // this exception is logged and ignored since WSDL is optional for an API log.error("Error in putting the WSDL resource to registry. ", e); } catch (APIManagementException e) { // this exception is logged and ignored since WSDL is optional for an API log.error("Error in creating the WSDL resource in the registry. ", e); } catch (FaultGatewaysException e) { // This is logged and process is continued because WSDL is optional for an API log.error("Failed to update API after adding WSDL. ", e); } } } /** * This method import endpoint certificate. * * @param pathToArchive location of the extracted folder of the API * @param importedApi the imported API object * @throws APIImportExportException If an error occurs while importing endpoint certificates from file */ private static void addEndpointCertificates(String pathToArchive, API importedApi, APIProvider apiProvider, int tenantId) throws APIManagementException { String jsonContent = null; String pathToEndpointsCertificatesDirectory = pathToArchive + File.separator + ImportExportConstants.ENDPOINT_CERTIFICATES_DIRECTORY; String pathToYamlFile = pathToEndpointsCertificatesDirectory + ImportExportConstants.ENDPOINTS_CERTIFICATE_FILE + ImportExportConstants.YAML_EXTENSION; String pathToJsonFile = pathToEndpointsCertificatesDirectory + ImportExportConstants.ENDPOINTS_CERTIFICATE_FILE + ImportExportConstants.JSON_EXTENSION; try { // try loading file as YAML if (CommonUtil.checkFileExistence(pathToYamlFile)) { if (log.isDebugEnabled()) { log.debug("Found certificate file " + pathToYamlFile); } String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { // load as a json fallback if (log.isDebugEnabled()) { log.debug("Found certificate file " + pathToJsonFile); } jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } if (jsonContent == null) { log.debug("No certificate file found to be added, skipping certificate import."); return; } JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA); JsonArray certificates = addFileContentToCertificates(configElement.getAsJsonArray(), pathToEndpointsCertificatesDirectory); for (JsonElement certificate : certificates) { updateAPIWithCertificate(certificate, apiProvider, importedApi, tenantId); } } catch (IOException e) { throw new APIManagementException("Error in reading certificates file", e); } } /** * Add the certificate content to the object. * * @param certificates Certificates array * @param pathToCertificatesDirectory File path to the certificates directory * @throws IOException If an error occurs while retrieving the certificate content from the file */ private static JsonArray addFileContentToCertificates(JsonArray certificates, String pathToCertificatesDirectory) throws IOException { JsonArray modifiedCertificates = new JsonArray(); for (JsonElement certificate : certificates) { JsonObject certificateObject = certificate.getAsJsonObject(); String certificateFileName = certificateObject.get(ImportExportConstants.CERTIFICATE_FILE).getAsString(); // Get the content of the certificate file from the relevant certificate file inside the certificates // directory and add it to the certificate String certificateContent = getFileContentOfCertificate(certificateFileName, pathToCertificatesDirectory); if (certificateObject.has(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY)) { certificateObject.remove(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY); } certificateObject.addProperty(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY, certificateContent); modifiedCertificates.add(certificateObject); } return modifiedCertificates; } /** * Get the file content of a certificate in the Client-certificate directory. * * @param certificateFileName Certificate file name * @param pathToCertificatesDirectory Path to client certificates directory * @return content of the certificate */ private static String getFileContentOfCertificate(String certificateFileName, String pathToCertificatesDirectory) throws IOException { String certificateContent = null; File certificatesDirectory = new File(pathToCertificatesDirectory); File[] certificatesDirectoryListing = certificatesDirectory.listFiles(); // Iterate the Endpoints certificates directory to get the relevant cert file if (certificatesDirectoryListing != null) { for (File endpointsCertificate : certificatesDirectoryListing) { if (StringUtils.equals(certificateFileName, endpointsCertificate.getName())) { certificateContent = FileUtils.readFileToString( new File(pathToCertificatesDirectory + File.separator + certificateFileName)); certificateContent = StringUtils.substringBetween(certificateContent, APIConstants.BEGIN_CERTIFICATE_STRING, APIConstants.END_CERTIFICATE_STRING); } } } return certificateContent; } /** * Update API with the certificate. * If certificate alias already exists for tenant in database, certificate content will be * updated in trust store. If cert alias does not exits in database for that tenant, add the certificate to * publisher and gateway nodes. In such case if alias already exits in the trust store, update the certificate * content for that alias. * * @param certificate Certificate JSON element * @param apiProvider API Provider * @param importedApi API to import * @param tenantId Tenant Id */ private static void updateAPIWithCertificate(JsonElement certificate, APIProvider apiProvider, API importedApi, int tenantId) throws APIManagementException { String certificateFileName = certificate.getAsJsonObject().get(ImportExportConstants.CERTIFICATE_FILE) .getAsString(); String certificateContent = certificate.getAsJsonObject() .get(ImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY).getAsString(); if (certificateContent == null) { throw new APIManagementException("Certificate " + certificateFileName + "is null"); } String alias = certificate.getAsJsonObject().get(ImportExportConstants.ALIAS_JSON_KEY).getAsString(); String endpoint = certificate.getAsJsonObject().get(ImportExportConstants.ENDPOINT_JSON_KEY).getAsString(); try { if (apiProvider.isCertificatePresent(tenantId, alias) || ( ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == (apiProvider .addCertificate(APIUtil.replaceEmailDomainBack(importedApi.getId().getProviderName()), certificateContent, alias, endpoint)))) { apiProvider.updateCertificate(certificateContent, alias); } } catch (APIManagementException e) { log.error("Error while importing certificate endpoint [" + endpoint + " ]" + "alias [" + alias + " ] tenant user [" + APIUtil.replaceEmailDomainBack(importedApi.getId().getProviderName()) + "]", e); } } /** * Import client certificates for Mutual SSL related configuration * * @param pathToArchive Location of the extracted folder of the API * @param apiProvider API Provider * @throws APIImportExportException */ private static void addClientCertificates(String pathToArchive, APIProvider apiProvider, Boolean preserveProvider, String provider) throws APIManagementException { String jsonContent = null; String pathToClientCertificatesDirectory = pathToArchive + File.separator + ImportExportConstants.CLIENT_CERTIFICATES_DIRECTORY; String pathToYamlFile = pathToClientCertificatesDirectory + ImportExportConstants.CLIENT_CERTIFICATE_FILE + ImportExportConstants.YAML_EXTENSION; String pathToJsonFile = pathToClientCertificatesDirectory + ImportExportConstants.CLIENT_CERTIFICATE_FILE + ImportExportConstants.JSON_EXTENSION; try { // try loading file as YAML if (CommonUtil.checkFileExistence(pathToYamlFile)) { log.debug("Found client certificate file " + pathToYamlFile); String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile)); jsonContent = CommonUtil.yamlToJson(yamlContent); } else if (CommonUtil.checkFileExistence(pathToJsonFile)) { // load as a json fallback log.debug("Found client certificate file " + pathToJsonFile); jsonContent = FileUtils.readFileToString(new File(pathToJsonFile)); } if (jsonContent == null) { log.debug("No client certificate file found to be added, skipping"); return; } JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA); JsonArray modifiedCertificatesData = addFileContentToCertificates(configElement.getAsJsonArray(), pathToClientCertificatesDirectory); Gson gson = new Gson(); List<ClientCertificateDTO> certificateMetadataDTOS = gson .fromJson(modifiedCertificatesData, new TypeToken<ArrayList<ClientCertificateDTO>>() { }.getType()); for (ClientCertificateDTO certDTO : certificateMetadataDTOS) { APIIdentifier apiIdentifier = !preserveProvider ? new APIIdentifier(provider, certDTO.getApiIdentifier().getApiName(), certDTO.getApiIdentifier().getVersion()) : certDTO.getApiIdentifier(); apiProvider.addClientCertificate(APIUtil.replaceEmailDomainBack(provider), apiIdentifier, certDTO.getCertificate(), certDTO.getAlias(), certDTO.getTierName()); } } catch (IOException e) { throw new APIManagementException("Error in reading certificates file", e); } catch (APIManagementException e) { throw new APIManagementException("Error while importing client certificate", e); } } /** * This method adds API sequences to the imported API. If the sequence is a newly defined one, it is added. * * @param pathToArchive Location of the extracted folder of the API * @param importedApi API * @param registry Registry * @throws APIImportExportException If an error occurs while importing mediation logic */ private static void addSOAPToREST(String pathToArchive, API importedApi, Registry registry) throws APIManagementException { String inFlowFileLocation = pathToArchive + File.separator + SOAPTOREST + File.separator + IN; String outFlowFileLocation = pathToArchive + File.separator + SOAPTOREST + File.separator + OUT; // Adding in-sequence, if any if (CommonUtil.checkFileExistence(inFlowFileLocation)) { APIIdentifier apiId = importedApi.getId(); String soapToRestLocationIn = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_IN_RESOURCE; String soapToRestLocationOut = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_OUT_RESOURCE; try { // Import inflow mediation logic Path inFlowDirectory = Paths.get(inFlowFileLocation); importMediationLogic(inFlowDirectory, registry, soapToRestLocationIn); // Import outflow mediation logic Path outFlowDirectory = Paths.get(outFlowFileLocation); importMediationLogic(outFlowDirectory, registry, soapToRestLocationOut); } catch (DirectoryIteratorException e) { throw new APIManagementException("Error in importing SOAP to REST mediation logic", e); } } } /** * Method created to add inflow and outflow mediation logic * * @param flowDirectory Inflow and outflow directory * @param registry Registry * @param soapToRestLocation Folder location * @throws APIImportExportException If an error occurs while importing/storing SOAP to REST mediation logic */ private static void importMediationLogic(Path flowDirectory, Registry registry, String soapToRestLocation) throws APIManagementException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(flowDirectory)) { for (Path file : stream) { String fileName = file.getFileName().toString(); String method = ""; if (fileName.split(".xml").length != 0) { method = fileName.split(".xml")[0].substring(file.getFileName().toString().lastIndexOf("_") + 1); } try (InputStream inputFlowStream = new FileInputStream(file.toFile())) { byte[] inSeqData = IOUtils.toByteArray(inputFlowStream); Resource inSeqResource = (Resource) registry.newResource(); inSeqResource.setContent(inSeqData); inSeqResource.addProperty(SOAPToRESTConstants.METHOD, method); inSeqResource.setMediaType("text/xml"); registry.put(soapToRestLocation + RegistryConstants.PATH_SEPARATOR + file.getFileName(), inSeqResource); } } } catch (IOException | DirectoryIteratorException e) { throw new APIManagementException("Error in importing SOAP to REST mediation logic", e); } catch (RegistryException e) { throw new APIManagementException("Error in storing imported SOAP to REST mediation logic", e); } } /** * This method returns the lifecycle action which can be used to transit from currentStatus to targetStatus. * * @param tenantDomain Tenant domain * @param currentStatus Current status to do status transition * @param targetStatus Target status to do status transition * @return Lifecycle action or null if target is not reachable * @throws APIImportExportException If getting lifecycle action failed */ public static String getLifeCycleAction(String tenantDomain, String currentStatus, String targetStatus, APIProvider provider) throws APIManagementException { // No need to change the lifecycle if both the statuses are same if (StringUtils.equalsIgnoreCase(currentStatus, targetStatus)) { return null; } LifeCycle lifeCycle = new LifeCycle(); // Parse DOM of APILifeCycle try { String data = provider.getLifecycleConfiguration(tenantDomain); DocumentBuilderFactory factory = APIUtil.getSecuredDocumentBuilder(); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); Document doc = builder.parse(inputStream); Element root = doc.getDocumentElement(); // Get all nodes with state NodeList states = root.getElementsByTagName("state"); int nStates = states.getLength(); for (int i = 0; i < nStates; i++) { Node node = states.item(i); Node id = node.getAttributes().getNamedItem("id"); if (id != null && !id.getNodeValue().isEmpty()) { LifeCycleTransition lifeCycleTransition = new LifeCycleTransition(); NodeList transitions = node.getChildNodes(); int nTransitions = transitions.getLength(); for (int j = 0; j < nTransitions; j++) { Node transition = transitions.item(j); // Add transitions if (ImportExportConstants.NODE_TRANSITION.equals(transition.getNodeName())) { Node target = transition.getAttributes().getNamedItem("target"); Node action = transition.getAttributes().getNamedItem("event"); if (target != null && action != null) { lifeCycleTransition .addTransition(target.getNodeValue().toLowerCase(), action.getNodeValue()); } } } lifeCycle.addLifeCycleState(id.getNodeValue().toLowerCase(), lifeCycleTransition); } } } catch (ParserConfigurationException | SAXException e) { throw new APIManagementException("Error parsing APILifeCycle for tenant: " + tenantDomain, e); } catch (UnsupportedEncodingException e) { throw new APIManagementException( "Error parsing unsupported encoding for APILifeCycle in tenant: " + tenantDomain, e); } catch (IOException e) { throw new APIManagementException("Error reading APILifeCycle for tenant: " + tenantDomain, e); } // Retrieve lifecycle action LifeCycleTransition transition = lifeCycle.getTransition(currentStatus.toLowerCase()); if (transition != null) { return transition.getAction(targetStatus.toLowerCase()); } return null; } /** * This method imports an API Product. * * @param extractedFolderPath Location of the extracted folder of the API Product * @param preserveProvider Decision to keep or replace the provider * @param overwriteAPIProduct Whether to update the API Product or not * @param overwriteAPIs Whether to update the dependent APIs or not * @param importAPIs Whether to import the dependent APIs or not * @throws APIImportExportException If there is an error in importing an API */ public static APIProduct importApiProduct(String extractedFolderPath, Boolean preserveProvider, Boolean overwriteAPIProduct, Boolean overwriteAPIs, Boolean importAPIs, String[] tokenScopes) throws APIManagementException { String userName = RestApiCommonUtil.getLoggedInUsername(); String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName)); APIProduct importedApiProduct = null; try { JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName); APIProductDTO importedApiProductDTO = new Gson().fromJson(jsonObject, APIProductDTO.class); APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiProductDTO.getProvider()); // Check whether the API resources are valid checkAPIProductResourcesValid(extractedFolderPath, userName, apiProvider, importedApiProductDTO, preserveProvider); if (importAPIs) { // Import dependent APIs only if it is asked (the UUIDs of the dependent APIs will be updated here if a // fresh import happens) importedApiProductDTO = importDependentAPIs(extractedFolderPath, userName, preserveProvider, apiProvider, overwriteAPIs, importedApiProductDTO, tokenScopes); } else { // Even we do not import APIs, the UUIDs of the dependent APIs should be updated if the APIs are already in the APIM importedApiProductDTO = updateDependentApiUuids(importedApiProductDTO, apiProvider, currentTenantDomain); } APIProduct targetApiProduct = retrieveApiProductToOverwrite(importedApiProductDTO.getName(), currentTenantDomain, apiProvider, Boolean.TRUE); // If the overwrite is set to true (which means an update), retrieve the existing API if (Boolean.TRUE.equals(overwriteAPIProduct) && targetApiProduct != null) { log.info("Existing API Product found, attempting to update it..."); importedApiProduct = PublisherCommonUtils.updateApiProduct(targetApiProduct, importedApiProductDTO, RestApiCommonUtil.getLoggedInUserProvider(), userName); } else { if (targetApiProduct == null && Boolean.TRUE.equals(overwriteAPIProduct)) { log.info("Cannot find : " + importedApiProductDTO.getName() + ". Creating it."); } importedApiProduct = PublisherCommonUtils .addAPIProductWithGeneratedSwaggerDefinition(importedApiProductDTO, importedApiProductDTO.getProvider(), importedApiProductDTO.getProvider()); } // Add/update swagger of API Product importedApiProduct = updateApiProductSwagger(extractedFolderPath, importedApiProduct, apiProvider); // Since Image, documents and client certificates are optional, exceptions are logged and ignored in implementation ApiTypeWrapper apiTypeWrapperWithUpdatedApiProduct = new ApiTypeWrapper(importedApiProduct); addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider); addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider); if (apiProvider.isClientCertificateBasedAuthenticationConfigured()) { if (log.isDebugEnabled()) { log.debug("Mutual SSL enabled. Importing client certificates."); } addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApiProduct.getId().getProviderName()); } return importedApiProduct; } catch (IOException e) { // Error is logged and APIImportExportException is thrown because adding API Product and swagger are // mandatory steps throw new APIManagementException( "Error while reading API Product meta information from path: " + extractedFolderPath, e); } catch (FaultGatewaysException e) { throw new APIManagementException( "Error while updating API Product: " + importedApiProduct.getId().getName(), e); } catch (APIManagementException e) { String errorMessage = "Error while importing API Product: "; if (importedApiProduct != null) { errorMessage += importedApiProduct.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApiProduct.getId().getVersion(); } throw new APIManagementException(errorMessage + " " + e.getMessage(), e); } } /** * This method checks whether the resources in the API Product are valid. * * @param path Location of the extracted folder of the API Product * @param currentUser The current logged in user * @param apiProvider API provider * @param apiProductDto API Product DTO * @throws IOException If there is an error while reading an API file * @throws APIManagementException If failed to get the API Provider of an API, * or failed when checking the existence of an API */ private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider) throws IOException, APIManagementException { // Get dependent APIs in the API Product List<ProductAPIDTO> apis = apiProductDto.getApis(); String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY; File apisDirectory = new File(apisDirectoryPath); File[] apisDirectoryListing = apisDirectory.listFiles(); if (apisDirectoryListing != null) { for (File apiDirectory : apisDirectoryListing) { String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory .getName(); JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser); APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class); String apiName = apiDto.getName(); String apiVersion = apiDto.getVersion(); String swaggerContent = loadSwaggerFile(apiDirectoryPath); APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent); Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent); for (ProductAPIDTO apiFromProduct : apis) { if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils .equals(apiFromProduct.getVersion(), apiVersion)) { List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources( apiFromProduct.getOperations(), apiUriTemplates); // If there are still product resources to be checked (which were not able to find in the // dependent APIs inside the directory) check whether those are already inside APIM if (!invalidApiOperations.isEmpty()) { // Get the provider of the API if the API is in current user's tenant domain. API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE); invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates()); } // invalidApiOperations is not empty means, at least one of the resources of the API // Product does not have corresponding API resources neither inside the importing directory nor // inside the APIM if (!invalidApiOperations.isEmpty()) { throw new APIMgtResourceNotFoundException( "Cannot find API resources for some API Product resources."); } } } } } } /** * This method filter the invalid resources in the API Product by matching with the URI Templates of a particular * dependent API. * * @param apiProductOperations Operations from API Product * @param apiUriTemplates URI Templates of the dependent API * (either inside the import directory or already inside the APIM) * @return Invalid API operations */ private static List<APIOperationsDTO> filterInvalidProductResources(List<APIOperationsDTO> apiProductOperations, Set<URITemplate> apiUriTemplates) { List<APIOperationsDTO> apiOperations = new ArrayList<>(apiProductOperations); for (URITemplate apiUriTemplate : apiUriTemplates) { // If the URI Template is Available in the API, remove it from the list since it is valid apiOperations.removeIf( apiOperation -> StringUtils.equals(apiOperation.getVerb(), apiUriTemplate.getHTTPVerb()) && StringUtils.equals(apiOperation.getTarget(), apiUriTemplate.getUriTemplate())); } return apiOperations; } /** * This method imports dependent APIs of the API Product. * * @param path Location of the extracted folder of the API Product * @param currentUser The current logged in user * @param isDefaultProviderAllowed Decision to keep or replace the provider * @param apiProvider API provider * @param overwriteAPIs Whether to overwrite the APIs or not * @param apiProductDto API Product DTO * @param tokenScopes Scopes of the token * @return Modified API Product DTO with the correct API UUIDs * @throws IOException If there is an error while reading an API file * @throws APIImportExportException If there is an error in importing an API * @throws APIManagementException If failed to get the API Provider of an API, or failed when * checking the existence of an API */ private static APIProductDTO importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed, APIProvider apiProvider, Boolean overwriteAPIs, APIProductDTO apiProductDto, String[] tokenScopes) throws IOException, APIManagementException { String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY; File apisDirectory = new File(apisDirectoryPath); File[] apisDirectoryListing = apisDirectory.listFiles(); if (apisDirectoryListing != null) { for (File apiDirectory : apisDirectoryListing) { String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory .getName(); JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, isDefaultProviderAllowed, currentUser); APIDTO apiDtoToImport = new Gson().fromJson(jsonObject, APIDTO.class); API importedApi = null; String apiName = apiDtoToImport.getName(); String apiVersion = apiDtoToImport.getVersion(); if (isDefaultProviderAllowed) { APIIdentifier apiIdentifier = new APIIdentifier( APIUtil.replaceEmailDomain(apiDtoToImport.getProvider()), apiName, apiVersion); // Checking whether the API exists if (apiProvider.isAPIAvailable(apiIdentifier)) { // If the API is already imported, update it if the overWriteAPIs flag is specified, // otherwise do not update the API. (Just skip it) if (Boolean.TRUE.equals(overwriteAPIs)) { importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.TRUE, tokenScopes); } } else { // If the API is not already imported, import it importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.FALSE, tokenScopes); } } else { // Retrieve the current tenant domain of the logged in user String currentTenantDomain = MultitenantUtils .getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)); // Get the provider of the API if the API is in current user's tenant domain. String apiProviderInCurrentTenantDomain = APIUtil .getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain); if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) { // If there is no API in the current tenant domain (which means the provider name is blank) // then the API should be imported freshly importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.FALSE, tokenScopes); } else { // If there is an API already in the current tenant domain, update it if the overWriteAPIs flag is specified, // otherwise do not import/update the API. (Just skip it) if (Boolean.TRUE.equals(overwriteAPIs)) { importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, Boolean.TRUE, tokenScopes); } } } if (importedApi == null) { // Retrieve the API from the environment (This happens when you have not specified // the overwrite flag, so that we should retrieve the API from inside) importedApi = retrieveApiToOverwrite(apiDtoToImport.getName(), apiDtoToImport.getVersion(), MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE); } updateApiUuidInApiProduct(apiProductDto, importedApi); } } else { String msg = "No dependent APIs supplied. Continuing ..."; log.info(msg); } return apiProductDto; } /** * This method updates the UUID of the dependent API in an API Product. * * @param apiProductDto API Product DTO * @param importedApi Imported API */ private static APIProductDTO updateApiUuidInApiProduct(APIProductDTO apiProductDto, API importedApi) { APIIdentifier importedApiIdentifier = importedApi.getId(); List<ProductAPIDTO> apis = apiProductDto.getApis(); for (ProductAPIDTO api : apis) { if (StringUtils.equals(api.getName(), importedApiIdentifier.getName()) && StringUtils .equals(api.getVersion(), importedApiIdentifier.getVersion())) { api.setApiId(importedApi.getUUID()); break; } } return apiProductDto; } /** * This method updates the UUIDs of dependent APIs, when the dependent APIs are already inside APIM. * * @param importedApiProductDtO API Product DTO * @param apiProvider API Provider * @param currentTenantDomain Current tenant domain * @throws APIManagementException If failed failed when checking the existence of an API */ private static APIProductDTO updateDependentApiUuids(APIProductDTO importedApiProductDtO, APIProvider apiProvider, String currentTenantDomain) throws APIManagementException { List<ProductAPIDTO> apis = importedApiProductDtO.getApis(); for (ProductAPIDTO api : apis) { API targetApi = retrieveApiToOverwrite(api.getName(), api.getVersion(), currentTenantDomain, apiProvider, Boolean.FALSE); if (targetApi != null) { api.setApiId(targetApi.getUUID()); } } return importedApiProductDtO; } /** * This method retrieves an API Product to overwrite in the current tenant domain. * * @param apiProductName API Product Name * @param currentTenantDomain Current tenant domain * @param apiProvider API Provider * @param ignoreAndImport This should be true if the exception should be ignored * @throws APIManagementException If an error occurs when retrieving the API to overwrite */ private static APIProduct retrieveApiProductToOverwrite(String apiProductName, String currentTenantDomain, APIProvider apiProvider, Boolean ignoreAndImport) throws APIManagementException { String provider = APIUtil.getAPIProviderFromAPINameVersionTenant(apiProductName, ImportExportConstants.DEFAULT_API_PRODUCT_VERSION, currentTenantDomain); APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), apiProductName, ImportExportConstants.DEFAULT_API_PRODUCT_VERSION); // Checking whether the API exists if (!apiProvider.isAPIProductAvailable(apiProductIdentifier)) { if (ignoreAndImport) { return null; } throw new APIMgtResourceNotFoundException( "Error occurred while retrieving the API Product. API Product: " + apiProductName + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + ImportExportConstants.DEFAULT_API_PRODUCT_VERSION + " not found"); } return apiProvider.getAPIProduct(apiProductIdentifier); } /** * This method updates the API Product and the swagger with the correct scopes. * * @param pathToArchive Path to the extracted folder * @param importedApiProduct Imported API Product * @param apiProvider API Provider * @throws APIManagementException If an error occurs when retrieving the parser and updating the API Product * @throws FaultGatewaysException If an error occurs when updating the API to overwrite * @throws IOException If an error occurs when loading the swagger file */ private static APIProduct updateApiProductSwagger(String pathToArchive, APIProduct importedApiProduct, APIProvider apiProvider) throws APIManagementException, FaultGatewaysException, IOException { String swaggerContent = loadSwaggerFile(pathToArchive); // Load required properties from swagger to the API Product APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent); Set<Scope> scopes = apiDefinition.getScopes(swaggerContent); importedApiProduct.setScopes(scopes); // This is required to make scopes get effected Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider .updateAPIProduct(importedApiProduct); apiProvider.updateAPIProductSwagger(apiToProductResourceMapping, importedApiProduct); return importedApiProduct; } }
Format setOperationsToDTO function
components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/common/mappings/ImportUtils.java
Format setOperationsToDTO function
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/common/mappings/ImportUtils.java <ide> /** <ide> * This method sets the operations which were retrieved from the swagger definition to the API DTO. <ide> * <del> * @param apiDto API DTO <del> * @param response API Validation Response <add> * @param apiDto API DTO <add> * @param response API Validation Response <ide> * @throws APIManagementException If an error occurs when retrieving the URI templates <ide> */ <ide> private static void setOperationsToDTO(APIDTO apiDto, APIDefinitionValidationResponse response) <ide> throws APIManagementException { <ide> List<URITemplate> uriTemplates = new ArrayList<>(); <ide> uriTemplates.addAll(response.getParser().getURITemplates(response.getJsonContent())); <del> List<APIOperationsDTO> apiOperationsDtos =APIMappingUtil.fromURITemplateListToOprationList(uriTemplates); <add> List<APIOperationsDTO> apiOperationsDtos = APIMappingUtil.fromURITemplateListToOprationList(uriTemplates); <ide> apiDto.setOperations(apiOperationsDtos); <ide> } <ide>
Java
agpl-3.0
522d27851c0681073113b73c5c33854457948d41
0
elki-project/elki,elki-project/elki,elki-project/elki
package experimentalcode.students.nuecke.algorithm.clustering.subspace; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.List; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.clustering.EM; import de.lmu.ifi.dbs.elki.data.Cluster; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.Subspace; import de.lmu.ifi.dbs.elki.data.VectorUtil; import de.lmu.ifi.dbs.elki.data.VectorUtil.SortDBIDsBySingleDimension; import de.lmu.ifi.dbs.elki.data.model.SubspaceModel; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore; import de.lmu.ifi.dbs.elki.database.ids.ArrayDBIDs; import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.DBIDArrayIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDMIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.ids.HashSetModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.ModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.database.relation.RelationUtil; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.logging.progress.StepProgress; import de.lmu.ifi.dbs.elki.math.MathUtil; import de.lmu.ifi.dbs.elki.math.MeanVariance; import de.lmu.ifi.dbs.elki.math.linearalgebra.CovarianceMatrix; import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.elki.math.linearalgebra.VMath; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; import de.lmu.ifi.dbs.elki.math.statistics.distribution.ChiSquaredDistribution; import de.lmu.ifi.dbs.elki.math.statistics.distribution.PoissonDistribution; import de.lmu.ifi.dbs.elki.utilities.BitsUtil; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.documentation.Title; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; /** * P3C: A Robust Projected Clustering Algorithm. * * <p> * Reference: <br/> * Gabriela Moise, Jörg Sander, Martin Ester<br /> * P3C: A Robust Projected Clustering Algorithm.<br/> * In: Proc. Sixth International Conference on Data Mining (ICDM '06) * </p> * * @author Florian Nuecke * @author Erich Schubert * * @apiviz.has SubspaceModel * * @param <V> the type of NumberVector handled by this Algorithm. */ @Title("P3C: A Robust Projected Clustering Algorithm.") @Reference(authors = "Gabriela Moise, Jörg Sander, Martin Ester", title = "P3C: A Robust Projected Clustering Algorithm", booktitle = "Proc. Sixth International Conference on Data Mining (ICDM '06)", url = "http://dx.doi.org/10.1109/ICDM.2006.123") public class P3C<V extends NumberVector<?>> extends AbstractAlgorithm<Clustering<SubspaceModel<V>>> { /** * The logger for this class. */ private static final Logging LOG = Logging.getLogger(P3C.class); /** * Minimum Log Likelihood. */ private static final double MIN_LOGLIKELIHOOD = -100000; /** * Parameter for the Poisson test threshold. */ protected double poissonThreshold; /** * Maximum number of iterations for the EM step. */ protected int maxEmIterations; /** * Threshold when to stop EM iterations. */ protected double emDelta; /** * Minimum cluster size for noise flagging. (Not existing in the original * publication). */ protected int minClusterSize; /** * Sets up a new instance of the algorithm's environment. */ public P3C(double poissonThreshold, int maxEmIterations, double emDelta, int minClusterSize) { super(); this.poissonThreshold = poissonThreshold; this.maxEmIterations = maxEmIterations; this.emDelta = emDelta; this.minClusterSize = minClusterSize; } /** * Performs the P3C algorithm on the given Database. */ public Clustering<SubspaceModel<V>> run(Database database, Relation<V> relation) { final int dim = RelationUtil.dimensionality(relation); // Overall progress. StepProgress stepProgress = LOG.isVerbose() ? new StepProgress(8) : null; if(stepProgress != null) { stepProgress.beginStep(1, "Grid-partitioning data.", LOG); } // Desired number of bins, as per Sturge: final int binCount = (int) Math.ceil(1 + (Math.log(relation.size()) / MathUtil.LOG2)); // Perform 1-dimensional projections, and split into bins. DBIDs[][] partitions = new DBIDs[dim][binCount]; ArrayModifiableDBIDs ids = DBIDUtil.newArray(relation.getDBIDs()); DBIDArrayIter iter = ids.iter(); SortDBIDsBySingleDimension sorter = new VectorUtil.SortDBIDsBySingleDimension(relation, 0); for(int d = 0; d < dim; d++) { sorter.setDimension(d); ids.sort(sorter); // Minimum: iter.seek(0); double min = relation.get(iter).doubleValue(d); // Extend: iter.seek(ids.size() - 1); double delta = (relation.get(iter).doubleValue(d) - min) / binCount; if(delta > 0.) { partition(relation, d, min, delta, ids, iter, 0, ids.size(), 0, binCount, partitions[d]); if(LOG.isDebugging()) { StringBuilder buf = new StringBuilder(); buf.append("Partition sizes of dim ").append(d).append(": "); int sum = 0; for(DBIDs p : partitions[d]) { buf.append(p.size()).append(' '); sum += p.size(); } LOG.debug(buf.toString()); assert (sum == ids.size()); } } else { partitions[d] = null; // Flag whole dimension as bad } } if(stepProgress != null) { stepProgress.beginStep(2, "Searching for non-uniform bins in support histograms.", LOG); } // Set markers for each attribute until they're all deemed uniform. final long[][] markers = new long[dim][]; int numuniform = 0; for(int d = 0; d < dim; d++) { final DBIDs[] parts = partitions[d]; if(parts == null) { continue; // Never mark any on constant dimensions. } final long[] marked = markers[d] = BitsUtil.zero(binCount); int card = 0; while(card < dim - 1) { // Find bin with largest support, test only the dimensions that were not // previously marked. int bestBin = chiSquaredUniformTest(parts, marked, card); if(bestBin < 0) { numuniform++; break; // Uniform } BitsUtil.setI(marked, bestBin); card++; } if(LOG.isDebugging()) { LOG.debug("Marked bins in dim " + d + ": " + BitsUtil.toString(marked, dim)); } } if(stepProgress != null) { stepProgress.beginStep(3, "Merging marked bins to 1-signatures.", LOG); } // Generate projected p-signature intervals. ArrayList<Signature> signatures = new ArrayList<>(); for(int d = 0; d < dim; d++) { final DBIDs[] parts = partitions[d]; if(parts == null) { continue; // Never mark any on constant dimensions. } final long[] marked = markers[d]; // Find sequences of 1s in marked. for(int start = BitsUtil.nextSetBit(marked, 0); start >= 0;) { int end = BitsUtil.nextClearBit(marked, start + 1) - 1; if(end == -1) { end = dim; } int[] signature = new int[dim << 1]; Arrays.fill(signature, -1); signature[d << 1] = start; signature[(d << 1) + 1] = end - 1; // inclusive HashSetModifiableDBIDs sids = unionDBIDs(parts, start, end /* exclusive */); if(LOG.isDebugging()) { LOG.debug("1-signature: " + d + " " + start + "-" + end); } signatures.add(new Signature(signature, sids)); start = (end < dim) ? BitsUtil.nextSetBit(marked, end + 1) : -1; } } if(stepProgress != null) { stepProgress.beginStep(4, "Computing cluster cores from merged p-signatures.", LOG); } FiniteProgress mergeProgress = LOG.isVerbose() ? new FiniteProgress("1-signatures merges", signatures.size(), LOG) : null; // Merge to (p+1)-signatures (cluster cores). ArrayList<Signature> clusterCores = new ArrayList<>(signatures); // Try adding merge 1-signature with each cluster core. for(int i = 0; i < signatures.size(); ++i) { final Signature signature = signatures.get(i); // Don't merge with future signatures: final int end = clusterCores.size(); // Skip previous 1-signatures: merges are symmetrical. But include newly // created cluster cores (i.e. those resulting from previous merges). FiniteProgress submergeProgress = LOG.isVerbose() ? new FiniteProgress("p-signatures merges", end - (i + 1), LOG) : null; for(int j = i + 1; j < end; ++j) { final Signature first = clusterCores.get(j); final Signature merge = mergeSignatures(first, signature, binCount); if(merge != null) { // We add each potential core to the list to allow remaining // 1-signatures to try merging with this p-signature as well. clusterCores.add(merge); // Flag both "parents" for removal. first.prune = true; signature.prune = true; } if(submergeProgress != null) { submergeProgress.incrementProcessed(LOG); } } if(submergeProgress != null) { submergeProgress.ensureCompleted(LOG); } if(mergeProgress != null) { mergeProgress.incrementProcessed(LOG); } } if(mergeProgress != null) { mergeProgress.ensureCompleted(LOG); } if(stepProgress != null) { stepProgress.beginStep(5, "Pruning redundant cluster cores.", LOG); } // Prune cluster cores based on Definition 3, Condition 2. ArrayList<Signature> retain = new ArrayList<>(clusterCores.size()); for(Signature clusterCore : clusterCores) { if(!clusterCore.prune) { retain.add(clusterCore); } } clusterCores = retain; if(LOG.isVerbose()) { LOG.verbose("Number of cluster cores found: " + clusterCores.size()); } if(clusterCores.size() == 0) { stepProgress.setCompleted(LOG); // FIXME: return trivial noise clustering. return null; } if(stepProgress != null) { stepProgress.beginStep(5, "Refining cluster cores to clusters via EM.", LOG); } // Track objects not assigned to any cluster: ModifiableDBIDs noise = DBIDUtil.newHashSet(); WritableDataStore<double[]> probClusterIGivenX = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_SORTED, double[].class); int k = clusterCores.size(); double[] clusterWeights = new double[k]; computeFuzzyMembership(relation, clusterCores, noise, probClusterIGivenX, clusterWeights); // Initial estimate of covariances, to assign noise objects Vector[] means = new Vector[k]; Matrix[] covarianceMatrices = new Matrix[k], invCovMatr = new Matrix[k]; final double norm = MathUtil.powi(MathUtil.TWOPI, dim); double[] normDistrFactor = new double[k]; Arrays.fill(normDistrFactor, 1. / Math.sqrt(norm)); EM.recomputeCovarianceMatrices(relation, probClusterIGivenX, means, covarianceMatrices, dim); EM.computeInverseMatrixes(covarianceMatrices, invCovMatr, normDistrFactor, norm); assignUnassigned(relation, probClusterIGivenX, means, invCovMatr, clusterWeights, noise); double emNew = EM.assignProbabilitiesToInstances(relation, normDistrFactor, means, invCovMatr, clusterWeights, probClusterIGivenX); for(int it = 1; it <= maxEmIterations || maxEmIterations < 0; it++) { final double emOld = emNew; EM.recomputeCovarianceMatrices(relation, probClusterIGivenX, means, covarianceMatrices, dim); EM.computeInverseMatrixes(covarianceMatrices, invCovMatr, normDistrFactor, norm); // reassign probabilities emNew = EM.assignProbabilitiesToInstances(relation, normDistrFactor, means, invCovMatr, clusterWeights, probClusterIGivenX); if(LOG.isVerbose()) { LOG.verbose("iteration " + it + " - expectation value: " + emNew); } if((emNew - emOld) / emOld <= emDelta) { break; } } // Perform EM clustering. if(stepProgress != null) { stepProgress.beginStep(6, "Generating hard clustering.", LOG); } // Create a hard clustering, making sure each data point only is part of one // cluster, based on the best match from the membership matrix. ArrayList<ClusterCandidate> clusterCandidates = hardClustering(probClusterIGivenX, clusterCores, ids); if(stepProgress != null) { stepProgress.beginStep(7, "Looking for outliers and moving them to the noise set.", LOG); } // Outlier detection. Remove points from clusters that have a Mahalanobis // distance larger than the critical value of the ChiSquare distribution. findOutliers(relation, means, invCovMatr, clusterCandidates, dim - numuniform, noise); if(stepProgress != null) { stepProgress.beginStep(8, "Removing empty clusters.", LOG); } // Remove near-empty clusters. for(Iterator<ClusterCandidate> it = clusterCandidates.iterator(); it.hasNext();) { ClusterCandidate cand = it.next(); final int size = cand.ids.size(); if(size < minClusterSize) { noise.addDBIDs(cand.ids); it.remove(); } } // Relevant attribute computation. for(ClusterCandidate candidate : clusterCandidates) { // TODO Check all attributes previously deemed uniform (section 3.5). } if(stepProgress != null) { stepProgress.beginStep(9, "Generating final result.", LOG); } // Generate final output. Clustering<SubspaceModel<V>> result = new Clustering<>("P3C", "P3C"); for(int cluster = 0; cluster < clusterCandidates.size(); ++cluster) { ClusterCandidate candidate = clusterCandidates.get(cluster); CovarianceMatrix cvm = CovarianceMatrix.make(relation, candidate.ids); result.addToplevelCluster(new Cluster<>(candidate.ids, new SubspaceModel<>(new Subspace(candidate.dimensions), cvm.getMeanVector(relation)))); } LOG.verbose("Noise size: "+ noise.size()); if(noise.size() > 0) { result.addToplevelCluster(new Cluster<SubspaceModel<V>>(noise, true)); } if(stepProgress != null) { stepProgress.ensureCompleted(LOG); } return result; } /** * Compute the union of multiple DBID sets. * * @param parts Parts array * @param start Array start index * @param end Array end index (exclusive) * @return */ protected HashSetModifiableDBIDs unionDBIDs(final DBIDs[] parts, int start, int end) { int sum = 0; for(int i = start; i < end; i++) { sum += parts[i].size(); } HashSetModifiableDBIDs sids = DBIDUtil.newHashSet(sum); for(int i = start; i < end; i++) { sids.addDBIDs(parts[i]); } return sids; } /** * Partition the data set by repeated binary splitting. * * @param relation Relation * @param d Dimension * @param min Minimum * @param delta Step size * @param ids ID array * @param iter ID iterator * @param start ID interval start * @param end ID interval end * @param ps Partition interval start * @param pe Partition interval end * @param partitions */ private void partition(Relation<V> relation, int d, double min, double delta, ArrayDBIDs ids, DBIDArrayIter iter, int start, int end, int ps, int pe, DBIDs[] partitions) { final int ph = (ps + pe) >>> 1; final double split = min + ph * delta; // Perform binary search int ss = start, se = end - 1; while(ss < se) { final int sh = (ss + se) >>> 1; iter.seek(sh); // LOG.debugFinest("sh: " + sh); final double v = relation.get(iter).doubleValue(d); if(split < v) { if(ss < sh - 1) { se = sh - 1; } else { se = sh; break; } } else { if(sh < se) { ss = sh + 1; } else { ss = sh; break; } } } // LOG.debugFinest("ss: " + ss + " se: " + se + " start: " + start + // " end: " + // end); // start to ss (inclusive) are left, // ss + 1 to end (exclusive) are right. if(ps == ph - 1) { assert (partitions[ph] == null); ModifiableDBIDs pids = DBIDUtil.newHashSet(ss + 1 - start); iter.seek(start); for(int i = start; i <= ss; i++, iter.advance()) { pids.add(iter); } partitions[ps] = pids; } else { partition(relation, d, min, delta, ids, iter, start, ss + 1, ps, ph, partitions); } if(ph == pe - 1) { assert (partitions[ph] == null); ModifiableDBIDs pids = DBIDUtil.newHashSet(end - (ss + 1)); iter.seek(start); for(int i = ss + 1; i < end; i++, iter.advance()) { pids.add(iter); } partitions[ph] = pids; } else { partition(relation, d, min, delta, ids, iter, ss + 1, end, ph, pe, partitions); } } /** * Performs a ChiSquared test to determine whether an attribute has a uniform * distribution. * * @param parts Data partitions. * @param marked the marked bins that should be ignored. * @param card Cardinality * @return Position of maximum, or -1 when uniform. */ private int chiSquaredUniformTest(DBIDs[] parts, long[] marked, int card) { // Remaining number of bins. final int binCount = parts.length - card; // Get global mean over all unmarked bins. int max = 0, maxpos = -1; MeanVariance mv = new MeanVariance(); for(int i = 0; i < parts.length; i++) { // Ignore already marked bins. if(BitsUtil.get(marked, i)) { continue; } final int binSupport = parts[i].size(); mv.put(binSupport); if(binSupport > max) { max = binSupport; maxpos = i; } } if(mv.getCount() < 1.) { return -1; } // ChiSquare statistic is the naive variance of the sizes! double chiSquare = mv.getNaiveVariance(); if((1 - 0.001) < ChiSquaredDistribution.cdf(chiSquare, Math.max(1, binCount - card - 1))) { return maxpos; } return -1; } /** * Computes a fuzzy membership with the weights based on which cluster cores * each data point is part of. * * @param relation Data relation * @param clusterCores the cluster cores. * @param unassigned set to which to add unassigned points. * @param probClusterIGivenX Membership probabilities. * @param clusterWeights Cluster weights */ private void computeFuzzyMembership(Relation<V> relation, ArrayList<Signature> clusterCores, ModifiableDBIDs unassigned, WritableDataStore<double[]> probClusterIGivenX, double[] clusterWeights) { final int n = relation.size(); final int k = clusterCores.size(); for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { int count = 0; double[] weights = new double[k]; for(int cluster = 0; cluster < k; ++cluster) { if(clusterCores.get(cluster).ids.contains(iter)) { weights[cluster] = 1.; ++count; } } // Set value(s) in membership matrix. if(count > 0) { // Rescale. VMath.timesEquals(weights, 1. / count); VMath.plusTimesEquals(clusterWeights, weights, 1. / n); } else { // Does not match any cluster, mark it. unassigned.add(iter); } probClusterIGivenX.put(iter, weights); } } /** * Assign unassigned objects to best candidate based on shortest Mahalanobis * distance. * * @param relation Data relation * @param probClusterIGivenX fuzzy membership matrix. * @param means Cluster means. * @param invCovMatr Cluster covariance matrices. * @param clusterWeights * @param assigned mapping of matrix row to DBID. * @param unassigned the list of points not yet assigned. */ private void assignUnassigned(Relation<V> relation, WritableDataStore<double[]> probClusterIGivenX, Vector[] means, Matrix[] invCovMatr, double[] clusterWeights, ModifiableDBIDs unassigned) { if(unassigned.size() == 0) { return; } final int k = means.length; double pweight = 1. / relation.size(); for(DBIDIter iter = unassigned.iter(); iter.valid(); iter.advance()) { // Find the best matching known cluster core using the Mahalanobis // distance. Vector v = relation.get(iter).getColumnVector(); int bestCluster = -1; double minDistance = Double.POSITIVE_INFINITY; for(int c = 0; c < k; ++c) { final double distance = MathUtil.mahalanobisDistance(invCovMatr[c], v.minus(means[c])); if(distance < minDistance) { minDistance = distance; bestCluster = c; } } // Assign to best core. double[] weights = new double[k]; weights[bestCluster] = 1.0; clusterWeights[bestCluster] += pweight; probClusterIGivenX.put(iter, weights); } // Clear the list of unassigned objects. unassigned.clear(); } /** * Creates a hard clustering from the specified soft membership matrix. * * @param probClusterIGivenX the membership matrix. * @param dbids mapping matrix row to DBID. * @return a hard clustering based on the matrix. */ private ArrayList<ClusterCandidate> hardClustering(WritableDataStore<double[]> probClusterIGivenX, List<Signature> clusterCores, ArrayModifiableDBIDs dbids) { final int k = clusterCores.size(); // Initialize cluster sets. ArrayList<ClusterCandidate> candidates = new ArrayList<>(); for(Signature sig : clusterCores) { candidates.add(new ClusterCandidate(sig)); } // Perform hard partitioning, assigning each data point only to one cluster, // namely that one it is most likely to belong to. for(DBIDIter iter = dbids.iter(); iter.valid(); iter.advance()) { final double[] probs = probClusterIGivenX.get(iter); int bestCluster = 0; double bestProbability = probs[0]; for(int c = 1; c < k; ++c) { if(probs[c] > bestProbability) { bestCluster = c; bestProbability = probs[c]; } } candidates.get(bestCluster).ids.add(iter); } return candidates; } /** * Performs outlier detection by testing the Mahalanobis distance of each * point in a cluster against the critical value of the ChiSquared * distribution with as many degrees of freedom as the cluster has relevant * attributes. * * @param relation Data relation * @param means Cluster means * @param invCovMatr Inverse covariance matrixes * @param clusterCandidates the list of clusters to check. * @param nonUniformDimensionCount the number of dimensions to consider when * testing. * @param noise the set to which to add points deemed outliers. */ private void findOutliers(Relation<V> relation, Vector[] means, Matrix[] invCovMatr, ArrayList<ClusterCandidate> clusterCandidates, int nonUniformDimensionCount, ModifiableDBIDs noise) { final int k = clusterCandidates.size(); for(int c = 0; c < k; ++c) { final ClusterCandidate candidate = clusterCandidates.get(c); if(candidate.ids.size() < 2) { continue; } for(DBIDMIter iter = candidate.ids.iter(); iter.valid(); iter.advance()) { final Vector mean = means[c]; final Vector delta = relation.get(iter).getColumnVector().minusEquals(mean); final Matrix invCov = invCovMatr[c]; final double distance = MathUtil.mahalanobisDistance(invCov, delta); final int dof = candidate.dimensions.cardinality() - 1; if((1 - 0.001) <= ChiSquaredDistribution.cdf(distance, dof)) { // Outlier, remove it and add it to the outlier set. noise.add(iter); iter.remove(); } } } } /** * Generates a merged signature of this and another one, where the other * signature must be a 1-signature. * * @param first First signature. * @param second Second signature, must be a 1-signature. * @param numBins Number of bins per dimension. * @return the merged signature, or null if the merge failed. */ protected Signature mergeSignatures(Signature first, Signature second, int numBins) { int d2 = -1; for(int i = 0; i < second.spec.length; i += 2) { if(second.spec[i] >= 0) { assert (d2 == -1) : "Merging with non-1-signature?!?"; d2 = i; } } assert (d2 >= 0) : "Merging with empty signature?"; // Skip the merge if the interval is already part of the signature. if(first.spec[d2] >= 0) { return null; } // Definition 3, Condition 1: // True support: final ModifiableDBIDs intersection = DBIDUtil.intersection(first.ids, second.ids); final int support = intersection.size(); // Interval width, computed using selected number of bins / total bins double width = (second.spec[d2 + 1] + 1 - second.spec[d2]) / (double) numBins; // Expected size thus: double expect = support * width; if(support <= expect) { return null; } if(PoissonDistribution.rawProbability(support, expect) >= poissonThreshold) { return null; } // Create merged signature. int[] spec = first.spec.clone(); spec[d2] = second.spec[d2]; spec[d2 + 1] = second.spec[d2]; return new Signature(spec, intersection); } private static class Signature implements Cloneable { /** * Subspace specification */ int[] spec; /** * Object ids. */ DBIDs ids; /** * Pruning flag. */ boolean prune = false; /** * Constructor. * * @param spec Subspace specification * @param ids IDs. */ private Signature(int[] spec, DBIDs ids) { super(); this.spec = spec; this.ids = ids; } @Override protected Signature clone() throws CloneNotSupportedException { Signature c = (Signature) super.clone(); c.spec = this.spec.clone(); c.ids = null; return c; } } /** * This class is used to represent potential clusters. * * TODO: Documentation. */ private static class ClusterCandidate { public final BitSet dimensions; public final ModifiableDBIDs ids; public ClusterCandidate(Signature clusterCore) { this.dimensions = new BitSet(clusterCore.spec.length >> 1); for(int i = 0; i < clusterCore.spec.length; i += 2) { this.dimensions.set(i >> 1); } this.ids = DBIDUtil.newArray(clusterCore.ids.size()); } } @Override public TypeInformation[] getInputTypeRestriction() { return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD); } @Override protected Logging getLogger() { return LOG; } /** * Parameterization class. * * @author Florian Nuecke * * @apiviz.exclude */ public static class Parameterizer<V extends NumberVector<?>> extends AbstractParameterizer { /** * Parameter for the poisson test threshold. */ public static final OptionID POISSON_THRESHOLD_ID = new OptionID("p3c.threshold", "The threshold value for the poisson test used when merging signatures."); /** * Maximum number of iterations for the EM step. */ public static final OptionID MAX_EM_ITERATIONS_ID = new OptionID("p3c.em.maxiter", "The maximum number of iterations for the EM step. Use -1 to run until delta convergence."); /** * Threshold when to stop EM iterations. */ public static final OptionID EM_DELTA_ID = new OptionID("p3c.em.delta", "The change delta for the EM step below which to stop."); /** * Minimum cluster size for noise flagging. (Not existant in the original * publication). */ public static final OptionID MIN_CLUSTER_SIZE_ID = new OptionID("p3c.minsize", "The minimum size of a cluster, otherwise it is seen as noise (this is a cheat, it is not mentioned in the paper)."); /** * Parameter for the poisson test threshold. */ protected double poissonThreshold; /** * Maximum number of iterations for the EM step. */ protected int maxEmIterations; /** * Threshold when to stop EM iterations. */ protected double emDelta; /** * Minimum cluster size for noise flagging. (Not existant in the original * publication). */ protected int minClusterSize; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); { DoubleParameter param = new DoubleParameter(POISSON_THRESHOLD_ID, 1.e-20); param.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if(config.grab(param)) { poissonThreshold = param.getValue(); } } { IntParameter param = new IntParameter(MAX_EM_ITERATIONS_ID, 20); param.addConstraint(CommonConstraints.GREATER_EQUAL_MINUSONE_INT); if(config.grab(param)) { maxEmIterations = param.getValue(); } } { DoubleParameter param = new DoubleParameter(EM_DELTA_ID, 1.e-5); param.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if(config.grab(param)) { emDelta = param.getValue(); } } { IntParameter param = new IntParameter(MIN_CLUSTER_SIZE_ID, 1); param.addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if(config.grab(param)) { minClusterSize = param.getValue(); } } } @Override protected P3C<V> makeInstance() { return new P3C<>(poissonThreshold, maxEmIterations, emDelta, minClusterSize); } } }
src/experimentalcode/students/nuecke/algorithm/clustering/subspace/P3C.java
package experimentalcode.students.nuecke.algorithm.clustering.subspace; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.List; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.clustering.EM; import de.lmu.ifi.dbs.elki.data.Cluster; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.Subspace; import de.lmu.ifi.dbs.elki.data.VectorUtil; import de.lmu.ifi.dbs.elki.data.VectorUtil.SortDBIDsBySingleDimension; import de.lmu.ifi.dbs.elki.data.model.SubspaceModel; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore; import de.lmu.ifi.dbs.elki.database.ids.ArrayDBIDs; import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.DBIDArrayIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDMIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.ids.HashSetModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.ModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.database.relation.RelationUtil; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.logging.progress.StepProgress; import de.lmu.ifi.dbs.elki.math.MathUtil; import de.lmu.ifi.dbs.elki.math.MeanVariance; import de.lmu.ifi.dbs.elki.math.linearalgebra.CovarianceMatrix; import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.elki.math.linearalgebra.VMath; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; import de.lmu.ifi.dbs.elki.math.statistics.distribution.ChiSquaredDistribution; import de.lmu.ifi.dbs.elki.math.statistics.distribution.PoissonDistribution; import de.lmu.ifi.dbs.elki.utilities.BitsUtil; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.documentation.Title; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; /** * P3C: A Robust Projected Clustering Algorithm. * * <p> * Reference: <br/> * Gabriela Moise, Jörg Sander, Martin Ester<br /> * P3C: A Robust Projected Clustering Algorithm.<br/> * In: Proc. Sixth International Conference on Data Mining (ICDM '06) * </p> * * @author Florian Nuecke * @author Erich Schubert * * @apiviz.has SubspaceModel * * @param <V> the type of NumberVector handled by this Algorithm. */ @Title("P3C: A Robust Projected Clustering Algorithm.") @Reference(authors = "Gabriela Moise, Jörg Sander, Martin Ester", title = "P3C: A Robust Projected Clustering Algorithm", booktitle = "Proc. Sixth International Conference on Data Mining (ICDM '06)", url = "http://dx.doi.org/10.1109/ICDM.2006.123") public class P3C<V extends NumberVector<?>> extends AbstractAlgorithm<Clustering<SubspaceModel<V>>> { /** * The logger for this class. */ private static final Logging LOG = Logging.getLogger(P3C.class); /** * Minimum Log Likelihood. */ private static final double MIN_LOGLIKELIHOOD = -100000; /** * Parameter for the Poisson test threshold. */ protected double poissonThreshold; /** * Maximum number of iterations for the EM step. */ protected int maxEmIterations; /** * Threshold when to stop EM iterations. */ protected double emDelta; /** * Minimum cluster size for noise flagging. (Not existing in the original * publication). */ protected int minClusterSize; /** * Maximum number of EM iterations. */ protected int maxiter = 100; /** * Sets up a new instance of the algorithm's environment. */ public P3C(double poissonThreshold, int maxEmIterations, double emDelta, int minClusterSize) { super(); this.poissonThreshold = poissonThreshold; this.maxEmIterations = maxEmIterations; this.emDelta = emDelta; this.minClusterSize = minClusterSize; } /** * Performs the P3C algorithm on the given Database. */ public Clustering<SubspaceModel<V>> run(Database database, Relation<V> relation) { final int dim = RelationUtil.dimensionality(relation); // Overall progress. StepProgress stepProgress = LOG.isVerbose() ? new StepProgress(8) : null; if (stepProgress != null) { stepProgress.beginStep(1, "Grid-partitioning data.", LOG); } // Desired number of bins, as per Sturge: final int binCount = (int) Math.ceil(1 + (Math.log(relation.size()) / MathUtil.LOG2)); // Perform 1-dimensional projections, and split into bins. DBIDs[][] partitions = new DBIDs[dim][binCount]; ArrayModifiableDBIDs ids = DBIDUtil.newArray(relation.getDBIDs()); DBIDArrayIter iter = ids.iter(); SortDBIDsBySingleDimension sorter = new VectorUtil.SortDBIDsBySingleDimension(relation, 0); for (int d = 0; d < dim; d++) { sorter.setDimension(d); ids.sort(sorter); // Minimum: iter.seek(0); double min = relation.get(iter).doubleValue(d); // Extend: iter.seek(ids.size() - 1); double delta = (relation.get(iter).doubleValue(d) - min) / binCount; if (delta > 0.) { partition(relation, d, min, delta, ids, iter, 0, ids.size(), 0, binCount, partitions[d]); if (LOG.isDebugging()) { StringBuilder buf = new StringBuilder(); buf.append("Partition sizes of dim ").append(d).append(": "); int sum = 0; for (DBIDs p : partitions[d]) { buf.append(p.size()).append(' '); sum += p.size(); } LOG.debug(buf.toString()); assert (sum == ids.size()); } } else { partitions[d] = null; // Flag whole dimension as bad } } if (stepProgress != null) { stepProgress.beginStep(2, "Searching for non-uniform bins in support histograms.", LOG); } // Set markers for each attribute until they're all deemed uniform. final long[][] markers = new long[dim][]; int numuniform = 0; for (int d = 0; d < dim; d++) { final DBIDs[] parts = partitions[d]; if (parts == null) { continue; // Never mark any on constant dimensions. } final long[] marked = markers[d] = BitsUtil.zero(binCount); int card = 0; while (card < dim - 1) { // Find bin with largest support, test only the dimensions that were not // previously marked. int bestBin = chiSquaredUniformTest(parts, marked, card); if (bestBin < 0) { numuniform++; break; // Uniform } BitsUtil.setI(marked, bestBin); card++; } if (LOG.isDebugging()) { LOG.debug("Marked bins in dim " + d + ": " + BitsUtil.toString(marked, dim)); } } if (stepProgress != null) { stepProgress.beginStep(3, "Merging marked bins to 1-signatures.", LOG); } // Generate projected p-signature intervals. ArrayList<Signature> signatures = new ArrayList<>(); for (int d = 0; d < dim; d++) { final DBIDs[] parts = partitions[d]; if (parts == null) { continue; // Never mark any on constant dimensions. } final long[] marked = markers[d]; // Find sequences of 1s in marked. for (int start = BitsUtil.nextSetBit(marked, 0); start >= 0;) { int end = BitsUtil.nextClearBit(marked, start + 1) - 1; if (end == -1) { end = dim; } int[] signature = new int[dim << 1]; Arrays.fill(signature, -1); signature[d << 1] = start; signature[(d << 1) + 1] = end - 1; // inclusive HashSetModifiableDBIDs sids = unionDBIDs(parts, start, end /* exclusive */); if (LOG.isDebugging()) { LOG.debug("1-signature: " + d + " " + start + "-" + end); } signatures.add(new Signature(signature, sids)); start = (end < dim) ? BitsUtil.nextSetBit(marked, end + 1) : -1; } } if (stepProgress != null) { stepProgress.beginStep(4, "Computing cluster cores from merged p-signatures.", LOG); } FiniteProgress mergeProgress = LOG.isVerbose() ? new FiniteProgress("1-signatures merges", signatures.size(), LOG) : null; // Merge to (p+1)-signatures (cluster cores). ArrayList<Signature> clusterCores = new ArrayList<>(signatures); // Try adding merge 1-signature with each cluster core. for (int i = 0; i < signatures.size(); ++i) { final Signature signature = signatures.get(i); // Don't merge with future signatures: final int end = clusterCores.size(); // Skip previous 1-signatures: merges are symmetrical. But include newly // created cluster cores (i.e. those resulting from previous merges). FiniteProgress submergeProgress = LOG.isVerbose() ? new FiniteProgress("p-signatures merges", end - (i + 1), LOG) : null; for (int j = i + 1; j < end; ++j) { final Signature first = clusterCores.get(j); final Signature merge = mergeSignatures(first, signature, binCount); if (merge != null) { // We add each potential core to the list to allow remaining // 1-signatures to try merging with this p-signature as well. clusterCores.add(merge); // Flag for removal. first.prune = true; signature.prune = true; } if (submergeProgress != null) { submergeProgress.incrementProcessed(LOG); } } if (submergeProgress != null) { submergeProgress.ensureCompleted(LOG); } if (mergeProgress != null) { mergeProgress.incrementProcessed(LOG); } } if (mergeProgress != null) { mergeProgress.ensureCompleted(LOG); } if (stepProgress != null) { stepProgress.beginStep(5, "Pruning incomplete cluster cores.", LOG); } // Prune cluster cores based on Definition 3, Condition 2. ArrayList<Signature> retain = new ArrayList<>(clusterCores.size()); for (Signature clusterCore : clusterCores) { if (!clusterCore.prune) { retain.add(clusterCore); } } clusterCores = retain; if (LOG.isVerbose()) { LOG.verbose("Number of cluster cores found: " + clusterCores.size()); } if (clusterCores.size() == 0) { stepProgress.setCompleted(LOG); // FIXME: return trivial noise clustering. return null; } if (stepProgress != null) { stepProgress.beginStep(5, "Refining cluster cores to clusters via EM.", LOG); } // Track objects not assigned to any cluster: ModifiableDBIDs noise = DBIDUtil.newHashSet(); WritableDataStore<double[]> probClusterIGivenX = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_SORTED, double[].class); int k = clusterCores.size(); double[] clusterWeights = new double[k]; computeFuzzyMembership(relation, clusterCores, noise, probClusterIGivenX, clusterWeights); // Initial estimate of covariances, to assign noise objects Vector[] means = new Vector[k]; Matrix[] covarianceMatrices = new Matrix[k], invCovMatr = new Matrix[k]; final double norm = MathUtil.powi(MathUtil.TWOPI, dim); double[] normDistrFactor = new double[k]; Arrays.fill(normDistrFactor, 1. / Math.sqrt(norm)); EM.recomputeCovarianceMatrices(relation, probClusterIGivenX, means, covarianceMatrices, dim); EM.computeInverseMatrixes(covarianceMatrices, invCovMatr, normDistrFactor, norm); assignUnassigned(relation, probClusterIGivenX, means, invCovMatr, clusterWeights, noise); double emNew = EM.assignProbabilitiesToInstances(relation, normDistrFactor, means, invCovMatr, clusterWeights, probClusterIGivenX); for (int it = 1; it <= maxiter || maxiter < 0; it++) { final double emOld = emNew; EM.recomputeCovarianceMatrices(relation, probClusterIGivenX, means, covarianceMatrices, dim); EM.computeInverseMatrixes(covarianceMatrices, invCovMatr, normDistrFactor, norm); // reassign probabilities emNew = EM.assignProbabilitiesToInstances(relation, normDistrFactor, means, invCovMatr, clusterWeights, probClusterIGivenX); if (LOG.isVerbose()) { LOG.verbose("iteration " + it + " - expectation value: " + emNew); } if (Math.abs(emOld - emNew) <= emDelta) { break; } } // Perform EM clustering. if (stepProgress != null) { stepProgress.beginStep(6, "Generating hard clustering.", LOG); } // Create a hard clustering, making sure each data point only is part of one // cluster, based on the best match from the membership matrix. ArrayList<ClusterCandidate> clusterCandidates = hardClustering(probClusterIGivenX, clusterCores, ids); if (stepProgress != null) { stepProgress.beginStep(7, "Looking for outliers and moving them to the noise set.", LOG); } // Outlier detection. Remove points from clusters that have a Mahalanobis // distance larger than the critical value of the ChiSquare distribution. findOutliers(relation, means, invCovMatr, clusterCandidates, dim - numuniform, noise); if (stepProgress != null) { stepProgress.beginStep(8, "Removing empty clusters.", LOG); } // Remove near-empty clusters. for (Iterator<ClusterCandidate> it = clusterCandidates.iterator(); it.hasNext();) { ClusterCandidate cand = it.next(); final int size = cand.ids.size(); if (size < minClusterSize) { noise.addDBIDs(cand.ids); it.remove(); } } // Relevant attribute computation. for (ClusterCandidate candidate : clusterCandidates) { // TODO Check all attributes previously deemed uniform (section 3.5). } if (stepProgress != null) { stepProgress.beginStep(9, "Generating final result.", LOG); } // Generate final output. Clustering<SubspaceModel<V>> result = new Clustering<>("P3C", "P3C"); if (noise.size() > 0) { result.addToplevelCluster(new Cluster<SubspaceModel<V>>(noise, true)); } for (int cluster = 0; cluster < clusterCandidates.size(); ++cluster) { ClusterCandidate candidate = clusterCandidates.get(cluster); CovarianceMatrix cvm = CovarianceMatrix.make(relation, candidate.ids); result.addToplevelCluster(new Cluster<>(candidate.ids, new SubspaceModel<>(new Subspace(candidate.dimensions), cvm.getMeanVector(relation)))); } if (stepProgress != null) { stepProgress.ensureCompleted(LOG); } return result; } /** * Compute the union of multiple DBID sets. * * @param parts Parts array * @param start Array start index * @param end Array end index (exclusive) * @return */ protected HashSetModifiableDBIDs unionDBIDs(final DBIDs[] parts, int start, int end) { int sum = 0; for (int i = start; i < end; i++) { sum += parts[i].size(); } HashSetModifiableDBIDs sids = DBIDUtil.newHashSet(sum); for (int i = start; i < end; i++) { sids.addDBIDs(parts[i]); } return sids; } /** * Partition the data set by repeated binary splitting. * * @param relation Relation * @param d Dimension * @param min Minimum * @param delta Step size * @param ids ID array * @param iter ID iterator * @param start ID interval start * @param end ID interval end * @param ps Partition interval start * @param pe Partition interval end * @param partitions */ private void partition(Relation<V> relation, int d, double min, double delta, ArrayDBIDs ids, DBIDArrayIter iter, int start, int end, int ps, int pe, DBIDs[] partitions) { final int ph = (ps + pe) >>> 1; final double split = min + ph * delta; // Perform binary search int ss = start, se = end - 1; while (ss < se) { final int sh = (ss + se) >>> 1; iter.seek(sh); // LOG.debugFinest("sh: " + sh); final double v = relation.get(iter).doubleValue(d); if (split < v) { if (ss < sh - 1) { se = sh - 1; } else { se = sh; break; } } else { if (sh < se) { ss = sh + 1; } else { ss = sh; break; } } } // LOG.debugFinest("ss: " + ss + " se: " + se + " start: " + start + // " end: " + // end); // start to ss (inclusive) are left, // ss + 1 to end (exclusive) are right. if (ps == ph - 1) { assert (partitions[ph] == null); ModifiableDBIDs pids = DBIDUtil.newHashSet(ss + 1 - start); iter.seek(start); for (int i = start; i <= ss; i++, iter.advance()) { pids.add(iter); } partitions[ps] = pids; } else { partition(relation, d, min, delta, ids, iter, start, ss + 1, ps, ph, partitions); } if (ph == pe - 1) { assert (partitions[ph] == null); ModifiableDBIDs pids = DBIDUtil.newHashSet(end - (ss + 1)); iter.seek(start); for (int i = ss + 1; i < end; i++, iter.advance()) { pids.add(iter); } partitions[ph] = pids; } else { partition(relation, d, min, delta, ids, iter, ss + 1, end, ph, pe, partitions); } } /** * Performs a ChiSquared test to determine whether an attribute has a uniform * distribution. * * @param parts Data partitions. * @param marked the marked bins that should be ignored. * @param card Cardinality * @return Position of maximum, or -1 when uniform. */ private int chiSquaredUniformTest(DBIDs[] parts, long[] marked, int card) { // Remaining number of bins. final int binCount = parts.length - card; // Get global mean over all unmarked bins. int max = 0, maxpos = -1; MeanVariance mv = new MeanVariance(); for (int i = 0; i < parts.length; i++) { // Ignore already marked bins. if (BitsUtil.get(marked, i)) { continue; } final int binSupport = parts[i].size(); mv.put(binSupport); if (binSupport > max) { max = binSupport; maxpos = i; } } if (mv.getCount() < 1.) { return -1; } // ChiSquare statistic is the naive variance of the sizes! double chiSquare = mv.getNaiveVariance(); if ((1 - 0.001) < ChiSquaredDistribution.cdf(chiSquare, Math.max(1, binCount - card - 1))) { return maxpos; } return -1; } /** * Computes a fuzzy membership with the weights based on which cluster cores * each data point is part of. * * @param relation Data relation * @param clusterCores the cluster cores. * @param unassigned set to which to add unassigned points. * @param probClusterIGivenX Membership probabilities. * @param clusterWeights Cluster weights */ private void computeFuzzyMembership(Relation<V> relation, ArrayList<Signature> clusterCores, ModifiableDBIDs unassigned, WritableDataStore<double[]> probClusterIGivenX, double[] clusterWeights) { final int n = relation.size(); final int k = clusterCores.size(); for (DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { int count = 0; double[] weights = new double[k]; for (int cluster = 0; cluster < k; ++cluster) { if (clusterCores.get(cluster).ids.contains(iter)) { weights[cluster] = 1.; ++count; } } // Set value(s) in membership matrix. if (count > 0) { // Rescale. VMath.timesEquals(weights, 1. / count); VMath.plusTimesEquals(clusterWeights, weights, 1. / n); } else { // Does not match any cluster, mark it. unassigned.add(iter); } probClusterIGivenX.put(iter, weights); } } /** * Assign unassigned objects to best candidate based on shortest Mahalanobis * distance. * * @param relation Data relation * @param probClusterIGivenX fuzzy membership matrix. * @param means Cluster means. * @param invCovMatr Cluster covariance matrices. * @param clusterWeights * @param assigned mapping of matrix row to DBID. * @param unassigned the list of points not yet assigned. */ private void assignUnassigned(Relation<V> relation, WritableDataStore<double[]> probClusterIGivenX, Vector[] means, Matrix[] invCovMatr, double[] clusterWeights, ModifiableDBIDs unassigned) { if (unassigned.size() == 0) { return; } final int k = means.length; double pweight = 1. / relation.size(); for (DBIDIter iter = unassigned.iter(); iter.valid(); iter.advance()) { // Find the best matching known cluster core using the Mahalanobis // distance. Vector v = relation.get(iter).getColumnVector(); int bestCluster = -1; double minDistance = Double.POSITIVE_INFINITY; for (int c = 0; c < k; ++c) { final double distance = MathUtil.mahalanobisDistance(invCovMatr[c], v.minus(means[c])); if (distance < minDistance) { minDistance = distance; bestCluster = c; } } // Assign to best core. double[] weights = new double[k]; weights[bestCluster] = 1.0; clusterWeights[bestCluster] += pweight; probClusterIGivenX.put(iter, weights); } // Clear the list of unassigned objects. unassigned.clear(); } /** * Creates a hard clustering from the specified soft membership matrix. * * @param probClusterIGivenX the membership matrix. * @param dbids mapping matrix row to DBID. * @return a hard clustering based on the matrix. */ private ArrayList<ClusterCandidate> hardClustering(WritableDataStore<double[]> probClusterIGivenX, List<Signature> clusterCores, ArrayModifiableDBIDs dbids) { final int k = clusterCores.size(); // Initialize cluster sets. ArrayList<ClusterCandidate> candidates = new ArrayList<>(); for (Signature sig : clusterCores) { candidates.add(new ClusterCandidate(sig)); } // Perform hard partitioning, assigning each data point only to one cluster, // namely that one it is most likely to belong to. for (DBIDIter iter = dbids.iter(); iter.valid(); iter.advance()) { final double[] probs = probClusterIGivenX.get(iter); int bestCluster = 0; double bestProbability = probs[0]; for (int c = 1; c < k; ++c) { if (probs[c] > bestProbability) { bestCluster = c; bestProbability = probs[c]; } } candidates.get(bestCluster).ids.add(iter); } return candidates; } /** * Performs outlier detection by testing the mahalanobis distance of each * point in a cluster against the critical value of the ChiSquared * distribution with as many degrees of freedom as the cluster has relevant * attributes. * * @param relation Data relation * @param means Cluster means * @param invCovMatr Inverse covariance matrixes * @param clusterCandidates the list of clusters to check. * @param nonUniformDimensionCount the number of dimensions to consider when * testing. * @param noise the set to which to add points deemed outliers. */ private void findOutliers(Relation<V> relation, Vector[] means, Matrix[] invCovMatr, ArrayList<ClusterCandidate> clusterCandidates, int nonUniformDimensionCount, ModifiableDBIDs noise) { final int k = clusterCandidates.size(); for (int c = 0; c < k; ++c) { final ClusterCandidate candidate = clusterCandidates.get(c); if (candidate.ids.size() < 2) { continue; } for (DBIDMIter iter = candidate.ids.iter(); iter.valid(); iter.advance()) { final Vector mean = means[c]; final Vector delta = relation.get(iter).getColumnVector().minusEquals(mean); final Matrix invCov = invCovMatr[c]; final double distance = MathUtil.mahalanobisDistance(invCov, delta); final int dof = candidate.dimensions.cardinality() - 1; if ((1 - 0.001) <= ChiSquaredDistribution.cdf(distance, dof)) { // Outlier, remove it and add it to the outlier set. noise.add(iter); iter.remove(); } } } } /** * Generates a merged signature of this and another one, where the other * signature must be a 1-signature. * * @param first First signature. * @param second Second signature, must be a 1-signature. * @param numBins Number of bins per dimension. * @return the merged signature, or null if the merge failed. */ protected Signature mergeSignatures(Signature first, Signature second, int numBins) { int d2 = -1; for (int i = 0; i < second.spec.length; i += 2) { if (second.spec[i] >= 0) { assert (d2 == -1) : "Merging with non-1-signature?!?"; d2 = i; } } assert (d2 >= 0) : "Merging with empty signature?"; // Skip the merge if the interval is already part of the signature. if (first.spec[d2] >= 0) { return null; } // Definition 3, Condition 1: // True support: final ModifiableDBIDs intersection = DBIDUtil.intersection(first.ids, second.ids); final int support = intersection.size(); // Interval width, computed using selected number of bins / total bins double width = (second.spec[d2 + 1] + 1 - second.spec[d2]) / (double) numBins; // Expected size thus: double expect = support * width; if (support <= expect) { return null; } if (PoissonDistribution.rawProbability(support, expect) >= poissonThreshold) { return null; } // Create merged signature. int[] spec = first.spec.clone(); spec[d2] = second.spec[d2]; spec[d2 + 1] = second.spec[d2]; return new Signature(spec, intersection); } private static class Signature implements Cloneable { /** * Subspace specification */ int[] spec; /** * Object ids. */ DBIDs ids; /** * Pruning flag. */ boolean prune = false; /** * Constructor. * * @param spec Subspace specification * @param ids IDs. */ private Signature(int[] spec, DBIDs ids) { super(); this.spec = spec; this.ids = ids; } @Override protected Signature clone() throws CloneNotSupportedException { Signature c = (Signature) super.clone(); c.spec = this.spec.clone(); c.ids = null; return c; } } /** * This class is used to represent potential clusters. * * TODO: Documentation. */ private static class ClusterCandidate { public final BitSet dimensions; public final ModifiableDBIDs ids; public ClusterCandidate(Signature clusterCore) { this.dimensions = new BitSet(clusterCore.spec.length >> 1); for (int i = 0; i < clusterCore.spec.length; i += 2) { this.dimensions.set(i >> 1); } this.ids = DBIDUtil.newArray(clusterCore.ids.size()); } } @Override public TypeInformation[] getInputTypeRestriction() { return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD); } @Override protected Logging getLogger() { return LOG; } /** * Parameterization class. * * @author Florian Nuecke * * @apiviz.exclude */ public static class Parameterizer<V extends NumberVector<?>> extends AbstractParameterizer { /** * Parameter for the poisson test threshold. */ public static final OptionID POISSON_THRESHOLD_ID = new OptionID("p3c.threshold", "The threshold value for the poisson test used when merging signatures."); /** * Maximum number of iterations for the EM step. */ public static final OptionID MAX_EM_ITERATIONS_ID = new OptionID("p3c.em.maxiter", "The maximum number of iterations for the EM step."); /** * Threshold when to stop EM iterations. */ public static final OptionID EM_DELTA_ID = new OptionID("p3c.em.delta", "The change delta for the EM step below which to stop."); /** * Minimum cluster size for noise flagging. (Not existant in the original * publication). */ public static final OptionID MIN_CLUSTER_SIZE_ID = new OptionID("p3c.minsize", "The minimum size of a cluster, otherwise it is seen as noise (this is a cheat, it is not mentioned in the paper)."); /** * Parameter for the poisson test threshold. */ protected double poissonThreshold; /** * Maximum number of iterations for the EM step. */ protected int maxEmIterations; /** * Threshold when to stop EM iterations. */ protected double emDelta; /** * Minimum cluster size for noise flagging. (Not existant in the original * publication). */ protected int minClusterSize; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); { DoubleParameter param = new DoubleParameter(POISSON_THRESHOLD_ID, 1.e-20); param.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if (config.grab(param)) { poissonThreshold = param.getValue(); } } { IntParameter param = new IntParameter(MAX_EM_ITERATIONS_ID, 10); param.addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if (config.grab(param)) { maxEmIterations = param.getValue(); } } { DoubleParameter param = new DoubleParameter(EM_DELTA_ID, 1.e-9); param.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if (config.grab(param)) { emDelta = param.getValue(); } } { IntParameter param = new IntParameter(MIN_CLUSTER_SIZE_ID, 1); param.addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if (config.grab(param)) { minClusterSize = param.getValue(); } } } @Override protected P3C<V> makeInstance() { return new P3C<>(poissonThreshold, maxEmIterations, emDelta, minClusterSize); } } }
Cleanups.
src/experimentalcode/students/nuecke/algorithm/clustering/subspace/P3C.java
Cleanups.
<ide><path>rc/experimentalcode/students/nuecke/algorithm/clustering/subspace/P3C.java <ide> protected int minClusterSize; <ide> <ide> /** <del> * Maximum number of EM iterations. <del> */ <del> protected int maxiter = 100; <del> <del> /** <ide> * Sets up a new instance of the algorithm's environment. <ide> */ <ide> public P3C(double poissonThreshold, int maxEmIterations, double emDelta, int minClusterSize) { <ide> // Overall progress. <ide> StepProgress stepProgress = LOG.isVerbose() ? new StepProgress(8) : null; <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(1, "Grid-partitioning data.", LOG); <ide> } <ide> <ide> ArrayModifiableDBIDs ids = DBIDUtil.newArray(relation.getDBIDs()); <ide> DBIDArrayIter iter = ids.iter(); <ide> SortDBIDsBySingleDimension sorter = new VectorUtil.SortDBIDsBySingleDimension(relation, 0); <del> for (int d = 0; d < dim; d++) { <add> for(int d = 0; d < dim; d++) { <ide> sorter.setDimension(d); <ide> ids.sort(sorter); <ide> // Minimum: <ide> // Extend: <ide> iter.seek(ids.size() - 1); <ide> double delta = (relation.get(iter).doubleValue(d) - min) / binCount; <del> if (delta > 0.) { <add> if(delta > 0.) { <ide> partition(relation, d, min, delta, ids, iter, 0, ids.size(), 0, binCount, partitions[d]); <del> if (LOG.isDebugging()) { <add> if(LOG.isDebugging()) { <ide> StringBuilder buf = new StringBuilder(); <ide> buf.append("Partition sizes of dim ").append(d).append(": "); <ide> int sum = 0; <del> for (DBIDs p : partitions[d]) { <add> for(DBIDs p : partitions[d]) { <ide> buf.append(p.size()).append(' '); <ide> sum += p.size(); <ide> } <ide> LOG.debug(buf.toString()); <ide> assert (sum == ids.size()); <ide> } <del> } else { <add> } <add> else { <ide> partitions[d] = null; // Flag whole dimension as bad <ide> } <ide> } <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(2, "Searching for non-uniform bins in support histograms.", LOG); <ide> } <ide> <ide> // Set markers for each attribute until they're all deemed uniform. <ide> final long[][] markers = new long[dim][]; <ide> int numuniform = 0; <del> for (int d = 0; d < dim; d++) { <add> for(int d = 0; d < dim; d++) { <ide> final DBIDs[] parts = partitions[d]; <del> if (parts == null) { <add> if(parts == null) { <ide> continue; // Never mark any on constant dimensions. <ide> } <ide> final long[] marked = markers[d] = BitsUtil.zero(binCount); <ide> int card = 0; <del> while (card < dim - 1) { <add> while(card < dim - 1) { <ide> // Find bin with largest support, test only the dimensions that were not <ide> // previously marked. <ide> int bestBin = chiSquaredUniformTest(parts, marked, card); <del> if (bestBin < 0) { <add> if(bestBin < 0) { <ide> numuniform++; <ide> break; // Uniform <ide> } <ide> BitsUtil.setI(marked, bestBin); <ide> card++; <ide> } <del> if (LOG.isDebugging()) { <add> if(LOG.isDebugging()) { <ide> LOG.debug("Marked bins in dim " + d + ": " + BitsUtil.toString(marked, dim)); <ide> } <ide> } <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(3, "Merging marked bins to 1-signatures.", LOG); <ide> } <ide> <ide> // Generate projected p-signature intervals. <ide> ArrayList<Signature> signatures = new ArrayList<>(); <del> for (int d = 0; d < dim; d++) { <add> for(int d = 0; d < dim; d++) { <ide> final DBIDs[] parts = partitions[d]; <del> if (parts == null) { <add> if(parts == null) { <ide> continue; // Never mark any on constant dimensions. <ide> } <ide> final long[] marked = markers[d]; <ide> // Find sequences of 1s in marked. <del> for (int start = BitsUtil.nextSetBit(marked, 0); start >= 0;) { <add> for(int start = BitsUtil.nextSetBit(marked, 0); start >= 0;) { <ide> int end = BitsUtil.nextClearBit(marked, start + 1) - 1; <del> if (end == -1) { <add> if(end == -1) { <ide> end = dim; <ide> } <ide> int[] signature = new int[dim << 1]; <ide> signature[d << 1] = start; <ide> signature[(d << 1) + 1] = end - 1; // inclusive <ide> HashSetModifiableDBIDs sids = unionDBIDs(parts, start, end /* exclusive */); <del> if (LOG.isDebugging()) { <add> if(LOG.isDebugging()) { <ide> LOG.debug("1-signature: " + d + " " + start + "-" + end); <ide> } <ide> signatures.add(new Signature(signature, sids)); <ide> } <ide> } <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(4, "Computing cluster cores from merged p-signatures.", LOG); <ide> } <ide> <ide> // Merge to (p+1)-signatures (cluster cores). <ide> ArrayList<Signature> clusterCores = new ArrayList<>(signatures); <ide> // Try adding merge 1-signature with each cluster core. <del> for (int i = 0; i < signatures.size(); ++i) { <add> for(int i = 0; i < signatures.size(); ++i) { <ide> final Signature signature = signatures.get(i); <ide> // Don't merge with future signatures: <ide> final int end = clusterCores.size(); <ide> // Skip previous 1-signatures: merges are symmetrical. But include newly <ide> // created cluster cores (i.e. those resulting from previous merges). <ide> FiniteProgress submergeProgress = LOG.isVerbose() ? new FiniteProgress("p-signatures merges", end - (i + 1), LOG) : null; <del> for (int j = i + 1; j < end; ++j) { <add> for(int j = i + 1; j < end; ++j) { <ide> final Signature first = clusterCores.get(j); <ide> final Signature merge = mergeSignatures(first, signature, binCount); <del> if (merge != null) { <add> if(merge != null) { <ide> // We add each potential core to the list to allow remaining <ide> // 1-signatures to try merging with this p-signature as well. <ide> clusterCores.add(merge); <del> // Flag for removal. <add> // Flag both "parents" for removal. <ide> first.prune = true; <ide> signature.prune = true; <ide> } <del> if (submergeProgress != null) { <add> if(submergeProgress != null) { <ide> submergeProgress.incrementProcessed(LOG); <ide> } <ide> } <del> if (submergeProgress != null) { <add> if(submergeProgress != null) { <ide> submergeProgress.ensureCompleted(LOG); <ide> } <del> if (mergeProgress != null) { <add> if(mergeProgress != null) { <ide> mergeProgress.incrementProcessed(LOG); <ide> } <ide> } <del> if (mergeProgress != null) { <add> if(mergeProgress != null) { <ide> mergeProgress.ensureCompleted(LOG); <ide> } <ide> <del> if (stepProgress != null) { <del> stepProgress.beginStep(5, "Pruning incomplete cluster cores.", LOG); <add> if(stepProgress != null) { <add> stepProgress.beginStep(5, "Pruning redundant cluster cores.", LOG); <ide> } <ide> <ide> // Prune cluster cores based on Definition 3, Condition 2. <ide> ArrayList<Signature> retain = new ArrayList<>(clusterCores.size()); <del> for (Signature clusterCore : clusterCores) { <del> if (!clusterCore.prune) { <add> for(Signature clusterCore : clusterCores) { <add> if(!clusterCore.prune) { <ide> retain.add(clusterCore); <ide> } <ide> } <ide> clusterCores = retain; <del> if (LOG.isVerbose()) { <add> if(LOG.isVerbose()) { <ide> LOG.verbose("Number of cluster cores found: " + clusterCores.size()); <ide> } <ide> <del> if (clusterCores.size() == 0) { <add> if(clusterCores.size() == 0) { <ide> stepProgress.setCompleted(LOG); <ide> // FIXME: return trivial noise clustering. <ide> return null; <ide> } <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(5, "Refining cluster cores to clusters via EM.", LOG); <ide> } <ide> <ide> assignUnassigned(relation, probClusterIGivenX, means, invCovMatr, clusterWeights, noise); <ide> <ide> double emNew = EM.assignProbabilitiesToInstances(relation, normDistrFactor, means, invCovMatr, clusterWeights, probClusterIGivenX); <del> for (int it = 1; it <= maxiter || maxiter < 0; it++) { <add> for(int it = 1; it <= maxEmIterations || maxEmIterations < 0; it++) { <ide> final double emOld = emNew; <ide> EM.recomputeCovarianceMatrices(relation, probClusterIGivenX, means, covarianceMatrices, dim); <ide> EM.computeInverseMatrixes(covarianceMatrices, invCovMatr, normDistrFactor, norm); <ide> // reassign probabilities <ide> emNew = EM.assignProbabilitiesToInstances(relation, normDistrFactor, means, invCovMatr, clusterWeights, probClusterIGivenX); <ide> <del> if (LOG.isVerbose()) { <add> if(LOG.isVerbose()) { <ide> LOG.verbose("iteration " + it + " - expectation value: " + emNew); <ide> } <del> if (Math.abs(emOld - emNew) <= emDelta) { <add> if((emNew - emOld) / emOld <= emDelta) { <ide> break; <ide> } <ide> } <ide> <ide> // Perform EM clustering. <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(6, "Generating hard clustering.", LOG); <ide> } <ide> <ide> // cluster, based on the best match from the membership matrix. <ide> ArrayList<ClusterCandidate> clusterCandidates = hardClustering(probClusterIGivenX, clusterCores, ids); <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(7, "Looking for outliers and moving them to the noise set.", LOG); <ide> } <ide> <ide> // distance larger than the critical value of the ChiSquare distribution. <ide> findOutliers(relation, means, invCovMatr, clusterCandidates, dim - numuniform, noise); <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(8, "Removing empty clusters.", LOG); <ide> } <ide> <ide> // Remove near-empty clusters. <del> for (Iterator<ClusterCandidate> it = clusterCandidates.iterator(); it.hasNext();) { <add> for(Iterator<ClusterCandidate> it = clusterCandidates.iterator(); it.hasNext();) { <ide> ClusterCandidate cand = it.next(); <ide> final int size = cand.ids.size(); <del> if (size < minClusterSize) { <add> if(size < minClusterSize) { <ide> noise.addDBIDs(cand.ids); <ide> it.remove(); <ide> } <ide> } <ide> <ide> // Relevant attribute computation. <del> for (ClusterCandidate candidate : clusterCandidates) { <add> for(ClusterCandidate candidate : clusterCandidates) { <ide> // TODO Check all attributes previously deemed uniform (section 3.5). <ide> } <ide> <del> if (stepProgress != null) { <add> if(stepProgress != null) { <ide> stepProgress.beginStep(9, "Generating final result.", LOG); <ide> } <ide> <ide> // Generate final output. <ide> Clustering<SubspaceModel<V>> result = new Clustering<>("P3C", "P3C"); <del> if (noise.size() > 0) { <del> result.addToplevelCluster(new Cluster<SubspaceModel<V>>(noise, true)); <del> } <del> for (int cluster = 0; cluster < clusterCandidates.size(); ++cluster) { <add> for(int cluster = 0; cluster < clusterCandidates.size(); ++cluster) { <ide> ClusterCandidate candidate = clusterCandidates.get(cluster); <ide> CovarianceMatrix cvm = CovarianceMatrix.make(relation, candidate.ids); <ide> result.addToplevelCluster(new Cluster<>(candidate.ids, new SubspaceModel<>(new Subspace(candidate.dimensions), cvm.getMeanVector(relation)))); <ide> } <del> <del> if (stepProgress != null) { <add> LOG.verbose("Noise size: "+ noise.size()); <add> if(noise.size() > 0) { <add> result.addToplevelCluster(new Cluster<SubspaceModel<V>>(noise, true)); <add> } <add> <add> if(stepProgress != null) { <ide> stepProgress.ensureCompleted(LOG); <ide> } <ide> <ide> */ <ide> protected HashSetModifiableDBIDs unionDBIDs(final DBIDs[] parts, int start, int end) { <ide> int sum = 0; <del> for (int i = start; i < end; i++) { <add> for(int i = start; i < end; i++) { <ide> sum += parts[i].size(); <ide> } <ide> HashSetModifiableDBIDs sids = DBIDUtil.newHashSet(sum); <del> for (int i = start; i < end; i++) { <add> for(int i = start; i < end; i++) { <ide> sids.addDBIDs(parts[i]); <ide> } <ide> return sids; <ide> final double split = min + ph * delta; <ide> // Perform binary search <ide> int ss = start, se = end - 1; <del> while (ss < se) { <add> while(ss < se) { <ide> final int sh = (ss + se) >>> 1; <ide> iter.seek(sh); <ide> // LOG.debugFinest("sh: " + sh); <ide> final double v = relation.get(iter).doubleValue(d); <del> if (split < v) { <del> if (ss < sh - 1) { <add> if(split < v) { <add> if(ss < sh - 1) { <ide> se = sh - 1; <del> } else { <add> } <add> else { <ide> se = sh; <ide> break; <ide> } <del> } else { <del> if (sh < se) { <add> } <add> else { <add> if(sh < se) { <ide> ss = sh + 1; <del> } else { <add> } <add> else { <ide> ss = sh; <ide> break; <ide> } <ide> // end); <ide> // start to ss (inclusive) are left, <ide> // ss + 1 to end (exclusive) are right. <del> if (ps == ph - 1) { <add> if(ps == ph - 1) { <ide> assert (partitions[ph] == null); <ide> ModifiableDBIDs pids = DBIDUtil.newHashSet(ss + 1 - start); <ide> iter.seek(start); <del> for (int i = start; i <= ss; i++, iter.advance()) { <add> for(int i = start; i <= ss; i++, iter.advance()) { <ide> pids.add(iter); <ide> } <ide> partitions[ps] = pids; <del> } else { <add> } <add> else { <ide> partition(relation, d, min, delta, ids, iter, start, ss + 1, ps, ph, partitions); <ide> } <del> if (ph == pe - 1) { <add> if(ph == pe - 1) { <ide> assert (partitions[ph] == null); <ide> ModifiableDBIDs pids = DBIDUtil.newHashSet(end - (ss + 1)); <ide> iter.seek(start); <del> for (int i = ss + 1; i < end; i++, iter.advance()) { <add> for(int i = ss + 1; i < end; i++, iter.advance()) { <ide> pids.add(iter); <ide> } <ide> partitions[ph] = pids; <del> } else { <add> } <add> else { <ide> partition(relation, d, min, delta, ids, iter, ss + 1, end, ph, pe, partitions); <ide> } <ide> } <ide> // Get global mean over all unmarked bins. <ide> int max = 0, maxpos = -1; <ide> MeanVariance mv = new MeanVariance(); <del> for (int i = 0; i < parts.length; i++) { <add> for(int i = 0; i < parts.length; i++) { <ide> // Ignore already marked bins. <del> if (BitsUtil.get(marked, i)) { <add> if(BitsUtil.get(marked, i)) { <ide> continue; <ide> } <ide> final int binSupport = parts[i].size(); <ide> mv.put(binSupport); <del> if (binSupport > max) { <add> if(binSupport > max) { <ide> max = binSupport; <ide> maxpos = i; <ide> } <ide> } <del> if (mv.getCount() < 1.) { <add> if(mv.getCount() < 1.) { <ide> return -1; <ide> } <ide> // ChiSquare statistic is the naive variance of the sizes! <ide> double chiSquare = mv.getNaiveVariance(); <ide> <del> if ((1 - 0.001) < ChiSquaredDistribution.cdf(chiSquare, Math.max(1, binCount - card - 1))) { <add> if((1 - 0.001) < ChiSquaredDistribution.cdf(chiSquare, Math.max(1, binCount - card - 1))) { <ide> return maxpos; <ide> } <ide> return -1; <ide> final int n = relation.size(); <ide> final int k = clusterCores.size(); <ide> <del> for (DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { <add> for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { <ide> int count = 0; <ide> double[] weights = new double[k]; <del> for (int cluster = 0; cluster < k; ++cluster) { <del> if (clusterCores.get(cluster).ids.contains(iter)) { <add> for(int cluster = 0; cluster < k; ++cluster) { <add> if(clusterCores.get(cluster).ids.contains(iter)) { <ide> weights[cluster] = 1.; <ide> ++count; <ide> } <ide> } <ide> <ide> // Set value(s) in membership matrix. <del> if (count > 0) { <add> if(count > 0) { <ide> // Rescale. <ide> VMath.timesEquals(weights, 1. / count); <ide> VMath.plusTimesEquals(clusterWeights, weights, 1. / n); <del> } else { <add> } <add> else { <ide> // Does not match any cluster, mark it. <ide> unassigned.add(iter); <ide> } <ide> * @param unassigned the list of points not yet assigned. <ide> */ <ide> private void assignUnassigned(Relation<V> relation, WritableDataStore<double[]> probClusterIGivenX, Vector[] means, Matrix[] invCovMatr, double[] clusterWeights, ModifiableDBIDs unassigned) { <del> if (unassigned.size() == 0) { <add> if(unassigned.size() == 0) { <ide> return; <ide> } <ide> final int k = means.length; <ide> double pweight = 1. / relation.size(); <ide> <del> for (DBIDIter iter = unassigned.iter(); iter.valid(); iter.advance()) { <add> for(DBIDIter iter = unassigned.iter(); iter.valid(); iter.advance()) { <ide> // Find the best matching known cluster core using the Mahalanobis <ide> // distance. <ide> Vector v = relation.get(iter).getColumnVector(); <ide> int bestCluster = -1; <ide> double minDistance = Double.POSITIVE_INFINITY; <del> for (int c = 0; c < k; ++c) { <add> for(int c = 0; c < k; ++c) { <ide> final double distance = MathUtil.mahalanobisDistance(invCovMatr[c], v.minus(means[c])); <del> if (distance < minDistance) { <add> if(distance < minDistance) { <ide> minDistance = distance; <ide> bestCluster = c; <ide> } <ide> <ide> // Initialize cluster sets. <ide> ArrayList<ClusterCandidate> candidates = new ArrayList<>(); <del> for (Signature sig : clusterCores) { <add> for(Signature sig : clusterCores) { <ide> candidates.add(new ClusterCandidate(sig)); <ide> } <ide> <ide> // Perform hard partitioning, assigning each data point only to one cluster, <ide> // namely that one it is most likely to belong to. <del> for (DBIDIter iter = dbids.iter(); iter.valid(); iter.advance()) { <add> for(DBIDIter iter = dbids.iter(); iter.valid(); iter.advance()) { <ide> final double[] probs = probClusterIGivenX.get(iter); <ide> int bestCluster = 0; <ide> double bestProbability = probs[0]; <del> for (int c = 1; c < k; ++c) { <del> if (probs[c] > bestProbability) { <add> for(int c = 1; c < k; ++c) { <add> if(probs[c] > bestProbability) { <ide> bestCluster = c; <ide> bestProbability = probs[c]; <ide> } <ide> } <ide> <ide> /** <del> * Performs outlier detection by testing the mahalanobis distance of each <add> * Performs outlier detection by testing the Mahalanobis distance of each <ide> * point in a cluster against the critical value of the ChiSquared <ide> * distribution with as many degrees of freedom as the cluster has relevant <ide> * attributes. <ide> private void findOutliers(Relation<V> relation, Vector[] means, Matrix[] invCovMatr, ArrayList<ClusterCandidate> clusterCandidates, int nonUniformDimensionCount, ModifiableDBIDs noise) { <ide> final int k = clusterCandidates.size(); <ide> <del> for (int c = 0; c < k; ++c) { <add> for(int c = 0; c < k; ++c) { <ide> final ClusterCandidate candidate = clusterCandidates.get(c); <del> if (candidate.ids.size() < 2) { <add> if(candidate.ids.size() < 2) { <ide> continue; <ide> } <del> for (DBIDMIter iter = candidate.ids.iter(); iter.valid(); iter.advance()) { <add> for(DBIDMIter iter = candidate.ids.iter(); iter.valid(); iter.advance()) { <ide> final Vector mean = means[c]; <ide> final Vector delta = relation.get(iter).getColumnVector().minusEquals(mean); <ide> final Matrix invCov = invCovMatr[c]; <ide> final double distance = MathUtil.mahalanobisDistance(invCov, delta); <ide> final int dof = candidate.dimensions.cardinality() - 1; <del> if ((1 - 0.001) <= ChiSquaredDistribution.cdf(distance, dof)) { <add> if((1 - 0.001) <= ChiSquaredDistribution.cdf(distance, dof)) { <ide> // Outlier, remove it and add it to the outlier set. <ide> noise.add(iter); <ide> iter.remove(); <ide> */ <ide> protected Signature mergeSignatures(Signature first, Signature second, int numBins) { <ide> int d2 = -1; <del> for (int i = 0; i < second.spec.length; i += 2) { <del> if (second.spec[i] >= 0) { <add> for(int i = 0; i < second.spec.length; i += 2) { <add> if(second.spec[i] >= 0) { <ide> assert (d2 == -1) : "Merging with non-1-signature?!?"; <ide> d2 = i; <ide> } <ide> assert (d2 >= 0) : "Merging with empty signature?"; <ide> <ide> // Skip the merge if the interval is already part of the signature. <del> if (first.spec[d2] >= 0) { <add> if(first.spec[d2] >= 0) { <ide> return null; <ide> } <ide> <ide> double width = (second.spec[d2 + 1] + 1 - second.spec[d2]) / (double) numBins; <ide> // Expected size thus: <ide> double expect = support * width; <del> if (support <= expect) { <add> if(support <= expect) { <ide> return null; <ide> } <del> if (PoissonDistribution.rawProbability(support, expect) >= poissonThreshold) { <add> if(PoissonDistribution.rawProbability(support, expect) >= poissonThreshold) { <ide> return null; <ide> } <ide> // Create merged signature. <ide> <ide> public ClusterCandidate(Signature clusterCore) { <ide> this.dimensions = new BitSet(clusterCore.spec.length >> 1); <del> for (int i = 0; i < clusterCore.spec.length; i += 2) { <add> for(int i = 0; i < clusterCore.spec.length; i += 2) { <ide> this.dimensions.set(i >> 1); <ide> } <ide> this.ids = DBIDUtil.newArray(clusterCore.ids.size()); <ide> /** <ide> * Maximum number of iterations for the EM step. <ide> */ <del> public static final OptionID MAX_EM_ITERATIONS_ID = new OptionID("p3c.em.maxiter", "The maximum number of iterations for the EM step."); <add> public static final OptionID MAX_EM_ITERATIONS_ID = new OptionID("p3c.em.maxiter", "The maximum number of iterations for the EM step. Use -1 to run until delta convergence."); <ide> <ide> /** <ide> * Threshold when to stop EM iterations. <ide> { <ide> DoubleParameter param = new DoubleParameter(POISSON_THRESHOLD_ID, 1.e-20); <ide> param.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); <del> if (config.grab(param)) { <add> if(config.grab(param)) { <ide> poissonThreshold = param.getValue(); <ide> } <ide> } <ide> <ide> { <del> IntParameter param = new IntParameter(MAX_EM_ITERATIONS_ID, 10); <del> param.addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); <del> if (config.grab(param)) { <add> IntParameter param = new IntParameter(MAX_EM_ITERATIONS_ID, 20); <add> param.addConstraint(CommonConstraints.GREATER_EQUAL_MINUSONE_INT); <add> if(config.grab(param)) { <ide> maxEmIterations = param.getValue(); <ide> } <ide> } <ide> <ide> { <del> DoubleParameter param = new DoubleParameter(EM_DELTA_ID, 1.e-9); <add> DoubleParameter param = new DoubleParameter(EM_DELTA_ID, 1.e-5); <ide> param.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); <del> if (config.grab(param)) { <add> if(config.grab(param)) { <ide> emDelta = param.getValue(); <ide> } <ide> } <ide> { <ide> IntParameter param = new IntParameter(MIN_CLUSTER_SIZE_ID, 1); <ide> param.addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); <del> if (config.grab(param)) { <add> if(config.grab(param)) { <ide> minClusterSize = param.getValue(); <ide> } <ide> }
Java
agpl-3.0
8beaaa350df7bba262be78fff0a0b58322775a86
0
PaulKh/scale-proactive,fviale/programming,lpellegr/programming,fviale/programming,fviale/programming,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,acontes/programming,PaulKh/scale-proactive,ow2-proactive/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,paraita/programming,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,acontes/programming,lpellegr/programming,PaulKh/scale-proactive,paraita/programming,fviale/programming,jrochas/scale-proactive,paraita/programming,ow2-proactive/programming,mnip91/programming-multiactivities,mnip91/programming-multiactivities,paraita/programming,PaulKh/scale-proactive,jrochas/scale-proactive,paraita/programming,acontes/programming,ow2-proactive/programming,jrochas/scale-proactive,lpellegr/programming,PaulKh/scale-proactive,jrochas/scale-proactive,lpellegr/programming,mnip91/proactive-component-monitoring,ow2-proactive/programming,ow2-proactive/programming,paraita/programming,lpellegr/programming,mnip91/programming-multiactivities,acontes/programming,PaulKh/scale-proactive,jrochas/scale-proactive,mnip91/proactive-component-monitoring,fviale/programming,acontes/programming,ow2-proactive/programming,acontes/programming,lpellegr/programming,fviale/programming,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,mnip91/programming-multiactivities,acontes/programming,jrochas/scale-proactive
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.jmx.mbean; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.concurrent.ConcurrentLinkedQueue; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import org.apache.log4j.Logger; import org.objectweb.proactive.api.ProMobileAgent; import org.objectweb.proactive.benchmarks.timit.util.basic.BasicTimer; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.AbstractBody; import org.objectweb.proactive.core.body.migration.Migratable; import org.objectweb.proactive.core.body.migration.MigrationException; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.gc.GarbageCollector; import org.objectweb.proactive.core.gc.ObjectGraph; import org.objectweb.proactive.core.jmx.naming.FactoryName; import org.objectweb.proactive.core.jmx.notification.NotificationType; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.profiling.TimerProvidable; import org.objectweb.proactive.core.util.profiling.TimerWarehouse; /** * Implementation of a BodyWrapperMBean * * @author ProActive Team */ public class BodyWrapper extends NotificationBroadcasterSupport implements Serializable, BodyWrapperMBean { /** JMX Logger */ private transient Logger logger = ProActiveLogger.getLogger(Loggers.JMX_MBEAN); private transient Logger notificationsLogger = ProActiveLogger.getLogger(Loggers.JMX_NOTIFICATION); /** ObjectName of this MBean */ private transient ObjectName objectName; /** Unique id of the active object */ private UniqueID id; /** The body wrapped in this MBean */ private AbstractBody body; /** The url of node containing this active object */ private transient String nodeUrl; /** The name of the body of the active object */ private String bodyName; // -- JMX Datas -- /** Timeout between updates */ private long updateFrequence = 300; /** Used by the JMX notifications */ private long counter = 1; /** * A list of jmx notifications. The current MBean sends a list of * notifications in order to not overload the network */ private transient ConcurrentLinkedQueue<Notification> notifications; public BodyWrapper() { /* Empty Constructor required by JMX */ } /** * Creates a new BodyWrapper MBean, representing an active object. * * @param oname * @param body */ public BodyWrapper(ObjectName oname, AbstractBody body, UniqueID id) { this.objectName = oname; this.id = id; this.nodeUrl = body.getNodeURL(); this.body = body; this.notifications = new ConcurrentLinkedQueue<Notification>(); launchNotificationsThread(); } public UniqueID getID() { return this.id; } public String getName() { if (this.bodyName == null) { this.bodyName = this.body.getName(); } return this.bodyName; } public ObjectName getObjectName() { if (this.objectName == null) { this.objectName = FactoryName.createActiveObjectName(getID()); } return this.objectName; } public String getNodeUrl() { return this.nodeUrl; } public void sendNotification(String type) { this.sendNotification(type, null); } public void sendNotification(String type, Object userData) { ObjectName source = getObjectName(); if (notificationsLogger.isDebugEnabled()) { notificationsLogger.debug("[" + type + "]#[BodyWrapper.sendNotification] source=" + source + ", userData=" + userData); } Notification notification = new Notification(type, source, counter++, System.nanoTime() / 1000); // timeStamp in microseconds notification.setUserData(userData); // If the migration is finished, we need to inform the // JMXNotificationManager if (type.equals(NotificationType.migrationFinished)) { sendNotifications(); notifications.add(notification); sendNotifications(NotificationType.migrationMessage); } else { notifications.add(notification); } } public Collection<BasicTimer> getTimersSnapshot(String[] timerNames) { TimerProvidable container = TimerWarehouse.getTimerProvidable(getID()); if (container == null) { throw new NullPointerException( "The timers container is null, the body is not timed."); } return container.getSnapshot(timerNames); } public void migrateTo(String nodeUrl) throws MigrationException { if (!(body instanceof Migratable)) { throw new MigrationException("Object cannot Migrate"); } Node node = null; try { node = NodeFactory.getNode(nodeUrl); } catch (NodeException e) { throw new MigrationException("Cannot find node " + nodeUrl, e); } ProMobileAgent.migrateTo(body, node, true, Request.NFREQUEST_IMMEDIATE_PRIORITY); } // // -- PRIVATE METHODS ----------------------------------------------------- // /** * Creates a new thread which sends JMX notifications. A BodyWrapperMBean * keeps all the notifications, and the NotificationsThread sends every * 'updateFrequence' a list of notifications. */ private void launchNotificationsThread() { Thread t = new Thread("JMXNotificationThread for " + BodyWrapper.this.objectName) { @Override public void run() { // first we wait for the creation of the body while (!BodyWrapper.this.body.isActive()) { try { Thread.sleep(updateFrequence); } catch (InterruptedException e) { logger.error("The JMX notifications sender thread was interrupted", e); } } // and once the body is activated, we can forward the notifications while (BodyWrapper.this.body.isActive()) { try { Thread.sleep(updateFrequence); sendNotifications(); } catch (InterruptedException e) { logger.error("The JMX notifications sender thread was interrupted", e); } } } }; t.setDaemon(true); t.start(); } /** * Sends a notification containing all stored notifications. */ private void sendNotifications() { this.sendNotifications(null); } /** * Sends a notification containing all stored notifications. * * @param userMessage * The message to send with the set of notifications. */ private void sendNotifications(String userMessage) { if (notifications == null) { this.notifications = new ConcurrentLinkedQueue<Notification>(); } // not sure if the synchronize is needed here, let's see ... // synchronized (notifications) { if (!notifications.isEmpty()) { ObjectName source = getObjectName(); Notification n = new Notification(NotificationType.setOfNotifications, source, counter++, userMessage); n.setUserData(notifications); super.sendNotification(n); notifications.clear(); // } } } // // -- SERIALIZATION METHODS ----------------------------------------------- // private void writeObject(java.io.ObjectOutputStream out) throws IOException { if (logger.isDebugEnabled()) { logger.debug( "[Serialisation.writeObject]#Serialization of the MBean :" + objectName); } // Send the notifications before migrates. if (!notifications.isEmpty()) { sendNotifications(); } // Unregister the MBean from the MBean Server. MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); if (mbs.isRegistered(objectName)) { try { mbs.unregisterMBean(objectName); } catch (InstanceNotFoundException e) { logger.error("The objectName " + objectName + " was not found during the serialization of the MBean", e); } catch (MBeanRegistrationException e) { logger.error("The MBean " + objectName + " can't be unregistered from the MBean server during the serialization of the MBean", e); } } // Default Serialization out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { // Warning loggers is transient logger = ProActiveLogger.getLogger(Loggers.JMX_MBEAN); notificationsLogger = ProActiveLogger.getLogger(Loggers.JMX_NOTIFICATION); if ((logger != null) && logger.isDebugEnabled()) { logger.debug( "[Serialisation.readObject]#Deserialization of the MBean"); } in.defaultReadObject(); // Warning objectName is transient this.objectName = FactoryName.createActiveObjectName(id); // Warning nodeUrl is transient // We get the url of the new node. this.nodeUrl = this.body.getNodeURL(); logger.debug("BodyWrapper.readObject() nodeUrl=" + nodeUrl); // Warning notifications is transient if (notifications == null) { this.notifications = new ConcurrentLinkedQueue<Notification>(); } // Register the MBean into the MBean Server MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.registerMBean(this, objectName); } catch (InstanceAlreadyExistsException e) { logger.error("A Mean is already registered with this objectName " + objectName, e); } catch (MBeanRegistrationException e) { logger.error("The MBean " + objectName + " can't be registered on the MBean server during the deserialization of the MBean", e); } catch (NotCompliantMBeanException e) { logger.error("Execption throws during the deserialization of the MBean", e); } launchNotificationsThread(); } /** * returns a list of outgoing active object references. */ public Collection<UniqueID> getReferenceList() { return ObjectGraph.getReferenceList(this.getID()); } public String getDgcState() { return GarbageCollector.getDgcState(this.getID()); } public Object[] getTimersSnapshotFromBody(String[] timerNames) throws Exception { org.objectweb.proactive.core.util.profiling.TimerProvidable container = org.objectweb.proactive.core.util.profiling.TimerWarehouse.getTimerProvidable(this.id); if (container == null) { throw new NullPointerException( "The timers container is null, the body is not timed."); } return new Object[] { container.getSnapshot(timerNames), // The list // of timers System.nanoTime() // The nano timestamp on this machine used // to stop all timers at the caller side }; } }
src/Core/org/objectweb/proactive/core/jmx/mbean/BodyWrapper.java
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.jmx.mbean; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.concurrent.ConcurrentLinkedQueue; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import org.apache.log4j.Logger; import org.objectweb.proactive.api.ProMobileAgent; import org.objectweb.proactive.benchmarks.timit.util.basic.BasicTimer; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.AbstractBody; import org.objectweb.proactive.core.body.migration.Migratable; import org.objectweb.proactive.core.body.migration.MigrationException; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.gc.GarbageCollector; import org.objectweb.proactive.core.gc.ObjectGraph; import org.objectweb.proactive.core.jmx.naming.FactoryName; import org.objectweb.proactive.core.jmx.notification.NotificationType; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.profiling.TimerProvidable; import org.objectweb.proactive.core.util.profiling.TimerWarehouse; /** * Implementation of a BodyWrapperMBean * * @author ProActive Team */ public class BodyWrapper extends NotificationBroadcasterSupport implements Serializable, BodyWrapperMBean { /** JMX Logger */ private transient Logger logger = ProActiveLogger.getLogger(Loggers.JMX_MBEAN); private transient Logger notificationsLogger = ProActiveLogger.getLogger(Loggers.JMX_NOTIFICATION); /** ObjectName of this MBean */ private transient ObjectName objectName; /** Unique id of the active object */ private UniqueID id; /** The body wrapped in this MBean */ private AbstractBody body; /** The url of node containing this active object */ private transient String nodeUrl; /** The name of the body of the active object */ private String bodyName; // -- JMX Datas -- /** Timeout between updates */ private long updateFrequence = 300; /** Used by the JMX notifications */ private long counter = 1; /** * A list of jmx notifications. The current MBean sends a list of * notifications in order to not overload the network */ private transient ConcurrentLinkedQueue<Notification> notifications; public BodyWrapper() { /* Empty Constructor required by JMX */ } /** * Creates a new BodyWrapper MBean, representing an active object. * * @param oname * @param body */ public BodyWrapper(ObjectName oname, AbstractBody body, UniqueID id) { this.objectName = oname; this.id = id; this.nodeUrl = body.getNodeURL(); this.body = body; this.notifications = new ConcurrentLinkedQueue<Notification>(); launchNotificationsThread(); } public UniqueID getID() { return this.id; } public String getName() { if (this.bodyName == null) { this.bodyName = this.body.getName(); } return this.bodyName; } public ObjectName getObjectName() { if (this.objectName == null) { this.objectName = FactoryName.createActiveObjectName(getID()); } return this.objectName; } public String getNodeUrl() { return this.nodeUrl; } public void sendNotification(String type) { this.sendNotification(type, null); } public void sendNotification(String type, Object userData) { ObjectName source = getObjectName(); if (notificationsLogger.isDebugEnabled()) { notificationsLogger.debug("[" + type + "]#[BodyWrapper.sendNotification] source=" + source + ", userData=" + userData); } Notification notification = new Notification(type, source, counter++,System.nanoTime()/1000); // timeStamp in microseconds notification.setUserData(userData); // If the migration is finished, we need to inform the // JMXNotificationManager if (type.equals(NotificationType.migrationFinished)) { sendNotifications(); notifications.add(notification); sendNotifications(NotificationType.migrationMessage); } else { notifications.add(notification); } } public Collection<BasicTimer> getTimersSnapshot(String[] timerNames) { TimerProvidable container = TimerWarehouse.getTimerProvidable(getID()); if (container == null) { throw new NullPointerException( "The timers container is null, the body is not timed."); } return container.getSnapshot(timerNames); } public void migrateTo(String nodeUrl) throws MigrationException { if (!(body instanceof Migratable)) { throw new MigrationException("Object cannot Migrate"); } Node node = null; try { node = NodeFactory.getNode(nodeUrl); } catch (NodeException e) { throw new MigrationException("Cannot find node " + nodeUrl, e); } ProMobileAgent.migrateTo(body, node, true, Request.NFREQUEST_IMMEDIATE_PRIORITY); } // // -- PRIVATE METHODS ----------------------------------------------------- // /** * Creates a new thread which sends JMX notifications. A BodyWrapperMBean * keeps all the notifications, and the NotificationsThread sends every * 'updateFrequence' a list of notifications. */ private void launchNotificationsThread() { Thread t = new Thread("JMXNotificationThread for " + BodyWrapper.this.objectName) { @Override public void run() { // first we wait for the creation of the body while (!BodyWrapper.this.body.isActive()) { try { Thread.sleep(updateFrequence); } catch (InterruptedException e) { logger.error("The JMX notifications sender thread was interrupted", e); } } // and once the body is activated, we can forward the notifications while (BodyWrapper.this.body.isActive()) { try { Thread.sleep(updateFrequence); sendNotifications(); } catch (InterruptedException e) { logger.error("The JMX notifications sender thread was interrupted", e); } } } }; t.setDaemon(true); t.start(); } /** * Sends a notification containing all stored notifications. */ private void sendNotifications() { this.sendNotifications(null); } /** * Sends a notification containing all stored notifications. * * @param userMessage * The message to send with the set of notifications. */ private void sendNotifications(String userMessage) { if (notifications == null) { this.notifications = new ConcurrentLinkedQueue<Notification>(); } // not sure if the synchronize is needed here, let's see ... // synchronized (notifications) { if (!notifications.isEmpty()) { ObjectName source = getObjectName(); Notification n = new Notification(NotificationType.setOfNotifications, source, counter++, userMessage); n.setUserData(notifications); super.sendNotification(n); notifications.clear(); // } } } // // -- SERIALIZATION METHODS ----------------------------------------------- // private void writeObject(java.io.ObjectOutputStream out) throws IOException { if (logger.isDebugEnabled()) { logger.debug( "[Serialisation.writeObject]#Serialization of the MBean :" + objectName); } // Send the notifications before migrates. if (!notifications.isEmpty()) { sendNotifications(); } // Unregister the MBean from the MBean Server. MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); if (mbs.isRegistered(objectName)) { try { mbs.unregisterMBean(objectName); } catch (InstanceNotFoundException e) { logger.error("The objectName " + objectName + " was not found during the serialization of the MBean", e); } catch (MBeanRegistrationException e) { logger.error("The MBean " + objectName + " can't be unregistered from the MBean server during the serialization of the MBean", e); } } // Default Serialization out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { // Warning loggers is transient logger = ProActiveLogger.getLogger(Loggers.JMX_MBEAN); notificationsLogger = ProActiveLogger.getLogger(Loggers.JMX_NOTIFICATION); if ((logger != null) && logger.isDebugEnabled()) { logger.debug( "[Serialisation.readObject]#Deserialization of the MBean"); } in.defaultReadObject(); // Warning objectName is transient this.objectName = FactoryName.createActiveObjectName(id); // Warning nodeUrl is transient // We get the url of the new node. this.nodeUrl = this.body.getNodeURL(); logger.debug("BodyWrapper.readObject() nodeUrl=" + nodeUrl); // Warning notifications is transient if (notifications == null) { this.notifications = new ConcurrentLinkedQueue<Notification>(); } // Register the MBean into the MBean Server MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.registerMBean(this, objectName); } catch (InstanceAlreadyExistsException e) { logger.error("A Mean is already registered with this objectName " + objectName, e); } catch (MBeanRegistrationException e) { logger.error("The MBean " + objectName + " can't be registered on the MBean server during the deserialization of the MBean", e); } catch (NotCompliantMBeanException e) { logger.error("Execption throws during the deserialization of the MBean", e); } launchNotificationsThread(); } /** * returns a list of outgoing active object references. */ public Collection<UniqueID> getReferenceList() { return ObjectGraph.getReferenceList(this.getID()); } public String getDgcState() { return GarbageCollector.getDgcState(this.getID()); } public Object[] getTimersSnapshotFromBody(String[] timerNames) throws Exception { org.objectweb.proactive.core.util.profiling.TimerProvidable container = org.objectweb.proactive.core.util.profiling.TimerWarehouse.getTimerProvidable(this.id); if (container == null) { throw new NullPointerException( "The timers container is null, the body is not timed."); } return new Object[] { container.getSnapshot(timerNames), // The list // of timers System.nanoTime() // The nano timestamp on this machine used // to stop all timers at the caller side }; } }
..lopy git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@6609 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/Core/org/objectweb/proactive/core/jmx/mbean/BodyWrapper.java
..lopy
<ide><path>rc/Core/org/objectweb/proactive/core/jmx/mbean/BodyWrapper.java <ide> ", userData=" + userData); <ide> } <ide> <del> Notification notification = new Notification(type, source, counter++,System.nanoTime()/1000); // timeStamp in microseconds <del> notification.setUserData(userData); <add> Notification notification = new Notification(type, source, counter++, <add> System.nanoTime() / 1000); // timeStamp in microseconds <add> notification.setUserData(userData); <ide> // If the migration is finished, we need to inform the <ide> // JMXNotificationManager <ide> if (type.equals(NotificationType.migrationFinished)) {
Java
apache-2.0
aa24461d30ee4e9e7c117e812d7c201056a302ab
0
volodymyr-babak/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard
/** * Copyright © 2016-2018 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.rule.engine.rest; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.ssl.SslContextBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.Netty4ClientHttpRequestFactory; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; import org.springframework.web.client.AsyncRestTemplate; import org.springframework.web.client.HttpClientErrorException; import org.thingsboard.rule.engine.api.util.TbNodeUtils; import org.thingsboard.rule.engine.api.*; import org.thingsboard.server.common.data.plugin.ComponentType; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import javax.net.ssl.SSLException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @Slf4j @RuleNode( type = ComponentType.EXTERNAL, name = "rest api call", configClazz = TbRestApiCallNodeConfiguration.class, nodeDescription = "Invoke REST API calls to external REST server", nodeDetails = "Will invoke REST API call <code>GET | POST | PUT | DELETE</code> to external REST server. " + "Message payload added into Request body. Configured attributes can be added into Headers from Message Metadata." + " Outbound message will contain response fields " + "(<code>status</code>, <code>statusCode</code>, <code>statusReason</code> and response <code>headers</code>) in the Message Metadata." + " Response body saved in outbound Message payload. " + "For example <b>statusCode</b> field can be accessed with <code>metadata.statusCode</code>.", uiResources = {"static/rulenode/rulenode-core-config.js"}, configDirective = "tbActionNodeRestApiCallConfig", iconUrl = "data:image/svg+xml;base64,PHN2ZyBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1MTIgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB2ZXJzaW9uPSIxLjEiIHk9IjBweCIgeD0iMHB4Ij48ZyB0cmFuc2Zvcm09Im1hdHJpeCguOTQ5NzUgMCAwIC45NDk3NSAxNy4xMiAyNi40OTIpIj48cGF0aCBkPSJtMTY5LjExIDEwOC41NGMtOS45MDY2IDAuMDczNC0xOS4wMTQgNi41NzI0LTIyLjAxNCAxNi40NjlsLTY5Ljk5MyAyMzEuMDhjLTMuNjkwNCAxMi4xODEgMy4yODkyIDI1LjIyIDE1LjQ2OSAyOC45MSAyLjIyNTkgMC42NzQ4MSA0LjQ5NjkgMSA2LjcyODUgMSA5Ljk3MjEgMCAxOS4xNjUtNi41MTUzIDIyLjE4Mi0xNi40NjdhNi41MjI0IDYuNTIyNCAwIDAgMCAwLjAwMiAtMC4wMDJsNjkuOTktMjMxLjA3YTYuNTIyNCA2LjUyMjQgMCAwIDAgMCAtMC4wMDJjMy42ODU1LTEyLjE4MS0zLjI4Ny0yNS4yMjUtMTUuNDcxLTI4LjkxMi0yLjI4MjUtMC42OTE0NS00LjYxMTYtMS4wMTY5LTYuODk4NC0xem04NC45ODggMGMtOS45MDQ4IDAuMDczNC0xOS4wMTggNi41Njc1LTIyLjAxOCAxNi40NjlsLTY5Ljk4NiAyMzEuMDhjLTMuNjg5OCAxMi4xNzkgMy4yODUzIDI1LjIxNyAxNS40NjUgMjguOTA4IDIuMjI5NyAwLjY3NjQ3IDQuNTAwOCAxLjAwMiA2LjczMjQgMS4wMDIgOS45NzIxIDAgMTkuMTY1LTYuNTE1MyAyMi4xODItMTYuNDY3YTYuNTIyNCA2LjUyMjQgMCAwIDAgMC4wMDIgLTAuMDAybDY5Ljk4OC0yMzEuMDdjMy42OTA4LTEyLjE4MS0zLjI4NTItMjUuMjIzLTE1LjQ2Ny0yOC45MTItMi4yODE0LTAuNjkyMzEtNC42MTA4LTEuMDE4OS02Ljg5ODQtMS4wMDJ6bS0yMTcuMjkgNDIuMjNjLTEyLjcyOS0wLjAwMDg3LTIzLjE4OCAxMC40NTYtMjMuMTg4IDIzLjE4NiAwLjAwMSAxMi43MjggMTAuNDU5IDIzLjE4NiAyMy4xODggMjMuMTg2IDEyLjcyNy0wLjAwMSAyMy4xODMtMTAuNDU5IDIzLjE4NC0yMy4xODYgMC4wMDA4NzYtMTIuNzI4LTEwLjQ1Ni0yMy4xODUtMjMuMTg0LTIzLjE4NnptMCAxNDYuNjRjLTEyLjcyNy0wLjAwMDg3LTIzLjE4NiAxMC40NTUtMjMuMTg4IDIzLjE4NC0wLjAwMDg3MyAxMi43MjkgMTAuNDU4IDIzLjE4OCAyMy4xODggMjMuMTg4IDEyLjcyOC0wLjAwMSAyMy4xODQtMTAuNDYgMjMuMTg0LTIzLjE4OC0wLjAwMS0xMi43MjYtMTAuNDU3LTIzLjE4My0yMy4xODQtMjMuMTg0em0yNzAuNzkgNDIuMjExYy0xMi43MjcgMC0yMy4xODQgMTAuNDU3LTIzLjE4NCAyMy4xODRzMTAuNDU1IDIzLjE4OCAyMy4xODQgMjMuMTg4aDE1NC45OGMxMi43MjkgMCAyMy4xODYtMTAuNDYgMjMuMTg2LTIzLjE4OCAwLjAwMS0xMi43MjgtMTAuNDU4LTIzLjE4NC0yMy4xODYtMjMuMTg0eiIgdHJhbnNmb3JtPSJtYXRyaXgoMS4wMzc2IDAgMCAxLjAzNzYgLTcuNTY3NiAtMTQuOTI1KSIgc3Ryb2tlLXdpZHRoPSIxLjI2OTMiLz48L2c+PC9zdmc+" ) public class TbRestApiCallNode implements TbNode { private static final String STATUS = "status"; private static final String STATUS_CODE = "statusCode"; private static final String STATUS_REASON = "statusReason"; private static final String ERROR = "error"; private static final String ERROR_BODY = "error_body"; private TbRestApiCallNodeConfiguration config; private EventLoopGroup eventLoopGroup; private AsyncRestTemplate httpClient; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { try { this.config = TbNodeUtils.convert(configuration, TbRestApiCallNodeConfiguration.class); this.eventLoopGroup = new NioEventLoopGroup(); Netty4ClientHttpRequestFactory nettyFactory = new Netty4ClientHttpRequestFactory(this.eventLoopGroup); nettyFactory.setSslContext(SslContextBuilder.forClient().build()); httpClient = new AsyncRestTemplate(nettyFactory); } catch (SSLException e) { throw new TbNodeException(e); } } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { String endpointUrl = TbNodeUtils.processPattern(config.getRestEndpointUrlPattern(), msg.getMetaData()); HttpHeaders headers = prepareHeaders(msg.getMetaData()); HttpMethod method = HttpMethod.valueOf(config.getRequestMethod()); HttpEntity<String> entity = new HttpEntity<>(msg.getData(), headers); ListenableFuture<ResponseEntity<String>> future = httpClient.exchange( endpointUrl, method, entity, String.class); future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() { @Override public void onFailure(Throwable throwable) { TbMsg next = processException(ctx, msg, throwable); ctx.tellFailure(next, throwable); } @Override public void onSuccess(ResponseEntity<String> responseEntity) { if (responseEntity.getStatusCode().is2xxSuccessful()) { TbMsg next = processResponse(ctx, msg, responseEntity); ctx.tellNext(next, TbRelationTypes.SUCCESS); } else { TbMsg next = processFailureResponse(ctx, msg, responseEntity); ctx.tellNext(next, TbRelationTypes.FAILURE); } } }); } @Override public void destroy() { if (this.eventLoopGroup != null) { this.eventLoopGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS); } } private TbMsg processResponse(TbContext ctx, TbMsg origMsg, ResponseEntity<String> response) { TbMsgMetaData metaData = origMsg.getMetaData(); metaData.putValue(STATUS, response.getStatusCode().name()); metaData.putValue(STATUS_CODE, response.getStatusCode().value()+""); metaData.putValue(STATUS_REASON, response.getStatusCode().getReasonPhrase()); response.getHeaders().toSingleValueMap().forEach((k,v) -> metaData.putValue(k,v) ); return ctx.transformMsg(origMsg, origMsg.getType(), origMsg.getOriginator(), metaData, response.getBody()); } private TbMsg processFailureResponse(TbContext ctx, TbMsg origMsg, ResponseEntity<String> response) { TbMsgMetaData metaData = origMsg.getMetaData(); metaData.putValue(STATUS, response.getStatusCode().name()); metaData.putValue(STATUS_CODE, response.getStatusCode().value()+""); metaData.putValue(STATUS_REASON, response.getStatusCode().getReasonPhrase()); metaData.putValue(ERROR_BODY, response.getBody()); return ctx.transformMsg(origMsg, origMsg.getType(), origMsg.getOriginator(), metaData, origMsg.getData()); } private TbMsg processException(TbContext ctx, TbMsg origMsg, Throwable e) { TbMsgMetaData metaData = origMsg.getMetaData(); metaData.putValue(ERROR, e.getClass() + ": " + e.getMessage()); if (e instanceof HttpClientErrorException) { HttpClientErrorException httpClientErrorException = (HttpClientErrorException)e; metaData.putValue(STATUS, httpClientErrorException.getStatusText()); metaData.putValue(STATUS_CODE, httpClientErrorException.getRawStatusCode()+""); metaData.putValue(ERROR_BODY, httpClientErrorException.getResponseBodyAsString()); } return ctx.transformMsg(origMsg, origMsg.getType(), origMsg.getOriginator(), metaData, origMsg.getData()); } private HttpHeaders prepareHeaders(TbMsgMetaData metaData) { HttpHeaders headers = new HttpHeaders(); config.getHeaders().forEach((k,v) -> { headers.add(TbNodeUtils.processPattern(k, metaData), TbNodeUtils.processPattern(v, metaData)); }); return headers; } }
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbRestApiCallNode.java
/** * Copyright © 2016-2018 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.rule.engine.rest; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.ssl.SslContextBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.Netty4ClientHttpRequestFactory; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; import org.springframework.web.client.AsyncRestTemplate; import org.springframework.web.client.HttpClientErrorException; import org.thingsboard.rule.engine.api.util.TbNodeUtils; import org.thingsboard.rule.engine.api.*; import org.thingsboard.server.common.data.plugin.ComponentType; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import javax.net.ssl.SSLException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @Slf4j @RuleNode( type = ComponentType.EXTERNAL, name = "rest api call", configClazz = TbRestApiCallNodeConfiguration.class, nodeDescription = "Invoke REST API calls to external REST server", nodeDetails = "Will invoke REST API call <code>GET | POST | PUT | DELETE</code> to external REST server. " + "Message payload added into Request body. Configured attributes can be added into Headers from Message Metadata." + " Outbound message will contain response fields " + "(<code>status</code>, <code>statusCode</code>, <code>statusReason</code> and response <code>headers</code>) in the Message Metadata." + " Response body saved in outbound Message payload. " + "For example <b>statusCode</b> field can be accessed with <code>metadata.statusCode</code>.", uiResources = {"static/rulenode/rulenode-core-config.js"}, configDirective = "tbActionNodeRestApiCallConfig", iconUrl = "data:image/svg+xml;base64,PHN2ZyBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1MTIgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB2ZXJzaW9uPSIxLjEiIHk9IjBweCIgeD0iMHB4Ij48ZyB0cmFuc2Zvcm09Im1hdHJpeCguOTQ5NzUgMCAwIC45NDk3NSAxNy4xMiAyNi40OTIpIj48cGF0aCBkPSJtMTY5LjExIDEwOC41NGMtOS45MDY2IDAuMDczNC0xOS4wMTQgNi41NzI0LTIyLjAxNCAxNi40NjlsLTY5Ljk5MyAyMzEuMDhjLTMuNjkwNCAxMi4xODEgMy4yODkyIDI1LjIyIDE1LjQ2OSAyOC45MSAyLjIyNTkgMC42NzQ4MSA0LjQ5NjkgMSA2LjcyODUgMSA5Ljk3MjEgMCAxOS4xNjUtNi41MTUzIDIyLjE4Mi0xNi40NjdhNi41MjI0IDYuNTIyNCAwIDAgMCAwLjAwMiAtMC4wMDJsNjkuOTktMjMxLjA3YTYuNTIyNCA2LjUyMjQgMCAwIDAgMCAtMC4wMDJjMy42ODU1LTEyLjE4MS0zLjI4Ny0yNS4yMjUtMTUuNDcxLTI4LjkxMi0yLjI4MjUtMC42OTE0NS00LjYxMTYtMS4wMTY5LTYuODk4NC0xem04NC45ODggMGMtOS45MDQ4IDAuMDczNC0xOS4wMTggNi41Njc1LTIyLjAxOCAxNi40NjlsLTY5Ljk4NiAyMzEuMDhjLTMuNjg5OCAxMi4xNzkgMy4yODUzIDI1LjIxNyAxNS40NjUgMjguOTA4IDIuMjI5NyAwLjY3NjQ3IDQuNTAwOCAxLjAwMiA2LjczMjQgMS4wMDIgOS45NzIxIDAgMTkuMTY1LTYuNTE1MyAyMi4xODItMTYuNDY3YTYuNTIyNCA2LjUyMjQgMCAwIDAgMC4wMDIgLTAuMDAybDY5Ljk4OC0yMzEuMDdjMy42OTA4LTEyLjE4MS0zLjI4NTItMjUuMjIzLTE1LjQ2Ny0yOC45MTItMi4yODE0LTAuNjkyMzEtNC42MTA4LTEuMDE4OS02Ljg5ODQtMS4wMDJ6bS0yMTcuMjkgNDIuMjNjLTEyLjcyOS0wLjAwMDg3LTIzLjE4OCAxMC40NTYtMjMuMTg4IDIzLjE4NiAwLjAwMSAxMi43MjggMTAuNDU5IDIzLjE4NiAyMy4xODggMjMuMTg2IDEyLjcyNy0wLjAwMSAyMy4xODMtMTAuNDU5IDIzLjE4NC0yMy4xODYgMC4wMDA4NzYtMTIuNzI4LTEwLjQ1Ni0yMy4xODUtMjMuMTg0LTIzLjE4NnptMCAxNDYuNjRjLTEyLjcyNy0wLjAwMDg3LTIzLjE4NiAxMC40NTUtMjMuMTg4IDIzLjE4NC0wLjAwMDg3MyAxMi43MjkgMTAuNDU4IDIzLjE4OCAyMy4xODggMjMuMTg4IDEyLjcyOC0wLjAwMSAyMy4xODQtMTAuNDYgMjMuMTg0LTIzLjE4OC0wLjAwMS0xMi43MjYtMTAuNDU3LTIzLjE4My0yMy4xODQtMjMuMTg0em0yNzAuNzkgNDIuMjExYy0xMi43MjcgMC0yMy4xODQgMTAuNDU3LTIzLjE4NCAyMy4xODRzMTAuNDU1IDIzLjE4OCAyMy4xODQgMjMuMTg4aDE1NC45OGMxMi43MjkgMCAyMy4xODYtMTAuNDYgMjMuMTg2LTIzLjE4OCAwLjAwMS0xMi43MjgtMTAuNDU4LTIzLjE4NC0yMy4xODYtMjMuMTg0eiIgdHJhbnNmb3JtPSJtYXRyaXgoMS4wMzc2IDAgMCAxLjAzNzYgLTcuNTY3NiAtMTQuOTI1KSIgc3Ryb2tlLXdpZHRoPSIxLjI2OTMiLz48L2c+PC9zdmc+" ) public class TbRestApiCallNode implements TbNode { private static final String STATUS = "status"; private static final String STATUS_CODE = "statusCode"; private static final String STATUS_REASON = "statusReason"; private static final String ERROR = "error"; private static final String ERROR_BODY = "error_body"; private TbRestApiCallNodeConfiguration config; private EventLoopGroup eventLoopGroup; private AsyncRestTemplate httpClient; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { try { this.config = TbNodeUtils.convert(configuration, TbRestApiCallNodeConfiguration.class); this.eventLoopGroup = new NioEventLoopGroup(); Netty4ClientHttpRequestFactory nettyFactory = new Netty4ClientHttpRequestFactory(this.eventLoopGroup); nettyFactory.setSslContext(SslContextBuilder.forClient().build()); httpClient = new AsyncRestTemplate(nettyFactory); } catch (SSLException e) { throw new TbNodeException(e); } } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { String endpointUrl = TbNodeUtils.processPattern(config.getRestEndpointUrlPattern(), msg.getMetaData()); HttpHeaders headers = prepareHeaders(msg.getMetaData()); HttpMethod method = HttpMethod.valueOf(config.getRequestMethod()); HttpEntity<String> entity = new HttpEntity<>(msg.getData(), headers); ListenableFuture<ResponseEntity<String>> future = httpClient.exchange( endpointUrl, method, entity, String.class); future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() { @Override public void onFailure(Throwable throwable) { TbMsg next = processException(ctx, msg, throwable); ctx.tellFailure(next, throwable); } @Override public void onSuccess(ResponseEntity<String> responseEntity) { if (responseEntity.getStatusCode().is2xxSuccessful()) { TbMsg next = processResponse(ctx, msg, responseEntity); ctx.tellNext(next, TbRelationTypes.SUCCESS); } else { TbMsg next = processFailureResponse(ctx, msg, responseEntity); ctx.tellNext(next, TbRelationTypes.FAILURE); } } }); } @Override public void destroy() { if (this.eventLoopGroup != null) { this.eventLoopGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS); } } private TbMsg processResponse(TbContext ctx, TbMsg origMsg, ResponseEntity<String> response) { TbMsgMetaData metaData = new TbMsgMetaData(); metaData.putValue(STATUS, response.getStatusCode().name()); metaData.putValue(STATUS_CODE, response.getStatusCode().value()+""); metaData.putValue(STATUS_REASON, response.getStatusCode().getReasonPhrase()); response.getHeaders().toSingleValueMap().forEach((k,v) -> metaData.putValue(k,v) ); return ctx.transformMsg(origMsg, origMsg.getType(), origMsg.getOriginator(), metaData, response.getBody()); } private TbMsg processFailureResponse(TbContext ctx, TbMsg origMsg, ResponseEntity<String> response) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue(STATUS, response.getStatusCode().name()); metaData.putValue(STATUS_CODE, response.getStatusCode().value()+""); metaData.putValue(STATUS_REASON, response.getStatusCode().getReasonPhrase()); metaData.putValue(ERROR_BODY, response.getBody()); return ctx.transformMsg(origMsg, origMsg.getType(), origMsg.getOriginator(), metaData, origMsg.getData()); } private TbMsg processException(TbContext ctx, TbMsg origMsg, Throwable e) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue(ERROR, e.getClass() + ": " + e.getMessage()); if (e instanceof HttpClientErrorException) { HttpClientErrorException httpClientErrorException = (HttpClientErrorException)e; metaData.putValue(STATUS, httpClientErrorException.getStatusText()); metaData.putValue(STATUS_CODE, httpClientErrorException.getRawStatusCode()+""); metaData.putValue(ERROR_BODY, httpClientErrorException.getResponseBodyAsString()); } return ctx.transformMsg(origMsg, origMsg.getType(), origMsg.getOriginator(), metaData, origMsg.getData()); } private HttpHeaders prepareHeaders(TbMsgMetaData metaData) { HttpHeaders headers = new HttpHeaders(); config.getHeaders().forEach((k,v) -> { headers.add(TbNodeUtils.processPattern(k, metaData), TbNodeUtils.processPattern(v, metaData)); }); return headers; } }
modify TbRestApiCallNode
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbRestApiCallNode.java
modify TbRestApiCallNode
<ide><path>ule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbRestApiCallNode.java <ide> } <ide> <ide> private TbMsg processResponse(TbContext ctx, TbMsg origMsg, ResponseEntity<String> response) { <del> TbMsgMetaData metaData = new TbMsgMetaData(); <add> TbMsgMetaData metaData = origMsg.getMetaData(); <ide> metaData.putValue(STATUS, response.getStatusCode().name()); <ide> metaData.putValue(STATUS_CODE, response.getStatusCode().value()+""); <ide> metaData.putValue(STATUS_REASON, response.getStatusCode().getReasonPhrase()); <ide> } <ide> <ide> private TbMsg processFailureResponse(TbContext ctx, TbMsg origMsg, ResponseEntity<String> response) { <del> TbMsgMetaData metaData = origMsg.getMetaData().copy(); <add> TbMsgMetaData metaData = origMsg.getMetaData(); <ide> metaData.putValue(STATUS, response.getStatusCode().name()); <ide> metaData.putValue(STATUS_CODE, response.getStatusCode().value()+""); <ide> metaData.putValue(STATUS_REASON, response.getStatusCode().getReasonPhrase()); <ide> } <ide> <ide> private TbMsg processException(TbContext ctx, TbMsg origMsg, Throwable e) { <del> TbMsgMetaData metaData = origMsg.getMetaData().copy(); <add> TbMsgMetaData metaData = origMsg.getMetaData(); <ide> metaData.putValue(ERROR, e.getClass() + ": " + e.getMessage()); <ide> if (e instanceof HttpClientErrorException) { <ide> HttpClientErrorException httpClientErrorException = (HttpClientErrorException)e;
Java
lgpl-2.1
75dba187458a386fcbd09ea1ef47e58d0f12662c
0
esig/dss,zsoltii/dss,esig/dss,alisdev/dss,openlimit-signcubes/dss,openlimit-signcubes/dss,zsoltii/dss,alisdev/dss
package eu.europa.esig.dss.asic.validation; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import eu.europa.esig.dss.DSSDocument; import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.asic.ManifestNamespace; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.ManifestFile; public class ASiCEWithXAdESManifestParser { private static final Logger LOG = LoggerFactory.getLogger(ASiCEWithXAdESManifestParser.class); static { DomUtils.registerNamespace("manifest", ManifestNamespace.NS); } private final DSSDocument signatureDocument; private final DSSDocument manifestDocument; public ASiCEWithXAdESManifestParser(DSSDocument signatureDocument, DSSDocument manifestDocument) { this.signatureDocument = signatureDocument; this.manifestDocument = manifestDocument; } public ManifestFile getDescription() { ManifestFile description = new ManifestFile(); description.setSignatureFilename(signatureDocument.getName()); description.setFilename(manifestDocument.getName()); description.setEntries(getEntries()); return description; } private List<String> getEntries() { List<String> result = new ArrayList<String>(); InputStream is = null; try { is = manifestDocument.openStream(); Document manifestDom = DomUtils.buildDOM(is); NodeList nodeList = DomUtils.getNodeList(manifestDom, "/manifest:manifest/manifest:file-entry"); if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Element fileEntryElement = (Element) nodeList.item(i); String fullpathValue = fileEntryElement.getAttribute(ManifestNamespace.FULL_PATH); if (!isContainerDefinition(fullpathValue)) { result.add(fullpathValue); } } } } catch (Exception e) { LOG.error("Unable to parse manifest file " + manifestDocument.getName(), e); } finally { Utils.closeQuietly(is); } return result; } private boolean isContainerDefinition(String fullpathValue) { return "/".equals(fullpathValue); } }
dss-asic-xades/src/main/java/eu/europa/esig/dss/asic/validation/ASiCEWithXAdESManifestParser.java
package eu.europa.esig.dss.asic.validation; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import eu.europa.esig.dss.DSSDocument; import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.asic.ManifestNamespace; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.ManifestFile; public class ASiCEWithXAdESManifestParser { private static final Logger LOG = LoggerFactory.getLogger(ASiCEWithXAdESManifestParser.class); static { DomUtils.registerNamespace("manifest", ManifestNamespace.NS); } private final DSSDocument signatureDocument; private final DSSDocument manifestDocument; public ASiCEWithXAdESManifestParser(DSSDocument signatureDocument, DSSDocument manifestDocument) { this.signatureDocument = signatureDocument; this.manifestDocument = manifestDocument; } public ManifestFile getDescription() { ManifestFile description = new ManifestFile(); description.setSignatureFilename(signatureDocument.getName()); description.setFilename(manifestDocument.getName()); description.setEntries(getEntries()); return description; } private List<String> getEntries() { List<String> result = new ArrayList<String>(); InputStream is = null; try { is = manifestDocument.openStream(); Document manifestDom = DomUtils.buildDOM(is); NodeList nodeList = DomUtils.getNodeList(manifestDom, "/manifest:manifest/manifest:file-entry"); if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Element fileEntryElement = (Element) nodeList.item(i); String fullpathValue = fileEntryElement.getAttribute(ManifestNamespace.FULL_PATH); if (!isContainerDefinition(fullpathValue) && !isSignatureFile(fullpathValue)) { result.add(fullpathValue); } } } } catch (Exception e) { LOG.error("Unable to parse manifest file " + manifestDocument.getName(), e); } finally { Utils.closeQuietly(is); } return result; } /** * Sometimes signature files can be listed in the manifest file * */ private boolean isSignatureFile(String fullpathValue) { return fullpathValue.matches("META-INF/.*signature.*\\.xml"); } private boolean isContainerDefinition(String fullpathValue) { return "/".equals(fullpathValue); } }
Remove wrong code
dss-asic-xades/src/main/java/eu/europa/esig/dss/asic/validation/ASiCEWithXAdESManifestParser.java
Remove wrong code
<ide><path>ss-asic-xades/src/main/java/eu/europa/esig/dss/asic/validation/ASiCEWithXAdESManifestParser.java <ide> for (int i = 0; i < nodeList.getLength(); i++) { <ide> Element fileEntryElement = (Element) nodeList.item(i); <ide> String fullpathValue = fileEntryElement.getAttribute(ManifestNamespace.FULL_PATH); <del> if (!isContainerDefinition(fullpathValue) && !isSignatureFile(fullpathValue)) { <add> if (!isContainerDefinition(fullpathValue)) { <ide> result.add(fullpathValue); <ide> } <ide> } <ide> return result; <ide> } <ide> <del> /** <del> * Sometimes signature files can be listed in the manifest file <del> * <del> */ <del> private boolean isSignatureFile(String fullpathValue) { <del> return fullpathValue.matches("META-INF/.*signature.*\\.xml"); <del> } <del> <ide> private boolean isContainerDefinition(String fullpathValue) { <ide> return "/".equals(fullpathValue); <ide> }
Java
lgpl-2.1
efd69b9f50e695f7d89b3e4b4f7094f287d7fdb0
0
levants/lightmare
package org.lightmare.jpa.datasource; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.jpa.datasource.Initializer.ConnectionConfig; import org.lightmare.utils.ObjectUtils; /** * Initializes data source from configuration YAML file * * @author Levan Tsinadze * @since 0.1.2 */ public class YamlParsers { // Key elements private static final String DATASOURCES_KEY = "datasources"; private static final String DATASOURCE_KEY = "datasource"; private static final Logger LOG = Logger.getLogger(YamlParsers.class); private void setProperty(Map.Entry<Object, Object> entry, Properties propertis) { Object key = entry.getKey(); Object value = entry.getValue(); if (ConnectionConfig.DRIVER_PROPERTY.name.equals(key)) { String name = ObjectUtils.cast(value, String.class); value = DriverConfig.getDriverName(name); } propertis.put(key, value); } private void initDataSource(Map<Object, Object> datasource) throws IOException { Properties properties = new Properties(); Set<Map.Entry<Object, Object>> entrySet = datasource.entrySet(); for (Map.Entry<Object, Object> entry : entrySet) { setProperty(entry, properties); } Initializer.registerDataSource(properties); } public void parseYaml(Map<Object, Object> config) throws IOException { Object value = config.get(DATASOURCES_KEY); if (ObjectUtils.notNull(value)) { List<Map<Object, Object>> datasources = ObjectUtils.cast(value); for (Map<Object, Object> datasource : datasources) { try { initDataSource(datasource); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } } value = config.get(DATASOURCE_KEY); if (ObjectUtils.notNull(value)) { Map<Object, Object> datasource = ObjectUtils.cast(value); initDataSource(datasource); } } }
src/main/java/org/lightmare/jpa/datasource/YamlParsers.java
package org.lightmare.jpa.datasource; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.jpa.datasource.Initializer.ConnectionConfig; import org.lightmare.utils.ObjectUtils; public class YamlParsers { private static final String DATASOURCES_KEY = "datasources"; private static final String DATASOURCE_KEY = "datasource"; private static final Logger LOG = Logger.getLogger(YamlParsers.class); private void initDataSource(Map<Object, Object> datasource) throws IOException { Properties propertis = new Properties(); Set<Map.Entry<Object, Object>> entrySet = datasource.entrySet(); Object key; Object value; for (Map.Entry<Object, Object> entry : entrySet) { key = entry.getKey(); value = entry.getValue(); if (ConnectionConfig.DRIVER_PROPERTY.name.equals(key)) { value = DriverConfig .getDriverName(ConnectionConfig.DRIVER_PROPERTY.name); } propertis.put(key, value); } Initializer.registerDataSource(propertis); } public void parseYaml(Map<Object, Object> config) throws IOException { Object value = config.get(DATASOURCES_KEY); if (ObjectUtils.notNull(value)) { List<Map<Object, Object>> datasources = ObjectUtils.cast(value); for (Map<Object, Object> datasource : datasources) { try { initDataSource(datasource); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } } value = config.get(DATASOURCE_KEY); if (ObjectUtils.notNull(value)) { Map<Object, Object> datasource = ObjectUtils.cast(value); initDataSource(datasource); } } }
improved data source configuration utility classes
src/main/java/org/lightmare/jpa/datasource/YamlParsers.java
improved data source configuration utility classes
<ide><path>rc/main/java/org/lightmare/jpa/datasource/YamlParsers.java <ide> import org.lightmare.jpa.datasource.Initializer.ConnectionConfig; <ide> import org.lightmare.utils.ObjectUtils; <ide> <add>/** <add> * Initializes data source from configuration YAML file <add> * <add> * @author Levan Tsinadze <add> * @since 0.1.2 <add> */ <ide> public class YamlParsers { <ide> <add> // Key elements <ide> private static final String DATASOURCES_KEY = "datasources"; <ide> <ide> private static final String DATASOURCE_KEY = "datasource"; <ide> <ide> private static final Logger LOG = Logger.getLogger(YamlParsers.class); <ide> <add> private void setProperty(Map.Entry<Object, Object> entry, <add> Properties propertis) { <add> <add> Object key = entry.getKey(); <add> Object value = entry.getValue(); <add> if (ConnectionConfig.DRIVER_PROPERTY.name.equals(key)) { <add> String name = ObjectUtils.cast(value, String.class); <add> value = DriverConfig.getDriverName(name); <add> } <add> propertis.put(key, value); <add> } <add> <ide> private void initDataSource(Map<Object, Object> datasource) <ide> throws IOException { <ide> <del> Properties propertis = new Properties(); <add> Properties properties = new Properties(); <ide> Set<Map.Entry<Object, Object>> entrySet = datasource.entrySet(); <del> Object key; <del> Object value; <ide> for (Map.Entry<Object, Object> entry : entrySet) { <del> key = entry.getKey(); <del> value = entry.getValue(); <del> if (ConnectionConfig.DRIVER_PROPERTY.name.equals(key)) { <del> value = DriverConfig <del> .getDriverName(ConnectionConfig.DRIVER_PROPERTY.name); <del> } <del> propertis.put(key, value); <add> setProperty(entry, properties); <ide> } <del> Initializer.registerDataSource(propertis); <add> Initializer.registerDataSource(properties); <ide> } <ide> <ide> public void parseYaml(Map<Object, Object> config) throws IOException {
JavaScript
apache-2.0
29a3a9d3b3b702e026a399b02ec807e009a32ccf
0
Orodan/3akai-ux,Ultimedia/3akai-UX-Vanilla,Orodan/3akai-ux-jitsi-fork,stuartf/3akai-ux,simong/3akai-ux,nicolaasmatthijs/3akai-ux,Coenego/3akai-ux,mrvisser/3akai-ux,simong/3akai-ux,nicolaasmatthijs/3akai-ux,mrvisser/3akai-ux,jfederico/3akai-ux,simong/3akai-ux,timdegroote/3akai-ux,stuartf/3akai-ux,rhollow/MYB-1615,jfederico/3akai-ux,jfederico/3akai-ux,rhollow/MYB-1615,ets-berkeley-edu/3akai-ux,timdegroote/3akai-ux,Orodan/3akai-ux-jitsi-fork,rhollow/MYB-1615,Ultimedia/3akai-UX-Vanilla,stuartf/3akai-ux,ets-berkeley-edu/3akai-ux,jonmhays/3akai-ux,jonmhays/3akai-ux,Ultimedia/3akai-UX-Vanilla,ets-berkeley-edu/3akai-ux,Coenego/avocet-ui,jonmhays/3akai-ux,Orodan/3akai-ux,nicolaasmatthijs/3akai-ux,mrvisser/3akai-ux,Coenego/avocet-ui,timdegroote/3akai-ux,Coenego/3akai-ux,Orodan/3akai-ux,Orodan/3akai-ux-jitsi-fork
var sakai = sakai || {}; sakai.myfriends = function(tuid,placement,showSettings){ var rootel = $("#" + tuid); var friends = false; sdata.Ajax.request({ httpMethod: "GET", url: "/rest/friend/status?p=0&n=6&friendStatus=ACCEPTED&s=firstName&s=lastName&o=asc&o=asc&sid=" + Math.random(), onSuccess: function(data){ friends = eval('(' + data + ')'); doProcessing(); }, onFail: function(status){ $("#list_rendered").html("<b>An error has occurred.</b> Please try again later"); } }); sdata.Ajax.request({ httpMethod: "GET", url: "/rest/friend/status?sid=" + Math.random(), onSuccess: function(data){ var json2 = eval('(' + data + ')'); var total = 0; if (json2.status.friends){ total += json2.status.sizes["INVITED"]; } if (total == 1){ $("#contact_requests", rootel).html("1 Contact Request"); } else if (total > 1) { $("#contact_requests", rootel).html(total + " Connection Requests"); } }, onFail: function(status){ } }); var doProcessing = function(){ var pOnline = {}; pOnline.items = []; var total = 0; pOnline.showMore = false; if (friends.status.friends) { for (var i = 0; i < friends.status.friends.length; i++) { var isOnline = false; if (!isOnline && total < 6) { var item = friends.status.friends[i]; item.id = item.friendUuid; if (item.profile.firstName && item.profile.lastName) { item.name = item.profile.firstName + " " + item.profile.lastName; } else { item.name = item.friendUuid; } if (item.profile.picture) { var pict = item.profile.picture; if (pict.name) { item.photo = "/sdata/f/_private" + item.properties.userStoragePrefix + pict.name; } } item.online = false; if (item.profile.basic) { var basic = eval('(' + item.profile.basic + ')'); if (basic.status) { item.status = basic.status; } else { item.status = ""; } } else { item.status = ""; } pOnline.items[pOnline.items.length] = item; total++; } else if (total >= 3 && !isOnline) { pOnline.showMore = true; } } } $("#my_contacts_list").html(sdata.html.Template.render("my_contacts_list_template", pOnline)); } }; sdata.widgets.WidgetLoader.informOnLoad("myfriends");
branches/K2-redesign/uxwidgets/src/main/webapp/myfriends/javascript/myfriends.js
var sakai = sakai || {}; sakai.myfriends = function(tuid,placement,showSettings){ var rootel = $("#" + tuid); var friends = false; sdata.Ajax.request({ httpMethod: "GET", url: "/rest/friend/status?p=0&n=6&friendStatus=ACCEPTED&s=firstName&s=lastName&o=asc&o=asc&sid=" + Math.random(), onSuccess: function(data){ friends = eval('(' + data + ')'); doProcessing(); }, onFail: function(status){ $("#list_rendered").html("<b>An error has occurred.</b> Please try again later"); } }); sdata.Ajax.request({ httpMethod: "GET", url: "/rest/friend/status?sid=" + Math.random(), onSuccess: function(data){ var json2 = eval('(' + data + ')'); var total = 0; if (json2.status.friends){ total += json2.status.sizes["INVITED"]; } if (total == 1){ $("#contact_requests", rootel).html("1 Contact Request"); } else if (total > 1) { $("#contact_requests", rootel).html(total + " Connection Requests"); } }, onFail: function(status){ } }); var doProcessing = function(){ var pOnline = {}; pOnline.items = []; var total = 0; pOnline.showMore = false; if (friends.status.friends) { for (var i = 0; i < friends.status.friends.length; i++) { var isOnline = false; if (!isOnline && total < 6) { var item = friends.status.friends[i]; item.id = item.friendUuid; if (item.profile.firstName && item.profile.lastName) { item.name = item.profile.firstName + " " + item.profile.lastName; } else { item.name = item.friendUuid; } if (item.profile.picture) { var pict = eval('(' + item.profile.picture + ')'); if (pict.name) { item.photo = "/sdata/f/_private" + item.properties.userStoragePrefix + pict.name; } } item.online = false; if (item.profile.basic) { var basic = eval('(' + item.profile.basic + ')'); if (basic.status) { item.status = basic.status; } else { item.status = ""; } } else { item.status = ""; } pOnline.items[pOnline.items.length] = item; total++; } else if (total >= 3 && !isOnline) { pOnline.showMore = true; } } } $("#my_contacts_list").html(sdata.html.Template.render("my_contacts_list_template", pOnline)); } }; sdata.widgets.WidgetLoader.informOnLoad("myfriends");
SAK-15773
branches/K2-redesign/uxwidgets/src/main/webapp/myfriends/javascript/myfriends.js
SAK-15773
<ide><path>ranches/K2-redesign/uxwidgets/src/main/webapp/myfriends/javascript/myfriends.js <ide> item.name = item.friendUuid; <ide> } <ide> if (item.profile.picture) { <del> var pict = eval('(' + item.profile.picture + ')'); <add> var pict = item.profile.picture; <ide> if (pict.name) { <ide> item.photo = "/sdata/f/_private" + item.properties.userStoragePrefix + pict.name; <ide> }
Java
agpl-3.0
3a7e719658e2c40023db1eb3783ed7ddba9c5fd0
0
bhutchinson/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,kuali/kfs,smith750/kfs,ua-eas/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,smith750/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,smith750/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs,kuali/kfs
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.report.service.impl; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.mail.MessagingException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.module.ar.ArConstants; import org.kuali.kfs.module.ar.ArKeyConstants; import org.kuali.kfs.module.ar.ArPropertyConstants; import org.kuali.kfs.module.ar.businessobject.InvoiceAddressDetail; import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument; import org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService; import org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService; import org.kuali.kfs.module.ar.report.service.TransmitContractsAndGrantsInvoicesService; import org.kuali.kfs.module.ar.service.AREmailService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.KFSKeyConstants; import org.kuali.kfs.sys.KFSPropertyConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.util.KfsDateUtils; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.search.SearchOperator; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.kew.api.document.DocumentStatus; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kim.api.identity.PersonService; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.krad.exception.InvalidAddressException; import org.kuali.rice.krad.exception.ValidationException; import org.kuali.rice.krad.service.DocumentService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; import com.lowagie.text.DocumentException; /** * Default implementation of the TransmitContractsAndGrantsInvoicesService */ public class TransmitContractsAndGrantsInvoicesServiceImpl implements TransmitContractsAndGrantsInvoicesService { protected ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService; protected ContractsGrantsInvoiceReportService contractsGrantsInvoiceReportService; protected DateTimeService dateTimeService; protected DocumentService documentService; protected AREmailService arEmailService; /** * @see org.kuali.kfs.module.ar.report.service.TransmitContractsAndGrantsInvoicesService#getInvoicesByParametersFromRequest(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public Collection<ContractsGrantsInvoiceDocument> getInvoicesByParametersFromRequest(Map fieldValues) throws WorkflowException, ParseException { Date fromDate = null; Date toDate = null; String unformattedToDate = (String)fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_TO); if (StringUtils.isNotEmpty(unformattedToDate)) { toDate = dateTimeService.convertToDate(unformattedToDate); } String unformattedFromDate = (String)fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_FROM); if (StringUtils.isNotEmpty(unformattedFromDate)) { fromDate = dateTimeService.convertToDate(unformattedFromDate); } String invoiceInitiatorPrincipalName = (String) fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_INITIATOR_PRINCIPAL_NAME); if (StringUtils.isNotEmpty(invoiceInitiatorPrincipalName)) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(invoiceInitiatorPrincipalName); if (ObjectUtils.isNotNull(principal)) { fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.INITIATOR_PRINCIPAL_ID, principal.getPrincipalId()); } else { throw new IllegalArgumentException("The parameter value for initiatorPrincipalName [" + invoiceInitiatorPrincipalName + "] passed in does not map to a person."); } } String proposalNumber = (String) fieldValues.get(KFSPropertyConstants.PROPOSAL_NUMBER); if (StringUtils.isNotEmpty(proposalNumber)) { fieldValues.put(ArPropertyConstants.ContractsGrantsInvoiceDocumentFields.PROPOSAL_NUMBER, proposalNumber); } String invoiceAmount = (String) fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT); if (StringUtils.isNotEmpty(invoiceAmount)) { fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.FINANCIAL_DOCUMENT_TOTAL_AMOUNT, invoiceAmount); } String invoiceTransmissionMethodCode = (String) fieldValues.get(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE); if (StringUtils.isNotBlank(invoiceTransmissionMethodCode)) { fieldValues.put(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_TRANSMISSION_METHOD_CODE, invoiceTransmissionMethodCode); } fieldValues.put(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INITIAL_TRANSMISSION_DATE, SearchOperator.NULL.op()); fieldValues.put(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_TRANSMISSION_METHOD_CODE, invoiceTransmissionMethodCode); fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE, DocumentStatus.FINAL.getCode() + SearchOperator.OR.op() + DocumentStatus.PROCESSED.getCode()); // filter out LOC CINV docs, we don't want those included in this process fieldValues.put(ArPropertyConstants.INVOICE_GENERAL_DETAIL + "." + ArPropertyConstants.BILLING_FREQUENCY_CODE, SearchOperator.NOT + ArConstants.LOC_BILLING_SCHEDULE_CODE); Collection<ContractsGrantsInvoiceDocument> list = getContractsGrantsInvoiceDocumentService().retrieveAllCGInvoicesByCriteria(fieldValues); Collection<ContractsGrantsInvoiceDocument> finalList = new ArrayList<ContractsGrantsInvoiceDocument>(); for (ContractsGrantsInvoiceDocument item : list) { ContractsGrantsInvoiceDocument invoice = (ContractsGrantsInvoiceDocument)getDocumentService().getByDocumentHeaderId(item.getDocumentNumber()); if (!invoice.isInvoiceReversal() && !invoice.hasInvoiceBeenCorrected()) { if (isInvoiceBetween(invoice, fromDate, toDate)) { if ((StringUtils.equals(ArConstants.InvoiceTransmissionMethod.EMAIL, invoiceTransmissionMethodCode) && isInvoiceValidToEmail(invoice)) || (StringUtils.equals(ArConstants.InvoiceTransmissionMethod.MAIL, invoiceTransmissionMethodCode) && isInvoiceValidToMail(invoice))) { finalList.add(invoice); } } } } return finalList; } /** * Checks whether invoice is between the dates provided. * @param invoice * @param fromDate * @param toDate * @return */ protected boolean isInvoiceBetween(ContractsGrantsInvoiceDocument invoice, Date fromDate, Date toDate) { Date dateCreated = invoice.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate(); if (ObjectUtils.isNotNull(fromDate)) { if (fromDate.after(dateCreated)) { return false; } } if (ObjectUtils.isNotNull(toDate)) { if (toDate.before(dateCreated) && !KfsDateUtils.isSameDay(toDate, dateCreated)) { return false; } } return true; } @Override public boolean isInvoiceValidToEmail(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { for (InvoiceAddressDetail invoiceAddressDetail : contractsGrantsInvoiceDocument.getInvoiceAddressDetails()) { if (ObjectUtils.isNull(invoiceAddressDetail.getInitialTransmissionDate()) && ArConstants.InvoiceTransmissionMethod.EMAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) { return true; } } return false; } @Override public boolean isInvoiceValidToMail(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { for (InvoiceAddressDetail invoiceAddressDetail : contractsGrantsInvoiceDocument.getInvoiceAddressDetails()) { if (ObjectUtils.isNull(invoiceAddressDetail.getInitialTransmissionDate()) && ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) { return true; } } return false; } @Override public boolean printInvoicesAndEnvelopesZip(Collection<ContractsGrantsInvoiceDocument> list, ByteArrayOutputStream baos) throws DocumentException, IOException { if (CollectionUtils.isNotEmpty(list)) { byte[] envelopes = contractsGrantsInvoiceReportService.combineInvoicePdfEnvelopes(list); byte[] report = contractsGrantsInvoiceReportService.combineInvoicePdfs(list); boolean invoiceFileWritten = false; boolean envelopeFileWritten = false; ZipOutputStream zos = new ZipOutputStream(baos); try { int bytesRead; byte[] buffer = new byte[1024]; CRC32 crc = new CRC32(); String invoiceFileName = ArConstants.INVOICES_FILE_PREFIX + getDateTimeService().toDateStringForFilename(getDateTimeService().getCurrentDate()) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION; invoiceFileWritten = writeFile(report, zos, invoiceFileName); String envelopeFileName = ArConstants.INVOICE_ENVELOPES_FILE_PREFIX + getDateTimeService().toDateStringForFilename(getDateTimeService().getCurrentDate()) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION; envelopeFileWritten = writeFile(envelopes, zos, envelopeFileName); } finally { zos.close(); } return invoiceFileWritten || envelopeFileWritten; } return false; } /** * * @param report * @param invoiceFileWritten * @param zos * @param buffer * @param crc * @return * @throws IOException */ private boolean writeFile(byte[] arrayToWrite, ZipOutputStream zos, String fileName) throws IOException { int bytesRead; byte[] buffer = new byte[1024]; CRC32 crc = new CRC32(); if (ObjectUtils.isNotNull(arrayToWrite) && arrayToWrite.length > 0) { BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(arrayToWrite)); try { while ((bytesRead = bis.read(buffer)) != -1) { crc.update(buffer, 0, bytesRead); } bis.close(); // Reset to beginning of input stream bis = new BufferedInputStream(new ByteArrayInputStream(arrayToWrite)); ZipEntry entry = new ZipEntry(fileName); entry.setMethod(ZipEntry.STORED); entry.setCompressedSize(arrayToWrite.length); entry.setSize(arrayToWrite.length); entry.setCrc(crc.getValue()); zos.putNextEntry(entry); while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } } finally { bis.close(); } return true; } return false; } @Override public void validateSearchParameters(Map<String,String> fieldValues) { String invoiceTransmissionMethodCode = fieldValues.get(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE); String invoiceInitiatorPrincipalName = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_INITIATOR_PRINCIPAL_NAME); String invoicePrintDateFromString = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_FROM); String invoicePrintDateToString = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_TO); String invoiceAmount = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT); // To validate the input fields before fetching invoices. if (StringUtils.isBlank(invoiceTransmissionMethodCode)) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE, KFSKeyConstants.ERROR_REQUIRED, ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_TRANSMISSION_METHOD_CODE_LABEL); } if (StringUtils.isNotBlank(invoicePrintDateFromString)) { try { dateTimeService.convertToDate(invoicePrintDateFromString); } catch (ParseException e) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_FROM, KFSKeyConstants.ERROR_DATE_TIME, ArConstants.PRINT_INVOICES_FROM_LABEL); } } if (StringUtils.isNotBlank(invoicePrintDateToString)) { try { dateTimeService.convertToDate(invoicePrintDateToString); } catch (ParseException e) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_TO, KFSKeyConstants.ERROR_DATE_TIME, ArConstants.PRINT_INVOICES_TO_LABEL); } } if (StringUtils.isNotBlank(invoiceAmount) && !KualiDecimal.isNumeric(invoiceAmount)) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT, KFSKeyConstants.ERROR_NUMERIC, ArConstants.INVOICE_AMOUNT_LABEL); } if (StringUtils.isNotEmpty(invoiceInitiatorPrincipalName)) { Person person = SpringContext.getBean(PersonService.class).getPersonByPrincipalName(invoiceInitiatorPrincipalName); if (ObjectUtils.isNull(person)) { GlobalVariables.getMessageMap().putErrorForSectionId(ArPropertyConstants.LOOKUP_SECTION_ID, ArKeyConstants.NO_PRINCIPAL_NAME_FOUND); } } if (GlobalVariables.getMessageMap().hasErrors()) { throw new ValidationException("Error(s) in search criteria"); } } /** * @see org.kuali.kfs.module.ar.report.service.TransmitContractsAndGrantsInvoicesService#sendEmailForListofInvoicesToAgency(java.util.Collection) */ @Override public boolean sendEmailForListofInvoicesToAgency(Collection<ContractsGrantsInvoiceDocument> list) throws InvalidAddressException, MessagingException { return arEmailService.sendInvoicesViaEmail(list); } public ContractsGrantsInvoiceDocumentService getContractsGrantsInvoiceDocumentService() { return contractsGrantsInvoiceDocumentService; } public void setContractsGrantsInvoiceDocumentService(ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService) { this.contractsGrantsInvoiceDocumentService = contractsGrantsInvoiceDocumentService; } public ContractsGrantsInvoiceReportService getContractsGrantsInvoiceReportService() { return contractsGrantsInvoiceReportService; } public void setContractsGrantsInvoiceReportService(ContractsGrantsInvoiceReportService contractsGrantsInvoiceReportService) { this.contractsGrantsInvoiceReportService = contractsGrantsInvoiceReportService; } public DateTimeService getDateTimeService() { return dateTimeService; } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } public DocumentService getDocumentService() { return documentService; } public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } public AREmailService getArEmailService() { return arEmailService; } public void setArEmailService(AREmailService arEmailService) { this.arEmailService = arEmailService; } }
work/src/org/kuali/kfs/module/ar/report/service/impl/TransmitContractsAndGrantsInvoicesServiceImpl.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.report.service.impl; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.mail.MessagingException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.module.ar.ArConstants; import org.kuali.kfs.module.ar.ArKeyConstants; import org.kuali.kfs.module.ar.ArPropertyConstants; import org.kuali.kfs.module.ar.businessobject.InvoiceAddressDetail; import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument; import org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService; import org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService; import org.kuali.kfs.module.ar.report.service.TransmitContractsAndGrantsInvoicesService; import org.kuali.kfs.module.ar.service.AREmailService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.KFSKeyConstants; import org.kuali.kfs.sys.KFSPropertyConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.util.KfsDateUtils; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.search.SearchOperator; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.kew.api.document.DocumentStatus; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kim.api.identity.PersonService; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.krad.exception.InvalidAddressException; import org.kuali.rice.krad.exception.ValidationException; import org.kuali.rice.krad.service.DocumentService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; import com.lowagie.text.DocumentException; /** * Default implementation of the TransmitContractsAndGrantsInvoicesService */ public class TransmitContractsAndGrantsInvoicesServiceImpl implements TransmitContractsAndGrantsInvoicesService { protected ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService; protected ContractsGrantsInvoiceReportService contractsGrantsInvoiceReportService; protected DateTimeService dateTimeService; protected DocumentService documentService; protected AREmailService arEmailService; /** * @see org.kuali.kfs.module.ar.report.service.TransmitContractsAndGrantsInvoicesService#getInvoicesByParametersFromRequest(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public Collection<ContractsGrantsInvoiceDocument> getInvoicesByParametersFromRequest(Map fieldValues) throws WorkflowException, ParseException { Date fromDate = null; Date toDate = null; String unformattedToDate = (String)fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_TO); if (StringUtils.isNotEmpty(unformattedToDate)) { toDate = dateTimeService.convertToDate(unformattedToDate); } String unformattedFromDate = (String)fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_FROM); if (StringUtils.isNotEmpty(unformattedFromDate)) { fromDate = dateTimeService.convertToDate(unformattedFromDate); } String invoiceInitiatorPrincipalName = (String) fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_INITIATOR_PRINCIPAL_NAME); if (StringUtils.isNotEmpty(invoiceInitiatorPrincipalName)) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(invoiceInitiatorPrincipalName); if (ObjectUtils.isNotNull(principal)) { fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.INITIATOR_PRINCIPAL_ID, principal.getPrincipalId()); } else { throw new IllegalArgumentException("The parameter value for initiatorPrincipalName [" + invoiceInitiatorPrincipalName + "] passed in does not map to a person."); } } String invoiceAmount = (String) fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT); if (StringUtils.isNotEmpty(invoiceAmount)) { fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.FINANCIAL_DOCUMENT_TOTAL_AMOUNT, invoiceAmount); } String invoiceTransmissionMethodCode = (String) fieldValues.get(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE); if (StringUtils.isNotBlank(invoiceTransmissionMethodCode)) { fieldValues.put(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_TRANSMISSION_METHOD_CODE, invoiceTransmissionMethodCode); } fieldValues.put(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INITIAL_TRANSMISSION_DATE, SearchOperator.NULL.op()); fieldValues.put(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_TRANSMISSION_METHOD_CODE, invoiceTransmissionMethodCode); fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE, DocumentStatus.FINAL.getCode() + SearchOperator.OR.op() + DocumentStatus.PROCESSED.getCode()); // filter out LOC CINV docs, we don't want those included in this process fieldValues.put(ArPropertyConstants.INVOICE_GENERAL_DETAIL + "." + ArPropertyConstants.BILLING_FREQUENCY_CODE, SearchOperator.NOT + ArConstants.LOC_BILLING_SCHEDULE_CODE); Collection<ContractsGrantsInvoiceDocument> list = getContractsGrantsInvoiceDocumentService().retrieveAllCGInvoicesByCriteria(fieldValues); Collection<ContractsGrantsInvoiceDocument> finalList = new ArrayList<ContractsGrantsInvoiceDocument>(); for (ContractsGrantsInvoiceDocument item : list) { ContractsGrantsInvoiceDocument invoice = (ContractsGrantsInvoiceDocument)getDocumentService().getByDocumentHeaderId(item.getDocumentNumber()); if (!invoice.isInvoiceReversal() && !invoice.hasInvoiceBeenCorrected()) { if (isInvoiceBetween(invoice, fromDate, toDate)) { if ((StringUtils.equals(ArConstants.InvoiceTransmissionMethod.EMAIL, invoiceTransmissionMethodCode) && isInvoiceValidToEmail(invoice)) || (StringUtils.equals(ArConstants.InvoiceTransmissionMethod.MAIL, invoiceTransmissionMethodCode) && isInvoiceValidToMail(invoice))) { finalList.add(invoice); } } } } return finalList; } /** * Checks whether invoice is between the dates provided. * @param invoice * @param fromDate * @param toDate * @return */ protected boolean isInvoiceBetween(ContractsGrantsInvoiceDocument invoice, Date fromDate, Date toDate) { Date dateCreated = invoice.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate(); if (ObjectUtils.isNotNull(fromDate)) { if (fromDate.after(dateCreated)) { return false; } } if (ObjectUtils.isNotNull(toDate)) { if (toDate.before(dateCreated) && !KfsDateUtils.isSameDay(toDate, dateCreated)) { return false; } } return true; } @Override public boolean isInvoiceValidToEmail(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { for (InvoiceAddressDetail invoiceAddressDetail : contractsGrantsInvoiceDocument.getInvoiceAddressDetails()) { if (ObjectUtils.isNull(invoiceAddressDetail.getInitialTransmissionDate()) && ArConstants.InvoiceTransmissionMethod.EMAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) { return true; } } return false; } @Override public boolean isInvoiceValidToMail(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { for (InvoiceAddressDetail invoiceAddressDetail : contractsGrantsInvoiceDocument.getInvoiceAddressDetails()) { if (ObjectUtils.isNull(invoiceAddressDetail.getInitialTransmissionDate()) && ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) { return true; } } return false; } @Override public boolean printInvoicesAndEnvelopesZip(Collection<ContractsGrantsInvoiceDocument> list, ByteArrayOutputStream baos) throws DocumentException, IOException { if (CollectionUtils.isNotEmpty(list)) { byte[] envelopes = contractsGrantsInvoiceReportService.combineInvoicePdfEnvelopes(list); byte[] report = contractsGrantsInvoiceReportService.combineInvoicePdfs(list); boolean invoiceFileWritten = false; boolean envelopeFileWritten = false; ZipOutputStream zos = new ZipOutputStream(baos); try { int bytesRead; byte[] buffer = new byte[1024]; CRC32 crc = new CRC32(); String invoiceFileName = ArConstants.INVOICES_FILE_PREFIX + getDateTimeService().toDateStringForFilename(getDateTimeService().getCurrentDate()) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION; invoiceFileWritten = writeFile(report, zos, invoiceFileName); String envelopeFileName = ArConstants.INVOICE_ENVELOPES_FILE_PREFIX + getDateTimeService().toDateStringForFilename(getDateTimeService().getCurrentDate()) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION; envelopeFileWritten = writeFile(envelopes, zos, envelopeFileName); } finally { zos.close(); } return invoiceFileWritten || envelopeFileWritten; } return false; } /** * * @param report * @param invoiceFileWritten * @param zos * @param buffer * @param crc * @return * @throws IOException */ private boolean writeFile(byte[] arrayToWrite, ZipOutputStream zos, String fileName) throws IOException { int bytesRead; byte[] buffer = new byte[1024]; CRC32 crc = new CRC32(); if (ObjectUtils.isNotNull(arrayToWrite) && arrayToWrite.length > 0) { BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(arrayToWrite)); try { while ((bytesRead = bis.read(buffer)) != -1) { crc.update(buffer, 0, bytesRead); } bis.close(); // Reset to beginning of input stream bis = new BufferedInputStream(new ByteArrayInputStream(arrayToWrite)); ZipEntry entry = new ZipEntry(fileName); entry.setMethod(ZipEntry.STORED); entry.setCompressedSize(arrayToWrite.length); entry.setSize(arrayToWrite.length); entry.setCrc(crc.getValue()); zos.putNextEntry(entry); while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } } finally { bis.close(); } return true; } return false; } @Override public void validateSearchParameters(Map<String,String> fieldValues) { String invoiceTransmissionMethodCode = fieldValues.get(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE); String invoiceInitiatorPrincipalName = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_INITIATOR_PRINCIPAL_NAME); String invoicePrintDateFromString = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_FROM); String invoicePrintDateToString = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_TO); String invoiceAmount = fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT); // To validate the input fields before fetching invoices. if (StringUtils.isBlank(invoiceTransmissionMethodCode)) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE, KFSKeyConstants.ERROR_REQUIRED, ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_TRANSMISSION_METHOD_CODE_LABEL); } if (StringUtils.isNotBlank(invoicePrintDateFromString)) { try { dateTimeService.convertToDate(invoicePrintDateFromString); } catch (ParseException e) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_FROM, KFSKeyConstants.ERROR_DATE_TIME, ArConstants.PRINT_INVOICES_FROM_LABEL); } } if (StringUtils.isNotBlank(invoicePrintDateToString)) { try { dateTimeService.convertToDate(invoicePrintDateToString); } catch (ParseException e) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_PRINT_DATE_TO, KFSKeyConstants.ERROR_DATE_TIME, ArConstants.PRINT_INVOICES_TO_LABEL); } } if (StringUtils.isNotBlank(invoiceAmount) && !KualiDecimal.isNumeric(invoiceAmount)) { GlobalVariables.getMessageMap().putError(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT, KFSKeyConstants.ERROR_NUMERIC, ArConstants.INVOICE_AMOUNT_LABEL); } if (StringUtils.isNotEmpty(invoiceInitiatorPrincipalName)) { Person person = SpringContext.getBean(PersonService.class).getPersonByPrincipalName(invoiceInitiatorPrincipalName); if (ObjectUtils.isNull(person)) { GlobalVariables.getMessageMap().putErrorForSectionId(ArPropertyConstants.LOOKUP_SECTION_ID, ArKeyConstants.NO_PRINCIPAL_NAME_FOUND); } } if (GlobalVariables.getMessageMap().hasErrors()) { throw new ValidationException("Error(s) in search criteria"); } } /** * @see org.kuali.kfs.module.ar.report.service.TransmitContractsAndGrantsInvoicesService#sendEmailForListofInvoicesToAgency(java.util.Collection) */ @Override public boolean sendEmailForListofInvoicesToAgency(Collection<ContractsGrantsInvoiceDocument> list) throws InvalidAddressException, MessagingException { return arEmailService.sendInvoicesViaEmail(list); } public ContractsGrantsInvoiceDocumentService getContractsGrantsInvoiceDocumentService() { return contractsGrantsInvoiceDocumentService; } public void setContractsGrantsInvoiceDocumentService(ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService) { this.contractsGrantsInvoiceDocumentService = contractsGrantsInvoiceDocumentService; } public ContractsGrantsInvoiceReportService getContractsGrantsInvoiceReportService() { return contractsGrantsInvoiceReportService; } public void setContractsGrantsInvoiceReportService(ContractsGrantsInvoiceReportService contractsGrantsInvoiceReportService) { this.contractsGrantsInvoiceReportService = contractsGrantsInvoiceReportService; } public DateTimeService getDateTimeService() { return dateTimeService; } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } public DocumentService getDocumentService() { return documentService; } public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } public AREmailService getArEmailService() { return arEmailService; } public void setArEmailService(AREmailService arEmailService) { this.arEmailService = arEmailService; } }
KFSTP-1762 - fix proposal number filtering
work/src/org/kuali/kfs/module/ar/report/service/impl/TransmitContractsAndGrantsInvoicesServiceImpl.java
KFSTP-1762 - fix proposal number filtering
<ide><path>ork/src/org/kuali/kfs/module/ar/report/service/impl/TransmitContractsAndGrantsInvoicesServiceImpl.java <ide> /* <ide> * The Kuali Financial System, a comprehensive financial management system for higher education. <del> * <add> * <ide> * Copyright 2005-2014 The Kuali Foundation <del> * <add> * <ide> * This program is free software: you can redistribute it and/or modify <ide> * it under the terms of the GNU Affero General Public License as <ide> * published by the Free Software Foundation, either version 3 of the <ide> * License, or (at your option) any later version. <del> * <add> * <ide> * This program is distributed in the hope that it will be useful, <ide> * but WITHOUT ANY WARRANTY; without even the implied warranty of <ide> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <ide> * GNU Affero General Public License for more details. <del> * <add> * <ide> * You should have received a copy of the GNU Affero General Public License <ide> * along with this program. If not, see <http://www.gnu.org/licenses/>. <ide> */ <ide> } <ide> } <ide> <add> String proposalNumber = (String) fieldValues.get(KFSPropertyConstants.PROPOSAL_NUMBER); <add> if (StringUtils.isNotEmpty(proposalNumber)) { <add> fieldValues.put(ArPropertyConstants.ContractsGrantsInvoiceDocumentFields.PROPOSAL_NUMBER, proposalNumber); <add> } <add> <ide> String invoiceAmount = (String) fieldValues.get(ArPropertyConstants.TransmitContractsAndGrantsInvoicesLookupFields.INVOICE_AMOUNT); <ide> if (StringUtils.isNotEmpty(invoiceAmount)) { <ide> fieldValues.put(KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.FINANCIAL_DOCUMENT_TOTAL_AMOUNT, invoiceAmount);
Java
mit
b67fc9f8d9086359e61edb7cf07e8f378c5381d6
0
nwcaldwell/Java,nwcaldwell/Java
package view.cgi; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import org.lwjgl.opengl.GL11; /**A factory class for loading models from files. * Currently only loads OBJ files. * * This class is distinct from MediaController because of * its dependency on LWJGL, which is non-standard, and should * not be a dependency for implementations that may not have * LWJGL.*/ public class ModelFactory { public static final String OBJ_VERTEX="v"; public static final String OBJ_TEXTURE_COORD="vt"; public static final String OBJ_SURFACE_NORMAL="vn"; public static final String OBJ_FACE="f"; /**makes a model from an obj file with a SINGLE OBJECT * and a texture reference.*/ public static Model3D makeFromObj(File model, int texture){ Scanner scan = null; try { scan = new Scanner(model); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } //list of faces for this model ArrayList<Face3D> faces=new ArrayList<Face3D>(); //vertices ArrayList<Vector3D> vertices=new ArrayList<Vector3D>(); //texture coordinates ArrayList<Vector2D> coords=new ArrayList<Vector2D>(); //surface normals by vertex ArrayList<Vector3D> normals=new ArrayList<Vector3D>(); String fileLine="#"; while (scan.hasNext()){ fileLine=scan.nextLine(); //split the line with whitespaces String[] tokens = fileLine.split("\\s+"); //skip empty strings if (tokens.length>0){ if (tokens[0].equalsIgnoreCase(OBJ_VERTEX)){ //it's a vertex float x=Float.parseFloat(tokens[1]); float y=Float.parseFloat(tokens[2]); float z=Float.parseFloat(tokens[3]); vertices.add(new Vector3D(x, y, z)); } if (tokens[0].equalsIgnoreCase(OBJ_SURFACE_NORMAL)){ //it's a vertex float x=Float.parseFloat(tokens[1]); float y=Float.parseFloat(tokens[2]); float z=Float.parseFloat(tokens[3]); normals.add(new Vector3D(x, y, z)); } if (tokens[0].equalsIgnoreCase(OBJ_TEXTURE_COORD)){ //it's a vertex float x=Float.parseFloat(tokens[1]); float y=Float.parseFloat(tokens[2]); //y values must flip coords.add(new Vector2D(x, 1-y)); } if (tokens[0].equalsIgnoreCase(OBJ_FACE)){ //it's a vertex Vector3D[] fv=new Vector3D[tokens.length-1]; Vector2D[] fc=new Vector2D[tokens.length-1]; Vector3D[] fn=new Vector3D[tokens.length-1]; boolean fullTextureData=true; boolean fullNormalData=true; boolean tristrip=false; for (int i=1;i<tokens.length;i++){ String[] indicies=tokens[i].split("/"); fv[tokens.length-(i+1)]=vertices.get(Integer.parseInt(indicies[0])-1); if (indicies[1].length()>0){ fc[tokens.length-(i+1)]=coords.get(Integer.parseInt(indicies[1])-1); }else{ fullTextureData=false; } if (indicies.length>2&&indicies[2].length()>0){ fn[tokens.length-(i+1)]=normals.get(Integer.parseInt(indicies[2])-1); }else{ fullNormalData=false; } if (i==5){ tristrip=true; } } int rendType=GL11.GL_TRIANGLES; if (fv.length==4){ rendType=GL11.GL_QUADS; } try { //simple triangulatioin for concave shapes. if (rendType!=GL11.GL_QUADS){ for (int i=2;i<fv.length;i++){ Vector3D[] triverts=new Vector3D[3]; triverts[0]=fv[0]; triverts[1]=fv[i-1]; triverts[2]=fv[i]; if (fullTextureData){ Vector2D[] tritex=new Vector2D[3]; tritex[0]=fc[0]; tritex[1]=fc[i-1]; tritex[2]=fc[i]; faces.add(new TexturedFace3D(texture, triverts, tritex, rendType)); }else{ faces.add(new Face3D(triverts, rendType)); } if (fullNormalData){ Vector3D[] trinorms=new Vector3D[3]; trinorms[0]=fv[0]; trinorms[1]=fv[i-1]; trinorms[2]=fv[i]; faces.get(faces.size()-1).setNormals(trinorms); } } } else { for (int i=2;i<fv.length;i++){ if (fullTextureData){ faces.add(new TexturedFace3D(texture, fv, fc, rendType)); }else{ faces.add(new Face3D(fv, rendType)); } if (fullNormalData){ faces.get(faces.size()-1).setNormals(fn); } } } } catch (Exception e) { System.err.println("OBJ file parsing: impossible error: complain to Christopher"); e.printStackTrace(); } } } } scan.close(); return new Model3D(faces); } }
src/view/cgi/ModelFactory.java
package view.cgi; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import org.lwjgl.opengl.GL11; /**A factory class for loading models from files. * Currently only loads OBJ files. * * This class is distinct from MediaController because of * its dependency on LWJGL, which is non-standard, and should * not be a dependency for implementations that may not have * LWJGL.*/ public class ModelFactory { public static final String OBJ_VERTEX="v"; public static final String OBJ_TEXTURE_COORD="vt"; public static final String OBJ_SURFACE_NORMAL="vn"; public static final String OBJ_FACE="f"; /**makes a model from an obj file with a SINGLE OBJECT * and a texture reference.*/ public static Model3D makeFromObj(File model, int texture){ Scanner scan = null; try { scan = new Scanner(model); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } //list of faces for this model ArrayList<Face3D> faces=new ArrayList<Face3D>(); //vertices ArrayList<Vector3D> vertices=new ArrayList<Vector3D>(); //texture coordinates ArrayList<Vector2D> coords=new ArrayList<Vector2D>(); //surface normals by vertex ArrayList<Vector3D> normals=new ArrayList<Vector3D>(); String fileLine="#"; while (scan.hasNext()){ fileLine=scan.nextLine(); //split the line with whitespaces String[] tokens = fileLine.split("\\s+"); //skip empty strings if (tokens.length>0){ if (tokens[0].equalsIgnoreCase(OBJ_VERTEX)){ //it's a vertex float x=Float.parseFloat(tokens[1]); float y=Float.parseFloat(tokens[2]); float z=Float.parseFloat(tokens[3]); vertices.add(new Vector3D(x, y, z)); } if (tokens[0].equalsIgnoreCase(OBJ_SURFACE_NORMAL)){ //it's a vertex float x=Float.parseFloat(tokens[1]); float y=Float.parseFloat(tokens[2]); float z=Float.parseFloat(tokens[3]); normals.add(new Vector3D(x, y, z)); } if (tokens[0].equalsIgnoreCase(OBJ_TEXTURE_COORD)){ //it's a vertex float x=Float.parseFloat(tokens[1]); float y=Float.parseFloat(tokens[2]); //y values must flip coords.add(new Vector2D(x, 1-y)); } if (tokens[0].equalsIgnoreCase(OBJ_FACE)){ //it's a vertex Vector3D[] fv=new Vector3D[tokens.length-1]; Vector2D[] fc=new Vector2D[tokens.length-1]; Vector3D[] fn=new Vector3D[tokens.length-1]; boolean fullTextureData=true; boolean fullNormalData=true; boolean tristrip=false; for (int i=1;i<tokens.length;i++){ String[] indicies=tokens[i].split("/"); fv[tokens.length-(i+1)]=vertices.get(Integer.parseInt(indicies[0])-1); if (indicies[1].length()>0){ fc[tokens.length-(i+1)]=coords.get(Integer.parseInt(indicies[1])-1); }else{ fullTextureData=false; } if (indicies.length>2&&indicies[2].length()>0){ fn[tokens.length-(i+1)]=normals.get(Integer.parseInt(indicies[2])-1); }else{ fullNormalData=false; } if (i==5){ tristrip=true; } } int rendType=GL11.GL_TRIANGLES; if (fv.length==4){ rendType=GL11.GL_QUADS; } if (fv.length>4){ rendType=GL11.GL_TRIANGLE_STRIP; System.out.println("trisrip"); } try { if (fullTextureData){ faces.add(new TexturedFace3D(texture, fv, fc, rendType)); }else{ faces.add(new Face3D(fv, rendType)); } if (fullNormalData){ faces.get(faces.size()-1).setNormals(fn); } } catch (Exception e) { System.err.println("OBJ file parsing: impossible error: complain to Christopher"); e.printStackTrace(); } } } } scan.close(); return new Model3D(faces); } }
ModelFactory can now triangulate convex faces.
src/view/cgi/ModelFactory.java
ModelFactory can now triangulate convex faces.
<ide><path>rc/view/cgi/ModelFactory.java <ide> if (fv.length==4){ <ide> rendType=GL11.GL_QUADS; <ide> } <del> if (fv.length>4){ <del> rendType=GL11.GL_TRIANGLE_STRIP; <del> System.out.println("trisrip"); <del> } <ide> try { <del> if (fullTextureData){ <del> faces.add(new TexturedFace3D(texture, fv, fc, rendType)); <del> }else{ <del> faces.add(new Face3D(fv, rendType)); <del> } <del> if (fullNormalData){ <del> faces.get(faces.size()-1).setNormals(fn); <add> //simple triangulatioin for concave shapes. <add> if (rendType!=GL11.GL_QUADS){ <add> for (int i=2;i<fv.length;i++){ <add> Vector3D[] triverts=new Vector3D[3]; <add> triverts[0]=fv[0]; <add> triverts[1]=fv[i-1]; <add> triverts[2]=fv[i]; <add> if (fullTextureData){ <add> Vector2D[] tritex=new Vector2D[3]; <add> tritex[0]=fc[0]; <add> tritex[1]=fc[i-1]; <add> tritex[2]=fc[i]; <add> faces.add(new TexturedFace3D(texture, triverts, tritex, rendType)); <add> }else{ <add> faces.add(new Face3D(triverts, rendType)); <add> } <add> if (fullNormalData){ <add> Vector3D[] trinorms=new Vector3D[3]; <add> trinorms[0]=fv[0]; <add> trinorms[1]=fv[i-1]; <add> trinorms[2]=fv[i]; <add> faces.get(faces.size()-1).setNormals(trinorms); <add> } <add> } <add> } else { <add> for (int i=2;i<fv.length;i++){ <add> if (fullTextureData){ <add> faces.add(new TexturedFace3D(texture, fv, fc, rendType)); <add> }else{ <add> faces.add(new Face3D(fv, rendType)); <add> } <add> if (fullNormalData){ <add> faces.get(faces.size()-1).setNormals(fn); <add> } <add> } <ide> } <ide> } catch (Exception e) { <ide> System.err.println("OBJ file parsing: impossible error: complain to Christopher");
Java
apache-2.0
00735c67bab4f4f8ff83ca1061c4c815152deac5
0
gbif/occurrence,gbif/occurrence,gbif/occurrence
package org.gbif.occurrence.cli.registry; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.model.common.paging.PagingResponse; import org.gbif.api.model.registry.Dataset; import org.gbif.api.model.registry.Endpoint; import org.gbif.api.model.registry.Organization; import org.gbif.api.service.registry.OrganizationService; import org.gbif.api.util.comparators.EndpointPriorityComparator; import org.gbif.api.vocabulary.EndpointType; import org.gbif.common.messaging.AbstractMessageCallback; import org.gbif.common.messaging.api.MessagePublisher; import org.gbif.common.messaging.api.messages.*; import org.gbif.occurrence.cli.registry.sync.OccurrenceScanMapper; import org.gbif.occurrence.cli.registry.sync.RegistryBasedOccurrenceMutator; import org.gbif.occurrence.cli.registry.sync.SyncCommon; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Listens for any registry changes {@link RegistryChangeMessage} * of interest to occurrences: namely organization and dataset updates or deletions. * <p> * This was written at a time when we only looked at occurrence datasets, but without * planning, it is now the process that also triggers crawling for checklist datasets, * and metadata-only datasets. */ public class RegistryChangeListener extends AbstractMessageCallback<RegistryChangeMessage> { private static final Logger LOG = LoggerFactory.getLogger(RegistryChangeListener.class); private static final int PAGING_LIMIT = 20; private static final String HBASE_TIMEOUT = "600000"; private static final String MR_MAP_MEMORY_MB = "1024"; //approx. 85% of MR_MAP_MEMORY_MB private static final String MR_MAP_JAVA_OPTS = "-Xmx768m"; private static final String MR_QUEUE_NAME = "crap"; private static final Set<EndpointType> CRAWLABLE_ENDPOINT_TYPES = new ImmutableSet.Builder<EndpointType>().add( EndpointType.BIOCASE, EndpointType.DIGIR, EndpointType.DIGIR_MANIS, EndpointType.TAPIR, EndpointType.DWC_ARCHIVE, EndpointType.EML).build(); // pipelines private static final String METADATA_INTERPRETATION = "METADATA"; private static final String LOCATION_INTERPRETATION = "LOCATION"; /* When an IPT publishes a new dataset we will get multiple messages from the registry informing us of the update (depending on the number of endpoints, contacts etc). We only want to send a single crawl message for one of those updates so we cache the dataset uuid for 5 seconds, which should be long enough to handle all of the registry updates. */ private static final Cache<UUID, Object> RECENTLY_UPDATED_DATASETS = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).initialCapacity(10).maximumSize(1000).build(); // used as a value for the cache - we only care about the keys private static final Object EMPTY_VALUE = new Object(); private final MessagePublisher messagePublisher; private final OrganizationService orgService; private RegistryBasedOccurrenceMutator occurrenceMutator; public RegistryChangeListener(MessagePublisher messagePublisher, OrganizationService orgService) { this.messagePublisher = messagePublisher; this.orgService = orgService; this.occurrenceMutator = new RegistryBasedOccurrenceMutator(); } @Override public void handleMessage(RegistryChangeMessage message) { LOG.info("Handling registry [{}] msg for class [{}]", message.getChangeType(), message.getObjectClass()); Class<?> clazz = message.getObjectClass(); if ("Dataset".equals(clazz.getSimpleName())) { handleDataset(message.getChangeType(), (Dataset) message.getOldObject(), (Dataset) message.getNewObject()); } else if ("Organization".equals(clazz.getSimpleName())) { handleOrganization(message.getChangeType(), (Organization) message.getOldObject(), (Organization) message.getNewObject()); } } private void handleDataset(RegistryChangeMessage.ChangeType changeType, Dataset oldDataset, Dataset newDataset) { switch (changeType) { case DELETED: LOG.info("Sending delete for dataset [{}]", oldDataset.getKey()); try { messagePublisher.send(new DeleteDatasetOccurrencesMessage(oldDataset.getKey(), OccurrenceDeletionReason.DATASET_MANUAL)); } catch (IOException e) { LOG.warn("Could not send delete dataset message for key [{}]", oldDataset.getKey(), e); } break; case UPDATED: // if it has a crawlable endpoint and we haven't just sent a crawl msg, we need to crawl it no matter what changed if (shouldCrawl(newDataset)) { LOG.info("Sending crawl for updated dataset [{}]", newDataset.getKey()); try { messagePublisher.send(new StartCrawlMessage(newDataset.getKey())); } catch (IOException e) { LOG.warn("Could not send start crawl message for dataset key [{}]", newDataset.getKey(), e); } // check if we should start a m/r job to update occurrence records // FIXME this can lead to issues if 100 datasets change organization in a batch update. if (occurrenceMutator.requiresUpdate(oldDataset, newDataset)) { Optional<String> changedMessage = occurrenceMutator.generateUpdateMessage(oldDataset, newDataset); // send message to pipelines sendUpdateMessageToPipelines( newDataset, Collections.singleton(METADATA_INTERPRETATION), changedMessage.orElse("Dataset changed in registry")); LOG.info("Starting m/r sync for dataset [{}], with reason {}", newDataset.getKey(), changedMessage); try { runMrSync(newDataset.getKey()); } catch (Exception e) { LOG.warn("Failed to run RegistrySync m/r for dataset [{}]", newDataset.getKey(), e); } } else { LOG.debug("Owning orgs and license match for updated dataset [{}] - taking no action", newDataset.getKey()); } } else { LOG.info("Ignoring update of dataset [{}] because either no crawlable endpoints or we just sent a crawl", newDataset.getKey()); } break; case CREATED: if (shouldCrawl(newDataset)) { LOG.info("Sending crawl for new dataset [{}]", newDataset.getKey()); try { messagePublisher.send(new StartCrawlMessage(newDataset.getKey())); } catch (IOException e) { LOG.warn("Could not send start crawl message for dataset key [{}]", newDataset.getKey(), e); } } else { LOG.info("Ignoring creation of dataset [{}] because no crawlable endpoints or we just sent a crawl", newDataset.getKey()); } break; } } private static boolean shouldCrawl(Dataset dataset) { if (RECENTLY_UPDATED_DATASETS.getIfPresent(dataset.getKey()) == null && isCrawlable(dataset)) { RECENTLY_UPDATED_DATASETS.put(dataset.getKey(), EMPTY_VALUE); return true; } return false; } private static boolean isCrawlable(Dataset dataset) { for (Endpoint endpoint : dataset.getEndpoints()) { if (CRAWLABLE_ENDPOINT_TYPES.contains(endpoint.getType())) { return true; } } return false; } private void handleOrganization( RegistryChangeMessage.ChangeType changeType, Organization oldOrg, Organization newOrg ) { switch (changeType) { case UPDATED: if (!oldOrg.isEndorsementApproved() && newOrg.isEndorsementApproved()) { LOG.info("Starting crawl of all datasets for newly endorsed org [{}]", newOrg.getKey()); DatasetVisitor visitor = dataset -> { try { messagePublisher.send(new StartCrawlMessage(dataset.getKey())); } catch (IOException e) { LOG.warn("Could not send start crawl message for newly endorsed dataset key [{}]", dataset.getKey(), e); } }; visitOwnedDatasets(newOrg.getKey(), visitor); } else if (occurrenceMutator.requiresUpdate(oldOrg, newOrg) && newOrg.getNumPublishedDatasets() > 0) { LOG.info( "Starting m/r sync for all datasets of org [{}] because it has changed country from [{}] to [{}]", newOrg.getKey(), oldOrg.getCountry(), newOrg.getCountry()); DatasetVisitor visitor = dataset -> { sendUpdateMessageToPipelines( dataset, Sets.newHashSet(METADATA_INTERPRETATION, LOCATION_INTERPRETATION), occurrenceMutator .generateUpdateMessage(oldOrg, newOrg) .orElse("Organization change in registry")); runMrSync(dataset.getKey()); }; visitOwnedDatasets(newOrg.getKey(), visitor); } break; case DELETED: case CREATED: break; } } /** * Creates and submit a MapReduce job to the cluster using {@link OccurrenceScanMapper} as a mapper. */ private static void runMrSync(@Nullable UUID datasetKey) { //create the HBase config here since hbase-site.xml is (at least should) be in our classpath. Configuration conf = HBaseConfiguration.create(); conf.set("hbase.client.scanner.timeout.period", HBASE_TIMEOUT); conf.set("hbase.rpc.timeout", HBASE_TIMEOUT); Properties props = SyncCommon.loadProperties(); // add all props to job context for use by the OccurrenceScanMapper when it no longer has access to our classpath for (Object key : props.keySet()) { String stringKey = (String) key; conf.set(stringKey, props.getProperty(stringKey)); } Scan scan = new Scan(); scan.addColumn(SyncCommon.OCC_CF, SyncCommon.DK_COL); //datasetKey scan.addColumn(SyncCommon.OCC_CF, SyncCommon.HC_COL); //publishingCountry scan.addColumn(SyncCommon.OCC_CF, SyncCommon.OOK_COL); //publishingOrgKey scan.addColumn(SyncCommon.OCC_CF, SyncCommon.CI_COL); //crawlId scan.addColumn(SyncCommon.OCC_CF, SyncCommon.LICENSE_COL); scan.setCaching(200); scan.setCacheBlocks(false); // don't set to true for MR jobs (from HBase MapReduce Examples) String targetTable = props.getProperty(SyncCommon.OCC_TABLE_PROPS_KEY); String mrUser = props.getProperty(SyncCommon.MR_USER_PROPS_KEY); String jobTitle = "Registry-Occurrence Sync on table " + targetTable; String rawDatasetKey = null; if (datasetKey != null) { rawDatasetKey = datasetKey.toString(); scan.setFilter(new SingleColumnValueFilter(SyncCommon.OCC_CF, SyncCommon.DK_COL, CompareFilter.CompareOp.EQUAL, Bytes.toBytes(rawDatasetKey))); } if (rawDatasetKey != null) { jobTitle = jobTitle + " for dataset " + rawDatasetKey; } try { Job job = Job.getInstance(conf, jobTitle); job.setUser(mrUser); job.setJarByClass(OccurrenceScanMapper.class); job.setOutputFormatClass(NullOutputFormat.class); job.setNumReduceTasks(0); job.getConfiguration().set("mapreduce.map.speculative", "false"); job.getConfiguration().set("mapreduce.reduce.speculative", "false"); job.getConfiguration().set("mapreduce.client.submit.file.replication", "3"); job.getConfiguration().set("mapreduce.task.classpath.user.precedence", "true"); job.getConfiguration().set("mapreduce.job.user.classpath.first", "true"); job.getConfiguration().set("mapreduce.map.memory.mb", MR_MAP_MEMORY_MB); job.getConfiguration().set("mapreduce.map.java.opts", MR_MAP_JAVA_OPTS); job.getConfiguration().set("mapred.job.queue.name", MR_QUEUE_NAME); if (targetTable == null || mrUser == null) { LOG.error("Sync m/r not properly configured (occ table or mapreduce user not set) - aborting"); } else { // NOTE: addDependencyJars must be false or you'll see it trying to load hdfs://c1n1/home/user/app/lib/occurrence-cli.jar TableMapReduceUtil.initTableMapperJob(targetTable, scan, OccurrenceScanMapper.class, ImmutableBytesWritable.class, NullWritable.class, job, false); job.waitForCompletion(true); } } catch (Exception e) { LOG.error("Could not start m/r job, aborting", e); } LOG.info("Finished running m/r sync for dataset [{}]", datasetKey); } private void visitOwnedDatasets(UUID orgKey, DatasetVisitor visitor) { int datasetCount = 0; boolean endOfRecords = false; int offset = 0; do { Pageable page = new PagingRequest(offset, PAGING_LIMIT); PagingResponse<Dataset> datasets = orgService.publishedDatasets(orgKey, page); for (Dataset dataset : datasets.getResults()) { visitor.visit(dataset); } datasetCount += datasets.getResults().size(); offset += PAGING_LIMIT; if (datasets.isEndOfRecords()) { endOfRecords = datasets.isEndOfRecords(); } } while (!endOfRecords); LOG.info("Visited [{}] datasets owned by org [{}]", datasetCount, orgKey); } private interface DatasetVisitor { void visit(Dataset dataset); } /** * Sends message to pipelines to update the metadata of the dataset. * * @param dataset dataset to update * @param interpretations interpretations that should be run * @param changedMessage message with the change occurred in the registry */ private void sendUpdateMessageToPipelines(Dataset dataset, Set<String> interpretations, String changedMessage) { Optional<Endpoint> endpoint = getEndpoint(dataset); if (!endpoint.isPresent()) { LOG.error( "Could not find a valid endpoint for dataset {}. Message to pipelines to update metadata NOT SENT", dataset.getKey()); return; } LOG.info( "Sending a message to pipelines to update the metadata for dataset [{}], with reason {}", dataset.getKey(), changedMessage); try { PipelinesVerbatimMessage message = new PipelinesVerbatimMessage( dataset.getKey(), null, interpretations, Sets.newHashSet("VERBATIM_TO_INTERPRETED", "INTERPRETED_TO_INDEX"), endpoint.get().getType()); messagePublisher.send( new PipelinesBalancerMessage(message.getClass().getSimpleName(), message.toString())); } catch (IOException e) { LOG.error("Could not send message to pipelines to update metadata for dataset [{}]", dataset.getKey(), e); } } private Optional<Endpoint> getEndpoint(Dataset dataset) { return dataset.getEndpoints() .stream() .filter(e -> EndpointPriorityComparator.PRIORITIES.contains(e.getType())) .min(new EndpointPriorityComparator()); } }
occurrence-registry-sync/src/main/java/org/gbif/occurrence/cli/registry/RegistryChangeListener.java
package org.gbif.occurrence.cli.registry; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.model.common.paging.PagingResponse; import org.gbif.api.model.registry.Dataset; import org.gbif.api.model.registry.Endpoint; import org.gbif.api.model.registry.Organization; import org.gbif.api.service.registry.OrganizationService; import org.gbif.api.util.comparators.EndpointPriorityComparator; import org.gbif.api.vocabulary.EndpointType; import org.gbif.common.messaging.AbstractMessageCallback; import org.gbif.common.messaging.api.MessagePublisher; import org.gbif.common.messaging.api.messages.*; import org.gbif.occurrence.cli.registry.sync.OccurrenceScanMapper; import org.gbif.occurrence.cli.registry.sync.RegistryBasedOccurrenceMutator; import org.gbif.occurrence.cli.registry.sync.SyncCommon; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Listens for any registry changes {@link RegistryChangeMessage} * of interest to occurrences: namely organization and dataset updates or deletions. * <p> * This was written at a time when we only looked at occurrence datasets, but without * planning, it is now the process that also triggers crawling for checklist datasets, * and metadata-only datasets. */ public class RegistryChangeListener extends AbstractMessageCallback<RegistryChangeMessage> { private static final Logger LOG = LoggerFactory.getLogger(RegistryChangeListener.class); private static final int PAGING_LIMIT = 20; private static final String HBASE_TIMEOUT = "600000"; private static final String MR_MAP_MEMORY_MB = "1024"; //approx. 85% of MR_MAP_MEMORY_MB private static final String MR_MAP_JAVA_OPTS = "-Xmx768m"; private static final String MR_QUEUE_NAME = "crap"; private static final Set<EndpointType> CRAWLABLE_ENDPOINT_TYPES = new ImmutableSet.Builder<EndpointType>().add( EndpointType.BIOCASE, EndpointType.DIGIR, EndpointType.DIGIR_MANIS, EndpointType.TAPIR, EndpointType.DWC_ARCHIVE, EndpointType.EML).build(); /* When an IPT publishes a new dataset we will get multiple messages from the registry informing us of the update (depending on the number of endpoints, contacts etc). We only want to send a single crawl message for one of those updates so we cache the dataset uuid for 5 seconds, which should be long enough to handle all of the registry updates. */ private static final Cache<UUID, Object> RECENTLY_UPDATED_DATASETS = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).initialCapacity(10).maximumSize(1000).build(); // used as a value for the cache - we only care about the keys private static final Object EMPTY_VALUE = new Object(); private final MessagePublisher messagePublisher; private final OrganizationService orgService; private RegistryBasedOccurrenceMutator occurrenceMutator; public RegistryChangeListener(MessagePublisher messagePublisher, OrganizationService orgService) { this.messagePublisher = messagePublisher; this.orgService = orgService; this.occurrenceMutator = new RegistryBasedOccurrenceMutator(); } @Override public void handleMessage(RegistryChangeMessage message) { LOG.info("Handling registry [{}] msg for class [{}]", message.getChangeType(), message.getObjectClass()); Class<?> clazz = message.getObjectClass(); if ("Dataset".equals(clazz.getSimpleName())) { handleDataset(message.getChangeType(), (Dataset) message.getOldObject(), (Dataset) message.getNewObject()); } else if ("Organization".equals(clazz.getSimpleName())) { handleOrganization(message.getChangeType(), (Organization) message.getOldObject(), (Organization) message.getNewObject()); } } private void handleDataset(RegistryChangeMessage.ChangeType changeType, Dataset oldDataset, Dataset newDataset) { switch (changeType) { case DELETED: LOG.info("Sending delete for dataset [{}]", oldDataset.getKey()); try { messagePublisher.send(new DeleteDatasetOccurrencesMessage(oldDataset.getKey(), OccurrenceDeletionReason.DATASET_MANUAL)); } catch (IOException e) { LOG.warn("Could not send delete dataset message for key [{}]", oldDataset.getKey(), e); } break; case UPDATED: // if it has a crawlable endpoint and we haven't just sent a crawl msg, we need to crawl it no matter what changed if (shouldCrawl(newDataset)) { LOG.info("Sending crawl for updated dataset [{}]", newDataset.getKey()); try { messagePublisher.send(new StartCrawlMessage(newDataset.getKey())); } catch (IOException e) { LOG.warn("Could not send start crawl message for dataset key [{}]", newDataset.getKey(), e); } // check if we should start a m/r job to update occurrence records // FIXME this can lead to issues if 100 datasets change organization in a batch update. if (occurrenceMutator.requiresUpdate(oldDataset, newDataset)) { Optional<String> changedMessage = occurrenceMutator.generateUpdateMessage(oldDataset, newDataset); // send message to pipelines sendUpdateMetadataMessageToPipelines( newDataset, changedMessage.orElse("Dataset changed in registry")); LOG.info("Starting m/r sync for dataset [{}], with reason {}", newDataset.getKey(), changedMessage); try { runMrSync(newDataset.getKey()); } catch (Exception e) { LOG.warn("Failed to run RegistrySync m/r for dataset [{}]", newDataset.getKey(), e); } } else { LOG.debug("Owning orgs and license match for updated dataset [{}] - taking no action", newDataset.getKey()); } } else { LOG.info("Ignoring update of dataset [{}] because either no crawlable endpoints or we just sent a crawl", newDataset.getKey()); } break; case CREATED: if (shouldCrawl(newDataset)) { LOG.info("Sending crawl for new dataset [{}]", newDataset.getKey()); try { messagePublisher.send(new StartCrawlMessage(newDataset.getKey())); } catch (IOException e) { LOG.warn("Could not send start crawl message for dataset key [{}]", newDataset.getKey(), e); } } else { LOG.info("Ignoring creation of dataset [{}] because no crawlable endpoints or we just sent a crawl", newDataset.getKey()); } break; } } private static boolean shouldCrawl(Dataset dataset) { if (RECENTLY_UPDATED_DATASETS.getIfPresent(dataset.getKey()) == null && isCrawlable(dataset)) { RECENTLY_UPDATED_DATASETS.put(dataset.getKey(), EMPTY_VALUE); return true; } return false; } private static boolean isCrawlable(Dataset dataset) { for (Endpoint endpoint : dataset.getEndpoints()) { if (CRAWLABLE_ENDPOINT_TYPES.contains(endpoint.getType())) { return true; } } return false; } private void handleOrganization( RegistryChangeMessage.ChangeType changeType, Organization oldOrg, Organization newOrg ) { switch (changeType) { case UPDATED: if (!oldOrg.isEndorsementApproved() && newOrg.isEndorsementApproved()) { LOG.info("Starting crawl of all datasets for newly endorsed org [{}]", newOrg.getKey()); DatasetVisitor visitor = dataset -> { try { messagePublisher.send(new StartCrawlMessage(dataset.getKey())); } catch (IOException e) { LOG.warn("Could not send start crawl message for newly endorsed dataset key [{}]", dataset.getKey(), e); } }; visitOwnedDatasets(newOrg.getKey(), visitor); } else if (occurrenceMutator.requiresUpdate(oldOrg, newOrg) && newOrg.getNumPublishedDatasets() > 0) { LOG.info( "Starting m/r sync for all datasets of org [{}] because it has changed country from [{}] to [{}]", newOrg.getKey(), oldOrg.getCountry(), newOrg.getCountry()); DatasetVisitor visitor = dataset -> { sendUpdateMetadataMessageToPipelines( dataset, occurrenceMutator .generateUpdateMessage(oldOrg, newOrg) .orElse("Organization change in registry")); runMrSync(dataset.getKey()); }; visitOwnedDatasets(newOrg.getKey(), visitor); } break; case DELETED: case CREATED: break; } } /** * Creates and submit a MapReduce job to the cluster using {@link OccurrenceScanMapper} as a mapper. */ private static void runMrSync(@Nullable UUID datasetKey) { //create the HBase config here since hbase-site.xml is (at least should) be in our classpath. Configuration conf = HBaseConfiguration.create(); conf.set("hbase.client.scanner.timeout.period", HBASE_TIMEOUT); conf.set("hbase.rpc.timeout", HBASE_TIMEOUT); Properties props = SyncCommon.loadProperties(); // add all props to job context for use by the OccurrenceScanMapper when it no longer has access to our classpath for (Object key : props.keySet()) { String stringKey = (String) key; conf.set(stringKey, props.getProperty(stringKey)); } Scan scan = new Scan(); scan.addColumn(SyncCommon.OCC_CF, SyncCommon.DK_COL); //datasetKey scan.addColumn(SyncCommon.OCC_CF, SyncCommon.HC_COL); //publishingCountry scan.addColumn(SyncCommon.OCC_CF, SyncCommon.OOK_COL); //publishingOrgKey scan.addColumn(SyncCommon.OCC_CF, SyncCommon.CI_COL); //crawlId scan.addColumn(SyncCommon.OCC_CF, SyncCommon.LICENSE_COL); scan.setCaching(200); scan.setCacheBlocks(false); // don't set to true for MR jobs (from HBase MapReduce Examples) String targetTable = props.getProperty(SyncCommon.OCC_TABLE_PROPS_KEY); String mrUser = props.getProperty(SyncCommon.MR_USER_PROPS_KEY); String jobTitle = "Registry-Occurrence Sync on table " + targetTable; String rawDatasetKey = null; if (datasetKey != null) { rawDatasetKey = datasetKey.toString(); scan.setFilter(new SingleColumnValueFilter(SyncCommon.OCC_CF, SyncCommon.DK_COL, CompareFilter.CompareOp.EQUAL, Bytes.toBytes(rawDatasetKey))); } if (rawDatasetKey != null) { jobTitle = jobTitle + " for dataset " + rawDatasetKey; } try { Job job = Job.getInstance(conf, jobTitle); job.setUser(mrUser); job.setJarByClass(OccurrenceScanMapper.class); job.setOutputFormatClass(NullOutputFormat.class); job.setNumReduceTasks(0); job.getConfiguration().set("mapreduce.map.speculative", "false"); job.getConfiguration().set("mapreduce.reduce.speculative", "false"); job.getConfiguration().set("mapreduce.client.submit.file.replication", "3"); job.getConfiguration().set("mapreduce.task.classpath.user.precedence", "true"); job.getConfiguration().set("mapreduce.job.user.classpath.first", "true"); job.getConfiguration().set("mapreduce.map.memory.mb", MR_MAP_MEMORY_MB); job.getConfiguration().set("mapreduce.map.java.opts", MR_MAP_JAVA_OPTS); job.getConfiguration().set("mapred.job.queue.name", MR_QUEUE_NAME); if (targetTable == null || mrUser == null) { LOG.error("Sync m/r not properly configured (occ table or mapreduce user not set) - aborting"); } else { // NOTE: addDependencyJars must be false or you'll see it trying to load hdfs://c1n1/home/user/app/lib/occurrence-cli.jar TableMapReduceUtil.initTableMapperJob(targetTable, scan, OccurrenceScanMapper.class, ImmutableBytesWritable.class, NullWritable.class, job, false); job.waitForCompletion(true); } } catch (Exception e) { LOG.error("Could not start m/r job, aborting", e); } LOG.info("Finished running m/r sync for dataset [{}]", datasetKey); } private void visitOwnedDatasets(UUID orgKey, DatasetVisitor visitor) { int datasetCount = 0; boolean endOfRecords = false; int offset = 0; do { Pageable page = new PagingRequest(offset, PAGING_LIMIT); PagingResponse<Dataset> datasets = orgService.publishedDatasets(orgKey, page); for (Dataset dataset : datasets.getResults()) { visitor.visit(dataset); } datasetCount += datasets.getResults().size(); offset += PAGING_LIMIT; if (datasets.isEndOfRecords()) { endOfRecords = datasets.isEndOfRecords(); } } while (!endOfRecords); LOG.info("Visited [{}] datasets owned by org [{}]", datasetCount, orgKey); } private interface DatasetVisitor { void visit(Dataset dataset); } /** * Sends message to pipelines to update the metadata of the dataset. * * @param dataset dataset to update * @param changedMessage message with the change occurred in the registry */ private void sendUpdateMetadataMessageToPipelines(Dataset dataset, String changedMessage) { Optional<Endpoint> endpoint = getEndpoint(dataset); if (!endpoint.isPresent()) { LOG.error( "Could not find a valid endpoint for dataset {}. Message to pipelines to update metadata NOT SENT", dataset.getKey()); return; } LOG.info( "Sending a message to pipelines to update the metadata for dataset [{}], with reason {}", dataset.getKey(), changedMessage); try { PipelinesVerbatimMessage message = new PipelinesVerbatimMessage( dataset.getKey(), null, Collections.singleton("METADATA"), Sets.newHashSet("VERBATIM_TO_INTERPRETED", "INTERPRETED_TO_INDEX"), endpoint.get().getType()); messagePublisher.send( new PipelinesBalancerMessage(message.getClass().getSimpleName(), message.toString())); } catch (IOException e) { LOG.error("Could not send message to pipelines to update metadata for dataset [{}]", dataset.getKey(), e); } } private Optional<Endpoint> getEndpoint(Dataset dataset) { return dataset.getEndpoints() .stream() .filter(e -> EndpointPriorityComparator.PRIORITIES.contains(e.getType())) .min(new EndpointPriorityComparator()); } }
updated message sent to pipelines when the country of an organization changes
occurrence-registry-sync/src/main/java/org/gbif/occurrence/cli/registry/RegistryChangeListener.java
updated message sent to pipelines when the country of an organization changes
<ide><path>ccurrence-registry-sync/src/main/java/org/gbif/occurrence/cli/registry/RegistryChangeListener.java <ide> EndpointType.DWC_ARCHIVE, <ide> EndpointType.EML).build(); <ide> <add> // pipelines <add> private static final String METADATA_INTERPRETATION = "METADATA"; <add> private static final String LOCATION_INTERPRETATION = "LOCATION"; <add> <ide> /* <ide> When an IPT publishes a new dataset we will get multiple messages from the registry informing us of the update <ide> (depending on the number of endpoints, contacts etc). We only want to send a single crawl message for one of those <ide> Optional<String> changedMessage = occurrenceMutator.generateUpdateMessage(oldDataset, newDataset); <ide> <ide> // send message to pipelines <del> sendUpdateMetadataMessageToPipelines( <del> newDataset, changedMessage.orElse("Dataset changed in registry")); <add> sendUpdateMessageToPipelines( <add> newDataset, Collections.singleton(METADATA_INTERPRETATION), changedMessage.orElse("Dataset changed in registry")); <ide> <ide> LOG.info("Starting m/r sync for dataset [{}], with reason {}", newDataset.getKey(), changedMessage); <ide> try { <ide> newOrg.getCountry()); <ide> DatasetVisitor visitor = <ide> dataset -> { <del> sendUpdateMetadataMessageToPipelines( <add> sendUpdateMessageToPipelines( <ide> dataset, <add> Sets.newHashSet(METADATA_INTERPRETATION, LOCATION_INTERPRETATION), <ide> occurrenceMutator <ide> .generateUpdateMessage(oldOrg, newOrg) <ide> .orElse("Organization change in registry")); <ide> * Sends message to pipelines to update the metadata of the dataset. <ide> * <ide> * @param dataset dataset to update <add> * @param interpretations interpretations that should be run <ide> * @param changedMessage message with the change occurred in the registry <ide> */ <del> private void sendUpdateMetadataMessageToPipelines(Dataset dataset, String changedMessage) { <add> private void sendUpdateMessageToPipelines(Dataset dataset, Set<String> interpretations, String changedMessage) { <ide> Optional<Endpoint> endpoint = getEndpoint(dataset); <ide> if (!endpoint.isPresent()) { <ide> LOG.error( <ide> new PipelinesVerbatimMessage( <ide> dataset.getKey(), <ide> null, <del> Collections.singleton("METADATA"), <add> interpretations, <ide> Sets.newHashSet("VERBATIM_TO_INTERPRETED", "INTERPRETED_TO_INDEX"), <ide> endpoint.get().getType()); <ide>
Java
apache-2.0
cbe0cd88d3bbb20573df7d38e3e63513c4b23353
0
aztg/cms
public class aga { public aga() { } public void setValue(String x) { System.out.println("aaablablab=" + x); } private String getValue() { return "xy"; } private void finsih() { } }
src/Main.java
public class aga { public aga() { } public setValue(String x) { System.out.println("blablab=" + x); } private String getValue() { return "xy"; } private void finsih() { } }
abababa
src/Main.java
abababa
<ide><path>rc/Main.java <ide> <ide> } <ide> <del> public setValue(String x) { <del> System.out.println("blablab=" + x); <add> public void setValue(String x) { <add> System.out.println("aaablablab=" + x); <ide> <ide> } <ide>
Java
apache-2.0
26c9839c664a55fe691a4aac09164783859e6a05
0
Reposoft/restclient
/** * Copyright (C) 2004-2012 Repos Mjukvara AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.repos.restclient.javase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.repos.restclient.HttpStatusError; import se.repos.restclient.ResponseHeaders; import se.repos.restclient.RestAuthentication; import se.repos.restclient.RestResponse; import se.repos.restclient.RestResponseAccept; import se.repos.restclient.base.Codecs; import se.repos.restclient.base.RestClientUrlBase; /** * REST client using java.net.URLConnection. * Has severe limitations: * <ul> * <li>Repeated HEAD requests make the client hang</li> * <li>HTTP authentication BASIC supported, not Digest</li> * </ul> * * Might be possible to work around these limitations in a future * version, but for now consider using repos-restclient-hc. * <p> * This implementation was previously called {@link HttpGetClientJavaNet}. */ public class RestClientJavaNet extends RestClientUrlBase { private static final Logger logger = LoggerFactory.getLogger(RestClientJavaNet.class); public static final String ACCEPT_HEADER_NAME = "Accept"; public static final String AUTH_HEADER_NAME = "Authorization"; public static final String AUTH_HEADER_PREFIX = "Basic "; /** * Timeout in milliseconds. * Default: {@value #DEFAULT_CONNECT_TIMEOUT}. */ public static final int DEFAULT_CONNECT_TIMEOUT = 5000; private int timeout = DEFAULT_CONNECT_TIMEOUT; private RestAuthentication auth; private boolean authenticationForced = false; private boolean keepalive = false; @Inject public RestClientJavaNet( @Named("config:se.repos.restclient.serverRootUrl") String serverRootUrl, RestAuthentication auth) { super(serverRootUrl); this.auth = auth; } @Override public void get(URL url, RestResponse response) throws IOException, HttpStatusError { Map<String,String> requestHeaders = new HashMap<String, String>(2); if (response instanceof RestResponseAccept) { requestHeaders.put(ACCEPT_HEADER_NAME, ((RestResponseAccept) response).getAccept()); } try { // There are 2 approaches to making BASIC Auth efficient: // - Remembering that Auth was needed after the first request. Per path? Per user? // - Indicating to the implementation to always send auth. Inherently per host unless multiple Restclient instances are created. if (authenticationForced && isAuthBasic()) { String username = auth.getUsername(null, null, null); logger.debug("Authenticating user {}, forced", username); setAuthHeaderBasic(requestHeaders, username, auth.getPassword(null, null, null, username)); } get(url, response, requestHeaders); } catch (HttpStatusError e) { // Retry if prompted for BAIDC authentication, support per-request users unlike java.net.Authenticate if (isAuthBasic() && e.getHttpStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { // TODO verify BASIC auth scheme List<String> challenge = e.getHeaders().get("WWW-Authenticate"); if (challenge.size() == 0) { logger.warn("Got 401 status without WWW-Authenticate header"); throw e; } // TODO verify realm String username = auth.getUsername(null, null, null); logger.debug("Authenticating user {} as retry for {}", username, challenge.get(0)); setAuthHeaderBasic(requestHeaders, username, auth.getPassword(null, null, null, username)); get(url, response, requestHeaders); } else { // Not authentication, throw the error throw e; } } } /** * * @param url * @param response Will only be written to after status 200 is received, * see {@link HttpStatusError#getResponse()} for error body. * @param requestHeaders Can be used for authentication, as the default Authenticator behavior is static * @throws IOException * @throws HttpStatusError */ public void get(URL url, RestResponse response, Map<String,String> requestHeaders) throws IOException, HttpStatusError { HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(); } catch (ClassCastException e) { throw new RuntimeException("Non-HTTP protocols not supported. Got URL: " + url); } catch (IOException e) { throw check(e); } // authentication and some settings is static for URLConnection, preserver current setting conn.setInstanceFollowRedirects(true); configure(conn); for (String h : requestHeaders.keySet()) { conn.setRequestProperty(h, requestHeaders.get(h)); } logger.info("GET connection to {}", url); try { conn.connect(); } catch (IOException e) { throw check(e); } // response should be ok regardless of status, get content ResponseHeaders headers = new URLConnectionResponseHeaders(conn); int responseCode = conn.getResponseCode(); // check status code before trying to get response body // to avoid the unclassified IOException // Currently getting body only for 200 OK. // There might be more 2xx responses with a valuable body. if (responseCode == HttpURLConnection.HTTP_OK) { OutputStream receiver = response.getResponseStream(headers); boolean disconnect = true; try { InputStream body = conn.getInputStream(); pipe(body, receiver); body.close(); // Should NOT close the receiver, must be handled by calling class. // See HttpClient BasicHttpEntity.writeTo(..) for consistency btw http clients. //receiver.close(); disconnect = false; } catch (IOException e) { throw check(e); } finally { disconnect(conn, disconnect); // potential keepalive if body processing went well. } } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { // redirect within the same protocol will be handled transparently, typically ending up here when redirected btw http/https logger.info("Server responded with redirect ({}): {}", responseCode, headers.get("Location")); ByteArrayOutputStream b = new ByteArrayOutputStream(); try { InputStream body = conn.getInputStream(); if (body == null) { logger.warn("Redirect did not contain a body."); } pipe(body, b); body.close(); } catch (IOException e) { throw check(e); } finally { disconnect(conn, true); // forcing disconnect, will likely retry on HTTPS instead } throw new HttpStatusError(url.toString(), headers, b.toString()); } else if (responseCode < 400) { // Other non-error responses. // Do we need to consume a stream if the server sends one? Important when using keep-alive? // Might need to handle a category of responses where we attempt to get the Body but allow failure. disconnect(conn, true); // forcing disconnect, need better management of body. logger.warn("Unsupported HTTP response code: {}", responseCode); //throw new RuntimeException("Unsupported HTTP response code: " + responseCode); } else { // Error stream expected for 4xx and 5xx. ByteArrayOutputStream b = new ByteArrayOutputStream(); try { InputStream body = conn.getErrorStream(); if (body == null) { throw new RuntimeException("Response error could not be read for status " + conn.getResponseCode()); } pipe(body, b); body.close(); } catch (IOException e) { throw check(e); } finally { disconnect(conn, true); // forcing disconnect at this time, consider enabling keepalive in the future } throw new HttpStatusError(url.toString(), headers, b.toString()); } } private static void setAuthHeaderBasic(Map<String, String> requestHeaders, String username, String password) { requestHeaders.put(AUTH_HEADER_NAME, AUTH_HEADER_PREFIX + Codecs.base64encode( username + ":" + password)); } public boolean isAuthenticationForced() { return authenticationForced; } /** * Makes the http client send authentication in the initial request without first getting a 401. * TODO: Consider making this an inject settor. * @param authenticationForced */ public void setAuthenticationForced(boolean authenticationForced) { if (authenticationForced && auth == null) { throw new IllegalArgumentException("Authentication forced assumes an authentication instance is provided."); } this.authenticationForced = authenticationForced; } /** * Makes the http client allow keepalive between requests. * @param keepalive */ public void setKeepalive(boolean keepalive) { this.keepalive = keepalive; } /** * Shared configuration for all request methods. * @param conn opened but not connected */ protected void configure(HttpURLConnection conn) { conn.setConnectTimeout(timeout); if (conn instanceof HttpsURLConnection) { configureSSL((HttpsURLConnection) conn); } } protected void configureSSL(HttpsURLConnection conn) { if (auth == null) { return; } URL url = conn.getURL(); String root = url.getProtocol() + "://" + url.getHost() + (url.getPort() > 0 ? ":" + url.getPort() : ""); SSLContext ctx = auth.getSSLContext(root); if (ctx == null) { return; } SSLSocketFactory ssl = ctx.getSocketFactory(); conn.setSSLSocketFactory(ssl); } /** * Makes post-processing possible. */ protected IOException check(IOException e) { return e; } private void pipe(InputStream source, OutputStream destination) throws IOException { // don't know if this is a good buffering strategy byte[] buffer = new byte[1024]; int len = source.read(buffer); while (len != -1) { destination.write(buffer, 0, len); len = source.read(buffer); } } private void disconnect(HttpURLConnection conn, boolean force) { // Can perform close or disconnect based on configuration. if (force || (!this.keepalive)) { conn.disconnect(); } } /** * TODO head should authenticate of auth returns credentials, getUsername should provide method name */ @Override public ResponseHeaders head(URL url) throws IOException { HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); } catch (ClassCastException e) { throw new RuntimeException("Non-HTTP protocols not supported. Got URL: " + url); } catch (IOException e) { throw check(e); } con.setRequestMethod("HEAD"); con.setInstanceFollowRedirects(false); configure(con); ResponseHeaders head = null; try { logger.warn("attempting HEAD request with java.net client to {}", url); // still not sure if java.net client behaves well for HEAD requests con.connect(); logger.trace("HEAD {} connected", url); // gets rid of the EOF issue in Jetty test: InputStream b; if (con.getResponseCode() == 200) { b = con.getInputStream(); logger.trace("HEAD {} output requested", url); while (b.read() != -1) {} logger.trace("HEAD {} output read", url); b.close(); } logger.trace("HEAD {} output closed", url); head = new URLConnectionResponseHeaders(con); logger.trace("HEAD {} headers read", url); } catch (IOException e) { throw check(e); } finally { con.disconnect(); } return head; } private boolean isAuthBasic() { if (auth != null && auth.getUsername(null, null, null) != null) { return true; } return false; } }
src/main/java/se/repos/restclient/javase/RestClientJavaNet.java
/** * Copyright (C) 2004-2012 Repos Mjukvara AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.repos.restclient.javase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.repos.restclient.HttpStatusError; import se.repos.restclient.ResponseHeaders; import se.repos.restclient.RestAuthentication; import se.repos.restclient.RestResponse; import se.repos.restclient.RestResponseAccept; import se.repos.restclient.base.Codecs; import se.repos.restclient.base.RestClientUrlBase; /** * REST client using java.net.URLConnection. * Has severe limitations: * <ul> * <li>Repeated HEAD requests make the client hang</li> * <li>HTTP authentication BASIC supported, not Digest</li> * </ul> * * Might be possible to work around these limitations in a future * version, but for now consider using repos-restclient-hc. * <p> * This implementation was previously called {@link HttpGetClientJavaNet}. */ public class RestClientJavaNet extends RestClientUrlBase { private static final Logger logger = LoggerFactory.getLogger(RestClientJavaNet.class); public static final String ACCEPT_HEADER_NAME = "Accept"; public static final String AUTH_HEADER_NAME = "Authorization"; public static final String AUTH_HEADER_PREFIX = "Basic "; /** * Timeout in milliseconds. * Default: {@value #DEFAULT_CONNECT_TIMEOUT}. */ public static final int DEFAULT_CONNECT_TIMEOUT = 5000; private int timeout = DEFAULT_CONNECT_TIMEOUT; private RestAuthentication auth; private boolean authenticationForced = false; private boolean keepalive = false; @Inject public RestClientJavaNet( @Named("config:se.repos.restclient.serverRootUrl") String serverRootUrl, RestAuthentication auth) { super(serverRootUrl); this.auth = auth; } @Override public void get(URL url, RestResponse response) throws IOException, HttpStatusError { Map<String,String> requestHeaders = new HashMap<String, String>(2); if (response instanceof RestResponseAccept) { requestHeaders.put(ACCEPT_HEADER_NAME, ((RestResponseAccept) response).getAccept()); } try { // There are 2 approaches to making BASIC Auth efficient: // - Remembering that Auth was needed after the first request. Per path? Per user? // - Indicating to the implementation to always send auth. Inherently per host unless multiple Restclient instances are created. if (authenticationForced && isAuthBasic()) { String username = auth.getUsername(null, null, null); logger.debug("Authenticating user {}, forced", username); setAuthHeaderBasic(requestHeaders, username, auth.getPassword(null, null, null, username)); } get(url, response, requestHeaders); } catch (HttpStatusError e) { // Retry if prompted for BAIDC authentication, support per-request users unlike java.net.Authenticate if (isAuthBasic() && e.getHttpStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { // TODO verify BASIC auth scheme List<String> challenge = e.getHeaders().get("WWW-Authenticate"); if (challenge.size() == 0) { logger.warn("Got 401 status without WWW-Authenticate header"); throw e; } // TODO verify realm String username = auth.getUsername(null, null, null); logger.debug("Authenticating user {} as retry for {}", username, challenge.get(0)); setAuthHeaderBasic(requestHeaders, username, auth.getPassword(null, null, null, username)); get(url, response, requestHeaders); } else { // Not authentication, throw the error throw e; } } } /** * * @param url * @param response Will only be written to after status 200 is received, * see {@link HttpStatusError#getResponse()} for error body. * @param requestHeaders Can be used for authentication, as the default Authenticator behavior is static * @throws IOException * @throws HttpStatusError */ public void get(URL url, RestResponse response, Map<String,String> requestHeaders) throws IOException, HttpStatusError { HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(); } catch (ClassCastException e) { throw new RuntimeException("Non-HTTP protocols not supported. Got URL: " + url); } catch (IOException e) { throw check(e); } // authentication and some settings is static for URLConnection, preserver current setting conn.setInstanceFollowRedirects(true); configure(conn); for (String h : requestHeaders.keySet()) { conn.setRequestProperty(h, requestHeaders.get(h)); } logger.info("GET connection to {}", url); try { conn.connect(); } catch (IOException e) { throw check(e); } // response should be ok regardless of status, get content ResponseHeaders headers = new URLConnectionResponseHeaders(conn); int responseCode = conn.getResponseCode(); // check status code before trying to get response body // to avoid the unclassified IOException // Currently getting body only for 200 OK. // There might be more 2xx responses with a valuable body. if (responseCode == HttpURLConnection.HTTP_OK) { OutputStream receiver = response.getResponseStream(headers); boolean disconnect = true; try { InputStream body = conn.getInputStream(); pipe(body, receiver); body.close(); receiver.close(); disconnect = false; } catch (IOException e) { throw check(e); } finally { disconnect(conn, disconnect); // potential keepalive if body processing went well. } } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { // redirect within the same protocol will be handled transparently, typically ending up here when redirected btw http/https logger.info("Server responded with redirect ({}): {}", responseCode, headers.get("Location")); ByteArrayOutputStream b = new ByteArrayOutputStream(); try { InputStream body = conn.getInputStream(); if (body == null) { logger.warn("Redirect did not contain a body."); } pipe(body, b); body.close(); } catch (IOException e) { throw check(e); } finally { disconnect(conn, true); // forcing disconnect, will likely retry on HTTPS instead } throw new HttpStatusError(url.toString(), headers, b.toString()); } else if (responseCode < 400) { // Other non-error responses. // Do we need to consume a stream if the server sends one? Important when using keep-alive? // Might need to handle a category of responses where we attempt to get the Body but allow failure. disconnect(conn, true); // forcing disconnect, need better management of body. logger.warn("Unsupported HTTP response code: {}", responseCode); //throw new RuntimeException("Unsupported HTTP response code: " + responseCode); } else { // Error stream expected for 4xx and 5xx. ByteArrayOutputStream b = new ByteArrayOutputStream(); try { InputStream body = conn.getErrorStream(); if (body == null) { throw new RuntimeException("Response error could not be read for status " + conn.getResponseCode()); } pipe(body, b); body.close(); } catch (IOException e) { throw check(e); } finally { disconnect(conn, true); // forcing disconnect at this time, consider enabling keepalive in the future } throw new HttpStatusError(url.toString(), headers, b.toString()); } } private static void setAuthHeaderBasic(Map<String, String> requestHeaders, String username, String password) { requestHeaders.put(AUTH_HEADER_NAME, AUTH_HEADER_PREFIX + Codecs.base64encode( username + ":" + password)); } public boolean isAuthenticationForced() { return authenticationForced; } /** * Makes the http client send authentication in the initial request without first getting a 401. * TODO: Consider making this an inject settor. * @param authenticationForced */ public void setAuthenticationForced(boolean authenticationForced) { if (authenticationForced && auth == null) { throw new IllegalArgumentException("Authentication forced assumes an authentication instance is provided."); } this.authenticationForced = authenticationForced; } /** * Makes the http client allow keepalive between requests. * @param keepalive */ public void setKeepalive(boolean keepalive) { this.keepalive = keepalive; } /** * Shared configuration for all request methods. * @param conn opened but not connected */ protected void configure(HttpURLConnection conn) { conn.setConnectTimeout(timeout); if (conn instanceof HttpsURLConnection) { configureSSL((HttpsURLConnection) conn); } } protected void configureSSL(HttpsURLConnection conn) { if (auth == null) { return; } URL url = conn.getURL(); String root = url.getProtocol() + "://" + url.getHost() + (url.getPort() > 0 ? ":" + url.getPort() : ""); SSLContext ctx = auth.getSSLContext(root); if (ctx == null) { return; } SSLSocketFactory ssl = ctx.getSocketFactory(); conn.setSSLSocketFactory(ssl); } /** * Makes post-processing possible. */ protected IOException check(IOException e) { return e; } private void pipe(InputStream source, OutputStream destination) throws IOException { // don't know if this is a good buffering strategy byte[] buffer = new byte[1024]; int len = source.read(buffer); while (len != -1) { destination.write(buffer, 0, len); len = source.read(buffer); } } private void disconnect(HttpURLConnection conn, boolean force) { // Can perform close or disconnect based on configuration. if (force || (!this.keepalive)) { conn.disconnect(); } } /** * TODO head should authenticate of auth returns credentials, getUsername should provide method name */ @Override public ResponseHeaders head(URL url) throws IOException { HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); } catch (ClassCastException e) { throw new RuntimeException("Non-HTTP protocols not supported. Got URL: " + url); } catch (IOException e) { throw check(e); } con.setRequestMethod("HEAD"); con.setInstanceFollowRedirects(false); configure(con); ResponseHeaders head = null; try { logger.warn("attempting HEAD request with java.net client to {}", url); // still not sure if java.net client behaves well for HEAD requests con.connect(); logger.trace("HEAD {} connected", url); // gets rid of the EOF issue in Jetty test: InputStream b; if (con.getResponseCode() == 200) { b = con.getInputStream(); logger.trace("HEAD {} output requested", url); while (b.read() != -1) {} logger.trace("HEAD {} output read", url); b.close(); } logger.trace("HEAD {} output closed", url); head = new URLConnectionResponseHeaders(con); logger.trace("HEAD {} headers read", url); } catch (IOException e) { throw check(e); } finally { con.disconnect(); } return head; } private boolean isAuthBasic() { if (auth != null && auth.getUsername(null, null, null) != null) { return true; } return false; } }
Revert: Attempt to fix issue with non-closed response receiver. Closing the stream must be done by caller.
src/main/java/se/repos/restclient/javase/RestClientJavaNet.java
Revert: Attempt to fix issue with non-closed response receiver. Closing the stream must be done by caller.
<ide><path>rc/main/java/se/repos/restclient/javase/RestClientJavaNet.java <ide> InputStream body = conn.getInputStream(); <ide> pipe(body, receiver); <ide> body.close(); <del> receiver.close(); <add> // Should NOT close the receiver, must be handled by calling class. <add> // See HttpClient BasicHttpEntity.writeTo(..) for consistency btw http clients. <add> //receiver.close(); <ide> disconnect = false; <ide> } catch (IOException e) { <ide> throw check(e);
JavaScript
agpl-3.0
be48583aa29473d150ee20a62bce7e84c9d33c82
0
nditech/fixmystreet,nditech/fixmystreet,alearce88/fixmystreet,mhalden/fixmystreet,nditech/fixmystreet,altinukshini/lokalizo,opencorato/barriosenaccion,altinukshini/lokalizo,dracos/fixmystreet,appstud/fixmystreet,dracos/fixmystreet,nditech/fixmystreet,alearce88/fixmystreet,alearce88/fixmystreet,otmezger/fixmystreet,eBay-Opportunity-Hack-Chennai-2014/Chennai_Street_Fix,altinukshini/lokalizo,mhalden/fixmystreet,appstud/fixmystreet,eBay-Opportunity-Hack-Chennai-2014/Chennai_Street_Fix,alearce88/fixmystreet,eBay-Opportunity-Hack-Chennai-2014/Chennai_Street_Fix,ciudadanointeligente/barriosenaccion,ciudadanointeligente/barriosenaccion,datauy/fixmystreet,alearce88/fixmystreet,otmezger/fixmystreet,opencorato/barriosenaccion,nditech/fixmystreet,datauy/fixmystreet,rbgdigital/fixmystreet,appstud/fixmystreet,nditech/fixmystreet,datauy/fixmystreet,opencorato/barriosenaccion,ciudadanointeligente/barriosenaccion,otmezger/fixmystreet,dracos/fixmystreet,otmezger/fixmystreet,antoinepemeja/fixmystreet,altinukshini/lokalizo,otmezger/fixmystreet,mhalden/fixmystreet,datauy/fixmystreet,opencorato/barriosenaccion,appstud/fixmystreet,altinukshini/lokalizo,mhalden/fixmystreet,mhalden/fixmystreet,alearce88/fixmystreet,antoinepemeja/fixmystreet,dracos/fixmystreet,ciudadanointeligente/barriosenaccion,rbgdigital/fixmystreet,ciudadanointeligente/barriosenaccion,rbgdigital/fixmystreet,alearce88/fixmystreet,antoinepemeja/fixmystreet,opencorato/barriosenaccion,dracos/fixmystreet,eBay-Opportunity-Hack-Chennai-2014/Chennai_Street_Fix,rbgdigital/fixmystreet,antoinepemeja/fixmystreet,ciudadanointeligente/barriosenaccion,dracos/fixmystreet,antoinepemeja/fixmystreet,rbgdigital/fixmystreet,appstud/fixmystreet,nditech/fixmystreet,ciudadanointeligente/barriosenaccion,otmezger/fixmystreet,appstud/fixmystreet,rbgdigital/fixmystreet,datauy/fixmystreet,mhalden/fixmystreet,antoinepemeja/fixmystreet,antoinepemeja/fixmystreet,datauy/fixmystreet,datauy/fixmystreet,alearce88/fixmystreet,opencorato/barriosenaccion,appstud/fixmystreet,otmezger/fixmystreet,eBay-Opportunity-Hack-Chennai-2014/Chennai_Street_Fix,opencorato/barriosenaccion,altinukshini/lokalizo
/* XXX Lots overlap with map-OpenLayers.js - refactor! XXX Things still need to be changed for mobile use, probably won't work there. TODO Pin size on report page */ function PaddingControl(div) { div.style.padding = '40px'; } function fixmystreet_update_pin(lonlat) { document.getElementById('fixmystreet.latitude').value = lonlat.lat(); document.getElementById('fixmystreet.longitude').value = lonlat.lng(); $.getJSON('/report/new/ajax', { latitude: $('#fixmystreet\\.latitude').val(), longitude: $('#fixmystreet\\.longitude').val() }, function(data) { if (data.error) { if (!$('#side-form-error').length) { $('<div id="side-form-error"/>').insertAfter($('#side-form')); } $('#side-form-error').html('<h1>' + translation_strings.reporting_a_problem + '</h1><p>' + data.error + '</p>').show(); $('#side-form').hide(); return; } $('#side-form, #site-logo').show(); $('#councils_text').html(data.councils_text); $('#form_category_row').html(data.category); if ( data.extra_name_info && !$('#form_fms_extra_title').length ) { // there might be a first name field on some cobrands var lb = $('#form_first_name').prev(); if ( lb.length === 0 ) { lb = $('#form_name').prev(); } lb.before(data.extra_name_info); } }); if (!$('#side-form-error').is(':visible')) { $('#side-form, #site-logo').show(); } } var infowindow = new google.maps.InfoWindow(); function make_infowindow(marker) { return function() { infowindow.setContent(marker.title + "<br><a href=/report/" + marker.id + ">" + translation_strings.more_details + "</a>"); infowindow.open(fixmystreet.map, marker); }; } function fms_markers_list(pins, transform) { var markers = []; if (fixmystreet.markers) { for (var m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(null); } } for (var i=0; i<pins.length; i++) { var pin = pins[i]; var pin_args = { position: new google.maps.LatLng( pin[0], pin[1] ), //size: pin[5] || 'normal', id: pin[3], title: pin[4] || '', map: fixmystreet.map }; if (pin[2] == 'green') { pin_args.icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|87dd00"; } if (pin[2] == 'yellow') { pin_args.icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ffd600"; } var marker = new google.maps.Marker(pin_args); if (fixmystreet.page == 'around' || fixmystreet.page == 'reports' || fixmystreet.page == 'my') { var l = new google.maps.event.addListener(marker, 'click', make_infowindow(marker)); } markers.push( marker ); } return markers; } function fms_map_clicked(e) { var lonlat = e.latLng; if (fixmystreet.page == 'new') { /* Already have a pin */ fixmystreet.report_marker.setPosition(lonlat); } else { var marker = new google.maps.Marker({ position: lonlat, draggable: true, animation: google.maps.Animation.DROP, map: fixmystreet.map }); var l = google.maps.event.addListener(marker, 'dragend', function(){ fixmystreet_update_pin( marker.getPosition() ); }); fixmystreet.report_marker = marker; google.maps.event.removeListener(fixmystreet.event_update_map); for (m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(null); } } // check to see if markers are visible. We click the // link so that it updates the text in case they go // back if ( ! 1 ) { // XXX fixmystreet.markers.getVisibility() ) fixmystreet.state_pins_were_hidden = true; $('#hide_pins_link').click(); } // Store pin location in form fields, and check coverage of point fixmystreet_update_pin(lonlat); // Already did this first time map was clicked, so no need to do it again. if (fixmystreet.page == 'new') { return; } $('#side').hide(); if (typeof heightFix !== 'undefined') { heightFix('#report-a-problem-sidebar', '.content', 26); } // If we clicked the map somewhere inconvenient // TODO $('#sub_map_links').hide(); fixmystreet.page = 'new'; location.hash = 'report'; } /* Pan data handler */ function fms_read_pin_json(obj) { var current, current_near; if (typeof(obj.current) != 'undefined' && (current = document.getElementById('current'))) { current.innerHTML = obj.current; } if (typeof(obj.current_near) != 'undefined' && (current_near = document.getElementById('current_near'))) { current_near.innerHTML = obj.current_near; } fixmystreet.markers = fms_markers_list( obj.pins, false ); } function fms_update_pins() { var b = fixmystreet.map.getBounds(), b_sw = b.getSouthWest(), b_ne = b.getNorthEast(), bbox = b_sw.lng() + ',' + b_sw.lat() + ',' + b_ne.lng() + ',' + b_ne.lat(), params = { bbox: bbox }; if (fixmystreet.all_pins) { params.all_pins = 1; } $.getJSON('/ajax', params, fms_read_pin_json); } function fms_map_initialize() { var centre = new google.maps.LatLng( fixmystreet.latitude, fixmystreet.longitude ); var map_args = { mapTypeId: google.maps.MapTypeId.ROADMAP, center: centre, zoom: 13 + fixmystreet.zoom, disableDefaultUI: true, panControl: true, panControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, zoomControl: true, zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, mapTypeControl: true, mapTypeControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU } }; if (!fixmystreet.zoomToBounds) { map_args.minZoom = 13; map_args.maxZoom = 18; } fixmystreet.map = new google.maps.Map(document.getElementById("map"), map_args); /* Space above the top right controls */ var paddingDiv = document.createElement('div'); var paddingControl = new PaddingControl(paddingDiv); paddingDiv.index = 0; fixmystreet.map.controls[google.maps.ControlPosition.RIGHT_TOP].push(paddingDiv); if (fixmystreet.state_map && fixmystreet.state_map == 'full') { // TODO Work better with window resizing, this is pretty 'set up' only at present var $content = $('.content'), mb = $('#map_box'), q = ( $content.offset().left - mb.offset().left + $content.width() ) / 2; if (q < 0) { q = 0; } // Need to try and fake the 'centre' being 75% from the left fixmystreet.map.panBy(-q, -25); } if (document.getElementById('mapForm')) { var l = google.maps.event.addListener(fixmystreet.map, 'click', fms_map_clicked); } $(window).hashchange(function(){ if (location.hash == '#report' && $('.rap-notes').is(':visible')) { $('.rap-notes-close').click(); return; } if (location.hash && location.hash != '#') { return; } // Okay, back to around view. fixmystreet.report_marker.setMap(null); fixmystreet.event_update_map = google.maps.event.addListener(fixmystreet.map, 'idle', fms_update_pins); google.maps.event.trigger(fixmystreet.map, 'idle'); if ( fixmystreet.state_pins_were_hidden ) { // If we had pins hidden when we clicked map (which had to show the pin layer as I'm doing it in one layer), hide them again. $('#hide_pins_link').click(); } $('#side-form').hide(); $('#side').show(); $('#sub_map_links').show(); //only on mobile $('#mob_sub_map_links').remove(); $('.mobile-map-banner').html('<a href="/">' + translation_strings.home + '</a> ' + translation_strings.place_pin_on_map); fixmystreet.page = 'around'; }); if ( fixmystreet.area.length ) { for (var i=0; i<fixmystreet.area.length; i++) { var args = { url: "http://mapit.mysociety.org/area/" + fixmystreet.area[i] + ".kml?simplify_tolerance=0.0001", clickable: false, preserveViewport: true, map: fixmystreet.map }; if ( fixmystreet.area.length == 1 ) { args.preserveViewport = false; } var a = new google.maps.KmlLayer(args); a.setMap(fixmystreet.map); } } if (fixmystreet.page == 'around') { fixmystreet.event_update_map = google.maps.event.addListener(fixmystreet.map, 'idle', fms_update_pins); } fixmystreet.markers = fms_markers_list( fixmystreet.pins, true ); /* if ( fixmystreet.zoomToBounds ) { var bounds = fixmystreet.markers.getDataExtent(); if (bounds) { var center = bounds.getCenterLonLat(); var z = fixmystreet.map.getZoomForExtent(bounds); if ( z < 13 && $('html').hasClass('mobile') ) { z = 13; } fixmystreet.map.setCenter(center, z); } } */ $('#hide_pins_link').click(function(e) { var i, m; e.preventDefault(); var showhide = [ 'Show pins', 'Hide pins', 'Dangos pinnau', 'Cuddio pinnau', "Vis nåler", "Gjem nåler", "Zeige Stecknadeln", "Stecknadeln ausblenden" ]; for (i=0; i<showhide.length; i+=2) { if (this.innerHTML == showhide[i]) { for (m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(fixmystreet.map); } this.innerHTML = showhide[i+1]; } else if (this.innerHTML == showhide[i+1]) { for (m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(null); } this.innerHTML = showhide[i]; } } }); $('#all_pins_link').click(function(e) { var i; e.preventDefault(); for (i=0; i<fixmystreet.markers.length; i++) { fixmystreet.markers[i].setMap(fixmystreet.map); } var texts = [ 'en', 'Show old', 'Hide old', 'nb', 'Inkluder utdaterte problemer', 'Skjul utdaterte rapporter', 'cy', 'Cynnwys hen adroddiadau', 'Cuddio hen adroddiadau' ]; for (i=0; i<texts.length; i+=3) { if (this.innerHTML == texts[i+1]) { this.innerHTML = texts[i+2]; fixmystreet.markers.protocol.options.params = { all_pins: 1 }; fixmystreet.markers.refresh( { force: true } ); lang = texts[i]; } else if (this.innerHTML == texts[i+2]) { this.innerHTML = texts[i+1]; fixmystreet.markers.protocol.options.params = { }; fixmystreet.markers.refresh( { force: true } ); lang = texts[i]; } } if (lang == 'cy') { document.getElementById('hide_pins_link').innerHTML = 'Cuddio pinnau'; } else if (lang == 'nb') { document.getElementById('hide_pins_link').innerHTML = 'Gjem nåler'; } else { document.getElementById('hide_pins_link').innerHTML = 'Hide pins'; } }); } google.maps.visualRefresh = true; google.maps.event.addDomListener(window, 'load', fms_map_initialize);
web/js/map-google.js
/* XXX Lots overlap with map-OpenLayers.js - refactor! XXX Things still need to be changed for mobile use, probably won't work there. TODO Pin size on report page */ function PaddingControl(div) { div.style.padding = '40px'; } function fixmystreet_update_pin(lonlat) { document.getElementById('fixmystreet.latitude').value = lonlat.lat(); document.getElementById('fixmystreet.longitude').value = lonlat.lng(); $.getJSON('/report/new/ajax', { latitude: $('#fixmystreet\\.latitude').val(), longitude: $('#fixmystreet\\.longitude').val() }, function(data) { if (data.error) { if (!$('#side-form-error').length) { $('<div id="side-form-error"/>').insertAfter($('#side-form')); } $('#side-form-error').html('<h1>' + translation_strings.reporting_a_problem + '</h1><p>' + data.error + '</p>').show(); $('#side-form').hide(); return; } $('#side-form, #site-logo').show(); $('#councils_text').html(data.councils_text); $('#form_category_row').html(data.category); if ( data.extra_name_info && !$('#form_fms_extra_title').length ) { // there might be a first name field on some cobrands var lb = $('#form_first_name').prev(); if ( lb.length === 0 ) { lb = $('#form_name').prev(); } lb.before(data.extra_name_info); } }); if (!$('#side-form-error').is(':visible')) { $('#side-form, #site-logo').show(); } } var infowindow = new google.maps.InfoWindow(); function make_infowindow(marker) { return function() { infowindow.setContent(marker.title + "<br><a href=/report/" + marker.id + ">" + translation_strings.more_details + "</a>"); infowindow.open(fixmystreet.map, marker); }; } function fms_markers_list(pins, transform) { var markers = []; if (fixmystreet.markers) { for (var m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(null); } } for (var i=0; i<pins.length; i++) { var pin = pins[i]; var pin_args = { position: new google.maps.LatLng( pin[0], pin[1] ), //size: pin[5] || 'normal', id: pin[3], title: pin[4] || '', map: fixmystreet.map }; if (pin[2] == 'green') { pin_args.icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|87dd00"; } if (pin[2] == 'yellow') { pin_args.icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ffd600"; } var marker = new google.maps.Marker(pin_args); if (fixmystreet.page == 'around' || fixmystreet.page == 'reports' || fixmystreet.page == 'my') { var l = new google.maps.event.addListener(marker, 'click', make_infowindow(marker)); } markers.push( marker ); } return markers; } function fms_map_clicked(e) { var lonlat = e.latLng; if (fixmystreet.page == 'new') { /* Already have a pin */ fixmystreet.report_marker.setPosition(lonlat); } else { var m = new google.maps.Marker({ position: lonlat, draggable: true, animation: google.maps.Animation.DROP, map: fixmystreet.map }); var l = google.maps.event.addListener(m, 'dragend', function(){ fixmystreet_update_pin( m.getPosition() ); }); fixmystreet.report_marker = m; google.maps.event.removeListener(fixmystreet.event_update_map); for (m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(null); } } // check to see if markers are visible. We click the // link so that it updates the text in case they go // back if ( ! 1 ) { // XXX fixmystreet.markers.getVisibility() ) fixmystreet.state_pins_were_hidden = true; $('#hide_pins_link').click(); } // Store pin location in form fields, and check coverage of point fixmystreet_update_pin(lonlat); // Already did this first time map was clicked, so no need to do it again. if (fixmystreet.page == 'new') { return; } $('#side').hide(); if (typeof heightFix !== 'undefined') { heightFix('#report-a-problem-sidebar', '.content', 26); } // If we clicked the map somewhere inconvenient // TODO $('#sub_map_links').hide(); fixmystreet.page = 'new'; location.hash = 'report'; } /* Pan data handler */ function fms_read_pin_json(obj) { var current, current_near; if (typeof(obj.current) != 'undefined' && (current = document.getElementById('current'))) { current.innerHTML = obj.current; } if (typeof(obj.current_near) != 'undefined' && (current_near = document.getElementById('current_near'))) { current_near.innerHTML = obj.current_near; } fixmystreet.markers = fms_markers_list( obj.pins, false ); } function fms_update_pins() { var b = fixmystreet.map.getBounds(), b_sw = b.getSouthWest(), b_ne = b.getNorthEast(), bbox = b_sw.lng() + ',' + b_sw.lat() + ',' + b_ne.lng() + ',' + b_ne.lat(), params = { bbox: bbox }; if (fixmystreet.all_pins) { params.all_pins = 1; } $.getJSON('/ajax', params, fms_read_pin_json); } function fms_map_initialize() { var centre = new google.maps.LatLng( fixmystreet.latitude, fixmystreet.longitude ); var map_args = { mapTypeId: google.maps.MapTypeId.ROADMAP, center: centre, zoom: 13 + fixmystreet.zoom, disableDefaultUI: true, panControl: true, panControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, zoomControl: true, zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, mapTypeControl: true, mapTypeControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU } }; if (!fixmystreet.zoomToBounds) { map_args.minZoom = 13; map_args.maxZoom = 18; } fixmystreet.map = new google.maps.Map(document.getElementById("map"), map_args); /* Space above the top right controls */ var paddingDiv = document.createElement('div'); var paddingControl = new PaddingControl(paddingDiv); paddingDiv.index = 0; fixmystreet.map.controls[google.maps.ControlPosition.RIGHT_TOP].push(paddingDiv); if (fixmystreet.state_map && fixmystreet.state_map == 'full') { // TODO Work better with window resizing, this is pretty 'set up' only at present var $content = $('.content'), mb = $('#map_box'), q = ( $content.offset().left - mb.offset().left + $content.width() ) / 2; if (q < 0) { q = 0; } // Need to try and fake the 'centre' being 75% from the left fixmystreet.map.panBy(-q, -25); } if (document.getElementById('mapForm')) { var l = google.maps.event.addListener(fixmystreet.map, 'click', fms_map_clicked); } $(window).hashchange(function(){ if (location.hash == '#report' && $('.rap-notes').is(':visible')) { $('.rap-notes-close').click(); return; } if (location.hash && location.hash != '#') { return; } // Okay, back to around view. fixmystreet.report_marker.setMap(null); fixmystreet.event_update_map = google.maps.event.addListener(fixmystreet.map, 'idle', fms_update_pins); google.maps.event.trigger(fixmystreet.map, 'idle'); if ( fixmystreet.state_pins_were_hidden ) { // If we had pins hidden when we clicked map (which had to show the pin layer as I'm doing it in one layer), hide them again. $('#hide_pins_link').click(); } $('#side-form').hide(); $('#side').show(); $('#sub_map_links').show(); //only on mobile $('#mob_sub_map_links').remove(); $('.mobile-map-banner').html('<a href="/">' + translation_strings.home + '</a> ' + translation_strings.place_pin_on_map); fixmystreet.page = 'around'; }); if ( fixmystreet.area.length ) { for (var i=0; i<fixmystreet.area.length; i++) { var args = { url: "http://mapit.mysociety.org/area/" + fixmystreet.area[i] + ".kml?simplify_tolerance=0.0001", clickable: false, preserveViewport: true, map: fixmystreet.map }; if ( fixmystreet.area.length == 1 ) { args.preserveViewport = false; } var a = new google.maps.KmlLayer(args); a.setMap(fixmystreet.map); } } if (fixmystreet.page == 'around') { fixmystreet.event_update_map = google.maps.event.addListener(fixmystreet.map, 'idle', fms_update_pins); } fixmystreet.markers = fms_markers_list( fixmystreet.pins, true ); /* if ( fixmystreet.zoomToBounds ) { var bounds = fixmystreet.markers.getDataExtent(); if (bounds) { var center = bounds.getCenterLonLat(); var z = fixmystreet.map.getZoomForExtent(bounds); if ( z < 13 && $('html').hasClass('mobile') ) { z = 13; } fixmystreet.map.setCenter(center, z); } } */ $('#hide_pins_link').click(function(e) { var i, m; e.preventDefault(); var showhide = [ 'Show pins', 'Hide pins', 'Dangos pinnau', 'Cuddio pinnau', "Vis nåler", "Gjem nåler", "Zeige Stecknadeln", "Stecknadeln ausblenden" ]; for (i=0; i<showhide.length; i+=2) { if (this.innerHTML == showhide[i]) { for (m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(fixmystreet.map); } this.innerHTML = showhide[i+1]; } else if (this.innerHTML == showhide[i+1]) { for (m=0; m<fixmystreet.markers.length; m++) { fixmystreet.markers[m].setMap(null); } this.innerHTML = showhide[i]; } } }); $('#all_pins_link').click(function(e) { var i; e.preventDefault(); for (i=0; i<fixmystreet.markers.length; i++) { fixmystreet.markers[i].setMap(fixmystreet.map); } var texts = [ 'en', 'Show old', 'Hide old', 'nb', 'Inkluder utdaterte problemer', 'Skjul utdaterte rapporter', 'cy', 'Cynnwys hen adroddiadau', 'Cuddio hen adroddiadau' ]; for (i=0; i<texts.length; i+=3) { if (this.innerHTML == texts[i+1]) { this.innerHTML = texts[i+2]; fixmystreet.markers.protocol.options.params = { all_pins: 1 }; fixmystreet.markers.refresh( { force: true } ); lang = texts[i]; } else if (this.innerHTML == texts[i+2]) { this.innerHTML = texts[i+1]; fixmystreet.markers.protocol.options.params = { }; fixmystreet.markers.refresh( { force: true } ); lang = texts[i]; } } if (lang == 'cy') { document.getElementById('hide_pins_link').innerHTML = 'Cuddio pinnau'; } else if (lang == 'nb') { document.getElementById('hide_pins_link').innerHTML = 'Gjem nåler'; } else { document.getElementById('hide_pins_link').innerHTML = 'Hide pins'; } }); } google.maps.visualRefresh = true; google.maps.event.addDomListener(window, 'load', fms_map_initialize);
Fixed Google map marker drag issue caused by inproper variable naming.
web/js/map-google.js
Fixed Google map marker drag issue caused by inproper variable naming.
<ide><path>eb/js/map-google.js <ide> /* Already have a pin */ <ide> fixmystreet.report_marker.setPosition(lonlat); <ide> } else { <del> var m = new google.maps.Marker({ <add> var marker = new google.maps.Marker({ <ide> position: lonlat, <ide> draggable: true, <ide> animation: google.maps.Animation.DROP, <ide> map: fixmystreet.map <ide> }); <del> var l = google.maps.event.addListener(m, 'dragend', function(){ <del> fixmystreet_update_pin( m.getPosition() ); <add> var l = google.maps.event.addListener(marker, 'dragend', function(){ <add> fixmystreet_update_pin( marker.getPosition() ); <ide> }); <del> fixmystreet.report_marker = m; <add> fixmystreet.report_marker = marker; <ide> google.maps.event.removeListener(fixmystreet.event_update_map); <ide> for (m=0; m<fixmystreet.markers.length; m++) { <ide> fixmystreet.markers[m].setMap(null);
Java
apache-2.0
52c85e878782aed8e77dde5c27616b25e99f4f73
0
benbek/HereAStory-Android,benbek/HereAStory-Android
package com.hereastory; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.View; import com.androidmapsextensions.ClusterGroup; import com.androidmapsextensions.ClusteringSettings; import com.androidmapsextensions.GoogleMap; import com.androidmapsextensions.GoogleMap.OnCameraChangeListener; import com.androidmapsextensions.GoogleMap.OnInfoWindowClickListener; import com.androidmapsextensions.GoogleMap.OnMarkerClickListener; import com.androidmapsextensions.GoogleMap.OnMyLocationChangeListener; import com.androidmapsextensions.MapFragment; import com.androidmapsextensions.Marker; import com.androidmapsextensions.MarkerOptions; import com.androidmapsextensions.Polyline; import com.androidmapsextensions.PolylineOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.hereastory.service.api.OutputFileServiceFactory; import com.hereastory.service.api.PointOfInterestReadHandler; import com.hereastory.service.api.PointOfInterestService; import com.hereastory.service.impl.PointOfInterestServiceImpl; import com.hereastory.shared.IntentConsts; import com.hereastory.shared.LimitedPointOfInterest; import com.hereastory.shared.LocationUnavailableException; import com.hereastory.shared.PointLocation; import com.hereastory.shared.PointOfInterest; import com.hereastory.shared.WebFetcher; import com.hereastory.ui.DirectionsFetcher; import com.hereastory.ui.MarkerClusteringOptionsProvider; import com.hereastory.ui.OnResponseRetrieved; import com.hereastory.ui.SystemUiHiderActivity; import com.parse.ParseException; /** * The main map activity. */ public class MapActivity extends SystemUiHiderActivity implements GooglePlayServicesClient.ConnectionCallbacks, OnMarkerClickListener, OnInfoWindowClickListener, OnCameraChangeListener, OnMyLocationChangeListener, OnResponseRetrieved { private static final String LOG_TAG = MapActivity.class.getSimpleName(); private static final String ERROR_INFO_WINDOW = "error_info_window"; private final class POIReader implements PointOfInterestReadHandler { @Override public void readLimitedFailed(String id, Exception e) { displayErrorPopup(); Log.w(LOG_TAG, "ReadLimited failed when trying to get POI with id \"".concat(id).concat("\""), e); } @Override public void readLimitedCompleted(LimitedPointOfInterest poi) { Marker clickedMarker = map.getMarkerShowingInfoWindow(); updateMarkerInfoWindow(clickedMarker, poi.getTitle(), poi.getAuthorName()); cachedMarkers.put((PointLocation) clickedMarker.getData(), poi); } @Override public void readFailed(String id, Exception e) { displayErrorPopup(); Log.w(LOG_TAG, "Read failed when trying to get POI with id \"".concat(id).concat("\""), e); } private void displayErrorPopup() { Marker clickedMarker = map.getMarkerShowingInfoWindow(); updateMarkerInfoWindow(clickedMarker, MapActivity.this.getString(R.string.marker_failed_title), MapActivity.this.getString(R.string.marker_failed_snippet)); } @Override public void readCompleted(PointOfInterest poi) { Intent hearStoryIntent = new Intent(MapActivity.this, HearStoryActivity.class); hearStoryIntent.putExtra(IntentConsts.STORY_OBJECT, poi); startActivityForResult(hearStoryIntent, IntentConsts.HEAR_STORY_CODE); } @Override public void readAllInAreaFailed(double latitude, double longitude, double maxDistance, ParseException e) { MapActivity.this.showExceptionDialog(e); Log.e(LOG_TAG, "ReadAllInArea failed", e); } @Override public void readAllInAreaCompleted(List<PointLocation> points) { for (PointLocation loc : points) { if (!knownPoints.contains(loc)) { addMarker(new MarkerOptions() .position(new LatLng(loc.getLatitude(), loc.getLongitude())) .data(loc)); knownPoints.add(loc); } } } } // End of class POIReader private static class LocationFailureHandler implements GooglePlayServicesClient.OnConnectionFailedListener { public final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; private Activity activity; private LocationFailureHandler(Activity activity) { this.activity = activity; } @Override public void onConnectionFailed(ConnectionResult connectionResult) { /* * Google Play services can resolve some errors it detects. * If the error has a resolution, try sending an Intent to * start a Google Play services activity that can resolve * error. */ if (connectionResult.hasResolution()) { try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST); } catch (IntentSender.SendIntentException e) { // Log the error e.printStackTrace(); } } else { /* * If no resolution is available, display a dialog to the * user with the error. */ } } } // End of class LocationFailureHandler private View recordStoryButton; private GoogleMap map; LocationFailureHandler failureHandler = new LocationFailureHandler(this); LocationClient locationClient; Location myLastLocation = null; final PointOfInterestReadHandler markerReader = new POIReader(); private PointOfInterestService poiService; private List<Marker> declusterifiedMarkers; protected Map<PointLocation, LimitedPointOfInterest> cachedMarkers = new HashMap<PointLocation, LimitedPointOfInterest>(); protected Set<PointLocation> knownPoints = new HashSet<PointLocation>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setLocale(); setContentView(R.layout.activity_map); int gPlayResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if (gPlayResult != ConnectionResult.SUCCESS) { GooglePlayServicesUtil.getErrorDialog(gPlayResult, this, 0).show(); finish(); } locationClient = new LocationClient(this, this, failureHandler); // Get a handle to the Map Fragment map = ((MapFragment) getFragmentManager() .findFragmentById(R.id.map)).getExtendedMap(); map.setMyLocationEnabled(true); map.setOnMarkerClickListener(this); map.setOnInfoWindowClickListener(this); map.setOnCameraChangeListener(this); map.setOnMyLocationChangeListener(this); super.setupUiHide(findViewById(R.id.map), findViewById(R.id.fullscreen_content_controls), R.id.record_story_button); OutputFileServiceFactory.init(this); // Here-a-Story services and interfaces poiService = new PointOfInterestServiceImpl(); // Clustering ClusteringSettings clusterSettings = new ClusteringSettings(); /*clusterSettings.clusterOptionsProvider(new ClusterOptionsProvider() { @Override public ClusterOptions getClusterOptions(List<Marker> markers) { float hue; if (markers.get(0).getClusterGroup() == STORIES_COLLECTION) { hue = BitmapDescriptorFactory.HUE_ORANGE; } else { hue = BitmapDescriptorFactory.HUE_GREEN; } BitmapDescriptor blueIcon = BitmapDescriptorFactory.defaultMarker(hue); return new ClusterOptions().icon(blueIcon); } }).clusterSize(20);*/ clusterSettings.clusterOptionsProvider(new MarkerClusteringOptionsProvider(getResources())); map.setClustering(clusterSettings); Location myLocation = map.getMyLocation(); if (myLocation != null) { map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()), 13)); this.myLastLocation = myLocation; } else if (savedInstanceState == null) { // Set location to Safra Campus, Jerusalem: (31.774476,35.203543) LatLng jerusalem = new LatLng(32.0866403, 34.7778583); map.moveCamera(CameraUpdateFactory.newLatLngZoom(jerusalem, 13)); } } /** * Sets the language of the activity and thus, the map's. */ private void setLocale() { Locale locale = new Locale(this.getString(R.string.default_map_locale)); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } protected void addMarker(MarkerOptions marker) { BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromResource(R.drawable.single_marker); map.addMarker(marker.icon(markerIcon) /*.rotation(340)*/); } protected void addMarkersAtLocation(LatLng location, float zoom) { poiService.readAllInArea(location.latitude, location.longitude, Math.max(50, 100 * (11.0 - zoom)), markerReader); } @Override public void onResume() { super.onResume(); setLocale(); int gPlayResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if (gPlayResult != ConnectionResult.SUCCESS) { GooglePlayServicesUtil.getErrorDialog(gPlayResult, this, 0).show(); } } @Override public boolean onMarkerClick(final Marker clickedMarker) { for (Polyline polyline : map.getPolylines()) { polyline.remove(); } if (clickedMarker.isCluster()) { declusterify(clickedMarker); return true; } PointLocation loc = clickedMarker.getData(); if (loc != null) { clickedMarker.setTitle(this.getString(R.string.marker_loading_title)); clickedMarker.setSnippet(""); // Clear out old values if (cachedMarkers.containsKey(loc)) { clickedMarker.showInfoWindow(); markerReader.readLimitedCompleted(cachedMarkers.get(loc)); } else { poiService.readLimited(loc.getPointOfInterestId(), markerReader); } fetchWalkingPoints(loc); } return false; } private void fetchWalkingPoints(PointLocation destination) { if (myLastLocation == null) return; String directionsUrl = DirectionsFetcher.makeUrl(myLastLocation.getLatitude(), myLastLocation.getLongitude(), destination.getLatitude(), destination.getLongitude()); WebFetcher webFetcher = new WebFetcher(this); webFetcher.execute(directionsUrl); } public void onResponseRetrieved(String jsonDirections) { List<LatLng> walkingPoints; PolylineOptions polylineOptions = new PolylineOptions(); try { walkingPoints = DirectionsFetcher.fetchPath(jsonDirections); } catch (JSONException e) { return; } polylineOptions.addAll(walkingPoints); /*LatLng last = null; for (int i = 0; i < list.size()-1; i++) { LatLng src = list.get(i); LatLng dest = list.get(i+1); last = dest; Polyline line = googleMap.addPolyline(new PolylineOptions().add( new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude)); }*/ map.addPolyline(polylineOptions.width(3).color(Color.BLUE)); } private void declusterify(Marker cluster) { clusterifyMarkers(); declusterifiedMarkers = cluster.getMarkers(); //LatLng clusterPosition = cluster.getPosition(); //double distance = calculateDistanceBetweenMarkers(); //double currentDistance = -declusterifiedMarkers.size() / 2 * distance; for (Marker marker : declusterifiedMarkers) { marker.setClusterGroup(ClusterGroup.NOT_CLUSTERED); //LatLng newPosition = new LatLng(clusterPosition.latitude, clusterPosition.longitude + currentDistance); PointLocation originalPosition = (PointLocation)marker.getData(); marker.animatePosition(new LatLng(originalPosition.getLatitude(), originalPosition.getLongitude())); //currentDistance += distance; } } private double calculateDistanceBetweenMarkers() { Projection projection = map.getProjection(); Point point = projection.toScreenLocation(new LatLng(0.0, 0.0)); point.x += getResources().getDimensionPixelSize(R.dimen.distance_between_markers); LatLng nextPosition = projection.fromScreenLocation(point); return nextPosition.longitude; } private void clusterifyMarkers() { if (declusterifiedMarkers != null) { for (Marker marker : declusterifiedMarkers) { PointLocation location = marker.getData(); marker.setPosition(new LatLng(location.getLatitude(), location.getLongitude())); marker.setClusterGroup(ClusterGroup.DEFAULT); } declusterifiedMarkers = null; } } protected void showExceptionDialog(Exception e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(e.getMessage()) .setCancelable(false) /*.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } });*/ .setNeutralButton(this.getString(R.string.close_exception_dialog), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } private boolean servicesConnected(Activity activity) { // Check that Google Play services is available int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity); // If Google Play services is available if (ConnectionResult.SUCCESS == resultCode) { return true; // Google Play services was not available for some reason. // resultCode holds the error code. } else { // Get the error dialog from Google Play services Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, activity, LocationFailureHandler.CONNECTION_FAILURE_RESOLUTION_REQUEST); // If Google Play services can provide an error dialog if (errorDialog != null) { errorDialog.show(); } else { } return false; } } public void recordStoryClick(View view) { this.recordStoryButton = view; view.setEnabled(false); if (myLastLocation != null) { startCreateStory(myLastLocation); } else { locationClient.connect(); } } @Override public void onConnected(Bundle connectionHint) { if (!servicesConnected(this)) { locationClient.disconnect(); this.recordStoryButton.setEnabled(true); return; } // Location is now available Location location; LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); try { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { showExceptionDialog(new LocationUnavailableException(this.getString(R.string.gps_unavailable_exception))); return; } location = locationClient.getLastLocation(); if (location == null) { Log.w(LOG_TAG, "Unable to acquire location after connected to GooglePlayServices"); showExceptionDialog(new LocationUnavailableException(this.getString(R.string.location_unavailable_exception))); return; } } finally { locationClient.disconnect(); this.recordStoryButton.setEnabled(true); } startCreateStory(location); } private void startCreateStory(Location location) { Intent createStoryIntent = new Intent(this, LoginActivity.class); createStoryIntent.putExtra(IntentConsts.CURRENT_LAT, location.getLatitude()); createStoryIntent.putExtra(IntentConsts.CURRENT_LONG, location.getLongitude()); startActivityForResult(createStoryIntent, IntentConsts.CREATE_STORY_CODE); this.recordStoryButton.setEnabled(true); } @Override public void onDisconnected() { } @Override public void onInfoWindowClick(Marker origin) { if (origin.getData().toString() == ERROR_INFO_WINDOW) { origin.hideInfoWindow(); } else { PointLocation data = origin.getData(); poiService.read(data.getPointOfInterestId(), markerReader); } } private void updateMarkerInfoWindow(Marker clickedMarker, String infoWindowTitle, String infoWindowSnippet) { if (clickedMarker != null) { clickedMarker.hideInfoWindow(); clickedMarker.setTitle(infoWindowTitle); clickedMarker.setSnippet(infoWindowSnippet); clickedMarker.showInfoWindow(); } } @Override public void onCameraChange(CameraPosition position) { addMarkersAtLocation(position.target, position.zoom); //clusterifyMarkers(); } @Override public void onMyLocationChange(Location location) { if (location == null) return; if (myLastLocation == null || (location.getLatitude() != myLastLocation.getLatitude() && location.getLongitude() != myLastLocation.getLongitude())) { map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()))); myLastLocation = location; } } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(this, MapActivity.class); startActivity(intent); } }
src/com/hereastory/MapActivity.java
package com.hereastory; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.View; import com.androidmapsextensions.ClusterGroup; import com.androidmapsextensions.ClusteringSettings; import com.androidmapsextensions.GoogleMap; import com.androidmapsextensions.GoogleMap.OnCameraChangeListener; import com.androidmapsextensions.GoogleMap.OnInfoWindowClickListener; import com.androidmapsextensions.GoogleMap.OnMarkerClickListener; import com.androidmapsextensions.GoogleMap.OnMyLocationChangeListener; import com.androidmapsextensions.MapFragment; import com.androidmapsextensions.Marker; import com.androidmapsextensions.MarkerOptions; import com.androidmapsextensions.Polyline; import com.androidmapsextensions.PolylineOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.hereastory.service.api.OutputFileServiceFactory; import com.hereastory.service.api.PointOfInterestReadHandler; import com.hereastory.service.api.PointOfInterestService; import com.hereastory.service.impl.PointOfInterestServiceImpl; import com.hereastory.shared.IntentConsts; import com.hereastory.shared.LimitedPointOfInterest; import com.hereastory.shared.LocationUnavailableException; import com.hereastory.shared.PointLocation; import com.hereastory.shared.PointOfInterest; import com.hereastory.shared.WebFetcher; import com.hereastory.ui.DirectionsFetcher; import com.hereastory.ui.MarkerClusteringOptionsProvider; import com.hereastory.ui.OnResponseRetrieved; import com.hereastory.ui.SystemUiHiderActivity; import com.parse.ParseException; /** * The main map activity. */ public class MapActivity extends SystemUiHiderActivity implements GooglePlayServicesClient.ConnectionCallbacks, OnMarkerClickListener, OnInfoWindowClickListener, OnCameraChangeListener, OnMyLocationChangeListener, OnResponseRetrieved { private static final String LOG_TAG = MapActivity.class.getSimpleName(); private static final String ERROR_INFO_WINDOW = "error_info_window"; private final class POIReader implements PointOfInterestReadHandler { @Override public void readLimitedFailed(String id, Exception e) { displayErrorPopup(); Log.w(LOG_TAG, "ReadLimited failed when trying to get POI with id \"".concat(id).concat("\""), e); } @Override public void readLimitedCompleted(LimitedPointOfInterest poi) { Marker clickedMarker = map.getMarkerShowingInfoWindow(); updateMarkerInfoWindow(clickedMarker, poi.getTitle(), poi.getAuthorName()); cachedMarkers.put((PointLocation) clickedMarker.getData(), poi); } @Override public void readFailed(String id, Exception e) { displayErrorPopup(); Log.w(LOG_TAG, "Read failed when trying to get POI with id \"".concat(id).concat("\""), e); } private void displayErrorPopup() { Marker clickedMarker = map.getMarkerShowingInfoWindow(); updateMarkerInfoWindow(clickedMarker, MapActivity.this.getString(R.string.marker_failed_title), MapActivity.this.getString(R.string.marker_failed_snippet)); } @Override public void readCompleted(PointOfInterest poi) { Intent hearStoryIntent = new Intent(MapActivity.this, HearStoryActivity.class); hearStoryIntent.putExtra(IntentConsts.STORY_OBJECT, poi); startActivityForResult(hearStoryIntent, IntentConsts.HEAR_STORY_CODE); } @Override public void readAllInAreaFailed(double latitude, double longitude, double maxDistance, ParseException e) { MapActivity.this.showExceptionDialog(e); Log.e(LOG_TAG, "ReadAllInArea failed", e); } @Override public void readAllInAreaCompleted(List<PointLocation> points) { for (PointLocation loc : points) { if (!knownPoints.contains(loc)) { addMarker(new MarkerOptions() .position(new LatLng(loc.getLatitude(), loc.getLongitude())) .data(loc)); knownPoints.add(loc); } } } } // End of class POIReader private static class LocationFailureHandler implements GooglePlayServicesClient.OnConnectionFailedListener { public final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; private Activity activity; private LocationFailureHandler(Activity activity) { this.activity = activity; } @Override public void onConnectionFailed(ConnectionResult connectionResult) { /* * Google Play services can resolve some errors it detects. * If the error has a resolution, try sending an Intent to * start a Google Play services activity that can resolve * error. */ if (connectionResult.hasResolution()) { try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST); } catch (IntentSender.SendIntentException e) { // Log the error e.printStackTrace(); } } else { /* * If no resolution is available, display a dialog to the * user with the error. */ } } } // End of class LocationFailureHandler private View recordStoryButton; private GoogleMap map; LocationFailureHandler failureHandler = new LocationFailureHandler(this); LocationClient locationClient; Location myLastLocation = null; final PointOfInterestReadHandler markerReader = new POIReader(); private PointOfInterestService poiService; private List<Marker> declusterifiedMarkers; protected Map<PointLocation, LimitedPointOfInterest> cachedMarkers = new HashMap<PointLocation, LimitedPointOfInterest>(); protected Set<PointLocation> knownPoints = new HashSet<PointLocation>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setLocale(); setContentView(R.layout.activity_map); int gPlayResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if (gPlayResult != ConnectionResult.SUCCESS) { GooglePlayServicesUtil.getErrorDialog(gPlayResult, this, 0).show(); finish(); } locationClient = new LocationClient(this, this, failureHandler); // Get a handle to the Map Fragment map = ((MapFragment) getFragmentManager() .findFragmentById(R.id.map)).getExtendedMap(); map.setMyLocationEnabled(true); map.setOnMarkerClickListener(this); map.setOnInfoWindowClickListener(this); map.setOnCameraChangeListener(this); map.setOnMyLocationChangeListener(this); super.setupUiHide(findViewById(R.id.map), findViewById(R.id.fullscreen_content_controls), R.id.record_story_button); OutputFileServiceFactory.init(this); // Here-a-Story services and interfaces poiService = new PointOfInterestServiceImpl(); // Clustering ClusteringSettings clusterSettings = new ClusteringSettings(); /*clusterSettings.clusterOptionsProvider(new ClusterOptionsProvider() { @Override public ClusterOptions getClusterOptions(List<Marker> markers) { float hue; if (markers.get(0).getClusterGroup() == STORIES_COLLECTION) { hue = BitmapDescriptorFactory.HUE_ORANGE; } else { hue = BitmapDescriptorFactory.HUE_GREEN; } BitmapDescriptor blueIcon = BitmapDescriptorFactory.defaultMarker(hue); return new ClusterOptions().icon(blueIcon); } }).clusterSize(20);*/ clusterSettings.clusterOptionsProvider(new MarkerClusteringOptionsProvider(getResources())); map.setClustering(clusterSettings); Location myLocation = map.getMyLocation(); if (myLocation != null) { map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()), 13)); this.myLastLocation = myLocation; } else if (savedInstanceState == null) { // Set location to Safra Campus, Jerusalem: (31.774476,35.203543) LatLng jerusalem = new LatLng(32.0866403, 34.7778583); map.moveCamera(CameraUpdateFactory.newLatLngZoom(jerusalem, 13)); } } /** * Sets the language of the activity and thus, the map's. */ private void setLocale() { Locale locale = new Locale(this.getString(R.string.default_map_locale)); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } protected void addMarker(MarkerOptions marker) { BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromResource(R.drawable.single_marker); map.addMarker(marker.icon(markerIcon) /*.rotation(340)*/); } protected void addMarkersAtLocation(LatLng location, float zoom) { poiService.readAllInArea(location.latitude, location.longitude, Math.max(50, 100 * (11.0 - zoom)), markerReader); } @Override public void onResume() { super.onResume(); setLocale(); int gPlayResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if (gPlayResult != ConnectionResult.SUCCESS) { GooglePlayServicesUtil.getErrorDialog(gPlayResult, this, 0).show(); } } @Override public boolean onMarkerClick(final Marker clickedMarker) { for (Polyline polyline : map.getPolylines()) { polyline.remove(); } if (clickedMarker.isCluster()) { declusterify(clickedMarker); return true; } PointLocation loc = clickedMarker.getData(); if (loc != null) { clickedMarker.setTitle(this.getString(R.string.marker_loading_title)); clickedMarker.setSnippet(""); // Clear out old values if (cachedMarkers.containsKey(loc)) { markerReader.readLimitedCompleted(cachedMarkers.get(loc)); } else { poiService.readLimited(loc.getPointOfInterestId(), markerReader); } fetchWalkingPoints(loc); } return false; } private void fetchWalkingPoints(PointLocation destination) { if (myLastLocation == null) return; String directionsUrl = DirectionsFetcher.makeUrl(myLastLocation.getLatitude(), myLastLocation.getLongitude(), destination.getLatitude(), destination.getLongitude()); WebFetcher webFetcher = new WebFetcher(this); webFetcher.execute(directionsUrl); } public void onResponseRetrieved(String jsonDirections) { List<LatLng> walkingPoints; PolylineOptions polylineOptions = new PolylineOptions(); try { walkingPoints = DirectionsFetcher.fetchPath(jsonDirections); } catch (JSONException e) { return; } polylineOptions.addAll(walkingPoints); /*LatLng last = null; for (int i = 0; i < list.size()-1; i++) { LatLng src = list.get(i); LatLng dest = list.get(i+1); last = dest; Polyline line = googleMap.addPolyline(new PolylineOptions().add( new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude)); }*/ map.addPolyline(polylineOptions.width(3).color(Color.BLUE)); } private void declusterify(Marker cluster) { clusterifyMarkers(); declusterifiedMarkers = cluster.getMarkers(); //LatLng clusterPosition = cluster.getPosition(); //double distance = calculateDistanceBetweenMarkers(); //double currentDistance = -declusterifiedMarkers.size() / 2 * distance; for (Marker marker : declusterifiedMarkers) { marker.setClusterGroup(ClusterGroup.NOT_CLUSTERED); //LatLng newPosition = new LatLng(clusterPosition.latitude, clusterPosition.longitude + currentDistance); PointLocation originalPosition = (PointLocation)marker.getData(); marker.animatePosition(new LatLng(originalPosition.getLatitude(), originalPosition.getLongitude())); //currentDistance += distance; } } private double calculateDistanceBetweenMarkers() { Projection projection = map.getProjection(); Point point = projection.toScreenLocation(new LatLng(0.0, 0.0)); point.x += getResources().getDimensionPixelSize(R.dimen.distance_between_markers); LatLng nextPosition = projection.fromScreenLocation(point); return nextPosition.longitude; } private void clusterifyMarkers() { if (declusterifiedMarkers != null) { for (Marker marker : declusterifiedMarkers) { PointLocation location = marker.getData(); marker.setPosition(new LatLng(location.getLatitude(), location.getLongitude())); marker.setClusterGroup(ClusterGroup.DEFAULT); } declusterifiedMarkers = null; } } protected void showExceptionDialog(Exception e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(e.getMessage()) .setCancelable(false) /*.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } });*/ .setNeutralButton(this.getString(R.string.close_exception_dialog), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } private boolean servicesConnected(Activity activity) { // Check that Google Play services is available int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity); // If Google Play services is available if (ConnectionResult.SUCCESS == resultCode) { return true; // Google Play services was not available for some reason. // resultCode holds the error code. } else { // Get the error dialog from Google Play services Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, activity, LocationFailureHandler.CONNECTION_FAILURE_RESOLUTION_REQUEST); // If Google Play services can provide an error dialog if (errorDialog != null) { errorDialog.show(); } else { } return false; } } public void recordStoryClick(View view) { this.recordStoryButton = view; view.setEnabled(false); if (myLastLocation != null) { startCreateStory(myLastLocation); } else { locationClient.connect(); } } @Override public void onConnected(Bundle connectionHint) { if (!servicesConnected(this)) { locationClient.disconnect(); this.recordStoryButton.setEnabled(true); return; } // Location is now available Location location; LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); try { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { showExceptionDialog(new LocationUnavailableException(this.getString(R.string.gps_unavailable_exception))); return; } location = locationClient.getLastLocation(); if (location == null) { Log.w(LOG_TAG, "Unable to acquire location after connected to GooglePlayServices"); showExceptionDialog(new LocationUnavailableException(this.getString(R.string.location_unavailable_exception))); return; } } finally { locationClient.disconnect(); this.recordStoryButton.setEnabled(true); } startCreateStory(location); } private void startCreateStory(Location location) { Intent createStoryIntent = new Intent(this, LoginActivity.class); createStoryIntent.putExtra(IntentConsts.CURRENT_LAT, location.getLatitude()); createStoryIntent.putExtra(IntentConsts.CURRENT_LONG, location.getLongitude()); startActivityForResult(createStoryIntent, IntentConsts.CREATE_STORY_CODE); this.recordStoryButton.setEnabled(true); } @Override public void onDisconnected() { } @Override public void onInfoWindowClick(Marker origin) { if (origin.getData().toString() == ERROR_INFO_WINDOW) { origin.hideInfoWindow(); } else { PointLocation data = origin.getData(); poiService.read(data.getPointOfInterestId(), markerReader); } } private void updateMarkerInfoWindow(Marker clickedMarker, String infoWindowTitle, String infoWindowSnippet) { if (clickedMarker != null) { clickedMarker.hideInfoWindow(); clickedMarker.setTitle(infoWindowTitle); clickedMarker.setSnippet(infoWindowSnippet); clickedMarker.showInfoWindow(); } } @Override public void onCameraChange(CameraPosition position) { addMarkersAtLocation(position.target, position.zoom); //clusterifyMarkers(); } @Override public void onMyLocationChange(Location location) { if (location == null) return; if (myLastLocation == null || (location.getLatitude() != myLastLocation.getLatitude() && location.getLongitude() != myLastLocation.getLongitude())) { map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()))); myLastLocation = location; } } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(this, MapActivity.class); startActivity(intent); } }
Marker.Click bug fix
src/com/hereastory/MapActivity.java
Marker.Click bug fix
<ide><path>rc/com/hereastory/MapActivity.java <ide> declusterify(clickedMarker); <ide> return true; <ide> } <add> <ide> PointLocation loc = clickedMarker.getData(); <ide> if (loc != null) { <ide> clickedMarker.setTitle(this.getString(R.string.marker_loading_title)); <ide> clickedMarker.setSnippet(""); // Clear out old values <ide> if (cachedMarkers.containsKey(loc)) { <add> clickedMarker.showInfoWindow(); <ide> markerReader.readLimitedCompleted(cachedMarkers.get(loc)); <ide> } else { <ide> poiService.readLimited(loc.getPointOfInterestId(), markerReader);
JavaScript
apache-2.0
42a166964c0c83d41cbc62146168045170d590be
0
OpenGeoscience/geojs,Kitware/geojs,Kitware/geojs,essamjoubori/geojs,Kitware/geojs,dcjohnston/geojs,essamjoubori/geojs,dcjohnston/geojs,dcjohnston/geojs,essamjoubori/geojs,dcjohnston/geojs,OpenGeoscience/geojs,OpenGeoscience/geojs,essamjoubori/geojs
////////////////////////////////////////////////////////////////////////////// /** * @module ogs.wfl */ /*jslint devel: true, forin: true, newcap: true, plusplus: true*/ /*jslint white: true, indent: 2*/ /*global geoModule, ogs, inherit, $, HTMLCanvasElement, Image*/ /*global vglModule, proj4, document*/ ////////////////////////////////////////////////////////////////////////////// /** * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 * @param obj1 object * @param obj2 object * @returns object a new object based on obj1 and obj2 */ function merge_options(obj1,obj2){ var obj3 = {}; for (var attrName in obj1) { obj3[attrName] = obj1[attrName]; } for (var attrName in obj2) { obj3[attrName] = obj2[attrName]; } return obj3; } function merge_options_in_place(obj1, obj2) { for (var attrName in obj2) { obj1[attrName] = obj2[attrName]; } return obj1; } function defaultValue(param, _default) { return typeof param !== 'undefined' ? param: _default; } function createIdCounter(initialId) { initialId = defaultValue(initialId, -1); return function() { initialId += 1; return initialId; }; } var nextWorkflowId = createIdCounter(); var nextModuleId = createIdCounter(); var nextLocationId = createIdCounter(); var nextConnectionId = createIdCounter(); var nextPortId = createIdCounter(); var nextFunctionId = createIdCounter(); function blankWorkflow(name, version, connections, modules, vistrail_id, id) { name = defaultValue(name, 'untitled'); version = defaultValue(version, '1.0.2'); connections = defaultValue(connections, []); modules = defaultValue(modules, []); vistrail_id = defaultValue(vistrail_id, ""); id = defaultValue(id, nextWorkflowId()); return { "workflow": { "@name": name, "@version": version, "@{http://www.w3.org/2001/XMLSchema-instance}schemaLocation": "http://www.vistrails.org/workflow.xsd", "connection": connections, "module": modules, "@vistrail_id": vistrail_id, "@id": id } }; } var moduleRegistry = {}, currentWorkflowStyle = climatePipesStyle, activeWorkflow; function debug(msg) { console.log(msg); } function initWorkflowCanvas() { $(window).on('resize', function() { if (activeWorkflow) activeWorkflow.resize(); }); // append workflow html elements $('body').append( [ '<div id="workflow-dialog" title="Workflow"><table id="mainTable">', '<tr><td><div id="modulediv"><table id="moduletable">', '<tbody></tbody></table></div></td>', '<td id="canvasContainer"><canvas id="workspace"></canvas></td></tr></table></div>' ].join('') ); setupWorkflowDragAndDrop(); setupWorkflowModuleList(); setupWorkflowInteraction(); setupWorkflowCSS(); } function setupWorkflowCSS() { var stylesheet = document.styleSheets[0], selector = "[draggable]", rule = [ '{-moz-user-select: none;', '-khtml-user-select: none;', '-webkit-user-select: none;', 'user-select: none;', '-khtml-user-drag: element;', '-webkit-user-drag: element;', 'cursor: move;}' ].join(''); if (stylesheet.insertRule) { var pos = stylesheet.cssRules ? stylesheet.cssRules.length : 0; stylesheet.insertRule(selector + rule, pos); } else if (stylesheet.addRule) { stylesheet.addRule(selector, rule, -1); } $('#mainTable').css({ height: '100%', width: '100%' }); $('#modulediv').css({ height: '100%', width: 160, overflow: 'auto' }); $('#canvasContainer').css({ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', 'background-image': 'url(/common/img/tweed.png)', 'background-repeat': 'repeat' }); $('#workflow-dialog').hide(); //give modules a texture fill var $canvas = $('#workspace'), context = $canvas[0].getContext('2d'), img = new Image(); img.onload = function() { climatePipesStyle.module.fill = context.createPattern(img, 'repeat'); }; img.src = '/common/img/squairy_light.png'; } function setupWorkflowDragAndDrop() { var $canvas = $('#workspace'); $canvas.on('dragover', function(e) { if (e.originalEvent) { //jQuery e = e.originalEvent; } if (e.preventDefault) { e.preventDefault(); } e.dataTransfer.dropEffect = 'copy'; }); $canvas.on('drop', function(e) { if (e.originalEvent) { //jQuery e = e.originalEvent; } if (e.preventDefault) { e.preventDefault(); } // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } var ctxPos = this.ctxMousePos(e); activeWorkflow.addNewModule( e.dataTransfer.getData("Text"), ctxPos.x, ctxPos.y ); activeWorkflow.draw($canvas[0].getContext('2d')); return false; }); } function setupWorkflowModuleList() { var $moduleTableBody = $('#moduletable > tbody:last'); for(var i = 0; i < reg.registry.package.length; i++) { var pkg = reg.registry.package[i]; if(!moduleRegistry.hasOwnProperty(pkg['@identifier'])) { moduleRegistry[pkg['@identifier']] = {}; } if(!pkg.hasOwnProperty('moduleDescriptor')) { continue; } for(var j = 0; j < pkg.moduleDescriptor.length; j++) { var moduleInfo = pkg.moduleDescriptor[j]; moduleRegistry[pkg['@identifier']][moduleInfo['@name']] = moduleInfo; addModuleToList(moduleInfo, $moduleTableBody); } } } function addModuleToList(moduleInfo, $moduleTableBody) { var $text = $(document.createElement('div')); $text.append(moduleInfo['@name']) .attr('draggable', 'true') .data('moduleInfo', moduleInfo) .on('dragstart', function(e) { if (e.originalEvent) { //jQuery e = e.originalEvent; } e.dataTransfer.effectAllowed = 'copy'; e.dataTransfer.setData("Text", JSON.stringify($(this).data('moduleInfo'))); debug(e); }); var $td = $(document.createElement('td')); var $tr = $(document.createElement('tr')); $moduleTableBody.append($tr.append($td.append($text))); } function setupWorkflowInteraction() { var $canvas = $('#workspace'), ctx = $canvas[0].getContext('2d'), panning, lastPoint, lastPanEvent, draggingPort, draggingPortPos, draggingPortModule, draggingModule, tempConnection = wflModule.connection(); $canvas.mousedown(function (e) { var modules = activeWorkflow.modules(), key, module; lastPoint = this.ctxMousePos(e); // find modules for(key in modules) { if(modules.hasOwnProperty(key)) { module = modules[key]; if(module.contains(lastPoint)) { if(draggingPort = module.portByPos(lastPoint)) { draggingPortPos = lastPoint; draggingPortModule = module; } else { draggingModule = module; } return; } } } // find connections // else initiate pan panning = true; lastPanEvent = e; }); $canvas.mousemove(function (e) { // if dragging module if(draggingModule) { var newPoint = this.ctxMousePos(e); draggingModule.getData().location['@x'] += newPoint.x - lastPoint.x; draggingModule.getData().location['@y'] -= newPoint.y - lastPoint.y; draggingModule.recomputeMetrics($canvas[0].getContext('2d'), currentWorkflowStyle); lastPoint = newPoint; activeWorkflow.draw(ctx); } else if (draggingPort) { lastPoint = this.ctxMousePos(e); activeWorkflow.draw(ctx); tempConnection.drawCurve(ctx, currentWorkflowStyle, { cx1: draggingPortPos.x, cy1: draggingPortPos.y, cx2: lastPoint.x, cy2: lastPoint.y }); } else if (panning) { activeWorkflow.translate( this.getContext('2d'), e.clientX - lastPanEvent.clientX, e.clientY - lastPanEvent.clientY ); lastPanEvent = e; activeWorkflow.draw(ctx); activeWorkflow.updateElementPositions(); } }); $canvas.mouseup(function (e) { panning = false; draggingModule = null; if( draggingPort ) { var port, modules = activeWorkflow.modules(), key, module, ctx = this.getContext('2d'); for(key in modules) { if(modules.hasOwnProperty(key)) { module = modules[key]; if(module.contains(lastPoint)) { if(port = module.portByPos(lastPoint)) { activeWorkflow.addConnection( draggingPortModule, draggingPort, module, port ); break; } } } } draggingPort = null; draggingPortModule = null; draggingPortPos = null; activeWorkflow.draw(ctx, currentWorkflowStyle); } }); $canvas.mouseout(function (e) { panning = false; }); } function ctxMousePos(event){ var totalOffsetX = 0, totalOffsetY = 0, currentElement = this, translated = activeWorkflow.translated(); do{ totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft; totalOffsetY += currentElement.offsetTop - currentElement.scrollTop; } while(currentElement = currentElement.offsetParent) return { x: event.pageX - totalOffsetX - translated.x, y: event.pageY - totalOffsetY - translated.y }; } /** * Draws a rounded rectangle using the current state of the canvas. * If you omit the last three params, it will draw a rectangle * outline with a 5 pixel border radius * @param {CanvasRenderingContext2D} ctx * @param {Number} x The top left x coordinate * @param {Number} y The top left y coordinate * @param {Number} width The width of the rectangle * @param {Number} height The height of the rectangle * @param {Number} radius The corner radius. Defaults to 5; * @param {Boolean} fill Whether to fill the rectangle. Defaults to false. * @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true. */ function roundRect(ctx, x, y, width, height, radius, fill, stroke) { if (typeof radius === "undefined") { radius = 5; } ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); ctx.lineTo(x + width, y + height - radius); ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); ctx.lineTo(x + radius, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius); ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); if (stroke || typeof stroke == "undefined") { ctx.stroke(); } if (fill) { ctx.fill(); } } HTMLCanvasElement.prototype.ctxMousePos = ctxMousePos;
wfl/workflowUtils.js
////////////////////////////////////////////////////////////////////////////// /** * @module ogs.wfl */ /*jslint devel: true, forin: true, newcap: true, plusplus: true*/ /*jslint white: true, indent: 2*/ /*global geoModule, ogs, inherit, $, HTMLCanvasElement, Image*/ /*global vglModule, proj4, document*/ ////////////////////////////////////////////////////////////////////////////// /** * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 * @param obj1 object * @param obj2 object * @returns object a new object based on obj1 and obj2 */ function merge_options(obj1,obj2){ var obj3 = {}; for (var attrName in obj1) { obj3[attrName] = obj1[attrName]; } for (var attrName in obj2) { obj3[attrName] = obj2[attrName]; } return obj3; } function merge_options_in_place(obj1, obj2) { for (var attrName in obj2) { obj1[attrName] = obj2[attrName]; } return obj1; } function defaultValue(param, _default) { return typeof param !== 'undefined' ? param: _default; } function createIdCounter(initialId) { initialId = defaultValue(initialId, -1); return function() { initialId += 1; return initialId; }; } var nextWorkflowId = createIdCounter(); var nextModuleId = createIdCounter(); var nextLocationId = createIdCounter(); var nextConnectionId = createIdCounter(); var nextPortId = createIdCounter(); var nextFunctionId = createIdCounter(); function blankWorkflow(name, version, connections, modules, vistrail_id, id) { name = defaultValue(name, 'untitled'); version = defaultValue(version, '1.0.2'); connections = defaultValue(connections, []); modules = defaultValue(modules, []); vistrail_id = defaultValue(vistrail_id, ""); id = defaultValue(id, nextWorkflowId()); return { "workflow": { "@name": name, "@version": version, "@{http://www.w3.org/2001/XMLSchema-instance}schemaLocation": "http://www.vistrails.org/workflow.xsd", "connection": connections, "module": modules, "@vistrail_id": vistrail_id, "@id": id } }; } var moduleRegistry = {}, currentWorkflowStyle = climatePipesStyle, activeWorkflow; function debug(msg) { console.log(msg); } function initWorkflowCanvas() { $(window).on('resize', function() { if (activeWorkflow) activeWorkflow.resize(); }); //append workflow html elements $('body').append( [ '<div id="workflow-dialog" title="Workflow"><table id="mainTable">', '<tr><td><div id="modulediv"><table id="moduletable">', '<tbody></tbody></table></div></td>', '<td id="canvasContainer"><canvas id="workspace"/></td></tr></table></div>' ].join('') ); setupWorkflowDragAndDrop(); setupWorkflowModuleList(); setupWorkflowInteraction(); setupWorkflowCSS(); } function setupWorkflowCSS() { var stylesheet = document.styleSheets[0], selector = "[draggable]", rule = [ '{-moz-user-select: none;', '-khtml-user-select: none;', '-webkit-user-select: none;', 'user-select: none;', '-khtml-user-drag: element;', '-webkit-user-drag: element;', 'cursor: move;}' ].join(''); if (stylesheet.insertRule) { var pos = stylesheet.cssRules ? stylesheet.cssRules.length : 0; stylesheet.insertRule(selector + rule, pos); } else if (stylesheet.addRule) { stylesheet.addRule(selector, rule, -1); } $('#mainTable').css({ height: '100%', width: '100%' }); $('#modulediv').css({ height: '100%', width: 160, overflow: 'auto' }); $('#canvasContainer').css({ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', 'background-image': 'url(/common/img/tweed.png)', 'background-repeat': 'repeat' }); //give modules a texture fill var $canvas = $('#workspace'), context = $canvas[0].getContext('2d'), img = new Image(); img.onload = function() { climatePipesStyle.module.fill = context.createPattern(img, 'repeat'); }; img.src = '/common/img/squairy_light.png'; } function setupWorkflowDragAndDrop() { var $canvas = $('#workspace'); $canvas.on('dragover', function(e) { if (e.originalEvent) { //jQuery e = e.originalEvent; } if (e.preventDefault) { e.preventDefault(); } e.dataTransfer.dropEffect = 'copy'; }); $canvas.on('drop', function(e) { if (e.originalEvent) { //jQuery e = e.originalEvent; } if (e.preventDefault) { e.preventDefault(); } // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } var ctxPos = this.ctxMousePos(e); activeWorkflow.addNewModule( e.dataTransfer.getData("Text"), ctxPos.x, ctxPos.y ); activeWorkflow.draw($canvas[0].getContext('2d')); return false; }); } function setupWorkflowModuleList() { var $moduleTableBody = $('#moduletable > tbody:last'); for(var i = 0; i < reg.registry.package.length; i++) { var pkg = reg.registry.package[i]; if(!moduleRegistry.hasOwnProperty(pkg['@identifier'])) { moduleRegistry[pkg['@identifier']] = {}; } if(!pkg.hasOwnProperty('moduleDescriptor')) { continue; } for(var j = 0; j < pkg.moduleDescriptor.length; j++) { var moduleInfo = pkg.moduleDescriptor[j]; moduleRegistry[pkg['@identifier']][moduleInfo['@name']] = moduleInfo; addModuleToList(moduleInfo, $moduleTableBody); } } } function addModuleToList(moduleInfo, $moduleTableBody) { var $text = $(document.createElement('div')); $text.append(moduleInfo['@name']) .attr('draggable', 'true') .data('moduleInfo', moduleInfo) .on('dragstart', function(e) { if (e.originalEvent) { //jQuery e = e.originalEvent; } e.dataTransfer.effectAllowed = 'copy'; e.dataTransfer.setData("Text", JSON.stringify($(this).data('moduleInfo'))); debug(e); }); var $td = $(document.createElement('td')); var $tr = $(document.createElement('tr')); $moduleTableBody.append($tr.append($td.append($text))); } function setupWorkflowInteraction() { var $canvas = $('#workspace'), ctx = $canvas[0].getContext('2d'), panning, lastPoint, lastPanEvent, draggingPort, draggingPortPos, draggingPortModule, draggingModule, tempConnection = wflModule.connection(); $canvas.mousedown(function (e) { var modules = activeWorkflow.modules(), key, module; lastPoint = this.ctxMousePos(e); // find modules for(key in modules) { if(modules.hasOwnProperty(key)) { module = modules[key]; if(module.contains(lastPoint)) { if(draggingPort = module.portByPos(lastPoint)) { draggingPortPos = lastPoint; draggingPortModule = module; } else { draggingModule = module; } return; } } } // find connections // else initiate pan panning = true; lastPanEvent = e; }); $canvas.mousemove(function (e) { // if dragging module if(draggingModule) { var newPoint = this.ctxMousePos(e); draggingModule.getData().location['@x'] += newPoint.x - lastPoint.x; draggingModule.getData().location['@y'] -= newPoint.y - lastPoint.y; draggingModule.recomputeMetrics($canvas[0].getContext('2d'), currentWorkflowStyle); lastPoint = newPoint; activeWorkflow.draw(ctx); } else if (draggingPort) { lastPoint = this.ctxMousePos(e); activeWorkflow.draw(ctx); tempConnection.drawCurve(ctx, currentWorkflowStyle, { cx1: draggingPortPos.x, cy1: draggingPortPos.y, cx2: lastPoint.x, cy2: lastPoint.y }); } else if (panning) { activeWorkflow.translate( this.getContext('2d'), e.clientX - lastPanEvent.clientX, e.clientY - lastPanEvent.clientY ); lastPanEvent = e; activeWorkflow.draw(ctx); activeWorkflow.updateElementPositions(); } }); $canvas.mouseup(function (e) { panning = false; draggingModule = null; if( draggingPort ) { var port, modules = activeWorkflow.modules(), key, module, ctx = this.getContext('2d'); for(key in modules) { if(modules.hasOwnProperty(key)) { module = modules[key]; if(module.contains(lastPoint)) { if(port = module.portByPos(lastPoint)) { activeWorkflow.addConnection( draggingPortModule, draggingPort, module, port ); break; } } } } draggingPort = null; draggingPortModule = null; draggingPortPos = null; activeWorkflow.draw(ctx, currentWorkflowStyle); } }); $canvas.mouseout(function (e) { panning = false; }); } function ctxMousePos(event){ var totalOffsetX = 0, totalOffsetY = 0, currentElement = this, translated = activeWorkflow.translated(); do{ totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft; totalOffsetY += currentElement.offsetTop - currentElement.scrollTop; } while(currentElement = currentElement.offsetParent) return { x: event.pageX - totalOffsetX - translated.x, y: event.pageY - totalOffsetY - translated.y }; } /** * Draws a rounded rectangle using the current state of the canvas. * If you omit the last three params, it will draw a rectangle * outline with a 5 pixel border radius * @param {CanvasRenderingContext2D} ctx * @param {Number} x The top left x coordinate * @param {Number} y The top left y coordinate * @param {Number} width The width of the rectangle * @param {Number} height The height of the rectangle * @param {Number} radius The corner radius. Defaults to 5; * @param {Boolean} fill Whether to fill the rectangle. Defaults to false. * @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true. */ function roundRect(ctx, x, y, width, height, radius, fill, stroke) { if (typeof radius === "undefined") { radius = 5; } ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); ctx.lineTo(x + width, y + height - radius); ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); ctx.lineTo(x + radius, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius); ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); if (stroke || typeof stroke == "undefined") { ctx.stroke(); } if (fill) { ctx.fill(); } } HTMLCanvasElement.prototype.ctxMousePos = ctxMousePos;
Fixes module list bug on main archive page
wfl/workflowUtils.js
Fixes module list bug on main archive page
<ide><path>fl/workflowUtils.js <ide> activeWorkflow.resize(); <ide> }); <ide> <del> //append workflow html elements <add>// append workflow html elements <ide> $('body').append( <ide> [ <ide> '<div id="workflow-dialog" title="Workflow"><table id="mainTable">', <ide> '<tr><td><div id="modulediv"><table id="moduletable">', <ide> '<tbody></tbody></table></div></td>', <del> '<td id="canvasContainer"><canvas id="workspace"/></td></tr></table></div>' <add> '<td id="canvasContainer"><canvas id="workspace"></canvas></td></tr></table></div>' <ide> ].join('') <ide> ); <ide> <ide> 'background-image': 'url(/common/img/tweed.png)', <ide> 'background-repeat': 'repeat' <ide> }); <add> <add> $('#workflow-dialog').hide(); <ide> <ide> //give modules a texture fill <ide> var $canvas = $('#workspace'),
Java
apache-2.0
3129ac1b5634eeed0cbe1d5f3a8348bb93b0554b
0
zeelichsheng/auth,zeelichsheng/auth,zeelichsheng/auth
/* * Copyright 2016 Yu Sheng. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, without warranties or * conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the * specific language governing permissions and limitations under the License. */ package com.ysheng.auth.backend.redis; import com.ysheng.auth.backend.redis.entity.ClientEntity; import com.ysheng.auth.common.backend.Database; import com.ysheng.auth.model.database.AuthorizationTicket; import com.ysheng.auth.model.database.Client; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * Implementation of the backend database based on Redis. */ public class RedisDatabase implements Database { // The Redis client. private RedisClient redisClient; /** * Constructs a RedisDatabase object. * * @param redisClient The Redis client. */ public RedisDatabase( RedisClient redisClient) { this.redisClient = redisClient; } /** * Stores a client object in database. * * @param client The client object to be stored. */ public void storeClient(Client client) { redisClient.hmset(new ClientEntity(client)); } /** * Finds a client object by client identifier. * * @param clientId The client identifier to be matched. * @return A client object that matches the client identifier. */ public Client findClientById(String clientId) { throw new NotImplementedException(); } /** * Finds a client object by redirect URI. * * @param redirectUri The client redirect URI to be matched. * @return A client object that matches the redirect URI. */ public Client findClientByRedirectUri(String redirectUri) { throw new NotImplementedException(); } /** * Stores an authorization ticket object in database. * * @param authorizationTicket The authorization ticket object to be stored. */ public void storeAuthorizationTicket(AuthorizationTicket authorizationTicket) { throw new NotImplementedException(); } /** * Finds an authorization ticket object by authorization code. * * @param code The authorization code to be matched. * @return An authorization ticket object that matches the authorization code. */ public AuthorizationTicket findAuthorizationTicketByCode(String code) { throw new NotImplementedException(); } }
auth-backend/src/main/java/com/ysheng/auth/backend/redis/RedisDatabase.java
/* * Copyright 2016 Yu Sheng. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, without warranties or * conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the * specific language governing permissions and limitations under the License. */ package com.ysheng.auth.backend.redis; import com.ysheng.auth.common.backend.Database; import com.ysheng.auth.model.database.AuthorizationTicket; import com.ysheng.auth.model.database.Client; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * Implementation of the backend database based on Redis. */ public class RedisDatabase implements Database { // The Redis client. private RedisClient redisClient; /** * Constructs a RedisDatabase object. * * @param redisClient The Redis client. */ public RedisDatabase( RedisClient redisClient) { this.redisClient = redisClient; } /** * Stores a client object in database. * * @param client The client object to be stored. */ public void storeClient(Client client) { throw new NotImplementedException(); } /** * Finds a client object by client identifier. * * @param clientId The client identifier to be matched. * @return A client object that matches the client identifier. */ public Client findClientById(String clientId) { throw new NotImplementedException(); } /** * Finds a client object by redirect URI. * * @param redirectUri The client redirect URI to be matched. * @return A client object that matches the redirect URI. */ public Client findClientByRedirectUri(String redirectUri) { throw new NotImplementedException(); } /** * Stores an authorization ticket object in database. * * @param authorizationTicket The authorization ticket object to be stored. */ public void storeAuthorizationTicket(AuthorizationTicket authorizationTicket) { throw new NotImplementedException(); } /** * Finds an authorization ticket object by authorization code. * * @param code The authorization code to be matched. * @return An authorization ticket object that matches the authorization code. */ public AuthorizationTicket findAuthorizationTicketByCode(String code) { throw new NotImplementedException(); } }
backend: implement storeClient function in Redis database
auth-backend/src/main/java/com/ysheng/auth/backend/redis/RedisDatabase.java
backend: implement storeClient function in Redis database
<ide><path>uth-backend/src/main/java/com/ysheng/auth/backend/redis/RedisDatabase.java <ide> <ide> package com.ysheng.auth.backend.redis; <ide> <add>import com.ysheng.auth.backend.redis.entity.ClientEntity; <ide> import com.ysheng.auth.common.backend.Database; <ide> import com.ysheng.auth.model.database.AuthorizationTicket; <ide> import com.ysheng.auth.model.database.Client; <ide> * @param client The client object to be stored. <ide> */ <ide> public void storeClient(Client client) { <del> throw new NotImplementedException(); <add> redisClient.hmset(new ClientEntity(client)); <ide> } <ide> <ide> /**
Java
apache-2.0
2af00a8f6481c8e81d60fe8131c95f6b17b14aa0
0
fbaligand/lognavigator,fbaligand/lognavigator
package org.lognavigator.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.Date; import java.util.Set; import java.util.TreeSet; import org.lognavigator.bean.FileInfo; import org.lognavigator.bean.LogAccessConfig; import org.lognavigator.exception.LogAccessException; import org.lognavigator.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.FileCopyUtils; /** * Abstract class defining common methods for LogAccessService based on shell commands */ public abstract class AbstractShellLogAccessService implements LogAccessService { private static final String DIRECTORY_MARKER = "4000"; private static final String GET_PERL_INFO_COMMAND = "perl -v"; private static final String PERL_INSTALLED_MARKER = "this is perl"; @Autowired protected ConfigService configService; /** * Check and return if host referenced by 'logAccessConfig' is running under Windows OS * @param logAccessConfig log access config to test * @return true if referenced host is running under Windows OS * @throws LogAccessException if a technical error occurs */ protected abstract boolean isWindowsOS(LogAccessConfig logAccessConfig) throws LogAccessException; /** * Check and return if host referenced by 'logAccessConfig' has perl installed * @param logAccessConfig log access config to test * @return true if referenced host has perl installed * @throws LogAccessException if a technical error occurs */ protected boolean isPerlInstalled(LogAccessConfig logAccessConfig) throws LogAccessException { if (logAccessConfig.isPerlInstalled() == null) { try { // Execute command to know if perl is installed InputStream resultStream = executeCommand(logAccessConfig.getId(), GET_PERL_INFO_COMMAND); // Check if perl is installed String result = FileCopyUtils.copyToString(new InputStreamReader(resultStream)); boolean isPerlInstalled = result.toLowerCase().contains(PERL_INSTALLED_MARKER); // Update logAccessConfig to cache the information (and not execute command every time) logAccessConfig.setPerlInstalled(isPerlInstalled); } catch (IOException ioe) { throw new LogAccessException("Error while reading response of command : " + GET_PERL_INFO_COMMAND, ioe); } } return logAccessConfig.isPerlInstalled(); } @Override public Set<FileInfo> listFiles(String logAccessConfigId, String subPath) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // If Perl is not installed : execute a simple 'ls' command if (!isPerlInstalled(logAccessConfig)) { return listFilesUsingNativeSystem(logAccessConfig, subPath); } // Construct perl list command based path and maximum file count String path = (subPath != null) ? subPath : "."; String listCommand = MessageFormat.format(Constants.PERL_LIST_COMMAND, path, configService.getFileListMaxCount()); if (isWindowsOS(logAccessConfig)) { listCommand = listCommand.replace("\"", "\\\""); listCommand = listCommand.replace('\'', '"'); } // Execute perl command InputStream resultStream = executeCommand(logAccessConfigId, listCommand); BufferedReader resultReader = new BufferedReader(new InputStreamReader(resultStream, Charset.forName("UTF-8"))); // Parse the result lines to build FileInfo list Set<FileInfo> fileInfos = new TreeSet<FileInfo>(); String line = null; try { while ((line = resultReader.readLine()) != null) { // Parse the line String[] lineTokens = line.split(" "); boolean isDirectory = lineTokens[0].equals(DIRECTORY_MARKER); long fileSize = Long.parseLong(lineTokens[1]); Date lastModified = new Date(Long.parseLong(lineTokens[2])); String fileName = lineTokens[3]; int tokenIndex = 4; while (tokenIndex < lineTokens.length) { fileName += " " + lineTokens[tokenIndex]; ++tokenIndex; } // Build FileInfo bean FileInfo fileInfo = new FileInfo(); fileInfo.setDirectory(isDirectory); fileInfo.setFileSize(isDirectory ? 0L : fileSize); fileInfo.setLastModified(lastModified); fileInfo.setFileName(fileName); fileInfo.setLogAccessType(logAccessConfig.getType()); fileInfo.setRelativePath((subPath != null) ? subPath + "/" + fileName : fileName); fileInfos.add(fileInfo); } // Return list of files return fileInfos; } catch (NumberFormatException e) { throw new LogAccessException("Error while executing list command : " + line, e); } catch (IOException e) { throw new LogAccessException("I/O Error while listing files in path '" + subPath + "' in log access config : " + logAccessConfig, e); } finally { try { resultReader.close(); } catch (IOException e) {} } } /** * list files of a path, using native underlying system * @see #listFiles(String, String) */ protected abstract Set<FileInfo> listFilesUsingNativeSystem(LogAccessConfig logAccessConfig, String subPath) throws LogAccessException; }
src/main/java/org/lognavigator/service/AbstractShellLogAccessService.java
package org.lognavigator.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.MessageFormat; import java.util.Date; import java.util.Set; import java.util.TreeSet; import org.lognavigator.bean.FileInfo; import org.lognavigator.bean.LogAccessConfig; import org.lognavigator.exception.LogAccessException; import org.lognavigator.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.FileCopyUtils; /** * Abstract class defining common methods for LogAccessService based on shell commands */ public abstract class AbstractShellLogAccessService implements LogAccessService { private static final String DIRECTORY_MARKER = "4000"; private static final String GET_PERL_INFO_COMMAND = "perl -v"; private static final String PERL_INSTALLED_MARKER = "this is perl"; @Autowired protected ConfigService configService; /** * Check and return if host referenced by 'logAccessConfig' is running under Windows OS * @param logAccessConfig log access config to test * @return true if referenced host is running under Windows OS * @throws LogAccessException if a technical error occurs */ protected abstract boolean isWindowsOS(LogAccessConfig logAccessConfig) throws LogAccessException; /** * Check and return if host referenced by 'logAccessConfig' has perl installed * @param logAccessConfig log access config to test * @return true if referenced host has perl installed * @throws LogAccessException if a technical error occurs */ protected boolean isPerlInstalled(LogAccessConfig logAccessConfig) throws LogAccessException { if (logAccessConfig.isPerlInstalled() == null) { try { // Execute command to know if perl is installed InputStream resultStream = executeCommand(logAccessConfig.getId(), GET_PERL_INFO_COMMAND); // Check if perl is installed String result = FileCopyUtils.copyToString(new InputStreamReader(resultStream)); boolean isPerlInstalled = result.toLowerCase().contains(PERL_INSTALLED_MARKER); // Update logAccessConfig to cache the information (and not execute command every time) logAccessConfig.setPerlInstalled(isPerlInstalled); } catch (IOException ioe) { throw new LogAccessException("Error while reading response of command : " + GET_PERL_INFO_COMMAND, ioe); } } return logAccessConfig.isPerlInstalled(); } @Override public Set<FileInfo> listFiles(String logAccessConfigId, String subPath) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // If Perl is not installed : execute a simple 'ls' command if (!isPerlInstalled(logAccessConfig)) { return listFilesUsingNativeSystem(logAccessConfig, subPath); } // Construct perl list command based path and maximum file count String path = (subPath != null) ? subPath : "."; String listCommand = MessageFormat.format(Constants.PERL_LIST_COMMAND, path, configService.getFileListMaxCount()); if (isWindowsOS(logAccessConfig)) { listCommand = listCommand.replace("\"", "\\\""); listCommand = listCommand.replace('\'', '"'); } // Execute perl command InputStream resultStream = executeCommand(logAccessConfigId, listCommand); BufferedReader resultReader = new BufferedReader(new InputStreamReader(resultStream)); // Parse the result lines to build FileInfo list Set<FileInfo> fileInfos = new TreeSet<FileInfo>(); String line; try { while ((line = resultReader.readLine()) != null) { // Parse the line String[] lineTokens = line.split(" "); boolean isDirectory = lineTokens[0].equals(DIRECTORY_MARKER); long fileSize = Long.parseLong(lineTokens[1]); Date lastModified = new Date(Long.parseLong(lineTokens[2])); String fileName = lineTokens[3]; int tokenIndex = 4; while (tokenIndex < lineTokens.length) { fileName += " " + lineTokens[tokenIndex]; ++tokenIndex; } // Build FileInfo bean FileInfo fileInfo = new FileInfo(); fileInfo.setDirectory(isDirectory); fileInfo.setFileSize(isDirectory ? 0L : fileSize); fileInfo.setLastModified(lastModified); fileInfo.setFileName(fileName); fileInfo.setLogAccessType(logAccessConfig.getType()); fileInfo.setRelativePath((subPath != null) ? subPath + "/" + fileName : fileName); fileInfos.add(fileInfo); } // Return list of files return fileInfos; } catch (IOException e) { throw new LogAccessException("I/O Error while listing files in path '" + subPath + "' in log access config : " + logAccessConfig, e); } finally { try { resultReader.close(); } catch (IOException e) {} } } /** * list files of a path, using native underlying system * @see #listFiles(String, String) */ protected abstract Set<FileInfo> listFilesUsingNativeSystem(LogAccessConfig logAccessConfig, String subPath) throws LogAccessException; }
fix accented characters display in files/folders list
src/main/java/org/lognavigator/service/AbstractShellLogAccessService.java
fix accented characters display in files/folders list
<ide><path>rc/main/java/org/lognavigator/service/AbstractShellLogAccessService.java <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.io.InputStreamReader; <add>import java.nio.charset.Charset; <ide> import java.text.MessageFormat; <ide> import java.util.Date; <ide> import java.util.Set; <ide> <ide> // Execute perl command <ide> InputStream resultStream = executeCommand(logAccessConfigId, listCommand); <del> BufferedReader resultReader = new BufferedReader(new InputStreamReader(resultStream)); <add> BufferedReader resultReader = new BufferedReader(new InputStreamReader(resultStream, Charset.forName("UTF-8"))); <ide> <ide> // Parse the result lines to build FileInfo list <ide> Set<FileInfo> fileInfos = new TreeSet<FileInfo>(); <del> String line; <add> String line = null; <ide> try { <ide> while ((line = resultReader.readLine()) != null) { <ide> <ide> // Return list of files <ide> return fileInfos; <ide> } <add> catch (NumberFormatException e) { <add> throw new LogAccessException("Error while executing list command : " + line, e); <add> } <ide> catch (IOException e) { <ide> throw new LogAccessException("I/O Error while listing files in path '" + subPath + "' in log access config : " + logAccessConfig, e); <ide> }
Java
apache-2.0
b56a3d51b6288df8b1eddd77e4703e7f2ff9b5ed
0
stinsonga/libgdx,tommyettinger/libgdx,stinsonga/libgdx,bladecoder/libgdx,NathanSweet/libgdx,NathanSweet/libgdx,stinsonga/libgdx,libgdx/libgdx,bladecoder/libgdx,bladecoder/libgdx,bladecoder/libgdx,libgdx/libgdx,NathanSweet/libgdx,stinsonga/libgdx,tommyettinger/libgdx,stinsonga/libgdx,cypherdare/libgdx,cypherdare/libgdx,libgdx/libgdx,cypherdare/libgdx,Zomby2D/libgdx,NathanSweet/libgdx,Zomby2D/libgdx,bladecoder/libgdx,Zomby2D/libgdx,tommyettinger/libgdx,Zomby2D/libgdx,Zomby2D/libgdx,cypherdare/libgdx,tommyettinger/libgdx,tommyettinger/libgdx,libgdx/libgdx,NathanSweet/libgdx,cypherdare/libgdx,libgdx/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import java.util.Iterator; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef.JointType; import com.badlogic.gdx.physics.box2d.joints.DistanceJoint; import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef; import com.badlogic.gdx.physics.box2d.joints.FrictionJoint; import com.badlogic.gdx.physics.box2d.joints.FrictionJointDef; import com.badlogic.gdx.physics.box2d.joints.GearJoint; import com.badlogic.gdx.physics.box2d.joints.GearJointDef; import com.badlogic.gdx.physics.box2d.joints.MotorJoint; import com.badlogic.gdx.physics.box2d.joints.MotorJointDef; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.physics.box2d.joints.PrismaticJoint; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; import com.badlogic.gdx.physics.box2d.joints.PulleyJoint; import com.badlogic.gdx.physics.box2d.joints.PulleyJointDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJoint; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; import com.badlogic.gdx.physics.box2d.joints.RopeJoint; import com.badlogic.gdx.physics.box2d.joints.RopeJointDef; import com.badlogic.gdx.physics.box2d.joints.WeldJoint; import com.badlogic.gdx.physics.box2d.joints.WeldJointDef; import com.badlogic.gdx.physics.box2d.joints.WheelJoint; import com.badlogic.gdx.physics.box2d.joints.WheelJointDef; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.LongMap; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.SharedLibraryLoader; /** The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient * memory management facilities. * @author mzechner */ public final class World implements Disposable { // @off /*JNI #include <Box2D/Box2D.h> static jclass worldClass = 0; static jmethodID shouldCollideID = 0; static jmethodID beginContactID = 0; static jmethodID endContactID = 0; static jmethodID preSolveID = 0; static jmethodID postSolveID = 0; static jmethodID reportFixtureID = 0; static jmethodID reportRayFixtureID = 0; class CustomRayCastCallback: public b2RayCastCallback { private: JNIEnv* env; jobject obj; public: CustomRayCastCallback( JNIEnv *env, jobject obj ) { this->env = env; this->obj = obj; } virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) { return env->CallFloatMethod(obj, reportRayFixtureID, (jlong)fixture, (jfloat)point.x, (jfloat)point.y, (jfloat)normal.x, (jfloat)normal.y, (jfloat)fraction ); } }; class CustomContactFilter: public b2ContactFilter { private: JNIEnv* env; jobject obj; public: CustomContactFilter( JNIEnv* env, jobject obj ) { this->env = env; this->obj = obj; } virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) { if( shouldCollideID != 0 ) return env->CallBooleanMethod( obj, shouldCollideID, (jlong)fixtureA, (jlong)fixtureB ); else return true; } }; class CustomContactListener: public b2ContactListener { private: JNIEnv* env; jobject obj; public: CustomContactListener( JNIEnv* env, jobject obj ) { this->env = env; this->obj = obj; } /// Called when two fixtures begin to touch. virtual void BeginContact(b2Contact* contact) { if( beginContactID != 0 ) env->CallVoidMethod(obj, beginContactID, (jlong)contact ); } /// Called when two fixtures cease to touch. virtual void EndContact(b2Contact* contact) { if( endContactID != 0 ) env->CallVoidMethod(obj, endContactID, (jlong)contact); } /// This is called after a contact is updated. virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { if( preSolveID != 0 ) env->CallVoidMethod(obj, preSolveID, (jlong)contact, (jlong)oldManifold); } /// This lets you inspect a contact after the solver is finished. virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { if( postSolveID != 0 ) env->CallVoidMethod(obj, postSolveID, (jlong)contact, (jlong)impulse); } }; class CustomQueryCallback: public b2QueryCallback { private: JNIEnv* env; jobject obj; public: CustomQueryCallback( JNIEnv* env, jobject obj ) { this->env = env; this->obj = obj; } virtual bool ReportFixture( b2Fixture* fixture ) { return env->CallBooleanMethod(obj, reportFixtureID, (jlong)fixture ); } }; inline b2BodyType getBodyType( int type ) { switch( type ) { case 0: return b2_staticBody; case 1: return b2_kinematicBody; case 2: return b2_dynamicBody; default: return b2_staticBody; } } b2ContactFilter defaultFilter; */ static { new SharedLibraryLoader().load("gdx-box2d"); } /** pool for bodies **/ protected final Pool<Body> freeBodies = new Pool<Body>(100, 200) { @Override protected Body newObject () { return new Body(World.this, 0); } }; /** pool for fixtures **/ protected final Pool<Fixture> freeFixtures = new Pool<Fixture>(100, 200) { @Override protected Fixture newObject () { return new Fixture(null, 0); } }; /** the address of the world instance **/ protected final long addr; /** all known bodies **/ protected final LongMap<Body> bodies = new LongMap<Body>(100); /** all known fixtures **/ protected final LongMap<Fixture> fixtures = new LongMap<Fixture>(100); /** all known joints **/ protected final LongMap<Joint> joints = new LongMap<Joint>(100); /** Contact filter **/ protected ContactFilter contactFilter = null; /** Contact listener **/ protected ContactListener contactListener = null; /** Construct a world object. * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ public World (Vector2 gravity, boolean doSleep) { addr = newWorld(gravity.x, gravity.y, doSleep); contacts.ensureCapacity(contactAddrs.length); freeContacts.ensureCapacity(contactAddrs.length); for (int i = 0; i < contactAddrs.length; i++) freeContacts.add(new Contact(this, 0)); } private native long newWorld (float gravityX, float gravityY, boolean doSleep); /* // we leak one global ref. if(!worldClass) { worldClass = (jclass)env->NewGlobalRef(env->GetObjectClass(object)); beginContactID = env->GetMethodID(worldClass, "beginContact", "(J)V" ); endContactID = env->GetMethodID( worldClass, "endContact", "(J)V" ); preSolveID = env->GetMethodID( worldClass, "preSolve", "(JJ)V" ); postSolveID = env->GetMethodID( worldClass, "postSolve", "(JJ)V" ); reportFixtureID = env->GetMethodID(worldClass, "reportFixture", "(J)Z" ); reportRayFixtureID = env->GetMethodID(worldClass, "reportRayFixture", "(JFFFFF)F" ); shouldCollideID = env->GetMethodID( worldClass, "contactFilter", "(JJ)Z"); } b2World* world = new b2World( b2Vec2( gravityX, gravityY )); world->SetAllowSleeping( doSleep ); return (jlong)world; */ /** Register a destruction listener. The listener is owned by you and must remain in scope. */ public void setDestructionListener (DestructionListener listener) { } /** Register a contact filter to provide specific control over collision. Otherwise the default filter is used * (b2_defaultFilter). The listener is owned by you and must remain in scope. */ public void setContactFilter (ContactFilter filter) { this.contactFilter = filter; setUseDefaultContactFilter(filter == null); } /** tells the native code not to call the Java world class if use is false **/ private native void setUseDefaultContactFilter(boolean use); /* // FIXME */ /** Register a contact event listener. The listener is owned by you and must remain in scope. */ public void setContactListener (ContactListener listener) { this.contactListener = listener; } /** Create a rigid body given a definition. No reference to the definition is retained. * Bodies created by this method are pooled internally by the World object. * They will be freed upon calling {@link World#destroyBody(Body)} * @see Pool * @warning This function is locked during callbacks. */ public Body createBody (BodyDef def) { long bodyAddr = jniCreateBody(addr, def.type.getValue(), def.position.x, def.position.y, def.angle, def.linearVelocity.x, def.linearVelocity.y, def.angularVelocity, def.linearDamping, def.angularDamping, def.allowSleep, def.awake, def.fixedRotation, def.bullet, def.active, def.gravityScale); Body body = freeBodies.obtain(); body.reset(bodyAddr); this.bodies.put(body.addr, body); return body; } private native long jniCreateBody (long addr, int type, float positionX, float positionY, float angle, float linearVelocityX, float linearVelocityY, float angularVelocity, float linearDamping, float angularDamping, boolean allowSleep, boolean awake, boolean fixedRotation, boolean bullet, boolean active, float inertiaScale); /* b2BodyDef bodyDef; bodyDef.type = getBodyType(type); bodyDef.position.Set( positionX, positionY ); bodyDef.angle = angle; bodyDef.linearVelocity.Set( linearVelocityX, linearVelocityY ); bodyDef.angularVelocity = angularVelocity; bodyDef.linearDamping = linearDamping; bodyDef.angularDamping = angularDamping; bodyDef.allowSleep = allowSleep; bodyDef.awake = awake; bodyDef.fixedRotation = fixedRotation; bodyDef.bullet = bullet; bodyDef.active = active; bodyDef.gravityScale = inertiaScale; b2World* world = (b2World*)addr; b2Body* body = world->CreateBody( &bodyDef ); return (jlong)body; */ /** Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during * callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ public void destroyBody (Body body) { Array<JointEdge> jointList = body.getJointList(); while (jointList.size > 0) destroyJoint(body.getJointList().get(0).joint); jniDestroyBody(addr, body.addr); body.setUserData(null); this.bodies.remove(body.addr); Array<Fixture> fixtureList = body.getFixtureList(); while(fixtureList.size > 0) { Fixture fixtureToDelete = fixtureList.removeIndex(0); this.fixtures.remove(fixtureToDelete.addr).setUserData(null); freeFixtures.free(fixtureToDelete); } freeBodies.free(body); } private native void jniDestroyBody (long addr, long bodyAddr); /* b2World* world = (b2World*)addr; b2Body* body = (b2Body*)bodyAddr; CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env,object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); world->DestroyBody(body); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Internal method for fixture destruction with notifying custom * contact listener * @param body * @param fixture */ void destroyFixture(Body body, Fixture fixture) { jniDestroyFixture(addr, body.addr, fixture.addr); } private native void jniDestroyFixture(long addr, long bodyAddr, long fixtureAddr); /* b2World* world = (b2World*)(addr); b2Body* body = (b2Body*)(bodyAddr); b2Fixture* fixture = (b2Fixture*)(fixtureAddr); CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env, object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); body->DestroyFixture(fixture); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Internal method for body deactivation with notifying custom * contact listener * @param body */ void deactivateBody(Body body) { jniDeactivateBody(addr, body.addr); } private native void jniDeactivateBody(long addr, long bodyAddr); /* b2World* world = (b2World*)(addr); b2Body* body = (b2Body*)(bodyAddr); CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env, object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); body->SetActive(false); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies * to cease colliding. * @warning This function is locked during callbacks. */ public Joint createJoint (JointDef def) { long jointAddr = createProperJoint(def); Joint joint = null; if (def.type == JointType.DistanceJoint) joint = new DistanceJoint(this, jointAddr); if (def.type == JointType.FrictionJoint) joint = new FrictionJoint(this, jointAddr); if (def.type == JointType.GearJoint) joint = new GearJoint(this, jointAddr, ((GearJointDef) def).joint1, ((GearJointDef) def).joint2); if (def.type == JointType.MotorJoint) joint = new MotorJoint(this, jointAddr); if (def.type == JointType.MouseJoint) joint = new MouseJoint(this, jointAddr); if (def.type == JointType.PrismaticJoint) joint = new PrismaticJoint(this, jointAddr); if (def.type == JointType.PulleyJoint) joint = new PulleyJoint(this, jointAddr); if (def.type == JointType.RevoluteJoint) joint = new RevoluteJoint(this, jointAddr); if (def.type == JointType.RopeJoint) joint = new RopeJoint(this, jointAddr); if (def.type == JointType.WeldJoint) joint = new WeldJoint(this, jointAddr); if (def.type == JointType.WheelJoint) joint = new WheelJoint(this, jointAddr); if (joint == null) throw new GdxRuntimeException("Unknown joint type: " + def.type); joints.put(joint.addr, joint); JointEdge jointEdgeA = new JointEdge(def.bodyB, joint); JointEdge jointEdgeB = new JointEdge(def.bodyA, joint); joint.jointEdgeA = jointEdgeA; joint.jointEdgeB = jointEdgeB; def.bodyA.joints.add(jointEdgeA); def.bodyB.joints.add(jointEdgeB); return joint; } private long createProperJoint (JointDef def) { if (def.type == JointType.DistanceJoint) { DistanceJointDef d = (DistanceJointDef)def; return jniCreateDistanceJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.length, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.FrictionJoint) { FrictionJointDef d = (FrictionJointDef)def; return jniCreateFrictionJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.maxForce, d.maxTorque); } if (def.type == JointType.GearJoint) { GearJointDef d = (GearJointDef)def; return jniCreateGearJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.joint1.addr, d.joint2.addr, d.ratio); } if (def.type == JointType.MotorJoint) { MotorJointDef d = (MotorJointDef)def; return jniCreateMotorJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.linearOffset.x, d.linearOffset.y, d.angularOffset, d.maxForce, d.maxTorque, d.correctionFactor); } if (def.type == JointType.MouseJoint) { MouseJointDef d = (MouseJointDef)def; return jniCreateMouseJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.target.x, d.target.y, d.maxForce, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.PrismaticJoint) { PrismaticJointDef d = (PrismaticJointDef)def; return jniCreatePrismaticJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.localAxisA.x, d.localAxisA.y, d.referenceAngle, d.enableLimit, d.lowerTranslation, d.upperTranslation, d.enableMotor, d.maxMotorForce, d.motorSpeed); } if (def.type == JointType.PulleyJoint) { PulleyJointDef d = (PulleyJointDef)def; return jniCreatePulleyJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.groundAnchorA.x, d.groundAnchorA.y, d.groundAnchorB.x, d.groundAnchorB.y, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.lengthA, d.lengthB, d.ratio); } if (def.type == JointType.RevoluteJoint) { RevoluteJointDef d = (RevoluteJointDef)def; return jniCreateRevoluteJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle, d.enableLimit, d.lowerAngle, d.upperAngle, d.enableMotor, d.motorSpeed, d.maxMotorTorque); } if (def.type == JointType.RopeJoint) { RopeJointDef d = (RopeJointDef)def; return jniCreateRopeJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.maxLength); } if (def.type == JointType.WeldJoint) { WeldJointDef d = (WeldJointDef)def; return jniCreateWeldJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.WheelJoint) { WheelJointDef d = (WheelJointDef)def; return jniCreateWheelJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.localAxisA.x, d.localAxisA.y, d.enableMotor, d.maxMotorTorque, d.motorSpeed, d.frequencyHz, d.dampingRatio); } return 0; } private native long jniCreateWheelJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, boolean enableMotor, float maxMotorTorque, float motorSpeed, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2WheelJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.localAxisA = b2Vec2(localAxisAX, localAxisAY); def.enableMotor = enableMotor; def.maxMotorTorque = maxMotorTorque; def.motorSpeed = motorSpeed; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateRopeJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float maxLength); /* b2World* world = (b2World*)addr; b2RopeJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.maxLength = maxLength; return (jlong)world->CreateJoint(&def); */ private native long jniCreateDistanceJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float length, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2DistanceJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.length = length; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateFrictionJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float maxForce, float maxTorque); /* b2World* world = (b2World*)addr; b2FrictionJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.maxForce = maxForce; def.maxTorque = maxTorque; return (jlong)world->CreateJoint(&def); */ private native long jniCreateGearJoint (long addr, long bodyA, long bodyB, boolean collideConnected, long joint1, long joint2, float ratio); /* b2World* world = (b2World*)addr; b2GearJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.joint1 = (b2Joint*)joint1; def.joint2 = (b2Joint*)joint2; def.ratio = ratio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateMotorJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float linearOffsetX, float linearOffsetY, float angularOffset, float maxForce, float maxTorque, float correctionFactor); /* b2World* world = (b2World*)addr; b2MotorJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.linearOffset = b2Vec2( linearOffsetX, linearOffsetY ); def.angularOffset = angularOffset; def.maxForce = maxForce; def.maxTorque = maxTorque; def.correctionFactor = correctionFactor; return (jlong)world->CreateJoint(&def); */ private native long jniCreateMouseJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float targetX, float targetY, float maxForce, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2MouseJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.target = b2Vec2( targetX, targetY ); def.maxForce = maxForce; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ private native long jniCreatePrismaticJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, float referenceAngle, boolean enableLimit, float lowerTranslation, float upperTranslation, boolean enableMotor, float maxMotorForce, float motorSpeed); /* b2World* world = (b2World*)addr; b2PrismaticJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.localAxisA = b2Vec2( localAxisAX, localAxisAY ); def.referenceAngle = referenceAngle; def.enableLimit = enableLimit; def.lowerTranslation = lowerTranslation; def.upperTranslation = upperTranslation; def.enableMotor = enableMotor; def.maxMotorForce = maxMotorForce; def.motorSpeed = motorSpeed; return (jlong)world->CreateJoint(&def); */ private native long jniCreatePulleyJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float groundAnchorAX, float groundAnchorAY, float groundAnchorBX, float groundAnchorBY, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float lengthA, float lengthB, float ratio); /* b2World* world = (b2World*)addr; b2PulleyJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.groundAnchorA = b2Vec2( groundAnchorAX, groundAnchorAY ); def.groundAnchorB = b2Vec2( groundAnchorBX, groundAnchorBY ); def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.lengthA = lengthA; def.lengthB = lengthB; def.ratio = ratio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateRevoluteJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle, boolean enableLimit, float lowerAngle, float upperAngle, boolean enableMotor, float motorSpeed, float maxMotorTorque); /* b2World* world = (b2World*)addr; b2RevoluteJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.referenceAngle = referenceAngle; def.enableLimit = enableLimit; def.lowerAngle = lowerAngle; def.upperAngle = upperAngle; def.enableMotor = enableMotor; def.motorSpeed = motorSpeed; def.maxMotorTorque = maxMotorTorque; return (jlong)world->CreateJoint(&def); */ private native long jniCreateWeldJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2WeldJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.referenceAngle = referenceAngle; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ /** Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ public void destroyJoint (Joint joint) { joint.setUserData(null); joints.remove(joint.addr); joint.jointEdgeA.other.joints.removeValue(joint.jointEdgeB, true); joint.jointEdgeB.other.joints.removeValue(joint.jointEdgeA, true); jniDestroyJoint(addr, joint.addr); } private native void jniDestroyJoint (long addr, long jointAddr); /* b2World* world = (b2World*)addr; b2Joint* joint = (b2Joint*)jointAddr; CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env,object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); world->DestroyJoint( joint ); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Take a time step. This performs collision detection, integration, and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public void step (float timeStep, int velocityIterations, int positionIterations) { jniStep(addr, timeStep, velocityIterations, positionIterations); } private native void jniStep (long addr, float timeStep, int velocityIterations, int positionIterations); /* b2World* world = (b2World*)addr; CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env,object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); world->Step( timeStep, velocityIterations, positionIterations ); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The * default behavior is modified by calling SetAutoClearForces. The purpose of this function is to support sub-stepping. * Sub-stepping is often used to maintain a fixed sized time step under a variable frame-rate. When you perform sub-stepping * you will disable auto clearing of forces and instead call ClearForces after all sub-steps are complete in one pass of your * game loop. {@link #setAutoClearForces(boolean)} */ public void clearForces () { jniClearForces(addr); } private native void jniClearForces (long addr); /* b2World* world = (b2World*)addr; world->ClearForces(); */ /** Enable/disable warm starting. For testing. */ public void setWarmStarting (boolean flag) { jniSetWarmStarting(addr, flag); } private native void jniSetWarmStarting (long addr, boolean flag); /* b2World* world = (b2World*)addr; world->SetWarmStarting(flag); */ /** Enable/disable continuous physics. For testing. */ public void setContinuousPhysics (boolean flag) { jniSetContiousPhysics(addr, flag); } private native void jniSetContiousPhysics (long addr, boolean flag); /* b2World* world = (b2World*)addr; world->SetContinuousPhysics(flag); */ /** Get the number of broad-phase proxies. */ public int getProxyCount () { return jniGetProxyCount(addr); } private native int jniGetProxyCount (long addr); /* b2World* world = (b2World*)addr; return world->GetProxyCount(); */ /** Get the number of bodies. */ public int getBodyCount () { return jniGetBodyCount(addr); } private native int jniGetBodyCount (long addr); /* b2World* world = (b2World*)addr; return world->GetBodyCount(); */ /** Get the number of fixtures. */ public int getFixtureCount () { return fixtures.size; } /** Get the number of joints. */ public int getJointCount () { return jniGetJointcount(addr); } private native int jniGetJointcount (long addr); /* b2World* world = (b2World*)addr; return world->GetJointCount(); */ /** Get the number of contacts (each may have 0 or more contact points). */ public int getContactCount () { return jniGetContactCount(addr); } private native int jniGetContactCount (long addr); /* b2World* world = (b2World*)addr; return world->GetContactCount(); */ /** Change the global gravity vector. */ public void setGravity (Vector2 gravity) { jniSetGravity(addr, gravity.x, gravity.y); } private native void jniSetGravity (long addr, float gravityX, float gravityY); /* b2World* world = (b2World*)addr; world->SetGravity( b2Vec2( gravityX, gravityY ) ); */ /** Get the global gravity vector. */ final float[] tmpGravity = new float[2]; final Vector2 gravity = new Vector2(); public Vector2 getGravity () { jniGetGravity(addr, tmpGravity); gravity.x = tmpGravity[0]; gravity.y = tmpGravity[1]; return gravity; } private native void jniGetGravity (long addr, float[] gravity); /* b2World* world = (b2World*)addr; b2Vec2 g = world->GetGravity(); gravity[0] = g.x; gravity[1] = g.y; */ /** Is the world locked (in the middle of a time step). */ public boolean isLocked () { return jniIsLocked(addr); } private native boolean jniIsLocked (long addr); /* b2World* world = (b2World*)addr; return world->IsLocked(); */ /** Set flag to control automatic clearing of forces after each time step. */ public void setAutoClearForces (boolean flag) { jniSetAutoClearForces(addr, flag); } private native void jniSetAutoClearForces (long addr, boolean flag); /* b2World* world = (b2World*)addr; world->SetAutoClearForces(flag); */ /** Get the flag that controls automatic clearing of forces after each time step. */ public boolean getAutoClearForces () { return jniGetAutoClearForces(addr); } private native boolean jniGetAutoClearForces (long addr); /* b2World* world = (b2World*)addr; return world->GetAutoClearForces(); */ /** Query the world for all fixtures that potentially overlap the provided AABB. * @param callback a user implemented callback class. * @param lowerX the x coordinate of the lower left corner * @param lowerY the y coordinate of the lower left corner * @param upperX the x coordinate of the upper right corner * @param upperY the y coordinate of the upper right corner */ public void QueryAABB (QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY) { queryCallback = callback; jniQueryAABB(addr, lowerX, lowerY, upperX, upperY); } private QueryCallback queryCallback = null;; private native void jniQueryAABB (long addr, float lowX, float lowY, float upX, float upY); /* b2World* world = (b2World*)addr; b2AABB aabb; aabb.lowerBound = b2Vec2( lowX, lowY ); aabb.upperBound = b2Vec2( upX, upY ); CustomQueryCallback callback( env, object ); world->QueryAABB( &callback, aabb ); */ // // /// Ray-cast the world for all fixtures in the path of the ray. Your callback // /// controls whether you get the closest point, any point, or n-points. // /// The ray-cast ignores shapes that contain the starting point. // /// @param callback a user implemented callback class. // /// @param point1 the ray starting point // /// @param point2 the ray ending point // void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; // // /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get // /// the next contact in the world list. A NULL contact indicates the end of the list. // /// @return the head of the world contact list. // /// @warning contacts are // b2Contact* GetContactList(); private long[] contactAddrs = new long[200]; private final Array<Contact> contacts = new Array<Contact>(); private final Array<Contact> freeContacts = new Array<Contact>(); /** Returns the list of {@link Contact} instances produced by the last call to {@link #step(float, int, int)}. Note that the * returned list will have O(1) access times when using indexing. contacts are created and destroyed in the middle of a time * step. Use {@link ContactListener} to avoid missing contacts * @return the contact list */ public Array<Contact> getContactList () { int numContacts = getContactCount(); if (numContacts > contactAddrs.length) { int newSize = 2 * numContacts; contactAddrs = new long[newSize]; contacts.ensureCapacity(newSize); freeContacts.ensureCapacity(newSize); } if (numContacts > freeContacts.size) { int freeConts = freeContacts.size; for (int i = 0; i < numContacts - freeConts; i++) freeContacts.add(new Contact(this, 0)); } jniGetContactList(addr, contactAddrs); contacts.clear(); for (int i = 0; i < numContacts; i++) { Contact contact = freeContacts.get(i); contact.addr = contactAddrs[i]; contacts.add(contact); } return contacts; } /** @param bodies an Array in which to place all bodies currently in the simulation */ public void getBodies (Array<Body> bodies) { bodies.clear(); bodies.ensureCapacity(this.bodies.size); for (Iterator<Body> iter = this.bodies.values(); iter.hasNext();) { bodies.add(iter.next()); } } /** @param fixtures an Array in which to place all fixtures currently in the simulation */ public void getFixtures (Array<Fixture> fixtures) { fixtures.clear(); fixtures.ensureCapacity(this.fixtures.size); for (Iterator<Fixture> iter = this.fixtures.values(); iter.hasNext();) { fixtures.add(iter.next()); } } /** @param joints an Array in which to place all joints currently in the simulation */ public void getJoints (Array<Joint> joints) { joints.clear(); joints.ensureCapacity(this.joints.size); for (Iterator<Joint> iter = this.joints.values(); iter.hasNext();) { joints.add(iter.next()); } } private native void jniGetContactList (long addr, long[] contacts); /* b2World* world = (b2World*)addr; b2Contact* contact = world->GetContactList(); int i = 0; while( contact != 0 ) { contacts[i++] = (long long)contact; contact = contact->GetNext(); } */ public void dispose () { jniDispose(addr); } private native void jniDispose (long addr); /* b2World* world = (b2World*)(addr); delete world; */ /** Internal method called from JNI in case a contact happens * @param fixtureA * @param fixtureB * @return whether the things collided */ private boolean contactFilter (long fixtureA, long fixtureB) { if (contactFilter != null) return contactFilter.shouldCollide(fixtures.get(fixtureA), fixtures.get(fixtureB)); else { Filter filterA = fixtures.get(fixtureA).getFilterData(); Filter filterB = fixtures.get(fixtureB).getFilterData(); if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) { return filterA.groupIndex > 0; } boolean collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; return collide; } } private final Contact contact = new Contact(this, 0); private final Manifold manifold = new Manifold(0); private final ContactImpulse impulse = new ContactImpulse(this, 0); private void beginContact (long contactAddr) { if (contactListener != null) { contact.addr = contactAddr; contactListener.beginContact(contact); } } private void endContact (long contactAddr) { if (contactListener != null) { contact.addr = contactAddr; contactListener.endContact(contact); } } private void preSolve (long contactAddr, long manifoldAddr) { if (contactListener != null) { contact.addr = contactAddr; manifold.addr = manifoldAddr; contactListener.preSolve(contact, manifold); } } private void postSolve (long contactAddr, long impulseAddr) { if (contactListener != null) { contact.addr = contactAddr; impulse.addr = impulseAddr; contactListener.postSolve(contact, impulse); } } private boolean reportFixture (long addr) { if (queryCallback != null) return queryCallback.reportFixture(fixtures.get(addr)); else return false; } /** Sets the box2d velocity threshold globally, for all World instances. * @param threshold the threshold, default 1.0f */ public static native void setVelocityThreshold (float threshold); /* b2_velocityThreshold = threshold; */ /** @return the global box2d velocity threshold. */ public static native float getVelocityThreshold (); /* return b2_velocityThreshold; */ /** Ray-cast the world for all fixtures in the path of the ray. The ray-cast ignores shapes that contain the starting point. * @param callback a user implemented callback class. * @param point1 the ray starting point * @param point2 the ray ending point */ public void rayCast (RayCastCallback callback, Vector2 point1, Vector2 point2) { rayCast(callback, point1.x, point1.y, point2.x, point2.y); } /** Ray-cast the world for all fixtures in the path of the ray. The ray-cast ignores shapes that contain the starting point. * @param callback a user implemented callback class. * @param point1X the ray starting point X * @param point1Y the ray starting point Y * @param point2X the ray ending point X * @param point2Y the ray ending point Y */ public void rayCast (RayCastCallback callback, float point1X, float point1Y, float point2X, float point2Y) { rayCastCallback = callback; jniRayCast(addr, point1X, point1Y, point2X, point2Y); } private RayCastCallback rayCastCallback = null; private native void jniRayCast (long addr, float aX, float aY, float bX, float bY); /* b2World *world = (b2World*)addr; CustomRayCastCallback callback( env, object ); world->RayCast( &callback, b2Vec2(aX,aY), b2Vec2(bX,bY) ); */ private Vector2 rayPoint = new Vector2(); private Vector2 rayNormal = new Vector2(); private float reportRayFixture (long addr, float pX, float pY, float nX, float nY, float fraction) { if (rayCastCallback != null) { rayPoint.x = pX; rayPoint.y = pY; rayNormal.x = nX; rayNormal.y = nY; return rayCastCallback.reportRayFixture(fixtures.get(addr), rayPoint, rayNormal, fraction); } else { return 0.0f; } } }
extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/World.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.physics.box2d; import java.util.Iterator; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.JointDef.JointType; import com.badlogic.gdx.physics.box2d.joints.DistanceJoint; import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef; import com.badlogic.gdx.physics.box2d.joints.FrictionJoint; import com.badlogic.gdx.physics.box2d.joints.FrictionJointDef; import com.badlogic.gdx.physics.box2d.joints.GearJoint; import com.badlogic.gdx.physics.box2d.joints.GearJointDef; import com.badlogic.gdx.physics.box2d.joints.MotorJoint; import com.badlogic.gdx.physics.box2d.joints.MotorJointDef; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.physics.box2d.joints.PrismaticJoint; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; import com.badlogic.gdx.physics.box2d.joints.PulleyJoint; import com.badlogic.gdx.physics.box2d.joints.PulleyJointDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJoint; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; import com.badlogic.gdx.physics.box2d.joints.RopeJoint; import com.badlogic.gdx.physics.box2d.joints.RopeJointDef; import com.badlogic.gdx.physics.box2d.joints.WeldJoint; import com.badlogic.gdx.physics.box2d.joints.WeldJointDef; import com.badlogic.gdx.physics.box2d.joints.WheelJoint; import com.badlogic.gdx.physics.box2d.joints.WheelJointDef; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.LongMap; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.SharedLibraryLoader; /** The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient * memory management facilities. * @author mzechner */ public final class World implements Disposable { // @off /*JNI #include <Box2D/Box2D.h> static jclass worldClass = 0; static jmethodID shouldCollideID = 0; static jmethodID beginContactID = 0; static jmethodID endContactID = 0; static jmethodID preSolveID = 0; static jmethodID postSolveID = 0; static jmethodID reportFixtureID = 0; static jmethodID reportRayFixtureID = 0; class CustomRayCastCallback: public b2RayCastCallback { private: JNIEnv* env; jobject obj; public: CustomRayCastCallback( JNIEnv *env, jobject obj ) { this->env = env; this->obj = obj; } virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) { return env->CallFloatMethod(obj, reportRayFixtureID, (jlong)fixture, (jfloat)point.x, (jfloat)point.y, (jfloat)normal.x, (jfloat)normal.y, (jfloat)fraction ); } }; class CustomContactFilter: public b2ContactFilter { private: JNIEnv* env; jobject obj; public: CustomContactFilter( JNIEnv* env, jobject obj ) { this->env = env; this->obj = obj; } virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) { if( shouldCollideID != 0 ) return env->CallBooleanMethod( obj, shouldCollideID, (jlong)fixtureA, (jlong)fixtureB ); else return true; } }; class CustomContactListener: public b2ContactListener { private: JNIEnv* env; jobject obj; public: CustomContactListener( JNIEnv* env, jobject obj ) { this->env = env; this->obj = obj; } /// Called when two fixtures begin to touch. virtual void BeginContact(b2Contact* contact) { if( beginContactID != 0 ) env->CallVoidMethod(obj, beginContactID, (jlong)contact ); } /// Called when two fixtures cease to touch. virtual void EndContact(b2Contact* contact) { if( endContactID != 0 ) env->CallVoidMethod(obj, endContactID, (jlong)contact); } /// This is called after a contact is updated. virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { if( preSolveID != 0 ) env->CallVoidMethod(obj, preSolveID, (jlong)contact, (jlong)oldManifold); } /// This lets you inspect a contact after the solver is finished. virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { if( postSolveID != 0 ) env->CallVoidMethod(obj, postSolveID, (jlong)contact, (jlong)impulse); } }; class CustomQueryCallback: public b2QueryCallback { private: JNIEnv* env; jobject obj; public: CustomQueryCallback( JNIEnv* env, jobject obj ) { this->env = env; this->obj = obj; } virtual bool ReportFixture( b2Fixture* fixture ) { return env->CallBooleanMethod(obj, reportFixtureID, (jlong)fixture ); } }; inline b2BodyType getBodyType( int type ) { switch( type ) { case 0: return b2_staticBody; case 1: return b2_kinematicBody; case 2: return b2_dynamicBody; default: return b2_staticBody; } } b2ContactFilter defaultFilter; */ static { new SharedLibraryLoader().load("gdx-box2d"); } /** pool for bodies **/ protected final Pool<Body> freeBodies = new Pool<Body>(100, 200) { @Override protected Body newObject () { return new Body(World.this, 0); } }; /** pool for fixtures **/ protected final Pool<Fixture> freeFixtures = new Pool<Fixture>(100, 200) { @Override protected Fixture newObject () { return new Fixture(null, 0); } }; /** the address of the world instance **/ protected final long addr; /** all known bodies **/ protected final LongMap<Body> bodies = new LongMap<Body>(100); /** all known fixtures **/ protected final LongMap<Fixture> fixtures = new LongMap<Fixture>(100); /** all known joints **/ protected final LongMap<Joint> joints = new LongMap<Joint>(100); /** Contact filter **/ protected ContactFilter contactFilter = null; /** Contact listener **/ protected ContactListener contactListener = null; /** Construct a world object. * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ public World (Vector2 gravity, boolean doSleep) { addr = newWorld(gravity.x, gravity.y, doSleep); contacts.ensureCapacity(contactAddrs.length); freeContacts.ensureCapacity(contactAddrs.length); for (int i = 0; i < contactAddrs.length; i++) freeContacts.add(new Contact(this, 0)); } private native long newWorld (float gravityX, float gravityY, boolean doSleep); /* // we leak one global ref. if(!worldClass) { worldClass = (jclass)env->NewGlobalRef(env->GetObjectClass(object)); beginContactID = env->GetMethodID(worldClass, "beginContact", "(J)V" ); endContactID = env->GetMethodID( worldClass, "endContact", "(J)V" ); preSolveID = env->GetMethodID( worldClass, "preSolve", "(JJ)V" ); postSolveID = env->GetMethodID( worldClass, "postSolve", "(JJ)V" ); reportFixtureID = env->GetMethodID(worldClass, "reportFixture", "(J)Z" ); reportRayFixtureID = env->GetMethodID(worldClass, "reportRayFixture", "(JFFFFF)F" ); shouldCollideID = env->GetMethodID( worldClass, "contactFilter", "(JJ)Z"); } b2World* world = new b2World( b2Vec2( gravityX, gravityY )); world->SetAllowSleeping( doSleep ); return (jlong)world; */ /** Register a destruction listener. The listener is owned by you and must remain in scope. */ public void setDestructionListener (DestructionListener listener) { } /** Register a contact filter to provide specific control over collision. Otherwise the default filter is used * (b2_defaultFilter). The listener is owned by you and must remain in scope. */ public void setContactFilter (ContactFilter filter) { this.contactFilter = filter; setUseDefaultContactFilter(filter == null); } /** tells the native code not to call the Java world class if use is false **/ private native void setUseDefaultContactFilter(boolean use); /* // FIXME */ /** Register a contact event listener. The listener is owned by you and must remain in scope. */ public void setContactListener (ContactListener listener) { this.contactListener = listener; } /** Create a rigid body given a definition. No reference to the definition is retained. * Bodies created by this method are pooled internally by the World object. * They will be freed upon calling {@link World#destroyBody(Body)} * @see Pool * @warning This function is locked during callbacks. */ public Body createBody (BodyDef def) { long bodyAddr = jniCreateBody(addr, def.type.getValue(), def.position.x, def.position.y, def.angle, def.linearVelocity.x, def.linearVelocity.y, def.angularVelocity, def.linearDamping, def.angularDamping, def.allowSleep, def.awake, def.fixedRotation, def.bullet, def.active, def.gravityScale); Body body = freeBodies.obtain(); body.reset(bodyAddr); this.bodies.put(body.addr, body); return body; } private native long jniCreateBody (long addr, int type, float positionX, float positionY, float angle, float linearVelocityX, float linearVelocityY, float angularVelocity, float linearDamping, float angularDamping, boolean allowSleep, boolean awake, boolean fixedRotation, boolean bullet, boolean active, float inertiaScale); /* b2BodyDef bodyDef; bodyDef.type = getBodyType(type); bodyDef.position.Set( positionX, positionY ); bodyDef.angle = angle; bodyDef.linearVelocity.Set( linearVelocityX, linearVelocityY ); bodyDef.angularVelocity = angularVelocity; bodyDef.linearDamping = linearDamping; bodyDef.angularDamping = angularDamping; bodyDef.allowSleep = allowSleep; bodyDef.awake = awake; bodyDef.fixedRotation = fixedRotation; bodyDef.bullet = bullet; bodyDef.active = active; bodyDef.gravityScale = inertiaScale; b2World* world = (b2World*)addr; b2Body* body = world->CreateBody( &bodyDef ); return (jlong)body; */ /** Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during * callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ public void destroyBody (Body body) { Array<JointEdge> jointList = body.getJointList(); while (jointList.size > 0) destroyJoint(body.getJointList().get(0).joint); jniDestroyBody(addr, body.addr); body.setUserData(null); this.bodies.remove(body.addr); Array<Fixture> fixtureList = body.getFixtureList(); while(fixtureList.size > 0) { Fixture fixtureToDelete = fixtureList.removeIndex(0); this.fixtures.remove(fixtureToDelete.addr).setUserData(null); freeFixtures.free(fixtureToDelete); } freeBodies.free(body); } private native void jniDestroyBody (long addr, long bodyAddr); /* b2World* world = (b2World*)addr; b2Body* body = (b2Body*)bodyAddr; CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env,object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); world->DestroyBody(body); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Internal method for fixture destruction with notifying custom * contact listener * @param body * @param fixture */ void destroyFixture(Body body, Fixture fixture) { jniDestroyFixture(addr, body.addr, fixture.addr); } private native void jniDestroyFixture(long addr, long bodyAddr, long fixtureAddr); /* b2World* world = (b2World*)(addr); b2Body* body = (b2Body*)(bodyAddr); b2Fixture* fixture = (b2Fixture*)(fixtureAddr); CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env, object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); body->DestroyFixture(fixture); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Internal method for body deactivation with notifying custom * contact listener * @param body */ void deactivateBody(Body body) { jniDeactivateBody(addr, body.addr); } private native void jniDeactivateBody(long addr, long bodyAddr); /* b2World* world = (b2World*)(addr); b2Body* body = (b2Body*)(bodyAddr); CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env, object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); body->SetActive(false); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies * to cease colliding. * @warning This function is locked during callbacks. */ public Joint createJoint (JointDef def) { long jointAddr = createProperJoint(def); Joint joint = null; if (def.type == JointType.DistanceJoint) joint = new DistanceJoint(this, jointAddr); if (def.type == JointType.FrictionJoint) joint = new FrictionJoint(this, jointAddr); if (def.type == JointType.GearJoint) joint = new GearJoint(this, jointAddr, ((GearJointDef) def).joint1, ((GearJointDef) def).joint2); if (def.type == JointType.MotorJoint) joint = new MotorJoint(this, jointAddr); if (def.type == JointType.MouseJoint) joint = new MouseJoint(this, jointAddr); if (def.type == JointType.PrismaticJoint) joint = new PrismaticJoint(this, jointAddr); if (def.type == JointType.PulleyJoint) joint = new PulleyJoint(this, jointAddr); if (def.type == JointType.RevoluteJoint) joint = new RevoluteJoint(this, jointAddr); if (def.type == JointType.RopeJoint) joint = new RopeJoint(this, jointAddr); if (def.type == JointType.WeldJoint) joint = new WeldJoint(this, jointAddr); if (def.type == JointType.WheelJoint) joint = new WheelJoint(this, jointAddr); if (joint == null) throw new GdxRuntimeException("Unknown joint type: " + def.type); joints.put(joint.addr, joint); JointEdge jointEdgeA = new JointEdge(def.bodyB, joint); JointEdge jointEdgeB = new JointEdge(def.bodyA, joint); joint.jointEdgeA = jointEdgeA; joint.jointEdgeB = jointEdgeB; def.bodyA.joints.add(jointEdgeA); def.bodyB.joints.add(jointEdgeB); return joint; } private long createProperJoint (JointDef def) { if (def.type == JointType.DistanceJoint) { DistanceJointDef d = (DistanceJointDef)def; return jniCreateDistanceJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.length, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.FrictionJoint) { FrictionJointDef d = (FrictionJointDef)def; return jniCreateFrictionJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.maxForce, d.maxTorque); } if (def.type == JointType.GearJoint) { GearJointDef d = (GearJointDef)def; return jniCreateGearJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.joint1.addr, d.joint2.addr, d.ratio); } if (def.type == JointType.MotorJoint) { MotorJointDef d = (MotorJointDef)def; return jniCreateMotorJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.linearOffset.x, d.linearOffset.y, d.angularOffset, d.maxForce, d.maxTorque, d.correctionFactor); } if (def.type == JointType.MouseJoint) { MouseJointDef d = (MouseJointDef)def; return jniCreateMouseJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.target.x, d.target.y, d.maxForce, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.PrismaticJoint) { PrismaticJointDef d = (PrismaticJointDef)def; return jniCreatePrismaticJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.localAxisA.x, d.localAxisA.y, d.referenceAngle, d.enableLimit, d.lowerTranslation, d.upperTranslation, d.enableMotor, d.maxMotorForce, d.motorSpeed); } if (def.type == JointType.PulleyJoint) { PulleyJointDef d = (PulleyJointDef)def; return jniCreatePulleyJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.groundAnchorA.x, d.groundAnchorA.y, d.groundAnchorB.x, d.groundAnchorB.y, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.lengthA, d.lengthB, d.ratio); } if (def.type == JointType.RevoluteJoint) { RevoluteJointDef d = (RevoluteJointDef)def; return jniCreateRevoluteJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle, d.enableLimit, d.lowerAngle, d.upperAngle, d.enableMotor, d.motorSpeed, d.maxMotorTorque); } if (def.type == JointType.RopeJoint) { RopeJointDef d = (RopeJointDef)def; return jniCreateRopeJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.maxLength); } if (def.type == JointType.WeldJoint) { WeldJointDef d = (WeldJointDef)def; return jniCreateWeldJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.referenceAngle, d.frequencyHz, d.dampingRatio); } if (def.type == JointType.WheelJoint) { WheelJointDef d = (WheelJointDef)def; return jniCreateWheelJoint(addr, d.bodyA.addr, d.bodyB.addr, d.collideConnected, d.localAnchorA.x, d.localAnchorA.y, d.localAnchorB.x, d.localAnchorB.y, d.localAxisA.x, d.localAxisA.y, d.enableMotor, d.maxMotorTorque, d.motorSpeed, d.frequencyHz, d.dampingRatio); } return 0; } private native long jniCreateWheelJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, boolean enableMotor, float maxMotorTorque, float motorSpeed, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2WheelJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.localAxisA = b2Vec2(localAxisAX, localAxisAY); def.enableMotor = enableMotor; def.maxMotorTorque = maxMotorTorque; def.motorSpeed = motorSpeed; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateRopeJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float maxLength); /* b2World* world = (b2World*)addr; b2RopeJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.maxLength = maxLength; return (jlong)world->CreateJoint(&def); */ private native long jniCreateDistanceJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float length, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2DistanceJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.length = length; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateFrictionJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float maxForce, float maxTorque); /* b2World* world = (b2World*)addr; b2FrictionJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.maxForce = maxForce; def.maxTorque = maxTorque; return (jlong)world->CreateJoint(&def); */ private native long jniCreateGearJoint (long addr, long bodyA, long bodyB, boolean collideConnected, long joint1, long joint2, float ratio); /* b2World* world = (b2World*)addr; b2GearJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.joint1 = (b2Joint*)joint1; def.joint2 = (b2Joint*)joint2; def.ratio = ratio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateMotorJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float linearOffsetX, float linearOffsetY, float angularOffset, float maxForce, float maxTorque, float correctionFactor); /* b2World* world = (b2World*)addr; b2MotorJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.linearOffset = b2Vec2( linearOffsetX, linearOffsetY ); def.angularOffset = angularOffset; def.maxForce = maxForce; def.maxTorque = maxTorque; def.correctionFactor = correctionFactor; return (jlong)world->CreateJoint(&def); */ private native long jniCreateMouseJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float targetX, float targetY, float maxForce, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2MouseJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.target = b2Vec2( targetX, targetY ); def.maxForce = maxForce; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ private native long jniCreatePrismaticJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float localAxisAX, float localAxisAY, float referenceAngle, boolean enableLimit, float lowerTranslation, float upperTranslation, boolean enableMotor, float maxMotorForce, float motorSpeed); /* b2World* world = (b2World*)addr; b2PrismaticJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.localAxisA = b2Vec2( localAxisAX, localAxisAY ); def.referenceAngle = referenceAngle; def.enableLimit = enableLimit; def.lowerTranslation = lowerTranslation; def.upperTranslation = upperTranslation; def.enableMotor = enableMotor; def.maxMotorForce = maxMotorForce; def.motorSpeed = motorSpeed; return (jlong)world->CreateJoint(&def); */ private native long jniCreatePulleyJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float groundAnchorAX, float groundAnchorAY, float groundAnchorBX, float groundAnchorBY, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float lengthA, float lengthB, float ratio); /* b2World* world = (b2World*)addr; b2PulleyJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.groundAnchorA = b2Vec2( groundAnchorAX, groundAnchorAY ); def.groundAnchorB = b2Vec2( groundAnchorBX, groundAnchorBY ); def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.lengthA = lengthA; def.lengthB = lengthB; def.ratio = ratio; return (jlong)world->CreateJoint(&def); */ private native long jniCreateRevoluteJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle, boolean enableLimit, float lowerAngle, float upperAngle, boolean enableMotor, float motorSpeed, float maxMotorTorque); /* b2World* world = (b2World*)addr; b2RevoluteJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.referenceAngle = referenceAngle; def.enableLimit = enableLimit; def.lowerAngle = lowerAngle; def.upperAngle = upperAngle; def.enableMotor = enableMotor; def.motorSpeed = motorSpeed; def.maxMotorTorque = maxMotorTorque; return (jlong)world->CreateJoint(&def); */ private native long jniCreateWeldJoint (long addr, long bodyA, long bodyB, boolean collideConnected, float localAnchorAX, float localAnchorAY, float localAnchorBX, float localAnchorBY, float referenceAngle, float frequencyHz, float dampingRatio); /* b2World* world = (b2World*)addr; b2WeldJointDef def; def.bodyA = (b2Body*)bodyA; def.bodyB = (b2Body*)bodyB; def.collideConnected = collideConnected; def.localAnchorA = b2Vec2(localAnchorAX, localAnchorAY); def.localAnchorB = b2Vec2(localAnchorBX, localAnchorBY); def.referenceAngle = referenceAngle; def.frequencyHz = frequencyHz; def.dampingRatio = dampingRatio; return (jlong)world->CreateJoint(&def); */ /** Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ public void destroyJoint (Joint joint) { joint.setUserData(null); joints.remove(joint.addr); joint.jointEdgeA.other.joints.removeValue(joint.jointEdgeB, true); joint.jointEdgeB.other.joints.removeValue(joint.jointEdgeA, true); jniDestroyJoint(addr, joint.addr); } private native void jniDestroyJoint (long addr, long jointAddr); /* b2World* world = (b2World*)addr; b2Joint* joint = (b2Joint*)jointAddr; CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env,object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); world->DestroyJoint( joint ); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Take a time step. This performs collision detection, integration, and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public void step (float timeStep, int velocityIterations, int positionIterations) { jniStep(addr, timeStep, velocityIterations, positionIterations); } private native void jniStep (long addr, float timeStep, int velocityIterations, int positionIterations); /* b2World* world = (b2World*)addr; CustomContactFilter contactFilter(env, object); CustomContactListener contactListener(env,object); world->SetContactFilter(&contactFilter); world->SetContactListener(&contactListener); world->Step( timeStep, velocityIterations, positionIterations ); world->SetContactFilter(&defaultFilter); world->SetContactListener(0); */ /** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The * default behavior is modified by calling SetAutoClearForces. The purpose of this function is to support sub-stepping. * Sub-stepping is often used to maintain a fixed sized time step under a variable frame-rate. When you perform sub-stepping * you will disable auto clearing of forces and instead call ClearForces after all sub-steps are complete in one pass of your * game loop. {@link #setAutoClearForces(boolean)} */ public void clearForces () { jniClearForces(addr); } private native void jniClearForces (long addr); /* b2World* world = (b2World*)addr; world->ClearForces(); */ /** Enable/disable warm starting. For testing. */ public void setWarmStarting (boolean flag) { jniSetWarmStarting(addr, flag); } private native void jniSetWarmStarting (long addr, boolean flag); /* b2World* world = (b2World*)addr; world->SetWarmStarting(flag); */ /** Enable/disable continuous physics. For testing. */ public void setContinuousPhysics (boolean flag) { jniSetContiousPhysics(addr, flag); } private native void jniSetContiousPhysics (long addr, boolean flag); /* b2World* world = (b2World*)addr; world->SetContinuousPhysics(flag); */ /** Get the number of broad-phase proxies. */ public int getProxyCount () { return jniGetProxyCount(addr); } private native int jniGetProxyCount (long addr); /* b2World* world = (b2World*)addr; return world->GetProxyCount(); */ /** Get the number of bodies. */ public int getBodyCount () { return jniGetBodyCount(addr); } private native int jniGetBodyCount (long addr); /* b2World* world = (b2World*)addr; return world->GetBodyCount(); */ /** Get the number of fixtures. */ public int getFixtureCount () { return fixtures.size; } /** Get the number of joints. */ public int getJointCount () { return jniGetJointcount(addr); } private native int jniGetJointcount (long addr); /* b2World* world = (b2World*)addr; return world->GetJointCount(); */ /** Get the number of contacts (each may have 0 or more contact points). */ public int getContactCount () { return jniGetContactCount(addr); } private native int jniGetContactCount (long addr); /* b2World* world = (b2World*)addr; return world->GetContactCount(); */ /** Change the global gravity vector. */ public void setGravity (Vector2 gravity) { jniSetGravity(addr, gravity.x, gravity.y); } private native void jniSetGravity (long addr, float gravityX, float gravityY); /* b2World* world = (b2World*)addr; world->SetGravity( b2Vec2( gravityX, gravityY ) ); */ /** Get the global gravity vector. */ final float[] tmpGravity = new float[2]; final Vector2 gravity = new Vector2(); public Vector2 getGravity () { jniGetGravity(addr, tmpGravity); gravity.x = tmpGravity[0]; gravity.y = tmpGravity[1]; return gravity; } private native void jniGetGravity (long addr, float[] gravity); /* b2World* world = (b2World*)addr; b2Vec2 g = world->GetGravity(); gravity[0] = g.x; gravity[1] = g.y; */ /** Is the world locked (in the middle of a time step). */ public boolean isLocked () { return jniIsLocked(addr); } private native boolean jniIsLocked (long addr); /* b2World* world = (b2World*)addr; return world->IsLocked(); */ /** Set flag to control automatic clearing of forces after each time step. */ public void setAutoClearForces (boolean flag) { jniSetAutoClearForces(addr, flag); } private native void jniSetAutoClearForces (long addr, boolean flag); /* b2World* world = (b2World*)addr; world->SetAutoClearForces(flag); */ /** Get the flag that controls automatic clearing of forces after each time step. */ public boolean getAutoClearForces () { return jniGetAutoClearForces(addr); } private native boolean jniGetAutoClearForces (long addr); /* b2World* world = (b2World*)addr; return world->GetAutoClearForces(); */ /** Query the world for all fixtures that potentially overlap the provided AABB. * @param callback a user implemented callback class. * @param lowerX the x coordinate of the lower left corner * @param lowerY the y coordinate of the lower left corner * @param upperX the x coordinate of the upper right corner * @param upperY the y coordinate of the upper right corner */ public void QueryAABB (QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY) { queryCallback = callback; jniQueryAABB(addr, lowerX, lowerY, upperX, upperY); } private QueryCallback queryCallback = null;; private native void jniQueryAABB (long addr, float lowX, float lowY, float upX, float upY); /* b2World* world = (b2World*)addr; b2AABB aabb; aabb.lowerBound = b2Vec2( lowX, lowY ); aabb.upperBound = b2Vec2( upX, upY ); CustomQueryCallback callback( env, object ); world->QueryAABB( &callback, aabb ); */ // // /// Ray-cast the world for all fixtures in the path of the ray. Your callback // /// controls whether you get the closest point, any point, or n-points. // /// The ray-cast ignores shapes that contain the starting point. // /// @param callback a user implemented callback class. // /// @param point1 the ray starting point // /// @param point2 the ray ending point // void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; // // /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get // /// the next contact in the world list. A NULL contact indicates the end of the list. // /// @return the head of the world contact list. // /// @warning contacts are // b2Contact* GetContactList(); private long[] contactAddrs = new long[200]; private final Array<Contact> contacts = new Array<Contact>(); private final Array<Contact> freeContacts = new Array<Contact>(); /** Returns the list of {@link Contact} instances produced by the last call to {@link #step(float, int, int)}. Note that the * returned list will have O(1) access times when using indexing. contacts are created and destroyed in the middle of a time * step. Use {@link ContactListener} to avoid missing contacts * @return the contact list */ public Array<Contact> getContactList () { int numContacts = getContactCount(); if (numContacts > contactAddrs.length) { int newSize = 2 * numContacts; contactAddrs = new long[newSize]; contacts.ensureCapacity(newSize); freeContacts.ensureCapacity(newSize); } if (numContacts > freeContacts.size) { int freeConts = freeContacts.size; for (int i = 0; i < numContacts - freeConts; i++) freeContacts.add(new Contact(this, 0)); } jniGetContactList(addr, contactAddrs); contacts.clear(); for (int i = 0; i < numContacts; i++) { Contact contact = freeContacts.get(i); contact.addr = contactAddrs[i]; contacts.add(contact); } return contacts; } /** @param bodies an Array in which to place all bodies currently in the simulation */ public void getBodies (Array<Body> bodies) { bodies.clear(); bodies.ensureCapacity(this.bodies.size); for (Iterator<Body> iter = this.bodies.values(); iter.hasNext();) { bodies.add(iter.next()); } } /** @param fixtures an Array in which to place all fixtures currently in the simulation */ public void getFixtures (Array<Fixture> fixtures) { fixtures.clear(); fixtures.ensureCapacity(this.fixtures.size); for (Iterator<Fixture> iter = this.fixtures.values(); iter.hasNext();) { fixtures.add(iter.next()); } } /** @param joints an Array in which to place all joints currently in the simulation */ public void getJoints (Array<Joint> joints) { joints.clear(); joints.ensureCapacity(this.joints.size); for (Iterator<Joint> iter = this.joints.values(); iter.hasNext();) { joints.add(iter.next()); } } private native void jniGetContactList (long addr, long[] contacts); /* b2World* world = (b2World*)addr; b2Contact* contact = world->GetContactList(); int i = 0; while( contact != 0 ) { contacts[i++] = (long long)contact; contact = contact->GetNext(); } */ public void dispose () { jniDispose(addr); } private native void jniDispose (long addr); /* b2World* world = (b2World*)(addr); delete world; */ /** Internal method called from JNI in case a contact happens * @param fixtureA * @param fixtureB * @return whether the things collided */ private boolean contactFilter (long fixtureA, long fixtureB) { if (contactFilter != null) return contactFilter.shouldCollide(fixtures.get(fixtureA), fixtures.get(fixtureB)); else { Filter filterA = fixtures.get(fixtureA).getFilterData(); Filter filterB = fixtures.get(fixtureB).getFilterData(); if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) { return filterA.groupIndex > 0; } boolean collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; return collide; } } private final Contact contact = new Contact(this, 0); private final Manifold manifold = new Manifold(0); private final ContactImpulse impulse = new ContactImpulse(this, 0); private void beginContact (long contactAddr) { contact.addr = contactAddr; if (contactListener != null) contactListener.beginContact(contact); } private void endContact (long contactAddr) { contact.addr = contactAddr; if (contactListener != null) contactListener.endContact(contact); } private void preSolve (long contactAddr, long manifoldAddr) { contact.addr = contactAddr; manifold.addr = manifoldAddr; if (contactListener != null) contactListener.preSolve(contact, manifold); } private void postSolve (long contactAddr, long impulseAddr) { contact.addr = contactAddr; impulse.addr = impulseAddr; if (contactListener != null) contactListener.postSolve(contact, impulse); } private boolean reportFixture (long addr) { if (queryCallback != null) return queryCallback.reportFixture(fixtures.get(addr)); else return false; } /** Sets the box2d velocity threshold globally, for all World instances. * @param threshold the threshold, default 1.0f */ public static native void setVelocityThreshold (float threshold); /* b2_velocityThreshold = threshold; */ /** @return the global box2d velocity threshold. */ public static native float getVelocityThreshold (); /* return b2_velocityThreshold; */ /** Ray-cast the world for all fixtures in the path of the ray. The ray-cast ignores shapes that contain the starting point. * @param callback a user implemented callback class. * @param point1 the ray starting point * @param point2 the ray ending point */ public void rayCast (RayCastCallback callback, Vector2 point1, Vector2 point2) { rayCast(callback, point1.x, point1.y, point2.x, point2.y); } /** Ray-cast the world for all fixtures in the path of the ray. The ray-cast ignores shapes that contain the starting point. * @param callback a user implemented callback class. * @param point1X the ray starting point X * @param point1Y the ray starting point Y * @param point2X the ray ending point X * @param point2Y the ray ending point Y */ public void rayCast (RayCastCallback callback, float point1X, float point1Y, float point2X, float point2Y) { rayCastCallback = callback; jniRayCast(addr, point1X, point1Y, point2X, point2Y); } private RayCastCallback rayCastCallback = null; private native void jniRayCast (long addr, float aX, float aY, float bX, float bY); /* b2World *world = (b2World*)addr; CustomRayCastCallback callback( env, object ); world->RayCast( &callback, b2Vec2(aX,aY), b2Vec2(bX,bY) ); */ private Vector2 rayPoint = new Vector2(); private Vector2 rayNormal = new Vector2(); private float reportRayFixture (long addr, float pX, float pY, float nX, float nY, float fraction) { if (rayCastCallback != null) { rayPoint.x = pX; rayPoint.y = pY; rayNormal.x = nX; rayNormal.y = nY; return rayCastCallback.reportRayFixture(fixtures.get(addr), rayPoint, rayNormal, fraction); } else { return 0.0f; } } }
box2D World.java contact listener method, dont affect addr if no listener (#5999) * box2D World.java contact listener method, dont affect addr if no listener * fix indent
extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/World.java
box2D World.java contact listener method, dont affect addr if no listener (#5999)
<ide><path>xtensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/World.java <ide> private final ContactImpulse impulse = new ContactImpulse(this, 0); <ide> <ide> private void beginContact (long contactAddr) { <del> contact.addr = contactAddr; <del> if (contactListener != null) contactListener.beginContact(contact); <add> if (contactListener != null) { <add> contact.addr = contactAddr; <add> contactListener.beginContact(contact); <add> } <ide> } <ide> <ide> private void endContact (long contactAddr) { <del> contact.addr = contactAddr; <del> if (contactListener != null) contactListener.endContact(contact); <add> if (contactListener != null) { <add> contact.addr = contactAddr; <add> contactListener.endContact(contact); <add> } <ide> } <ide> <ide> private void preSolve (long contactAddr, long manifoldAddr) { <del> contact.addr = contactAddr; <del> manifold.addr = manifoldAddr; <del> if (contactListener != null) contactListener.preSolve(contact, manifold); <add> if (contactListener != null) { <add> contact.addr = contactAddr; <add> manifold.addr = manifoldAddr; <add> contactListener.preSolve(contact, manifold); <add> } <ide> } <ide> <ide> private void postSolve (long contactAddr, long impulseAddr) { <del> contact.addr = contactAddr; <del> impulse.addr = impulseAddr; <del> if (contactListener != null) contactListener.postSolve(contact, impulse); <add> if (contactListener != null) { <add> contact.addr = contactAddr; <add> impulse.addr = impulseAddr; <add> contactListener.postSolve(contact, impulse); <add> } <ide> } <ide> <ide> private boolean reportFixture (long addr) {
Java
lgpl-2.1
d62d78ca8288d2c7a2091122a261201c76ec29f2
0
deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.feature.persistence.sql.rules; import static org.deegree.commons.utils.JDBCUtils.close; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.apache.xerces.xs.XSElementDeclaration; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.genericxml.GenericXMLElement; import org.deegree.commons.tom.primitive.PrimitiveType; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.commons.utils.Pair; import org.deegree.commons.xml.NamespaceBindings; import org.deegree.feature.Feature; import org.deegree.feature.persistence.sql.AbstractSQLFeatureStore; import org.deegree.feature.persistence.sql.FeatureBuilder; import org.deegree.feature.persistence.sql.FeatureTypeMapping; import org.deegree.feature.persistence.sql.expressions.TableJoin; import org.deegree.feature.property.GenericProperty; import org.deegree.feature.property.Property; import org.deegree.feature.types.FeatureType; import org.deegree.feature.types.property.PropertyType; import org.deegree.filter.expression.PropertyName; import org.deegree.filter.sql.DBField; import org.deegree.filter.sql.MappingExpression; import org.deegree.geometry.io.WKBReader; import org.deegree.gml.GMLVersion; import org.deegree.gml.feature.FeatureReference; import org.jaxen.expr.Expr; import org.jaxen.expr.LocationPath; import org.jaxen.expr.NameStep; import org.jaxen.expr.Step; import org.jaxen.expr.TextNodeStep; import org.jaxen.saxpath.Axis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vividsolutions.jts.io.ParseException; /** * Builds {@link Feature} instances from SQL result set rows (relational mode). * * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class FeatureBuilderRelational implements FeatureBuilder { private static final Logger LOG = LoggerFactory.getLogger( FeatureBuilderRelational.class ); private final AbstractSQLFeatureStore fs; private final FeatureType ft; private final FeatureTypeMapping ftMapping; private final Connection conn; private final NamespaceBindings nsBindings; private final GMLVersion gmlVersion; private final LinkedHashMap<String, Integer> colToRsIdx = new LinkedHashMap<String, Integer>(); /** * Creates a new {@link FeatureBuilderRelational} instance. * * @param fs * feature store, must not be <code>null</code> * @param ft * feature type, must not be <code>null</code> * @param ftMapping * feature type mapping, must not be <code>null</code> * @param conn * JDBC connection (used for performing subsequent SELECTs), must not be <code>null</code> */ public FeatureBuilderRelational( AbstractSQLFeatureStore fs, FeatureType ft, FeatureTypeMapping ftMapping, Connection conn ) { this.fs = fs; this.ft = ft; this.ftMapping = ftMapping; this.conn = conn; this.nsBindings = new NamespaceBindings(); for ( String prefix : fs.getNamespaceContext().keySet() ) { String ns = fs.getNamespaceContext().get( prefix ); nsBindings.addNamespace( prefix, ns ); } if ( ft.getSchema().getXSModel() != null ) { this.gmlVersion = ft.getSchema().getXSModel().getVersion(); } else { this.gmlVersion = GMLVersion.GML_32; } } @Override public List<String> getInitialSelectColumns() { for ( Pair<String, PrimitiveType> fidColumn : ftMapping.getFidMapping().getColumns() ) { addColumn( colToRsIdx, fidColumn.first ); } for ( Mapping mapping : ftMapping.getMappings() ) { addSelectColumns( mapping, colToRsIdx, true ); } LOG.debug( "Initial select columns: " + colToRsIdx ); return new ArrayList<String>( colToRsIdx.keySet() ); } private void addColumn( LinkedHashMap<String, Integer> colToRsIdx, String column ) { if ( !colToRsIdx.containsKey( column ) ) { colToRsIdx.put( column, colToRsIdx.size() + 1 ); } } private LinkedHashMap<String, Integer> getSubsequentSelectColumns( Mapping mapping ) { LinkedHashMap<String, Integer> colToRsIdx = new LinkedHashMap<String, Integer>(); addSelectColumns( mapping, colToRsIdx, false ); return colToRsIdx; } private void addSelectColumns( Mapping mapping, LinkedHashMap<String, Integer> colToRsIdx, boolean initial ) { List<TableJoin> jc = mapping.getJoinedTable(); if ( jc != null && initial ) { if ( initial ) { for ( String column : jc.get( 0 ).getFromColumns() ) { addColumn( colToRsIdx, column ); } } } else { if ( mapping instanceof PrimitiveMapping ) { PrimitiveMapping pm = (PrimitiveMapping) mapping; MappingExpression column = pm.getMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, ( (DBField) column ).getColumn() ); } else { LOG.info( "Omitting mapping '" + mapping + "' from SELECT list. Not mapped to column.'" ); } } else if ( mapping instanceof GeometryMapping ) { GeometryMapping gm = (GeometryMapping) mapping; MappingExpression column = gm.getMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, fs.getSQLValueMapper().selectGeometry( ( (DBField) column ).getColumn() ) ); } } else if ( mapping instanceof FeatureMapping ) { FeatureMapping fm = (FeatureMapping) mapping; MappingExpression column = fm.getMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, ( (DBField) column ).getColumn() ); } column = fm.getHrefMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, ( (DBField) column ).getColumn() ); } } else if ( mapping instanceof CompoundMapping ) { CompoundMapping cm = (CompoundMapping) mapping; for ( Mapping particle : cm.getParticles() ) { addSelectColumns( particle, colToRsIdx, true ); } } else if ( mapping instanceof ConstantMapping<?> ) { // nothing to do } else { LOG.warn( "Mappings of type '" + mapping.getClass() + "' are not handled yet." ); } } } @Override public Feature buildFeature( ResultSet rs ) throws SQLException { String gmlId = ftMapping.getFidMapping().getPrefix(); for ( Pair<String, PrimitiveType> fidColumn : ftMapping.getFidMapping().getColumns() ) { gmlId += rs.getObject( colToRsIdx.get( fidColumn.first ) ); } Feature feature = (Feature) fs.getCache().get( gmlId ); if ( feature == null ) { LOG.debug( "Cache miss. Recreating feature '" + gmlId + "' from db (relational mode)." ); List<Property> props = new ArrayList<Property>(); for ( Mapping mapping : ftMapping.getMappings() ) { PropertyName propName = mapping.getPath(); if ( propName.getAsQName() != null ) { PropertyType pt = ft.getPropertyDeclaration( propName.getAsQName(), gmlVersion ); addProperties( props, pt, mapping, rs ); } else { // TODO more complex mappings, e.g. "propname[1]" LOG.warn( "Omitting mapping '" + mapping + "'. Only simple property names (QNames) are currently supported here." ); } } feature = ft.newFeature( gmlId, props, null, null ); fs.getCache().add( feature ); } else { LOG.debug( "Cache hit." ); } return feature; } private void addProperties( List<Property> props, PropertyType pt, Mapping propMapping, ResultSet rs ) throws SQLException { List<TypedObjectNode> particles = buildParticles( propMapping, rs, colToRsIdx ); for ( TypedObjectNode particle : particles ) { if ( particle instanceof GenericXMLElement ) { GenericXMLElement xmlEl = (GenericXMLElement) particle; props.add( new GenericProperty( pt, xmlEl.getName(), null, xmlEl.getAttributes(), xmlEl.getChildren() ) ); } else { props.add( new GenericProperty( pt, pt.getName(), particle ) ); } } } private List<TypedObjectNode> buildParticles( Mapping mapping, ResultSet rs, LinkedHashMap<String, Integer> colToRsIdx ) throws SQLException { if ( mapping.getJoinedTable() != null ) { List<TypedObjectNode> values = new ArrayList<TypedObjectNode>(); ResultSet rs2 = null; try { Pair<ResultSet, LinkedHashMap<String, Integer>> p = getJoinedResultSet( mapping.getJoinedTable().get( 0 ), mapping, rs, colToRsIdx ); rs2 = p.first; while ( rs2.next() ) { TypedObjectNode particle = buildParticle( mapping, rs2, p.second ); if ( particle != null ) { values.add( buildParticle( mapping, rs2, p.second ) ); } } } finally { if ( rs2 != null ) { rs2.getStatement().close(); rs2.close(); } } return values; } TypedObjectNode particle = buildParticle( mapping, rs, colToRsIdx ); if ( particle != null ) { return Collections.singletonList( buildParticle( mapping, rs, colToRsIdx ) ); } return Collections.emptyList(); } private TypedObjectNode buildParticle( Mapping mapping, ResultSet rs, LinkedHashMap<String, Integer> colToRsIdx ) throws SQLException { TypedObjectNode particle = null; if ( mapping instanceof PrimitiveMapping ) { PrimitiveMapping pm = (PrimitiveMapping) mapping; MappingExpression me = pm.getMapping(); if ( me instanceof DBField ) { Object value = rs.getObject( colToRsIdx.get( ( (DBField) me ).getColumn() ) ); if ( value != null ) { particle = new PrimitiveValue( value, pm.getType() ); } } } else if ( mapping instanceof GeometryMapping ) { GeometryMapping pm = (GeometryMapping) mapping; MappingExpression me = pm.getMapping(); if ( me instanceof DBField ) { byte[] wkb = rs.getBytes( colToRsIdx.get( fs.getSQLValueMapper().selectGeometry( ( (DBField) me ).getColumn() ) ) ); if ( wkb != null ) { try { particle = WKBReader.read( wkb, pm.getCRS() ); } catch ( ParseException e ) { throw new SQLException( "Error parsing WKB from database: " + e.getMessage(), e ); } } } } else if ( mapping instanceof FeatureMapping ) { FeatureMapping fm = (FeatureMapping) mapping; MappingExpression me = fm.getMapping(); if ( me instanceof DBField ) { Object value = rs.getObject( colToRsIdx.get( ( (DBField) me ).getColumn() ) ); if ( value != null ) { // TODO String ref = "#" + value; particle = new FeatureReference( fs.getResolver(), ref, null ); } } me = fm.getHrefMapping(); if ( me instanceof DBField ) { String value = rs.getString( colToRsIdx.get( ( (DBField) me ).getColumn() ) ); if ( value != null ) { particle = new FeatureReference( fs.getResolver(), value, null ); } } } else if ( mapping instanceof ConstantMapping<?> ) { particle = ( (ConstantMapping<?>) mapping ).getValue(); } else if ( mapping instanceof CompoundMapping ) { CompoundMapping cm = (CompoundMapping) mapping; Map<QName, PrimitiveValue> attrs = new HashMap<QName, PrimitiveValue>(); List<TypedObjectNode> children = new ArrayList<TypedObjectNode>(); for ( Mapping particleMapping : cm.getParticles() ) { List<TypedObjectNode> particleValues = buildParticles( particleMapping, rs, colToRsIdx ); Expr xpath = particleMapping.getPath().getAsXPath(); if ( xpath instanceof LocationPath ) { LocationPath lp = (LocationPath) xpath; if ( lp.getSteps().size() != 1 ) { LOG.warn( "Unhandled location path: '" + particleMapping.getPath() + "'. Only single step paths are handled." ); continue; } if ( lp.isAbsolute() ) { LOG.warn( "Unhandled location path: '" + particleMapping.getPath() + "'. Only relative paths are handled." ); continue; } Step step = (Step) lp.getSteps().get( 0 ); if ( !step.getPredicates().isEmpty() ) { LOG.warn( "Unhandled location path: '" + particleMapping.getPath() + "'. Only unpredicated steps are handled." ); continue; } if ( step instanceof TextNodeStep ) { for ( TypedObjectNode particleValue : particleValues ) { children.add( particleValue ); } } else if ( step instanceof NameStep ) { NameStep ns = (NameStep) step; QName name = getQName( ns ); if ( step.getAxis() == Axis.ATTRIBUTE ) { for ( TypedObjectNode particleValue : particleValues ) { if ( particleValue instanceof PrimitiveValue ) { attrs.put( name, (PrimitiveValue) particleValue ); } else { LOG.warn( "Value not suitable for attribute." ); } } } else if ( step.getAxis() == Axis.CHILD ) { for ( TypedObjectNode particleValue : particleValues ) { if ( particleValue instanceof PrimitiveValue ) { // TODO XSElementDeclaration childType = null; GenericXMLElement child = new GenericXMLElement( name, childType, Collections.<QName, PrimitiveValue> emptyMap(), Collections.singletonList( particleValue ) ); children.add( child ); } else if ( particleValue != null ) { children.add( particleValue ); } } } else { LOG.warn( "Unhandled axis type '" + step.getAxis() + "' for path: '" + particleMapping.getPath() + "'" ); } } else { // TODO handle other steps as self() for ( TypedObjectNode particleValue : particleValues ) { children.add( particleValue ); } } } else { LOG.warn( "Unhandled mapping type '" + particleMapping.getClass() + "' for path: '" + particleMapping.getPath() + "'" ); } } // TODO XSElementDeclaration xsType = null; if ( ( !attrs.isEmpty() ) || !children.isEmpty() ) { particle = new GenericXMLElement( cm.getPath().getAsQName(), xsType, attrs, children ); } } else { LOG.warn( "Handling of '" + mapping.getClass() + "' mappings is not implemented yet." ); } return particle; } private Pair<ResultSet, LinkedHashMap<String, Integer>> getJoinedResultSet( TableJoin jc, Mapping mapping, ResultSet rs, LinkedHashMap<String, Integer> colToRsIdx ) throws SQLException { LinkedHashMap<String, Integer> rsToIdx = getSubsequentSelectColumns( mapping ); StringBuilder sql = new StringBuilder( "SELECT " ); boolean first = true; for ( String column : rsToIdx.keySet() ) { if ( !first ) { sql.append( ',' ); } sql.append( column ); first = false; } sql.append( " FROM " ); sql.append( jc.getToTable() ); sql.append( " WHERE " ); first = true; for ( String keyColumn : jc.getToColumns() ) { if ( !first ) { sql.append( " AND " ); } sql.append( keyColumn ); sql.append( " = ?" ); first = false; } LOG.debug( "SQL: {}", sql ); PreparedStatement stmt = null; ResultSet rs2 = null; try { long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing subsequent SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; for ( String keyColumn : jc.getFromColumns() ) { Object key = rs.getObject( colToRsIdx.get( keyColumn ) ); LOG.debug( "? = '{}' ({})", key, keyColumn ); stmt.setObject( i++, key ); } begin = System.currentTimeMillis(); rs2 = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); } catch ( Throwable t ) { close( rs2, stmt, null, LOG ); String msg = "Error performing subsequent SELECT: " + t.getMessage(); LOG.error( msg, t ); throw new SQLException( msg, t ); } return new Pair<ResultSet, LinkedHashMap<String, Integer>>( rs2, rsToIdx ); } private QName getQName( NameStep step ) { String prefix = step.getPrefix(); QName qName; if ( prefix.isEmpty() ) { qName = new QName( step.getLocalName() ); } else { String ns = nsBindings.translateNamespacePrefixToUri( prefix ); qName = new QName( ns, step.getLocalName(), prefix ); } return qName; } }
deegree-datastores/deegree-featurestore/deegree-featurestore-commons/src/main/java/org/deegree/feature/persistence/sql/rules/FeatureBuilderRelational.java
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.feature.persistence.sql.rules; import static org.deegree.commons.utils.JDBCUtils.close; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.apache.xerces.xs.XSElementDeclaration; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.genericxml.GenericXMLElement; import org.deegree.commons.tom.primitive.PrimitiveType; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.commons.utils.Pair; import org.deegree.commons.xml.NamespaceBindings; import org.deegree.feature.Feature; import org.deegree.feature.persistence.sql.AbstractSQLFeatureStore; import org.deegree.feature.persistence.sql.FeatureBuilder; import org.deegree.feature.persistence.sql.FeatureTypeMapping; import org.deegree.feature.persistence.sql.expressions.TableJoin; import org.deegree.feature.property.GenericProperty; import org.deegree.feature.property.Property; import org.deegree.feature.types.FeatureType; import org.deegree.feature.types.property.PropertyType; import org.deegree.filter.expression.PropertyName; import org.deegree.filter.sql.DBField; import org.deegree.filter.sql.MappingExpression; import org.deegree.geometry.io.WKBReader; import org.deegree.gml.GMLVersion; import org.deegree.gml.feature.FeatureReference; import org.jaxen.expr.Expr; import org.jaxen.expr.LocationPath; import org.jaxen.expr.NameStep; import org.jaxen.expr.Step; import org.jaxen.expr.TextNodeStep; import org.jaxen.saxpath.Axis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vividsolutions.jts.io.ParseException; /** * Builds {@link Feature} instances from SQL result set rows (relational mode). * * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class FeatureBuilderRelational implements FeatureBuilder { private static final Logger LOG = LoggerFactory.getLogger( FeatureBuilderRelational.class ); private final AbstractSQLFeatureStore fs; private final FeatureType ft; private final FeatureTypeMapping ftMapping; private final Connection conn; private final NamespaceBindings nsBindings; private final GMLVersion gmlVersion; private final LinkedHashMap<String, Integer> colToRsIdx = new LinkedHashMap<String, Integer>(); /** * Creates a new {@link FeatureBuilderRelational} instance. * * @param fs * feature store, must not be <code>null</code> * @param ft * feature type, must not be <code>null</code> * @param ftMapping * feature type mapping, must not be <code>null</code> * @param conn * JDBC connection (used for performing subsequent SELECTs), must not be <code>null</code> */ public FeatureBuilderRelational( AbstractSQLFeatureStore fs, FeatureType ft, FeatureTypeMapping ftMapping, Connection conn ) { this.fs = fs; this.ft = ft; this.ftMapping = ftMapping; this.conn = conn; this.nsBindings = new NamespaceBindings(); for ( String prefix : fs.getNamespaceContext().keySet() ) { String ns = fs.getNamespaceContext().get( prefix ); nsBindings.addNamespace( prefix, ns ); } if ( ft.getSchema().getXSModel() != null ) { this.gmlVersion = ft.getSchema().getXSModel().getVersion(); } else { this.gmlVersion = GMLVersion.GML_32; } } @Override public List<String> getInitialSelectColumns() { for ( Pair<String, PrimitiveType> fidColumn : ftMapping.getFidMapping().getColumns() ) { addColumn( colToRsIdx, fidColumn.first ); } for ( Mapping mapping : ftMapping.getMappings() ) { addSelectColumns( mapping, colToRsIdx, true ); } LOG.debug( "Initial select columns: " + colToRsIdx ); return new ArrayList<String>( colToRsIdx.keySet() ); } private void addColumn( LinkedHashMap<String, Integer> colToRsIdx, String column ) { if ( !colToRsIdx.containsKey( column ) ) { colToRsIdx.put( column, colToRsIdx.size() + 1 ); } } private LinkedHashMap<String, Integer> getSubsequentSelectColumns( Mapping mapping ) { LinkedHashMap<String, Integer> colToRsIdx = new LinkedHashMap<String, Integer>(); addSelectColumns( mapping, colToRsIdx, false ); return colToRsIdx; } private void addSelectColumns( Mapping mapping, LinkedHashMap<String, Integer> colToRsIdx, boolean initial ) { List<TableJoin> jc = mapping.getJoinedTable(); if ( jc != null && initial ) { if ( initial ) { for ( String column : jc.get( 0 ).getFromColumns() ) { addColumn( colToRsIdx, column ); } } } else { if ( mapping instanceof PrimitiveMapping ) { PrimitiveMapping pm = (PrimitiveMapping) mapping; MappingExpression column = pm.getMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, ( (DBField) column ).getColumn() ); } else { LOG.info( "Omitting mapping '" + mapping + "' from SELECT list. Not mapped to column.'" ); } } else if ( mapping instanceof GeometryMapping ) { GeometryMapping gm = (GeometryMapping) mapping; MappingExpression column = gm.getMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, fs.getSQLValueMapper().selectGeometry( ( (DBField) column ).getColumn() ) ); } } else if ( mapping instanceof FeatureMapping ) { FeatureMapping fm = (FeatureMapping) mapping; MappingExpression column = fm.getMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, ( (DBField) column ).getColumn() ); } column = fm.getHrefMapping(); if ( column instanceof DBField ) { addColumn( colToRsIdx, ( (DBField) column ).getColumn() ); } } else if ( mapping instanceof CompoundMapping ) { CompoundMapping cm = (CompoundMapping) mapping; for ( Mapping particle : cm.getParticles() ) { addSelectColumns( particle, colToRsIdx, true ); } } else if ( mapping instanceof ConstantMapping<?> ) { // nothing to do } else { LOG.warn( "Mappings of type '" + mapping.getClass() + "' are not handled yet." ); } } } @Override public Feature buildFeature( ResultSet rs ) throws SQLException { String gmlId = ftMapping.getFidMapping().getPrefix(); for ( Pair<String, PrimitiveType> fidColumn : ftMapping.getFidMapping().getColumns() ) { gmlId += rs.getObject( colToRsIdx.get( fidColumn.first ) ); } Feature feature = (Feature) fs.getCache().get( gmlId ); if ( feature == null ) { LOG.debug( "Cache miss. Recreating feature '" + gmlId + "' from db (relational mode)." ); List<Property> props = new ArrayList<Property>(); for ( Mapping mapping : ftMapping.getMappings() ) { PropertyName propName = mapping.getPath(); if ( propName.getAsQName() != null ) { PropertyType pt = ft.getPropertyDeclaration( propName.getAsQName(), gmlVersion ); addProperties( props, pt, mapping, rs ); } else { // TODO more complex mappings, e.g. "propname[1]" LOG.warn( "Omitting mapping '" + mapping + "'. Only simple property names (QNames) are currently supported here." ); } } feature = ft.newFeature( gmlId, props, null, null ); fs.getCache().add( feature ); } else { LOG.debug( "Cache hit." ); } return feature; } private void addProperties( List<Property> props, PropertyType pt, Mapping propMapping, ResultSet rs ) throws SQLException { List<TypedObjectNode> particles = buildParticles( propMapping, rs, colToRsIdx ); for ( TypedObjectNode particle : particles ) { if ( particle instanceof GenericXMLElement ) { GenericXMLElement xmlEl = (GenericXMLElement) particle; props.add( new GenericProperty( pt, xmlEl.getName(), null, xmlEl.getAttributes(), xmlEl.getChildren() ) ); } else { props.add( new GenericProperty( pt, pt.getName(), particle ) ); } } } private List<TypedObjectNode> buildParticles( Mapping mapping, ResultSet rs, LinkedHashMap<String, Integer> colToRsIdx ) throws SQLException { if ( mapping.getJoinedTable() != null ) { List<TypedObjectNode> values = new ArrayList<TypedObjectNode>(); ResultSet rs2 = null; try { Pair<ResultSet, LinkedHashMap<String, Integer>> p = getJoinedResultSet( mapping.getJoinedTable().get( 0 ), mapping, rs, colToRsIdx ); rs2 = p.first; while ( rs2.next() ) { TypedObjectNode particle = buildParticle( mapping, rs2, p.second ); if ( particle != null ) { values.add( buildParticle( mapping, rs2, p.second ) ); } } } finally { if ( rs2 != null ) { rs2.close(); } } return values; } TypedObjectNode particle = buildParticle( mapping, rs, colToRsIdx ); if ( particle != null ) { return Collections.singletonList( buildParticle( mapping, rs, colToRsIdx ) ); } return Collections.emptyList(); } private TypedObjectNode buildParticle( Mapping mapping, ResultSet rs, LinkedHashMap<String, Integer> colToRsIdx ) throws SQLException { TypedObjectNode particle = null; if ( mapping instanceof PrimitiveMapping ) { PrimitiveMapping pm = (PrimitiveMapping) mapping; MappingExpression me = pm.getMapping(); if ( me instanceof DBField ) { Object value = rs.getObject( colToRsIdx.get( ( (DBField) me ).getColumn() ) ); if ( value != null ) { particle = new PrimitiveValue( value, pm.getType() ); } } } else if ( mapping instanceof GeometryMapping ) { GeometryMapping pm = (GeometryMapping) mapping; MappingExpression me = pm.getMapping(); if ( me instanceof DBField ) { byte[] wkb = rs.getBytes( colToRsIdx.get( fs.getSQLValueMapper().selectGeometry( ( (DBField) me ).getColumn() ) ) ); if ( wkb != null ) { try { particle = WKBReader.read( wkb, pm.getCRS() ); } catch ( ParseException e ) { throw new SQLException( "Error parsing WKB from database: " + e.getMessage(), e ); } } } } else if ( mapping instanceof FeatureMapping ) { FeatureMapping fm = (FeatureMapping) mapping; MappingExpression me = fm.getMapping(); if ( me instanceof DBField ) { Object value = rs.getObject( colToRsIdx.get( ( (DBField) me ).getColumn() ) ); if ( value != null ) { // TODO String ref = "#" + value; particle = new FeatureReference( fs.getResolver(), ref, null ); } } me = fm.getHrefMapping(); if ( me instanceof DBField ) { String value = rs.getString( colToRsIdx.get( ( (DBField) me ).getColumn() ) ); if ( value != null ) { particle = new FeatureReference( fs.getResolver(), value, null ); } } } else if ( mapping instanceof ConstantMapping<?> ) { particle = ( (ConstantMapping<?>) mapping ).getValue(); } else if ( mapping instanceof CompoundMapping ) { CompoundMapping cm = (CompoundMapping) mapping; Map<QName, PrimitiveValue> attrs = new HashMap<QName, PrimitiveValue>(); List<TypedObjectNode> children = new ArrayList<TypedObjectNode>(); for ( Mapping particleMapping : cm.getParticles() ) { List<TypedObjectNode> particleValues = buildParticles( particleMapping, rs, colToRsIdx ); Expr xpath = particleMapping.getPath().getAsXPath(); if ( xpath instanceof LocationPath ) { LocationPath lp = (LocationPath) xpath; if ( lp.getSteps().size() != 1 ) { LOG.warn( "Unhandled location path: '" + particleMapping.getPath() + "'. Only single step paths are handled." ); continue; } if ( lp.isAbsolute() ) { LOG.warn( "Unhandled location path: '" + particleMapping.getPath() + "'. Only relative paths are handled." ); continue; } Step step = (Step) lp.getSteps().get( 0 ); if ( !step.getPredicates().isEmpty() ) { LOG.warn( "Unhandled location path: '" + particleMapping.getPath() + "'. Only unpredicated steps are handled." ); continue; } if ( step instanceof TextNodeStep ) { for ( TypedObjectNode particleValue : particleValues ) { children.add( particleValue ); } } else if ( step instanceof NameStep ) { NameStep ns = (NameStep) step; QName name = getQName( ns ); if ( step.getAxis() == Axis.ATTRIBUTE ) { for ( TypedObjectNode particleValue : particleValues ) { if ( particleValue instanceof PrimitiveValue ) { attrs.put( name, (PrimitiveValue) particleValue ); } else { LOG.warn( "Value not suitable for attribute." ); } } } else if ( step.getAxis() == Axis.CHILD ) { for ( TypedObjectNode particleValue : particleValues ) { if ( particleValue instanceof PrimitiveValue ) { // TODO XSElementDeclaration childType = null; GenericXMLElement child = new GenericXMLElement( name, childType, Collections.<QName, PrimitiveValue> emptyMap(), Collections.singletonList( particleValue ) ); children.add( child ); } else if ( particleValue != null ) { children.add( particleValue ); } } } else { LOG.warn( "Unhandled axis type '" + step.getAxis() + "' for path: '" + particleMapping.getPath() + "'" ); } } else { // TODO handle other steps as self() for ( TypedObjectNode particleValue : particleValues ) { children.add( particleValue ); } } } else { LOG.warn( "Unhandled mapping type '" + particleMapping.getClass() + "' for path: '" + particleMapping.getPath() + "'" ); } } // TODO XSElementDeclaration xsType = null; if ( ( !attrs.isEmpty() ) || !children.isEmpty() ) { particle = new GenericXMLElement( cm.getPath().getAsQName(), xsType, attrs, children ); } } else { LOG.warn( "Handling of '" + mapping.getClass() + "' mappings is not implemented yet." ); } return particle; } private Pair<ResultSet, LinkedHashMap<String, Integer>> getJoinedResultSet( TableJoin jc, Mapping mapping, ResultSet rs, LinkedHashMap<String, Integer> colToRsIdx ) throws SQLException { LinkedHashMap<String, Integer> rsToIdx = getSubsequentSelectColumns( mapping ); StringBuilder sql = new StringBuilder( "SELECT " ); boolean first = true; for ( String column : rsToIdx.keySet() ) { if ( !first ) { sql.append( ',' ); } sql.append( column ); first = false; } sql.append( " FROM " ); sql.append( jc.getToTable() ); sql.append( " WHERE " ); first = true; for ( String keyColumn : jc.getToColumns() ) { if ( !first ) { sql.append( " AND " ); } sql.append( keyColumn ); sql.append( " = ?" ); first = false; } LOG.debug( "SQL: {}", sql ); PreparedStatement stmt = null; ResultSet rs2 = null; try { long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing subsequent SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; for ( String keyColumn : jc.getFromColumns() ) { Object key = rs.getObject( colToRsIdx.get( keyColumn ) ); LOG.debug( "? = '{}' ({})", key, keyColumn ); stmt.setObject( i++, key ); } begin = System.currentTimeMillis(); rs2 = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); } catch ( Throwable t ) { close( rs2, stmt, null, LOG ); String msg = "Error performing subsequent SELECT: " + t.getMessage(); LOG.error( msg, t ); throw new SQLException( msg, t ); } return new Pair<ResultSet, LinkedHashMap<String, Integer>>( rs2, rsToIdx ); } private QName getQName( NameStep step ) { String prefix = step.getPrefix(); QName qName; if ( prefix.isEmpty() ) { qName = new QName( step.getLocalName() ); } else { String ns = nsBindings.translateNamespacePrefixToUri( prefix ); qName = new QName( ns, step.getLocalName(), prefix ); } return qName; } }
also close statement
deegree-datastores/deegree-featurestore/deegree-featurestore-commons/src/main/java/org/deegree/feature/persistence/sql/rules/FeatureBuilderRelational.java
also close statement
<ide><path>eegree-datastores/deegree-featurestore/deegree-featurestore-commons/src/main/java/org/deegree/feature/persistence/sql/rules/FeatureBuilderRelational.java <ide> } <ide> } finally { <ide> if ( rs2 != null ) { <add> rs2.getStatement().close(); <ide> rs2.close(); <ide> } <ide> }