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
JavaScript
mit
88a9eeab2bf792f3830167ab2b2328e72878ee72
0
Baptouuuu/Sy,Baptouuuu/Sy
namespace('Sy.Validator.Constraint'); /** * Date constraint validator * * @package Sy * @subpackage Validator * @class * @extends {Sy.Validator.AbstractConstraintValidator} */ Sy.Validator.Constraint.DateValidator = function () { Sy.Validator.AbstractConstraintValidator.call(this); }; Sy.Validator.Constraint.DateValidator.prototype = Object.create(Sy.Validator.AbstractConstraintValidator.prototype, { /** * @inheritDoc */ validate: { value: function (value, constraint) { if (!(constraint instanceof Sy.Validator.Constraint.Date)) { throw new TypeError('Invalid constraint'); } if (typeof value === 'string') { if ((new Date(value)).toDateString() === 'Invalid Date') { this.context.addViolation(constraint.getMessage()); } } else if (!(value instanceof Date)) { this.context.addViolation(constraint.getMessage()); } } } });
src/Validator/Constraint/DateValidator.js
namespace('Sy.Validator.Constraint'); /** * Date constraint validator * * @package Sy * @subpackage Validator * @class * @extends {Sy.Validator.AbstractConstraintValidator} */ Sy.Validator.Constraint.DateValidator = function () { Sy.Validator.AbstractConstraintValidator.call(this); }; Sy.Validator.Constraint.DateValidator.prototype = Object.create(Sy.Validator.AbstractConstraintValidator.prototype, { /** * @inheritDoc */ validate: { value: function (value, constraint) { if (!(constraint instanceof Sy.Validator.Constraint.Date)) { throw new TypeError('Invalid constraint'); } if (typeof value === 'string' && (new Date(value)).toDateString() === 'Invalid Date') { this.context.addViolation(constraint.getMessage()); } else if (!(value instanceof Date)) { this.context.addViolation(constraint.getMessage()); } } } });
#15 fixed an error causing a valid date string to be flagged as violation
src/Validator/Constraint/DateValidator.js
#15 fixed an error causing a valid date string to be flagged as violation
<ide><path>rc/Validator/Constraint/DateValidator.js <ide> throw new TypeError('Invalid constraint'); <ide> } <ide> <del> if (typeof value === 'string' && (new Date(value)).toDateString() === 'Invalid Date') { <del> this.context.addViolation(constraint.getMessage()); <add> if (typeof value === 'string') { <add> if ((new Date(value)).toDateString() === 'Invalid Date') { <add> this.context.addViolation(constraint.getMessage()); <add> } <ide> } else if (!(value instanceof Date)) { <ide> this.context.addViolation(constraint.getMessage()); <ide> }
JavaScript
mit
3cc89b4157bc33579292e49148c289a7d2003129
0
AdapTeach/code-assessments
module.exports = { dbUrl: 'mongodb://Charl:[email protected]:39277/codeassessments', dbRoot : 'admin', dbPassword :'KAPDyGr4G2Rp', crossOrigin: '', port: process.env.OPENSHIFT_NODEJS_PORT || 8080, address : process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1" };
config/env/production.js
module.exports = { dbUrl: 'mongodb://Charl:[email protected]:39277/codeassessments', dbRoot : 'admin', dbPassword :'KAPDyGr4G2Rp', crossOrigin: '', port: process.env.OPENSHIFT_NODEJS_PORT || 8080, address : process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1" };
deployment fixes
config/env/production.js
deployment fixes
<ide><path>onfig/env/production.js <ide> module.exports = { <del> dbUrl: 'mongodb://Charl:[email protected]:39277/codeassessments', <add> dbUrl: 'mongodb://Charl:[email protected]:39277/codeassessments', <ide> dbRoot : 'admin', <ide> dbPassword :'KAPDyGr4G2Rp', <ide> crossOrigin: '',
Java
apache-2.0
error: pathspec 'com/planet_ink/coffee_mud/Commands/GenPortal.java' did not match any file(s) known to git
f2eb5d8bc3a4b76eb52a2451c63f9cf2c76b15d4
1
bozimmerman/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud
package com.planet_ink.coffee_mud.Commands; public class GenPortal { }
com/planet_ink/coffee_mud/Commands/GenPortal.java
git-svn-id: svn://192.168.1.10/public/CoffeeMud@3539 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Commands/GenPortal.java
<ide><path>om/planet_ink/coffee_mud/Commands/GenPortal.java <add>package com.planet_ink.coffee_mud.Commands; <add> <add>public class GenPortal <add>{ <add>}
Java
bsd-3-clause
a0bca5ff529ebf9af4ce631880c85e3b365254d0
0
knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org
/* * Copyright (c) 2008-2010, KNOPFLERFISH project * 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 KNOPFLERFISH 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. */ package org.knopflerfish.framework.permissions; import java.lang.reflect.*; import java.security.*; import java.util.*; import org.osgi.framework.Bundle; import org.osgi.service.condpermadmin.*; import org.osgi.service.permissionadmin.PermissionInfo; import org.knopflerfish.framework.Debug; import org.knopflerfish.framework.FrameworkContext; /** * A binding of a set of Conditions to a set of Permissions. * */ class ConditionalPermissionInfoImpl implements ConditionalPermissionInfo { private ConditionalPermissionInfoStorage cpis; final private ConditionInfo [] conditionInfos; final private PermissionInfo [] permissionInfos; final private String access; final private FrameworkContext framework; final private Debug debug; private String name; private PermissionCollection permissions; /** */ ConditionalPermissionInfoImpl(ConditionalPermissionInfoStorage cpis, String name, ConditionInfo [] conds, PermissionInfo [] perms, String access, FrameworkContext fw) { this.cpis = cpis; this.name = name; conditionInfos = conds; permissionInfos = perms; this.access = access; framework = fw; debug = fw.debug; permissions = null; } /** */ ConditionalPermissionInfoImpl(ConditionalPermissionInfoStorage cpis, String encoded, FrameworkContext fw) { this.cpis = cpis; framework = fw; debug = fw.debug; try { char [] eca = encoded.toCharArray(); int pos = PermUtil.skipWhite(eca, 0); if ((eca[pos] == 'A' || eca[pos] == 'a') && (eca[pos+1] == 'L' || eca[pos+1] == 'l') && (eca[pos+2] == 'L' || eca[pos+2] == 'l') && (eca[pos+3] == 'O' || eca[pos+3] == 'o') && (eca[pos+4] == 'W' || eca[pos+4] == 'w') && eca[pos+5] == ' ') { pos += 6; access = ConditionalPermissionInfo.ALLOW; } else if ((eca[pos] == 'D' || eca[pos] == 'd') && (eca[pos+1] == 'E' || eca[pos+1] == 'e') && (eca[pos+2] == 'N' || eca[pos+2] == 'n') && (eca[pos+3] == 'Y' || eca[pos+3] == 'y') && eca[pos+4] == ' ') { pos += 5; access = ConditionalPermissionInfo.DENY; } else { throw new IllegalArgumentException("Access must be allow or deny"); } pos = PermUtil.skipWhite(eca, pos); if (eca[pos++] != '{') { throw new IllegalArgumentException("Missing open brace"); } ArrayList cal = new ArrayList(); ArrayList pal = new ArrayList(); boolean seenPermInfo = false; while (true) { pos = PermUtil.skipWhite(eca, pos); char c = eca[pos]; char ec; if (!seenPermInfo && c == '[') { ec = ']'; } else if (c == '(') { ec = ')'; seenPermInfo = true; } else if (c == '}') { pos++; break; } else { throw new IllegalArgumentException("Unexpected char '" + c + "' at pos " + pos); } int start_pos = pos++; do { c = eca[pos]; if (c == '"') { pos = PermUtil.unquote(eca, pos, null); } else { pos++; } } while(c != ec); String info = new String(eca, start_pos, pos - start_pos); if (c == ']') { cal.add(new ConditionInfo(info)); } else { pal.add(new PermissionInfo(info)); } } if (!seenPermInfo) { throw new IllegalArgumentException("Permissions must contain atleast one element"); } pos = PermUtil.endOfString(eca, pos, eca.length); if (pos != -1) { StringBuffer buf = new StringBuffer(); pos = PermUtil.unquote(eca, pos, buf); name = buf.toString(); if ((pos = PermUtil.endOfString(eca, pos, eca.length)) != -1) { throw new IllegalArgumentException("Unexpected characters at end of string: " + new String(eca, pos, eca.length - pos)); } } else { name = null; } conditionInfos = (ConditionInfo [])cal.toArray(new ConditionInfo [cal.size()]); permissionInfos = (PermissionInfo [])pal.toArray(new PermissionInfo [pal.size()]); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Unexpected end of string"); } } // Interface ConditionalPermissionInfo /** * Returns the Condition Infos for the Conditions that must be satisfied to * enable the Permissions. * * @return The Condition Infos for the Conditions in this Conditional * Permission Info. */ public ConditionInfo[] getConditionInfos() { return conditionInfos; } /** * Returns the Permission Infos for the Permission in this Conditional * Permission Info. * * @return The Permission Infos for the Permission in this Conditional * Permission Info. */ public PermissionInfo[] getPermissionInfos() { return permissionInfos; } /** * Removes this Conditional Permission Info from the Conditional Permission * Admin. * * @throws SecurityException If the caller does not have * <code>AllPermission</code>. */ public void delete() { if (cpis == null) { throw new UnsupportedOperationException("Not in use"); } cpis.remove(this); } /** * Returns the name of this Conditional Permission Info. * * @return The name of this Conditional Permission Info. */ public String getName() { return name; } public String getAccessDecision() { return access; } public String getEncoded() { StringBuffer res = new StringBuffer(access); res.append(" { "); if (conditionInfos != null) { for (int i = 0; i < conditionInfos.length; i++) { res.append(conditionInfos[i].getEncoded()); res.append(' '); } } if (permissionInfos != null) { for (int i = 0; i < permissionInfos.length; i++) { res.append(permissionInfos[i].getEncoded()); res.append(' '); } } res.append('}'); if (name != null) { res.append(' '); PermUtil.quote(name, res); } return res.toString(); } /** * Returns a string representation of this object. * */ public String toString() { return getEncoded(); } /** * */ public final boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } ConditionalPermissionInfo cpi = (ConditionalPermissionInfo)obj; if (name == null ? cpi.getName() != null : !name.equals(cpi.getName())) { return false; } // NYI, we should allow permuted arrays, also affects hashCode. if (!Arrays.equals(permissionInfos, cpi.getPermissionInfos())) { return false; } if (!Arrays.equals(conditionInfos, cpi.getConditionInfos())) { return false; } return access == cpi.getAccessDecision(); } /** * */ public final int hashCode() { if (name != null) { return name.hashCode(); } int res = conditionInfos != null && conditionInfos.length > 0 ? conditionInfos[0].hashCode() : 0; return res + permissionInfos[0].hashCode(); } // // Package methods // static final Class[] argClasses = new Class[] {Bundle.class, ConditionInfo.class}; /** * */ ConditionalPermission getConditionalPermission(Bundle bundle) { String me = "ConditionalPermissionInfoImpl.getConditionalPermission: "; ArrayList conds = new ArrayList(conditionInfos.length); for (int i = 0; i < conditionInfos.length; i++) { Class clazz; Condition c; try { clazz = Class.forName(conditionInfos[i].getType(), true, framework.getClassLoader(null)); Constructor cons = null; Method method = null; try { method = clazz.getMethod("getCondition", argClasses); if ((method.getModifiers() & Modifier.STATIC) == 0) { method = null; } } catch (NoSuchMethodException ignore) { } if (method != null) { if (debug.permissions) { debug.println(me + "Invoke, " + method + " for bundle " + bundle); } c = (Condition) method.invoke(null, new Object [] {bundle, conditionInfos[i]}); } else { try { cons = clazz.getConstructor(argClasses); } catch (NoSuchMethodException ignore) { } if (cons != null) { if (debug.permissions) { debug.println(me + "Construct, " + cons + " for bundle " + bundle); } c = (Condition) cons.newInstance(new Object [] {bundle, conditionInfos[i]}); } else { debug.println("NYI! Log faulty ConditionInfo object!?"); continue; } } if (!c.isMutable()) { if (!c.isPostponed() /* || debug.tck401compat */ ) { if (c.isSatisfied()) { if (debug.permissions) { debug.println(me + "Immutable condition ok, continue"); } continue; } else { if (debug.permissions) { debug.println(me + "Immutable condition NOT ok, abort"); } return null; } } } conds.add(c); } catch (Throwable t) { debug.printStackTrace("NYI! Log failed Condition creation", t); return null; } } return new ConditionalPermission((Condition [])conds.toArray(new Condition[conds.size()]), getPermissions(), access, this); } /** * */ PermissionCollection getPermissions() { if (permissions == null) { permissions = new PermissionInfoPermissions(framework, null, permissionInfos); } return permissions; } /** * Set storage for this Conditional Permission Info. * */ void setPermissionInfoStorage(ConditionalPermissionInfoStorage storage) { cpis = storage; } /** * Set the name of this Conditional Permission Info. * */ void setName(String newName) { name = newName; } }
osgi/framework/src/org/knopflerfish/framework/permissions/ConditionalPermissionInfoImpl.java
/* * Copyright (c) 2008-2010, KNOPFLERFISH project * 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 KNOPFLERFISH 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. */ package org.knopflerfish.framework.permissions; import java.lang.reflect.*; import java.security.*; import java.util.*; import org.osgi.framework.Bundle; import org.osgi.service.condpermadmin.*; import org.osgi.service.permissionadmin.PermissionInfo; import org.knopflerfish.framework.Debug; import org.knopflerfish.framework.FrameworkContext; /** * A binding of a set of Conditions to a set of Permissions. * */ class ConditionalPermissionInfoImpl implements ConditionalPermissionInfo { private ConditionalPermissionInfoStorage cpis; final private ConditionInfo [] conditionInfos; final private PermissionInfo [] permissionInfos; final private String access; final private FrameworkContext framework; final private Debug debug; private String name; private PermissionCollection permissions; /** */ ConditionalPermissionInfoImpl(ConditionalPermissionInfoStorage cpis, String name, ConditionInfo [] conds, PermissionInfo [] perms, String access, FrameworkContext fw) { this.cpis = cpis; this.name = name; conditionInfos = conds; permissionInfos = perms; this.access = access; framework = fw; debug = fw.debug; permissions = null; } /** */ ConditionalPermissionInfoImpl(ConditionalPermissionInfoStorage cpis, String encoded, FrameworkContext fw) { this.cpis = cpis; framework = fw; debug = fw.debug; try { char [] eca = encoded.toCharArray(); int pos = PermUtil.skipWhite(eca, 0); if ((eca[pos] == 'A' || eca[pos] == 'a') && (eca[pos+1] == 'L' || eca[pos+1] == 'l') && (eca[pos+2] == 'L' || eca[pos+2] == 'l') && (eca[pos+3] == 'O' || eca[pos+3] == 'o') && (eca[pos+4] == 'W' || eca[pos+4] == 'w') && eca[pos+5] == ' ') { pos += 6; access = ConditionalPermissionInfo.ALLOW; } else if ((eca[pos] == 'D' || eca[pos] == 'd') && (eca[pos+1] == 'E' || eca[pos+1] == 'e') && (eca[pos+2] == 'N' || eca[pos+2] == 'n') && (eca[pos+3] == 'Y' || eca[pos+3] == 'y') && eca[pos+4] == ' ') { pos += 5; access = ConditionalPermissionInfo.DENY; } else { throw new IllegalArgumentException("Access must be allow or deny"); } pos = PermUtil.skipWhite(eca, pos); if (eca[pos++] != '{') { throw new IllegalArgumentException("Missing open brace"); } ArrayList cal = new ArrayList(); ArrayList pal = new ArrayList(); boolean seenPermInfo = false; while (true) { pos = PermUtil.skipWhite(eca, pos); char c = eca[pos]; char ec; if (!seenPermInfo && c == '[') { ec = ']'; } else if (c == '(') { ec = ')'; seenPermInfo = true; } else if (c == '}') { pos++; break; } else { throw new IllegalArgumentException("Unexpected char '" + c + "' at pos " + pos); } int start_pos = pos++; do { c = eca[pos]; if (c == '"') { pos = PermUtil.unquote(eca, pos, null); } else { pos++; } } while(c != ec); String info = new String(eca, start_pos, pos - start_pos); if (c == ']') { cal.add(new ConditionInfo(info)); } else { pal.add(new PermissionInfo(info)); } } if (!seenPermInfo) { throw new IllegalArgumentException("Permissions must contain atleast one element"); } pos = PermUtil.endOfString(eca, pos, eca.length); if (pos != -1) { StringBuffer buf = new StringBuffer(); PermUtil.unquote(eca, pos, buf); name = buf.toString(); if ((pos = PermUtil.endOfString(eca, pos, eca.length)) != -1) { throw new IllegalArgumentException("Unexpected characters at end of string: " + new String(eca, pos, eca.length - pos)); } } else { name = null; } conditionInfos = (ConditionInfo [])cal.toArray(new ConditionInfo [cal.size()]); permissionInfos = (PermissionInfo [])pal.toArray(new PermissionInfo [pal.size()]); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Unexpected end of string"); } } // Interface ConditionalPermissionInfo /** * Returns the Condition Infos for the Conditions that must be satisfied to * enable the Permissions. * * @return The Condition Infos for the Conditions in this Conditional * Permission Info. */ public ConditionInfo[] getConditionInfos() { return conditionInfos; } /** * Returns the Permission Infos for the Permission in this Conditional * Permission Info. * * @return The Permission Infos for the Permission in this Conditional * Permission Info. */ public PermissionInfo[] getPermissionInfos() { return permissionInfos; } /** * Removes this Conditional Permission Info from the Conditional Permission * Admin. * * @throws SecurityException If the caller does not have * <code>AllPermission</code>. */ public void delete() { if (cpis == null) { throw new UnsupportedOperationException("Not in use"); } cpis.remove(this); } /** * Returns the name of this Conditional Permission Info. * * @return The name of this Conditional Permission Info. */ public String getName() { return name; } public String getAccessDecision() { return access; } public String getEncoded() { StringBuffer res = new StringBuffer(access); res.append(" { "); if (conditionInfos != null) { for (int i = 0; i < conditionInfos.length; i++) { res.append(conditionInfos[i].getEncoded()); res.append(' '); } } if (permissionInfos != null) { for (int i = 0; i < permissionInfos.length; i++) { res.append(permissionInfos[i].getEncoded()); res.append(' '); } } res.append('}'); if (name != null) { res.append(' '); PermUtil.quote(name, res); } return res.toString(); } /** * Returns a string representation of this object. * */ public String toString() { return getEncoded(); } /** * */ public final boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } ConditionalPermissionInfo cpi = (ConditionalPermissionInfo)obj; if (name == null ? cpi.getName() != null : !name.equals(cpi.getName())) { return false; } // NYI, we should allow permuted arrays, also affects hashCode. if (!Arrays.equals(permissionInfos, cpi.getPermissionInfos())) { return false; } if (!Arrays.equals(conditionInfos, cpi.getConditionInfos())) { return false; } return access == cpi.getAccessDecision(); } /** * */ public final int hashCode() { if (name != null) { return name.hashCode(); } int res = conditionInfos != null && conditionInfos.length > 0 ? conditionInfos[0].hashCode() : 0; return res + permissionInfos[0].hashCode(); } // // Package methods // static final Class[] argClasses = new Class[] {Bundle.class, ConditionInfo.class}; /** * */ ConditionalPermission getConditionalPermission(Bundle bundle) { String me = "ConditionalPermissionInfoImpl.getConditionalPermission: "; ArrayList conds = new ArrayList(conditionInfos.length); for (int i = 0; i < conditionInfos.length; i++) { Class clazz; Condition c; try { clazz = Class.forName(conditionInfos[i].getType(), true, framework.getClassLoader(null)); Constructor cons = null; Method method = null; try { method = clazz.getMethod("getCondition", argClasses); if ((method.getModifiers() & Modifier.STATIC) == 0) { method = null; } } catch (NoSuchMethodException ignore) { } if (method != null) { if (debug.permissions) { debug.println(me + "Invoke, " + method + " for bundle " + bundle); } c = (Condition) method.invoke(null, new Object [] {bundle, conditionInfos[i]}); } else { try { cons = clazz.getConstructor(argClasses); } catch (NoSuchMethodException ignore) { } if (cons != null) { if (debug.permissions) { debug.println(me + "Construct, " + cons + " for bundle " + bundle); } c = (Condition) cons.newInstance(new Object [] {bundle, conditionInfos[i]}); } else { debug.println("NYI! Log faulty ConditionInfo object!?"); continue; } } if (!c.isMutable()) { if (!c.isPostponed() /* || debug.tck401compat */ ) { if (c.isSatisfied()) { if (debug.permissions) { debug.println(me + "Immutable condition ok, continue"); } continue; } else { if (debug.permissions) { debug.println(me + "Immutable condition NOT ok, abort"); } return null; } } } conds.add(c); } catch (Throwable t) { debug.printStackTrace("NYI! Log failed Condition creation", t); return null; } } return new ConditionalPermission((Condition [])conds.toArray(new Condition[conds.size()]), getPermissions(), access, this); } /** * */ PermissionCollection getPermissions() { if (permissions == null) { permissions = new PermissionInfoPermissions(framework, null, permissionInfos); } return permissions; } /** * Set storage for this Conditional Permission Info. * */ void setPermissionInfoStorage(ConditionalPermissionInfoStorage storage) { cpis = storage; } /** * Set the name of this Conditional Permission Info. * */ void setName(String newName) { name = newName; } }
fix for bug when using names for encoded policies
osgi/framework/src/org/knopflerfish/framework/permissions/ConditionalPermissionInfoImpl.java
fix for bug when using names for encoded policies
<ide><path>sgi/framework/src/org/knopflerfish/framework/permissions/ConditionalPermissionInfoImpl.java <ide> pos = PermUtil.endOfString(eca, pos, eca.length); <ide> if (pos != -1) { <ide> StringBuffer buf = new StringBuffer(); <del> PermUtil.unquote(eca, pos, buf); <add> pos = PermUtil.unquote(eca, pos, buf); <ide> name = buf.toString(); <ide> if ((pos = PermUtil.endOfString(eca, pos, eca.length)) != -1) { <ide> throw new IllegalArgumentException("Unexpected characters at end of string: " +
JavaScript
mit
f2e87c56af691fc01fab09d301d92b0b5e572e2f
0
ADI-Labs/calendar-web,ADI-Labs/calendar-web
"use strict"; var path = require("path"); var assetsPath = path.resolve("src/assets"); var srcPath = path.resolve("src"); var HtmlWebpackPlugin = require("html-webpack-plugin"); var autoprefixer = require("autoprefixer"); var webpack = require("webpack"); module.exports = { debug: true, devtool: "#source-map", devServer: { // contentBase technically not needed... // b/c everything is served from mem contentBase: path.resolve("dist"), historyApiFallback: true, hot: true, proxy: { "/api/*": "http://localhost:5000" }, stats: { chunks: false } }, resolve: { // for big apps, resolve the top level directories // alias: { // "assets": assetsPath // }, root: srcPath }, entry: [ "babel-polyfill", "webpack-hot-middleware/client", path.resolve(srcPath, "index") ], output: { filename: "[name].bundle.js", path: path.resolve("dist"), pathinfo: true, publicPath: "/" }, module: { loaders: [{ test: /\.js$/, include: srcPath, loader: "babel" }, { test: /\.css$/, include: path.resolve(assetsPath, "css"), loaders: [ "style", "css", "postcss" ] }, { test: /\.styl$/, include: path.resolve(assetsPath, "styles"), loaders: [ "style", "css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]", "postcss", "stylus" ] }, { test: /\.json$/, include: assetsPath, loader: "json" }, { test: /\.(jpe?g|png|gif|svg)$/i, include: assetsPath, loader: "file" }] }, postcss: [autoprefixer], plugins: [ new HtmlWebpackPlugin({ favicon: path.resolve(assetsPath, "images/favicon.png"), template: path.resolve(assetsPath, "index.html") }), new webpack.DefinePlugin({ "__DEV__": true }), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.ProgressPlugin(function(percentage, message) { process.stderr.write(message + "\r"); }), new webpack.ProvidePlugin({ "fetch": "isomorphic-fetch" }) ] }
webpack.config/webpack.config.dev.js
"use strict"; var path = require("path"); var assetsPath = path.resolve("src/assets"); var srcPath = path.resolve("src"); var HtmlWebpackPlugin = require("html-webpack-plugin"); var autoprefixer = require("autoprefixer"); var webpack = require("webpack"); module.exports = { debug: true, devtool: "#source-map", devServer: { // contentBase technically not needed... // b/c everything is served from mem contentBase: path.resolve("dist"), historyApiFallback: true, hot: true, proxy: { "/api/*": "http://localhost:5000" }, stats: { chunks: false } }, resolve: { // for big apps, resolve the top level directories // alias: { // "assets": assetsPath // }, root: srcPath }, entry: [ "babel-polyfill", "webpack-hot-middleware/client", path.resolve(srcPath, "index") ], output: { filename: "[name].bundle.js", path: path.resolve("dist"), pathinfo: true, publicPath: "/", // sourceMapFilename must be named 'index' for sourcemapping to work. fucking stupid. sourceMapFilename: "index.js.map" }, module: { loaders: [{ test: /\.js$/, include: srcPath, loader: "babel" }, { test: /\.css$/, include: path.resolve(assetsPath, "css"), loaders: [ "style", "css", "postcss" ] }, { test: /\.styl$/, include: path.resolve(assetsPath, "styles"), loaders: [ "style", "css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]", "postcss", "stylus" ] }, { test: /\.json$/, include: assetsPath, loader: "json" }, { test: /\.(jpe?g|png|gif|svg)$/i, include: assetsPath, loader: "file" }] }, postcss: [autoprefixer], plugins: [ new HtmlWebpackPlugin({ favicon: path.resolve(assetsPath, "images/favicon.png"), template: path.resolve(assetsPath, "index.html") }), new webpack.DefinePlugin({ "__DEV__": true }), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.ProgressPlugin(function(percentage, message) { process.stderr.write(message + "\r"); }), new webpack.ProvidePlugin({ "fetch": "isomorphic-fetch" }) ] }
Update webpack.config.dev.js
webpack.config/webpack.config.dev.js
Update webpack.config.dev.js
<ide><path>ebpack.config/webpack.config.dev.js <ide> filename: "[name].bundle.js", <ide> path: path.resolve("dist"), <ide> pathinfo: true, <del> publicPath: "/", <del> // sourceMapFilename must be named 'index' for sourcemapping to work. fucking stupid. <del> sourceMapFilename: "index.js.map" <add> publicPath: "/" <ide> }, <ide> module: { <ide> loaders: [{
Java
apache-2.0
bf5cca52a439b20cd8e009a2d2ad63bef8282eac
0
abstractj/keycloak,mposolda/keycloak,mposolda/keycloak,raehalme/keycloak,pedroigor/keycloak,hmlnarik/keycloak,keycloak/keycloak,thomasdarimont/keycloak,reneploetz/keycloak,ahus1/keycloak,jpkrohling/keycloak,jpkrohling/keycloak,darranl/keycloak,raehalme/keycloak,keycloak/keycloak,ahus1/keycloak,jpkrohling/keycloak,vmuzikar/keycloak,ssilvert/keycloak,raehalme/keycloak,ahus1/keycloak,reneploetz/keycloak,raehalme/keycloak,ssilvert/keycloak,srose/keycloak,ssilvert/keycloak,mhajas/keycloak,pedroigor/keycloak,srose/keycloak,brat000012001/keycloak,hmlnarik/keycloak,brat000012001/keycloak,brat000012001/keycloak,ahus1/keycloak,pedroigor/keycloak,thomasdarimont/keycloak,brat000012001/keycloak,hmlnarik/keycloak,vmuzikar/keycloak,jpkrohling/keycloak,keycloak/keycloak,thomasdarimont/keycloak,stianst/keycloak,ahus1/keycloak,mposolda/keycloak,thomasdarimont/keycloak,hmlnarik/keycloak,vmuzikar/keycloak,abstractj/keycloak,stianst/keycloak,srose/keycloak,keycloak/keycloak,darranl/keycloak,pedroigor/keycloak,abstractj/keycloak,srose/keycloak,jpkrohling/keycloak,reneploetz/keycloak,mposolda/keycloak,reneploetz/keycloak,darranl/keycloak,vmuzikar/keycloak,hmlnarik/keycloak,mhajas/keycloak,pedroigor/keycloak,brat000012001/keycloak,mhajas/keycloak,abstractj/keycloak,darranl/keycloak,mhajas/keycloak,srose/keycloak,ssilvert/keycloak,pedroigor/keycloak,mhajas/keycloak,thomasdarimont/keycloak,stianst/keycloak,stianst/keycloak,raehalme/keycloak,abstractj/keycloak,raehalme/keycloak,vmuzikar/keycloak,mposolda/keycloak,keycloak/keycloak,reneploetz/keycloak,ssilvert/keycloak,stianst/keycloak,mposolda/keycloak,hmlnarik/keycloak,thomasdarimont/keycloak,ahus1/keycloak,vmuzikar/keycloak
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.pages.social; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import static org.keycloak.testsuite.util.UIUtils.clickLink; import static org.keycloak.testsuite.util.URLUtils.navigateToUri; import static org.keycloak.testsuite.util.WaitUtils.pause; /** * @author Vaclav Muzikar <[email protected]> */ public class GoogleLoginPage extends AbstractSocialLoginPage { @FindBy(id = "identifierId") private WebElement emailInput; @FindBy(xpath = ".//input[@type='password']") private WebElement passwordInput; @FindBy(xpath = "//form//ul/li/div[@role='link']") private List<WebElement> selectAccountLinks; @Override public void login(String user, String password) { if (selectAccountLinks.size() > 1) { clickLink(selectAccountLinks.get(selectAccountLinks.size() - 1)); } emailInput.clear(); emailInput.sendKeys(user); emailInput.sendKeys(Keys.RETURN); pause(3000); // wait for some animation or whatever passwordInput.sendKeys(password); passwordInput.sendKeys(Keys.RETURN); } @Override public void logout() { log.info("performing logout from Google"); navigateToUri("https://www.google.com/accounts/Logout"); } }
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/social/GoogleLoginPage.java
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.pages.social; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import static org.keycloak.testsuite.util.UIUtils.clickLink; import static org.keycloak.testsuite.util.UIUtils.performOperationWithPageReload; import static org.keycloak.testsuite.util.URLUtils.navigateToUri; /** * @author Vaclav Muzikar <[email protected]> */ public class GoogleLoginPage extends AbstractSocialLoginPage { @FindBy(id = "identifierId") private WebElement emailInput; @FindBy(xpath = ".//input[@type='password']") private WebElement passwordInput; @FindBy(xpath = "//form//ul/li/div[@role='link']") private List<WebElement> selectAccountLinks; @Override public void login(String user, String password) { if (selectAccountLinks.size() > 1) { clickLink(selectAccountLinks.get(selectAccountLinks.size() - 1)); } emailInput.clear(); emailInput.sendKeys(user); performOperationWithPageReload(() -> emailInput.sendKeys(Keys.RETURN)); passwordInput.sendKeys(password); passwordInput.sendKeys(Keys.RETURN); } @Override public void logout() { log.info("performing logout from Google"); navigateToUri("https://www.google.com/accounts/Logout"); } }
KEYCLOAK-11675 Fix unstable Google Social Login test
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/social/GoogleLoginPage.java
KEYCLOAK-11675 Fix unstable Google Social Login test
<ide><path>estsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/social/GoogleLoginPage.java <ide> import java.util.List; <ide> <ide> import static org.keycloak.testsuite.util.UIUtils.clickLink; <del>import static org.keycloak.testsuite.util.UIUtils.performOperationWithPageReload; <ide> import static org.keycloak.testsuite.util.URLUtils.navigateToUri; <add>import static org.keycloak.testsuite.util.WaitUtils.pause; <ide> <ide> /** <ide> * @author Vaclav Muzikar <[email protected]> <ide> <ide> emailInput.clear(); <ide> emailInput.sendKeys(user); <del> performOperationWithPageReload(() -> emailInput.sendKeys(Keys.RETURN)); <add> emailInput.sendKeys(Keys.RETURN); <add> pause(3000); // wait for some animation or whatever <ide> passwordInput.sendKeys(password); <ide> passwordInput.sendKeys(Keys.RETURN); <ide> }
Java
mit
db9369617e351e547d1a6bd28967842f8929e1c5
0
paramaggarwal/react-native-youtube,inProgress-team/react-native-youtube,paramaggarwal/react-native-youtube,inProgress-team/react-native-youtube,inProgress-team/react-native-youtube
package com.inprogress.reactnativeyoutube; import android.support.annotation.Nullable; import com.facebook.infer.annotation.Assertions; import com.facebook.react.common.MapBuilder; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; import java.util.Map; public class YouTubeManager extends SimpleViewManager<YouTubeView> { private static final int COMMAND_SEEK_TO = 1; private static final int COMMAND_NEXT_VIDEO = 2; private static final int COMMAND_PREVIOUS_VIDEO = 3; private static final int COMMAND_PLAY_VIDEO_AT = 4; @Override public String getName() { return "ReactYouTube"; } @Override protected YouTubeView createViewInstance(ThemedReactContext themedReactContext) { return new YouTubeView(themedReactContext); } @Override public Map<String,Integer> getCommandsMap() { return MapBuilder.of( "seekTo", COMMAND_SEEK_TO, "nextVideo", COMMAND_NEXT_VIDEO, "previousVideo", COMMAND_PREVIOUS_VIDEO, "playVideoAt", COMMAND_PLAY_VIDEO_AT ); } @Override public void receiveCommand(YouTubeView view, int commandType, @Nullable ReadableArray args) { Assertions.assertNotNull(view); Assertions.assertNotNull(args); switch (commandType) { case COMMAND_SEEK_TO: { view.seekTo(args.getInt(0)); return; } case COMMAND_NEXT_VIDEO: { view.nextVideo(); return; } case COMMAND_PREVIOUS_VIDEO: { view.previousVideo(); return; } case COMMAND_PLAY_VIDEO_AT: { view.playVideoAt(args.getInt(0)); return; } default: throw new IllegalArgumentException( String.format("Unsupported command %d received by %s.", commandType, getClass().getSimpleName()) ); } } @Override public @Nullable Map <String,Object> getExportedCustomDirectEventTypeConstants() { return MapBuilder.of( "error", (Object) MapBuilder.of("registrationName", "onYouTubeError"), "ready", (Object) MapBuilder.of("registrationName", "onYouTubeReady"), "state", (Object) MapBuilder.of("registrationName", "onYouTubeChangeState"), "quality", (Object) MapBuilder.of("registrationName", "onYouTubeChangeQuality"), "fullscreen", (Object) MapBuilder.of("registrationName", "onYouTubeChangeFullscreen") ); } public int getVideosIndex(YouTubeView view) { return view.getVideosIndex(); } @ReactProp(name = "apiKey") public void setApiKey(YouTubeView view, @Nullable String param) { view.setApiKey(param); } @ReactProp(name = "videoId") public void setPropVideoId(YouTubeView view, @Nullable String param) { view.setVideoId(param); } @ReactProp(name = "videoIds") public void setPropVideoIds(YouTubeView view, @Nullable ReadableArray param) { view.setVideoIds(param); } @ReactProp(name = "playlistId") public void setPropPlaylistId(YouTubeView view, @Nullable String param) { view.setPlaylistId(param); } @ReactProp(name = "play") public void setPropPlay(YouTubeView view, @Nullable boolean param) { view.setPlay(param); } @ReactProp(name = "loop") public void setPropLoop(YouTubeView view, @Nullable boolean param) { view.setLoop(param); } @ReactProp(name = "fullscreen") public void setPropFullscreen(YouTubeView view, @Nullable boolean param) { view.setFullscreen(param); } @ReactProp(name = "controls") public void setPropControls(YouTubeView view, @Nullable int param) { view.setControls(param); } @ReactProp(name = "showFullscreenButton") public void setPropShowFullscreenButton(YouTubeView view, @Nullable boolean param) { view.setShowFullscreenButton(param); } }
android/src/main/java/com/inprogress/reactnativeyoutube/YouTubeManager.java
package com.inprogress.reactnativeyoutube; import android.support.annotation.Nullable; import com.facebook.infer.annotation.Assertions; import com.facebook.react.common.MapBuilder; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; import java.util.Map; public class YouTubeManager extends SimpleViewManager<YouTubeView> { private static final int COMMAND_SEEK_TO = 1; private static final int COMMAND_NEXT_VIDEO = 2; private static final int COMMAND_PREVIOUS_VIDEO = 3; private static final int COMMAND_PLAY_VIDEO_AT = 4; @Override public String getName() { return "ReactYouTube"; } @Override protected YouTubeView createViewInstance(ThemedReactContext themedReactContext) { return new YouTubeView(themedReactContext); } @Override public Map<String,Integer> getCommandsMap() { return MapBuilder.of( "seekTo", COMMAND_SEEK_TO, "nextVideo", COMMAND_NEXT_VIDEO, "previousVideo", COMMAND_PREVIOUS_VIDEO, "playVideoAt", COMMAND_PLAY_VIDEO_AT ); } @Override public void receiveCommand(YouTubeView view, int commandType, @Nullable ReadableArray args) { Assertions.assertNotNull(view); Assertions.assertNotNull(args); switch (commandType) { case COMMAND_SEEK_TO: { view.seekTo(args.getInt(0)); return; } case COMMAND_NEXT_VIDEO: { view.nextVideo(); return; } case COMMAND_PREVIOUS_VIDEO: { view.previousVideo(); return; } case COMMAND_PLAY_VIDEO_AT: { view.playVideoAt(args.getInt(0)); return; } default: throw new IllegalArgumentException( String.format("Unsupported command %d received by %s.", commandType, getClass().getSimpleName()) ); } } @Override public @Nullable Map <String,Object> getExportedCustomDirectEventTypeConstants() { return MapBuilder.of( "error", (Object) MapBuilder.of("registrationName", "onYouTubeError"), "ready", (Object) MapBuilder.of("registrationName", "onYouTubeReady"), "state", (Object) MapBuilder.of("registrationName", "onYouTubeChangeState"), "quality", (Object) MapBuilder.of("registrationName", "onYouTubeChangeQuality"), "fullscreen", (Object) MapBuilder.of("registrationName", "onYouTubeChangeFullscreen") ); } public int getVideosIndex(YouTubeView view) { return view.getVideosIndex(); } @ReactProp(name = "apiKey") public void setApiKey(YouTubeView view, @Nullable String param) { view.setApiKey(param); } @ReactProp(name = "videoId") public void setPropVideoId(YouTubeView view, @Nullable String param) { view.setVideoId(param); } @ReactProp(name = "videoIds") public void setPropVideoIds(YouTubeView view, @Nullable ReadableArray param) { view.setVideoIds(param); } @ReactProp(name = "playlistId") public void setPropPlaylistId(YouTubeView view, @Nullable String param) { view.setPlaylistId(param); } @ReactProp(name = "play") public void setPropPlay(YouTubeView view, @Nullable boolean param) { view.setPlay(param); } @ReactProp(name = "loop") public void setPropLoop(YouTubeView view, @Nullable boolean param) { view.setLoop(param); } @ReactProp(name = "fullscreen") public void setPropFullscreen(YouTubeView view, @Nullable boolean param) { view.setFullscreen(param); } @ReactProp(name = "controls") public void setPropControls(YouTubeView view, @Nullable int param) { view.setControls(param); } @ReactProp(name = "showFullscreenButton") public void setPropShowFullscreenButton(YouTubeView view, @Nullable boolean param) { view.setShowFullscreenButton(param); } }
reset v1 branch from upstream
android/src/main/java/com/inprogress/reactnativeyoutube/YouTubeManager.java
reset v1 branch from upstream
<ide><path>ndroid/src/main/java/com/inprogress/reactnativeyoutube/YouTubeManager.java <ide> ); <ide> } <ide> <del> <ide> public int getVideosIndex(YouTubeView view) { <ide> return view.getVideosIndex(); <ide> }
JavaScript
mpl-2.0
99a1b40b6b44211941699b00262b106b51ba725a
0
kumar303/web-ext,rpl/web-ext,mozilla/web-ext,kumar303/web-ext,mozilla/web-ext,rpl/web-ext
/* @flow */ import path from 'path'; import {readFileSync} from 'fs'; import camelCase from 'camelcase'; import git from 'git-rev-sync'; import yargs from 'yargs'; import defaultCommands from './cmd'; import {UsageError} from './errors'; import {createLogger, consoleStream as defaultLogStream} from './util/logger'; import {coerceCLICustomPreference} from './firefox/preferences'; import {checkForUpdates as defaultUpdateChecker} from './util/updates'; const log = createLogger(__filename); const envPrefix = 'WEB_EXT'; type ProgramOptions = {| absolutePackageDir?: string, |} // TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed type ExecuteOptions = { checkForUpdates?: Function, systemProcess?: typeof process, logStream?: typeof defaultLogStream, getVersion?: Function, shouldExitProgram?: boolean, globalEnv?: string, } /* * The command line program. */ export class Program { yargs: any; commands: { [key: string]: Function }; shouldExitProgram: boolean; options: Object; constructor( argv: ?Array<string>, { absolutePackageDir = process.cwd(), }: ProgramOptions = {} ) { // This allows us to override the process argv which is useful for // testing. // NOTE: process.argv.slice(2) removes the path to node and web-ext // executables from the process.argv array. argv = argv || process.argv.slice(2); // NOTE: always initialize yargs explicitly with the package dir // so that we are sure that it is going to load the 'boolean-negation: false' // config (See web-ext#469 for rationale). const yargsInstance = yargs(argv, absolutePackageDir); this.shouldExitProgram = true; this.yargs = yargsInstance; this.yargs.strict(); this.commands = {}; this.options = {}; } command( name: string, description: string, executor: Function, commandOptions: Object = {} ): Program { this.options[camelCase(name)] = commandOptions; this.yargs.command(name, description, (yargsForCmd) => { if (!commandOptions) { return; } return yargsForCmd // Make sure the user does not add any extra commands. For example, // this would be a mistake because lint does not accept arguments: // web-ext lint ./src/path/to/file.js .demandCommand(0, 0, undefined, 'This command does not take any arguments') .strict() .exitProcess(this.shouldExitProgram) // Calling env() will be unnecessary after // https://github.com/yargs/yargs/issues/486 is fixed .env(envPrefix) .options(commandOptions); }); this.commands[name] = executor; return this; } setGlobalOptions(options: Object): Program { // This is a convenience for setting global options. // An option is only global (i.e. available to all sub commands) // with the `global` flag so this makes sure every option has it. this.options = {...this.options, ...options}; Object.keys(options).forEach((key) => { options[key].global = true; if (options[key].demand === undefined) { // By default, all options should be "demanded" otherwise // yargs.strict() will think they are missing when declared. options[key].demand = true; } }); this.yargs.options(options); return this; } async execute( absolutePackageDir: string, { checkForUpdates = defaultUpdateChecker, systemProcess = process, logStream = defaultLogStream, getVersion = defaultVersionGetter, shouldExitProgram = true, globalEnv = WEBEXT_BUILD_ENV, }: ExecuteOptions = {} ): Promise<void> { this.shouldExitProgram = shouldExitProgram; this.yargs.exitProcess(this.shouldExitProgram); const argv = this.yargs.argv; const cmd = argv._[0]; const runCommand = this.commands[cmd]; if (argv.verbose) { logStream.makeVerbose(); log.info('Version:', getVersion(absolutePackageDir)); } try { if (cmd === undefined) { throw new UsageError('No sub-command was specified in the args'); } if (!runCommand) { throw new UsageError(`Unknown command: ${cmd}`); } if (globalEnv === 'production') { checkForUpdates ({ version: getVersion(absolutePackageDir), }); } await runCommand(argv, {shouldExitProgram}); } catch (error) { const prefix = cmd ? `${cmd}: ` : ''; if (!(error instanceof UsageError) || argv.verbose) { log.error(`\n${prefix}${error.stack}\n`); } else { log.error(`\n${prefix}${error}\n`); } if (error.code) { log.error(`${prefix}Error code: ${error.code}\n`); } if (this.shouldExitProgram) { systemProcess.exit(1); } else { throw error; } } } } // A global variable generated by DefinePlugin, generated in webpack.config.js declare var WEBEXT_BUILD_ENV: string; //A defintion of type of argument for defaultVersionGetter type VersionGetterOptions = { globalEnv?: string, }; export function defaultVersionGetter( absolutePackageDir: string, {globalEnv = WEBEXT_BUILD_ENV}: VersionGetterOptions = {} ): string { if (globalEnv === 'production') { log.debug('Getting the version from package.json'); const packageData: any = readFileSync( path.join(absolutePackageDir, 'package.json')); return JSON.parse(packageData).version; } else { log.debug('Getting version from the git revision'); return `${git.branch(absolutePackageDir)}-${git.long(absolutePackageDir)}`; } } // TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed type MainParams = { getVersion?: Function, commands?: Object, argv: Array<any>, runOptions?: Object, } export function main( absolutePackageDir: string, { getVersion = defaultVersionGetter, commands = defaultCommands, argv, runOptions = {}, }: MainParams = {} ): Promise<any> { const program = new Program(argv, {absolutePackageDir}); // yargs uses magic camel case expansion to expose options on the // final argv object. For example, the 'artifacts-dir' option is alternatively // available as argv.artifactsDir. program.yargs .usage(`Usage: $0 [options] command Option values can also be set by declaring an environment variable prefixed with $${envPrefix}_. For example: $${envPrefix}_SOURCE_DIR=/path is the same as --source-dir=/path. To view specific help for any given command, add the command name. Example: $0 --help run. `) .help('help') .alias('h', 'help') .env(envPrefix) .version(() => getVersion(absolutePackageDir)) .demandCommand(1, 'You must specify a command') .strict(); program.setGlobalOptions({ 'source-dir': { alias: 's', describe: 'Web extension source directory.', default: process.cwd(), requiresArg: true, type: 'string', coerce: path.resolve, }, 'artifacts-dir': { alias: 'a', describe: 'Directory where artifacts will be saved.', default: path.join(process.cwd(), 'web-ext-artifacts'), normalize: true, requiresArg: true, type: 'string', }, 'verbose': { alias: 'v', describe: 'Show verbose output', type: 'boolean', }, 'ignore-files': { alias: 'i', describe: 'A list of glob patterns to define which files should be ' + 'ignored. (Example: --ignore-files=path/to/first.js ' + 'path/to/second.js "**/*.log")', demand: false, requiresArg: true, type: 'array', }, 'no-input': { describe: 'Disable all features that require standard input', type: 'boolean', }, }); program .command( 'build', 'Create a web extension package from source', commands.build, { 'as-needed': { describe: 'Watch for file changes and re-build as needed', type: 'boolean', }, 'overwrite-dest': { alias: 'o', describe: 'Overwrite destination package if it exists.', type: 'boolean', }, }) .command( 'sign', 'Sign the web extension so it can be installed in Firefox', commands.sign, { 'api-key': { describe: 'API key (JWT issuer) from addons.mozilla.org', demand: true, type: 'string', }, 'api-secret': { describe: 'API secret (JWT secret) from addons.mozilla.org', demand: true, type: 'string', }, 'api-url-prefix': { describe: 'Signing API URL prefix', default: 'https://addons.mozilla.org/api/v3', demand: true, type: 'string', }, 'api-proxy': { describe: 'Use a proxy to access the signing API. ' + 'Example: https://yourproxy:6000 ', demand: false, type: 'string', }, 'id': { describe: 'A custom ID for the extension. This has no effect if the ' + 'extension already declares an explicit ID in its manifest.', demand: false, type: 'string', }, 'timeout': { describe: 'Number of milliseconds to wait before giving up', type: 'number', }, }) .command('run', 'Run the web extension', commands.run, { 'firefox': { alias: ['f', 'firefox-binary'], describe: 'Path or alias to a Firefox executable such as firefox-bin ' + 'or firefox.exe. ' + 'If not specified, the default Firefox will be used. ' + 'You can specify the following aliases in lieu of a path: ' + 'firefox, beta, nightly, firefoxdeveloperedition.', demand: false, type: 'string', }, 'firefox-profile': { alias: 'p', describe: 'Run Firefox using a copy of this profile. The profile ' + 'can be specified as a directory or a name, such as one ' + 'you would see in the Profile Manager. If not specified, ' + 'a new temporary profile will be created.', demand: false, type: 'string', }, 'keep-profile-changes': { describe: 'Run Firefox directly in custom profile. Any changes to ' + 'the profile will be saved.', demand: false, type: 'boolean', }, 'no-reload': { describe: 'Do not reload the extension when source files change', demand: false, type: 'boolean', }, 'pre-install': { describe: 'Pre-install the extension into the profile before ' + 'startup. This is only needed to support older versions ' + 'of Firefox.', demand: false, type: 'boolean', }, 'pref': { describe: 'Launch firefox with a custom preference ' + '(example: --pref=general.useragent.locale=fr-FR). ' + 'You can repeat this option to set more than one ' + 'preference.', demand: false, requiresArg: true, type: 'string', coerce: coerceCLICustomPreference, }, 'start-url': { alias: ['u', 'url'], describe: 'Launch firefox at specified page', demand: false, requiresArg: true, type: 'string', }, 'browser-console': { alias: ['bc'], describe: 'Open the DevTools Browser Console.', demand: false, type: 'boolean', }, }) .command('lint', 'Validate the web extension source', commands.lint, { 'output': { alias: 'o', describe: 'The type of output to generate', type: 'string', default: 'text', choices: ['json', 'text'], }, 'metadata': { describe: 'Output only metadata as JSON', type: 'boolean', default: false, }, 'warnings-as-errors': { describe: 'Treat warnings as errors by exiting non-zero for warnings', alias: 'w', type: 'boolean', default: false, }, 'pretty': { describe: 'Prettify JSON output', type: 'boolean', default: false, }, 'self-hosted': { describe: 'Your extension will be self-hosted. This disables messages ' + 'related to hosting on addons.mozilla.org.', type: 'boolean', default: false, }, 'boring': { describe: 'Disables colorful shell output', type: 'boolean', default: false, }, }) .command('docs', 'Open the web-ext documentation in a browser', commands.docs, {}); return program.execute(absolutePackageDir, runOptions); }
src/program.js
/* @flow */ import path from 'path'; import {readFileSync} from 'fs'; import camelCase from 'camelcase'; import git from 'git-rev-sync'; import yargs from 'yargs'; import defaultCommands from './cmd'; import {UsageError} from './errors'; import {createLogger, consoleStream as defaultLogStream} from './util/logger'; import {coerceCLICustomPreference} from './firefox/preferences'; import {checkForUpdates as defaultUpdateChecker} from './util/updates'; const log = createLogger(__filename); const envPrefix = 'WEB_EXT'; type ProgramOptions = {| absolutePackageDir?: string, |} // TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed type ExecuteOptions = { checkForUpdates?: Function, systemProcess?: typeof process, logStream?: typeof defaultLogStream, getVersion?: Function, shouldExitProgram?: boolean, globalEnv?: string, } /* * The command line program. */ export class Program { yargs: any; commands: { [key: string]: Function }; shouldExitProgram: boolean; options: Object; constructor( argv: ?Array<string>, { absolutePackageDir = process.cwd(), }: ProgramOptions = {} ) { // This allows us to override the process argv which is useful for // testing. // NOTE: process.argv.slice(2) removes the path to node and web-ext // executables from the process.argv array. argv = argv || process.argv.slice(2); // NOTE: always initialize yargs explicitly with the package dir // so that we are sure that it is going to load the 'boolean-negation: false' // config (See web-ext#469 for rationale). const yargsInstance = yargs(argv, absolutePackageDir); this.shouldExitProgram = true; this.yargs = yargsInstance; this.yargs.strict(); this.commands = {}; this.options = {}; } command( name: string, description: string, executor: Function, commandOptions: Object = {} ): Program { this.options[camelCase(name)] = commandOptions; this.yargs.command(name, description, (yargsForCmd) => { if (!commandOptions) { return; } return yargsForCmd // Make sure the user does not add any extra commands. For example, // this would be a mistake because lint does not accept arguments: // web-ext lint ./src/path/to/file.js .demandCommand(0, 0, undefined, 'This command does not take any arguments') .strict() .exitProcess(this.shouldExitProgram) // Calling env() will be unnecessary after // https://github.com/yargs/yargs/issues/486 is fixed .env(envPrefix) .options(commandOptions); }); this.commands[name] = executor; return this; } setGlobalOptions(options: Object): Program { // This is a convenience for setting global options. // An option is only global (i.e. available to all sub commands) // with the `global` flag so this makes sure every option has it. this.options = {...this.options, ...options}; Object.keys(options).forEach((key) => { options[key].global = true; if (options[key].demand === undefined) { // By default, all options should be "demanded" otherwise // yargs.strict() will think they are missing when declared. options[key].demand = true; } }); this.yargs.options(options); return this; } async execute( absolutePackageDir: string, { checkForUpdates = defaultUpdateChecker, systemProcess = process, logStream = defaultLogStream, getVersion = defaultVersionGetter, shouldExitProgram = true, globalEnv = WEBEXT_BUILD_ENV, }: ExecuteOptions = {} ): Promise<void> { this.shouldExitProgram = shouldExitProgram; this.yargs.exitProcess(this.shouldExitProgram); const argv = this.yargs.argv; const cmd = argv._[0]; const runCommand = this.commands[cmd]; if (argv.verbose) { logStream.makeVerbose(); log.info('Version:', getVersion(absolutePackageDir)); } try { if (cmd === undefined) { throw new UsageError('No sub-command was specified in the args'); } if (!runCommand) { throw new UsageError(`Unknown command: ${cmd}`); } if (globalEnv === 'production') { checkForUpdates ({ version: getVersion(absolutePackageDir), }); } await runCommand(argv, {shouldExitProgram}); } catch (error) { const prefix = cmd ? `${cmd}: ` : ''; if (!(error instanceof UsageError) || argv.verbose) { log.error(`\n${prefix}${error.stack}\n`); } else { log.error(`\n${prefix}${error}\n`); } if (error.code) { log.error(`${prefix}Error code: ${error.code}\n`); } if (this.shouldExitProgram) { systemProcess.exit(1); } else { throw error; } } } } // A global variable generated by DefinePlugin, generated in webpack.config.js declare var WEBEXT_BUILD_ENV: string; //A defintion of type of argument for defaultVersionGetter type VersionGetterOptions = { globalEnv?: string, }; export function defaultVersionGetter( absolutePackageDir: string, {globalEnv = WEBEXT_BUILD_ENV}: VersionGetterOptions = {} ): string { if (globalEnv === 'production') { log.debug('Getting the version from package.json'); const packageData: any = readFileSync( path.join(absolutePackageDir, 'package.json')); return JSON.parse(packageData).version; } else { log.debug('Getting version from the git revision'); return `${git.branch(absolutePackageDir)}-${git.long(absolutePackageDir)}`; } } // TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed type MainParams = { getVersion?: Function, commands?: Object, argv: Array<any>, runOptions?: Object, } export function main( absolutePackageDir: string, { getVersion = defaultVersionGetter, commands = defaultCommands, argv, runOptions = {}, }: MainParams = {} ): Promise<any> { const program = new Program(argv, {absolutePackageDir}); // yargs uses magic camel case expansion to expose options on the // final argv object. For example, the 'artifacts-dir' option is alternatively // available as argv.artifactsDir. program.yargs .usage(`Usage: $0 [options] command Option values can also be set by declaring an environment variable prefixed with $${envPrefix}_. For example: $${envPrefix}_SOURCE_DIR=/path is the same as --source-dir=/path. To view specific help for any given command, add the command name. Example: $0 --help run. `) .help('help') .alias('h', 'help') .env(envPrefix) .version(() => getVersion(absolutePackageDir)) .demandCommand(1, 'You must specify a command') .strict(); program.setGlobalOptions({ 'source-dir': { alias: 's', describe: 'Web extension source directory.', default: process.cwd(), requiresArg: true, type: 'string', coerce: path.resolve, }, 'artifacts-dir': { alias: 'a', describe: 'Directory where artifacts will be saved.', default: path.join(process.cwd(), 'web-ext-artifacts'), normalize: true, requiresArg: true, type: 'string', }, 'verbose': { alias: 'v', describe: 'Show verbose output', type: 'boolean', }, 'ignore-files': { alias: 'i', describe: 'A list of glob patterns to define which files should be ' + 'ignored. (Example: --ignore-files=path/to/first.js ' + 'path/to/second.js "**/*.log")', demand: false, requiresArg: true, type: 'array', }, }); program .command( 'build', 'Create a web extension package from source', commands.build, { 'as-needed': { describe: 'Watch for file changes and re-build as needed', type: 'boolean', }, 'overwrite-dest': { alias: 'o', describe: 'Overwrite destination package if it exists.', type: 'boolean', }, }) .command( 'sign', 'Sign the web extension so it can be installed in Firefox', commands.sign, { 'api-key': { describe: 'API key (JWT issuer) from addons.mozilla.org', demand: true, type: 'string', }, 'api-secret': { describe: 'API secret (JWT secret) from addons.mozilla.org', demand: true, type: 'string', }, 'api-url-prefix': { describe: 'Signing API URL prefix', default: 'https://addons.mozilla.org/api/v3', demand: true, type: 'string', }, 'api-proxy': { describe: 'Use a proxy to access the signing API. ' + 'Example: https://yourproxy:6000 ', demand: false, type: 'string', }, 'id': { describe: 'A custom ID for the extension. This has no effect if the ' + 'extension already declares an explicit ID in its manifest.', demand: false, type: 'string', }, 'timeout': { describe: 'Number of milliseconds to wait before giving up', type: 'number', }, }) .command('run', 'Run the web extension', commands.run, { 'firefox': { alias: ['f', 'firefox-binary'], describe: 'Path or alias to a Firefox executable such as firefox-bin ' + 'or firefox.exe. ' + 'If not specified, the default Firefox will be used. ' + 'You can specify the following aliases in lieu of a path: ' + 'firefox, beta, nightly, firefoxdeveloperedition.', demand: false, type: 'string', }, 'firefox-profile': { alias: 'p', describe: 'Run Firefox using a copy of this profile. The profile ' + 'can be specified as a directory or a name, such as one ' + 'you would see in the Profile Manager. If not specified, ' + 'a new temporary profile will be created.', demand: false, type: 'string', }, 'keep-profile-changes': { describe: 'Run Firefox directly in custom profile. Any changes to ' + 'the profile will be saved.', demand: false, type: 'boolean', }, 'no-reload': { describe: 'Do not reload the extension when source files change', demand: false, type: 'boolean', }, 'pre-install': { describe: 'Pre-install the extension into the profile before ' + 'startup. This is only needed to support older versions ' + 'of Firefox.', demand: false, type: 'boolean', }, 'pref': { describe: 'Launch firefox with a custom preference ' + '(example: --pref=general.useragent.locale=fr-FR). ' + 'You can repeat this option to set more than one ' + 'preference.', demand: false, requiresArg: true, type: 'string', coerce: coerceCLICustomPreference, }, 'start-url': { alias: ['u', 'url'], describe: 'Launch firefox at specified page', demand: false, requiresArg: true, type: 'string', }, 'browser-console': { alias: ['bc'], describe: 'Open the DevTools Browser Console.', demand: false, type: 'boolean', }, }) .command('lint', 'Validate the web extension source', commands.lint, { 'output': { alias: 'o', describe: 'The type of output to generate', type: 'string', default: 'text', choices: ['json', 'text'], }, 'metadata': { describe: 'Output only metadata as JSON', type: 'boolean', default: false, }, 'warnings-as-errors': { describe: 'Treat warnings as errors by exiting non-zero for warnings', alias: 'w', type: 'boolean', default: false, }, 'pretty': { describe: 'Prettify JSON output', type: 'boolean', default: false, }, 'self-hosted': { describe: 'Your extension will be self-hosted. This disables messages ' + 'related to hosting on addons.mozilla.org.', type: 'boolean', default: false, }, 'boring': { describe: 'Disables colorful shell output', type: 'boolean', default: false, }, }) .command('docs', 'Open the web-ext documentation in a browser', commands.docs, {}); return program.execute(absolutePackageDir, runOptions); }
feat: Added --no-input option to disable standard input (#1044)
src/program.js
feat: Added --no-input option to disable standard input (#1044)
<ide><path>rc/program.js <ide> requiresArg: true, <ide> type: 'array', <ide> }, <add> 'no-input': { <add> describe: 'Disable all features that require standard input', <add> type: 'boolean', <add> }, <ide> }); <ide> <ide> program
Java
apache-2.0
5c8ed288b772fef4183971d59b3d2bced6d94404
0
collinprice/titanium_mobile,benbahrenburg/titanium_mobile,taoger/titanium_mobile,benbahrenburg/titanium_mobile,falkolab/titanium_mobile,AngelkPetkov/titanium_mobile,formalin14/titanium_mobile,perdona/titanium_mobile,AngelkPetkov/titanium_mobile,ashcoding/titanium_mobile,FokkeZB/titanium_mobile,bhatfield/titanium_mobile,pinnamur/titanium_mobile,smit1625/titanium_mobile,peymanmortazavi/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,csg-coder/titanium_mobile,ashcoding/titanium_mobile,falkolab/titanium_mobile,collinprice/titanium_mobile,formalin14/titanium_mobile,indera/titanium_mobile,jhaynie/titanium_mobile,collinprice/titanium_mobile,kopiro/titanium_mobile,jhaynie/titanium_mobile,jhaynie/titanium_mobile,collinprice/titanium_mobile,falkolab/titanium_mobile,pinnamur/titanium_mobile,prop/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,AngelkPetkov/titanium_mobile,taoger/titanium_mobile,pec1985/titanium_mobile,jvkops/titanium_mobile,sriks/titanium_mobile,pec1985/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,indera/titanium_mobile,pec1985/titanium_mobile,FokkeZB/titanium_mobile,taoger/titanium_mobile,cheekiatng/titanium_mobile,rblalock/titanium_mobile,mano-mykingdom/titanium_mobile,bright-sparks/titanium_mobile,formalin14/titanium_mobile,benbahrenburg/titanium_mobile,smit1625/titanium_mobile,FokkeZB/titanium_mobile,FokkeZB/titanium_mobile,kopiro/titanium_mobile,openbaoz/titanium_mobile,rblalock/titanium_mobile,KoketsoMabuela92/titanium_mobile,csg-coder/titanium_mobile,benbahrenburg/titanium_mobile,benbahrenburg/titanium_mobile,falkolab/titanium_mobile,falkolab/titanium_mobile,csg-coder/titanium_mobile,KoketsoMabuela92/titanium_mobile,shopmium/titanium_mobile,kopiro/titanium_mobile,cheekiatng/titanium_mobile,pec1985/titanium_mobile,openbaoz/titanium_mobile,kopiro/titanium_mobile,bright-sparks/titanium_mobile,taoger/titanium_mobile,KangaCoders/titanium_mobile,emilyvon/titanium_mobile,linearhub/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,sriks/titanium_mobile,shopmium/titanium_mobile,emilyvon/titanium_mobile,KangaCoders/titanium_mobile,sriks/titanium_mobile,KangaCoders/titanium_mobile,formalin14/titanium_mobile,ashcoding/titanium_mobile,indera/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,falkolab/titanium_mobile,bhatfield/titanium_mobile,linearhub/titanium_mobile,indera/titanium_mobile,csg-coder/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,peymanmortazavi/titanium_mobile,bright-sparks/titanium_mobile,openbaoz/titanium_mobile,perdona/titanium_mobile,smit1625/titanium_mobile,mano-mykingdom/titanium_mobile,linearhub/titanium_mobile,KangaCoders/titanium_mobile,kopiro/titanium_mobile,openbaoz/titanium_mobile,prop/titanium_mobile,csg-coder/titanium_mobile,cheekiatng/titanium_mobile,rblalock/titanium_mobile,KangaCoders/titanium_mobile,cheekiatng/titanium_mobile,KangaCoders/titanium_mobile,pec1985/titanium_mobile,peymanmortazavi/titanium_mobile,emilyvon/titanium_mobile,mvitr/titanium_mobile,linearhub/titanium_mobile,mano-mykingdom/titanium_mobile,smit1625/titanium_mobile,perdona/titanium_mobile,linearhub/titanium_mobile,pinnamur/titanium_mobile,perdona/titanium_mobile,cheekiatng/titanium_mobile,jvkops/titanium_mobile,benbahrenburg/titanium_mobile,formalin14/titanium_mobile,KangaCoders/titanium_mobile,ashcoding/titanium_mobile,pec1985/titanium_mobile,mvitr/titanium_mobile,KangaCoders/titanium_mobile,taoger/titanium_mobile,openbaoz/titanium_mobile,collinprice/titanium_mobile,sriks/titanium_mobile,prop/titanium_mobile,jvkops/titanium_mobile,linearhub/titanium_mobile,emilyvon/titanium_mobile,smit1625/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,perdona/titanium_mobile,mano-mykingdom/titanium_mobile,sriks/titanium_mobile,shopmium/titanium_mobile,jhaynie/titanium_mobile,FokkeZB/titanium_mobile,peymanmortazavi/titanium_mobile,smit1625/titanium_mobile,openbaoz/titanium_mobile,rblalock/titanium_mobile,benbahrenburg/titanium_mobile,emilyvon/titanium_mobile,csg-coder/titanium_mobile,ashcoding/titanium_mobile,pec1985/titanium_mobile,cheekiatng/titanium_mobile,pec1985/titanium_mobile,AngelkPetkov/titanium_mobile,bright-sparks/titanium_mobile,indera/titanium_mobile,kopiro/titanium_mobile,pec1985/titanium_mobile,jvkops/titanium_mobile,mvitr/titanium_mobile,formalin14/titanium_mobile,mano-mykingdom/titanium_mobile,jvkops/titanium_mobile,collinprice/titanium_mobile,AngelkPetkov/titanium_mobile,AngelkPetkov/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,bhatfield/titanium_mobile,falkolab/titanium_mobile,pinnamur/titanium_mobile,FokkeZB/titanium_mobile,ashcoding/titanium_mobile,indera/titanium_mobile,bhatfield/titanium_mobile,shopmium/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,jhaynie/titanium_mobile,rblalock/titanium_mobile,AngelkPetkov/titanium_mobile,prop/titanium_mobile,kopiro/titanium_mobile,falkolab/titanium_mobile,taoger/titanium_mobile,FokkeZB/titanium_mobile,bright-sparks/titanium_mobile,prop/titanium_mobile,jhaynie/titanium_mobile,emilyvon/titanium_mobile,jhaynie/titanium_mobile,taoger/titanium_mobile,peymanmortazavi/titanium_mobile,csg-coder/titanium_mobile,KoketsoMabuela92/titanium_mobile,mvitr/titanium_mobile,perdona/titanium_mobile,emilyvon/titanium_mobile,indera/titanium_mobile,prop/titanium_mobile,bright-sparks/titanium_mobile,bhatfield/titanium_mobile,perdona/titanium_mobile,shopmium/titanium_mobile,csg-coder/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,FokkeZB/titanium_mobile,rblalock/titanium_mobile,formalin14/titanium_mobile,linearhub/titanium_mobile,rblalock/titanium_mobile,kopiro/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,openbaoz/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,ashcoding/titanium_mobile,pinnamur/titanium_mobile,collinprice/titanium_mobile,formalin14/titanium_mobile,sriks/titanium_mobile,emilyvon/titanium_mobile,bright-sparks/titanium_mobile,KoketsoMabuela92/titanium_mobile,perdona/titanium_mobile,indera/titanium_mobile,smit1625/titanium_mobile,shopmium/titanium_mobile,linearhub/titanium_mobile,openbaoz/titanium_mobile,smit1625/titanium_mobile,jhaynie/titanium_mobile,prop/titanium_mobile,AngelkPetkov/titanium_mobile,prop/titanium_mobile,taoger/titanium_mobile,KoketsoMabuela92/titanium_mobile,benbahrenburg/titanium_mobile,sriks/titanium_mobile,pinnamur/titanium_mobile,sriks/titanium_mobile,peymanmortazavi/titanium_mobile,rblalock/titanium_mobile,shopmium/titanium_mobile,collinprice/titanium_mobile
/** * Appcelerator Titanium Mobile * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.network; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; import android.net.Uri; public interface SecurityManagerProtocol { /** * Defines if the SecurityManager will provide TrustManagers and KeyManagers for SSL Context given a Uri * @param uri - The end point for the network connection * @return true if SecurityManagers will define SSL Context, false otherwise. */ public boolean willHandleURL(Uri uri); /** * Returns the X509TrustManager array for SSL Context. * @param uri - The end point of the network connection * @return Return array of X509TrustManager for custom server validation. Null otherwise. */ public X509TrustManager[] getTrustManagers(Uri uri); /** * Returns the X509KeyManager array for the SSL Context. * @param uri - The end point of the network connection * @return Return array of X509KeyManager for custom client certificate management. Null otherwise. */ public X509KeyManager[] getKeyManagers(Uri uri); }
android/modules/network/src/java/ti/modules/titanium/network/SecurityManagerProtocol.java
/** * Appcelerator Titanium Mobile * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.network; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; import android.net.Uri; public interface SecurityManagerProtocol { /** * Defines if the SecurityManager will provide TrustManagers and KeyManagers for SSL Context given a Uri * @param uri - The end point for the network connection * @return true if SecurityManagers will define SSL Context, false otherwise. */ public boolean willHandleURL(Uri uri); /** * Returns the X509TrustManager array for SSL Context. * @param uri - The end point of the network connection * @return Return array of X509TrustManager for custom server validation. Null otherwise. */ public X509TrustManager[] getTrustManagers(Uri uri); /** * Reurns the X509KeyManager array for the SSL Context. * @param uri - The end point of the network connection * @return Return array of X509KeyManager for custom client certificate management. Null otherwise. */ public X509KeyManager[] getKeyManagers(Uri uri); }
[TIMOB-16857] Typo
android/modules/network/src/java/ti/modules/titanium/network/SecurityManagerProtocol.java
[TIMOB-16857] Typo
<ide><path>ndroid/modules/network/src/java/ti/modules/titanium/network/SecurityManagerProtocol.java <ide> public X509TrustManager[] getTrustManagers(Uri uri); <ide> <ide> /** <del> * Reurns the X509KeyManager array for the SSL Context. <add> * Returns the X509KeyManager array for the SSL Context. <ide> * @param uri - The end point of the network connection <ide> * @return Return array of X509KeyManager for custom client certificate management. Null otherwise. <ide> */
Java
lgpl-2.1
ed208677be58388176fd168bdf84c1f74456250e
0
MinecraftForge/ForgeGradle,MinecraftForge/ForgeGradle
/* * ForgeGradle * Copyright (C) 2018 Forge Development LLC * * 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 net.minecraftforge.gradle.common.util.runs; import net.minecraftforge.gradle.common.util.RunConfig; import net.minecraftforge.gradle.common.util.Utils; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.tasks.SourceSet; import org.gradle.plugins.ide.idea.model.IdeaModel; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; public class IntellijRunGenerator extends RunConfigGenerator.XMLConfigurationBuilder { boolean useGradlePaths = true; public IntellijRunGenerator(@Nonnull final Project project) { detectGradleDelegation(project); } private void detectGradleDelegation(Project project) { XPath xpath = XPathFactory.newInstance().newXPath(); // This file contains the current gradle import settings. File ideaGradleSettings = project.file(".idea/gradle.xml"); if (ideaGradleSettings.exists() && ideaGradleSettings.isFile()) { try (InputStream in = Files.newInputStream(ideaGradleSettings.toPath())) { Node value = (Node) xpath.evaluate( "/project/component[@name='GradleSettings']/option[@name='linkedExternalProjectsSettings']/GradleProjectSettings/option[@name='delegatedBuild']/@value", new InputSource(in), XPathConstants.NODE); if (value != null) { useGradlePaths = Boolean.parseBoolean(value.getTextContent()); return; } } catch (IOException | XPathExpressionException e) { e.printStackTrace(); } } // This value is normally true, and won't be used unless the project's gradle.xml is missing. File ideaWorkspace = project.file(".idea/workspace.xml"); if (ideaWorkspace.exists() && ideaWorkspace.isFile()) { try (InputStream in = Files.newInputStream(ideaWorkspace.toPath())) { Node value = (Node) xpath.evaluate( "/project/component[@name='DefaultGradleProjectSettings']/option[@name='delegatedBuild']/@value", new InputSource(in), XPathConstants.NODE); if (value != null) { useGradlePaths = Boolean.parseBoolean(value.getTextContent()); return; } } catch (IOException | XPathExpressionException e) { e.printStackTrace(); } } // Fallback, in case someone has a file-based project instead of a directory-based project. final IdeaModel idea = project.getExtensions().findByType(IdeaModel.class); File ideaFileProject = project.file(idea != null ? idea.getProject().getOutputFile() : (project.getName() + ".ipr")); if (ideaFileProject.exists() && ideaFileProject.isFile()) { try (InputStream in = Files.newInputStream(ideaFileProject.toPath())) { Node value = (Node) xpath.evaluate( "/project/component[@name='GradleSettings']/option[@name='linkedExternalProjectsSettings']/GradleProjectSettings/option[@name='delegatedBuild']/@value", new InputSource(in), XPathConstants.NODE); if (value != null) { useGradlePaths = Boolean.parseBoolean(value.getTextContent()); } } catch (IOException | XPathExpressionException e) { e.printStackTrace(); } } } @Override @Nonnull protected Map<String, Document> createRunConfiguration(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final DocumentBuilder documentBuilder, List<String> additionalClientArgs) { final Map<String, Document> documents = new LinkedHashMap<>(); Map<String, Supplier<String>> updatedTokens = configureTokensLazy(project, runConfig, useGradlePaths ? mapModClassesToGradle(project, runConfig) : mapModClassesToIdea(project, runConfig) ); // Java run config final Document javaDocument = documentBuilder.newDocument(); { final Element rootElement = javaDocument.createElement("component"); { final Element configuration = javaDocument.createElement("configuration"); { configuration.setAttribute("default", "false"); configuration.setAttribute("name", runConfig.getUniqueName()); configuration.setAttribute("type", "Application"); configuration.setAttribute("factoryName", "Application"); configuration.setAttribute("singleton", runConfig.isSingleInstance() ? "true" : "false"); elementOption(javaDocument, configuration, "MAIN_CLASS_NAME", runConfig.getMain()); elementOption(javaDocument, configuration, "VM_PARAMETERS", getJvmArgs(runConfig, additionalClientArgs, updatedTokens)); elementOption(javaDocument, configuration, "PROGRAM_PARAMETERS", getArgs(runConfig, updatedTokens)); elementOption(javaDocument, configuration, "WORKING_DIRECTORY", replaceRootDirBy(project, runConfig.getWorkingDirectory(), "$PROJECT_DIR$")); final Element module = javaDocument.createElement("module"); { module.setAttribute("name", runConfig.getIdeaModule()); } configuration.appendChild(module); final Element envs = javaDocument.createElement("envs"); { runConfig.getEnvironment().forEach((name, value) -> { final Element envEntry = javaDocument.createElement("env"); { envEntry.setAttribute("name", name); envEntry.setAttribute("value", replaceRootDirBy(project, runConfig.replace(updatedTokens, value), "$PROJECT_DIR$")); } envs.appendChild(envEntry); }); } configuration.appendChild(envs); final Element methods = javaDocument.createElement("method"); { methods.setAttribute("v", "2"); final Element makeTask = javaDocument.createElement("option"); { makeTask.setAttribute("name", "Make"); makeTask.setAttribute("enabled", "true"); } methods.appendChild(makeTask); final Element gradleTask = javaDocument.createElement("option"); { gradleTask.setAttribute("name", "Gradle.BeforeRunTask"); gradleTask.setAttribute("enabled", "true"); gradleTask.setAttribute("tasks", project.getTasks().getByName("prepare" + Utils.capitalize(runConfig.getTaskName())).getPath()); gradleTask.setAttribute("externalProjectPath", "$PROJECT_DIR$"); } methods.appendChild(gradleTask); } configuration.appendChild(methods); } rootElement.appendChild(configuration); } javaDocument.appendChild(rootElement); } documents.put(runConfig.getUniqueFileName() + ".xml", javaDocument); return documents; } private static Stream<String> mapModClassesToIdea(@Nonnull final Project project, @Nonnull final RunConfig runConfig) { final Map<SourceSet, Project> sourceSetsToProjects = new IdentityHashMap<>(); project.getRootProject().getAllprojects().forEach(proj -> { final JavaPluginExtension javaPlugin = proj.getExtensions().findByType(JavaPluginExtension.class); if (javaPlugin != null) { for (SourceSet sourceSet : javaPlugin.getSourceSets()) { sourceSetsToProjects.put(sourceSet, proj); } } }); if (runConfig.getMods().isEmpty()) { final IdeaModel idea = project.getExtensions().findByType(IdeaModel.class); return getIdeaPathsForSourceset(project, idea, "production", null); } else { return runConfig.getMods().stream() .flatMap(modConfig -> modConfig.getSources().stream() .flatMap(source -> { String outName = source.getName().equals(SourceSet.MAIN_SOURCE_SET_NAME) ? "production" : source.getName(); final Project sourceSetProject = sourceSetsToProjects.getOrDefault(source, project); final IdeaModel ideaModel = sourceSetProject.getExtensions().findByType(IdeaModel.class); return getIdeaPathsForSourceset(sourceSetProject, ideaModel, outName, modConfig.getName()); })); } } private static Stream<String> getIdeaPathsForSourceset(@Nonnull Project project, @Nullable IdeaModel idea, String outName, @Nullable String modName) { String ideaResources, ideaClasses; try { String outputPath = idea != null ? idea.getModule().getPathFactory().path("$MODULE_DIR$").getCanonicalUrl() : project.getProjectDir().getCanonicalPath(); ideaResources = Paths.get(outputPath, "out", outName, "resources").toFile().getCanonicalPath(); ideaClasses = Paths.get(outputPath, "out", outName, "classes").toFile().getCanonicalPath(); } catch (IOException e) { throw new RuntimeException("Error getting paths for idea run configs", e); } if (modName != null) { ideaResources = modName + "%%" + ideaResources; ideaClasses = modName + "%%" + ideaClasses; } return Stream.of(ideaResources, ideaClasses); } }
src/common/java/net/minecraftforge/gradle/common/util/runs/IntellijRunGenerator.java
/* * ForgeGradle * Copyright (C) 2018 Forge Development LLC * * 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 net.minecraftforge.gradle.common.util.runs; import net.minecraftforge.gradle.common.util.RunConfig; import net.minecraftforge.gradle.common.util.Utils; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.plugins.ide.idea.model.IdeaModel; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; public class IntellijRunGenerator extends RunConfigGenerator.XMLConfigurationBuilder { boolean useGradlePaths = true; public IntellijRunGenerator(@Nonnull final Project project) { detectGradleDelegation(project); } private void detectGradleDelegation(Project project) { XPath xpath = XPathFactory.newInstance().newXPath(); // This file contains the current gradle import settings. File ideaGradleSettings = project.file(".idea/gradle.xml"); if (ideaGradleSettings.exists() && ideaGradleSettings.isFile()) { try { Node value = (Node) xpath.evaluate( "/project/component[@name='GradleSettings']/option[@name='linkedExternalProjectsSettings']/GradleProjectSettings/option[@name='delegatedBuild']/@value", new InputSource(new FileInputStream(ideaGradleSettings)), XPathConstants.NODE); if (value != null) { useGradlePaths = Boolean.parseBoolean(value.getTextContent()); return; } } catch (IOException | XPathExpressionException e) { e.printStackTrace(); } } // This value is normally true, and won't be used unless the project's gradle.xml is missing. File ideaWorkspace = project.file(".idea/workspace.xml"); if (ideaWorkspace.exists() && ideaWorkspace.isFile()) { try { Node value = (Node) xpath.evaluate( "/project/component[@name='DefaultGradleProjectSettings']/option[@name='delegatedBuild']/@value", new InputSource(new FileInputStream(ideaWorkspace)), XPathConstants.NODE); if (value != null) { useGradlePaths = Boolean.parseBoolean(value.getTextContent()); return; } } catch (IOException | XPathExpressionException e) { e.printStackTrace(); } } // Fallback, in case someone has a file-based project instead of a directory-based project. final IdeaModel idea = project.getExtensions().findByType(IdeaModel.class); File ideaFileProject = project.file(idea != null ? idea.getProject().getOutputFile() : (project.getName() + ".ipr")); if (ideaFileProject.exists() && ideaFileProject.isFile()) { try { Node value = (Node) xpath.evaluate( "/project/component[@name='GradleSettings']/option[@name='linkedExternalProjectsSettings']/GradleProjectSettings/option[@name='delegatedBuild']/@value", new InputSource(new FileInputStream(ideaFileProject)), XPathConstants.NODE); if (value != null) { useGradlePaths = Boolean.parseBoolean(value.getTextContent()); return; } } catch (IOException | XPathExpressionException e) { e.printStackTrace(); } } } @Override @Nonnull protected Map<String, Document> createRunConfiguration(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final DocumentBuilder documentBuilder, List<String> additionalClientArgs) { final Map<String, Document> documents = new LinkedHashMap<>(); Map<String, Supplier<String>> updatedTokens = configureTokensLazy(project, runConfig, useGradlePaths ? mapModClassesToGradle(project, runConfig) : mapModClassesToIdea(project, runConfig) ); // Java run config final Document javaDocument = documentBuilder.newDocument(); { final Element rootElement = javaDocument.createElement("component"); { final Element configuration = javaDocument.createElement("configuration"); { configuration.setAttribute("default", "false"); configuration.setAttribute("name", runConfig.getUniqueName()); configuration.setAttribute("type", "Application"); configuration.setAttribute("factoryName", "Application"); configuration.setAttribute("singleton", runConfig.isSingleInstance() ? "true" : "false"); elementOption(javaDocument, configuration, "MAIN_CLASS_NAME", runConfig.getMain()); elementOption(javaDocument, configuration, "VM_PARAMETERS", getJvmArgs(runConfig, additionalClientArgs, updatedTokens)); elementOption(javaDocument, configuration, "PROGRAM_PARAMETERS", getArgs(runConfig, updatedTokens)); elementOption(javaDocument, configuration, "WORKING_DIRECTORY", replaceRootDirBy(project, runConfig.getWorkingDirectory(), "$PROJECT_DIR$")); final Element module = javaDocument.createElement("module"); { module.setAttribute("name", runConfig.getIdeaModule()); } configuration.appendChild(module); final Element envs = javaDocument.createElement("envs"); { runConfig.getEnvironment().forEach((name, value) -> { final Element envEntry = javaDocument.createElement("env"); { envEntry.setAttribute("name", name); envEntry.setAttribute("value", replaceRootDirBy(project, runConfig.replace(updatedTokens, value), "$PROJECT_DIR$")); } envs.appendChild(envEntry); }); } configuration.appendChild(envs); final Element methods = javaDocument.createElement("method"); { methods.setAttribute("v", "2"); final Element makeTask = javaDocument.createElement("option"); { makeTask.setAttribute("name", "Make"); makeTask.setAttribute("enabled", "true"); } methods.appendChild(makeTask); final Element gradleTask = javaDocument.createElement("option"); { gradleTask.setAttribute("name", "Gradle.BeforeRunTask"); gradleTask.setAttribute("enabled", "true"); gradleTask.setAttribute("tasks", project.getTasks().getByName("prepare" + Utils.capitalize(runConfig.getTaskName())).getPath()); gradleTask.setAttribute("externalProjectPath", "$PROJECT_DIR$"); } methods.appendChild(gradleTask); } configuration.appendChild(methods); } rootElement.appendChild(configuration); } javaDocument.appendChild(rootElement); } documents.put(runConfig.getUniqueFileName() + ".xml", javaDocument); return documents; } private static Stream<String> mapModClassesToIdea(@Nonnull final Project project, @Nonnull final RunConfig runConfig) { final IdeaModel idea = project.getExtensions().findByType(IdeaModel.class); JavaPluginExtension javaPlugin = project.getExtensions().getByType(JavaPluginExtension.class); SourceSetContainer sourceSets = javaPlugin.getSourceSets(); final SourceSet main = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME); if (runConfig.getMods().isEmpty()) { return getIdeaPathsForSourceset(project, idea, "production", null); } else { return runConfig.getMods().stream() .map(modConfig -> { return modConfig.getSources().stream().flatMap(source -> { String outName = source == main ? "production" : source.getName(); return getIdeaPathsForSourceset(project, idea, outName, modConfig.getName()); }); }) .flatMap(Function.identity()); } } private static Stream<String> getIdeaPathsForSourceset(@Nonnull Project project, @Nullable IdeaModel idea, String outName, @Nullable String modName) { String ideaResources, ideaClasses; try { String outputPath = idea != null ? idea.getProject().getPathFactory().path("$PROJECT_DIR$").getCanonicalUrl() : project.getProjectDir().getCanonicalPath(); ideaResources = Paths.get(outputPath, "out", outName, "resources").toFile().getCanonicalPath(); ideaClasses = Paths.get(outputPath, "out", outName, "classes").toFile().getCanonicalPath(); } catch (IOException e) { throw new RuntimeException("Error getting paths for idea run configs", e); } if (modName != null) { ideaResources = modName + "%%" + ideaResources; ideaClasses = modName + "%%" + ideaClasses; } return Stream.of(ideaResources, ideaClasses); } }
Fix IntelliJ run configurations for multiprojects built with IntelliJ (#851)
src/common/java/net/minecraftforge/gradle/common/util/runs/IntellijRunGenerator.java
Fix IntelliJ run configurations for multiprojects built with IntelliJ (#851)
<ide><path>rc/common/java/net/minecraftforge/gradle/common/util/runs/IntellijRunGenerator.java <ide> import org.gradle.api.Project; <ide> import org.gradle.api.plugins.JavaPluginExtension; <ide> import org.gradle.api.tasks.SourceSet; <del>import org.gradle.api.tasks.SourceSetContainer; <ide> import org.gradle.plugins.ide.idea.model.IdeaModel; <ide> import org.w3c.dom.Document; <ide> import org.w3c.dom.Element; <ide> import org.xml.sax.InputSource; <ide> <ide> import java.io.File; <del>import java.io.FileInputStream; <ide> import java.io.IOException; <add>import java.io.InputStream; <add>import java.nio.file.Files; <ide> import java.nio.file.Paths; <add>import java.util.IdentityHashMap; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <del>import java.util.function.Function; <ide> import java.util.function.Supplier; <ide> import java.util.stream.Stream; <ide> <ide> File ideaGradleSettings = project.file(".idea/gradle.xml"); <ide> if (ideaGradleSettings.exists() && ideaGradleSettings.isFile()) <ide> { <del> try <add> try (InputStream in = Files.newInputStream(ideaGradleSettings.toPath())) <ide> { <ide> Node value = (Node) xpath.evaluate( <ide> "/project/component[@name='GradleSettings']/option[@name='linkedExternalProjectsSettings']/GradleProjectSettings/option[@name='delegatedBuild']/@value", <del> new InputSource(new FileInputStream(ideaGradleSettings)), <add> new InputSource(in), <ide> XPathConstants.NODE); <ide> if (value != null) <ide> { <ide> File ideaWorkspace = project.file(".idea/workspace.xml"); <ide> if (ideaWorkspace.exists() && ideaWorkspace.isFile()) <ide> { <del> try <add> try (InputStream in = Files.newInputStream(ideaWorkspace.toPath())) <ide> { <ide> Node value = (Node) xpath.evaluate( <ide> "/project/component[@name='DefaultGradleProjectSettings']/option[@name='delegatedBuild']/@value", <del> new InputSource(new FileInputStream(ideaWorkspace)), <add> new InputSource(in), <ide> XPathConstants.NODE); <ide> if (value != null) <ide> { <ide> File ideaFileProject = project.file(idea != null ? idea.getProject().getOutputFile() : (project.getName() + ".ipr")); <ide> if (ideaFileProject.exists() && ideaFileProject.isFile()) <ide> { <del> try <add> try (InputStream in = Files.newInputStream(ideaFileProject.toPath())) <ide> { <ide> Node value = (Node) xpath.evaluate( <ide> "/project/component[@name='GradleSettings']/option[@name='linkedExternalProjectsSettings']/GradleProjectSettings/option[@name='delegatedBuild']/@value", <del> new InputSource(new FileInputStream(ideaFileProject)), <add> new InputSource(in), <ide> XPathConstants.NODE); <ide> if (value != null) <ide> { <ide> useGradlePaths = Boolean.parseBoolean(value.getTextContent()); <del> return; <ide> } <ide> } <ide> catch (IOException | XPathExpressionException e) <ide> } <ide> <ide> private static Stream<String> mapModClassesToIdea(@Nonnull final Project project, @Nonnull final RunConfig runConfig) { <del> final IdeaModel idea = project.getExtensions().findByType(IdeaModel.class); <del> <del> JavaPluginExtension javaPlugin = project.getExtensions().getByType(JavaPluginExtension.class); <del> SourceSetContainer sourceSets = javaPlugin.getSourceSets(); <del> final SourceSet main = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME); <add> final Map<SourceSet, Project> sourceSetsToProjects = new IdentityHashMap<>(); <add> <add> project.getRootProject().getAllprojects().forEach(proj -> { <add> final JavaPluginExtension javaPlugin = proj.getExtensions().findByType(JavaPluginExtension.class); <add> if (javaPlugin != null) { <add> for (SourceSet sourceSet : javaPlugin.getSourceSets()) { <add> sourceSetsToProjects.put(sourceSet, proj); <add> } <add> } <add> }); <add> <ide> if (runConfig.getMods().isEmpty()) { <add> final IdeaModel idea = project.getExtensions().findByType(IdeaModel.class); <ide> return getIdeaPathsForSourceset(project, idea, "production", null); <ide> } else { <ide> <ide> return runConfig.getMods().stream() <del> .map(modConfig -> { <del> return modConfig.getSources().stream().flatMap(source -> { <del> String outName = source == main ? "production" : source.getName(); <del> return getIdeaPathsForSourceset(project, idea, outName, modConfig.getName()); <del> }); <del> }) <del> .flatMap(Function.identity()); <add> .flatMap(modConfig -> modConfig.getSources().stream() <add> .flatMap(source -> { <add> String outName = source.getName().equals(SourceSet.MAIN_SOURCE_SET_NAME) ? "production" : source.getName(); <add> final Project sourceSetProject = sourceSetsToProjects.getOrDefault(source, project); <add> final IdeaModel ideaModel = sourceSetProject.getExtensions().findByType(IdeaModel.class); <add> return getIdeaPathsForSourceset(sourceSetProject, ideaModel, outName, modConfig.getName()); <add> })); <ide> } <ide> } <ide> <ide> try <ide> { <ide> String outputPath = idea != null <del> ? idea.getProject().getPathFactory().path("$PROJECT_DIR$").getCanonicalUrl() <add> ? idea.getModule().getPathFactory().path("$MODULE_DIR$").getCanonicalUrl() <ide> : project.getProjectDir().getCanonicalPath(); <ide> <ide> ideaResources = Paths.get(outputPath, "out", outName, "resources").toFile().getCanonicalPath();
Java
apache-2.0
afb2250201ea359959864c491f6857c27a8a31d6
0
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* * $Log: Wsdl.java,v $ * Revision 1.17 2012-10-11 09:10:43 m00f069 * To lower case on targetAddress destination (QUEUE -> queue) * * Revision 1.16 2012/10/10 09:43:53 Jaco de Groot <[email protected]> * Added comment on ESB_SOAP_JMS * * Revision 1.15 2012/10/04 11:28:57 Jaco de Groot <[email protected]> * Fixed ESB Soap namespace * Added location (url) of WSDL generation to the WSDL documentation * Show warning add the bottom of the WSDL (if any) instead of Ibis logging * * Revision 1.14 2012/10/03 14:30:46 Jaco de Groot <[email protected]> * Different filename for ESB Soap WSDL * * Revision 1.13 2012/10/03 12:22:41 Jaco de Groot <[email protected]> * Different transport uri, jndi properties and connectionFactory for ESB Soap. * Fill targetAddress with a value when running locally. * * Revision 1.12 2012/10/02 16:12:14 Jaco de Groot <[email protected]> * Bugfix for one-way WSDL (switched esbSoapOperationName and esbSoapOperationVersion). * Log a warning in case paradigm could not be extracted from the soap body. * * Revision 1.11 2012/10/01 15:23:44 Jaco de Groot <[email protected]> * Strip schemaLocation from xsd import in case of generated WSDL with inline XSD's. * * Revision 1.10 2012/09/28 14:39:47 Jaco de Groot <[email protected]> * Bugfix WSLD target namespace for ESB Soap, part XSD should be WSDL * * Revision 1.9 2012/09/27 14:28:59 Jaco de Groot <[email protected]> * Better error message / adapter name when constructor throws exception. * * Revision 1.8 2012/09/27 13:44:31 Jaco de Groot <[email protected]> * Updates in generating wsdl namespace, wsdl input message name, wsdl output message name, wsdl port type name and wsdl operation name in case of EsbSoap * * Revision 1.7 2012/09/26 12:41:05 Jaco de Groot <[email protected]> * Bugfix in WSDL generator: Wrong prefix being used in element attribute of PipeLineInput and PipeLineOutput message part when using EsbSoapValidator. * * Revision 1.6 2012/08/23 11:57:43 Jaco de Groot <[email protected]> * Updates from Michiel * * Revision 1.5 2012/05/08 15:53:59 Jaco de Groot <[email protected]> * Fix invalid chars in wsdl:service name. * * Revision 1.4 2012/03/30 17:03:45 Jaco de Groot <[email protected]> * Michiel added JMS binding/service to WSDL generator, made WSDL validator work for Bis WSDL and made console show syntax problems for schema's used in XmlValidator * * Revision 1.3 2012/03/16 15:35:43 Jaco de Groot <[email protected]> * Michiel added EsbSoapValidator and WsdlXmlValidator, made WSDL's available for all adapters and did a bugfix on XML Validator where it seems to be dependent on the order of specified XSD's * * Revision 1.2 2011/12/15 10:08:06 Jaco de Groot <[email protected]> * Added CVS log * */ package nl.nn.adapterframework.soap; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.naming.NamingException; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import nl.nn.adapterframework.core.IListener; import nl.nn.adapterframework.core.IPipe; import nl.nn.adapterframework.core.PipeLine; import nl.nn.adapterframework.extensions.esb.EsbSoapWrapperPipe; import nl.nn.adapterframework.http.WebServiceListener; import nl.nn.adapterframework.jms.JmsListener; import nl.nn.adapterframework.pipes.XmlValidator; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.ClassUtils; import org.apache.commons.lang.StringUtils; /** * Utility class to generate the WSDL. Straight-forwardly implemented using stax only. * * An object of this class represents the WSDL associated with one IBIS pipeline. * * * TODO http://cxf.547215.n5.nabble.com/ClassName-quot-is-already-defined-in-quot-during-compilation-after-code-generation-td4299849.html * * TODO perhaps use wsdl4j or easywsdl to generate the WSDL more genericly (for easy switching between 1.1 and 2.0). * * @author Michiel Meeuwissen */ class Wsdl { protected static final String XSD = XMLConstants.W3C_XML_SCHEMA_NS_URI;//"http://www.w3.org/2001/XMLSchema"; protected static final String WSDL = "http://schemas.xmlsoap.org/wsdl/"; protected static final String SOAP_WSDL = "http://schemas.xmlsoap.org/wsdl/soap/"; protected static final String SOAP_HTTP = "http://schemas.xmlsoap.org/soap/http"; protected static final String SOAP_JMS = "http://www.w3.org/2010/soapjms/"; protected static final String ESB_SOAP_JMS = "http://www.tibco.com/namespaces/ws/2004/soap/binding/JMS";//Tibco BW will not detect the transport when SOAP_JMS is being used instead protected static final String ESB_SOAP_JNDI = "http://www.tibco.com/namespaces/ws/2004/soap/apis/jndi"; protected static final String ESB_SOAP_TNS_BASE_URI = "http://nn.nl/WSDL"; protected static final QName NAME = new QName(null, "name"); protected static final QName TNS = new QName(null, "targetNamespace"); protected static final QName ELFORMDEFAULT = new QName(null, "elementFormDefault"); protected static final QName SCHEMA = new QName(XSD, "schema"); protected static final QName ELEMENT = new QName(XSD, "element"); protected static final QName IMPORT = new QName(XSD, "import"); protected static final QName INCLUDE = new QName(XSD, "include"); protected static final QName SCHEMALOCATION = new QName(null, "schemaLocation"); protected static final QName NAMESPACE = new QName(null, "namespace"); protected static final QName XMLNS = new QName(null, XMLConstants.XMLNS_ATTRIBUTE); private final String name; private final String filename; private final String targetNamespace; private final boolean indentWsdl; private final PipeLine pipeLine; private final XmlValidator inputValidator; private String webServiceListenerNamespace; private boolean recursiveXsds = false; private boolean includeXsds = false; private Set<XSD> xsds = null; private String wsdlInputMessageName = "PipeLineInput"; private String wsdlOutputMessageName = "PipeLineOutput"; private String wsdlPortTypeName = "PipeLine"; private String wsdlOperationName = "Process"; private boolean esbSoap = false; private String esbSoapBusinessDomain; private String esbSoapServiceName; private String esbSoapServiceContext; private String esbSoapServiceContextVersion; private String esbSoapOperationName; private String esbSoapOperationVersion; private String documentation; private List<String> warnings = new ArrayList<String>(); Wsdl(PipeLine pipeLine, boolean indent, String documentation) { this.pipeLine = pipeLine; this.indentWsdl = indent; this.documentation = documentation; this.name = this.pipeLine.getAdapter().getName(); if (this.name == null) { throw new IllegalArgumentException("The adapter '" + pipeLine.getAdapter() + "' has no name"); } inputValidator = (XmlValidator)pipeLine.getInputValidator(); if (inputValidator == null) { throw new IllegalStateException("The adapter '" + getName() + "' has no input validator"); } AppConstants appConstants = AppConstants.getInstance(); String tns = appConstants.getResolvedProperty("wsdl." + getName() + ".targetNamespace"); if (tns == null) { tns = appConstants.getResolvedProperty("wsdl.targetNamespace"); } if (tns == null) { EsbSoapWrapperPipe inputWrapper = getEsbSoapInputWrapper(); EsbSoapWrapperPipe outputWrapper = getEsbSoapOutputWrapper(); if (outputWrapper != null || (inputWrapper != null && EsbSoapWrapperPipe.isValidNamespace(getFirstNamespaceFromSchemaLocation(inputValidator)))) { esbSoap = true; String outputParadigm = null; if (outputWrapper != null) { esbSoapBusinessDomain = outputWrapper.getBusinessDomain(); esbSoapServiceName = outputWrapper.getServiceName(); esbSoapServiceContext = outputWrapper.getServiceContext(); esbSoapServiceContextVersion = outputWrapper.getServiceContextVersion(); esbSoapOperationName = outputWrapper.getOperationName(); esbSoapOperationVersion = outputWrapper.getOperationVersion(); outputParadigm = outputWrapper.getParadigm(); } else { // One-way WSDL String s = getFirstNamespaceFromSchemaLocation(inputValidator); int i = s.lastIndexOf('/'); esbSoapOperationVersion = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapOperationName = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceContextVersion = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceContext = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceName = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapBusinessDomain = s.substring(i + 1); } String wsdlType = "abstract"; for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof JmsListener) { wsdlType = "concrete"; } } filename = esbSoapBusinessDomain + "_" + esbSoapServiceName + "_" + esbSoapServiceContext + "_" + esbSoapServiceContextVersion + "_" + esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + wsdlType; tns = ESB_SOAP_TNS_BASE_URI + "/" + esbSoapBusinessDomain + "/" + esbSoapServiceName + "/" + esbSoapServiceContext + "/" + esbSoapServiceContextVersion; String inputParadigm = null; if (inputValidator instanceof SoapValidator) { String soapBody = ((SoapValidator)inputValidator).getSoapBody(); if (soapBody != null) { int i = soapBody.lastIndexOf('_'); if (i != -1) { inputParadigm = soapBody.substring(i + 1); } } } if (inputParadigm != null) { wsdlInputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + inputParadigm; } else { warn("Could not extract paradigm from soapBody attribute of inputValidator"); } if (outputParadigm != null) { wsdlOutputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + outputParadigm; } wsdlPortTypeName = esbSoapOperationName + "_Interface_" + esbSoapOperationVersion; wsdlOperationName = esbSoapOperationName + "_" + esbSoapOperationVersion; } else { filename = name; for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof WebServiceListener) { webServiceListenerNamespace = ((WebServiceListener)l).getServiceNamespaceURI(); tns = webServiceListenerNamespace; } } if (tns == null) { tns = getFirstNamespaceFromSchemaLocation(inputValidator); } if (tns != null) { if (tns.endsWith("/")) { tns = tns + "wsdl/"; } else { tns = tns + "/wsdl/"; } } else { tns = "${wsdl." + getName() + ".targetNamespace}"; } } } else { filename = name; } this.targetNamespace = WsdlUtils.validUri(tns); } /** * Writes the WSDL to an output stream * @param out * @param servlet The servlet what is used as the web service (because this needs to be present in the WSDL) * @throws XMLStreamException * @throws IOException */ public void wsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, URISyntaxException, NamingException { XMLStreamWriter w = WsdlUtils.createWriter(out, indentWsdl); w.writeStartDocument(WsdlUtils.ENCODING, "1.0"); w.setPrefix("wsdl", WSDL); w.setPrefix("xsd", XSD); w.setPrefix("soap", SOAP_WSDL); if (esbSoap) { w.setPrefix("jms", ESB_SOAP_JMS); w.setPrefix("jndi", ESB_SOAP_JNDI); } else { w.setPrefix("jms", SOAP_JMS); } w.setPrefix("ibis", getTargetNamespace()); for (XSD xsd : getXSDs()) { w.setPrefix(xsd.pref, xsd.nameSpace); } w.writeStartElement(WSDL, "definitions"); { w.writeNamespace("wsdl", WSDL); w.writeNamespace("xsd", XSD); w.writeNamespace("soap", SOAP_WSDL); if (esbSoap) { w.writeNamespace("jndi", ESB_SOAP_JNDI); } w.writeNamespace("ibis", getTargetNamespace()); for (XSD xsd : getXSDs()) { w.writeNamespace(xsd.pref, xsd.nameSpace); } w.writeAttribute("targetNamespace", getTargetNamespace()); documentation(w); types(w); messages(w); portType(w); binding(w); service(w, servlet); } w.writeEndDocument(); warnings(w); w.close(); } /** * Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's. * @see {@link #wsdl(java.io.OutputStream, String)} */ public void zip(OutputStream stream, String servletName) throws IOException, XMLStreamException, URISyntaxException, NamingException { ZipOutputStream out = new ZipOutputStream(stream); // First an entry for the WSDL itself: ZipEntry wsdlEntry = new ZipEntry(getFilename() + ".wsdl"); out.putNextEntry(wsdlEntry); wsdl(out, servletName); out.closeEntry(); //And then all XSD's setRecursiveXsds(true); Set<String> entries = new HashSet<String>(); Map<String, String> correctingNamespaces = new HashMap<String, String>(); for (XSD xsd : getXSDs()) { String zipName = xsd.getBaseUrl() + xsd.getName(); if (entries.add(zipName)) { ZipEntry xsdEntry = new ZipEntry(zipName); out.putNextEntry(xsdEntry); XMLStreamWriter writer = WsdlUtils.createWriter(out, false); WsdlUtils.includeXSD(xsd, writer, correctingNamespaces, true, false); out.closeEntry(); } else { warn("Duplicate xsds in " + this + " " + xsd + " " + getXSDs()); } } out.close(); } public String getName() { return name; } public String getFilename() { return filename; } protected String getTargetNamespace() { return targetNamespace; } private List<XSD> parseSchema(String schemaLocation) throws MalformedURLException, URISyntaxException { List<XSD> result = new ArrayList<XSD>(); if (schemaLocation != null) { String[] split = schemaLocation.split("\\s+"); if (split.length % 2 != 0) throw new IllegalStateException("The schema must exist from an even number of strings, but it is " + schemaLocation); for (int i = 0; i < split.length; i += 2) { result.add(getXSD(split[i], split[i + 1])); } } return result; } /** * Returns a map: namespace -> Collection of all relevant XSD's * @return * @throws XMLStreamException * @throws IOException */ Map<String, Collection<XSD>> getMappedXSDs() throws XMLStreamException, IOException, URISyntaxException { Map<String, Collection<XSD>> result = new HashMap<String, Collection<XSD>>(); for (XSD xsd : getXSDs()) { Collection<XSD> col = result.get(xsd.nameSpace); if (col == null) { col = new ArrayList<XSD>(); result.put(xsd.nameSpace, col); } col.add(xsd); } return result; } Set<XSD> getXSDs() throws IOException, XMLStreamException, URISyntaxException { if (xsds == null) { xsds = new TreeSet<XSD>(); String inputSchema = inputValidator.getSchema(); if (inputSchema != null) { // In case of a WebServiceListener using soap=true it might be // valid to use the schema attribute (in which case the schema // doesn't have a namespace) as the WebServiceListener will // remove the soap envelop and body element before it is // validated. In this case we use the serviceNamespaceURI from // the WebServiceListener as the namespace for the schema. if (webServiceListenerNamespace != null) { XSD x = getXSD(webServiceListenerNamespace, inputSchema); if (recursiveXsds) { x.getImportXSDs(xsds); } } else { throw new IllegalStateException("The adapter " + pipeLine + " has an input validator using the schema attribute but a namespace is required"); } } for (XSD x : parseSchema(inputValidator.getSchemaLocation())) { if (recursiveXsds) { x.getImportXSDs(xsds); } } XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator != null) { String outputSchema = outputValidator.getSchema(); if (outputSchema != null) { getXSD(null, outputSchema); } parseSchema(outputValidator.getSchemaLocation()); } } return xsds; } protected XSD getXSD(String nameSpace) throws IOException, XMLStreamException, URISyntaxException { if (nameSpace == null) throw new IllegalArgumentException("Cannot get an XSD for null namespace"); for (XSD xsd : getXSDs()) { if (xsd.nameSpace.equals(nameSpace)) { return xsd; } } throw new IllegalArgumentException("No xsd for namespace '" + nameSpace + "' found (known are " + getXSDs() + ")"); } /** * Outputs a 'documentation' section of the WSDL */ protected void documentation(XMLStreamWriter w) throws XMLStreamException { if (documentation != null) { w.writeStartElement(WSDL, "documentation"); w.writeCharacters(documentation); w.writeEndElement(); } } /** * Output the 'types' section of the WSDL * @param w * @throws XMLStreamException * @throws IOException */ protected void types(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "types"); Map<String, String> correctingNamesSpaces = new HashMap<String, String>(); if (includeXsds) { for (XSD xsd : getXSDs()) { WsdlUtils.includeXSD(xsd, w, correctingNamesSpaces, false, true); } } else { for (Map.Entry<String, Collection<XSD>> xsd: getMappedXSDs().entrySet()) { WsdlUtils.xsincludeXSDs(xsd.getKey(), xsd.getValue(), w, correctingNamesSpaces); } } w.writeEndElement(); } /** * Outputs the 'messages' section. * @param w * @throws XMLStreamException * @throws IOException */ protected void messages(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { message(w, "Header", getHeaderTags()); message(w, wsdlInputMessageName, getInputTags()); XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator != null) { Collection<QName> out = getOutputTags(); message(w, wsdlOutputMessageName, out); } else { // One-way WSDL } //message(w, "PipeLineFault", "error", "bla:bloe"); } protected void message(XMLStreamWriter w, String name, Collection<QName> tags) throws XMLStreamException, IOException { if (tags == null) throw new IllegalArgumentException("Tag cannot be null for " + name); if (!tags.isEmpty()) { w.writeStartElement(WSDL, "message"); w.writeAttribute("name", name); { for (QName tag : tags) { w.writeEmptyElement(WSDL, "part"); w.writeAttribute("name", getIbisName(tag)); String typ = tag.getPrefix() + ":" + tag.getLocalPart(); w.writeAttribute("element", typ); } } w.writeEndElement(); } } protected void portType(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "portType"); w.writeAttribute("name", wsdlPortTypeName); { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(WSDL, "input"); w.writeAttribute("message", "ibis:" + wsdlInputMessageName); if (getOutputTags() != null) { w.writeEmptyElement(WSDL, "output"); w.writeAttribute("message", "ibis:" + wsdlOutputMessageName); } /* w.writeEmptyElement(WSDL, "fault"); w.writeAttribute("message", "ibis:PipeLineFault"); */ } w.writeEndElement(); } w.writeEndElement(); } protected String getSoapAction() { AppConstants appConstants = AppConstants.getInstance(); String sa = appConstants.getResolvedProperty("wsdl." + getName() + ".soapAction"); if (sa != null) return sa; sa = appConstants.getResolvedProperty("wsdl.soapAction"); if (sa != null) return sa; if (esbSoapOperationName != null && esbSoapOperationVersion != null) { return esbSoapOperationName + "_" + esbSoapOperationVersion; } return "${wsdl." + getName() + ".soapAction}"; } private EsbSoapWrapperPipe getEsbSoapInputWrapper() { IPipe inputWrapper = pipeLine.getInputWrapper(); if (inputWrapper instanceof EsbSoapWrapperPipe) { return (EsbSoapWrapperPipe) inputWrapper; } return null; } private EsbSoapWrapperPipe getEsbSoapOutputWrapper() { IPipe outputWrapper = pipeLine.getOutputWrapper(); if (outputWrapper instanceof EsbSoapWrapperPipe) { return (EsbSoapWrapperPipe) outputWrapper; } return null; } protected void binding(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpBinding(w); } else if (listener instanceof JmsListener) { jmsBinding(w, (JmsListener) listener); } else { w.writeComment("Binding: Unrecognized listener " + listener.getClass() + ": " + listener.getName()); } } } protected void httpBinding(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("transport", SOAP_HTTP); w.writeAttribute("style", "document"); writeSoapOperation(w); } w.writeEndElement(); } protected void writeSoapOperation(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(SOAP_WSDL, "operation"); w.writeAttribute("style", "document"); w.writeAttribute("soapAction", getSoapAction()); w.writeStartElement(WSDL, "input"); { writeSoapHeader(w); Collection<QName> inputTags = getInputTags(); //w.writeEmptyElement(input.xsd.nameSpace, input.getRootTag()); w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, inputTags); w.writeAttribute("use", "literal"); } w.writeEndElement(); Collection<QName> outputTags = getOutputTags(); if (outputTags != null) { w.writeStartElement(WSDL, "output"); { writeSoapHeader(w); ///w.writeEmptyElement(outputTag.xsd.nameSpace, outputTag.getRootTag()); w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, outputTags); w.writeAttribute("use", "literal"); } w.writeEndElement(); } /* w.writeStartElement(WSDL, "fault"); { w.writeEmptyElement(SOAP_WSDL, "error"); w.writeAttribute("use", "literal"); } w.writeEndElement(); */ } w.writeEndElement(); } protected void writeSoapHeader(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { Collection<QName> headers = getHeaderTags(); if (! headers.isEmpty()) { if (headers.size() > 1) { warn("Can only deal with one soap header. Taking only the first of " + headers); } w.writeEmptyElement(SOAP_WSDL, "header"); w.writeAttribute("part", getIbisName(headers.iterator().next())); w.writeAttribute("use", "literal"); w.writeAttribute("message", "ibis:Header"); } } protected void writeParts(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException { StringBuilder builder = new StringBuilder(); for (QName outputTag : tags) { if (builder.length() > 0) builder.append(" "); builder.append(getIbisName(outputTag)); } w.writeAttribute("parts", builder.toString()); } protected String getIbisName(QName qname) { return qname.getLocalPart(); } protected void jmsBinding(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("style", "document"); if (esbSoap) { w.writeAttribute("transport", ESB_SOAP_JMS); w.writeEmptyElement(ESB_SOAP_JMS, "binding"); w.writeAttribute("messageFormat", "Text"); writeSoapOperation(w); } else { w.writeAttribute("transport", SOAP_JMS); } } w.writeEndElement(); } protected void service(XMLStreamWriter w, String servlet) throws XMLStreamException, NamingException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpService(w, servlet); } else if (listener instanceof JmsListener) { jmsService(w, (JmsListener) listener); } else { w.writeComment("Service: Unrecognized listener " + listener.getClass() + " " + listener); } } } protected void httpService(XMLStreamWriter w, String servlet) throws XMLStreamException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapHttp"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); w.writeAttribute("location", servlet); } w.writeEndElement(); } w.writeEndElement(); } protected void jmsService(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { if (!esbSoap) { // Per example of https://docs.jboss.org/author/display/JBWS/SOAP+over+JMS w.writeStartElement(SOAP_JMS, "jndiConnectionFactoryName"); w.writeCharacters(listener.getQueueConnectionFactoryName()); } w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapJMS"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); String destinationName = listener.getDestinationName(); if (destinationName != null) { w.writeAttribute("location", destinationName); } if (esbSoap) { writeEsbSoapJndiContext(w, listener); w.writeStartElement(ESB_SOAP_JMS, "connectionFactory"); { w.writeCharacters("externalJndiName-for-" + listener.getQueueConnectionFactoryName() + "-on-" + AppConstants.getInstance().getResolvedProperty("otap.stage")); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JMS, "targetAddress"); { w.writeAttribute("destination", listener.getDestinationType().toLowerCase()); String queueName = listener.getPhysicalDestinationShortName(); if (queueName == null) { queueName = "queueName-for-" + listener.getDestinationName() + "-on-" + AppConstants.getInstance().getResolvedProperty("otap.stage"); } w.writeCharacters(queueName); w.writeEndElement(); } } } w.writeEndElement(); } w.writeEndElement(); } protected void writeEsbSoapJndiContext(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(ESB_SOAP_JNDI, "context"); { w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.factory.initial"); w.writeAttribute("type", "java.lang.String"); w.writeCharacters("com.tibco.tibjms.naming.TibjmsInitialContextFactory"); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.provider.url"); w.writeAttribute("type", "java.lang.String"); String qcf = ""; String stage = ""; try { qcf = URLEncoder.encode( listener.getQueueConnectionFactoryName(), "UTF-8"); stage = URLEncoder.encode( AppConstants.getInstance().getResolvedProperty("otap.stage"), "UTF-8"); } catch (UnsupportedEncodingException e) { } w.writeCharacters("tibjmsnaming://host-for-" + qcf + "-on-" + stage + ":37222"); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.factory.object"); w.writeAttribute("type", "java.lang.String"); w.writeCharacters("com.tibco.tibjms.custom.CustomObjectFactory"); w.writeEndElement(); } } w.writeEndElement(); } protected void warnings(XMLStreamWriter w) throws XMLStreamException { for (String warning : warnings) { w.writeComment(warning); } } protected PipeLine getPipeLine() { return pipeLine; } protected Collection<QName> getHeaderTags(XmlValidator xmlValidator) throws XMLStreamException, IOException, URISyntaxException { if (xmlValidator instanceof SoapValidator) { String root = ((SoapValidator)xmlValidator).getSoapHeader(); QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } } return Collections.emptyList(); } protected Collection<QName> getRootTags(XmlValidator xmlValidator) throws IOException, XMLStreamException, URISyntaxException { String root; if (xmlValidator instanceof SoapValidator) { root = ((SoapValidator)xmlValidator).getSoapBody(); } else { root = xmlValidator.getRoot(); } QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } return Collections.emptyList(); } protected QName getRootTag(String tag) throws XMLStreamException, IOException, URISyntaxException { if (StringUtils.isNotEmpty(tag)) { for (XSD xsd : xsds) { for (String rootTag : xsd.rootTags) { if (tag.equals(rootTag)) { return xsd.getTag(tag); } } } warn("Root element '" + tag + "' not found in XSD's"); } return null; } protected Collection<QName> getHeaderTags() throws IOException, XMLStreamException, URISyntaxException { return getHeaderTags(inputValidator); } protected Collection<QName> getInputTags() throws IOException, XMLStreamException, URISyntaxException { return getRootTags(inputValidator); } protected Collection<QName> getOutputTags() throws IOException, XMLStreamException, URISyntaxException { XmlValidator outputValidator = (XmlValidator) getPipeLine().getOutputValidator(); if (outputValidator != null) { return getRootTags((XmlValidator) getPipeLine().getOutputValidator()); } else { // One-way WSDL return null; } } protected String getFirstNamespaceFromSchemaLocation(XmlValidator inputValidator) { String schemaLocation = inputValidator.getSchemaLocation(); if (schemaLocation != null) { String[] split = schemaLocation.split("\\s+"); if (split.length > 0) { return split[0]; } } return null; } protected void warn(String warning) { warning = "Warning: " + warning; if (!warnings.contains(warning)) { warnings.add(warning); } } private XSD getXSD(String ns, String resource) throws URISyntaxException { URI url = ClassUtils.getResourceURL(resource).toURI(); if (url == null) { throw new IllegalArgumentException("No such resource " + resource); } for (XSD xsd : xsds) { if (xsd.nameSpace == null) { if (xsd.url.equals(url)) { return xsd; } } else { if (xsd.nameSpace.equals(ns) && xsd.url.equals(url)){ return xsd; } } } XSD xsd = new XSD("", ns, url, xsds.size() + 1); xsds.add(xsd); return xsd; } public boolean isRecursiveXsds() { return recursiveXsds; } /** * Make an effort to collect all XSD's also the included ones in {@link #getXSDs()} * @param recursiveXsds */ public void setRecursiveXsds(boolean recursiveXsds) { this.recursiveXsds = recursiveXsds; xsds = null; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public boolean isIncludeXsds() { return includeXsds; } public void setIncludeXsds(boolean includeXsds) { this.includeXsds = includeXsds; } /* public void easywsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, SchemaException, URISyntaxException { Description description = WSDLFactory.newInstance().newDescription(AbsItfDescription.WSDLVersionConstants.WSDL11); SchemaFactory fact = SchemaFactory.newInstance(); Types t = description.getTypes(); for (XSD xsd : getXsds()) { description.addNamespace(xsd.pref, xsd.nameSpace); SchemaReader sr = fact.newSchemaReader(); Schema s = sr.read(xsd.url); t.addSchema(s); } InterfaceType it = description.createInterface(); Operation o = it.createOperation(); Input i = o.createInput(); i.setName("IbisInput"); //i. // s t.addOperation(it.createOperation()); description.addInterface(); Binding binding = description.createBinding(); BindingOperation op = binding.createBindingOperation(); //description.addBinding(binding); } */ }
JavaSource/nl/nn/adapterframework/soap/Wsdl.java
/* * $Log: Wsdl.java,v $ * Revision 1.16 2012-10-10 09:43:53 m00f069 * Added comment on ESB_SOAP_JMS * * Revision 1.15 2012/10/04 11:28:57 Jaco de Groot <[email protected]> * Fixed ESB Soap namespace * Added location (url) of WSDL generation to the WSDL documentation * Show warning add the bottom of the WSDL (if any) instead of Ibis logging * * Revision 1.14 2012/10/03 14:30:46 Jaco de Groot <[email protected]> * Different filename for ESB Soap WSDL * * Revision 1.13 2012/10/03 12:22:41 Jaco de Groot <[email protected]> * Different transport uri, jndi properties and connectionFactory for ESB Soap. * Fill targetAddress with a value when running locally. * * Revision 1.12 2012/10/02 16:12:14 Jaco de Groot <[email protected]> * Bugfix for one-way WSDL (switched esbSoapOperationName and esbSoapOperationVersion). * Log a warning in case paradigm could not be extracted from the soap body. * * Revision 1.11 2012/10/01 15:23:44 Jaco de Groot <[email protected]> * Strip schemaLocation from xsd import in case of generated WSDL with inline XSD's. * * Revision 1.10 2012/09/28 14:39:47 Jaco de Groot <[email protected]> * Bugfix WSLD target namespace for ESB Soap, part XSD should be WSDL * * Revision 1.9 2012/09/27 14:28:59 Jaco de Groot <[email protected]> * Better error message / adapter name when constructor throws exception. * * Revision 1.8 2012/09/27 13:44:31 Jaco de Groot <[email protected]> * Updates in generating wsdl namespace, wsdl input message name, wsdl output message name, wsdl port type name and wsdl operation name in case of EsbSoap * * Revision 1.7 2012/09/26 12:41:05 Jaco de Groot <[email protected]> * Bugfix in WSDL generator: Wrong prefix being used in element attribute of PipeLineInput and PipeLineOutput message part when using EsbSoapValidator. * * Revision 1.6 2012/08/23 11:57:43 Jaco de Groot <[email protected]> * Updates from Michiel * * Revision 1.5 2012/05/08 15:53:59 Jaco de Groot <[email protected]> * Fix invalid chars in wsdl:service name. * * Revision 1.4 2012/03/30 17:03:45 Jaco de Groot <[email protected]> * Michiel added JMS binding/service to WSDL generator, made WSDL validator work for Bis WSDL and made console show syntax problems for schema's used in XmlValidator * * Revision 1.3 2012/03/16 15:35:43 Jaco de Groot <[email protected]> * Michiel added EsbSoapValidator and WsdlXmlValidator, made WSDL's available for all adapters and did a bugfix on XML Validator where it seems to be dependent on the order of specified XSD's * * Revision 1.2 2011/12/15 10:08:06 Jaco de Groot <[email protected]> * Added CVS log * */ package nl.nn.adapterframework.soap; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.naming.NamingException; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import nl.nn.adapterframework.core.IListener; import nl.nn.adapterframework.core.IPipe; import nl.nn.adapterframework.core.PipeLine; import nl.nn.adapterframework.extensions.esb.EsbSoapWrapperPipe; import nl.nn.adapterframework.http.WebServiceListener; import nl.nn.adapterframework.jms.JmsListener; import nl.nn.adapterframework.pipes.XmlValidator; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.ClassUtils; import org.apache.commons.lang.StringUtils; /** * Utility class to generate the WSDL. Straight-forwardly implemented using stax only. * * An object of this class represents the WSDL associated with one IBIS pipeline. * * * TODO http://cxf.547215.n5.nabble.com/ClassName-quot-is-already-defined-in-quot-during-compilation-after-code-generation-td4299849.html * * TODO perhaps use wsdl4j or easywsdl to generate the WSDL more genericly (for easy switching between 1.1 and 2.0). * * @author Michiel Meeuwissen */ class Wsdl { protected static final String XSD = XMLConstants.W3C_XML_SCHEMA_NS_URI;//"http://www.w3.org/2001/XMLSchema"; protected static final String WSDL = "http://schemas.xmlsoap.org/wsdl/"; protected static final String SOAP_WSDL = "http://schemas.xmlsoap.org/wsdl/soap/"; protected static final String SOAP_HTTP = "http://schemas.xmlsoap.org/soap/http"; protected static final String SOAP_JMS = "http://www.w3.org/2010/soapjms/"; protected static final String ESB_SOAP_JMS = "http://www.tibco.com/namespaces/ws/2004/soap/binding/JMS";//Tibco BW will not detect the transport when SOAP_JMS is being used instead protected static final String ESB_SOAP_JNDI = "http://www.tibco.com/namespaces/ws/2004/soap/apis/jndi"; protected static final String ESB_SOAP_TNS_BASE_URI = "http://nn.nl/WSDL"; protected static final QName NAME = new QName(null, "name"); protected static final QName TNS = new QName(null, "targetNamespace"); protected static final QName ELFORMDEFAULT = new QName(null, "elementFormDefault"); protected static final QName SCHEMA = new QName(XSD, "schema"); protected static final QName ELEMENT = new QName(XSD, "element"); protected static final QName IMPORT = new QName(XSD, "import"); protected static final QName INCLUDE = new QName(XSD, "include"); protected static final QName SCHEMALOCATION = new QName(null, "schemaLocation"); protected static final QName NAMESPACE = new QName(null, "namespace"); protected static final QName XMLNS = new QName(null, XMLConstants.XMLNS_ATTRIBUTE); private final String name; private final String filename; private final String targetNamespace; private final boolean indentWsdl; private final PipeLine pipeLine; private final XmlValidator inputValidator; private String webServiceListenerNamespace; private boolean recursiveXsds = false; private boolean includeXsds = false; private Set<XSD> xsds = null; private String wsdlInputMessageName = "PipeLineInput"; private String wsdlOutputMessageName = "PipeLineOutput"; private String wsdlPortTypeName = "PipeLine"; private String wsdlOperationName = "Process"; private boolean esbSoap = false; private String esbSoapBusinessDomain; private String esbSoapServiceName; private String esbSoapServiceContext; private String esbSoapServiceContextVersion; private String esbSoapOperationName; private String esbSoapOperationVersion; private String documentation; private List<String> warnings = new ArrayList<String>(); Wsdl(PipeLine pipeLine, boolean indent, String documentation) { this.pipeLine = pipeLine; this.indentWsdl = indent; this.documentation = documentation; this.name = this.pipeLine.getAdapter().getName(); if (this.name == null) { throw new IllegalArgumentException("The adapter '" + pipeLine.getAdapter() + "' has no name"); } inputValidator = (XmlValidator)pipeLine.getInputValidator(); if (inputValidator == null) { throw new IllegalStateException("The adapter '" + getName() + "' has no input validator"); } AppConstants appConstants = AppConstants.getInstance(); String tns = appConstants.getResolvedProperty("wsdl." + getName() + ".targetNamespace"); if (tns == null) { tns = appConstants.getResolvedProperty("wsdl.targetNamespace"); } if (tns == null) { EsbSoapWrapperPipe inputWrapper = getEsbSoapInputWrapper(); EsbSoapWrapperPipe outputWrapper = getEsbSoapOutputWrapper(); if (outputWrapper != null || (inputWrapper != null && EsbSoapWrapperPipe.isValidNamespace(getFirstNamespaceFromSchemaLocation(inputValidator)))) { esbSoap = true; String outputParadigm = null; if (outputWrapper != null) { esbSoapBusinessDomain = outputWrapper.getBusinessDomain(); esbSoapServiceName = outputWrapper.getServiceName(); esbSoapServiceContext = outputWrapper.getServiceContext(); esbSoapServiceContextVersion = outputWrapper.getServiceContextVersion(); esbSoapOperationName = outputWrapper.getOperationName(); esbSoapOperationVersion = outputWrapper.getOperationVersion(); outputParadigm = outputWrapper.getParadigm(); } else { // One-way WSDL String s = getFirstNamespaceFromSchemaLocation(inputValidator); int i = s.lastIndexOf('/'); esbSoapOperationVersion = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapOperationName = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceContextVersion = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceContext = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceName = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapBusinessDomain = s.substring(i + 1); } String wsdlType = "abstract"; for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof JmsListener) { wsdlType = "concrete"; } } filename = esbSoapBusinessDomain + "_" + esbSoapServiceName + "_" + esbSoapServiceContext + "_" + esbSoapServiceContextVersion + "_" + esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + wsdlType; tns = ESB_SOAP_TNS_BASE_URI + "/" + esbSoapBusinessDomain + "/" + esbSoapServiceName + "/" + esbSoapServiceContext + "/" + esbSoapServiceContextVersion; String inputParadigm = null; if (inputValidator instanceof SoapValidator) { String soapBody = ((SoapValidator)inputValidator).getSoapBody(); if (soapBody != null) { int i = soapBody.lastIndexOf('_'); if (i != -1) { inputParadigm = soapBody.substring(i + 1); } } } if (inputParadigm != null) { wsdlInputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + inputParadigm; } else { warn("Could not extract paradigm from soapBody attribute of inputValidator"); } if (outputParadigm != null) { wsdlOutputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + outputParadigm; } wsdlPortTypeName = esbSoapOperationName + "_Interface_" + esbSoapOperationVersion; wsdlOperationName = esbSoapOperationName + "_" + esbSoapOperationVersion; } else { filename = name; for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof WebServiceListener) { webServiceListenerNamespace = ((WebServiceListener)l).getServiceNamespaceURI(); tns = webServiceListenerNamespace; } } if (tns == null) { tns = getFirstNamespaceFromSchemaLocation(inputValidator); } if (tns != null) { if (tns.endsWith("/")) { tns = tns + "wsdl/"; } else { tns = tns + "/wsdl/"; } } else { tns = "${wsdl." + getName() + ".targetNamespace}"; } } } else { filename = name; } this.targetNamespace = WsdlUtils.validUri(tns); } /** * Writes the WSDL to an output stream * @param out * @param servlet The servlet what is used as the web service (because this needs to be present in the WSDL) * @throws XMLStreamException * @throws IOException */ public void wsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, URISyntaxException, NamingException { XMLStreamWriter w = WsdlUtils.createWriter(out, indentWsdl); w.writeStartDocument(WsdlUtils.ENCODING, "1.0"); w.setPrefix("wsdl", WSDL); w.setPrefix("xsd", XSD); w.setPrefix("soap", SOAP_WSDL); if (esbSoap) { w.setPrefix("jms", ESB_SOAP_JMS); w.setPrefix("jndi", ESB_SOAP_JNDI); } else { w.setPrefix("jms", SOAP_JMS); } w.setPrefix("ibis", getTargetNamespace()); for (XSD xsd : getXSDs()) { w.setPrefix(xsd.pref, xsd.nameSpace); } w.writeStartElement(WSDL, "definitions"); { w.writeNamespace("wsdl", WSDL); w.writeNamespace("xsd", XSD); w.writeNamespace("soap", SOAP_WSDL); if (esbSoap) { w.writeNamespace("jndi", ESB_SOAP_JNDI); } w.writeNamespace("ibis", getTargetNamespace()); for (XSD xsd : getXSDs()) { w.writeNamespace(xsd.pref, xsd.nameSpace); } w.writeAttribute("targetNamespace", getTargetNamespace()); documentation(w); types(w); messages(w); portType(w); binding(w); service(w, servlet); } w.writeEndDocument(); warnings(w); w.close(); } /** * Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's. * @see {@link #wsdl(java.io.OutputStream, String)} */ public void zip(OutputStream stream, String servletName) throws IOException, XMLStreamException, URISyntaxException, NamingException { ZipOutputStream out = new ZipOutputStream(stream); // First an entry for the WSDL itself: ZipEntry wsdlEntry = new ZipEntry(getFilename() + ".wsdl"); out.putNextEntry(wsdlEntry); wsdl(out, servletName); out.closeEntry(); //And then all XSD's setRecursiveXsds(true); Set<String> entries = new HashSet<String>(); Map<String, String> correctingNamespaces = new HashMap<String, String>(); for (XSD xsd : getXSDs()) { String zipName = xsd.getBaseUrl() + xsd.getName(); if (entries.add(zipName)) { ZipEntry xsdEntry = new ZipEntry(zipName); out.putNextEntry(xsdEntry); XMLStreamWriter writer = WsdlUtils.createWriter(out, false); WsdlUtils.includeXSD(xsd, writer, correctingNamespaces, true, false); out.closeEntry(); } else { warn("Duplicate xsds in " + this + " " + xsd + " " + getXSDs()); } } out.close(); } public String getName() { return name; } public String getFilename() { return filename; } protected String getTargetNamespace() { return targetNamespace; } private List<XSD> parseSchema(String schemaLocation) throws MalformedURLException, URISyntaxException { List<XSD> result = new ArrayList<XSD>(); if (schemaLocation != null) { String[] split = schemaLocation.split("\\s+"); if (split.length % 2 != 0) throw new IllegalStateException("The schema must exist from an even number of strings, but it is " + schemaLocation); for (int i = 0; i < split.length; i += 2) { result.add(getXSD(split[i], split[i + 1])); } } return result; } /** * Returns a map: namespace -> Collection of all relevant XSD's * @return * @throws XMLStreamException * @throws IOException */ Map<String, Collection<XSD>> getMappedXSDs() throws XMLStreamException, IOException, URISyntaxException { Map<String, Collection<XSD>> result = new HashMap<String, Collection<XSD>>(); for (XSD xsd : getXSDs()) { Collection<XSD> col = result.get(xsd.nameSpace); if (col == null) { col = new ArrayList<XSD>(); result.put(xsd.nameSpace, col); } col.add(xsd); } return result; } Set<XSD> getXSDs() throws IOException, XMLStreamException, URISyntaxException { if (xsds == null) { xsds = new TreeSet<XSD>(); String inputSchema = inputValidator.getSchema(); if (inputSchema != null) { // In case of a WebServiceListener using soap=true it might be // valid to use the schema attribute (in which case the schema // doesn't have a namespace) as the WebServiceListener will // remove the soap envelop and body element before it is // validated. In this case we use the serviceNamespaceURI from // the WebServiceListener as the namespace for the schema. if (webServiceListenerNamespace != null) { XSD x = getXSD(webServiceListenerNamespace, inputSchema); if (recursiveXsds) { x.getImportXSDs(xsds); } } else { throw new IllegalStateException("The adapter " + pipeLine + " has an input validator using the schema attribute but a namespace is required"); } } for (XSD x : parseSchema(inputValidator.getSchemaLocation())) { if (recursiveXsds) { x.getImportXSDs(xsds); } } XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator != null) { String outputSchema = outputValidator.getSchema(); if (outputSchema != null) { getXSD(null, outputSchema); } parseSchema(outputValidator.getSchemaLocation()); } } return xsds; } protected XSD getXSD(String nameSpace) throws IOException, XMLStreamException, URISyntaxException { if (nameSpace == null) throw new IllegalArgumentException("Cannot get an XSD for null namespace"); for (XSD xsd : getXSDs()) { if (xsd.nameSpace.equals(nameSpace)) { return xsd; } } throw new IllegalArgumentException("No xsd for namespace '" + nameSpace + "' found (known are " + getXSDs() + ")"); } /** * Outputs a 'documentation' section of the WSDL */ protected void documentation(XMLStreamWriter w) throws XMLStreamException { if (documentation != null) { w.writeStartElement(WSDL, "documentation"); w.writeCharacters(documentation); w.writeEndElement(); } } /** * Output the 'types' section of the WSDL * @param w * @throws XMLStreamException * @throws IOException */ protected void types(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "types"); Map<String, String> correctingNamesSpaces = new HashMap<String, String>(); if (includeXsds) { for (XSD xsd : getXSDs()) { WsdlUtils.includeXSD(xsd, w, correctingNamesSpaces, false, true); } } else { for (Map.Entry<String, Collection<XSD>> xsd: getMappedXSDs().entrySet()) { WsdlUtils.xsincludeXSDs(xsd.getKey(), xsd.getValue(), w, correctingNamesSpaces); } } w.writeEndElement(); } /** * Outputs the 'messages' section. * @param w * @throws XMLStreamException * @throws IOException */ protected void messages(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { message(w, "Header", getHeaderTags()); message(w, wsdlInputMessageName, getInputTags()); XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator != null) { Collection<QName> out = getOutputTags(); message(w, wsdlOutputMessageName, out); } else { // One-way WSDL } //message(w, "PipeLineFault", "error", "bla:bloe"); } protected void message(XMLStreamWriter w, String name, Collection<QName> tags) throws XMLStreamException, IOException { if (tags == null) throw new IllegalArgumentException("Tag cannot be null for " + name); if (!tags.isEmpty()) { w.writeStartElement(WSDL, "message"); w.writeAttribute("name", name); { for (QName tag : tags) { w.writeEmptyElement(WSDL, "part"); w.writeAttribute("name", getIbisName(tag)); String typ = tag.getPrefix() + ":" + tag.getLocalPart(); w.writeAttribute("element", typ); } } w.writeEndElement(); } } protected void portType(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "portType"); w.writeAttribute("name", wsdlPortTypeName); { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(WSDL, "input"); w.writeAttribute("message", "ibis:" + wsdlInputMessageName); if (getOutputTags() != null) { w.writeEmptyElement(WSDL, "output"); w.writeAttribute("message", "ibis:" + wsdlOutputMessageName); } /* w.writeEmptyElement(WSDL, "fault"); w.writeAttribute("message", "ibis:PipeLineFault"); */ } w.writeEndElement(); } w.writeEndElement(); } protected String getSoapAction() { AppConstants appConstants = AppConstants.getInstance(); String sa = appConstants.getResolvedProperty("wsdl." + getName() + ".soapAction"); if (sa != null) return sa; sa = appConstants.getResolvedProperty("wsdl.soapAction"); if (sa != null) return sa; if (esbSoapOperationName != null && esbSoapOperationVersion != null) { return esbSoapOperationName + "_" + esbSoapOperationVersion; } return "${wsdl." + getName() + ".soapAction}"; } private EsbSoapWrapperPipe getEsbSoapInputWrapper() { IPipe inputWrapper = pipeLine.getInputWrapper(); if (inputWrapper instanceof EsbSoapWrapperPipe) { return (EsbSoapWrapperPipe) inputWrapper; } return null; } private EsbSoapWrapperPipe getEsbSoapOutputWrapper() { IPipe outputWrapper = pipeLine.getOutputWrapper(); if (outputWrapper instanceof EsbSoapWrapperPipe) { return (EsbSoapWrapperPipe) outputWrapper; } return null; } protected void binding(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpBinding(w); } else if (listener instanceof JmsListener) { jmsBinding(w, (JmsListener) listener); } else { w.writeComment("Binding: Unrecognized listener " + listener.getClass() + ": " + listener.getName()); } } } protected void httpBinding(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("transport", SOAP_HTTP); w.writeAttribute("style", "document"); writeSoapOperation(w); } w.writeEndElement(); } protected void writeSoapOperation(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(SOAP_WSDL, "operation"); w.writeAttribute("style", "document"); w.writeAttribute("soapAction", getSoapAction()); w.writeStartElement(WSDL, "input"); { writeSoapHeader(w); Collection<QName> inputTags = getInputTags(); //w.writeEmptyElement(input.xsd.nameSpace, input.getRootTag()); w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, inputTags); w.writeAttribute("use", "literal"); } w.writeEndElement(); Collection<QName> outputTags = getOutputTags(); if (outputTags != null) { w.writeStartElement(WSDL, "output"); { writeSoapHeader(w); ///w.writeEmptyElement(outputTag.xsd.nameSpace, outputTag.getRootTag()); w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, outputTags); w.writeAttribute("use", "literal"); } w.writeEndElement(); } /* w.writeStartElement(WSDL, "fault"); { w.writeEmptyElement(SOAP_WSDL, "error"); w.writeAttribute("use", "literal"); } w.writeEndElement(); */ } w.writeEndElement(); } protected void writeSoapHeader(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { Collection<QName> headers = getHeaderTags(); if (! headers.isEmpty()) { if (headers.size() > 1) { warn("Can only deal with one soap header. Taking only the first of " + headers); } w.writeEmptyElement(SOAP_WSDL, "header"); w.writeAttribute("part", getIbisName(headers.iterator().next())); w.writeAttribute("use", "literal"); w.writeAttribute("message", "ibis:Header"); } } protected void writeParts(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException { StringBuilder builder = new StringBuilder(); for (QName outputTag : tags) { if (builder.length() > 0) builder.append(" "); builder.append(getIbisName(outputTag)); } w.writeAttribute("parts", builder.toString()); } protected String getIbisName(QName qname) { return qname.getLocalPart(); } protected void jmsBinding(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("style", "document"); if (esbSoap) { w.writeAttribute("transport", ESB_SOAP_JMS); w.writeEmptyElement(ESB_SOAP_JMS, "binding"); w.writeAttribute("messageFormat", "Text"); writeSoapOperation(w); } else { w.writeAttribute("transport", SOAP_JMS); } } w.writeEndElement(); } protected void service(XMLStreamWriter w, String servlet) throws XMLStreamException, NamingException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpService(w, servlet); } else if (listener instanceof JmsListener) { jmsService(w, (JmsListener) listener); } else { w.writeComment("Service: Unrecognized listener " + listener.getClass() + " " + listener); } } } protected void httpService(XMLStreamWriter w, String servlet) throws XMLStreamException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapHttp"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); w.writeAttribute("location", servlet); } w.writeEndElement(); } w.writeEndElement(); } protected void jmsService(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { if (!esbSoap) { // Per example of https://docs.jboss.org/author/display/JBWS/SOAP+over+JMS w.writeStartElement(SOAP_JMS, "jndiConnectionFactoryName"); w.writeCharacters(listener.getQueueConnectionFactoryName()); } w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapJMS"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); String destinationName = listener.getDestinationName(); if (destinationName != null) { w.writeAttribute("location", destinationName); } if (esbSoap) { writeEsbSoapJndiContext(w, listener); w.writeStartElement(ESB_SOAP_JMS, "connectionFactory"); { w.writeCharacters("externalJndiName-for-" + listener.getQueueConnectionFactoryName() + "-on-" + AppConstants.getInstance().getResolvedProperty("otap.stage")); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JMS, "targetAddress"); { String destinationType = listener.getDestinationType(); if (destinationType != null) { w.writeAttribute("destination", destinationType); } String queueName = listener.getPhysicalDestinationShortName(); if (queueName == null) { queueName = "queueName-for-" + listener.getDestinationName() + "-on-" + AppConstants.getInstance().getResolvedProperty("otap.stage"); } w.writeCharacters(queueName); w.writeEndElement(); } } } w.writeEndElement(); } w.writeEndElement(); } protected void writeEsbSoapJndiContext(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(ESB_SOAP_JNDI, "context"); { w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.factory.initial"); w.writeAttribute("type", "java.lang.String"); w.writeCharacters("com.tibco.tibjms.naming.TibjmsInitialContextFactory"); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.provider.url"); w.writeAttribute("type", "java.lang.String"); String qcf = ""; String stage = ""; try { qcf = URLEncoder.encode( listener.getQueueConnectionFactoryName(), "UTF-8"); stage = URLEncoder.encode( AppConstants.getInstance().getResolvedProperty("otap.stage"), "UTF-8"); } catch (UnsupportedEncodingException e) { } w.writeCharacters("tibjmsnaming://host-for-" + qcf + "-on-" + stage + ":37222"); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.factory.object"); w.writeAttribute("type", "java.lang.String"); w.writeCharacters("com.tibco.tibjms.custom.CustomObjectFactory"); w.writeEndElement(); } } w.writeEndElement(); } protected void warnings(XMLStreamWriter w) throws XMLStreamException { for (String warning : warnings) { w.writeComment(warning); } } protected PipeLine getPipeLine() { return pipeLine; } protected Collection<QName> getHeaderTags(XmlValidator xmlValidator) throws XMLStreamException, IOException, URISyntaxException { if (xmlValidator instanceof SoapValidator) { String root = ((SoapValidator)xmlValidator).getSoapHeader(); QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } } return Collections.emptyList(); } protected Collection<QName> getRootTags(XmlValidator xmlValidator) throws IOException, XMLStreamException, URISyntaxException { String root; if (xmlValidator instanceof SoapValidator) { root = ((SoapValidator)xmlValidator).getSoapBody(); } else { root = xmlValidator.getRoot(); } QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } return Collections.emptyList(); } protected QName getRootTag(String tag) throws XMLStreamException, IOException, URISyntaxException { if (StringUtils.isNotEmpty(tag)) { for (XSD xsd : xsds) { for (String rootTag : xsd.rootTags) { if (tag.equals(rootTag)) { return xsd.getTag(tag); } } } warn("Root element '" + tag + "' not found in XSD's"); } return null; } protected Collection<QName> getHeaderTags() throws IOException, XMLStreamException, URISyntaxException { return getHeaderTags(inputValidator); } protected Collection<QName> getInputTags() throws IOException, XMLStreamException, URISyntaxException { return getRootTags(inputValidator); } protected Collection<QName> getOutputTags() throws IOException, XMLStreamException, URISyntaxException { XmlValidator outputValidator = (XmlValidator) getPipeLine().getOutputValidator(); if (outputValidator != null) { return getRootTags((XmlValidator) getPipeLine().getOutputValidator()); } else { // One-way WSDL return null; } } protected String getFirstNamespaceFromSchemaLocation(XmlValidator inputValidator) { String schemaLocation = inputValidator.getSchemaLocation(); if (schemaLocation != null) { String[] split = schemaLocation.split("\\s+"); if (split.length > 0) { return split[0]; } } return null; } protected void warn(String warning) { warning = "Warning: " + warning; if (!warnings.contains(warning)) { warnings.add(warning); } } private XSD getXSD(String ns, String resource) throws URISyntaxException { URI url = ClassUtils.getResourceURL(resource).toURI(); if (url == null) { throw new IllegalArgumentException("No such resource " + resource); } for (XSD xsd : xsds) { if (xsd.nameSpace == null) { if (xsd.url.equals(url)) { return xsd; } } else { if (xsd.nameSpace.equals(ns) && xsd.url.equals(url)){ return xsd; } } } XSD xsd = new XSD("", ns, url, xsds.size() + 1); xsds.add(xsd); return xsd; } public boolean isRecursiveXsds() { return recursiveXsds; } /** * Make an effort to collect all XSD's also the included ones in {@link #getXSDs()} * @param recursiveXsds */ public void setRecursiveXsds(boolean recursiveXsds) { this.recursiveXsds = recursiveXsds; xsds = null; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public boolean isIncludeXsds() { return includeXsds; } public void setIncludeXsds(boolean includeXsds) { this.includeXsds = includeXsds; } /* public void easywsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, SchemaException, URISyntaxException { Description description = WSDLFactory.newInstance().newDescription(AbsItfDescription.WSDLVersionConstants.WSDL11); SchemaFactory fact = SchemaFactory.newInstance(); Types t = description.getTypes(); for (XSD xsd : getXsds()) { description.addNamespace(xsd.pref, xsd.nameSpace); SchemaReader sr = fact.newSchemaReader(); Schema s = sr.read(xsd.url); t.addSchema(s); } InterfaceType it = description.createInterface(); Operation o = it.createOperation(); Input i = o.createInput(); i.setName("IbisInput"); //i. // s t.addOperation(it.createOperation()); description.addInterface(); Binding binding = description.createBinding(); BindingOperation op = binding.createBindingOperation(); //description.addBinding(binding); } */ }
To lower case on targetAddress destination (QUEUE -> queue)
JavaSource/nl/nn/adapterframework/soap/Wsdl.java
To lower case on targetAddress destination (QUEUE -> queue)
<ide><path>avaSource/nl/nn/adapterframework/soap/Wsdl.java <ide> /* <ide> * $Log: Wsdl.java,v $ <del> * Revision 1.16 2012-10-10 09:43:53 m00f069 <add> * Revision 1.17 2012-10-11 09:10:43 m00f069 <add> * To lower case on targetAddress destination (QUEUE -> queue) <add> * <add> * Revision 1.16 2012/10/10 09:43:53 Jaco de Groot <[email protected]> <ide> * Added comment on ESB_SOAP_JMS <ide> * <ide> * Revision 1.15 2012/10/04 11:28:57 Jaco de Groot <[email protected]> <ide> w.writeEndElement(); <ide> } <ide> w.writeStartElement(ESB_SOAP_JMS, "targetAddress"); { <del> String destinationType = listener.getDestinationType(); <del> if (destinationType != null) { <del> w.writeAttribute("destination", destinationType); <del> } <add> w.writeAttribute("destination", <add> listener.getDestinationType().toLowerCase()); <ide> String queueName = listener.getPhysicalDestinationShortName(); <ide> if (queueName == null) { <ide> queueName = "queueName-for-"
Java
mit
23feb819c2e2778f60e8a7a8096b92d4086ff3ea
0
jenkinsci/job-import-plugin,jenkinsci/job-import-plugin
/* * The MIT License * * Copyright (c) 2011, Jesse Farinacci * * 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 org.jenkins.ci.plugins.jobimport; import java.io.IOException; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * @author <a href="mailto:[email protected]">Jesse Farinacci</a> * @since 1.0 */ public final class RemoteJobUtils { private static final Logger LOG = Logger.getLogger(RemoteJobUtils.class.getName()); private static final XPathExpression XPATH_EXPRESSION_FREE_STYLE_PROJECT_DESCRIPTION; private static final XPathExpression XPATH_EXPRESSION_FREE_STYLE_PROJECT_NAME; private static final XPathExpression XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL; private static final XPathExpression XPATH_EXPRESSION_HUDSON_JOB_URL; private static final XPathExpression XPATH_EXPRESSION_LIST_VIEW_JOB_URL; private static final XPathExpression XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION; private static final XPathExpression XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME; private static final XPathExpression XPATH_EXPRESSION_MAVEN_MODULE_SET_URL; static { try { XPATH_EXPRESSION_FREE_STYLE_PROJECT_DESCRIPTION = XPathUtils.compile("/freeStyleProject/description"); XPATH_EXPRESSION_FREE_STYLE_PROJECT_NAME = XPathUtils.compile("/freeStyleProject/name"); XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL = XPathUtils.compile("/freeStyleProject/url"); XPATH_EXPRESSION_HUDSON_JOB_URL = XPathUtils.compile("/hudson/job/url"); XPATH_EXPRESSION_LIST_VIEW_JOB_URL = XPathUtils.compile("/listView/job/url"); XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION = XPathUtils.compile("/mavenModuleSet/description"); XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME = XPathUtils.compile("/mavenModuleSet/name"); XPATH_EXPRESSION_MAVEN_MODULE_SET_URL = XPathUtils.compile("/mavenModuleSet/url"); } catch (final XPathExpressionException e) { LOG.log(Level.WARNING, e.getMessage(), e); throw new IllegalStateException(e); } } protected static RemoteJob fromFreeStyleProjectXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { if (StringUtils.isEmpty(xml)) { return null; } if (!xml.startsWith("<freeStyleProject>")) { return null; } final Document document = XPathUtils.parse(xml); return new RemoteJob(XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_FREE_STYLE_PROJECT_NAME), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_FREE_STYLE_PROJECT_DESCRIPTION)); } protected static SortedSet<RemoteJob> fromHudsonXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { final SortedSet<RemoteJob> remoteJobs = new TreeSet<RemoteJob>(); if (StringUtils.isEmpty(xml)) { return remoteJobs; } if (!xml.startsWith("<hudson>")) { return remoteJobs; } final Document document = XPathUtils.parse(xml); for (final String jobUrl : XPathUtils.evaluateNodeListTextXPath(document, XPATH_EXPRESSION_HUDSON_JOB_URL)) { remoteJobs.addAll(fromXml(URLUtils.fetchUrl(jobUrl + "/api/xml"))); } return remoteJobs; } protected static SortedSet<RemoteJob> fromListViewXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { final SortedSet<RemoteJob> remoteJobs = new TreeSet<RemoteJob>(); if (StringUtils.isEmpty(xml)) { return remoteJobs; } if (!xml.startsWith("<listView>")) { return remoteJobs; } final Document document = XPathUtils.parse(xml); for (final String jobUrl : XPathUtils.evaluateNodeListTextXPath(document, XPATH_EXPRESSION_LIST_VIEW_JOB_URL)) { remoteJobs.addAll(fromXml(URLUtils.fetchUrl(jobUrl + "/api/xml"))); } return remoteJobs; } protected static RemoteJob fromMavenModuleSetXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { if (StringUtils.isEmpty(xml)) { return null; } if (!xml.startsWith("<mavenModuleSet>")) { return null; } final Document document = XPathUtils.parse(xml); return new RemoteJob(XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_MAVEN_MODULE_SET_URL), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION)); } public static SortedSet<RemoteJob> fromXml(final String xml) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException { final SortedSet<RemoteJob> remoteJobs = new TreeSet<RemoteJob>(); if (StringUtils.isEmpty(xml)) { return remoteJobs; } // --- if (xml.startsWith("<hudson>")) { remoteJobs.addAll(fromHudsonXml(xml)); } else if (xml.startsWith("<freeStyleProject>")) { remoteJobs.add(fromFreeStyleProjectXml(xml)); } else if (xml.startsWith("<listView>")) { remoteJobs.addAll(fromListViewXml(xml)); } else if (xml.startsWith("<mavenModuleSet>")) { remoteJobs.add(fromMavenModuleSetXml(xml)); } return remoteJobs; } /** * Static-only access. */ private RemoteJobUtils() { // static-only access } }
src/main/java/org/jenkins/ci/plugins/jobimport/RemoteJobUtils.java
/* * The MIT License * * Copyright (c) 2011, Jesse Farinacci * * 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 org.jenkins.ci.plugins.jobimport; import java.io.IOException; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * @author <a href="mailto:[email protected]">Jesse Farinacci</a> * @since 1.0 */ public final class RemoteJobUtils { private static final Logger LOG = Logger.getLogger(RemoteJobUtils.class.getName()); private static final XPathExpression XPATH_EXPRESSION_FREE_STYLE_PROJECT_DESCRIPTION; private static final XPathExpression XPATH_EXPRESSION_FREE_STYLE_PROJECT_NAME; private static final XPathExpression XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL; private static final XPathExpression XPATH_EXPRESSION_HUDSON_JOB_URL; private static final XPathExpression XPATH_EXPRESSION_LIST_VIEW_JOB_URL; private static final XPathExpression XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION; private static final XPathExpression XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME; private static final XPathExpression XPATH_EXPRESSION_MAVEN_MODULE_SET_URL; static { try { XPATH_EXPRESSION_FREE_STYLE_PROJECT_DESCRIPTION = XPathUtils.compile("/freeStyleProject/description"); XPATH_EXPRESSION_FREE_STYLE_PROJECT_NAME = XPathUtils.compile("/freeStyleProject/name"); XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL = XPathUtils.compile("/freeStyleProject/url"); XPATH_EXPRESSION_HUDSON_JOB_URL = XPathUtils.compile("/hudson/job/url"); XPATH_EXPRESSION_LIST_VIEW_JOB_URL = XPathUtils.compile("/listView/job/url"); XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION = XPathUtils.compile("/freeStyleProject/description"); XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME = XPathUtils.compile("/freeStyleProject/name"); XPATH_EXPRESSION_MAVEN_MODULE_SET_URL = XPathUtils.compile("/freeStyleProject/url"); } catch (final XPathExpressionException e) { LOG.log(Level.WARNING, e.getMessage(), e); throw new IllegalStateException(e); } } protected static RemoteJob fromFreeStyleProjectXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { if (StringUtils.isEmpty(xml)) { return null; } if (!xml.startsWith("<freeStyleProject>")) { return null; } final Document document = XPathUtils.parse(xml); return new RemoteJob(XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_FREE_STYLE_PROJECT_NAME), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_FREE_STYLE_PROJECT_DESCRIPTION)); } protected static SortedSet<RemoteJob> fromHudsonXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { final SortedSet<RemoteJob> remoteJobs = new TreeSet<RemoteJob>(); if (StringUtils.isEmpty(xml)) { return remoteJobs; } if (!xml.startsWith("<hudson>")) { return remoteJobs; } final Document document = XPathUtils.parse(xml); for (final String jobUrl : XPathUtils.evaluateNodeListTextXPath(document, XPATH_EXPRESSION_HUDSON_JOB_URL)) { remoteJobs.addAll(fromXml(URLUtils.fetchUrl(jobUrl + "/api/xml"))); } return remoteJobs; } protected static SortedSet<RemoteJob> fromListViewXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { final SortedSet<RemoteJob> remoteJobs = new TreeSet<RemoteJob>(); if (StringUtils.isEmpty(xml)) { return remoteJobs; } if (!xml.startsWith("<listView>")) { return remoteJobs; } final Document document = XPathUtils.parse(xml); for (final String jobUrl : XPathUtils.evaluateNodeListTextXPath(document, XPATH_EXPRESSION_LIST_VIEW_JOB_URL)) { remoteJobs.addAll(fromXml(URLUtils.fetchUrl(jobUrl + "/api/xml"))); } return remoteJobs; } protected static RemoteJob fromMavenModuleSetXml(final String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { if (StringUtils.isEmpty(xml)) { return null; } if (!xml.startsWith("<mavenModuleSet>")) { return null; } final Document document = XPathUtils.parse(xml); return new RemoteJob(XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_MAVEN_MODULE_SET_URL), XPathUtils.evaluateStringXPath(document, XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION)); } public static SortedSet<RemoteJob> fromXml(final String xml) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException { final SortedSet<RemoteJob> remoteJobs = new TreeSet<RemoteJob>(); if (StringUtils.isEmpty(xml)) { return remoteJobs; } // --- if (xml.startsWith("<hudson>")) { remoteJobs.addAll(fromHudsonXml(xml)); } else if (xml.startsWith("<freeStyleProject>")) { remoteJobs.add(fromFreeStyleProjectXml(xml)); } else if (xml.startsWith("<listView>")) { remoteJobs.addAll(fromListViewXml(xml)); } else if (xml.startsWith("<mavenModuleSet>")) { remoteJobs.add(fromMavenModuleSetXml(xml)); } return remoteJobs; } /** * Static-only access. */ private RemoteJobUtils() { // static-only access } }
copy and paste error
src/main/java/org/jenkins/ci/plugins/jobimport/RemoteJobUtils.java
copy and paste error
<ide><path>rc/main/java/org/jenkins/ci/plugins/jobimport/RemoteJobUtils.java <ide> XPATH_EXPRESSION_FREE_STYLE_PROJECT_URL = XPathUtils.compile("/freeStyleProject/url"); <ide> XPATH_EXPRESSION_HUDSON_JOB_URL = XPathUtils.compile("/hudson/job/url"); <ide> XPATH_EXPRESSION_LIST_VIEW_JOB_URL = XPathUtils.compile("/listView/job/url"); <del> XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION = XPathUtils.compile("/freeStyleProject/description"); <del> XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME = XPathUtils.compile("/freeStyleProject/name"); <del> XPATH_EXPRESSION_MAVEN_MODULE_SET_URL = XPathUtils.compile("/freeStyleProject/url"); <add> XPATH_EXPRESSION_MAVEN_MODULE_SET_DESCRIPTION = XPathUtils.compile("/mavenModuleSet/description"); <add> XPATH_EXPRESSION_MAVEN_MODULE_SET_NAME = XPathUtils.compile("/mavenModuleSet/name"); <add> XPATH_EXPRESSION_MAVEN_MODULE_SET_URL = XPathUtils.compile("/mavenModuleSet/url"); <ide> } <ide> <ide> catch (final XPathExpressionException e) {
Java
mit
6d5a1031154d81d19f42abba20b6e93868f3e521
0
copygirl/AdvHealthOptions
package net.mcft.copy.aho.config; import java.io.File; import net.mcft.copy.core.copycore; import net.mcft.copy.core.config.Config; import net.mcft.copy.core.config.setting.BooleanSetting; import net.mcft.copy.core.config.setting.DoubleSetting; import net.mcft.copy.core.config.setting.EnumSetting; import net.mcft.copy.core.config.setting.IntegerSetting; import net.mcft.copy.core.config.setting.Setting; public class AHOWorldConfig extends Config { // General public static final String generalPreset = "general.preset"; // Regeneration public static final String regenHealTime = "regeneration.healTime"; public static final String regenHungerMinimum = "regeneration.hungerMinimum"; public static final String regenHungerMaximum = "regeneration.hungerMaximum"; public static final String regenExhaustion = "regeneration.exhaustion"; public static final String regenHungerPoisonFactor = "regeneration.hungerPoisonFactor"; // Hurt penalty public static final String hurtPenaltyTime = "hurtPenalty.time"; public static final String hurtPenaltyTimeMaximum = "hurtPenalty.timeMaximum"; public static final String hurtPenaltyMaximum = "hurtPenalty.maximum"; public static final String hurtPenaltyBuffer = "hurtPenalty.buffer"; // Respawn public static final String respawnHealth = "respawn.health"; public static final String respawnFood = "respawn.food"; public static final String respawnShield = "respawn.shield"; public static final String respawnHurtPenalty = "respawn.hurtPenalty"; // Shield public static final String shieldMode = "shield.mode"; public static final String shieldMaximum = "shield.maximum"; public static final String shieldMaximumArmor = "shield.maximumArmor"; public static final String shieldTimeout = "shield.timeout"; public static final String shieldRechargeTime = "shield.rechargeTime"; public static final String shieldRequirement = "shield.requirement"; // Miscellaneous public static final String hunger = "misc.hunger"; public final File file; public AHOWorldConfig(File file) { super(file, copycore.MOD_ID); this.file = file; // General new EnumSetting(this, generalPreset, EnumPreset.NORMAL) .setComment("Choose a preset you want to go with, or CUSTOM if you want to build your own.\n" + "WARNING: If you select anything other than CUSTOM, all settings will be overwritten!\n" + "Valid values are PEACEFUL, EASY, NORMAL, HARD, HARDCORE, ULTRAHARDCORE, CUSTOM."); // Regeneration new DoubleSetting(this, regenHealTime, EnumPreset.NORMAL.regenHealTime).setValidRange(0.0, Double.MAX_VALUE) .setComment("Minimum time in seconds between healing half a heart. Use 0 to disable."); new IntegerSetting(this, regenHungerMinimum, EnumPreset.NORMAL.regenHungerMinimum).setValidRange(0, 20) .setComment("Natural regeneration starts at this hunger level. Valid values: 0 - 20."); new IntegerSetting(this, regenHungerMaximum, EnumPreset.NORMAL.regenHungerMaximum).setValidRange(0, 20) .setComment("Natural regeneration is at its maximum at this hunger level. Valid values: 0 - 20."); new DoubleSetting(this, regenExhaustion, EnumPreset.NORMAL.regenExhaustion).setValidRange(0.0, Double.MAX_VALUE) .setComment("Exhaustion added when healing naturally (higher = more food needed)."); new DoubleSetting(this, regenHungerPoisonFactor, EnumPreset.NORMAL.regenHungerFactor).setValidRange(0.0, 1.0) .setComment("Regeneration speed is multiplied by this if food poisoned (for example from rotten flesh)."); // Hurt penalty addCategoryComment("hurtPenalty", "When taking damage, a variable amount of 'penalty time' is added.\n" + "During this time, health regeneration is decreased or completely inactive."); new DoubleSetting(this, hurtPenaltyTime, EnumPreset.NORMAL.hurtTime).setValidRange(0.0, Double.MAX_VALUE) .setComment("Penalty time in seconds added per point of damage (= half a heart).\n" + "When no damage is taken from a hit, half of this value is added instead."); new DoubleSetting(this, hurtPenaltyTimeMaximum, EnumPreset.NORMAL.hurtTimeMaximum).setValidRange(0.0, Double.MAX_VALUE) .setComment("Maximum penalty time added at once when taking damage."); new DoubleSetting(this, hurtPenaltyMaximum, EnumPreset.NORMAL.hurtMaximum).setValidRange(0.0, Double.MAX_VALUE) .setComment("Maximum penalty time that can be accumulated."); new DoubleSetting(this, hurtPenaltyBuffer, EnumPreset.NORMAL.hurtBuffer).setValidRange(0.0, Double.MAX_VALUE) .setComment("Penalty time where regeneration speed decreases linearly.\n" + "When the penalty time is larger than this amount, regeneration is inactive."); // Respawn new IntegerSetting(this, respawnHealth, EnumPreset.NORMAL.respawnHealth).setValidRange(1, 20) .setComment("Health players respawn with after death. Valid values: 1 - 20."); new IntegerSetting(this, respawnFood, EnumPreset.NORMAL.respawnFood).setValidRange(0, 20) .setComment("Food players respawn with after death. Valid values: 0 - 20."); new IntegerSetting(this, respawnShield, EnumPreset.NORMAL.respawnShield).setValidRange(0, 40) .setComment("Shield points players respawn with after death.\n" + "The shield remains until it's used up. Valid values: 0 - 40."); new DoubleSetting(this, respawnHurtPenalty, EnumPreset.NORMAL.respawnPenalty).setValidRange(0, Double.MAX_VALUE) .setComment("Penalty time players respawn with after death.\n" + "Can be larger than the maximum hurt penalty time."); // Shield new EnumSetting(this, shieldMode, EnumShieldMode.ABSORPTION) .setComment("ABSORPTION = Uses vanilla absorption hearts, applied after armor.\n" + "SUBTRACTION = Decreases damage taken before armor calculation."); new IntegerSetting(this, shieldMaximum).setValidRange(0, 40) .setComment("Maximum shield points that can be recharged. Use 0 to disable. Valid values: 0 - 40."); new BooleanSetting(this, shieldMaximumArmor) .setComment("When enabled, total armor points affect the maximum shield capacity."); new DoubleSetting(this, shieldTimeout).setValidRange(0, Double.MAX_VALUE) .setComment("Time for which the shield doesn't recharge after being hit."); new DoubleSetting(this, shieldRechargeTime).setValidRange(0, Double.MAX_VALUE) .setComment("Time it takes to recharge one shield point."); new EnumSetting(this, shieldRequirement, EnumShieldReq.NONE) .setComment("NONE = Both shield and health can regenerate at the same time.\n" + "SHIELD_REQ_HEALTH = Full health is required for the shield to recharge.\n" + "HEALTH_REQ_SHIELD = Health regeneration is paused while shield is not full."); // Miscellaneous new EnumSetting(this, hunger, EnumHunger.ENABLE).setSynced() .setComment("ENABLE = Hunger functions like normal and affects regeneration speed.\n" + "DISABLE = Hunger is completely disabled, food can be eaten but is ignored.\n" + "HEALTH = Hunger is disabled, eating food directly translates to health.\n" + "When hunger is disabled the food meter will internally be locked at 8, enough to sprint."); } @Override public void load() { super.load(); // If the preset setting is set to anything other // than CUSTOM, change all settings to the preset's. EnumPreset preset = getEnum(AHOWorldConfig.generalPreset); if (preset != EnumPreset.CUSTOM) usePreset(preset); } /** Loads settings from the config file or uses settings from the global config. */ public void load(AHOGlobalConfig config) { if (file.exists()) this.load(); else for (Setting setting : settings.values()) setting.setValue(config.get(setting.fullName).getValue()); } /** Changes the config settings to use the preset's values. */ public void usePreset(EnumPreset preset) { get(generalPreset).setValue(preset); get(regenHealTime).setValue(preset.regenHealTime); get(regenHungerMinimum).setValue(preset.regenHungerMinimum); get(regenHungerMaximum).setValue(preset.regenHungerMaximum); get(regenExhaustion).setValue(preset.regenExhaustion); get(hurtPenaltyTime).setValue(preset.hurtTime); get(hurtPenaltyTimeMaximum).setValue(preset.hurtTimeMaximum); get(hurtPenaltyMaximum).setValue(preset.hurtMaximum); get(hurtPenaltyBuffer).setValue(preset.hurtBuffer); get(respawnHealth).setValue(preset.respawnHealth); get(respawnFood).setValue(preset.respawnFood); get(respawnHurtPenalty).setValue(preset.respawnPenalty); get(respawnShield).setValue(preset.respawnShield); } }
src/net/mcft/copy/aho/config/AHOWorldConfig.java
package net.mcft.copy.aho.config; import java.io.File; import net.mcft.copy.core.config.Config; import net.mcft.copy.core.config.setting.BooleanSetting; import net.mcft.copy.core.config.setting.DoubleSetting; import net.mcft.copy.core.config.setting.EnumSetting; import net.mcft.copy.core.config.setting.IntegerSetting; import net.mcft.copy.core.config.setting.Setting; public class AHOWorldConfig extends Config { // General public static final String generalPreset = "general.preset"; // Regeneration public static final String regenHealTime = "regeneration.healTime"; public static final String regenHungerMinimum = "regeneration.hungerMinimum"; public static final String regenHungerMaximum = "regeneration.hungerMaximum"; public static final String regenExhaustion = "regeneration.exhaustion"; public static final String regenHungerPoisonFactor = "regeneration.hungerPoisonFactor"; // Hurt penalty public static final String hurtPenaltyTime = "hurtPenalty.time"; public static final String hurtPenaltyTimeMaximum = "hurtPenalty.timeMaximum"; public static final String hurtPenaltyMaximum = "hurtPenalty.maximum"; public static final String hurtPenaltyBuffer = "hurtPenalty.buffer"; // Respawn public static final String respawnHealth = "respawn.health"; public static final String respawnFood = "respawn.food"; public static final String respawnShield = "respawn.shield"; public static final String respawnHurtPenalty = "respawn.hurtPenalty"; // Shield public static final String shieldMode = "shield.mode"; public static final String shieldMaximum = "shield.maximum"; public static final String shieldMaximumArmor = "shield.maximumArmor"; public static final String shieldTimeout = "shield.timeout"; public static final String shieldRechargeTime = "shield.rechargeTime"; public static final String shieldRequirement = "shield.requirement"; // Miscellaneous public static final String hunger = "misc.hunger"; public final File file; public AHOWorldConfig(File file) { super(file); this.file = file; // General new EnumSetting(this, generalPreset, EnumPreset.NORMAL) .setComment("Choose a preset you want to go with, or CUSTOM if you want to build your own.\n" + "WARNING: If you select anything other than CUSTOM, all settings will be overwritten!\n" + "Valid values are PEACEFUL, EASY, NORMAL, HARD, HARDCORE, ULTRAHARDCORE, CUSTOM."); // Regeneration new DoubleSetting(this, regenHealTime, EnumPreset.NORMAL.regenHealTime).setValidRange(0.0, Double.MAX_VALUE) .setComment("Minimum time in seconds between healing half a heart. Use 0 to disable."); new IntegerSetting(this, regenHungerMinimum, EnumPreset.NORMAL.regenHungerMinimum).setValidRange(0, 20) .setComment("Natural regeneration starts at this hunger level. Valid values: 0 - 20."); new IntegerSetting(this, regenHungerMaximum, EnumPreset.NORMAL.regenHungerMaximum).setValidRange(0, 20) .setComment("Natural regeneration is at its maximum at this hunger level. Valid values: 0 - 20."); new DoubleSetting(this, regenExhaustion, EnumPreset.NORMAL.regenExhaustion).setValidRange(0.0, Double.MAX_VALUE) .setComment("Exhaustion added when healing naturally (higher = more food needed)."); new DoubleSetting(this, regenHungerPoisonFactor, EnumPreset.NORMAL.regenHungerFactor).setValidRange(0.0, 1.0) .setComment("Regeneration speed is multiplied by this if food poisoned (for example from rotten flesh)."); // Hurt penalty addCategoryComment("hurtPenalty", "When taking damage, a variable amount of 'penalty time' is added.\n" + "During this time, health regeneration is decreased or completely inactive."); new DoubleSetting(this, hurtPenaltyTime, EnumPreset.NORMAL.hurtTime).setValidRange(0.0, Double.MAX_VALUE) .setComment("Penalty time in seconds added per point of damage (= half a heart).\n" + "When no damage is taken from a hit, half of this value is added instead."); new DoubleSetting(this, hurtPenaltyTimeMaximum, EnumPreset.NORMAL.hurtTimeMaximum).setValidRange(0.0, Double.MAX_VALUE) .setComment("Maximum penalty time added at once when taking damage."); new DoubleSetting(this, hurtPenaltyMaximum, EnumPreset.NORMAL.hurtMaximum).setValidRange(0.0, Double.MAX_VALUE) .setComment("Maximum penalty time that can be accumulated."); new DoubleSetting(this, hurtPenaltyBuffer, EnumPreset.NORMAL.hurtBuffer).setValidRange(0.0, Double.MAX_VALUE) .setComment("Penalty time where regeneration speed decreases linearly.\n" + "When the penalty time is larger than this amount, regeneration is inactive."); // Respawn new IntegerSetting(this, respawnHealth, EnumPreset.NORMAL.respawnHealth).setValidRange(1, 20) .setComment("Health players respawn with after death. Valid values: 1 - 20."); new IntegerSetting(this, respawnFood, EnumPreset.NORMAL.respawnFood).setValidRange(0, 20) .setComment("Food players respawn with after death. Valid values: 0 - 20."); new IntegerSetting(this, respawnShield, EnumPreset.NORMAL.respawnShield).setValidRange(0, 40) .setComment("Shield points players respawn with after death.\n" + "The shield remains until it's used up. Valid values: 0 - 40."); new DoubleSetting(this, respawnHurtPenalty, EnumPreset.NORMAL.respawnPenalty).setValidRange(0, Double.MAX_VALUE) .setComment("Penalty time players respawn with after death.\n" + "Can be larger than the maximum hurt penalty time."); // Shield new EnumSetting(this, shieldMode, EnumShieldMode.ABSORPTION) .setComment("ABSORPTION = Uses vanilla absorption hearts, applied after armor.\n" + "SUBTRACTION = Decreases damage taken before armor calculation."); new IntegerSetting(this, shieldMaximum).setValidRange(0, 40) .setComment("Maximum shield points that can be recharged. Use 0 to disable. Valid values: 0 - 40."); new BooleanSetting(this, shieldMaximumArmor) .setComment("When enabled, total armor points affect the maximum shield capacity."); new DoubleSetting(this, shieldTimeout).setValidRange(0, Double.MAX_VALUE) .setComment("Time for which the shield doesn't recharge after being hit."); new DoubleSetting(this, shieldRechargeTime).setValidRange(0, Double.MAX_VALUE) .setComment("Time it takes to recharge one shield point."); new EnumSetting(this, shieldRequirement, EnumShieldReq.NONE) .setComment("NONE = Both shield and health can regenerate at the same time.\n" + "SHIELD_REQ_HEALTH = Full health is required for the shield to recharge.\n" + "HEALTH_REQ_SHIELD = Health regeneration is paused while shield is not full."); // Miscellaneous new EnumSetting(this, hunger, EnumHunger.ENABLE).setSynced() .setComment("ENABLE = Hunger functions like normal and affects regeneration speed.\n" + "DISABLE = Hunger is completely disabled, food can be eaten but is ignored.\n" + "HEALTH = Hunger is disabled, eating food directly translates to health.\n" + "When hunger is disabled the food meter will internally be locked at 8, enough to sprint."); } @Override public void load() { super.load(); // If the preset setting is set to anything other // than CUSTOM, change all settings to the preset's. EnumPreset preset = getEnum(AHOWorldConfig.generalPreset); if (preset != EnumPreset.CUSTOM) usePreset(preset); } /** Loads settings from the config file or uses settings from the global config. */ public void load(AHOGlobalConfig config) { if (file.exists()) this.load(); else for (Setting setting : settings.values()) setting.setValue(config.get(setting.fullName).getValue()); } /** Changes the config settings to use the preset's values. */ public void usePreset(EnumPreset preset) { get(generalPreset).setValue(preset); get(regenHealTime).setValue(preset.regenHealTime); get(regenHungerMinimum).setValue(preset.regenHungerMinimum); get(regenHungerMaximum).setValue(preset.regenHungerMaximum); get(regenExhaustion).setValue(preset.regenExhaustion); get(hurtPenaltyTime).setValue(preset.hurtTime); get(hurtPenaltyTimeMaximum).setValue(preset.hurtTimeMaximum); get(hurtPenaltyMaximum).setValue(preset.hurtMaximum); get(hurtPenaltyBuffer).setValue(preset.hurtBuffer); get(respawnHealth).setValue(preset.respawnHealth); get(respawnFood).setValue(preset.respawnFood); get(respawnHurtPenalty).setValue(preset.respawnPenalty); get(respawnShield).setValue(preset.respawnShield); } }
Fix AHOWorldConfig tripping up getActiveModId
src/net/mcft/copy/aho/config/AHOWorldConfig.java
Fix AHOWorldConfig tripping up getActiveModId
<ide><path>rc/net/mcft/copy/aho/config/AHOWorldConfig.java <ide> <ide> import java.io.File; <ide> <add>import net.mcft.copy.core.copycore; <ide> import net.mcft.copy.core.config.Config; <ide> import net.mcft.copy.core.config.setting.BooleanSetting; <ide> import net.mcft.copy.core.config.setting.DoubleSetting; <ide> public final File file; <ide> <ide> public AHOWorldConfig(File file) { <del> super(file); <add> super(file, copycore.MOD_ID); <ide> this.file = file; <ide> <ide> // General
Java
apache-2.0
8960a20e89d61899ae40b7849ad4abfd50c4f8f7
0
jaychang0917/SimpleRecyclerView,jaychang0917/SimpleRecyclerView
package com.jaychang.srv; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; public abstract class SimpleCell<T, VH extends SimpleViewHolder> { public interface OnCellClickListener<T> { void onCellClicked(@NonNull T item); } public interface OnCellLongClickListener<T> { void onCellLongClicked(@NonNull T item); } public interface OnCellClickListener2<CELL, VH, T> { void onCellClicked(@NonNull CELL cell, @NonNull VH viewHolder, @NonNull T item); } public interface OnCellLongClickListener2<CELL, VH, T> { void onCellLongClicked(@NonNull CELL cell, @NonNull VH viewHolder, @NonNull T item); } private int spanSize = 1; private T item; private OnCellClickListener onCellClickListener; private OnCellClickListener2 onCellClickListener2; private OnCellLongClickListener onCellLongClickListener; private OnCellLongClickListener2 onCellLongClickListener2; public SimpleCell(@NonNull T item) { this.item = item; } @LayoutRes protected abstract int getLayoutRes(); @NonNull protected abstract VH onCreateViewHolder(@NonNull ViewGroup parent, @NonNull View cellView); protected abstract void onBindViewHolder(@NonNull VH holder, int position, @NonNull Context context, Object payload); protected void onUnbindViewHolder(@NonNull VH holder) { } @NonNull public T getItem() { return item; } public void setItem(@NonNull T item) { this.item = item; } protected abstract long getItemId(); public int getSpanSize() { return spanSize; } public void setSpanSize(int spanSize) { this.spanSize = spanSize; } public void setOnCellClickListener(@NonNull OnCellClickListener onCellClickListener) { this.onCellClickListener = onCellClickListener; } public void setOnCellLongClickListener(@NonNull OnCellLongClickListener onCellLongClickListener) { this.onCellLongClickListener = onCellLongClickListener; } public OnCellClickListener getOnCellClickListener() { return onCellClickListener; } public OnCellLongClickListener getOnCellLongClickListener() { return onCellLongClickListener; } public void setOnCellClickListener2(@NonNull OnCellClickListener2 onCellClickListener2) { this.onCellClickListener2 = onCellClickListener2; } public void setOnCellLongClickListener2(@NonNull OnCellLongClickListener2 onCellLongClickListener2) { this.onCellLongClickListener2 = onCellLongClickListener2; } public OnCellClickListener2 getOnCellClickListener2() { return onCellClickListener2; } public OnCellLongClickListener2 getOnCellLongClickListener2() { return onCellLongClickListener2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleCell<?, ?> cell = (SimpleCell<?, ?>) o; return getItemId() == cell.getItemId(); } @Override public int hashCode() { return (int) (getItemId() ^ (getItemId() >>> 32)); } }
library/src/main/java/com/jaychang/srv/SimpleCell.java
package com.jaychang.srv; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; public abstract class SimpleCell<T, VH extends SimpleViewHolder> { public interface OnCellClickListener<T> { void onCellClicked(@NonNull T item); } public interface OnCellLongClickListener<T> { void onCellLongClicked(@NonNull T item); } public interface OnCellClickListener2<CELL, VH, T> { void onCellClicked(@NonNull CELL cell, @NonNull VH viewHolder, @NonNull T item); } public interface OnCellLongClickListener2<CELL, VH, T> { void onCellLongClicked(@NonNull CELL cell, @NonNull VH viewHolder, @NonNull T item); } private int spanSize = 1; private T item; private OnCellClickListener onCellClickListener; private OnCellClickListener2 onCellClickListener2; private OnCellLongClickListener onCellLongClickListener; private OnCellLongClickListener2 onCellLongClickListener2; public SimpleCell(@NonNull T item) { this.item = item; } @LayoutRes protected abstract int getLayoutRes(); @NonNull protected abstract VH onCreateViewHolder(@NonNull ViewGroup parent, @NonNull View cellView); protected abstract void onBindViewHolder(@NonNull VH holder, int position, @NonNull Context context, @Nullable Object payload); protected void onUnbindViewHolder(@NonNull VH holder) { } @NonNull public T getItem() { return item; } public void setItem(@NonNull T item) { this.item = item; } protected abstract long getItemId(); public int getSpanSize() { return spanSize; } public void setSpanSize(int spanSize) { this.spanSize = spanSize; } public void setOnCellClickListener(@NonNull OnCellClickListener onCellClickListener) { this.onCellClickListener = onCellClickListener; } public void setOnCellLongClickListener(@NonNull OnCellLongClickListener onCellLongClickListener) { this.onCellLongClickListener = onCellLongClickListener; } public OnCellClickListener getOnCellClickListener() { return onCellClickListener; } public OnCellLongClickListener getOnCellLongClickListener() { return onCellLongClickListener; } public void setOnCellClickListener2(@NonNull OnCellClickListener2 onCellClickListener2) { this.onCellClickListener2 = onCellClickListener2; } public void setOnCellLongClickListener2(@NonNull OnCellLongClickListener2 onCellLongClickListener2) { this.onCellLongClickListener2 = onCellLongClickListener2; } public OnCellClickListener2 getOnCellClickListener2() { return onCellClickListener2; } public OnCellLongClickListener2 getOnCellLongClickListener2() { return onCellLongClickListener2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleCell<?, ?> cell = (SimpleCell<?, ?>) o; return getItemId() == cell.getItemId(); } @Override public int hashCode() { return (int) (getItemId() ^ (getItemId() >>> 32)); } }
Revise kotlin compatibility issue
library/src/main/java/com/jaychang/srv/SimpleCell.java
Revise kotlin compatibility issue
<ide><path>ibrary/src/main/java/com/jaychang/srv/SimpleCell.java <ide> import android.content.Context; <ide> import android.support.annotation.LayoutRes; <ide> import android.support.annotation.NonNull; <del>import android.support.annotation.Nullable; <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> <ide> <ide> @NonNull protected abstract VH onCreateViewHolder(@NonNull ViewGroup parent, @NonNull View cellView); <ide> <del> protected abstract void onBindViewHolder(@NonNull VH holder, int position, @NonNull Context context, @Nullable Object payload); <add> protected abstract void onBindViewHolder(@NonNull VH holder, int position, @NonNull Context context, Object payload); <ide> <ide> protected void onUnbindViewHolder(@NonNull VH holder) { <ide> }
Java
epl-1.0
43716fd65ec8665167dfc5db7d07f09212c24783
0
jsight/windup,OndraZizka/windup,windup/windup,jsight/windup,OndraZizka/windup,windup/windup,Maarc/windup,windup/windup,johnsteele/windup,Maarc/windup,OndraZizka/windup,OndraZizka/windup,Maarc/windup,johnsteele/windup,jsight/windup,windup/windup,johnsteele/windup,Maarc/windup,johnsteele/windup,jsight/windup
package org.jboss.windup.rules.apps.java.scan.provider; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jboss.windup.ast.java.ASTProcessor; import org.jboss.windup.ast.java.BatchASTFuture; import org.jboss.windup.ast.java.BatchASTListener; import org.jboss.windup.ast.java.BatchASTProcessor; import org.jboss.windup.ast.java.data.ClassReference; import org.jboss.windup.ast.java.data.ResolutionStatus; import org.jboss.windup.ast.java.data.TypeReferenceLocation; import org.jboss.windup.ast.java.data.annotations.AnnotationArrayValue; import org.jboss.windup.ast.java.data.annotations.AnnotationClassReference; import org.jboss.windup.ast.java.data.annotations.AnnotationLiteralValue; import org.jboss.windup.ast.java.data.annotations.AnnotationValue; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.loader.RuleLoaderContext; import org.jboss.windup.config.metadata.RuleMetadata; import org.jboss.windup.config.metadata.TechnologyMetadata; import org.jboss.windup.config.metadata.TechnologyMetadataProvider; import org.jboss.windup.config.metadata.TechnologyReference; import org.jboss.windup.config.operation.GraphOperation; import org.jboss.windup.config.phase.InitialAnalysisPhase; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.model.TechnologyReferenceModel; import org.jboss.windup.graph.model.WindupConfigurationModel; import org.jboss.windup.graph.model.resource.FileModel; import org.jboss.windup.graph.service.GraphService; import org.jboss.windup.graph.service.WindupConfigurationService; import org.jboss.windup.reporting.service.ClassificationService; import org.jboss.windup.rules.apps.java.JavaTechnologyMetadata; import org.jboss.windup.rules.apps.java.model.JarArchiveModel; import org.jboss.windup.rules.apps.java.model.JavaSourceFileModel; import org.jboss.windup.rules.apps.java.model.WindupJavaConfigurationModel; import org.jboss.windup.rules.apps.java.scan.ast.JavaTypeReferenceModel; import org.jboss.windup.rules.apps.java.scan.ast.TypeInterestFactory; import org.jboss.windup.rules.apps.java.scan.ast.WindupWildcardImportResolver; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationListTypeValueModel; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationLiteralTypeValueModel; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationTypeReferenceModel; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationTypeValueModel; import org.jboss.windup.rules.apps.java.service.TypeReferenceService; import org.jboss.windup.rules.apps.java.service.WindupJavaConfigurationService; import org.jboss.windup.util.ExecutionStatistics; import org.jboss.windup.util.Logging; import org.jboss.windup.util.ProgressEstimate; import org.jboss.windup.util.exception.WindupException; import org.jboss.windup.util.exception.WindupStopException; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; /** * Scan the Java Source code files and store the used type information from them. * * @author <a href="mailto:[email protected]">Jesse Sightler</a> * @author <a href="mailto:[email protected]">Ondrej Zizka</a> */ @RuleMetadata(phase = InitialAnalysisPhase.class, haltOnException = true) public class AnalyzeJavaFilesRuleProvider extends AbstractRuleProvider { static final String UNPARSEABLE_JAVA_CLASSIFICATION = "Unparseable Java File"; static final String UNPARSEABLE_JAVA_DESCRIPTION = "This Java file could not be parsed"; public static final int COMMIT_INTERVAL = 500; public static final int LOG_INTERVAL = 250; private static final Logger LOG = Logging.get(AnalyzeJavaFilesRuleProvider.class); @Inject private WindupWildcardImportResolver importResolver; @Inject private TechnologyMetadataProvider technologyMetadataProvider; // @formatter:off @Override public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) { return ConfigurationBuilder.begin() .addRule() .perform(new ParseSourceOperation()); } // @formatter:on private final class ParseSourceOperation extends GraphOperation { private static final int ANALYSIS_QUEUE_SIZE = 5000; final Map<Path, JavaSourceFileModel> sourcePathToFileModel = new TreeMap<>(); public void perform(final GraphRewrite event, EvaluationContext context) { final AtomicInteger ticks = new AtomicInteger(); ExecutionStatistics.get().begin("AnalyzeJavaFilesRuleProvider.analyzeFile"); try { final GraphContext graphContext = event.getGraphContext(); WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(graphContext); Iterable<JavaSourceFileModel> allJavaSourceModels = graphContext.service(JavaSourceFileModel.class).findAll(); final Set<Path> allSourceFiles = new TreeSet<>(); Set<String> sourcePaths = new HashSet<>(); for (JavaSourceFileModel javaFile : allJavaSourceModels) { FileModel rootSourceFolder = javaFile.getRootSourceFolder(); if (rootSourceFolder != null) { sourcePaths.add(rootSourceFolder.getFilePath()); } if (windupJavaConfigurationService.shouldScanPackage(javaFile.getPackageName())) { Path path = Paths.get(javaFile.getFilePath()); allSourceFiles.add(path); sourcePathToFileModel.put(path, javaFile); } } LOG.log(Level.INFO, "Analyzing {0} Java source files.", allSourceFiles.size()); WindupJavaConfigurationModel javaConfiguration = WindupJavaConfigurationService.getJavaConfigurationModel(graphContext); Set<String> libraryPaths = collectLibraryPaths(graphContext, javaConfiguration); ExecutionStatistics.get().begin("AnalyzeJavaFilesRuleProvider.parseFiles"); final boolean classNotFoundAnalysisEnabled = javaConfiguration.isClassNotFoundAnalysisEnabled(); try { WindupWildcardImportResolver.setContext(graphContext); final BlockingQueue<Pair<Path, List<ClassReference>>> processedPaths = new ArrayBlockingQueue<>(ANALYSIS_QUEUE_SIZE); final ConcurrentMap<Path, String> failures = new ConcurrentHashMap<>(); BatchASTListener listener = new BatchASTListener() { @Override public void processed(Path filePath, List<ClassReference> references) { checkExecutionStopRequest(); try { processedPaths.put(new ImmutablePair<>(filePath, filterClassReferences(references, classNotFoundAnalysisEnabled))); } catch (InterruptedException e) { throw new WindupException(e.getMessage(), e); } } @Override public void failed(Path filePath, Throwable cause) { checkExecutionStopRequest(); final String message = "Failed to process: " + filePath + " due to: " + cause.getMessage(); LOG.log(Level.WARNING, message, cause); failures.put(filePath, message); } private void checkExecutionStopRequest() { if (ticks.incrementAndGet() % 20 == 0) if (event.shouldWindupStop()) throw new WindupStopException("Stop requested while analyzing Java files."); } }; Set<Path> filesToProcess = new TreeSet<>(allSourceFiles); BatchASTFuture future = BatchASTProcessor.analyze(listener, importResolver, libraryPaths, sourcePaths, filesToProcess); ProgressEstimate estimate = new ProgressEstimate(filesToProcess.size()); // This tracks the number of items added to the graph AtomicInteger referenceCount = new AtomicInteger(0); while (!future.isDone() || !processedPaths.isEmpty()) { if (processedPaths.size() > (ANALYSIS_QUEUE_SIZE / 2)) LOG.info("Queue size: " + processedPaths.size() + " / " + ANALYSIS_QUEUE_SIZE); Pair<Path, List<ClassReference>> pair = processedPaths.poll(250, TimeUnit.MILLISECONDS); if (pair == null) continue; processReferences(graphContext, referenceCount, pair.getKey(), pair.getValue()); estimate.addWork(1); printProgressEstimate(event, estimate); filesToProcess.remove(pair.getKey()); } for (Map.Entry<Path, String> failure : failures.entrySet()) { ClassificationService classificationService = new ClassificationService(graphContext); JavaSourceFileModel sourceFileModel = getJavaSourceFileModel(graphContext, failure.getKey()); classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION); sourceFileModel.setParseError(failure.getValue()); } if (!filesToProcess.isEmpty()) { /* * These were rejected by the batch, so try them one file at a time because the one-at-a-time ASTParser usually succeeds where * the batch failed. */ for (Path unprocessed : new ArrayList<>(filesToProcess)) { try { List<ClassReference> references = ASTProcessor.analyze(importResolver, libraryPaths, sourcePaths, unprocessed); processReferences(graphContext, referenceCount, unprocessed, filterClassReferences(references, classNotFoundAnalysisEnabled)); filesToProcess.remove(unprocessed); } catch (Exception e) { final String message = "Failed to process: " + unprocessed + " due to: " + e.getMessage(); LOG.log(Level.WARNING, message, e); ClassificationService classificationService = new ClassificationService(graphContext); JavaSourceFileModel sourceFileModel = getJavaSourceFileModel(graphContext, unprocessed); classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION); sourceFileModel.setParseError(message); } estimate.addWork(1); printProgressEstimate(event, estimate); } } if (!filesToProcess.isEmpty()) { ClassificationService classificationService = new ClassificationService(graphContext); StringBuilder message = new StringBuilder(); message.append("Failed to process " + filesToProcess.size() + " files:\n"); for (Path unprocessed : filesToProcess) { JavaSourceFileModel sourceFileModel = getJavaSourceFileModel(graphContext, unprocessed); message.append("\tFailed to process: " + unprocessed + "\n"); classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION); // Is the classification attached 2nd time here? } LOG.warning(message.toString()); } ExecutionStatistics.get().end("AnalyzeJavaFilesRuleProvider.parseFiles"); } catch (Exception e) { LOG.log(Level.SEVERE, "Could not analyze java files: " + e.getMessage(), e); } finally { WindupWildcardImportResolver.setContext(null); } } finally { sourcePathToFileModel.clear(); ExecutionStatistics.get().end("AnalyzeJavaFilesRuleProvider.analyzeFile"); } } private Set<String> collectLibraryPaths(final GraphContext graphContext, WindupJavaConfigurationModel javaConfiguration) { Set<String> libraryPaths; libraryPaths = new HashSet<>(); WindupConfigurationModel configurationModel = WindupConfigurationService.getConfigurationModel(graphContext); for (TechnologyReferenceModel target : configurationModel.getTargetTechnologies()) { TechnologyMetadata technologyMetadata = technologyMetadataProvider.getMetadata(graphContext, new TechnologyReference(target)); if (technologyMetadata != null && technologyMetadata instanceof JavaTechnologyMetadata) { JavaTechnologyMetadata javaMetadata = (JavaTechnologyMetadata) technologyMetadata; libraryPaths.addAll( javaMetadata .getAdditionalClasspaths() .stream() .map(Path::toString) .collect(Collectors.toList())); } } for (FileModel additionalClasspath : javaConfiguration.getAdditionalClasspaths()) { libraryPaths.add(additionalClasspath.getFilePath()); } Iterable<JarArchiveModel> libraries = graphContext.service(JarArchiveModel.class).findAll(); for (JarArchiveModel library : libraries) { libraryPaths.add(library.getFilePath()); } return libraryPaths; } private void commitIfNeeded(GraphContext context, int numberAddedToGraph) { if (numberAddedToGraph % COMMIT_INTERVAL == 0) context.getGraph().getBaseGraph().commit(); } private void printProgressEstimate(GraphRewrite event, ProgressEstimate estimate) { if (estimate.getWorked() % LOG_INTERVAL != 0) return; int timeRemainingInMillis = (int) estimate.getTimeRemainingInMillis(); if (timeRemainingInMillis > 0) { boolean windupStopRequested = event.ruleEvaluationProgress("Analyze Java", estimate.getWorked(), estimate.getTotal(), timeRemainingInMillis / 1000); if (windupStopRequested) { throw new WindupStopException("Windup stop requested through ruleEvaluationProgress() during " + AnalyzeJavaFilesRuleProvider.class.getName()); } } LOG.info("Analyzed Java File: " + estimate.getWorked() + " / " + estimate.getTotal()); } private List<ClassReference> filterClassReferences(List<ClassReference> references, boolean classNotFoundAnalysisEnabled) { List<ClassReference> results = new ArrayList<>(references.size()); for (ClassReference reference : references) { boolean shouldKeep = reference.getLocation() == TypeReferenceLocation.TYPE; shouldKeep |= classNotFoundAnalysisEnabled && reference.getResolutionStatus() != ResolutionStatus.RESOLVED; shouldKeep |= TypeInterestFactory.matchesAny(reference.getQualifiedName(), reference.getLocation()); // we are always interested in types + anything that the TypeInterestFactory has registered if (shouldKeep) { results.add(reference); } } return results; } private void processReferences(GraphContext context, AtomicInteger referenceCount, Path filePath, List<ClassReference> references) { TypeReferenceService typeReferenceService = new TypeReferenceService(context); Map<ClassReference, JavaTypeReferenceModel> added = new IdentityHashMap<>(references.size()); for (ClassReference reference : references) { if (added.containsKey(reference)) continue; JavaSourceFileModel javaSourceModel = getJavaSourceFileModel(context, filePath); JavaTypeReferenceModel typeReference = typeReferenceService.createTypeReference(javaSourceModel, reference.getLocation(), reference.getResolutionStatus(), reference.getLineNumber(), reference.getColumn(), reference.getLength(), reference.getQualifiedName(), reference.getLine()); added.put(reference, typeReference); if (reference instanceof AnnotationClassReference) { AnnotationClassReference annotationClassReference = (AnnotationClassReference) reference; Map<String, AnnotationValue> annotationValues = annotationClassReference.getAnnotationValues(); JavaAnnotationTypeReferenceModel annotationTypeReferenceModel = addAnnotationValues(context, javaSourceModel, typeReference, annotationValues); // Link the annotation to the thing that it is annotating (method, type, etc). ClassReference originalReference = annotationClassReference.getOriginalReference(); if (originalReference == null) { LOG.warning("No original reference set for annotation: " + annotationClassReference); } else { JavaTypeReferenceModel originalReferenceModel = added.get(originalReference); if (originalReferenceModel == null) { originalReferenceModel = typeReferenceService.createTypeReference(javaSourceModel, originalReference.getLocation(), originalReference.getResolutionStatus(), originalReference.getLineNumber(), originalReference.getColumn(), originalReference.getLength(), originalReference.getQualifiedName(), originalReference.getLine()); added.put(originalReference, originalReferenceModel); } annotationTypeReferenceModel.setAnnotatedType(originalReferenceModel); } } referenceCount.incrementAndGet(); commitIfNeeded(context, referenceCount.get()); } } private JavaSourceFileModel getJavaSourceFileModel(GraphContext context, Path filePath) { return GraphService.refresh(context, sourcePathToFileModel.get(filePath)); } /** * Adds parameters contained in the annotation into the annotation type reference */ private JavaAnnotationTypeReferenceModel addAnnotationValues(GraphContext context, JavaSourceFileModel javaSourceFileModel, JavaTypeReferenceModel typeReference, Map<String, AnnotationValue> annotationValues) { GraphService<JavaAnnotationTypeReferenceModel> annotationTypeReferenceService = new GraphService<>(context, JavaAnnotationTypeReferenceModel.class); JavaAnnotationTypeReferenceModel javaAnnotationTypeReferenceModel = annotationTypeReferenceService.addTypeToModel(typeReference); Map<String, JavaAnnotationTypeValueModel> valueModels = new HashMap<>(); for (Map.Entry<String, AnnotationValue> entry : annotationValues.entrySet()) { valueModels.put(entry.getKey(), getValueModelForAnnotationValue(context, javaSourceFileModel, entry.getValue())); } javaAnnotationTypeReferenceModel.setAnnotationValues(valueModels); return javaAnnotationTypeReferenceModel; } private JavaAnnotationTypeValueModel getValueModelForAnnotationValue(GraphContext context, JavaSourceFileModel javaSourceFileModel, AnnotationValue value) { JavaAnnotationTypeValueModel result; if (value instanceof AnnotationLiteralValue) { GraphService<JavaAnnotationLiteralTypeValueModel> literalValueService = new GraphService<>(context, JavaAnnotationLiteralTypeValueModel.class); AnnotationLiteralValue literal = (AnnotationLiteralValue) value; JavaAnnotationLiteralTypeValueModel literalValueModel = literalValueService.create(); literalValueModel.setLiteralType(literal.getLiteralType().getSimpleName()); literalValueModel.setLiteralValue(literal.getLiteralValue() == null ? null : literal.getLiteralValue().toString()); result = literalValueModel; } else if (value instanceof AnnotationArrayValue) { GraphService<JavaAnnotationListTypeValueModel> listValueService = new GraphService<>(context, JavaAnnotationListTypeValueModel.class); AnnotationArrayValue arrayValues = (AnnotationArrayValue) value; JavaAnnotationListTypeValueModel listModel = listValueService.create(); for (AnnotationValue arrayValue : arrayValues.getValues()) { listModel.addItem(getValueModelForAnnotationValue(context, javaSourceFileModel, arrayValue)); } result = listModel; } else if (value instanceof AnnotationClassReference) { GraphService<JavaAnnotationTypeReferenceModel> annotationTypeReferenceService = new GraphService<>(context, JavaAnnotationTypeReferenceModel.class); AnnotationClassReference annotationClassReference = (AnnotationClassReference) value; Map<String, JavaAnnotationTypeValueModel> valueModels = new HashMap<>(); for (Map.Entry<String, AnnotationValue> entry : annotationClassReference.getAnnotationValues().entrySet()) { valueModels.put(entry.getKey(), getValueModelForAnnotationValue(context, javaSourceFileModel, entry.getValue())); } JavaAnnotationTypeReferenceModel annotationTypeReferenceModel = annotationTypeReferenceService.create(); annotationTypeReferenceModel.setAnnotationValues(valueModels); attachLocationMetadata(annotationTypeReferenceModel, annotationClassReference, javaSourceFileModel); result = annotationTypeReferenceModel; } else { throw new WindupException("Unrecognized AnnotationValue subtype: " + value.getClass().getCanonicalName()); } return result; } private void attachLocationMetadata(JavaTypeReferenceModel javaTypeReferenceModel, AnnotationClassReference annotationClassReference, JavaSourceFileModel javaSourceFileModel) { javaTypeReferenceModel.setResolutionStatus(annotationClassReference.getResolutionStatus()); javaTypeReferenceModel.setResolvedSourceSnippit(annotationClassReference.getQualifiedName()); javaTypeReferenceModel.setSourceSnippit(annotationClassReference.getLine()); javaTypeReferenceModel.setReferenceLocation(annotationClassReference.getLocation()); javaTypeReferenceModel.setColumnNumber(annotationClassReference.getColumn()); javaTypeReferenceModel.setLineNumber(annotationClassReference.getLineNumber()); javaTypeReferenceModel.setLength(annotationClassReference.getLength()); javaTypeReferenceModel.setFile(javaSourceFileModel); } @Override public String toString() { return "ParseJavaSource"; } } }
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/AnalyzeJavaFilesRuleProvider.java
package org.jboss.windup.rules.apps.java.scan.provider; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jboss.windup.ast.java.ASTProcessor; import org.jboss.windup.ast.java.BatchASTFuture; import org.jboss.windup.ast.java.BatchASTListener; import org.jboss.windup.ast.java.BatchASTProcessor; import org.jboss.windup.ast.java.data.ClassReference; import org.jboss.windup.ast.java.data.ResolutionStatus; import org.jboss.windup.ast.java.data.TypeReferenceLocation; import org.jboss.windup.ast.java.data.annotations.AnnotationArrayValue; import org.jboss.windup.ast.java.data.annotations.AnnotationClassReference; import org.jboss.windup.ast.java.data.annotations.AnnotationLiteralValue; import org.jboss.windup.ast.java.data.annotations.AnnotationValue; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.loader.RuleLoaderContext; import org.jboss.windup.config.metadata.RuleMetadata; import org.jboss.windup.config.metadata.TechnologyMetadata; import org.jboss.windup.config.metadata.TechnologyMetadataProvider; import org.jboss.windup.config.metadata.TechnologyReference; import org.jboss.windup.config.operation.GraphOperation; import org.jboss.windup.config.phase.InitialAnalysisPhase; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.model.TechnologyReferenceModel; import org.jboss.windup.graph.model.WindupConfigurationModel; import org.jboss.windup.graph.model.resource.FileModel; import org.jboss.windup.graph.service.GraphService; import org.jboss.windup.graph.service.WindupConfigurationService; import org.jboss.windup.reporting.service.ClassificationService; import org.jboss.windup.rules.apps.java.JavaTechnologyMetadata; import org.jboss.windup.rules.apps.java.model.JarArchiveModel; import org.jboss.windup.rules.apps.java.model.JavaSourceFileModel; import org.jboss.windup.rules.apps.java.model.WindupJavaConfigurationModel; import org.jboss.windup.rules.apps.java.scan.ast.JavaTypeReferenceModel; import org.jboss.windup.rules.apps.java.scan.ast.TypeInterestFactory; import org.jboss.windup.rules.apps.java.scan.ast.WindupWildcardImportResolver; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationListTypeValueModel; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationLiteralTypeValueModel; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationTypeReferenceModel; import org.jboss.windup.rules.apps.java.scan.ast.annotations.JavaAnnotationTypeValueModel; import org.jboss.windup.rules.apps.java.service.TypeReferenceService; import org.jboss.windup.rules.apps.java.service.WindupJavaConfigurationService; import org.jboss.windup.util.ExecutionStatistics; import org.jboss.windup.util.Logging; import org.jboss.windup.util.ProgressEstimate; import org.jboss.windup.util.exception.WindupException; import org.jboss.windup.util.exception.WindupStopException; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; /** * Scan the Java Source code files and store the used type information from them. * * @author <a href="mailto:[email protected]">Jesse Sightler</a> * @author <a href="mailto:[email protected]">Ondrej Zizka</a> */ @RuleMetadata(phase = InitialAnalysisPhase.class, haltOnException = true) public class AnalyzeJavaFilesRuleProvider extends AbstractRuleProvider { static final String UNPARSEABLE_JAVA_CLASSIFICATION = "Unparseable Java File"; static final String UNPARSEABLE_JAVA_DESCRIPTION = "This Java file could not be parsed"; public static final int COMMIT_INTERVAL = 500; public static final int LOG_INTERVAL = 250; private static final Logger LOG = Logging.get(AnalyzeJavaFilesRuleProvider.class); @Inject private WindupWildcardImportResolver importResolver; @Inject private TechnologyMetadataProvider technologyMetadataProvider; // @formatter:off @Override public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) { return ConfigurationBuilder.begin() .addRule() .perform(new ParseSourceOperation()); } // @formatter:on private final class ParseSourceOperation extends GraphOperation { private static final int ANALYSIS_QUEUE_SIZE = 5000; final Map<Path, JavaSourceFileModel> sourcePathToFileModel = new TreeMap<>(); public void perform(final GraphRewrite event, EvaluationContext context) { final AtomicInteger ticks = new AtomicInteger(); ExecutionStatistics.get().begin("AnalyzeJavaFilesRuleProvider.analyzeFile"); try { final GraphContext graphContext = event.getGraphContext(); WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(graphContext); Iterable<JavaSourceFileModel> allJavaSourceModels = graphContext.service(JavaSourceFileModel.class).findAll(); final Set<Path> allSourceFiles = new TreeSet<>(); Set<String> sourcePaths = new HashSet<>(); for (JavaSourceFileModel javaFile : allJavaSourceModels) { FileModel rootSourceFolder = javaFile.getRootSourceFolder(); if (rootSourceFolder != null) { sourcePaths.add(rootSourceFolder.getFilePath()); } if (windupJavaConfigurationService.shouldScanPackage(javaFile.getPackageName())) { Path path = Paths.get(javaFile.getFilePath()); allSourceFiles.add(path); sourcePathToFileModel.put(path, javaFile); } } LOG.log(Level.INFO, "Analyzing {0} Java source files.", allSourceFiles.size()); Set<String> libraryPaths = new HashSet<>(); WindupConfigurationModel configurationModel = WindupConfigurationService.getConfigurationModel(graphContext); for (TechnologyReferenceModel target : configurationModel.getTargetTechnologies()) { TechnologyMetadata technologyMetadata = technologyMetadataProvider.getMetadata(graphContext, new TechnologyReference(target)); if (technologyMetadata != null && technologyMetadata instanceof JavaTechnologyMetadata) { JavaTechnologyMetadata javaMetadata = (JavaTechnologyMetadata) technologyMetadata; libraryPaths.addAll( javaMetadata .getAdditionalClasspaths() .stream() .map(Path::toString) .collect(Collectors.toList())); } } final WindupJavaConfigurationModel javaConfiguration = WindupJavaConfigurationService.getJavaConfigurationModel(graphContext); for (FileModel additionalClasspath : javaConfiguration.getAdditionalClasspaths()) { libraryPaths.add(additionalClasspath.getFilePath()); } Iterable<JarArchiveModel> libraries = graphContext.service(JarArchiveModel.class).findAll(); for (JarArchiveModel library : libraries) { libraryPaths.add(library.getFilePath()); } ExecutionStatistics.get().begin("AnalyzeJavaFilesRuleProvider.parseFiles"); final boolean classNotFoundAnalysisEnabled = javaConfiguration.isClassNotFoundAnalysisEnabled(); try { WindupWildcardImportResolver.setContext(graphContext); final BlockingQueue<Pair<Path, List<ClassReference>>> processedPaths = new ArrayBlockingQueue<>(ANALYSIS_QUEUE_SIZE); final ConcurrentMap<Path, String> failures = new ConcurrentHashMap<>(); BatchASTListener listener = new BatchASTListener() { @Override public void processed(Path filePath, List<ClassReference> references) { checkExecutionStopRequest(); try { processedPaths.put(new ImmutablePair<>(filePath, filterClassReferences(references, classNotFoundAnalysisEnabled))); } catch (InterruptedException e) { throw new WindupException(e.getMessage(), e); } } @Override public void failed(Path filePath, Throwable cause) { checkExecutionStopRequest(); final String message = "Failed to process: " + filePath + " due to: " + cause.getMessage(); LOG.log(Level.WARNING, message, cause); failures.put(filePath, message); } private void checkExecutionStopRequest() { if (ticks.incrementAndGet() % 20 == 0) if (event.shouldWindupStop()) throw new WindupStopException("Stop requested while analyzing Java files."); } }; Set<Path> filesToProcess = new TreeSet<>(allSourceFiles); BatchASTFuture future = BatchASTProcessor.analyze(listener, importResolver, libraryPaths, sourcePaths, filesToProcess); ProgressEstimate estimate = new ProgressEstimate(filesToProcess.size()); // This tracks the number of items added to the graph AtomicInteger referenceCount = new AtomicInteger(0); while (!future.isDone() || !processedPaths.isEmpty()) { if (processedPaths.size() > (ANALYSIS_QUEUE_SIZE / 2)) LOG.info("Queue size: " + processedPaths.size() + " / " + ANALYSIS_QUEUE_SIZE); Pair<Path, List<ClassReference>> pair = processedPaths.poll(250, TimeUnit.MILLISECONDS); if (pair == null) continue; processReferences(graphContext, referenceCount, pair.getKey(), pair.getValue()); estimate.addWork(1); printProgressEstimate(event, estimate); filesToProcess.remove(pair.getKey()); } for (Map.Entry<Path, String> failure : failures.entrySet()) { ClassificationService classificationService = new ClassificationService(graphContext); JavaSourceFileModel sourceFileModel = getJavaSourceFileModel(graphContext, failure.getKey()); classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION); sourceFileModel.setParseError(failure.getValue()); } if (!filesToProcess.isEmpty()) { /* * These were rejected by the batch, so try them one file at a time because the one-at-a-time ASTParser usually succeeds where * the batch failed. */ for (Path unprocessed : new ArrayList<>(filesToProcess)) { try { List<ClassReference> references = ASTProcessor.analyze(importResolver, libraryPaths, sourcePaths, unprocessed); processReferences(graphContext, referenceCount, unprocessed, filterClassReferences(references, classNotFoundAnalysisEnabled)); filesToProcess.remove(unprocessed); } catch (Exception e) { final String message = "Failed to process: " + unprocessed + " due to: " + e.getMessage(); LOG.log(Level.WARNING, message, e); ClassificationService classificationService = new ClassificationService(graphContext); JavaSourceFileModel sourceFileModel = getJavaSourceFileModel(graphContext, unprocessed); classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION); sourceFileModel.setParseError(message); } estimate.addWork(1); printProgressEstimate(event, estimate); } } if (!filesToProcess.isEmpty()) { ClassificationService classificationService = new ClassificationService(graphContext); StringBuilder message = new StringBuilder(); message.append("Failed to process " + filesToProcess.size() + " files:\n"); for (Path unprocessed : filesToProcess) { JavaSourceFileModel sourceFileModel = getJavaSourceFileModel(graphContext, unprocessed); message.append("\tFailed to process: " + unprocessed + "\n"); classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION); // Is the classification attached 2nd time here? } LOG.warning(message.toString()); } ExecutionStatistics.get().end("AnalyzeJavaFilesRuleProvider.parseFiles"); } catch (Exception e) { LOG.log(Level.SEVERE, "Could not analyze java files: " + e.getMessage(), e); } finally { WindupWildcardImportResolver.setContext(null); } } finally { sourcePathToFileModel.clear(); ExecutionStatistics.get().end("AnalyzeJavaFilesRuleProvider.analyzeFile"); } } private void commitIfNeeded(GraphContext context, int numberAddedToGraph) { if (numberAddedToGraph % COMMIT_INTERVAL == 0) context.getGraph().getBaseGraph().commit(); } private void printProgressEstimate(GraphRewrite event, ProgressEstimate estimate) { if (estimate.getWorked() % LOG_INTERVAL != 0) return; int timeRemainingInMillis = (int) estimate.getTimeRemainingInMillis(); if (timeRemainingInMillis > 0) { boolean windupStopRequested = event.ruleEvaluationProgress("Analyze Java", estimate.getWorked(), estimate.getTotal(), timeRemainingInMillis / 1000); if (windupStopRequested) { throw new WindupStopException("Windup stop requested through ruleEvaluationProgress() during " + AnalyzeJavaFilesRuleProvider.class.getName()); } } LOG.info("Analyzed Java File: " + estimate.getWorked() + " / " + estimate.getTotal()); } private List<ClassReference> filterClassReferences(List<ClassReference> references, boolean classNotFoundAnalysisEnabled) { List<ClassReference> results = new ArrayList<>(references.size()); for (ClassReference reference : references) { boolean shouldKeep = reference.getLocation() == TypeReferenceLocation.TYPE; shouldKeep |= classNotFoundAnalysisEnabled && reference.getResolutionStatus() != ResolutionStatus.RESOLVED; shouldKeep |= TypeInterestFactory.matchesAny(reference.getQualifiedName(), reference.getLocation()); // we are always interested in types + anything that the TypeInterestFactory has registered if (shouldKeep) { results.add(reference); } } return results; } private void processReferences(GraphContext context, AtomicInteger referenceCount, Path filePath, List<ClassReference> references) { TypeReferenceService typeReferenceService = new TypeReferenceService(context); Map<ClassReference, JavaTypeReferenceModel> added = new IdentityHashMap<>(references.size()); for (ClassReference reference : references) { if (added.containsKey(reference)) continue; JavaSourceFileModel javaSourceModel = getJavaSourceFileModel(context, filePath); JavaTypeReferenceModel typeReference = typeReferenceService.createTypeReference(javaSourceModel, reference.getLocation(), reference.getResolutionStatus(), reference.getLineNumber(), reference.getColumn(), reference.getLength(), reference.getQualifiedName(), reference.getLine()); added.put(reference, typeReference); if (reference instanceof AnnotationClassReference) { AnnotationClassReference annotationClassReference = (AnnotationClassReference) reference; Map<String, AnnotationValue> annotationValues = annotationClassReference.getAnnotationValues(); JavaAnnotationTypeReferenceModel annotationTypeReferenceModel = addAnnotationValues(context, javaSourceModel, typeReference, annotationValues); // Link the annotation to the thing that it is annotating (method, type, etc). ClassReference originalReference = annotationClassReference.getOriginalReference(); if (originalReference == null) { LOG.warning("No original reference set for annotation: " + annotationClassReference); } else { JavaTypeReferenceModel originalReferenceModel = added.get(originalReference); if (originalReferenceModel == null) { originalReferenceModel = typeReferenceService.createTypeReference(javaSourceModel, originalReference.getLocation(), originalReference.getResolutionStatus(), originalReference.getLineNumber(), originalReference.getColumn(), originalReference.getLength(), originalReference.getQualifiedName(), originalReference.getLine()); added.put(originalReference, originalReferenceModel); } annotationTypeReferenceModel.setAnnotatedType(originalReferenceModel); } } referenceCount.incrementAndGet(); commitIfNeeded(context, referenceCount.get()); } } private JavaSourceFileModel getJavaSourceFileModel(GraphContext context, Path filePath) { return GraphService.refresh(context, sourcePathToFileModel.get(filePath)); } /** * Adds parameters contained in the annotation into the annotation type reference */ private JavaAnnotationTypeReferenceModel addAnnotationValues(GraphContext context, JavaSourceFileModel javaSourceFileModel, JavaTypeReferenceModel typeReference, Map<String, AnnotationValue> annotationValues) { GraphService<JavaAnnotationTypeReferenceModel> annotationTypeReferenceService = new GraphService<>(context, JavaAnnotationTypeReferenceModel.class); JavaAnnotationTypeReferenceModel javaAnnotationTypeReferenceModel = annotationTypeReferenceService.addTypeToModel(typeReference); Map<String, JavaAnnotationTypeValueModel> valueModels = new HashMap<>(); for (Map.Entry<String, AnnotationValue> entry : annotationValues.entrySet()) { valueModels.put(entry.getKey(), getValueModelForAnnotationValue(context, javaSourceFileModel, entry.getValue())); } javaAnnotationTypeReferenceModel.setAnnotationValues(valueModels); return javaAnnotationTypeReferenceModel; } private JavaAnnotationTypeValueModel getValueModelForAnnotationValue(GraphContext context, JavaSourceFileModel javaSourceFileModel, AnnotationValue value) { JavaAnnotationTypeValueModel result; if (value instanceof AnnotationLiteralValue) { GraphService<JavaAnnotationLiteralTypeValueModel> literalValueService = new GraphService<>(context, JavaAnnotationLiteralTypeValueModel.class); AnnotationLiteralValue literal = (AnnotationLiteralValue) value; JavaAnnotationLiteralTypeValueModel literalValueModel = literalValueService.create(); literalValueModel.setLiteralType(literal.getLiteralType().getSimpleName()); literalValueModel.setLiteralValue(literal.getLiteralValue() == null ? null : literal.getLiteralValue().toString()); result = literalValueModel; } else if (value instanceof AnnotationArrayValue) { GraphService<JavaAnnotationListTypeValueModel> listValueService = new GraphService<>(context, JavaAnnotationListTypeValueModel.class); AnnotationArrayValue arrayValues = (AnnotationArrayValue) value; JavaAnnotationListTypeValueModel listModel = listValueService.create(); for (AnnotationValue arrayValue : arrayValues.getValues()) { listModel.addItem(getValueModelForAnnotationValue(context, javaSourceFileModel, arrayValue)); } result = listModel; } else if (value instanceof AnnotationClassReference) { GraphService<JavaAnnotationTypeReferenceModel> annotationTypeReferenceService = new GraphService<>(context, JavaAnnotationTypeReferenceModel.class); AnnotationClassReference annotationClassReference = (AnnotationClassReference) value; Map<String, JavaAnnotationTypeValueModel> valueModels = new HashMap<>(); for (Map.Entry<String, AnnotationValue> entry : annotationClassReference.getAnnotationValues().entrySet()) { valueModels.put(entry.getKey(), getValueModelForAnnotationValue(context, javaSourceFileModel, entry.getValue())); } JavaAnnotationTypeReferenceModel annotationTypeReferenceModel = annotationTypeReferenceService.create(); annotationTypeReferenceModel.setAnnotationValues(valueModels); attachLocationMetadata(annotationTypeReferenceModel, annotationClassReference, javaSourceFileModel); result = annotationTypeReferenceModel; } else { throw new WindupException("Unrecognized AnnotationValue subtype: " + value.getClass().getCanonicalName()); } return result; } private void attachLocationMetadata(JavaTypeReferenceModel javaTypeReferenceModel, AnnotationClassReference annotationClassReference, JavaSourceFileModel javaSourceFileModel) { javaTypeReferenceModel.setResolutionStatus(annotationClassReference.getResolutionStatus()); javaTypeReferenceModel.setResolvedSourceSnippit(annotationClassReference.getQualifiedName()); javaTypeReferenceModel.setSourceSnippit(annotationClassReference.getLine()); javaTypeReferenceModel.setReferenceLocation(annotationClassReference.getLocation()); javaTypeReferenceModel.setColumnNumber(annotationClassReference.getColumn()); javaTypeReferenceModel.setLineNumber(annotationClassReference.getLineNumber()); javaTypeReferenceModel.setLength(annotationClassReference.getLength()); javaTypeReferenceModel.setFile(javaSourceFileModel); } @Override public String toString() { return "ParseJavaSource"; } } }
Move some code to a method
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/AnalyzeJavaFilesRuleProvider.java
Move some code to a method
<ide><path>ules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/AnalyzeJavaFilesRuleProvider.java <ide> <ide> LOG.log(Level.INFO, "Analyzing {0} Java source files.", allSourceFiles.size()); <ide> <del> Set<String> libraryPaths = new HashSet<>(); <del> <del> WindupConfigurationModel configurationModel = WindupConfigurationService.getConfigurationModel(graphContext); <del> for (TechnologyReferenceModel target : configurationModel.getTargetTechnologies()) <del> { <del> TechnologyMetadata technologyMetadata = technologyMetadataProvider.getMetadata(graphContext, new TechnologyReference(target)); <del> if (technologyMetadata != null && technologyMetadata instanceof JavaTechnologyMetadata) <del> { <del> JavaTechnologyMetadata javaMetadata = (JavaTechnologyMetadata) technologyMetadata; <del> libraryPaths.addAll( <del> javaMetadata <del> .getAdditionalClasspaths() <del> .stream() <del> .map(Path::toString) <del> .collect(Collectors.toList())); <del> } <del> } <del> <del> final WindupJavaConfigurationModel javaConfiguration = WindupJavaConfigurationService.getJavaConfigurationModel(graphContext); <del> for (FileModel additionalClasspath : javaConfiguration.getAdditionalClasspaths()) <del> { <del> libraryPaths.add(additionalClasspath.getFilePath()); <del> } <del> <del> Iterable<JarArchiveModel> libraries = graphContext.service(JarArchiveModel.class).findAll(); <del> for (JarArchiveModel library : libraries) <del> { <del> libraryPaths.add(library.getFilePath()); <del> } <add> WindupJavaConfigurationModel javaConfiguration = WindupJavaConfigurationService.getJavaConfigurationModel(graphContext); <add> <add> Set<String> libraryPaths = collectLibraryPaths(graphContext, javaConfiguration); <ide> <ide> ExecutionStatistics.get().begin("AnalyzeJavaFilesRuleProvider.parseFiles"); <ide> final boolean classNotFoundAnalysisEnabled = javaConfiguration.isClassNotFoundAnalysisEnabled(); <ide> } <ide> } <ide> <add> private Set<String> collectLibraryPaths(final GraphContext graphContext, WindupJavaConfigurationModel javaConfiguration) <add> { <add> Set<String> libraryPaths; <add> libraryPaths = new HashSet<>(); <add> WindupConfigurationModel configurationModel = WindupConfigurationService.getConfigurationModel(graphContext); <add> for (TechnologyReferenceModel target : configurationModel.getTargetTechnologies()) <add> { <add> TechnologyMetadata technologyMetadata = technologyMetadataProvider.getMetadata(graphContext, new TechnologyReference(target)); <add> if (technologyMetadata != null && technologyMetadata instanceof JavaTechnologyMetadata) <add> { <add> JavaTechnologyMetadata javaMetadata = (JavaTechnologyMetadata) technologyMetadata; <add> libraryPaths.addAll( <add> javaMetadata <add> .getAdditionalClasspaths() <add> .stream() <add> .map(Path::toString) <add> .collect(Collectors.toList())); <add> } <add> } <add> for (FileModel additionalClasspath : javaConfiguration.getAdditionalClasspaths()) <add> { <add> libraryPaths.add(additionalClasspath.getFilePath()); <add> } <add> Iterable<JarArchiveModel> libraries = graphContext.service(JarArchiveModel.class).findAll(); <add> for (JarArchiveModel library : libraries) <add> { <add> libraryPaths.add(library.getFilePath()); <add> } <add> return libraryPaths; <add> } <add> <ide> private void commitIfNeeded(GraphContext context, int numberAddedToGraph) <ide> { <ide> if (numberAddedToGraph % COMMIT_INTERVAL == 0)
JavaScript
agpl-3.0
282b02b8e4856b6e572f7b081b0f8661ce1efe01
0
firewalla/firewalla,firewalla/firewalla,MelvinTo/firewalla,firewalla/firewalla,MelvinTo/firewalla,MelvinTo/firewalla,MelvinTo/firewalla,firewalla/firewalla,firewalla/firewalla,MelvinTo/firewalla
/* Copyright 2016 Firewalla LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ 'use strict'; let log = require('./logger.js')(__filename); let redis = require('redis'); let rclient = redis.createClient(); let Promise = require('bluebird'); Promise.promisifyAll(redis.RedisClient.prototype); Promise.promisifyAll(redis.Multi.prototype); let async = require('asyncawait/async'); let await = require('asyncawait/await'); let DNSManager = require('./DNSManager.js'); let dnsManager = new DNSManager('info'); let async2 = require('async'); let util = require('util'); let IntelTool = require('../net2/IntelTool'); let intelTool = new IntelTool(); let DestIPFoundHook = require('../hook/DestIPFoundHook'); let destIPFoundHook = new DestIPFoundHook(); let country = require('../extension/country/country.js'); const MAX_RECENT_INTERVAL = 24 * 60 * 60; // one day const QUERY_MAX_FLOW = 10000; const MAX_RECENT_FLOW = 50; const MAX_CONCURRENT_ACTIVITY = 10; let instance = null; class FlowTool { constructor() { if(!instance) { instance = this; } return instance; } trimFlow(flow) { if(!flow) return; if("flows" in flow) delete flow.flows; if("pf" in flow) delete flow.pf; if("bl" in flow) delete flow.bl; if("af" in flow) delete flow.af; if("f" in flow) delete flow.f; } _mergeFlow(targetFlow, flow) { targetFlow.rb += flow.rb; targetFlow.ct += flow.ct; targetFlow.ob += flow.ob; targetFlow.du += flow.du; if (targetFlow.ts < flow.ts) { targetFlow.ts = flow.ts; } if (flow.pf) { for (let k in flow.pf) { if (targetFlow.pf[k] != null) { targetFlow.pf[k].rb += flow.pf[k].rb; targetFlow.pf[k].ob += flow.pf[k].ob; targetFlow.pf[k].ct += flow.pf[k].ct; } else { targetFlow.pf[k] = flow.pf[k] } } } if (flow.flows) { if (targetFlow.flows) { targetFlow.flows = targetFlow.flows.concat(flow.flows); } else { targetFlow.flows = flow.flows; } } } _getKey(flow) { let key = ""; if (flow.sh === flow.lh) { key = flow.dh + ":" + flow.fd; } else { key = flow.sh + ":" + flow.fd; } return key; } _getRemoteIP(flow) { if (flow.sh === flow.lh) { return flow.dh; } else { return flow.sh; } } // append to existing flow or create new _appendFlow(conndb, flowObject, ip) { let o = flowObject; let key = this._getKey(o, ip); let flow = conndb[key]; if (flow == null) { conndb[key] = o; } else { this._mergeFlow(flow, o); } } _flowStringToJSON(flow) { try { return JSON.parse(flow); } catch(err) { return null; } } _isFlowValid(flow) { let o = flow; if (!o) { log.error("Host:Flows:Sorting:Parsing", flow); return false; } if ( !o.rb || !o.ob ) { return false } if (o.rb === 0 && o.ob === 0) { // ignore zero length flows return false; } return true; } _enrichCountryInfo(flow) { let sh = flow.sh; let dh = flow.dh; let lh = flow.lh; if (sh === lh) { flow.country = country.getCountry(dh); } else { flow.country = country.getCountry(sh); } } // FIXME: support dynamically load intel from cloud _enrichDNSInfo(flows) { return new Promise((resolve, reject) => { async.eachLimit(flows, MAX_CONCURRENT_ACTIVITY, (flow, cb) => { let ip = this._getRemoteIP(flow); dnsManager.resolvehost(ip, (err, info, dnsData) => { if (err) { cb(err); return; } if (info && info.name) { flow.dhname = info.name; } cb(); }); }, (err) => { if(err) { reject(err); return; } resolve(flows); }); }); } prepareRecentFlowsForHost(json, listip) { if (!("flows" in json)) { json.flows = {}; } json.flows.recent = []; let promises = listip.map((ip) => { return this.getRecentOutgoingConnections(ip) .then((flows) => { Array.prototype.push.apply(json.flows.recent, flows); return json; }) }); return Promise.all(promises); } _mergeFlows(flowObjects) { let mergedFlowObjects = []; let lastFlowObject = null; flowObjects.forEach((flowObject) => { if(!lastFlowObject) { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; return; } if (this._getKey(lastFlowObject) === this._getKey(flowObject)) { this._mergeFlow(lastFlowObject, flowObject); } else { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; } }); return mergedFlowObjects; } // convert flow json to a simplified json format that's more readable by app toSimpleFlow(flow) { let f = {}; f.ts = flow.ts; f.fd = flow.fd; if(flow.lh === flow.sh) { f.ip = flow.dh; f.upload = flow.ob; f.download = flow.rb; } else { f.ip = flow.sh; f.upload = flow.rb; f.download = flow.ob; } return f; } legacyGetRecentOutgoingConnections(ip) { let key = "flow:conn:in:" + ip; let to = new Date() / 1000; let from = to - MAX_RECENT_INTERVAL; return rclient.zrevrangebyscoreAsync([key, to, from, "LIMIT", 0 , MAX_RECENT_FLOW]) .then((results) => { if(results === null || results.length === 0) return []; let flowObjects = results .map((x) => this._flowStringToJSON(x)) .filter((x) => this._isFlowValid(x)); flowObjects.forEach((x) => this.trimFlow(x)); let mergedFlowObjects = []; let lastFlowObject = null; flowObjects.forEach((flowObject) => { if(!lastFlowObject) { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; return; } if (this._getKey(lastFlowObject) === this._getKey(flowObject)) { this._mergeFlow(lastFlowObject, flowObject); } else { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; } }); // add country info mergedFlowObjects.forEach(this._enrichCountryInfo); return this._enrichDNSInfo(mergedFlowObjects); }).catch((err) => { log.error("Failed to query flow data for ip", ip, ":", err, err.stack, {}); }); } getRecentOutgoingConnections(ip) { return this.getRecentConnections(ip, "in") } getRecentIncomingConnections(ip) { return this.getRecentConnections(ip, "out"); } getRecentConnections(ip, direction) { let key = util.format("flow:conn:%s:%s", direction, ip); let to = new Date() / 1000; let from = to - MAX_RECENT_INTERVAL; return async(() => { let results = await (rclient.zrevrangebyscoreAsync([key, to, from, "LIMIT", 0 , MAX_RECENT_FLOW])); if(results === null || results.length === 0) return []; let flowObjects = results .map((x) => this._flowStringToJSON(x)) .filter((x) => this._isFlowValid(x)); flowObjects.forEach((x) => this.trimFlow(x)); let mergedFlow = this._mergeFlows(flowObjects); let simpleFlows = mergedFlow.map((f) => this.toSimpleFlow(f)); let promises = Promise.all(simpleFlows.map((f) => { return intelTool.getIntel(f.ip) .then((intel) => { if(intel) { f.country = intel.country; f.host = intel.host; return f; } else { // intel not exists in redis, create a new one return async(() => { intel = await (destIPFoundHook.processIP(f.ip)); f.country = intel.country; f.host = intel.host; return f; })(); } return f; }); })); return promises; })(); } getFlowKey(ip, type) { return util.format("flow:conn:%s:%s", type, ip); } addFlow(ip, type, flow) { let key = this.getFlowKey(ip, type); if(typeof flow !== 'object') { return Promise.reject("Invalid flow type: " + typeof flow); } return rclient.zaddAsync(key, flow.ts, JSON.stringify(flow)); } removeFlow(ip, type, flow) { let key = this.getFlowKey(ip, type); if(typeof flow !== 'object') { return Promise.reject("Invalid flow type: " + typeof flow); } return rclient.zremAsync(key, JSON.stringify(flow)) } flowExists(ip, type, flow) { let key = this.getFlowKey(ip, type); if(typeof flow !== 'object') { return Promise.reject("Invalid flow type: " + typeof flow); } return async(() => { let result = await(rclient.zscoreAsync(key, JSON.stringify(flow))); if(result == null) { return false; } else { return true; } })(); } queryFlows(ip, type, begin, end) { let key = this.getFlowKey(ip, type); return rclient.zrangebyscoreAsync(key, "(" + begin, end) // char '(' means open interval .then((flowStrings) => { return flowStrings.map((flowString) => JSON.parse(flowString)); }) } getDestIP(flow) { if(flow.lh === flow.sh) { return flow.dh; } else { return flow.sh; } } getDownloadTraffic(flow) { if(flow.lh === flow.sh) { return flow.rb; } else { return flow.ob; } } getUploadTraffic(flow) { if(flow.lh === flow.sh) { return flow.ob; } else { return flow.rb; } } } module.exports = function() { return new FlowTool(); };
net2/FlowTool.js
/* Copyright 2016 Firewalla LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ 'use strict'; let log = require('./logger.js')(__filename); let redis = require('redis'); let rclient = redis.createClient(); let Promise = require('bluebird'); Promise.promisifyAll(redis.RedisClient.prototype); Promise.promisifyAll(redis.Multi.prototype); let async = require('asyncawait/async'); let await = require('asyncawait/await'); let DNSManager = require('./DNSManager.js'); let dnsManager = new DNSManager('info'); let async2 = require('async'); let util = require('util'); let IntelTool = require('../net2/IntelTool'); let intelTool = new IntelTool(); let DestIPFoundHook = require('../hook/DestIPFoundHook'); let destIPFoundHook = new DestIPFoundHook(); let country = require('../extension/country/country.js'); const MAX_RECENT_INTERVAL = 24 * 60 * 60; // one day const QUERY_MAX_FLOW = 10000; const MAX_RECENT_FLOW = 50; const MAX_CONCURRENT_ACTIVITY = 10; let instance = null; class FlowTool { constructor() { if(!instance) { instance = this; } return instance; } trimFlow(flow) { if(!flow) return; if("flows" in flow) delete flow.flows; if("pf" in flow) delete flow.pf; if("bl" in flow) delete flow.bl; if("af" in flow) delete flow.af; if("f" in flow) delete flow.f; } _mergeFlow(targetFlow, flow) { targetFlow.rb += flow.rb; targetFlow.ct += flow.ct; targetFlow.ob += flow.ob; targetFlow.du += flow.du; if (targetFlow.ts < flow.ts) { targetFlow.ts = flow.ts; } if (flow.pf) { for (let k in flow.pf) { if (targetFlow.pf[k] != null) { targetFlow.pf[k].rb += flow.pf[k].rb; targetFlow.pf[k].ob += flow.pf[k].ob; targetFlow.pf[k].ct += flow.pf[k].ct; } else { targetFlow.pf[k] = flow.pf[k] } } } if (flow.flows) { if (targetFlow.flows) { targetFlow.flows = targetFlow.flows.concat(flow.flows); } else { targetFlow.flows = flow.flows; } } } _getKey(flow) { let key = ""; if (flow.sh === flow.lh) { key = flow.dh + ":" + flow.fd; } else { key = flow.sh + ":" + flow.fd; } return key; } _getRemoteIP(flow) { if (flow.sh === flow.lh) { return flow.dh; } else { return flow.sh; } } // append to existing flow or create new _appendFlow(conndb, flowObject, ip) { let o = flowObject; let key = this._getKey(o, ip); let flow = conndb[key]; if (flow == null) { conndb[key] = o; } else { this._mergeFlow(flow, o); } } _flowStringToJSON(flow) { try { return JSON.parse(flow); } catch(err) { return null; } } _isFlowValid(flow) { let o = flow; if (!o) { log.error("Host:Flows:Sorting:Parsing", flow); return false; } if ( !o.rb || !o.ob ) { return false } if (o.rb === 0 && o.ob === 0) { // ignore zero length flows return false; } return true; } _enrichCountryInfo(flow) { let sh = flow.sh; let dh = flow.dh; let lh = flow.lh; if (sh === lh) { flow.country = country.getCountry(dh); } else { flow.country = country.getCountry(sh); } } // FIXME: support dynamically load intel from cloud _enrichDNSInfo(flows) { return new Promise((resolve, reject) => { async.eachLimit(flows, MAX_CONCURRENT_ACTIVITY, (flow, cb) => { let ip = this._getRemoteIP(flow); dnsManager.resolvehost(ip, (err, info, dnsData) => { if (err) { cb(err); return; } if (info && info.name) { flow.dhname = info.name; } cb(); }); }, (err) => { if(err) { reject(err); return; } resolve(flows); }); }); } prepareRecentFlowsForHost(json, listip) { if (!("flows" in json)) { json.flows = {}; } json.flows.time = []; let promises = listip.map((ip) => { return this.getRecentOutgoingConnections(ip) .then((flows) => { Array.prototype.push.apply(json.flows.time, flows); return json; }) }); return Promise.all(promises); } _mergeFlows(flowObjects) { let mergedFlowObjects = []; let lastFlowObject = null; flowObjects.forEach((flowObject) => { if(!lastFlowObject) { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; return; } if (this._getKey(lastFlowObject) === this._getKey(flowObject)) { this._mergeFlow(lastFlowObject, flowObject); } else { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; } }); return mergedFlowObjects; } // convert flow json to a simplified json format that's more readable by app toSimpleFlow(flow) { let f = {}; f.ts = flow.ts; f.fd = flow.fd; if(flow.lh === flow.sh) { f.ip = flow.dh; f.upload = flow.ob; f.download = flow.rb; } else { f.ip = flow.sh; f.upload = flow.rb; f.download = flow.ob; } return f; } legacyGetRecentOutgoingConnections(ip) { let key = "flow:conn:in:" + ip; let to = new Date() / 1000; let from = to - MAX_RECENT_INTERVAL; return rclient.zrevrangebyscoreAsync([key, to, from, "LIMIT", 0 , MAX_RECENT_FLOW]) .then((results) => { if(results === null || results.length === 0) return []; let flowObjects = results .map((x) => this._flowStringToJSON(x)) .filter((x) => this._isFlowValid(x)); flowObjects.forEach((x) => this.trimFlow(x)); let mergedFlowObjects = []; let lastFlowObject = null; flowObjects.forEach((flowObject) => { if(!lastFlowObject) { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; return; } if (this._getKey(lastFlowObject) === this._getKey(flowObject)) { this._mergeFlow(lastFlowObject, flowObject); } else { mergedFlowObjects.push(flowObject); lastFlowObject = flowObject; } }); // add country info mergedFlowObjects.forEach(this._enrichCountryInfo); return this._enrichDNSInfo(mergedFlowObjects); }).catch((err) => { log.error("Failed to query flow data for ip", ip, ":", err, err.stack, {}); }); } getRecentOutgoingConnections(ip) { return this.getRecentConnections(ip, "in") } getRecentIncomingConnections(ip) { return this.getRecentConnections(ip, "out"); } getRecentConnections(ip, direction) { let key = util.format("flow:conn:%s:%s", direction, ip); let to = new Date() / 1000; let from = to - MAX_RECENT_INTERVAL; return async(() => { let results = await (rclient.zrevrangebyscoreAsync([key, to, from, "LIMIT", 0 , MAX_RECENT_FLOW])); if(results === null || results.length === 0) return []; let flowObjects = results .map((x) => this._flowStringToJSON(x)) .filter((x) => this._isFlowValid(x)); flowObjects.forEach((x) => this.trimFlow(x)); let mergedFlow = this._mergeFlows(flowObjects); let simpleFlows = mergedFlow.map((f) => this.toSimpleFlow(f)); let promises = Promise.all(simpleFlows.map((f) => { return intelTool.getIntel(f.ip) .then((intel) => { if(intel) { f.country = intel.country; f.host = intel.host; return f; } else { // intel not exists in redis, create a new one return async(() => { intel = await (destIPFoundHook.processIP(f.ip)); f.country = intel.country; f.host = intel.host; return f; })(); } return f; }); })); return promises; })(); } getFlowKey(ip, type) { return util.format("flow:conn:%s:%s", type, ip); } addFlow(ip, type, flow) { let key = this.getFlowKey(ip, type); if(typeof flow !== 'object') { return Promise.reject("Invalid flow type: " + typeof flow); } return rclient.zaddAsync(key, flow.ts, JSON.stringify(flow)); } removeFlow(ip, type, flow) { let key = this.getFlowKey(ip, type); if(typeof flow !== 'object') { return Promise.reject("Invalid flow type: " + typeof flow); } return rclient.zremAsync(key, JSON.stringify(flow)) } flowExists(ip, type, flow) { let key = this.getFlowKey(ip, type); if(typeof flow !== 'object') { return Promise.reject("Invalid flow type: " + typeof flow); } return async(() => { let result = await(rclient.zscoreAsync(key, JSON.stringify(flow))); if(result == null) { return false; } else { return true; } })(); } queryFlows(ip, type, begin, end) { let key = this.getFlowKey(ip, type); return rclient.zrangebyscoreAsync(key, "(" + begin, end) // char '(' means open interval .then((flowStrings) => { return flowStrings.map((flowString) => JSON.parse(flowString)); }) } getDestIP(flow) { if(flow.lh === flow.sh) { return flow.dh; } else { return flow.sh; } } getDownloadTraffic(flow) { if(flow.lh === flow.sh) { return flow.rb; } else { return flow.ob; } } getUploadTraffic(flow) { if(flow.lh === flow.sh) { return flow.ob; } else { return flow.rb; } } } module.exports = function() { return new FlowTool(); };
use flows.recent to store host recent download/uploads
net2/FlowTool.js
use flows.recent to store host recent download/uploads
<ide><path>et2/FlowTool.js <ide> json.flows = {}; <ide> } <ide> <del> json.flows.time = []; <add> json.flows.recent = []; <ide> <ide> let promises = listip.map((ip) => { <ide> return this.getRecentOutgoingConnections(ip) <ide> .then((flows) => { <del> Array.prototype.push.apply(json.flows.time, flows); <add> Array.prototype.push.apply(json.flows.recent, flows); <ide> return json; <ide> }) <ide> });
JavaScript
bsd-3-clause
5e8604febedbbdae9a7cec343d8ffafed8284f82
0
rgbkrk/nteract,nteract/nteract,nteract/composition,jdfreder/nteract,rgbkrk/nteract,rgbkrk/nteract,nteract/nteract,jdfreder/nteract,rgbkrk/nteract,nteract/nteract,nteract/nteract,rgbkrk/nteract,jdfreder/nteract,nteract/composition,nteract/composition,nteract/nteract,jdfreder/nteract
/* @flow */ import { Observable } from "rxjs/Observable"; import { of } from "rxjs/observable/of"; import { empty } from "rxjs/observable/empty"; import { merge } from "rxjs/observable/merge"; import { from } from "rxjs/observable/from"; import { createKernelRef } from "../state/refs"; import { createMessage, childOf, ofMessageType } from "@nteract/messaging"; import type { Notebook, ImmutableNotebook } from "@nteract/commutable"; import type { KernelRef } from "../state/refs"; const path = require("path"); import { filter, map, tap, mergeMap, concatMap, catchError, first, pluck, switchMap } from "rxjs/operators"; import { ActionsObservable, ofType } from "redux-observable"; import * as uuid from "uuid"; import type { NewKernelAction, RestartKernel, SetNotebookAction } from "../actionTypes"; import * as selectors from "../selectors"; import * as actions from "../actions"; import * as actionTypes from "../actionTypes"; /** * Sets the execution state after a kernel has been launched. * * @oaram {ActionObservable} action$ ActionObservable for LAUNCH_KERNEL_SUCCESSFUL action */ export const watchExecutionStateEpic = (action$: ActionsObservable<*>) => action$.pipe( ofType(actionTypes.LAUNCH_KERNEL_SUCCESSFUL), switchMap((action: NewKernelAction) => action.payload.kernel.channels.pipe( filter(msg => msg.header.msg_type === "status"), map(msg => actions.setExecutionState({ kernelStatus: msg.content.execution_state, kernelRef: action.payload.kernelRef }) ) ) ) ); /** * Send a kernel_info_request to the kernel. * * @param {Object} channels A object containing the kernel channels * @returns {Observable} The reply from the server */ export function acquireKernelInfo(channels: Channels, kernelRef: KernelRef) { const message = createMessage("kernel_info_request"); const obs = channels.pipe( childOf(message), ofMessageType("kernel_info_reply"), first(), pluck("content", "language_info"), map(langInfo => actions.setLanguageInfo({ langInfo, kernelRef })) ); return Observable.create(observer => { const subscription = obs.subscribe(observer); channels.next(message); return subscription; }); } /** * Gets information about newly launched kernel. * * @param {ActionObservable} The action type */ export const acquireKernelInfoEpic = (action$: ActionsObservable<*>) => action$.pipe( ofType(actionTypes.LAUNCH_KERNEL_SUCCESSFUL), switchMap((action: NewKernelAction) => { const { payload: { kernel: { channels }, kernelRef } } = action; return acquireKernelInfo(channels, kernelRef); }) ); export const extractNewKernel = ( filename: ?string, notebook: ImmutableNotebook ) => { // TODO: There's some incongruence between desktop and web app here, regarding path vs. filename const cwd = (filename && path.dirname(filename)) || "/"; const kernelSpecName = notebook.getIn( ["metadata", "kernelspec", "name"], notebook.getIn(["metadata", "language_info", "name"], "python3") ); return { cwd, kernelSpecName }; }; export const launchKernelWhenNotebookSetEpic = ( action$: ActionsObservable<*> ) => action$.pipe( ofType(actionTypes.SET_NOTEBOOK), map((action: SetNotebookAction) => { const { cwd, kernelSpecName } = extractNewKernel( action.payload.filename, action.payload.notebook ); return actions.launchKernelByName({ kernelSpecName, cwd, kernelRef: action.payload.kernelRef, selectNextKernel: true }); }) ); export const restartKernelEpic = (action$: ActionsObservable<*>, store: *) => action$.pipe( ofType(actionTypes.RESTART_KERNEL), concatMap((action: RestartKernel) => { const state = store.getState(); const oldKernelRef = action.payload.kernelRef; const oldKernel = selectors.kernel(state, { kernelRef: oldKernelRef }); const notificationSystem = selectors.notificationSystem(state); if (!oldKernelRef || !oldKernel) { notificationSystem.addNotification({ title: "Failure to Restart", message: `Unable to restart kernel, please select a new kernel.`, dismissible: true, position: "tr", level: "error" }); // TODO: Wow do we need to send notifications through our store for // consistency return empty(); } // TODO: Incorporate this into each of the launchKernelByName // actions... // This only mirrors the old behavior of restart kernel (for now) notificationSystem.addNotification({ title: "Kernel Restarted", message: `Kernel ${oldKernel.kernelSpecName} has been restarted.`, dismissible: true, position: "tr", level: "success" }); return of( actions.killKernel({ restarting: true, kernelRef: oldKernelRef }), actions.launchKernelByName({ kernelSpecName: oldKernel.kernelSpecName, cwd: oldKernel.cwd, kernelRef: createKernelRef(), selectNextKernel: true }) ); }) );
packages/core/src/epics/kernel-lifecycle.js
/* @flow */ import { Observable } from "rxjs/Observable"; import { of } from "rxjs/observable/of"; import { empty } from "rxjs/observable/empty"; import { merge } from "rxjs/observable/merge"; import { from } from "rxjs/observable/from"; import { createKernelRef } from "../state/refs"; import { createMessage, childOf, ofMessageType } from "@nteract/messaging"; import type { Notebook, ImmutableNotebook } from "@nteract/commutable"; import type { KernelRef } from "../state/refs"; const path = require("path"); import { filter, map, tap, mergeMap, concatMap, catchError, first, pluck, switchMap } from "rxjs/operators"; import { ActionsObservable, ofType } from "redux-observable"; import * as uuid from "uuid"; import type { NewKernelAction, RestartKernel, SetNotebookAction } from "../actionTypes"; import * as selectors from "../selectors"; import * as actions from "../actions"; import * as actionTypes from "../actionTypes"; /** * Sets the execution state after a kernel has been launched. * * @oaram {ActionObservable} action$ ActionObservable for LAUNCH_KERNEL_SUCCESSFUL action */ export const watchExecutionStateEpic = (action$: ActionsObservable<*>) => action$.pipe( ofType(actionTypes.LAUNCH_KERNEL_SUCCESSFUL), switchMap((action: NewKernelAction) => action.payload.kernel.channels.pipe( filter(msg => msg.header.msg_type === "status"), map(msg => actions.setExecutionState({ kernelStatus: msg.content.execution_state, kernelRef: action.payload.kernelRef }) ) ) ) ); /** * Send a kernel_info_request to the kernel. * * @param {Object} channels A object containing the kernel channels * @returns {Observable} The reply from the server */ export function acquireKernelInfo(channels: Channels, kernelRef: KernelRef) { const message = createMessage("kernel_info_request"); const obs = channels.pipe( childOf(message), ofMessageType("kernel_info_reply"), first(), pluck("content", "language_info"), map(langInfo => actions.setLanguageInfo({ langInfo, kernelRef })) ); return Observable.create(observer => { const subscription = obs.subscribe(observer); channels.next(message); return subscription; }); } /** * Gets information about newly launched kernel. * * @param {ActionObservable} The action type */ export const acquireKernelInfoEpic = (action$: ActionsObservable<*>) => action$.pipe( ofType(actionTypes.LAUNCH_KERNEL_SUCCESSFUL), switchMap((action: NewKernelAction) => { const { payload: { kernel: { channels }, kernelRef } } = action; return acquireKernelInfo(channels, kernelRef); }) ); export const extractNewKernel = ( filename: ?string, notebook: ImmutableNotebook ) => { // TODO: There's some incongruence between desktop and web app here, regarding path vs. filename const cwd = (filename && path.dirname(filename)) || "/"; const kernelSpecName = notebook.getIn( ["metadata", "kernelspec", "name"], notebook.getIn(["metadata", "language_info", "name"], "python3") ); return { cwd, kernelSpecName }; }; export const launchKernelWhenNotebookSetEpic = ( action$: ActionsObservable<*> ) => action$.pipe( ofType(actionTypes.SET_NOTEBOOK), map((action: SetNotebookAction) => { const { cwd, kernelSpecName } = extractNewKernel( action.payload.filename, action.payload.notebook ); return actions.launchKernelByName({ kernelSpecName, cwd, kernelRef: action.payload.kernelRef, selectNextKernel: true }); }) ); export const restartKernelEpic = (action$: ActionsObservable<*>, store: *) => action$.pipe( ofType(actionTypes.RESTART_KERNEL), concatMap((action: RestartKernel) => { const state = store.getState(); const kernel = selectors.currentKernel(state); const notificationSystem = selectors.notificationSystem(state); if (!kernel) { notificationSystem.addNotification({ title: "Failure to Restart", message: `Unable to restart kernel, please select a new kernel.`, dismissible: true, position: "tr", level: "error" }); // TODO: Wow do we need to send notifications through our store for // consistency return empty(); } // TODO: Incorporate this into each of the launchKernelByName // actions... // This only mirrors the old behavior of restart kernel (for now) notificationSystem.addNotification({ title: "Kernel Restarted", message: `Kernel ${kernel.kernelSpecName} has been restarted.`, dismissible: true, position: "tr", level: "success" }); return of( actions.killKernel({ restarting: true, kernelRef: action.payload.kernelRef }), actions.launchKernelByName({ kernelSpecName: kernel.kernelSpecName, cwd: kernel.cwd, kernelRef: createKernelRef(), selectNextKernel: true }) ); }) );
refer to old kernel by name in restart epic
packages/core/src/epics/kernel-lifecycle.js
refer to old kernel by name in restart epic
<ide><path>ackages/core/src/epics/kernel-lifecycle.js <ide> ofType(actionTypes.RESTART_KERNEL), <ide> concatMap((action: RestartKernel) => { <ide> const state = store.getState(); <del> const kernel = selectors.currentKernel(state); <add> <add> const oldKernelRef = action.payload.kernelRef; <add> const oldKernel = selectors.kernel(state, { kernelRef: oldKernelRef }); <add> <ide> const notificationSystem = selectors.notificationSystem(state); <ide> <del> if (!kernel) { <add> if (!oldKernelRef || !oldKernel) { <ide> notificationSystem.addNotification({ <ide> title: "Failure to Restart", <ide> message: `Unable to restart kernel, please select a new kernel.`, <ide> // This only mirrors the old behavior of restart kernel (for now) <ide> notificationSystem.addNotification({ <ide> title: "Kernel Restarted", <del> message: `Kernel ${kernel.kernelSpecName} has been restarted.`, <add> message: `Kernel ${oldKernel.kernelSpecName} has been restarted.`, <ide> dismissible: true, <ide> position: "tr", <ide> level: "success" <ide> return of( <ide> actions.killKernel({ <ide> restarting: true, <del> kernelRef: action.payload.kernelRef <add> kernelRef: oldKernelRef <ide> }), <ide> actions.launchKernelByName({ <del> kernelSpecName: kernel.kernelSpecName, <del> cwd: kernel.cwd, <add> kernelSpecName: oldKernel.kernelSpecName, <add> cwd: oldKernel.cwd, <ide> kernelRef: createKernelRef(), <ide> selectNextKernel: true <ide> })
Java
mit
6b614be92f4aa1f0b3e603722ebe74187f945f34
0
ngageoint/geopackage-core-java
package mil.nga.geopackage.extension.contents; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import mil.nga.geopackage.GeoPackageCore; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.core.contents.Contents; import mil.nga.geopackage.core.contents.ContentsDao; import mil.nga.geopackage.core.contents.ContentsDataType; import mil.nga.geopackage.extension.BaseExtension; import mil.nga.geopackage.extension.ExtensionScopeType; import mil.nga.geopackage.extension.Extensions; import mil.nga.geopackage.property.GeoPackageProperties; import mil.nga.geopackage.property.PropertyConstants; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; /** * This extension assigns a unique integer identifier to tables defined in the * contents. Allows foreign key referencing to a contents (text based primary * key) by an integer identifier. * * @author osbornb * @since 3.1.1 */ public class ContentsIdExtension extends BaseExtension { /** * Logger */ private static final Logger logger = Logger .getLogger(ContentsIdExtension.class.getName()); /** * Extension author */ public static final String EXTENSION_AUTHOR = "nga"; /** * Extension name without the author */ public static final String EXTENSION_NAME_NO_AUTHOR = "contents_id"; /** * Extension, with author and name */ public static final String EXTENSION_NAME = Extensions.buildExtensionName( EXTENSION_AUTHOR, EXTENSION_NAME_NO_AUTHOR); /** * Extension definition URL */ public static final String EXTENSION_DEFINITION = GeoPackageProperties .getProperty(PropertyConstants.EXTENSIONS, EXTENSION_NAME_NO_AUTHOR); /** * Contents Id DAO */ private final ContentsIdDao contentsIdDao; /** * Constructor * * @param geoPackage * GeoPackage */ public ContentsIdExtension(GeoPackageCore geoPackage) { super(geoPackage); contentsIdDao = geoPackage.getContentsIdDao(); } /** * Get the contents id DAO * * @return dao */ public ContentsIdDao getDao() { return contentsIdDao; } /** * Determine if the GeoPackage has the extension * * @return true if has extension */ public boolean has() { boolean exists = false; try { exists = has(EXTENSION_NAME, null, null) && contentsIdDao.isTableExists(); } catch (SQLException e) { throw new GeoPackageException( "Failed to check for contents id for GeoPackage: " + geoPackage.getName(), e); } return exists; } /** * Get the contents id object * * @param contents * contents * @return contents id or null */ public ContentsId get(Contents contents) { return get(contents.getTableName()); } /** * Get the contents id object * * @param tableName * table name * @return contents id or null */ public ContentsId get(String tableName) { ContentsId contentsId = null; try { if (contentsIdDao.isTableExists()) { contentsId = contentsIdDao.queryForTableName(tableName); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query contents id for GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName, e); } return contentsId; } /** * Get the contents id * * @param contents * contents * @return contents id or null */ public Long getId(Contents contents) { return getId(contents.getTableName()); } /** * Get the contents id * * @param tableName * table name * @return contents id or null */ public Long getId(String tableName) { Long id = null; ContentsId contentsId = get(tableName); if (contentsId != null) { id = contentsId.getId(); } return id; } /** * Create a contents id * * @param contents * contents * @return new contents id */ public ContentsId create(Contents contents) { return create(contents.getTableName()); } /** * Create a contents id * * @param tableName * table name * @return new contents id */ public ContentsId create(String tableName) { if (!has()) { getOrCreateExtension(); } ContentsId contentsId = new ContentsId(); Contents contents = geoPackage.getTableContents(tableName); contentsId.setContents(contents); try { contentsIdDao.create(contentsId); } catch (SQLException e) { throw new GeoPackageException( "Failed to create contents id for GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName, e); } return contentsId; } /** * Create a contents id * * @param contents * contents * @return new contents id */ public long createId(Contents contents) { return createId(contents.getTableName()); } /** * Create a contents id * * @param tableName * table name * @return new contents id */ public long createId(String tableName) { ContentsId contentsId = create(tableName); return contentsId.getId(); } /** * Get or create a contents id * * @param contents * contents * @return new or existing contents id */ public ContentsId getOrCreate(Contents contents) { return getOrCreate(contents.getTableName()); } /** * Get or create a contents id * * @param tableName * table name * @return new or existing contents id */ public ContentsId getOrCreate(String tableName) { ContentsId contentsId = get(tableName); if (contentsId == null) { contentsId = create(tableName); } return contentsId; } /** * Get or create a contents id * * @param contents * contents * @return new or existing contents id */ public long getOrCreateId(Contents contents) { return getOrCreateId(contents.getTableName()); } /** * Get or create a contents id * * @param tableName * table name * @return new or existing contents id */ public long getOrCreateId(String tableName) { ContentsId contentsId = getOrCreate(tableName); return contentsId.getId(); } /** * Delete the contents id for the contents * * @param contents * contents * * @return true if deleted */ public boolean delete(Contents contents) { return delete(contents.getTableName()); } /** * Delete the contents id for the table * * @param tableName * table name * * @return true if deleted */ public boolean delete(String tableName) { boolean deleted = false; try { if (contentsIdDao.isTableExists()) { deleted = contentsIdDao.deleteByTableName(tableName) > 0; } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete Contents Id extension table. GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName, e); } return deleted; } /** * Create contents ids for contents currently without * * @return newly created contents ids count */ public int createIds() { return createIds(""); } /** * Create contents ids for contents of the data type and currently without * * @param type * contents data type * @return newly created contents ids count */ public int createIds(ContentsDataType type) { return createIds(type.getName()); } /** * Create contents ids for contents of the data type and currently without * * @param type * contents data type * @return newly created contents ids count */ public int createIds(String type) { List<String> tables = getMissing(type); for (String tableName : tables) { getOrCreate(tableName); } return tables.size(); } /** * Delete all contents ids * * @return deleted contents ids count */ public int deleteIds() { int deleted = 0; try { if (contentsIdDao.isTableExists()) { deleted = contentsIdDao.delete(contentsIdDao.deleteBuilder() .prepare()); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete all contents ids. GeoPackage: " + geoPackage.getName(), e); } return deleted; } /** * Delete contents ids for contents of the data type * * @param type * contents data type * @return deleted contents ids count */ public int deleteIds(ContentsDataType type) { return deleteIds(type.getName()); } /** * Delete contents ids for contents of the data type * * @param type * contents data type * @return deleted contents ids count */ public int deleteIds(String type) { int deleted = 0; try { if (contentsIdDao.isTableExists()) { List<ContentsId> contentsIds = getIds(type); deleted = contentsIdDao.delete(contentsIds); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete contents ids by type. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } return deleted; } /** * Get all contents ids * * @return contents ids */ public List<ContentsId> getIds() { List<ContentsId> contentsIds = null; try { if (contentsIdDao.isTableExists()) { contentsIds = contentsIdDao.queryForAll(); } else { contentsIds = new ArrayList<>(); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query for all contents ids. GeoPackage: " + geoPackage.getName(), e); } return contentsIds; } /** * Get the count of contents ids * * @return count * @since 3.1.1 */ public long count() { long count = 0; if (has()) { try { count = contentsIdDao.countOf(); } catch (SQLException e) { throw new GeoPackageException( "Failed to count contents ids. GeoPackage: " + geoPackage.getName(), e); } } return count; } /** * Get by contents data type * * @param type * contents data type * @return contents ids */ public List<ContentsId> getIds(ContentsDataType type) { return getIds(type.getName()); } /** * Get by contents data type * * @param type * contents data type * @return contents ids */ public List<ContentsId> getIds(String type) { List<ContentsId> contentsIds = null; ContentsDao contentsDao = geoPackage.getContentsDao(); try { if (contentsIdDao.isTableExists()) { QueryBuilder<Contents, String> contentsQueryBuilder = contentsDao .queryBuilder(); QueryBuilder<ContentsId, Long> contentsIdQueryBuilder = contentsIdDao .queryBuilder(); contentsQueryBuilder.where() .eq(Contents.COLUMN_DATA_TYPE, type); contentsIdQueryBuilder.join(contentsQueryBuilder); contentsIds = contentsIdQueryBuilder.query(); } else { contentsIds = new ArrayList<>(); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query for contents id by contents data type. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } return contentsIds; } /** * Get contents without contents ids * * @return table names without contents ids */ public List<String> getMissing() { return getMissing(""); } /** * Get contents by data type without contents ids * * @param type * contents data type * @return table names without contents ids */ public List<String> getMissing(ContentsDataType type) { return getMissing(type.getName()); } /** * Get contents by data type without contents ids * * @param type * contents data type * @return table names without contents ids */ public List<String> getMissing(String type) { List<String> missing = new ArrayList<>(); ContentsDao contentsDao = geoPackage.getContentsDao(); GenericRawResults<String[]> results = null; try { StringBuilder query = new StringBuilder(); query.append("SELECT "); query.append(Contents.COLUMN_TABLE_NAME); query.append(" FROM "); query.append(Contents.TABLE_NAME); StringBuilder where = new StringBuilder(); String[] queryArgs; if (type != null && !type.isEmpty()) { where.append(Contents.COLUMN_DATA_TYPE); where.append(" = ?"); queryArgs = new String[] { type }; } else { queryArgs = new String[] {}; type = null; } if (contentsIdDao.isTableExists()) { if (where.length() > 0) { where.append(" AND "); } where.append(Contents.COLUMN_TABLE_NAME); where.append(" NOT IN (SELECT "); where.append(ContentsId.COLUMN_TABLE_NAME); where.append(" FROM "); where.append(ContentsId.TABLE_NAME); where.append(")"); } if (where.length() > 0) { query.append(" WHERE ").append(where); } results = contentsDao.queryRaw(query.toString(), queryArgs); for (String[] resultRow : results) { missing.add(resultRow[0]); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query for missing contents ids. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } finally { if (results != null) { try { results.close(); } catch (IOException e) { logger.log(Level.WARNING, "Failed to close generic raw results from missing contents ids query. type: " + type, e); } } } return missing; } /** * Get or create if needed the extension * * @return extensions object */ public Extensions getOrCreateExtension() { // Create table geoPackage.createContentsIdTable(); Extensions extension = getOrCreate(EXTENSION_NAME, null, null, EXTENSION_DEFINITION, ExtensionScopeType.READ_WRITE); return extension; } /** * Get the extension * * @return extensions object or null if one does not exist */ public Extensions getExtension() { Extensions extension = get(EXTENSION_NAME, null, null); return extension; } /** * Remove all trace of the extension */ public void removeExtension() { try { if (contentsIdDao.isTableExists()) { geoPackage.dropTable(contentsIdDao.getTableName()); } if (extensionsDao.isTableExists()) { extensionsDao.deleteByExtension(EXTENSION_NAME); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete Contents Id extension and table. GeoPackage: " + geoPackage.getName(), e); } } }
src/main/java/mil/nga/geopackage/extension/contents/ContentsIdExtension.java
package mil.nga.geopackage.extension.contents; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import mil.nga.geopackage.GeoPackageCore; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.core.contents.Contents; import mil.nga.geopackage.core.contents.ContentsDao; import mil.nga.geopackage.core.contents.ContentsDataType; import mil.nga.geopackage.extension.BaseExtension; import mil.nga.geopackage.extension.ExtensionScopeType; import mil.nga.geopackage.extension.Extensions; import mil.nga.geopackage.property.GeoPackageProperties; import mil.nga.geopackage.property.PropertyConstants; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; /** * This extension assigns a unique integer identifier to tables defined in the * contents. Allows foreign key referencing to a contents (text based primary * key) by an integer identifier. * * @author osbornb * @since 3.1.1 */ public class ContentsIdExtension extends BaseExtension { /** * Logger */ private static final Logger logger = Logger .getLogger(ContentsIdExtension.class.getName()); /** * Extension author */ public static final String EXTENSION_AUTHOR = "nga"; /** * Extension name without the author */ public static final String EXTENSION_NAME_NO_AUTHOR = "contents_id"; /** * Extension, with author and name */ public static final String EXTENSION_NAME = Extensions.buildExtensionName( EXTENSION_AUTHOR, EXTENSION_NAME_NO_AUTHOR); /** * Extension definition URL */ public static final String EXTENSION_DEFINITION = GeoPackageProperties .getProperty(PropertyConstants.EXTENSIONS, EXTENSION_NAME_NO_AUTHOR); /** * Contents Id DAO */ private final ContentsIdDao contentsIdDao; /** * Constructor * * @param geoPackage * GeoPackage */ public ContentsIdExtension(GeoPackageCore geoPackage) { super(geoPackage); contentsIdDao = geoPackage.getContentsIdDao(); } /** * Get the contents id DAO * * @return dao */ public ContentsIdDao getDao() { return contentsIdDao; } /** * Determine if the GeoPackage has the extension * * @return true if has extension */ public boolean has() { boolean exists = false; try { exists = has(EXTENSION_NAME, null, null) && contentsIdDao.isTableExists(); } catch (SQLException e) { throw new GeoPackageException( "Failed to check for contents id for GeoPackage: " + geoPackage.getName(), e); } return exists; } /** * Get the contents id object * * @param contents * contents * @return contents id or null */ public ContentsId get(Contents contents) { return get(contents.getTableName()); } /** * Get the contents id object * * @param tableName * table name * @return contents id or null */ public ContentsId get(String tableName) { ContentsId contentsId = null; try { if (contentsIdDao.isTableExists()) { contentsId = contentsIdDao.queryForTableName(tableName); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query contents id for GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName, e); } return contentsId; } /** * Get the contents id * * @param contents * contents * @return contents id or null */ public Long getId(Contents contents) { return getId(contents.getTableName()); } /** * Get the contents id * * @param tableName * table name * @return contents id or null */ public Long getId(String tableName) { Long id = null; ContentsId contentsId = get(tableName); if (contentsId != null) { id = contentsId.getId(); } return id; } /** * Create a contents id * * @param contents * contents * @return new contents id */ public ContentsId create(Contents contents) { return create(contents.getTableName()); } /** * Create a contents id * * @param tableName * table name * @return new contents id */ public ContentsId create(String tableName) { if (!has()) { getOrCreateExtension(); } ContentsId contentsId = new ContentsId(); Contents contents = geoPackage.getTableContents(tableName); contentsId.setContents(contents); try { contentsIdDao.create(contentsId); } catch (SQLException e) { throw new GeoPackageException( "Failed to create contents id for GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName, e); } return contentsId; } /** * Create a contents id * * @param contents * contents * @return new contents id */ public long createId(Contents contents) { return createId(contents.getTableName()); } /** * Create a contents id * * @param tableName * table name * @return new contents id */ public long createId(String tableName) { ContentsId contentsId = create(tableName); return contentsId.getId(); } /** * Get or create a contents id * * @param contents * contents * @return new or existing contents id */ public ContentsId getOrCreate(Contents contents) { return getOrCreate(contents.getTableName()); } /** * Get or create a contents id * * @param tableName * table name * @return new or existing contents id */ public ContentsId getOrCreate(String tableName) { ContentsId contentsId = get(tableName); if (contentsId == null) { contentsId = create(tableName); } return contentsId; } /** * Get or create a contents id * * @param contents * contents * @return new or existing contents id */ public long getOrCreateId(Contents contents) { return getOrCreateId(contents.getTableName()); } /** * Get or create a contents id * * @param tableName * table name * @return new or existing contents id */ public long getOrCreateId(String tableName) { ContentsId contentsId = getOrCreate(tableName); return contentsId.getId(); } /** * Delete the contents id for the contents * * @param contents * contents * * @return true if deleted */ public boolean delete(Contents contents) { return delete(contents.getTableName()); } /** * Delete the contents id for the table * * @param tableName * table name * * @return true if deleted */ public boolean delete(String tableName) { boolean deleted = false; try { if (contentsIdDao.isTableExists()) { deleted = contentsIdDao.deleteByTableName(tableName) > 0; } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete Contents Id extension table. GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName, e); } return deleted; } /** * Create contents ids for contents currently without * * @return newly created contents ids count */ public int createIds() { return createIds(""); } /** * Create contents ids for contents of the data type and currently without * * @param type * contents data type * @return newly created contents ids count */ public int createIds(ContentsDataType type) { return createIds(type.getName()); } /** * Create contents ids for contents of the data type and currently without * * @param type * contents data type * @return newly created contents ids count */ public int createIds(String type) { List<String> tables = getMissing(type); for (String tableName : tables) { getOrCreate(tableName); } return tables.size(); } /** * Delete all contents ids * * @return deleted contents ids count */ public int deleteIds() { int deleted = 0; try { if (contentsIdDao.isTableExists()) { deleted = contentsIdDao.delete(contentsIdDao.deleteBuilder() .prepare()); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete all contents ids. GeoPackage: " + geoPackage.getName(), e); } return deleted; } /** * Delete contents ids for contents of the data type * * @param type * contents data type * @return deleted contents ids count */ public int deleteIds(ContentsDataType type) { return deleteIds(type.getName()); } /** * Delete contents ids for contents of the data type * * @param type * contents data type * @return deleted contents ids count */ public int deleteIds(String type) { int deleted = 0; try { if (contentsIdDao.isTableExists()) { List<ContentsId> contentsIds = getIds(type); deleted = contentsIdDao.delete(contentsIds); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete contents ids by type. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } return deleted; } /** * Get all contents ids * * @return contents ids */ public List<ContentsId> getIds() { List<ContentsId> contentsIds = null; try { if (contentsIdDao.isTableExists()) { contentsIds = contentsIdDao.queryForAll(); } else { contentsIds = new ArrayList<>(); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query for all contents ids. GeoPackage: " + geoPackage.getName(), e); } return contentsIds; } /** * Get by contents data type * * @param type * contents data type * @return contents ids */ public List<ContentsId> getIds(ContentsDataType type) { return getIds(type.getName()); } /** * Get by contents data type * * @param type * contents data type * @return contents ids */ public List<ContentsId> getIds(String type) { List<ContentsId> contentsIds = null; ContentsDao contentsDao = geoPackage.getContentsDao(); try { if (contentsIdDao.isTableExists()) { QueryBuilder<Contents, String> contentsQueryBuilder = contentsDao .queryBuilder(); QueryBuilder<ContentsId, Long> contentsIdQueryBuilder = contentsIdDao .queryBuilder(); contentsQueryBuilder.where() .eq(Contents.COLUMN_DATA_TYPE, type); contentsIdQueryBuilder.join(contentsQueryBuilder); contentsIds = contentsIdQueryBuilder.query(); } else { contentsIds = new ArrayList<>(); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query for contents id by contents data type. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } return contentsIds; } /** * Get contents without contents ids * * @return table names without contents ids */ public List<String> getMissing() { return getMissing(""); } /** * Get contents by data type without contents ids * * @param type * contents data type * @return table names without contents ids */ public List<String> getMissing(ContentsDataType type) { return getMissing(type.getName()); } /** * Get contents by data type without contents ids * * @param type * contents data type * @return table names without contents ids */ public List<String> getMissing(String type) { List<String> missing = new ArrayList<>(); ContentsDao contentsDao = geoPackage.getContentsDao(); GenericRawResults<String[]> results = null; try { StringBuilder query = new StringBuilder(); query.append("SELECT "); query.append(Contents.COLUMN_TABLE_NAME); query.append(" FROM "); query.append(Contents.TABLE_NAME); StringBuilder where = new StringBuilder(); String[] queryArgs; if (type != null && !type.isEmpty()) { where.append(Contents.COLUMN_DATA_TYPE); where.append(" = ?"); queryArgs = new String[] { type }; } else { queryArgs = new String[] {}; type = null; } if (contentsIdDao.isTableExists()) { if (where.length() > 0) { where.append(" AND "); } where.append(Contents.COLUMN_TABLE_NAME); where.append(" NOT IN (SELECT "); where.append(ContentsId.COLUMN_TABLE_NAME); where.append(" FROM "); where.append(ContentsId.TABLE_NAME); where.append(")"); } if (where.length() > 0) { query.append(" WHERE ").append(where); } results = contentsDao.queryRaw(query.toString(), queryArgs); for (String[] resultRow : results) { missing.add(resultRow[0]); } } catch (SQLException e) { throw new GeoPackageException( "Failed to query for missing contents ids. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } finally { if (results != null) { try { results.close(); } catch (IOException e) { logger.log(Level.WARNING, "Failed to close generic raw results from missing contents ids query. type: " + type, e); } } } return missing; } /** * Get or create if needed the extension * * @return extensions object */ public Extensions getOrCreateExtension() { // Create table geoPackage.createContentsIdTable(); Extensions extension = getOrCreate(EXTENSION_NAME, null, null, EXTENSION_DEFINITION, ExtensionScopeType.READ_WRITE); return extension; } /** * Get the extension * * @return extensions object or null if one does not exist */ public Extensions getExtension() { Extensions extension = get(EXTENSION_NAME, null, null); return extension; } /** * Remove all trace of the extension */ public void removeExtension() { try { if (contentsIdDao.isTableExists()) { geoPackage.dropTable(contentsIdDao.getTableName()); } if (extensionsDao.isTableExists()) { extensionsDao.deleteByExtension(EXTENSION_NAME); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete Contents Id extension and table. GeoPackage: " + geoPackage.getName(), e); } } }
contents id extension count method
src/main/java/mil/nga/geopackage/extension/contents/ContentsIdExtension.java
contents id extension count method
<ide><path>rc/main/java/mil/nga/geopackage/extension/contents/ContentsIdExtension.java <ide> + geoPackage.getName(), e); <ide> } <ide> return contentsIds; <add> } <add> <add> /** <add> * Get the count of contents ids <add> * <add> * @return count <add> * @since 3.1.1 <add> */ <add> public long count() { <add> long count = 0; <add> if (has()) { <add> try { <add> count = contentsIdDao.countOf(); <add> } catch (SQLException e) { <add> throw new GeoPackageException( <add> "Failed to count contents ids. GeoPackage: " <add> + geoPackage.getName(), e); <add> } <add> } <add> return count; <ide> } <ide> <ide> /**
Java
apache-2.0
431a5e98c29131e20c33a997e09c36c6fc84953a
0
saego/RepositBasic,saego/RepositBasic
import java.io.*; /** Created by ${Ruslan} on 16.01.17. */ class WorkChat { void chatting(File fileAnswers, File logs, InputStream input) throws IOException { BufferedReader bufferedReader; long []positions; int n = 0, rowsQuantity =0; try(RandomAccessFile rafr00 = new RandomAccessFile(fileAnswers, "r")){ while (rafr00.readLine() != null){ rowsQuantity++; } } catch (IOException ex){ System.out.println(ex.getMessage()); } positions = new long[rowsQuantity]; //формуємо массив позицій початків рядків try (RandomAccessFile rafr0 = new RandomAccessFile(fileAnswers, "r")){ do { long m = rafr0.getFilePointer(); if (n != rowsQuantity - 1){ positions[n] = m; n++; } } while (rafr0.readLine() != null); } catch (IOException ex){ System.out.println(ex.getMessage()); } try( RandomAccessFile rafr = new RandomAccessFile(fileAnswers, "r"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logs)) ) { String lineAsk; do { //зчитуємо з консолі питання bufferedReader = new BufferedReader(new InputStreamReader(input)); lineAsk = bufferedReader.readLine(); //записуємо в лог-файл питання String user = "User : "; bufferedWriter.write(user.concat(lineAsk)); //зчитуємо відповідь з файла відповідей if (!lineAsk.toLowerCase().equals("stop")) bufferedWriter.newLine(); if(!lineAsk.toLowerCase().equals("stop") && !lineAsk.toLowerCase().equals("pause")) { rafr.seek(positions[(int) (Math.random() * (positions.length - 1))]); String lineAnswer = rafr.readLine(); //записуємо в лог-файл відповідь String computer = "Computer : "; bufferedWriter.write(computer.concat(lineAnswer).concat(System.lineSeparator())); //записуємо відповідь в консоль System.out.println(computer.concat(lineAnswer)); } } while (!lineAsk.toLowerCase().equals("stop")); } catch (IOException ex){ System.out.println(ex.getMessage()); } } }
Chat/src/main/java/WorkChat.java
import java.io.*; /** Created by ${Ruslan} on 16.01.17. */ class WorkChat { void chatting(File fileAnswers, File logs, InputStream input) throws IOException { BufferedReader bufferedReader; int []positions; int n = 0, rowsQuantity =0; try(RandomAccessFile rafr00 = new RandomAccessFile(fileAnswers, "r")){ while (rafr00.readLine() != null){ rowsQuantity++; } } catch (IOException ex){ System.out.println(ex.getMessage()); } positions = new int[rowsQuantity]; //формуємо массив позицій початків рядків try (RandomAccessFile rafr0 = new RandomAccessFile(fileAnswers, "r")){ do { long m = rafr0.getFilePointer(); if (n != rowsQuantity - 1){ positions[n] = (int)m; n++; } } while (rafr0.readLine() != null); } catch (IOException ex){ System.out.println(ex.getMessage()); } try( RandomAccessFile rafr = new RandomAccessFile(fileAnswers, "r"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logs)) ) { String lineAsk; do { //зчитуємо з консолі питання bufferedReader = new BufferedReader(new InputStreamReader(input)); lineAsk = bufferedReader.readLine(); //записуємо в лог-файл питання String user = "User : "; bufferedWriter.write(user.concat(lineAsk)); //зчитуємо відповідь з файла відповідей if (!lineAsk.equals("stop")) bufferedWriter.newLine(); if(!lineAsk.equals("stop") && !lineAsk.equals("pause")) { rafr.seek((long)positions[(int) (Math.random() * (positions.length - 1))]); String lineAnswer = rafr.readLine(); //записуємо в лог-файл відповідь String computer = "Computer : "; bufferedWriter.write(computer.concat(lineAnswer).concat(System.lineSeparator())); //записуємо відповідь в консоль System.out.println(computer.concat(lineAnswer)); } } while (!lineAsk.equals("stop")); } catch (IOException ex){ System.out.println(ex.getMessage()); } } }
19/17 15/29 chat don't know what to do
Chat/src/main/java/WorkChat.java
19/17 15/29 chat don't know what to do
<ide><path>hat/src/main/java/WorkChat.java <ide> <ide> void chatting(File fileAnswers, File logs, InputStream input) throws IOException { <ide> BufferedReader bufferedReader; <del> int []positions; <add> long []positions; <ide> int n = 0, rowsQuantity =0; <ide> try(RandomAccessFile rafr00 = new RandomAccessFile(fileAnswers, "r")){ <ide> while (rafr00.readLine() != null){ <ide> catch (IOException ex){ <ide> System.out.println(ex.getMessage()); <ide> } <del> positions = new int[rowsQuantity]; <add> positions = new long[rowsQuantity]; <ide> //формуємо массив позицій початків рядків <ide> try (RandomAccessFile rafr0 = new RandomAccessFile(fileAnswers, "r")){ <ide> do { <ide> long m = rafr0.getFilePointer(); <ide> if (n != rowsQuantity - 1){ <del> positions[n] = (int)m; <add> positions[n] = m; <ide> n++; <ide> } <ide> } <ide> String user = "User : "; <ide> bufferedWriter.write(user.concat(lineAsk)); <ide> //зчитуємо відповідь з файла відповідей <del> if (!lineAsk.equals("stop")) <add> if (!lineAsk.toLowerCase().equals("stop")) <ide> bufferedWriter.newLine(); <del> if(!lineAsk.equals("stop") && !lineAsk.equals("pause")) { <del> rafr.seek((long)positions[(int) (Math.random() * (positions.length - 1))]); <add> if(!lineAsk.toLowerCase().equals("stop") && !lineAsk.toLowerCase().equals("pause")) { <add> rafr.seek(positions[(int) (Math.random() * (positions.length - 1))]); <ide> String lineAnswer = rafr.readLine(); <ide> //записуємо в лог-файл відповідь <ide> String computer = "Computer : "; <ide> System.out.println(computer.concat(lineAnswer)); <ide> } <ide> } <del> while (!lineAsk.equals("stop")); <add> while (!lineAsk.toLowerCase().equals("stop")); <ide> } <ide> catch (IOException ex){ <ide> System.out.println(ex.getMessage());
Java
apache-2.0
c6e14425f07fdb37e4babb530953eadbefb03c8e
0
adrcotfas/Goodtime
package com.apps.adrcotfas.goodtime.Settings; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.text.InputFilter; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.apps.adrcotfas.goodtime.R; import androidx.appcompat.app.AlertDialog; import androidx.preference.Preference; import androidx.preference.PreferenceViewHolder; import static android.graphics.Paint.UNDERLINE_TEXT_FLAG; import static android.text.InputType.TYPE_CLASS_NUMBER; import static android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL; /** * Preference based on android.preference.SeekBarPreference but uses support v7 preference as base. * The main difference is the fact that the seekbar value is updated while the user is tracking the touch. * It contains a title and a seekbar and an optional seekbar value TextView. The actual preference * layout is customizable by setting {@code android:layout} on the preference widget layout or * {@code CustomSeekStyle} attribute. * The seekbar within the preference can be defined adjustable or not by setting {@code * adjustable} attribute. If adjustable, the preference will be responsive to DPAD left/right keys. * Otherwise, it skips those keys. * The seekbar value view can be shown or disabled by setting {@code showSeekBarValue} attribute * to true or false, respectively. * Other SeekBar specific attributes (e.g. {@code title, summary, defaultValue, min, max}) can be * set directly on the preference widget layout. */ public class ProperSeekBarPreference extends Preference { private int mSeekBarValue; private int mMin; private int mMax; private int mSeekBarIncrement; private SeekBar mSeekBar; private TextView mSeekBarValueTextView; private boolean mAdjustable; // whether the seekbar should respond to the left/right keys private boolean mShowSeekBarValue; // whether to show the seekbar value TextView next to the bar private String mUnit; private String mDialogTitle; private static final String TAG = "ProperSeekBarPreference"; /** * Listener reacting to the SeekBar changing value by the user */ private OnSeekBarChangeListener mSeekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { syncValueInternal(seekBar); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; /** * Listener reacting to the user pressing DPAD left/right keys if {@code * adjustable} attribute is set to true; it transfers the key presses to the SeekBar * to be handled accordingly. */ private View.OnKeyListener mSeekBarKeyListener = new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } if (!mAdjustable && (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { // Right or left keys are pressed when in non-adjustable mode; Skip the keys. return false; } // We don't want to propagate the click keys down to the seekbar view since it will // create the ripple effect for the thumb. if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { return false; } if (mSeekBar == null) { Log.e(TAG, "SeekBar view is null and hence cannot be adjusted."); return false; } return mSeekBar.onKeyDown(keyCode, event); } }; public ProperSeekBarPreference( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.ProperSeekBarPreference, defStyleAttr, defStyleRes); /** * The ordering of these two statements are important. If we want to set max first, we need * to perform the same steps by changing min/max to max/min as following: * mMax = a.getInt(...) and setMin(...). */ mMin = a.getInt(R.styleable.ProperSeekBarPreference_min, 0); setMax(a.getInt(R.styleable.ProperSeekBarPreference_android_max, 100)); setSeekBarIncrement(a.getInt(R.styleable.ProperSeekBarPreference_seekBarIncrement, 0)); mAdjustable = a.getBoolean(R.styleable.ProperSeekBarPreference_adjustable, true); mShowSeekBarValue = a.getBoolean(R.styleable.ProperSeekBarPreference_showSeekBarValue, true); mUnit = a.getString(R.styleable.ProperSeekBarPreference_unitOfMeasurement); mDialogTitle = a.getString(R.styleable.ProperSeekBarPreference_dialogTitle); a.recycle(); } public ProperSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public ProperSeekBarPreference(Context context, AttributeSet attrs) { this(context, attrs, R.attr.seekBarPreferenceStyle); } public ProperSeekBarPreference(Context context) { this(context, null); } @Override public void onBindViewHolder(PreferenceViewHolder view) { super.onBindViewHolder(view); view.itemView.setOnKeyListener(mSeekBarKeyListener); mSeekBar = (SeekBar) view.findViewById(R.id.seekbar); float dpi = getContext().getResources().getDisplayMetrics().density; mSeekBar.setPadding(0,(int)(5 * dpi),(int)(16 * dpi),(int)(5 * dpi)); mSeekBarValueTextView = (TextView) view.findViewById(R.id.seekbar_value); mSeekBarValueTextView.setClickable(true); mSeekBarValueTextView.setPaintFlags(UNDERLINE_TEXT_FLAG); mSeekBarValueTextView.setTextSize(14); mSeekBarValueTextView.setTextColor(getContext().getResources().getColor(R.color.transparent_light)); mSeekBarValueTextView.setOnClickListener(view1 -> { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); LinearLayout layout = new LinearLayout(getContext()); final EditText input = new EditText(getContext()); input.setInputType(TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMAL); input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); input.setSingleLine(); InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(3); input.setFilters(FilterArray); layout.addView(input); layout.setPadding((int)(19*dpi), (int)(5*dpi), (int)(19*dpi), (int)(5*dpi)); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); builder.setTitle(mDialogTitle) .setView(layout); builder.setPositiveButton("OK", (di, i) -> { final String name = input.getText().toString(); if (!TextUtils.isEmpty(name)) { setValueInternal(Integer.parseInt(name), true); } }); builder.setNegativeButton("Cancel", (di, i) -> { }); AlertDialog dialog = builder.create(); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); }); if (mShowSeekBarValue) { mSeekBarValueTextView.setVisibility(View.VISIBLE); } else { mSeekBarValueTextView.setVisibility(View.GONE); mSeekBarValueTextView = null; } if (mSeekBar == null) { Log.e(TAG, "SeekBar view is null in onBindViewHolder."); return; } mSeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener); mSeekBar.setMax(mMax - mMin); // If the increment is not zero, use that. Otherwise, use the default mKeyProgressIncrement // in AbsSeekBar when it's zero. This default increment value is set by AbsSeekBar // after calling setMax. That's why it's important to call setKeyProgressIncrement after // calling setMax() since setMax() can change the increment value. if (mSeekBarIncrement != 0) { mSeekBar.setKeyProgressIncrement(mSeekBarIncrement); } else { mSeekBarIncrement = mSeekBar.getKeyProgressIncrement(); } mSeekBar.setProgress(mSeekBarValue - mMin); if (mSeekBarValueTextView != null) { mSeekBarValueTextView.setText(String.valueOf(mSeekBarValue) + mUnit); } mSeekBar.setEnabled(isEnabled()); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedInt(mSeekBarValue) : (Integer) defaultValue); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getInt(index, 0); } public void setMin(int min) { if (min > mMax) { min = mMax; } if (min != mMin) { mMin = min; notifyChanged(); } } public int getMin() { return mMin; } public final void setMax(int max) { if (max < mMin) { max = mMin; } if (max != mMax) { mMax = max; notifyChanged(); } } /** * Returns the amount of increment change via each arrow key click. This value is derived from * user's specified increment value if it's not zero. Otherwise, the default value is picked * from the default mKeyProgressIncrement value in {@link android.widget.AbsSeekBar}. * @return The amount of increment on the SeekBar performed after each user's arrow key press. */ public final int getSeekBarIncrement() { return mSeekBarIncrement; } /** * Sets the increment amount on the SeekBar for each arrow key press. * @param seekBarIncrement The amount to increment or decrement when the user presses an * arrow key. */ public final void setSeekBarIncrement(int seekBarIncrement) { if (seekBarIncrement != mSeekBarIncrement) { mSeekBarIncrement = Math.min(mMax - mMin, Math.abs(seekBarIncrement)); notifyChanged(); } } public int getMax() { return mMax; } public void setAdjustable(boolean adjustable) { mAdjustable = adjustable; } public boolean isAdjustable() { return mAdjustable; } public void setValue(int seekBarValue) { setValueInternal(seekBarValue, true); } private void setValueInternal(int seekBarValue, boolean notifyChanged) { if (seekBarValue < mMin) { seekBarValue = mMin; } if (seekBarValue > mMax) { seekBarValue = mMax; } if (seekBarValue != mSeekBarValue) { mSeekBarValue = seekBarValue; if (mSeekBarValueTextView != null) { mSeekBarValueTextView.setText(String.valueOf(mSeekBarValue) + mUnit); } persistInt(seekBarValue); if (notifyChanged) { notifyChanged(); } } } public int getValue() { return mSeekBarValue; } /** * Persist the seekBar's seekbar value if callChangeListener * returns true, otherwise set the seekBar's value to the stored value */ private void syncValueInternal(SeekBar seekBar) { int seekBarValue = mMin + seekBar.getProgress(); if (seekBarValue != mSeekBarValue) { if (callChangeListener(seekBarValue)) { setValueInternal(seekBarValue, false); } else { seekBar.setProgress(mSeekBarValue - mMin); } } } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { // No need to save instance state since it's persistent return superState; } // Save the instance state final SavedState myState = new SavedState(superState); myState.seekBarValue = mSeekBarValue; myState.min = mMin; myState.max = mMax; return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!state.getClass().equals(SavedState.class)) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); return; } // Restore the instance state SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); mSeekBarValue = myState.seekBarValue; mMin = myState.min; mMax = myState.max; notifyChanged(); } /** * SavedState, a subclass of {@link BaseSavedState}, will store the state * of MyPreference, a subclass of Preference. * <p> * It is important to always call through to super methods. */ private static class SavedState extends BaseSavedState { int seekBarValue; int min; int max; public SavedState(Parcel source) { super(source); // Restore the click counter seekBarValue = source.readInt(); min = source.readInt(); max = source.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); // Save the click counter dest.writeInt(seekBarValue); dest.writeInt(min); dest.writeInt(max); } public SavedState(Parcelable superState) { super(superState); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
app/src/main/java/com/apps/adrcotfas/goodtime/Settings/ProperSeekBarPreference.java
package com.apps.adrcotfas.goodtime.Settings; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.apps.adrcotfas.goodtime.R; import androidx.appcompat.app.AlertDialog; import androidx.preference.Preference; import androidx.preference.PreferenceViewHolder; import static android.graphics.Paint.UNDERLINE_TEXT_FLAG; import static android.text.InputType.TYPE_CLASS_NUMBER; import static android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL; /** * Preference based on android.preference.SeekBarPreference but uses support v7 preference as base. * The main difference is the fact that the seekbar value is updated while the user is tracking the touch. * It contains a title and a seekbar and an optional seekbar value TextView. The actual preference * layout is customizable by setting {@code android:layout} on the preference widget layout or * {@code CustomSeekStyle} attribute. * The seekbar within the preference can be defined adjustable or not by setting {@code * adjustable} attribute. If adjustable, the preference will be responsive to DPAD left/right keys. * Otherwise, it skips those keys. * The seekbar value view can be shown or disabled by setting {@code showSeekBarValue} attribute * to true or false, respectively. * Other SeekBar specific attributes (e.g. {@code title, summary, defaultValue, min, max}) can be * set directly on the preference widget layout. */ public class ProperSeekBarPreference extends Preference { private int mSeekBarValue; private int mMin; private int mMax; private int mSeekBarIncrement; private SeekBar mSeekBar; private TextView mSeekBarValueTextView; private boolean mAdjustable; // whether the seekbar should respond to the left/right keys private boolean mShowSeekBarValue; // whether to show the seekbar value TextView next to the bar private String mUnit; private String mDialogTitle; private static final String TAG = "ProperSeekBarPreference"; /** * Listener reacting to the SeekBar changing value by the user */ private OnSeekBarChangeListener mSeekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { syncValueInternal(seekBar); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; /** * Listener reacting to the user pressing DPAD left/right keys if {@code * adjustable} attribute is set to true; it transfers the key presses to the SeekBar * to be handled accordingly. */ private View.OnKeyListener mSeekBarKeyListener = new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } if (!mAdjustable && (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { // Right or left keys are pressed when in non-adjustable mode; Skip the keys. return false; } // We don't want to propagate the click keys down to the seekbar view since it will // create the ripple effect for the thumb. if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { return false; } if (mSeekBar == null) { Log.e(TAG, "SeekBar view is null and hence cannot be adjusted."); return false; } return mSeekBar.onKeyDown(keyCode, event); } }; public ProperSeekBarPreference( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.ProperSeekBarPreference, defStyleAttr, defStyleRes); /** * The ordering of these two statements are important. If we want to set max first, we need * to perform the same steps by changing min/max to max/min as following: * mMax = a.getInt(...) and setMin(...). */ mMin = a.getInt(R.styleable.ProperSeekBarPreference_min, 0); setMax(a.getInt(R.styleable.ProperSeekBarPreference_android_max, 100)); setSeekBarIncrement(a.getInt(R.styleable.ProperSeekBarPreference_seekBarIncrement, 0)); mAdjustable = a.getBoolean(R.styleable.ProperSeekBarPreference_adjustable, true); mShowSeekBarValue = a.getBoolean(R.styleable.ProperSeekBarPreference_showSeekBarValue, true); mUnit = a.getString(R.styleable.ProperSeekBarPreference_unitOfMeasurement); mDialogTitle = a.getString(R.styleable.ProperSeekBarPreference_dialogTitle); a.recycle(); } public ProperSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public ProperSeekBarPreference(Context context, AttributeSet attrs) { this(context, attrs, R.attr.seekBarPreferenceStyle); } public ProperSeekBarPreference(Context context) { this(context, null); } @Override public void onBindViewHolder(PreferenceViewHolder view) { super.onBindViewHolder(view); view.itemView.setOnKeyListener(mSeekBarKeyListener); mSeekBar = (SeekBar) view.findViewById(R.id.seekbar); float dpi = getContext().getResources().getDisplayMetrics().density; mSeekBar.setPadding(0,(int)(5 * dpi),(int)(16 * dpi),(int)(5 * dpi)); mSeekBarValueTextView = (TextView) view.findViewById(R.id.seekbar_value); mSeekBarValueTextView.setClickable(true); mSeekBarValueTextView.setPaintFlags(UNDERLINE_TEXT_FLAG); mSeekBarValueTextView.setTextSize(14); mSeekBarValueTextView.setTextColor(getContext().getResources().getColor(R.color.transparent_light)); mSeekBarValueTextView.setOnClickListener(view1 -> { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); LinearLayout layout = new LinearLayout(getContext()); final EditText input = new EditText(getContext()); input.setInputType(TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMAL); input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); input.setSingleLine(); layout.addView(input); layout.setPadding((int)(19*dpi), (int)(5*dpi), (int)(19*dpi), (int)(5*dpi)); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); builder.setTitle(mDialogTitle) .setView(layout); builder.setPositiveButton("OK", (di, i) -> { final String name = input.getText().toString(); if (!TextUtils.isEmpty(name)) { setValueInternal(Integer.parseInt(name), true); } }); builder.setNegativeButton("Cancel", (di, i) -> { }); AlertDialog dialog = builder.create(); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); }); if (mShowSeekBarValue) { mSeekBarValueTextView.setVisibility(View.VISIBLE); } else { mSeekBarValueTextView.setVisibility(View.GONE); mSeekBarValueTextView = null; } if (mSeekBar == null) { Log.e(TAG, "SeekBar view is null in onBindViewHolder."); return; } mSeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener); mSeekBar.setMax(mMax - mMin); // If the increment is not zero, use that. Otherwise, use the default mKeyProgressIncrement // in AbsSeekBar when it's zero. This default increment value is set by AbsSeekBar // after calling setMax. That's why it's important to call setKeyProgressIncrement after // calling setMax() since setMax() can change the increment value. if (mSeekBarIncrement != 0) { mSeekBar.setKeyProgressIncrement(mSeekBarIncrement); } else { mSeekBarIncrement = mSeekBar.getKeyProgressIncrement(); } mSeekBar.setProgress(mSeekBarValue - mMin); if (mSeekBarValueTextView != null) { mSeekBarValueTextView.setText(String.valueOf(mSeekBarValue) + mUnit); } mSeekBar.setEnabled(isEnabled()); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedInt(mSeekBarValue) : (Integer) defaultValue); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getInt(index, 0); } public void setMin(int min) { if (min > mMax) { min = mMax; } if (min != mMin) { mMin = min; notifyChanged(); } } public int getMin() { return mMin; } public final void setMax(int max) { if (max < mMin) { max = mMin; } if (max != mMax) { mMax = max; notifyChanged(); } } /** * Returns the amount of increment change via each arrow key click. This value is derived from * user's specified increment value if it's not zero. Otherwise, the default value is picked * from the default mKeyProgressIncrement value in {@link android.widget.AbsSeekBar}. * @return The amount of increment on the SeekBar performed after each user's arrow key press. */ public final int getSeekBarIncrement() { return mSeekBarIncrement; } /** * Sets the increment amount on the SeekBar for each arrow key press. * @param seekBarIncrement The amount to increment or decrement when the user presses an * arrow key. */ public final void setSeekBarIncrement(int seekBarIncrement) { if (seekBarIncrement != mSeekBarIncrement) { mSeekBarIncrement = Math.min(mMax - mMin, Math.abs(seekBarIncrement)); notifyChanged(); } } public int getMax() { return mMax; } public void setAdjustable(boolean adjustable) { mAdjustable = adjustable; } public boolean isAdjustable() { return mAdjustable; } public void setValue(int seekBarValue) { setValueInternal(seekBarValue, true); } private void setValueInternal(int seekBarValue, boolean notifyChanged) { if (seekBarValue < mMin) { seekBarValue = mMin; } if (seekBarValue > mMax) { seekBarValue = mMax; } if (seekBarValue != mSeekBarValue) { mSeekBarValue = seekBarValue; if (mSeekBarValueTextView != null) { mSeekBarValueTextView.setText(String.valueOf(mSeekBarValue) + mUnit); } persistInt(seekBarValue); if (notifyChanged) { notifyChanged(); } } } public int getValue() { return mSeekBarValue; } /** * Persist the seekBar's seekbar value if callChangeListener * returns true, otherwise set the seekBar's value to the stored value */ private void syncValueInternal(SeekBar seekBar) { int seekBarValue = mMin + seekBar.getProgress(); if (seekBarValue != mSeekBarValue) { if (callChangeListener(seekBarValue)) { setValueInternal(seekBarValue, false); } else { seekBar.setProgress(mSeekBarValue - mMin); } } } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { // No need to save instance state since it's persistent return superState; } // Save the instance state final SavedState myState = new SavedState(superState); myState.seekBarValue = mSeekBarValue; myState.min = mMin; myState.max = mMax; return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!state.getClass().equals(SavedState.class)) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); return; } // Restore the instance state SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); mSeekBarValue = myState.seekBarValue; mMin = myState.min; mMax = myState.max; notifyChanged(); } /** * SavedState, a subclass of {@link BaseSavedState}, will store the state * of MyPreference, a subclass of Preference. * <p> * It is important to always call through to super methods. */ private static class SavedState extends BaseSavedState { int seekBarValue; int min; int max; public SavedState(Parcel source) { super(source); // Restore the click counter seekBarValue = source.readInt(); min = source.readInt(); max = source.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); // Save the click counter dest.writeInt(seekBarValue); dest.writeInt(min); dest.writeInt(max); } public SavedState(Parcelable superState) { super(superState); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
fix possible crash
app/src/main/java/com/apps/adrcotfas/goodtime/Settings/ProperSeekBarPreference.java
fix possible crash
<ide><path>pp/src/main/java/com/apps/adrcotfas/goodtime/Settings/ProperSeekBarPreference.java <ide> import android.content.res.TypedArray; <ide> import android.os.Parcel; <ide> import android.os.Parcelable; <add>import android.text.InputFilter; <ide> import android.text.TextUtils; <ide> import android.util.AttributeSet; <ide> import android.util.Log; <ide> input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); <ide> input.setSingleLine(); <ide> <add> InputFilter[] FilterArray = new InputFilter[1]; <add> FilterArray[0] = new InputFilter.LengthFilter(3); <add> input.setFilters(FilterArray); <add> <ide> layout.addView(input); <ide> layout.setPadding((int)(19*dpi), (int)(5*dpi), (int)(19*dpi), (int)(5*dpi)); <ide> layout.setOrientation(LinearLayout.VERTICAL);
Java
lgpl-2.1
7069ae51f339c7c21539b43653a77d055374bbe8
0
schernolyas/hibernate-ogm,DavideD/hibernate-ogm-cassandra,tempbottle/hibernate-ogm,schernolyas/hibernate-ogm,ZJaffee/hibernate-ogm,gunnarmorling/hibernate-ogm,DavideD/hibernate-ogm,Sanne/hibernate-ogm,DavideD/hibernate-ogm-contrib,uugaa/hibernate-ogm,DavideD/hibernate-ogm,DavideD/hibernate-ogm,mp911de/hibernate-ogm,mp911de/hibernate-ogm,jhalliday/hibernate-ogm,hibernate/hibernate-ogm,jhalliday/hibernate-ogm,uugaa/hibernate-ogm,mp911de/hibernate-ogm,emmanuelbernard/hibernate-ogm,ZJaffee/hibernate-ogm,DavideD/hibernate-ogm-contrib,hibernate/hibernate-ogm,tempbottle/hibernate-ogm,Sanne/hibernate-ogm,hferentschik/hibernate-ogm,DavideD/hibernate-ogm-cassandra,DavideD/hibernate-ogm-contrib,Sanne/hibernate-ogm,uugaa/hibernate-ogm,hibernate/hibernate-ogm,gunnarmorling/hibernate-ogm,jhalliday/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm-cassandra,gunnarmorling/hibernate-ogm,tempbottle/hibernate-ogm,ZJaffee/hibernate-ogm,schernolyas/hibernate-ogm,Sanne/hibernate-ogm,DavideD/hibernate-ogm
/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2010-2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ogm.test.simpleentity; import static org.fest.assertions.Assertions.assertThat; import static org.hibernate.ogm.test.utils.TestHelper.assertNumberOfAssociations; import static org.hibernate.ogm.test.utils.TestHelper.assertNumberOfEntities; import static org.hibernate.ogm.test.utils.TestHelper.dropSchemaAndDatabase; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.annotations.common.util.StringHelper; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.ogm.cfg.OgmConfiguration; import org.hibernate.ogm.test.utils.GridDialectType; import org.hibernate.ogm.test.utils.SkipByGridDialect; import org.hibernate.ogm.test.utils.TestHelper; import org.hibernate.ogm.util.impl.Log; import org.hibernate.ogm.util.impl.LoggerFactory; import org.hibernate.search.FullTextSession; import org.hibernate.search.Search; import org.hibernate.search.SearchFactory; import org.hibernate.search.engine.spi.SearchFactoryImplementor; import org.hibernate.testing.FailureExpected; /** * A base class for all OGM tests. * * This class is a mix of SearchTestCase from HSearch 4 and OgmTestCase from the Core 3.6 days * It could get some love to clean this mess * * @author Emmanuel Bernard * @author Hardy Ferentschik */ public abstract class OgmTestCase extends TestCase { static { TestHelper.initializeHelpers(); } protected static Configuration cfg; private static Class<?> lastTestClass; private static final Log log = LoggerFactory.make(); protected SessionFactory sessions; private Session session; @Override @Before public void setUp() throws Exception { if ( cfg == null || lastTestClass != getClass() ) { buildConfiguration(); lastTestClass = getClass(); } // OGM-300: re-build session factory if it has been discarded by a previous test method if ( sessions == null ) { rebuildSessionFactory(); } } protected String[] getXmlFiles() { return new String[] {}; } protected static void setCfg(Configuration cfg) { OgmTestCase.cfg = cfg; } protected static Configuration getCfg() { return cfg; } protected void configure(Configuration cfg) { } @Override @After public void tearDown() throws Exception { handleUnclosedResources(); closeResources(); } protected abstract Class<?>[] getAnnotatedClasses(); protected boolean recreateSchema() { return true; } protected String[] getAnnotatedPackages() { return new String[] {}; } protected SearchFactoryImplementor getSearchFactoryImpl() { FullTextSession s = Search.getFullTextSession( openSession() ); s.close(); SearchFactory searchFactory = s.getSearchFactory(); return (SearchFactoryImplementor) searchFactory; } private void reportSkip(Skip skip) { reportSkip( skip.reason, skip.testDescription ); } protected void reportSkip(String reason, String testDescription) { StringBuilder builder = new StringBuilder(); builder.append( "*** skipping test [" ); builder.append( fullTestName() ); builder.append( "] - " ); builder.append( testDescription ); builder.append( " : " ); builder.append( reason ); log.warn( builder.toString() ); } protected Skip buildSkip(GridDialectType dialect, String comment) { StringBuilder buffer = new StringBuilder(); buffer.append( "skipping database-specific test [" ); buffer.append( fullTestName() ); buffer.append( "] for dialect [" ); buffer.append( dialect.name() ); buffer.append( ']' ); if ( StringHelper.isNotEmpty( comment ) ) { buffer.append( "; " ).append( comment ); } return new Skip( buffer.toString(), null ); } protected <T extends Annotation> T locateAnnotation(Class<T> annotationClass, Method runMethod) { T annotation = runMethod.getAnnotation( annotationClass ); if ( annotation == null ) { annotation = getClass().getAnnotation( annotationClass ); } if ( annotation == null ) { annotation = runMethod.getDeclaringClass().getAnnotation( annotationClass ); } return annotation; } protected final Skip determineSkipByGridDialect(Method runMethod) throws Exception { SkipByGridDialect skipForDialectAnn = locateAnnotation( SkipByGridDialect.class, runMethod ); if ( skipForDialectAnn != null ) { for ( GridDialectType gridDialectType : skipForDialectAnn.value() ) { if ( gridDialectType.equals( TestHelper.getCurrentDialectType() ) ) { return buildSkip( gridDialectType, skipForDialectAnn.comment() ); } } } return null; } protected static class Skip { private final String reason; private final String testDescription; public Skip(String reason, String testDescription) { this.reason = reason; this.testDescription = testDescription; } } @Override protected void runTest() throws Throwable { Method runMethod = findTestMethod(); FailureExpected failureExpected = locateAnnotation( FailureExpected.class, runMethod ); try { super.runTest(); if ( failureExpected != null ) { throw new FailureExpectedTestPassedException(); } } catch ( FailureExpectedTestPassedException t ) { closeResources(); throw t; } catch ( Throwable t ) { if ( t instanceof InvocationTargetException ) { t = ( (InvocationTargetException) t ).getTargetException(); } if ( t instanceof IllegalAccessException ) { t.fillInStackTrace(); } closeResources(); if ( failureExpected != null ) { StringBuilder builder = new StringBuilder(); if ( StringHelper.isNotEmpty( failureExpected.message() ) ) { builder.append( failureExpected.message() ); } else { builder.append( "ignoring @FailureExpected test" ); } builder.append( " (" ).append( failureExpected.jiraKey() ).append( ")" ); log.warn( builder.toString(), t ); } else { throw t; } } } @Override public void runBare() throws Throwable { Method runMethod = findTestMethod(); final Skip skip = determineSkipByGridDialect( runMethod ); if ( skip != null ) { reportSkip( skip ); return; } setUp(); try { runTest(); } finally { tearDown(); } } public String fullTestName() { return this.getClass().getName() + "#" + this.getName(); } private Method findTestMethod() { String fName = getName(); assertNotNull( fName ); Method runMethod = null; try { runMethod = getClass().getMethod( fName ); } catch ( NoSuchMethodException e ) { fail( "Method \"" + fName + "\" not found" ); } if ( !Modifier.isPublic( runMethod.getModifiers() ) ) { fail( "Method \"" + fName + "\" should be public" ); } return runMethod; } private static class FailureExpectedTestPassedException extends Exception { public FailureExpectedTestPassedException() { super( "Test marked as @FailureExpected, but did not fail!" ); } } public Session openSession() throws HibernateException { rebuildSessionFactory(); session = getSessions().openSession(); return session; } private void rebuildSessionFactory() { if ( sessions == null ) { try { buildConfiguration(); } catch ( Exception e ) { throw new HibernateException( e ); } } } protected void setSessions(SessionFactory sessions) { this.sessions = sessions; } protected SessionFactory getSessions() { return sessions; } protected SessionFactoryImplementor sfi() { return (SessionFactoryImplementor) getSessions(); } // FIXME clear cache when this happens protected void runSchemaGeneration() { } protected void runSchemaDrop() { dropSchemaAndDatabase( session ); } protected void buildConfiguration() throws Exception { closeSessionFactory(); try { setCfg( new OgmConfiguration() ); // Other configurations // by default use the new id generator scheme... cfg.setProperty( Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); for ( Map.Entry<String, String> entry : TestHelper.getEnvironmentProperties().entrySet() ) { cfg.setProperty( entry.getKey(), entry.getValue() ); } configure( cfg ); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "none" ); } for ( String aPackage : getAnnotatedPackages() ) { getCfg().addPackage( aPackage ); } for ( Class<?> aClass : getAnnotatedClasses() ) { getCfg().addAnnotatedClass( aClass ); } for ( String xmlFile : getXmlFiles() ) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ); getCfg().addInputStream( is ); } setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */) ); } catch ( Exception e ) { throw e; } } protected void handleUnclosedResources() { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } } session.close(); session = null; fail( "unclosed session" ); } else { session = null; } closeSessionFactory(); } private void closeSessionFactory() { if ( sessions != null ) { if ( !sessions.isClosed() ) { dropSchemaAndDatabase( sessions ); sessions.close(); sessions = null; } else { sessions = null; } } } protected void closeResources() { try { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } } session.close(); } } catch ( Exception ignore ) { } try { closeSessionFactory(); } catch ( Exception ignore ) { } } public void checkCleanCache() { assertThat( assertNumberOfEntities( 0, sessions ) ).as( "Entity cache should be empty" ).isTrue(); assertThat( assertNumberOfAssociations( 0, sessions ) ).as( "Association cache should be empty" ).isTrue(); } }
hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2010-2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ogm.test.simpleentity; import static org.fest.assertions.Assertions.assertThat; import static org.hibernate.ogm.test.utils.TestHelper.assertNumberOfAssociations; import static org.hibernate.ogm.test.utils.TestHelper.assertNumberOfEntities; import static org.hibernate.ogm.test.utils.TestHelper.dropSchemaAndDatabase; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.annotations.common.util.StringHelper; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.ogm.cfg.OgmConfiguration; import org.hibernate.ogm.test.utils.GridDialectType; import org.hibernate.ogm.test.utils.SkipByGridDialect; import org.hibernate.ogm.test.utils.TestHelper; import org.hibernate.ogm.util.impl.Log; import org.hibernate.ogm.util.impl.LoggerFactory; import org.hibernate.search.FullTextSession; import org.hibernate.search.Search; import org.hibernate.search.SearchFactory; import org.hibernate.search.engine.spi.SearchFactoryImplementor; import org.hibernate.testing.FailureExpected; /** * A base class for all OGM tests. * * This class is a mix of SearchTestCase from HSearch 4 and OgmTestCase from the Core 3.6 days * It could get some love to clean this mess * * @author Emmanuel Bernard * @author Hardy Ferentschik */ public abstract class OgmTestCase extends TestCase { static { TestHelper.initializeHelpers(); } protected static Configuration cfg; private static Class<?> lastTestClass; private static final Log log = LoggerFactory.make(); protected SessionFactory sessions; private Session session; @Before public void setUp() throws Exception { if ( cfg == null || lastTestClass != getClass() ) { buildConfiguration(); lastTestClass = getClass(); } } protected String[] getXmlFiles() { return new String[] {}; } protected static void setCfg(Configuration cfg) { OgmTestCase.cfg = cfg; } protected static Configuration getCfg() { return cfg; } protected void configure(Configuration cfg) { } @After public void tearDown() throws Exception { handleUnclosedResources(); closeResources(); } protected abstract Class<?>[] getAnnotatedClasses(); protected boolean recreateSchema() { return true; } protected String[] getAnnotatedPackages() { return new String[] {}; } protected SearchFactoryImplementor getSearchFactoryImpl() { FullTextSession s = Search.getFullTextSession( openSession() ); s.close(); SearchFactory searchFactory = s.getSearchFactory(); return (SearchFactoryImplementor) searchFactory; } private void reportSkip(Skip skip) { reportSkip( skip.reason, skip.testDescription ); } protected void reportSkip(String reason, String testDescription) { StringBuilder builder = new StringBuilder(); builder.append( "*** skipping test [" ); builder.append( fullTestName() ); builder.append( "] - " ); builder.append( testDescription ); builder.append( " : " ); builder.append( reason ); log.warn( builder.toString() ); } protected Skip buildSkip(GridDialectType dialect, String comment) { StringBuilder buffer = new StringBuilder(); buffer.append( "skipping database-specific test [" ); buffer.append( fullTestName() ); buffer.append( "] for dialect [" ); buffer.append( dialect.name() ); buffer.append( ']' ); if ( StringHelper.isNotEmpty( comment ) ) { buffer.append( "; " ).append( comment ); } return new Skip( buffer.toString(), null ); } protected <T extends Annotation> T locateAnnotation(Class<T> annotationClass, Method runMethod) { T annotation = runMethod.getAnnotation( annotationClass ); if ( annotation == null ) { annotation = getClass().getAnnotation( annotationClass ); } if ( annotation == null ) { annotation = runMethod.getDeclaringClass().getAnnotation( annotationClass ); } return annotation; } protected final Skip determineSkipByGridDialect(Method runMethod) throws Exception { SkipByGridDialect skipForDialectAnn = locateAnnotation( SkipByGridDialect.class, runMethod ); if ( skipForDialectAnn != null ) { for ( GridDialectType gridDialectType : skipForDialectAnn.value() ) { if ( gridDialectType.equals( TestHelper.getCurrentDialectType() ) ) { return buildSkip( gridDialectType, skipForDialectAnn.comment() ); } } } return null; } protected static class Skip { private final String reason; private final String testDescription; public Skip(String reason, String testDescription) { this.reason = reason; this.testDescription = testDescription; } } @Override protected void runTest() throws Throwable { Method runMethod = findTestMethod(); FailureExpected failureExpected = locateAnnotation( FailureExpected.class, runMethod ); try { super.runTest(); if ( failureExpected != null ) { throw new FailureExpectedTestPassedException(); } } catch ( FailureExpectedTestPassedException t ) { closeResources(); throw t; } catch ( Throwable t ) { if ( t instanceof InvocationTargetException ) { t = ( (InvocationTargetException) t ).getTargetException(); } if ( t instanceof IllegalAccessException ) { t.fillInStackTrace(); } closeResources(); if ( failureExpected != null ) { StringBuilder builder = new StringBuilder(); if ( StringHelper.isNotEmpty( failureExpected.message() ) ) { builder.append( failureExpected.message() ); } else { builder.append( "ignoring @FailureExpected test" ); } builder.append( " (" ).append( failureExpected.jiraKey() ).append( ")" ); log.warn( builder.toString(), t ); } else { throw t; } } } @Override public void runBare() throws Throwable { Method runMethod = findTestMethod(); final Skip skip = determineSkipByGridDialect( runMethod ); if ( skip != null ) { reportSkip( skip ); return; } setUp(); try { runTest(); } finally { tearDown(); } } public String fullTestName() { return this.getClass().getName() + "#" + this.getName(); } private Method findTestMethod() { String fName = getName(); assertNotNull( fName ); Method runMethod = null; try { runMethod = getClass().getMethod( fName ); } catch ( NoSuchMethodException e ) { fail( "Method \"" + fName + "\" not found" ); } if ( !Modifier.isPublic( runMethod.getModifiers() ) ) { fail( "Method \"" + fName + "\" should be public" ); } return runMethod; } private static class FailureExpectedTestPassedException extends Exception { public FailureExpectedTestPassedException() { super( "Test marked as @FailureExpected, but did not fail!" ); } } public Session openSession() throws HibernateException { rebuildSessionFactory(); session = getSessions().openSession(); return session; } private void rebuildSessionFactory() { if ( sessions == null ) { try { buildConfiguration(); } catch ( Exception e ) { throw new HibernateException( e ); } } } protected void setSessions(SessionFactory sessions) { this.sessions = sessions; } protected SessionFactory getSessions() { return sessions; } protected SessionFactoryImplementor sfi() { return (SessionFactoryImplementor) getSessions(); } // FIXME clear cache when this happens protected void runSchemaGeneration() { } protected void runSchemaDrop() { dropSchemaAndDatabase( session ); } protected void buildConfiguration() throws Exception { closeSessionFactory(); try { setCfg( new OgmConfiguration() ); // Other configurations // by default use the new id generator scheme... cfg.setProperty( Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); for ( Map.Entry<String, String> entry : TestHelper.getEnvironmentProperties().entrySet() ) { cfg.setProperty( entry.getKey(), entry.getValue() ); } configure( cfg ); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "none" ); } for ( String aPackage : getAnnotatedPackages() ) { getCfg().addPackage( aPackage ); } for ( Class<?> aClass : getAnnotatedClasses() ) { getCfg().addAnnotatedClass( aClass ); } for ( String xmlFile : getXmlFiles() ) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ); getCfg().addInputStream( is ); } setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */) ); } catch ( Exception e ) { e.printStackTrace(); throw e; } } protected void handleUnclosedResources() { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } } session.close(); session = null; fail( "unclosed session" ); } else { session = null; } closeSessionFactory(); } private void closeSessionFactory() { if ( sessions != null ) { if ( !sessions.isClosed() ) { dropSchemaAndDatabase( sessions ); sessions.close(); sessions = null; } else { sessions = null; } } } protected void closeResources() { try { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { if ( session.getTransaction().isActive() ) { session.getTransaction().rollback(); } } session.close(); } } catch ( Exception ignore ) { } try { closeSessionFactory(); } catch ( Exception ignore ) { } } public void checkCleanCache() { assertThat( assertNumberOfEntities( 0, sessions ) ).as( "Entity cache should be empty" ).isTrue(); assertThat( assertNumberOfAssociations( 0, sessions ) ).as( "Association cache should be empty" ).isTrue(); } }
OGM-300 Re-creating session factory in OgmTestCase if it has been disposed in earlier tests
hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java
OGM-300 Re-creating session factory in OgmTestCase if it has been disposed in earlier tests
<ide><path>ibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java <ide> protected SessionFactory sessions; <ide> private Session session; <ide> <add> @Override <ide> @Before <ide> public void setUp() throws Exception { <ide> if ( cfg == null || lastTestClass != getClass() ) { <ide> buildConfiguration(); <ide> lastTestClass = getClass(); <ide> } <add> <add> // OGM-300: re-build session factory if it has been discarded by a previous test method <add> if ( sessions == null ) { <add> rebuildSessionFactory(); <add> } <ide> } <ide> <ide> protected String[] getXmlFiles() { <ide> protected void configure(Configuration cfg) { <ide> } <ide> <add> @Override <ide> @After <ide> public void tearDown() throws Exception { <ide> handleUnclosedResources(); <ide> setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */) ); <ide> } <ide> catch ( Exception e ) { <del> e.printStackTrace(); <ide> throw e; <ide> } <ide> }
Java
mit
ce16d943ca42a760a1e306994d0645bec9d4fd82
0
phenoscape/Phenex,phenoscape/Phenex
package org.phenoscape.bridge; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.net.URL; import java.util.HashSet; import java.util.Set; import org.obd.model.CompositionalDescription; import org.obd.model.Graph; import org.obd.model.LinkStatement; import org.obd.model.Node; import org.obd.model.CompositionalDescription.Predicate; import org.obd.model.Node.Metatype; import org.obd.query.Shard; import org.obd.query.impl.AbstractSQLShard; import org.obd.query.impl.OBDSQLShard; import org.purl.obo.vocab.RelationVocabulary; public class ZfinObdBridge { protected Graph graph; public static String GENOTYPE_PHENOTYPE_REL_ID = "PHENOSCAPE:exhibits"; public static String GENE_GENOTYPE_REL_ID = "PHENOSCAPE:has_allele"; public static String PUBLICATION_TYPE_ID = "cdao:Pub"; public static String HAS_PUB_REL_ID = "cdao:hasPub"; public static String GENOTYPE_TYPE_ID = "SO:0001027"; public static String GENE_TYPE_ID = "SO:0000704"; Set<String> geneSet = new HashSet<String>(); Set<String> genotypeSet = new HashSet<String>(); Set<String> pubSet = new HashSet<String>(); private static RelationVocabulary relationVocabulary = new RelationVocabulary(); public ZfinObdBridge() { super(); graph = new Graph(); } public void loadZfinData(Shard obdsql) { try { File connParamFile = new File("testfiles/zfinLocations"); BufferedReader br = new BufferedReader( new FileReader(connParamFile)); URL phenotypeURL = null, genotypeURL = null, missingMarkersURL = null; String param, phenoFileLine, genoFileLine, missingMarkersFileLine; LinkStatement genotypeAnnotLink = new LinkStatement(); LinkStatement geneAnnotLink = new LinkStatement(); while ((param = br.readLine()) != null) { if (param.contains("pheno")) phenotypeURL = new URL(param); else if(param.contains("missing_markers")) missingMarkersURL = new URL(param); else{ genotypeURL = new URL(param); } } if (phenotypeURL != null) { BufferedReader br1 = new BufferedReader(new InputStreamReader( phenotypeURL.openStream())); while ((phenoFileLine = br1.readLine()) != null) { String[] pComps = phenoFileLine.split("\\t"); String pub = pComps[8]; String qualID = pComps[5]; String entity1ID = pComps[4]; String genotypeId = pComps[0]; String genotypeName = pComps[1]; Node genotypeNode = createInstanceNode(genotypeId, GENOTYPE_TYPE_ID); genotypeNode.setLabel(genotypeName); graph.addNode(genotypeNode); Node publicationNode = createInstanceNode(pub, PUBLICATION_TYPE_ID); graph.addNode(publicationNode); if (entity1ID != null && entity1ID.trim().length() > 0) { // Collection<Statement> stmts = obdsql // .getStatementsForTarget(entity1ID); // Iterator<Statement> it = stmts.iterator(); // if (it.hasNext()) { // while (it.hasNext()) { // Statement stmt = it.next(); // if (stmt.getRelationId().contains("DbXref")) { // String equivEntityID = stmt.getNodeId(); // e1 = new OBOClassImpl(equivEntityID); // } // } // } if (qualID != null && qualID.trim().length() > 0) { CompositionalDescription cd = new CompositionalDescription( Predicate.INTERSECTION); cd.addArgument(qualID); cd.addArgument(relationVocabulary.inheres_in(), entity1ID); genotypeAnnotLink.setNodeId(genotypeId); genotypeAnnotLink .setRelationId(GENOTYPE_PHENOTYPE_REL_ID); genotypeAnnotLink.setTargetId(cd.toString()); // genotypeAnnotLink.addSubLinkStatement( // HAS_PUB_REL_ID, pub); // System.err.println("Adding genotype statement " //+ genotypeAnnotLink.toString()); graph.addLinkStatement(genotypeNode, GENOTYPE_PHENOTYPE_REL_ID, cd.toString()); } } } } else { System.err.println("Uninitialized URL for phenotypic data"); } if (genotypeURL != null && missingMarkersURL != null) { BufferedReader br2 = new BufferedReader(new InputStreamReader( genotypeURL.openStream())); BufferedReader br3 = new BufferedReader(new InputStreamReader(missingMarkersURL.openStream())); while ((genoFileLine = br2.readLine()) != null) { String geneID = ""; String[] gComps = genoFileLine.split("\\t"); String genotypeID = normalizetoZfin(gComps[0]); if(gComps.length > 9){ geneID = normalizetoZfin(gComps[9]); } if (geneID != null && geneID.trim().length() > 0) { Node geneNode = createInstanceNode(geneID, GENE_TYPE_ID); graph.addNode(geneNode); geneSet.add(geneID); geneAnnotLink.setNodeId(geneID); geneAnnotLink.setRelationId(GENE_GENOTYPE_REL_ID); geneAnnotLink.setTargetId(genotypeID); // System.err.println("Adding gene statement " + // geneAnnotLink); graph.addLinkStatement(geneNode, GENE_GENOTYPE_REL_ID, genotypeID); } else{ while((missingMarkersFileLine = br3.readLine()) != null){ String[] mmComps = missingMarkersFileLine.split("\\t"); if(mmComps[0].equals(gComps[0])){ if(mmComps[4] != null && mmComps[4].trim().length() > 0){ geneID = normalizetoZfin(mmComps[4]); Node geneNode = createInstanceNode(geneID, GENE_TYPE_ID); graph.addNode(geneNode); geneSet.add(geneID); geneAnnotLink.setNodeId(geneID); geneAnnotLink.setRelationId(GENE_GENOTYPE_REL_ID); geneAnnotLink.setTargetId(genotypeID); graph.addLinkStatement(geneNode, GENE_GENOTYPE_REL_ID, genotypeID); } } } } } } else { System.err.println("Uninitialized URL for genotypic data"); } } catch (Exception e) { e.printStackTrace(); } //int j = 0; //for(LiteralStatement s : graph.getLiteralStatements()){ // System.out.println(++j + ". " + s.getTargetId()); //} obdsql.putGraph(graph); } /** * Another helper method to deal with the prefix inconsistencies in ZFIN * Gene to Genotype files lack the ZFIN prefix * Genotype to Phenotype files have the prefix * @param string * @return */ private String normalizetoZfin(String string) { return "ZFIN:" + string; } protected Node createInstanceNode(String id, String typeId) { Node n = new Node(id); n.setMetatype(Metatype.CLASS); n.addStatement(new LinkStatement(id, relationVocabulary.instance_of(), typeId)); graph.addNode(n); return n; } public static void main(String[] args) { File connParamFile = new File("testfiles/connectionParameters"); try { BufferedReader br = new BufferedReader( new FileReader(connParamFile)); String[] connParams = new String[3]; String param; int j = 0; while ((param = br.readLine()) != null) { connParams[j++] = param; } Shard obdsql = new OBDSQLShard(); ((AbstractSQLShard) obdsql).connect(connParams[0], connParams[1], connParams[2]); ZfinObdBridge zob = new ZfinObdBridge(); zob.loadZfinData(obdsql); } catch (Exception e) { e.printStackTrace(); } } }
src/org/phenoscape/bridge/ZfinObdBridge.java
package org.phenoscape.bridge; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.net.URL; import java.util.HashSet; import java.util.Set; import org.obd.model.CompositionalDescription; import org.obd.model.Graph; import org.obd.model.LinkStatement; import org.obd.model.LiteralStatement; import org.obd.model.Node; import org.obd.model.CompositionalDescription.Predicate; import org.obd.model.Node.Metatype; import org.obd.query.Shard; import org.obd.query.impl.AbstractSQLShard; import org.obd.query.impl.OBDSQLShard; import org.purl.obo.vocab.RelationVocabulary; public class ZfinObdBridge { protected Graph graph; public static String GENOTYPE_PHENOTYPE_REL_ID = "PHENOSCAPE:exhibits"; public static String GENE_GENOTYPE_REL_ID = "PHENOSCAPE:has_allele"; public static String PUBLICATION_TYPE_ID = "cdao:Pub"; public static String HAS_PUB_REL_ID = "cdao:hasPub"; public static String GENOTYPE_TYPE_ID = "SO:0001027"; public static String GENE_TYPE_ID = "SO:0000704"; Set<String> geneSet = new HashSet<String>(); Set<String> genotypeSet = new HashSet<String>(); Set<String> pubSet = new HashSet<String>(); private static RelationVocabulary relationVocabulary = new RelationVocabulary(); public ZfinObdBridge() { super(); graph = new Graph(); } public void loadZfinData(Shard obdsql) { try { File connParamFile = new File("testfiles/zfinLocations"); BufferedReader br = new BufferedReader( new FileReader(connParamFile)); URL phenotypeURL = null, genotypeURL = null, missingMarkersURL = null; String param, phenoFileLine, genoFileLine, missingMarkersFileLine; LinkStatement genotypeAnnotLink = new LinkStatement(); LinkStatement geneAnnotLink = new LinkStatement(); while ((param = br.readLine()) != null) { if (param.contains("pheno")) phenotypeURL = new URL(param); else if(param.contains("missing_markers")) missingMarkersURL = new URL(param); else{ genotypeURL = new URL(param); } } if (phenotypeURL != null) { BufferedReader br1 = new BufferedReader(new InputStreamReader( phenotypeURL.openStream())); while ((phenoFileLine = br1.readLine()) != null) { String[] pComps = phenoFileLine.split("\\t"); String pub = pComps[8]; String qualID = pComps[5]; String entity1ID = pComps[4]; String genotypeId = pComps[0]; String genotypeName = pComps[1]; Node genotypeNode = createInstanceNode(genotypeId, GENOTYPE_TYPE_ID); genotypeNode.setLabel(genotypeName); graph.addNode(genotypeNode); Node publicationNode = createInstanceNode(pub, PUBLICATION_TYPE_ID); graph.addNode(publicationNode); if (entity1ID != null && entity1ID.trim().length() > 0) { // Collection<Statement> stmts = obdsql // .getStatementsForTarget(entity1ID); // Iterator<Statement> it = stmts.iterator(); // if (it.hasNext()) { // while (it.hasNext()) { // Statement stmt = it.next(); // if (stmt.getRelationId().contains("DbXref")) { // String equivEntityID = stmt.getNodeId(); // e1 = new OBOClassImpl(equivEntityID); // } // } // } if (qualID != null && qualID.trim().length() > 0) { CompositionalDescription cd = new CompositionalDescription( Predicate.INTERSECTION); cd.addArgument(qualID); cd.addArgument(relationVocabulary.inheres_in(), entity1ID); genotypeAnnotLink.setNodeId(genotypeId); genotypeAnnotLink .setRelationId(GENOTYPE_PHENOTYPE_REL_ID); genotypeAnnotLink.setTargetId(cd.toString()); // genotypeAnnotLink.addSubLinkStatement( // HAS_PUB_REL_ID, pub); // System.err.println("Adding genotype statement " //+ genotypeAnnotLink.toString()); graph.addLinkStatement(genotypeNode, GENOTYPE_PHENOTYPE_REL_ID, cd.toString()); } } } } else { System.err.println("Uninitialized URL for phenotypic data"); } if (genotypeURL != null && missingMarkersURL != null) { BufferedReader br2 = new BufferedReader(new InputStreamReader( genotypeURL.openStream())); BufferedReader br3 = new BufferedReader(new InputStreamReader(missingMarkersURL.openStream())); while ((genoFileLine = br2.readLine()) != null) { String geneID = ""; String[] gComps = genoFileLine.split("\\t"); String genotypeID = gComps[0]; if(gComps.length > 9){ geneID = gComps[9]; } if (geneID != null && geneID.trim().length() > 0) { Node geneNode = createInstanceNode(geneID, GENE_TYPE_ID); graph.addNode(geneNode); geneSet.add(geneID); geneAnnotLink.setNodeId(geneID); geneAnnotLink.setRelationId(GENE_GENOTYPE_REL_ID); geneAnnotLink.setTargetId(genotypeID); // System.err.println("Adding gene statement " + // geneAnnotLink); graph.addLinkStatement(geneNode, GENE_GENOTYPE_REL_ID, genotypeID); } else{ while((missingMarkersFileLine = br3.readLine()) != null){ String[] mmComps = missingMarkersFileLine.split("\\t"); if(mmComps[0].equals(genotypeID)){ if(mmComps[4] != null && mmComps[4].trim().length() > 0){ Node geneNode = createInstanceNode(mmComps[4], GENE_TYPE_ID); graph.addNode(geneNode); geneSet.add(mmComps[4]); geneAnnotLink.setNodeId(geneID); geneAnnotLink.setRelationId(GENE_GENOTYPE_REL_ID); geneAnnotLink.setTargetId(genotypeID); graph.addLinkStatement(geneNode, GENE_GENOTYPE_REL_ID, genotypeID); } } } } } } else { System.err.println("Uninitialized URL for genotypic data"); } } catch (Exception e) { e.printStackTrace(); } //int j = 0; //for(LiteralStatement s : graph.getLiteralStatements()){ // System.out.println(++j + ". " + s.getTargetId()); //} obdsql.putGraph(graph); } protected Node createInstanceNode(String id, String typeId) { Node n = new Node(id); n.setMetatype(Metatype.CLASS); n.addStatement(new LinkStatement(id, relationVocabulary.instance_of(), typeId)); graph.addNode(n); return n; } public static void main(String[] args) { File connParamFile = new File("testfiles/connectionParameters"); try { BufferedReader br = new BufferedReader( new FileReader(connParamFile)); String[] connParams = new String[3]; String param; int j = 0; while ((param = br.readLine()) != null) { connParams[j++] = param; } Shard obdsql = new OBDSQLShard(); ((AbstractSQLShard) obdsql).connect(connParams[0], connParams[1], connParams[2]); ZfinObdBridge zob = new ZfinObdBridge(); zob.loadZfinData(obdsql); } catch (Exception e) { e.printStackTrace(); } } }
Added a new method to normalize all ZFIN identifiers so the ZFIN: prefix is always present
src/org/phenoscape/bridge/ZfinObdBridge.java
Added a new method to normalize all ZFIN identifiers so the ZFIN: prefix is always present
<ide><path>rc/org/phenoscape/bridge/ZfinObdBridge.java <ide> import org.obd.model.CompositionalDescription; <ide> import org.obd.model.Graph; <ide> import org.obd.model.LinkStatement; <del>import org.obd.model.LiteralStatement; <ide> import org.obd.model.Node; <ide> import org.obd.model.CompositionalDescription.Predicate; <ide> import org.obd.model.Node.Metatype; <ide> while ((genoFileLine = br2.readLine()) != null) { <ide> String geneID = ""; <ide> String[] gComps = genoFileLine.split("\\t"); <del> String genotypeID = gComps[0]; <add> String genotypeID = normalizetoZfin(gComps[0]); <ide> if(gComps.length > 9){ <del> geneID = gComps[9]; <add> geneID = normalizetoZfin(gComps[9]); <ide> } <ide> <ide> if (geneID != null && geneID.trim().length() > 0) { <ide> else{ <ide> while((missingMarkersFileLine = br3.readLine()) != null){ <ide> String[] mmComps = missingMarkersFileLine.split("\\t"); <del> if(mmComps[0].equals(genotypeID)){ <add> if(mmComps[0].equals(gComps[0])){ <ide> if(mmComps[4] != null && mmComps[4].trim().length() > 0){ <del> Node geneNode = createInstanceNode(mmComps[4], GENE_TYPE_ID); <add> geneID = normalizetoZfin(mmComps[4]); <add> Node geneNode = createInstanceNode(geneID, GENE_TYPE_ID); <ide> graph.addNode(geneNode); <del> geneSet.add(mmComps[4]); <add> geneSet.add(geneID); <ide> geneAnnotLink.setNodeId(geneID); <ide> geneAnnotLink.setRelationId(GENE_GENOTYPE_REL_ID); <ide> geneAnnotLink.setTargetId(genotypeID); <ide> // System.out.println(++j + ". " + s.getTargetId()); <ide> //} <ide> obdsql.putGraph(graph); <add> } <add> <add> /** <add> * Another helper method to deal with the prefix inconsistencies in ZFIN <add> * Gene to Genotype files lack the ZFIN prefix <add> * Genotype to Phenotype files have the prefix <add> * @param string <add> * @return <add> */ <add> private String normalizetoZfin(String string) { <add> return "ZFIN:" + string; <ide> } <ide> <ide> protected Node createInstanceNode(String id, String typeId) {
Java
apache-2.0
b7e8352ea46720da6d835f484de8f0d0efae7311
0
apache/jackrabbit-oak,amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak
/* * 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.jackrabbit.oak.security.user; import java.security.Principal; import java.text.ParseException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.query.Query; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.jackrabbit.commons.iterator.RangeIteratorAdapter; import org.apache.jackrabbit.oak.api.ContentSession; import org.apache.jackrabbit.oak.api.CoreValue; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Result; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.SessionQueryEngine; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager; import org.apache.jackrabbit.oak.spi.security.principal.TreeBasedPrincipal; import org.apache.jackrabbit.oak.spi.security.user.MembershipProvider; import org.apache.jackrabbit.oak.spi.security.user.UserConstants; import org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig; import org.apache.jackrabbit.oak.spi.security.user.UserProvider; import org.apache.jackrabbit.oak.util.NodeUtil; import org.apache.jackrabbit.util.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * User provider implementation and manager for group memberships with the * following characteristics: * * <h1>UserProvider</h1> * * <h2>User and Group Creation</h2> * This implementation creates the JCR nodes corresponding the a given * authorizable ID with the following behavior: * <ul> * <li>Users are created below /rep:security/rep:authorizables/rep:users or * the path configured in the {@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_USER_PATH} * respectively.</li> * <li>Groups are created below /rep:security/rep:authorizables/rep:groups or * the path configured in the {@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_GROUP_PATH} * respectively.</li> * <li>Below each category authorizables are created within a human readable * structure based on the defined intermediate path or some internal logic * with a depth defined by the {@code defaultDepth} config option.<br> * E.g. creating a user node for an ID 'aSmith' would result in the following * structure assuming defaultDepth == 2 is used: * <pre> * + rep:security [rep:AuthorizableFolder] * + rep:authorizables [rep:AuthorizableFolder] * + rep:users [rep:AuthorizableFolder] * + a [rep:AuthorizableFolder] * + aS [rep:AuthorizableFolder] * -> + aSmith [rep:User] * </pre> * </li> * <li>The node name is calculated from the specified authorizable ID * {@link org.apache.jackrabbit.util.Text#escapeIllegalJcrChars(String) escaping} any illegal JCR chars.</li> * <li>If no intermediate path is passed the names of the intermediate * folders are calculated from the leading chars of the escaped node name.</li> * <li>If the escaped node name is shorter than the {@code defaultDepth} * the last char is repeated.<br> * E.g. creating a user node for an ID 'a' would result in the following * structure assuming defaultDepth == 2 is used: * <pre> * + rep:security [rep:AuthorizableFolder] * + rep:authorizables [rep:AuthorizableFolder] * + rep:users [rep:AuthorizableFolder] * + a [rep:AuthorizableFolder] * + aa [rep:AuthorizableFolder] * -> + a [rep:User] * </pre></li> * * <h3>Conflicts</h3> * * <ul> * <li>If the authorizable node to be created would collide with an existing * folder the conflict is resolved by using the colling folder as target.</li> * <li>The current implementation asserts that authorizable nodes are always * created underneath an node of type {@code rep:AuthorizableFolder}. If this * condition is violated a {@code ConstraintViolationException} is thrown.</li> * <li>If the specified intermediate path results in an authorizable node * being located outside of the configured content structure a * {@code ConstraintViolationException} is thrown.</li> * </ul> * * <h3>Configuration Options</h3> * <ul> * <li>{@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_USER_PATH}: Underneath this structure * all user nodes are created. Default value is * "/rep:security/rep:authorizables/rep:users"</li> * <li>{@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_GROUP_PATH}: Underneath this structure * all group nodes are created. Default value is * "/rep:security/rep:authorizables/rep:groups"</li> * <li>{@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_DEFAULT_DEPTH}: A positive {@code integer} * greater than zero defining the depth of the default structure that is * always created. Default value: 2</li> * </ul> * * <h3>Compatibility with Jackrabbit 2.x</h3> * * Due to the fact that this JCR implementation is expected to deal with huge amount * of child nodes the following configuration options are no longer supported: * <ul> * <li>autoExpandTree</li> * <li>autoExpandSize</li> * </ul> * * <h2>User and Group Access</h2> * <h3>By ID</h3> * TODO * <h3>By Path</h3> * TODO * <h3>By Principal Name</h3> * TODO * * <h1>MembershipProvider</h1> * * TODO */ public class UserProviderImpl implements UserProvider, MembershipProvider, UserConstants { /** * logger instance */ private static final Logger log = LoggerFactory.getLogger(UserProviderImpl.class); private static final String DELIMITER = "/"; private static final int DEFAULT_DEPTH = 2; private final ContentSession contentSession; private final Root root; private final IdentifierManager identifierManager; private final int defaultDepth; private final int splitSize; private final String adminId; private final String groupPath; private final String userPath; public UserProviderImpl(ContentSession contentSession, Root root, UserManagerConfig config) { this.contentSession = contentSession; this.root = root; this.identifierManager = new IdentifierManager(contentSession, root); defaultDepth = config.getConfigValue(UserManagerConfig.PARAM_DEFAULT_DEPTH, DEFAULT_DEPTH); int splitValue = config.getConfigValue(UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE, 4); if (splitValue < 4) { log.warn("Invalid value {} for {}. Expected integer >= 4", splitValue, UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE); splitValue = 0; } this.splitSize = splitValue; this.adminId = config.getAdminId(); groupPath = config.getConfigValue(UserManagerConfig.PARAM_GROUP_PATH, DEFAULT_GROUP_PATH); userPath = config.getConfigValue(UserManagerConfig.PARAM_USER_PATH, DEFAULT_USER_PATH); } //-------------------------------------------------------< UserProvider >--- @Override public Tree createUser(String userID, String intermediateJcrPath) throws RepositoryException { return createAuthorizableNode(userID, false, intermediateJcrPath); } @Override public Tree createGroup(String groupID, String intermediateJcrPath) throws RepositoryException { return createAuthorizableNode(groupID, true, intermediateJcrPath); } @Override public Tree getAuthorizable(String authorizableId) { Tree tree = identifierManager.getTree(getContentID(authorizableId)); if (isAuthorizableTree(tree, UserManager.SEARCH_TYPE_AUTHORIZABLE)) { return tree; } else { return null; } } @Override public Tree getAuthorizable(String authorizableId, int authorizableType) { Tree tree = identifierManager.getTree(getContentID(authorizableId)); if (isAuthorizableTree(tree, authorizableType)) { return tree; } else { return null; } } @Override() public Tree getAuthorizableByPath(String authorizableOakPath) { Tree tree = root.getTree(authorizableOakPath); if (isAuthorizableTree(tree, UserManager.SEARCH_TYPE_AUTHORIZABLE)) { return tree; } else { return null; } } @Override public Tree getAuthorizableByPrincipal(Principal principal) { Tree authorizableTree = null; if (principal instanceof TreeBasedPrincipal) { authorizableTree = root.getTree(((TreeBasedPrincipal) principal).getOakPath()); } else { // NOTE: in contrast to JR2 the extra shortcut for ID==principalName // can be omitted as principals names are stored in user defined // index as well. SessionQueryEngine queryEngine = contentSession.getQueryEngine(); try { CoreValue bindValue = contentSession.getCoreValueFactory().createValue(principal.getName()); Map<String, CoreValue> bindings = Collections.singletonMap("principalName", bindValue); String stmt = "SELECT * FROM [rep:Authorizable] WHERE [rep:principalName] = $principalName"; Result result = contentSession.getQueryEngine().executeQuery(stmt, Query.JCR_SQL2, 1, 0, Collections.singletonMap("principalName", bindValue), new NamePathMapper.Default()); Iterator rows = result.getRows().iterator(); if (rows.hasNext()) { String path = rows.next().toString(); authorizableTree = root.getTree(path); } } catch (ParseException ex) { log.error("query failed", ex); } } return authorizableTree; } @Override public String getAuthorizableId(Tree authorizableTree) { assert authorizableTree != null; PropertyState idProp = authorizableTree.getProperty(UserConstants.REP_AUTHORIZABLE_ID); if (idProp != null) { return idProp.getValue().getString(); } else { return Text.unescapeIllegalJcrChars(authorizableTree.getName()); } } @Override public boolean isAdminUser(Tree userTree) { assert userTree != null; return isAuthorizableTree(userTree, UserManager.SEARCH_TYPE_USER) && adminId.equals(getAuthorizableId(userTree)); } //--------------------------------------------------< MembershipProvider>--- @Override public Iterator<String> getMembership(String authorizableId, boolean includeInherited) { return getMembership(getAuthorizable(authorizableId), includeInherited); } @Override public Iterator<String> getMembership(Tree authorizableTree, boolean includeInherited) { Set<String> groupPaths = new HashSet<String>(); Set<String> refPaths = identifierManager.getWeakReferences(authorizableTree, null, NT_REP_GROUP, NT_REP_MEMBERS); for (String propPath : refPaths) { int index = propPath.indexOf('/'+REP_MEMBERS); if (index > 0) { groupPaths.add(propPath.substring(0, index)); } else { log.debug("Not a membership reference property " + propPath); } } Iterator<String> it = groupPaths.iterator(); if (includeInherited && it.hasNext()) { return getAllMembership(groupPaths.iterator()); } else { return new RangeIteratorAdapter(it, groupPaths.size()); } } @Override public Iterator<String> getMembers(String groupId, int authorizableType, boolean includeInherited) { return getMembers(getAuthorizable(groupId), UserManager.SEARCH_TYPE_AUTHORIZABLE, includeInherited); } @Override public Iterator<String> getMembers(Tree groupTree, int authorizableType, boolean includeInherited) { Iterable memberPaths = Collections.emptySet(); if (useMemberNode(groupTree)) { Tree membersTree = groupTree.getChild(REP_MEMBERS); if (membersTree != null) { // FIXME: replace usage of PropertySequence (oak-api not possible there) // PropertySequence propertySequence = getPropertySequence(membersTree); // iterator = new AuthorizableIterator(propertySequence, authorizableType, userManager); } } else { PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { List<CoreValue> vs = property.getValues(); memberPaths = Iterables.transform(vs, new Function<CoreValue,String>() { @Override public String apply(@Nullable CoreValue value) { return identifierManager.getPath(value); } }); } } Iterator it = memberPaths.iterator(); if (includeInherited && it.hasNext()) { return getAllMembers(it, authorizableType); } else { return new RangeIteratorAdapter(it, Iterables.size(memberPaths)); } } @Override public boolean isMember(Tree groupTree, Tree authorizableTree, boolean includeInherited) { if (includeInherited) { Iterator<String> groupPaths = getMembership(authorizableTree, true); String path = groupTree.getPath(); while (groupPaths.hasNext()) { if (path.equals(groupPaths.next())) { return true; } } } else { if (useMemberNode(groupTree)) { Tree membersTree = groupTree.getChild(REP_MEMBERS); if (membersTree != null) { // FIXME: fix.. testing for property name isn't correct. // FIXME: usage of PropertySequence isn't possible when operating on oak-API // PropertySequence propertySequence = getPropertySequence(membersTree); // return propertySequence.hasItem(authorizable.getID()); return false; } } else { PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { List<CoreValue> members = property.getValues(); String authorizableUUID = getContentID(authorizableTree); for (CoreValue v : members) { if (authorizableUUID.equals(v.getString())) { return true; } } } } } // no a member of the specified group return false; } @Override public boolean addMember(Tree groupTree, Tree newMemberTree) { if (useMemberNode(groupTree)) { NodeUtil groupNode = new NodeUtil(groupTree, contentSession); NodeUtil membersNode = groupNode.getOrAddChild(REP_MEMBERS, NT_REP_MEMBERS); //FIXME: replace usage of PropertySequence with oak-compatible utility // PropertySequence properties = getPropertySequence(membersTree); // String propName = Text.escapeIllegalJcrChars(authorizable.getID()); // if (properties.hasItem(propName)) { // log.debug("Authorizable {} is already member of {}", authorizable, this); // return false; // } else { // CoreValue newMember = createCoreValue(authorizable); // properties.addProperty(propName, newMember); // } } else { List<CoreValue> values; CoreValue toAdd = createCoreValue(newMemberTree); PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { values = property.getValues(); if (values.contains(toAdd)) { return false; } else { values.add(toAdd); } } else { values = Collections.singletonList(toAdd); } groupTree.setProperty(REP_MEMBERS, values); } return true; } @Override public boolean removeMember(Tree groupTree, Tree memberTree) { if (useMemberNode(groupTree)) { Tree membersTree = groupTree.getChild(REP_MEMBERS); if (membersTree != null) { // FIXME: replace usage of PropertySequence with oak-compatible utility // PropertySequence properties = getPropertySequence(membersTree); // String propName = authorizable.getTree().getName(); // FIXME: fix.. testing for property name isn't correct. // if (properties.hasItem(propName)) { // Property p = properties.getItem(propName); // userManager.removeInternalProperty(p.getParent(), propName); // } // return true; return false; } } else { PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { CoreValue toRemove = createCoreValue(memberTree); List<CoreValue> values = property.getValues(); if (values.remove(toRemove)) { if (values.isEmpty()) { groupTree.removeProperty(REP_MEMBERS); } else { groupTree.setProperty(REP_MEMBERS, values); } return true; } } } // nothing changed log.debug("Authorizable {} was not member of {}", memberTree.getName(), groupTree.getName()); return false; } //------------------------------------------------------------< private >--- private String getContentID(String authorizableId) { return IdentifierManager.generateUUID(authorizableId.toLowerCase()); } private String getContentID(Tree authorizableTree) { return identifierManager.getIdentifier(authorizableTree); } private boolean isAuthorizableTree(Tree tree, int type) { // FIXME: check for node type according to the specified type constraint if (tree != null && tree.hasProperty(JcrConstants.JCR_PRIMARYTYPE)) { String ntName = tree.getProperty(JcrConstants.JCR_PRIMARYTYPE).getValue().getString(); switch (type) { case UserManager.SEARCH_TYPE_GROUP: return NT_REP_GROUP.equals(ntName); case UserManager.SEARCH_TYPE_USER: return NT_REP_USER.equals(ntName); default: return NT_REP_USER.equals(ntName) || NT_REP_GROUP.equals(ntName); } } return false; } //-----------------------------------------------< private UserProvider >--- private Tree createAuthorizableNode(String authorizableId, boolean isGroup, String intermediatePath) throws RepositoryException { String nodeName = Text.escapeIllegalJcrChars(authorizableId); NodeUtil folder = createFolderNodes(authorizableId, nodeName, isGroup, intermediatePath); String ntName = (isGroup) ? NT_REP_GROUP : NT_REP_USER; NodeUtil authorizableNode = folder.addChild(nodeName, ntName); String nodeID = getContentID(authorizableId); authorizableNode.setString(REP_AUTHORIZABLE_ID, authorizableId); authorizableNode.setString(JcrConstants.JCR_UUID, nodeID); return authorizableNode.getTree(); } /** * Create folder structure for the authorizable to be created. The structure * consists of a tree of rep:AuthorizableFolder node(s) starting at the * configured user or group path. Note that Authorizable nodes are never * nested. * * @param authorizableId * @param nodeName * @param isGroup * @param intermediatePath * @return The folder node. * @throws RepositoryException If an error occurs */ private NodeUtil createFolderNodes(String authorizableId, String nodeName, boolean isGroup, String intermediatePath) throws RepositoryException { String authRoot = (isGroup) ? groupPath : userPath; NodeUtil folder; Tree authTree = root.getTree(authRoot); if (authTree == null) { folder = new NodeUtil(root.getTree("/"), contentSession); for (String name : Text.explode(authRoot, '/', false)) { folder = folder.getOrAddChild(name, NT_REP_AUTHORIZABLE_FOLDER); } } else { folder = new NodeUtil(authTree, contentSession); } String folderPath = getFolderPath(authorizableId, intermediatePath); String[] segmts = Text.explode(folderPath, '/', false); for (String segment : segmts) { folder = folder.getOrAddChild(segment, NT_REP_AUTHORIZABLE_FOLDER); // TODO: remove check once UserValidator is active if (!folder.hasPrimaryNodeTypeName(NT_REP_AUTHORIZABLE_FOLDER)) { String msg = "Cannot create user/group: Intermediate folders must be of type rep:AuthorizableFolder."; throw new ConstraintViolationException(msg); } } // test for colliding folder child node. while (folder.hasChild(nodeName)) { NodeUtil colliding = folder.getChild(nodeName); // TODO: remove check once UserValidator is active if (colliding.hasPrimaryNodeTypeName(NT_REP_AUTHORIZABLE_FOLDER)) { log.debug("Existing folder node collides with user/group to be created. Expanding path by: " + colliding.getName()); folder = colliding; } else { String msg = "Failed to create authorizable with id '" + authorizableId + "' : " + "Detected conflicting node of unexpected node type '" + colliding.getString(JcrConstants.JCR_PRIMARYTYPE, null) + "'."; log.error(msg); throw new ConstraintViolationException(msg); } } // TODO: remove check once UserValidator is active if (!Text.isDescendantOrEqual(authRoot, folder.getTree().getPath())) { throw new ConstraintViolationException("Attempt to create user/group outside of configured scope " + authRoot); } return folder; } private String getFolderPath(String authorizableId, String intermediatePath) { StringBuilder sb = new StringBuilder(); if (intermediatePath != null && !intermediatePath.isEmpty()) { sb.append(intermediatePath); } else { int idLength = authorizableId.length(); StringBuilder segment = new StringBuilder(); for (int i = 0; i < defaultDepth; i++) { if (idLength > i) { segment.append(authorizableId.charAt(i)); } else { // escapedID is too short -> append the last char again segment.append(authorizableId.charAt(idLength-1)); } sb.append(DELIMITER).append(Text.escapeIllegalJcrChars(segment.toString())); } } return sb.toString(); } //-----------------------------------------< private MembershipProvider >--- private CoreValue createCoreValue(Tree authorizableTree) { return contentSession.getCoreValueFactory().createValue(getContentID(authorizableTree), PropertyType.WEAKREFERENCE); } private boolean useMemberNode(Tree groupTree) { return splitSize >= 4 && !groupTree.hasProperty(REP_MEMBERS); } /** * Returns an iterator of authorizables which includes all indirect members * of the given iterator of authorizables. * * * @param declaredMembers * @param authorizableType * @return Iterator of Authorizable objects */ private Iterator<String> getAllMembers(final Iterator<String> declaredMembers, final int authorizableType) { Iterator<Iterator<String>> inheritedMembers = new Iterator<Iterator<String>>() { @Override public boolean hasNext() { return declaredMembers.hasNext(); } @Override public Iterator<String> next() { String memberPath = declaredMembers.next(); return Iterators.concat(Iterators.singletonIterator(memberPath), inherited(memberPath)); } @Override public void remove() { throw new UnsupportedOperationException(); } private Iterator<String> inherited(String authorizablePath) { Tree group = getAuthorizableByPath(authorizablePath); if (isAuthorizableTree(group, UserManager.SEARCH_TYPE_GROUP)) { return getMembers(group, authorizableType, true); } else { return Iterators.emptyIterator(); } } }; return Iterators.filter(Iterators.concat(inheritedMembers), new ProcessedPathPredicate()); } private Iterator<String> getAllMembership(final Iterator<String> groupPaths) { Iterator<Iterator<String>> inheritedMembership = new Iterator<Iterator<String>>() { @Override public boolean hasNext() { return groupPaths.hasNext(); } @Override public Iterator<String> next() { String groupPath = groupPaths.next(); return Iterators.concat(Iterators.singletonIterator(groupPath), inherited(groupPath)); } @Override public void remove() { throw new UnsupportedOperationException(); } private Iterator<String> inherited(String authorizablePath) { Tree group = getAuthorizableByPath(authorizablePath); if (isAuthorizableTree(group, UserManager.SEARCH_TYPE_GROUP)) { return getMembership(group, true); } else { return Iterators.emptyIterator(); } } }; return Iterators.filter(Iterators.concat(inheritedMembership), new ProcessedPathPredicate()); } private static final class ProcessedPathPredicate implements Predicate<String> { private final Set<String> processed = new HashSet<String>(); @Override public boolean apply(@Nullable String path) { return processed.add(path); } } }
oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserProviderImpl.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.jackrabbit.oak.security.user; import java.security.Principal; import java.text.ParseException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.query.Query; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.jackrabbit.commons.iterator.RangeIteratorAdapter; import org.apache.jackrabbit.oak.api.ContentSession; import org.apache.jackrabbit.oak.api.CoreValue; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Result; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.SessionQueryEngine; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager; import org.apache.jackrabbit.oak.spi.security.principal.TreeBasedPrincipal; import org.apache.jackrabbit.oak.spi.security.user.MembershipProvider; import org.apache.jackrabbit.oak.spi.security.user.UserConstants; import org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig; import org.apache.jackrabbit.oak.spi.security.user.UserProvider; import org.apache.jackrabbit.oak.util.NodeUtil; import org.apache.jackrabbit.util.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * User provider implementation and manager for group memberships with the * following characteristics: * * <h1>UserProvider</h1> * * <h2>User and Group Creation</h2> * This implementation creates the JCR nodes corresponding the a given * authorizable ID with the following behavior: * <ul> * <li>Users are created below /rep:security/rep:authorizables/rep:users or * the path configured in the {@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_USER_PATH} * respectively.</li> * <li>Groups are created below /rep:security/rep:authorizables/rep:groups or * the path configured in the {@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_GROUP_PATH} * respectively.</li> * <li>Below each category authorizables are created within a human readable * structure based on the defined intermediate path or some internal logic * with a depth defined by the {@code defaultDepth} config option.<br> * E.g. creating a user node for an ID 'aSmith' would result in the following * structure assuming defaultDepth == 2 is used: * <pre> * + rep:security [rep:AuthorizableFolder] * + rep:authorizables [rep:AuthorizableFolder] * + rep:users [rep:AuthorizableFolder] * + a [rep:AuthorizableFolder] * + aS [rep:AuthorizableFolder] * -> + aSmith [rep:User] * </pre> * </li> * <li>The node name is calculated from the specified authorizable ID * {@link org.apache.jackrabbit.util.Text#escapeIllegalJcrChars(String) escaping} any illegal JCR chars.</li> * <li>If no intermediate path is passed the names of the intermediate * folders are calculated from the leading chars of the escaped node name.</li> * <li>If the escaped node name is shorter than the {@code defaultDepth} * the last char is repeated.<br> * E.g. creating a user node for an ID 'a' would result in the following * structure assuming defaultDepth == 2 is used: * <pre> * + rep:security [rep:AuthorizableFolder] * + rep:authorizables [rep:AuthorizableFolder] * + rep:users [rep:AuthorizableFolder] * + a [rep:AuthorizableFolder] * + aa [rep:AuthorizableFolder] * -> + a [rep:User] * </pre></li> * * <h3>Conflicts</h3> * * <ul> * <li>If the authorizable node to be created would collide with an existing * folder the conflict is resolved by using the colling folder as target.</li> * <li>The current implementation asserts that authorizable nodes are always * created underneath an node of type {@code rep:AuthorizableFolder}. If this * condition is violated a {@code ConstraintViolationException} is thrown.</li> * <li>If the specified intermediate path results in an authorizable node * being located outside of the configured content structure a * {@code ConstraintViolationException} is thrown.</li> * </ul> * * <h3>Configuration Options</h3> * <ul> * <li>{@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_USER_PATH}: Underneath this structure * all user nodes are created. Default value is * "/rep:security/rep:authorizables/rep:users"</li> * <li>{@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_GROUP_PATH}: Underneath this structure * all group nodes are created. Default value is * "/rep:security/rep:authorizables/rep:groups"</li> * <li>{@link org.apache.jackrabbit.oak.spi.security.user.UserManagerConfig#PARAM_DEFAULT_DEPTH}: A positive {@code integer} * greater than zero defining the depth of the default structure that is * always created. Default value: 2</li> * </ul> * * <h3>Compatibility with Jackrabbit 2.x</h3> * * Due to the fact that this JCR implementation is expected to deal with huge amount * of child nodes the following configuration options are no longer supported: * <ul> * <li>autoExpandTree</li> * <li>autoExpandSize</li> * </ul> * * <h2>User and Group Access</h2> * <h3>By ID</h3> * TODO * <h3>By Path</h3> * TODO * <h3>By Principal Name</h3> * TODO * * <h1>MembershipProvider</h1> * * TODO */ public class UserProviderImpl implements UserProvider, MembershipProvider, UserConstants { /** * logger instance */ private static final Logger log = LoggerFactory.getLogger(UserProviderImpl.class); private static final String DELIMITER = "/"; private static final int DEFAULT_DEPTH = 2; private final ContentSession contentSession; private final Root root; private final IdentifierManager identifierManager; private final int defaultDepth; private final int splitSize; private final String adminId; private final String groupPath; private final String userPath; public UserProviderImpl(ContentSession contentSession, Root root, UserManagerConfig config) { this.contentSession = contentSession; this.root = root; this.identifierManager = new IdentifierManager(contentSession, root); defaultDepth = config.getConfigValue(UserManagerConfig.PARAM_DEFAULT_DEPTH, DEFAULT_DEPTH); int splitValue = config.getConfigValue(UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE, 0); if (splitValue < 4) { log.warn("Invalid value {} for {}. Expected integer >= 4", splitValue, UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE); splitValue = 0; } this.splitSize = splitValue; this.adminId = config.getAdminId(); groupPath = config.getConfigValue(UserManagerConfig.PARAM_GROUP_PATH, DEFAULT_GROUP_PATH); userPath = config.getConfigValue(UserManagerConfig.PARAM_USER_PATH, DEFAULT_USER_PATH); } //-------------------------------------------------------< UserProvider >--- @Override public Tree createUser(String userID, String intermediateJcrPath) throws RepositoryException { return createAuthorizableNode(userID, false, intermediateJcrPath); } @Override public Tree createGroup(String groupID, String intermediateJcrPath) throws RepositoryException { return createAuthorizableNode(groupID, true, intermediateJcrPath); } @Override public Tree getAuthorizable(String authorizableId) { Tree tree = identifierManager.getTree(getContentID(authorizableId)); if (isAuthorizableTree(tree, UserManager.SEARCH_TYPE_AUTHORIZABLE)) { return tree; } else { return null; } } @Override public Tree getAuthorizable(String authorizableId, int authorizableType) { Tree tree = identifierManager.getTree(getContentID(authorizableId)); if (isAuthorizableTree(tree, authorizableType)) { return tree; } else { return null; } } @Override() public Tree getAuthorizableByPath(String authorizableOakPath) { Tree tree = root.getTree(authorizableOakPath); if (isAuthorizableTree(tree, UserManager.SEARCH_TYPE_AUTHORIZABLE)) { return tree; } else { return null; } } @Override public Tree getAuthorizableByPrincipal(Principal principal) { Tree authorizableTree = null; if (principal instanceof TreeBasedPrincipal) { authorizableTree = root.getTree(((TreeBasedPrincipal) principal).getOakPath()); } else { // NOTE: in contrast to JR2 the extra shortcut for ID==principalName // can be omitted as principals names are stored in user defined // index as well. SessionQueryEngine queryEngine = contentSession.getQueryEngine(); try { CoreValue bindValue = contentSession.getCoreValueFactory().createValue(principal.getName()); Map<String, CoreValue> bindings = Collections.singletonMap("principalName", bindValue); String stmt = "SELECT * FROM [rep:Authorizable] WHERE [rep:principalName] = $principalName"; Result result = contentSession.getQueryEngine().executeQuery(stmt, Query.JCR_SQL2, 1, 0, Collections.singletonMap("principalName", bindValue), new NamePathMapper.Default()); Iterator rows = result.getRows().iterator(); if (rows.hasNext()) { String path = rows.next().toString(); authorizableTree = root.getTree(path); } } catch (ParseException ex) { log.error("query failed", ex); } } return authorizableTree; } @Override public String getAuthorizableId(Tree authorizableTree) { assert authorizableTree != null; PropertyState idProp = authorizableTree.getProperty(UserConstants.REP_AUTHORIZABLE_ID); if (idProp != null) { return idProp.getValue().getString(); } else { return Text.unescapeIllegalJcrChars(authorizableTree.getName()); } } @Override public boolean isAdminUser(Tree userTree) { assert userTree != null; return isAuthorizableTree(userTree, UserManager.SEARCH_TYPE_USER) && adminId.equals(getAuthorizableId(userTree)); } //--------------------------------------------------< MembershipProvider>--- @Override public Iterator<String> getMembership(String authorizableId, boolean includeInherited) { return getMembership(getAuthorizable(authorizableId), includeInherited); } @Override public Iterator<String> getMembership(Tree authorizableTree, boolean includeInherited) { Set<String> groupPaths = new HashSet<String>(); Set<String> refPaths = identifierManager.getWeakReferences(authorizableTree, null, NT_REP_GROUP, NT_REP_MEMBERS); for (String propPath : refPaths) { int index = propPath.indexOf('/'+REP_MEMBERS); if (index > 0) { groupPaths.add(propPath.substring(0, index)); } else { log.debug("Not a membership reference property " + propPath); } } Iterator<String> it = groupPaths.iterator(); if (includeInherited && it.hasNext()) { return getAllMembership(groupPaths.iterator()); } else { return new RangeIteratorAdapter(it, groupPaths.size()); } } @Override public Iterator<String> getMembers(String groupId, int authorizableType, boolean includeInherited) { return getMembers(getAuthorizable(groupId), UserManager.SEARCH_TYPE_AUTHORIZABLE, includeInherited); } @Override public Iterator<String> getMembers(Tree groupTree, int authorizableType, boolean includeInherited) { Iterable memberPaths = Collections.emptySet(); if (useMemberNode(groupTree)) { Tree membersTree = groupTree.getChild(REP_MEMBERS); if (membersTree != null) { // FIXME: replace usage of PropertySequence (oak-api not possible there) // PropertySequence propertySequence = getPropertySequence(membersTree); // iterator = new AuthorizableIterator(propertySequence, authorizableType, userManager); } } else { PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { List<CoreValue> vs = property.getValues(); memberPaths = Iterables.transform(vs, new Function<CoreValue,String>() { @Override public String apply(@Nullable CoreValue value) { return identifierManager.getPath(value); } }); } } Iterator it = memberPaths.iterator(); if (includeInherited && it.hasNext()) { return getAllMembers(it, authorizableType); } else { return new RangeIteratorAdapter(it, Iterables.size(memberPaths)); } } @Override public boolean isMember(Tree groupTree, Tree authorizableTree, boolean includeInherited) { if (includeInherited) { Iterator<String> groupPaths = getMembership(authorizableTree, true); String path = groupTree.getPath(); while (groupPaths.hasNext()) { if (path.equals(groupPaths.next())) { return true; } } } else { if (useMemberNode(groupTree)) { Tree membersTree = groupTree.getChild(REP_MEMBERS); if (membersTree != null) { // FIXME: fix.. testing for property name isn't correct. // FIXME: usage of PropertySequence isn't possible when operating on oak-API // PropertySequence propertySequence = getPropertySequence(membersTree); // return propertySequence.hasItem(authorizable.getID()); return false; } } else { PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { List<CoreValue> members = property.getValues(); String authorizableUUID = getContentID(authorizableTree); for (CoreValue v : members) { if (authorizableUUID.equals(v.getString())) { return true; } } } } } // no a member of the specified group return false; } @Override public boolean addMember(Tree groupTree, Tree newMemberTree) { if (useMemberNode(groupTree)) { NodeUtil groupNode = new NodeUtil(groupTree, contentSession); NodeUtil membersNode = groupNode.getOrAddChild(REP_MEMBERS, NT_REP_MEMBERS); //FIXME: replace usage of PropertySequence with oak-compatible utility // PropertySequence properties = getPropertySequence(membersTree); // String propName = Text.escapeIllegalJcrChars(authorizable.getID()); // if (properties.hasItem(propName)) { // log.debug("Authorizable {} is already member of {}", authorizable, this); // return false; // } else { // CoreValue newMember = createCoreValue(authorizable); // properties.addProperty(propName, newMember); // } } else { List<CoreValue> values; CoreValue toAdd = createCoreValue(newMemberTree); PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { values = property.getValues(); if (values.contains(toAdd)) { return false; } else { values.add(toAdd); } } else { values = Collections.singletonList(toAdd); } groupTree.setProperty(REP_MEMBERS, values); } return true; } @Override public boolean removeMember(Tree groupTree, Tree memberTree) { if (useMemberNode(groupTree)) { Tree membersTree = groupTree.getChild(REP_MEMBERS); if (membersTree != null) { // FIXME: replace usage of PropertySequence with oak-compatible utility // PropertySequence properties = getPropertySequence(membersTree); // String propName = authorizable.getTree().getName(); // FIXME: fix.. testing for property name isn't correct. // if (properties.hasItem(propName)) { // Property p = properties.getItem(propName); // userManager.removeInternalProperty(p.getParent(), propName); // } // return true; return false; } } else { PropertyState property = groupTree.getProperty(REP_MEMBERS); if (property != null) { CoreValue toRemove = createCoreValue(memberTree); List<CoreValue> values = property.getValues(); if (values.remove(toRemove)) { if (values.isEmpty()) { groupTree.removeProperty(REP_MEMBERS); } else { groupTree.setProperty(REP_MEMBERS, values); } return true; } } } // nothing changed log.debug("Authorizable {} was not member of {}", memberTree.getName(), groupTree.getName()); return false; } //------------------------------------------------------------< private >--- private String getContentID(String authorizableId) { return IdentifierManager.generateUUID(authorizableId.toLowerCase()); } private String getContentID(Tree authorizableTree) { return identifierManager.getIdentifier(authorizableTree); } private boolean isAuthorizableTree(Tree tree, int type) { // FIXME: check for node type according to the specified type constraint if (tree.hasProperty(JcrConstants.JCR_PRIMARYTYPE)) { String ntName = tree.getProperty(JcrConstants.JCR_PRIMARYTYPE).getValue().getString(); switch (type) { case UserManager.SEARCH_TYPE_GROUP: return NT_REP_GROUP.equals(ntName); case UserManager.SEARCH_TYPE_USER: return NT_REP_USER.equals(ntName); default: return NT_REP_USER.equals(ntName) || NT_REP_GROUP.equals(ntName); } } return false; } //-----------------------------------------------< private UserProvider >--- private Tree createAuthorizableNode(String authorizableId, boolean isGroup, String intermediatePath) throws RepositoryException { String nodeName = Text.escapeIllegalJcrChars(authorizableId); NodeUtil folder = createFolderNodes(authorizableId, nodeName, isGroup, intermediatePath); String ntName = (isGroup) ? NT_REP_GROUP : NT_REP_USER; NodeUtil authorizableNode = folder.addChild(nodeName, ntName); String nodeID = getContentID(authorizableId); authorizableNode.setString(REP_AUTHORIZABLE_ID, authorizableId); authorizableNode.setString(JcrConstants.JCR_UUID, nodeID); return authorizableNode.getTree(); } /** * Create folder structure for the authorizable to be created. The structure * consists of a tree of rep:AuthorizableFolder node(s) starting at the * configured user or group path. Note that Authorizable nodes are never * nested. * * @param authorizableId * @param nodeName * @param isGroup * @param intermediatePath * @return The folder node. * @throws RepositoryException If an error occurs */ private NodeUtil createFolderNodes(String authorizableId, String nodeName, boolean isGroup, String intermediatePath) throws RepositoryException { String authRoot = (isGroup) ? groupPath : userPath; NodeUtil folder; Tree authTree = root.getTree(authRoot); if (authTree == null) { folder = new NodeUtil(root.getTree(""), contentSession); for (String name : Text.explode(authRoot, '/', false)) { folder = folder.getOrAddChild(name, NT_REP_AUTHORIZABLE_FOLDER); } } else { folder = new NodeUtil(authTree, contentSession); } String folderPath = getFolderPath(authorizableId, intermediatePath); String[] segmts = Text.explode(folderPath, '/', false); for (String segment : segmts) { folder = folder.getOrAddChild(segment, NT_REP_AUTHORIZABLE_FOLDER); // TODO: remove check once UserValidator is active if (!folder.hasPrimaryNodeTypeName(NT_REP_AUTHORIZABLE_FOLDER)) { String msg = "Cannot create user/group: Intermediate folders must be of type rep:AuthorizableFolder."; throw new ConstraintViolationException(msg); } } // test for colliding folder child node. while (folder.hasChild(nodeName)) { NodeUtil colliding = folder.getChild(nodeName); // TODO: remove check once UserValidator is active if (colliding.hasPrimaryNodeTypeName(NT_REP_AUTHORIZABLE_FOLDER)) { log.debug("Existing folder node collides with user/group to be created. Expanding path by: " + colliding.getName()); folder = colliding; } else { String msg = "Failed to create authorizable with id '" + authorizableId + "' : " + "Detected conflicting node of unexpected node type '" + colliding.getString(JcrConstants.JCR_PRIMARYTYPE, null) + "'."; log.error(msg); throw new ConstraintViolationException(msg); } } // TODO: remove check once UserValidator is active if (!Text.isDescendantOrEqual(authRoot, folder.getTree().getPath())) { throw new ConstraintViolationException("Attempt to create user/group outside of configured scope " + authRoot); } return folder; } private String getFolderPath(String authorizableId, String intermediatePath) { StringBuilder sb = new StringBuilder(); if (intermediatePath != null && !intermediatePath.isEmpty()) { sb.append(intermediatePath); } else { int idLength = authorizableId.length(); StringBuilder segment = new StringBuilder(); for (int i = 0; i < defaultDepth; i++) { if (idLength > i) { segment.append(authorizableId.charAt(i)); } else { // escapedID is too short -> append the last char again segment.append(authorizableId.charAt(idLength-1)); } sb.append(DELIMITER).append(Text.escapeIllegalJcrChars(segment.toString())); } } return sb.toString(); } //-----------------------------------------< private MembershipProvider >--- private CoreValue createCoreValue(Tree authorizableTree) { return contentSession.getCoreValueFactory().createValue(getContentID(authorizableTree), PropertyType.WEAKREFERENCE); } private boolean useMemberNode(Tree groupTree) { return splitSize >= 4 && !groupTree.hasProperty(REP_MEMBERS); } /** * Returns an iterator of authorizables which includes all indirect members * of the given iterator of authorizables. * * * @param declaredMembers * @param authorizableType * @return Iterator of Authorizable objects */ private Iterator<String> getAllMembers(final Iterator<String> declaredMembers, final int authorizableType) { Iterator<Iterator<String>> inheritedMembers = new Iterator<Iterator<String>>() { @Override public boolean hasNext() { return declaredMembers.hasNext(); } @Override public Iterator<String> next() { String memberPath = declaredMembers.next(); return Iterators.concat(Iterators.singletonIterator(memberPath), inherited(memberPath)); } @Override public void remove() { throw new UnsupportedOperationException(); } private Iterator<String> inherited(String authorizablePath) { Tree group = getAuthorizableByPath(authorizablePath); if (isAuthorizableTree(group, UserManager.SEARCH_TYPE_GROUP)) { return getMembers(group, authorizableType, true); } else { return Iterators.emptyIterator(); } } }; return Iterators.filter(Iterators.concat(inheritedMembers), new ProcessedPathPredicate()); } private Iterator<String> getAllMembership(final Iterator<String> groupPaths) { Iterator<Iterator<String>> inheritedMembership = new Iterator<Iterator<String>>() { @Override public boolean hasNext() { return groupPaths.hasNext(); } @Override public Iterator<String> next() { String groupPath = groupPaths.next(); return Iterators.concat(Iterators.singletonIterator(groupPath), inherited(groupPath)); } @Override public void remove() { throw new UnsupportedOperationException(); } private Iterator<String> inherited(String authorizablePath) { Tree group = getAuthorizableByPath(authorizablePath); if (isAuthorizableTree(group, UserManager.SEARCH_TYPE_GROUP)) { return getMembership(group, true); } else { return Iterators.emptyIterator(); } } }; return Iterators.filter(Iterators.concat(inheritedMembership), new ProcessedPathPredicate()); } private static final class ProcessedPathPredicate implements Predicate<String> { private final Set<String> processed = new HashSet<String>(); @Override public boolean apply(@Nullable String path) { return processed.add(path); } } }
OAK-259: Issues in o.a.j.oak.security.user.UserProviderImpl thanks Chetan Mehrotra for the patch git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1374992 13f79535-47bb-0310-9956-ffa450edef68
oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserProviderImpl.java
OAK-259: Issues in o.a.j.oak.security.user.UserProviderImpl thanks Chetan Mehrotra for the patch
<ide><path>ak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserProviderImpl.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.annotation.Nullable; <ide> import javax.jcr.PropertyType; <ide> import javax.jcr.RepositoryException; <ide> this.identifierManager = new IdentifierManager(contentSession, root); <ide> <ide> defaultDepth = config.getConfigValue(UserManagerConfig.PARAM_DEFAULT_DEPTH, DEFAULT_DEPTH); <del> int splitValue = config.getConfigValue(UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE, 0); <add> int splitValue = config.getConfigValue(UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE, 4); <ide> if (splitValue < 4) { <ide> log.warn("Invalid value {} for {}. Expected integer >= 4", splitValue, UserManagerConfig.PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE); <ide> splitValue = 0; <ide> <ide> private boolean isAuthorizableTree(Tree tree, int type) { <ide> // FIXME: check for node type according to the specified type constraint <del> if (tree.hasProperty(JcrConstants.JCR_PRIMARYTYPE)) { <add> if (tree != null && tree.hasProperty(JcrConstants.JCR_PRIMARYTYPE)) { <ide> String ntName = tree.getProperty(JcrConstants.JCR_PRIMARYTYPE).getValue().getString(); <ide> switch (type) { <ide> case UserManager.SEARCH_TYPE_GROUP: <ide> NodeUtil folder; <ide> Tree authTree = root.getTree(authRoot); <ide> if (authTree == null) { <del> folder = new NodeUtil(root.getTree(""), contentSession); <add> folder = new NodeUtil(root.getTree("/"), contentSession); <ide> for (String name : Text.explode(authRoot, '/', false)) { <ide> folder = folder.getOrAddChild(name, NT_REP_AUTHORIZABLE_FOLDER); <ide> }
Java
bsd-3-clause
da2cfd65d77689750f33c8a9887faafb860384e3
0
rwth-acis/LAS2peer,rwth-acis/LAS2peer
package i5.las2peer.classLoaders.libraries; import org.junit.Assert; import org.junit.Test; import i5.las2peer.classLoaders.helpers.LibraryDependency; import i5.las2peer.classLoaders.helpers.LibraryIdentifier; public class LoadedNetworkLibraryTest { @Test public void testXMLandBack() { try { LibraryIdentifier libId = new LibraryIdentifier("testlib", "4.2.1"); LoadedNetworkLibrary noDeps = new LoadedNetworkLibrary(null, libId, null); String xml = noDeps.toXmlString(); LoadedNetworkLibrary backNoDeps = LoadedNetworkLibrary.createFromXml(null, xml); Assert.assertEquals(noDeps.getIdentifier().toString(), backNoDeps.getIdentifier().toString()); LibraryDependency[] deps = backNoDeps.getDependencies(); Assert.assertNotNull(deps); Assert.assertEquals(0, deps.length); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } }
src/test/java/i5/las2peer/classLoaders/libraries/LoadedNetworkLibraryTest.java
package i5.las2peer.classLoaders.libraries; import org.junit.Assert; import org.junit.Test; import i5.las2peer.classLoaders.helpers.LibraryIdentifier; public class LoadedNetworkLibraryTest { @Test public void testXMLandBack() { try { LibraryIdentifier libId = new LibraryIdentifier("testlib", "4.2.1"); LoadedNetworkLibrary noDeps = new LoadedNetworkLibrary(null, libId, null); String xml = noDeps.toXmlString(); LoadedNetworkLibrary backNoDeps = LoadedNetworkLibrary.createFromXml(null, xml); Assert.assertEquals(noDeps.getIdentifier().toString(), backNoDeps.getIdentifier().toString()); Assert.assertNotNull(backNoDeps.getDependencies()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } }
improve LoadedNetworkLibraryTest
src/test/java/i5/las2peer/classLoaders/libraries/LoadedNetworkLibraryTest.java
improve LoadedNetworkLibraryTest
<ide><path>rc/test/java/i5/las2peer/classLoaders/libraries/LoadedNetworkLibraryTest.java <ide> import org.junit.Assert; <ide> import org.junit.Test; <ide> <add>import i5.las2peer.classLoaders.helpers.LibraryDependency; <ide> import i5.las2peer.classLoaders.helpers.LibraryIdentifier; <ide> <ide> public class LoadedNetworkLibraryTest { <ide> String xml = noDeps.toXmlString(); <ide> LoadedNetworkLibrary backNoDeps = LoadedNetworkLibrary.createFromXml(null, xml); <ide> Assert.assertEquals(noDeps.getIdentifier().toString(), backNoDeps.getIdentifier().toString()); <del> Assert.assertNotNull(backNoDeps.getDependencies()); <add> LibraryDependency[] deps = backNoDeps.getDependencies(); <add> Assert.assertNotNull(deps); <add> Assert.assertEquals(0, deps.length); <ide> } catch (Exception e) { <ide> e.printStackTrace(); <ide> Assert.fail(e.toString());
Java
mit
aa8af7c59f6ebacffde89eee4b8a49f9f22ac15a
0
yDelouis/selfoss-android
package fr.ydelouis.selfoss.adapter; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.support.v13.app.FragmentPagerAdapter; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.UiThread; import java.util.ArrayList; import java.util.List; import fr.ydelouis.selfoss.entity.Article; import fr.ydelouis.selfoss.entity.Filter; import fr.ydelouis.selfoss.fragment.ArticleFragment_; import fr.ydelouis.selfoss.model.ArticleProvider; @EBean public class ArticlePagerAdapter extends FragmentPagerAdapter implements ArticleProvider.Listener { @Bean protected ArticleProvider provider; private List<Article> articles = new ArrayList<Article>(); public ArticlePagerAdapter(Context context) { super(((Activity) context).getFragmentManager()); } @AfterInject protected void init() { provider.setListener(this); } public void setFilter(Filter filter) { provider.setFilter(filter); } public void setArticle(Article article) { articles.clear(); articles.add(article); provider.loadNew(article); } @Override public void onNewLoaded(List<Article> newArticles) { if (newArticles != null) { articles.addAll(0, newArticles); } } public int getPosition(Article article) { return articles.indexOf(article); } public Article getArticle(int position) { return articles.get(position); } @Override public Fragment getItem(int position) { if (isNewPageNeeded(position)) { loadNextArticles(); } return ArticleFragment_.builder().article(getArticle(position)).build(); } private boolean isNewPageNeeded(int position) { return position == getCount()-1; } @Background protected void loadNextArticles() { int count = getCount(); Article lastArticle = null; if (count > 0) { lastArticle = getArticle(count - 1); } provider.loadNext(count, lastArticle); } @Override public int getCount() { return articles.size(); } @Override @UiThread public void onNextLoaded(List<Article> nextArticles) { if (nextArticles != null) { for (Article article : nextArticles) { if (!articles.contains(article)) { articles.add(article); } } if (!nextArticles.isEmpty()) { notifyDataSetChanged(); } } } }
app/src/main/java/fr/ydelouis/selfoss/adapter/ArticlePagerAdapter.java
package fr.ydelouis.selfoss.adapter; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.support.v13.app.FragmentPagerAdapter; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.UiThread; import java.util.ArrayList; import java.util.List; import fr.ydelouis.selfoss.entity.Article; import fr.ydelouis.selfoss.entity.Filter; import fr.ydelouis.selfoss.fragment.ArticleFragment_; import fr.ydelouis.selfoss.model.ArticleProvider; @EBean public class ArticlePagerAdapter extends FragmentPagerAdapter implements ArticleProvider.Listener { @Bean protected ArticleProvider provider; private List<Article> articles = new ArrayList<Article>(); public ArticlePagerAdapter(Context context) { super(((Activity) context).getFragmentManager()); } @AfterInject protected void init() { provider.setListener(this); } public void setFilter(Filter filter) { provider.setFilter(filter); } public void setArticle(Article article) { articles.clear(); articles.add(article); provider.loadNew(article); } @Override public void onNewLoaded(List<Article> newArticles) { articles.addAll(0, newArticles); } public int getPosition(Article article) { return articles.indexOf(article); } public Article getArticle(int position) { return articles.get(position); } @Override public Fragment getItem(int position) { if (isNewPageNeeded(position)) { loadNextArticles(); } return ArticleFragment_.builder().article(getArticle(position)).build(); } private boolean isNewPageNeeded(int position) { return position == getCount()-1; } @Background protected void loadNextArticles() { int count = getCount(); Article lastArticle = null; if (count > 0) { lastArticle = getArticle(count - 1); } provider.loadNext(count, lastArticle); } @Override public int getCount() { return articles.size(); } @Override @UiThread public void onNextLoaded(List<Article> nextArticles) { for(Article article : nextArticles) { if(!articles.contains(article)) articles.add(article); } if (!nextArticles.isEmpty()) { notifyDataSetChanged(); } } }
Fix NPE in ArticlePagerAdapter
app/src/main/java/fr/ydelouis/selfoss/adapter/ArticlePagerAdapter.java
Fix NPE in ArticlePagerAdapter
<ide><path>pp/src/main/java/fr/ydelouis/selfoss/adapter/ArticlePagerAdapter.java <ide> <ide> @Override <ide> public void onNewLoaded(List<Article> newArticles) { <del> articles.addAll(0, newArticles); <add> if (newArticles != null) { <add> articles.addAll(0, newArticles); <add> } <ide> } <ide> <ide> public int getPosition(Article article) { <ide> @Override <ide> @UiThread <ide> public void onNextLoaded(List<Article> nextArticles) { <del> for(Article article : nextArticles) { <del> if(!articles.contains(article)) <del> articles.add(article); <del> } <del> if (!nextArticles.isEmpty()) { <del> notifyDataSetChanged(); <add> if (nextArticles != null) { <add> for (Article article : nextArticles) { <add> if (!articles.contains(article)) { <add> articles.add(article); <add> } <add> } <add> if (!nextArticles.isEmpty()) { <add> notifyDataSetChanged(); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
0c43e59ea81b975dfb36530da41b72f41d2f3106
0
pkdevbox/spring-social-github,cpitman/spring-social-auth0,pkdevbox/spring-social-github,spring-projects/spring-social-github,cpitman/spring-social-auth0,spring-projects/spring-social-github
/* * Copyright 2011 the original author or 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.springframework.social.github.api.impl; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Map; import org.springframework.social.github.api.GitHubApi; import org.springframework.social.github.api.GitHubUserProfile; import org.springframework.social.oauth2.AbstractOAuth2ApiTemplate; import org.springframework.social.oauth2.OAuth2Version; /** * <p> * The central class for interacting with TripIt. * </p> * <p> * TripIt operations require OAuth 1 authentication. Therefore TripIt template * must be given the minimal amount of information required to sign requests to * the TripIt API with an OAuth <code>Authorization</code> header. * </p> * @author Craig Walls */ public class GitHubTemplate extends AbstractOAuth2ApiTemplate implements GitHubApi { /** * Constructs a GitHubTemplate with the minimal amount of information * required to sign requests with an OAuth <code>Authorization</code> * header. * * @param accessToken * An access token granted to the application after OAuth * authentication. */ public GitHubTemplate(String accessToken) { super(accessToken); } @Override protected OAuth2Version getOAuth2Version() { return OAuth2Version.DRAFT_8; } public String getProfileId() { return getUserProfile().getUsername(); } @SuppressWarnings("unchecked") public GitHubUserProfile getUserProfile() { Map<String, ?> result = getRestTemplate().getForObject(PROFILE_URL, Map.class); Map<String, ?> user = (Map<String, String>) result.get("user"); Long gitHubId = Long.valueOf(String.valueOf(user.get("id"))); String username = String.valueOf(user.get("login")); String name = String.valueOf(user.get("name")); String location = user.get("location") != null ? String.valueOf(user.get("location")) : null; String company = user.get("company") != null ? String.valueOf(user.get("company")) : null; String blog = user.get("blog") != null ? String.valueOf(user.get("blog")) : null; String email = user.get("email") != null ? String.valueOf(user.get("email")) : null; Date createdDate = toDate(String.valueOf(user.get("created_at")), dateFormat); String gravatarId = (String) user.get("gravatar_id"); String profileImageUrl = gravatarId != null ? "https://secure.gravatar.com/avatar/" + gravatarId : null; return new GitHubUserProfile(gitHubId, username, name, location, company, blog, email, profileImageUrl, createdDate); } public String getProfileUrl() { return "https://github.com/" + getProfileId(); } // internal helpers private Date toDate(String dateString, DateFormat dateFormat) { try { return dateFormat.parse(dateString); } catch (ParseException e) { return null; } } private DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z", Locale.ENGLISH); static final String PROFILE_URL = "https://github.com/api/v2/json/user/show"; }
spring-social-github/src/main/java/org/springframework/social/github/api/impl/GitHubTemplate.java
/* * Copyright 2011 the original author or 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.springframework.social.github.api.impl; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Map; import org.springframework.social.github.api.GitHubApi; import org.springframework.social.github.api.GitHubUserProfile; import org.springframework.social.oauth2.AbstractOAuth2ApiTemplate; /** * <p> * The central class for interacting with TripIt. * </p> * <p> * TripIt operations require OAuth 1 authentication. Therefore TripIt template * must be given the minimal amount of information required to sign requests to * the TripIt API with an OAuth <code>Authorization</code> header. * </p> * @author Craig Walls */ public class GitHubTemplate extends AbstractOAuth2ApiTemplate.Draft8ApiTemplate implements GitHubApi { /** * Constructs a GitHubTemplate with the minimal amount of information * required to sign requests with an OAuth <code>Authorization</code> * header. * * @param accessToken * An access token granted to the application after OAuth * authentication. */ public GitHubTemplate(String accessToken) { super(accessToken); } public String getProfileId() { return getUserProfile().getUsername(); } @SuppressWarnings("unchecked") public GitHubUserProfile getUserProfile() { Map<String, ?> result = getRestTemplate().getForObject(PROFILE_URL, Map.class); Map<String, ?> user = (Map<String, String>) result.get("user"); Long gitHubId = Long.valueOf(String.valueOf(user.get("id"))); String username = String.valueOf(user.get("login")); String name = String.valueOf(user.get("name")); String location = user.get("location") != null ? String.valueOf(user.get("location")) : null; String company = user.get("company") != null ? String.valueOf(user.get("company")) : null; String blog = user.get("blog") != null ? String.valueOf(user.get("blog")) : null; String email = user.get("email") != null ? String.valueOf(user.get("email")) : null; Date createdDate = toDate(String.valueOf(user.get("created_at")), dateFormat); String gravatarId = (String) user.get("gravatar_id"); String profileImageUrl = gravatarId != null ? "https://secure.gravatar.com/avatar/" + gravatarId : null; return new GitHubUserProfile(gitHubId, username, name, location, company, blog, email, profileImageUrl, createdDate); } public String getProfileUrl() { return "https://github.com/" + getProfileId(); } // internal helpers private Date toDate(String dateString, DateFormat dateFormat) { try { return dateFormat.parse(dateString); } catch (ParseException e) { return null; } } private DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z", Locale.ENGLISH); static final String PROFILE_URL = "https://github.com/api/v2/json/user/show"; }
refactored base OAuth2 api template to allow specification of OAuth2Version by subclasses, removed dead ApiTemplate code
spring-social-github/src/main/java/org/springframework/social/github/api/impl/GitHubTemplate.java
refactored base OAuth2 api template to allow specification of OAuth2Version by subclasses, removed dead ApiTemplate code
<ide><path>pring-social-github/src/main/java/org/springframework/social/github/api/impl/GitHubTemplate.java <ide> import org.springframework.social.github.api.GitHubApi; <ide> import org.springframework.social.github.api.GitHubUserProfile; <ide> import org.springframework.social.oauth2.AbstractOAuth2ApiTemplate; <add>import org.springframework.social.oauth2.OAuth2Version; <ide> <ide> /** <ide> * <p> <ide> * </p> <ide> * @author Craig Walls <ide> */ <del>public class GitHubTemplate extends AbstractOAuth2ApiTemplate.Draft8ApiTemplate implements GitHubApi { <add>public class GitHubTemplate extends AbstractOAuth2ApiTemplate implements GitHubApi { <ide> <ide> /** <ide> * Constructs a GitHubTemplate with the minimal amount of information <ide> */ <ide> public GitHubTemplate(String accessToken) { <ide> super(accessToken); <add> } <add> <add> @Override <add> protected OAuth2Version getOAuth2Version() { <add> return OAuth2Version.DRAFT_8; <ide> } <ide> <ide> public String getProfileId() {
Java
mit
5c722cba589e83b0c2df3eba0902a3e46d4117d9
0
hres/cfg-task-service,hres/cfg-task-service,hres/cfg-task-service
package ca.gc.ip346.classification.resource; import static com.google.common.net.HttpHeaders.ACCEPT; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static com.google.common.net.HttpHeaders.CONTENT_TYPE; import static com.google.common.net.HttpHeaders.ORIGIN; import static com.google.common.net.HttpHeaders.X_REQUESTED_WITH; import static com.mongodb.client.model.Filters.and; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Updates.combine; import static com.mongodb.client.model.Updates.currentDate; import static com.mongodb.client.model.Updates.set; import static javax.ws.rs.HttpMethod.DELETE; import static javax.ws.rs.HttpMethod.GET; import static javax.ws.rs.HttpMethod.HEAD; import static javax.ws.rs.HttpMethod.OPTIONS; import static javax.ws.rs.HttpMethod.POST; import static javax.ws.rs.HttpMethod.PUT; import static org.apache.logging.log4j.Level.DEBUG; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.glassfish.jersey.client.ClientProperties; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures; import com.google.gson.GsonBuilder; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; // import ca.gc.ip346.classification.model.Added; import ca.gc.ip346.classification.model.CanadaFoodGuideFoodItem; import ca.gc.ip346.classification.model.CfgFilter; import ca.gc.ip346.classification.model.CfgTier; import ca.gc.ip346.classification.model.ContainsAdded; import ca.gc.ip346.classification.model.Dataset; import ca.gc.ip346.classification.model.Missing; import ca.gc.ip346.classification.model.PseudoBoolean; import ca.gc.ip346.classification.model.PseudoDouble; import ca.gc.ip346.classification.model.PseudoInteger; import ca.gc.ip346.classification.model.PseudoString; import ca.gc.ip346.classification.model.RecipeRolled; import ca.gc.ip346.util.ClassificationProperties; import ca.gc.ip346.util.DBConnection; import ca.gc.ip346.util.MongoClientFactory; import ca.gc.ip346.util.RequestURI; @Path("/datasets") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public class FoodsResource { private static final Logger logger = LogManager.getLogger(FoodsResource.class); private Connection conn = null; private DatabaseMetaData meta = null; private MongoClient mongoClient = null; private MongoCollection<Document> collection = null; @Context private HttpServletRequest request; public FoodsResource() { mongoClient = MongoClientFactory.getMongoClient(); collection = mongoClient.getDatabase(MongoClientFactory.getDatabase()).getCollection(MongoClientFactory.getCollection()); try { conn = DBConnection.getConnection(); } catch(Exception e) { // TODO: proper response to handle exceptions logger.debug("" + e.getMessage() + ""); logger.debug("" + e.getMessage() + ""); } } @OPTIONS @Path("/search") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response getFoodListPreflight() { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @GET @Path("/search") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* List<CanadaFoodGuideFoodItem> */ Response getFoodList(@BeanParam CfgFilter search) { String sql = ContentHandler.read("canada_food_guide_food_item.sql", getClass()); search.setSql(sql); mongoClient.close(); return doSearchCriteria(search); } @OPTIONS @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response saveDatasetPreflight() { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* Map<String, Object> */ Response saveDataset(Dataset dataset) { ResponseBuilder response = null; Status status = null; Map<String, Object> map = new HashMap<String, Object>(); if (dataset.getData() != null && dataset.getName() != null && dataset.getName() != null) { Document doc = new Document() .append("data", dataset.getData()) .append("name", dataset.getName()) .append("env", dataset.getEnv()) .append("owner", dataset.getOwner()) .append("status", dataset.getStatus()) .append("comments", dataset.getComments()); collection.insertOne(doc); ObjectId id = (ObjectId)doc.get("_id"); collection.updateOne( eq("_id", id), combine( set("name", dataset.getName()), set("comments", dataset.getComments()), currentDate("modifiedDate")) ); logger.debug("Last inserted Dataset id: " + id + ""); logger.debug("Current number of Datasets: " + collection.count() + ""); map.put("id", id.toString()); logger.debug("" + Response.Status.CREATED.getStatusCode() + " " + Response.Status.CREATED.toString() + ""); status = Response.Status.CREATED; response = Response.status(status); } else { List<String> list = new ArrayList<String>(); if (dataset.getData() == null) list.add("data"); if (dataset.getName() == null) list.add("name"); if (dataset.getEnv() == null) list.add("env"); if (dataset.getComments() == null) list.add("comments"); map.put("code", Response.Status.BAD_REQUEST.getStatusCode()); map.put("description", Response.Status.BAD_REQUEST.toString() + " - Unable to insert Dataset!"); map.put("fields", StringUtils.join(list, ", ")); logger.debug("" + Response.Status.BAD_REQUEST.toString() + " - Unable to insert Dataset!" + ""); logger.debug("" + Response.Status.BAD_REQUEST.getStatusCode() + " " + Response.Status.BAD_REQUEST.toString() + ""); status = Response.Status.BAD_REQUEST; response = Response.status(status); } // mongoClient.close(); logger.debug("" + "response status: " + response.build().getStatusInfo() + ""); return getResponse(POST, status, map); } // @OPTIONS // @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) // @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) // public Response getDatasetsPreflight() { // Map<String, String> msg = new HashMap<String, String>(); // msg.put("message", "options-catch-all"); // return getResponse(OPTIONS, Response.Status.OK, msg); // } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* List<Map<String, String>> */ Response getDatasets(@QueryParam("env") String env) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); MongoCursor<Document> cursorDocMap = collection.find(eq("env", env)).iterator(); while (cursorDocMap.hasNext()) { Map<String, String> map = new HashMap<String, String>(); Document doc = cursorDocMap.next(); map.put("id", doc.get("_id").toString()); if (doc.get("name" ) != null) map.put("name", doc.get("name" ).toString()); if (doc.get("env" ) != null) map.put("env", doc.get("env" ).toString()); if (doc.get("owner" ) != null) map.put("owner", doc.get("owner" ).toString()); if (doc.get("status" ) != null) map.put("status", doc.get("status" ).toString()); if (doc.get("comments" ) != null) map.put("comments", doc.get("comments" ).toString()); if (doc.get("modifiedDate") != null) map.put("modifiedDate", doc.get("modifiedDate").toString()); list.add(map); logger.debug("Dataset ID: " + doc.get("_id") + ""); } logger.debug("" + "request URI : " + RequestURI.getUri() + ""); logger.debug("" + "request URI : " + request.getRequestURI() + ""); logger.debug("" + "request URL : " + request.getRequestURL() + ""); logger.debug("" + "request Name : " + request.getServerName() + ""); logger.debug("" + "request Port : " + request.getServerPort() + ""); logger.debug("" + "request Protocol : " + request.getProtocol() + ""); mongoClient.close(); return getResponse(GET, Response.Status.OK, list); } @GET @Path("/{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* List<Map<String, Object>> */ Response getDataset(@PathParam("id") String id) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); MongoCursor<Document> cursorDocMap = null; if (ObjectId.isValid(id)) { System.out.println("" + "Valid hexadecimal representation of ObjectId " + id + ""); cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); } else { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Invalid hexadecimal representation of ObjectId " + id + ""); System.out.println("" + "Invalid hexadecimal representation of ObjectId " + id + ""); mongoClient.close(); return getResponse(GET, Response.Status.BAD_REQUEST, msg); } if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(GET, Response.Status.NOT_FOUND, msg); } while (cursorDocMap.hasNext()) { Map<String, Object> map = new HashMap<String, Object>(); Document doc = cursorDocMap.next(); logger.debug("Dataset ID: " + doc.get("_id") + ""); if (doc != null) { map.put("id", id); map.put("data", doc.get("data")); map.put("name", doc.get("name")); map.put("env", doc.get("env")); map.put("owner", doc.get("owner")); map.put("status", doc.get("status")); map.put("comments", doc.get("comments")); map.put("modifiedDate", doc.get("modifiedDate")); list.add(map); } } mongoClient.close(); return getResponse(GET, Response.Status.OK, list.get(0)); } @OPTIONS @Path("/{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response deleteDatasetPreflight() { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @DELETE @Path("/{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response deleteDataset(@PathParam("id") String id) { MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(DELETE, Response.Status.NOT_FOUND, msg); } while (cursorDocMap.hasNext()) { Document doc = cursorDocMap.next(); logger.debug("Dataset ID: " + doc.get("_id") + ""); collection.deleteOne(doc); } mongoClient.close(); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Successfully deleted dataset with ID: " + id); return getResponse(DELETE, Response.Status.OK, msg); } @DELETE @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response deleteAllDatasets() { collection.deleteMany(new Document()); mongoClient.close(); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Successfully deleted all datasets"); return getResponse(DELETE, Response.Status.OK, msg); } @PUT @Path("/{id}") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response updateDataset(@PathParam("id") String id, Dataset dataset) { Map<Integer, Map<String, Object>> original_values_map = new HashMap<Integer, Map<String, Object>>(); Map<Integer, Map<String, Object>> toupdate_values_map = new HashMap<Integer, Map<String, Object>>(); List<Object> list = null; List<Bson> firstLevelSets = new ArrayList<Bson>(); int changes = 0; // retrive the corresponding dataset with the given id MongoCursor<Document> cursorDocMap = null; if (ObjectId.isValid(id)) { System.out.println("" + "Valid hexadecimal representation of ObjectId " + id + ""); cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); } else { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Invalid hexadecimal representation of ObjectId " + id + ""); System.out.println("" + "Invalid hexadecimal representation of ObjectId " + id + ""); mongoClient.close(); return getResponse(PUT, Response.Status.BAD_REQUEST, msg); } if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(PUT, Response.Status.NOT_FOUND, msg); } while (cursorDocMap.hasNext()) { Document doc = cursorDocMap.next(); list = castList(doc.get("data"), Object.class); for (Object obj : list) { Map<?, ?> mObj = (Map<?, ?>)obj; Map<String, Object> tmp = new HashMap<String, Object>(); Iterator<?> it = mObj.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); tmp.put(key, mObj.get(key)); } original_values_map.put((Integer)tmp.get("code"), tmp); } logger.debug("Update: " + "casting property 'data' seems to have passed!" + ""); if (dataset.getName() != null && !dataset.getName().equals(doc.get("name"))) { firstLevelSets.add(set("name", dataset.getName())); ++changes; } if (dataset.getEnv() != null && !dataset.getEnv().equals(doc.get("env"))) { firstLevelSets.add(set("env", dataset.getEnv())); ++changes; } if (dataset.getOwner() != null && !dataset.getOwner().equals(doc.get("owner"))) { firstLevelSets.add(set("owner", dataset.getOwner())); ++changes; } if (dataset.getStatus() != null && !dataset.getStatus().equals(doc.get("status"))) { firstLevelSets.add(set("status", dataset.getStatus())); ++changes; } if (dataset.getComments() != null && !dataset.getComments().equals(doc.get("comments"))) { firstLevelSets.add(set("comments", dataset.getComments())); ++changes; } } List<Map<String, Object>> updates = dataset.getData(); for (Map<String, Object> map : updates) { toupdate_values_map.put((Integer)map.get("code"), map); logger.debug("Dataset: " + toupdate_values_map.get(map.get("code")) + ""); logger.debug("name: " + toupdate_values_map.get(map.get("code")).get("name") + ""); } Map<String, String> updateDatePair = new HashMap<String, String>(); updateDatePair.put("cfgCode", "cfgCodeUpdateDate" ); updateDatePair.put("comments", "" ); updateDatePair.put("containsAddedFat", "containsAddedFatUpdateDate" ); updateDatePair.put("containsAddedSodium", "containsAddedSodiumUpdateDate" ); updateDatePair.put("containsAddedSugar", "containsAddedSugarUpdateDate" ); updateDatePair.put("containsAddedTransfat", "containsAddedTransfatUpdateDate" ); updateDatePair.put("containsCaffeine", "containsCaffeineUpdateDate" ); updateDatePair.put("containsFreeSugars", "containsFreeSugarsUpdateDate" ); updateDatePair.put("containsSugarSubstitutes", "containsSugarSubstitutesUpdateDate" ); updateDatePair.put("foodGuideServingG", "foodGuideUpdateDate" ); updateDatePair.put("foodGuideServingMeasure", "foodGuideUpdateDate" ); updateDatePair.put("marketedToKids", "" ); updateDatePair.put("overrideSmallRaAdjustment", "" ); updateDatePair.put("replacementCode", "" ); updateDatePair.put("rolledUp", "rolledUpUpdateDate" ); updateDatePair.put("satfatAmountPer100g", "satfatImputationDate" ); updateDatePair.put("satfatImputationReference", "satfatImputationDate" ); updateDatePair.put("sodiumAmountPer100g", "sodiumImputationDate" ); updateDatePair.put("sodiumImputationReference", "sodiumImputationDate" ); updateDatePair.put("sugarAmountPer100g", "sugarImputationDate" ); updateDatePair.put("sugarImputationReference", "sugarImputationDate" ); updateDatePair.put("tier4ServingG", "tier4ServingUpdateDate" ); updateDatePair.put("tier4ServingMeasure", "tier4ServingUpdateDate" ); updateDatePair.put("totalFatAmountPer100g", "totalFatImputationDate" ); updateDatePair.put("totalFatImputationReference", "totalFatImputationDate" ); updateDatePair.put("transfatAmountPer100g", "transfatImputationDate" ); updateDatePair.put("transfatImputationReference", "transfatImputationDate" ); logger.debug(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(updateDatePair)); for (Map<String, Object> map : updates) { List<Bson> sets = new ArrayList<Bson>(); logger.debug("size: " + sets.size() + ""); if (toupdate_values_map.get(map.get("code")).get("name") != null && !toupdate_values_map .get (map .get ("code")) .get ("name") .equals (original_values_map .get (map .get ("code")) .get ("name"))) { sets.add(set("data.$.name", map.get("name"))); ++changes; logger.debug("value changed: " + map.get("name") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("cnfGroupCode") != null && !toupdate_values_map .get (map .get ("code")) .get ("cnfGroupCode") .equals (original_values_map .get (map .get ("code")) .get ("cnfGroupCode"))) { sets.add(set("data.$.cnfGroupCode", map.get("cnfGroupCode"))); ++changes; logger.debug("value changed: " + map.get("cnfGroupCode") + ""); } for (String key : updateDatePair.keySet()) { changes = updateIfModified(key, updateDatePair.get(key), sets, changes, original_values_map, toupdate_values_map, map); } if (toupdate_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("energyKcal") != null && !toupdate_values_map .get (map .get ("code")) .get ("energyKcal") .equals (original_values_map .get (map .get ("code")) .get ("energyKcal"))) { sets.add(set("data.$.energyKcal", map.get("energyKcal"))); ++changes; logger.debug("value changed: " + map.get("energyKcal") + ""); } logger.debug("" + "before: " + original_values_map .get (map .get ("code")) .get ("validated") + " - validated" + ""); logger.debug("" + " after: " + toupdate_values_map .get (map .get ("code")) .get ("validated") + " - validated" + ""); if (toupdate_values_map .get (map .get ("code")) .get ("validated") != null && !toupdate_values_map .get (map .get ("code")) .get ("validated") .equals (original_values_map .get (map .get ("code")) .get ("validated"))) { sets.add(set("data.$.validated", map.get("validated"))); ++changes; logger.debug("value changed: " + map.get("validated") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("sodiumImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("sodiumImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("sodiumImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("sugarImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("sugarImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("sugarImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("transfatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("transfatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("transfatImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("satfatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("satfatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("satfatImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("totalFatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("totalFatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("totalFatImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountG") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountG") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountG"))) { sets.add(set("data.$.referenceAmountG", map.get("referenceAmountG"))); sets.add(currentDate("data.$.referenceAmountUpdateDate")); ++changes; logger.debug("value changed: " + map.get("referenceAmountG") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountMeasure") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountMeasure") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountMeasure"))) { sets.add(set("data.$.referenceAmountMeasure", map.get("referenceAmountMeasure"))); ++changes; logger.debug("value changed: " + map.get("referenceAmountMeasure") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate"))) { } // if (toupdate_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment") != null && !toupdate_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment") .equals (original_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment"))) { // sets.add(set("data.$.overrideSmallRaAdjustment", map.get("overrideSmallRaAdjustment"))); // ++changes; // logger.debug("value changed: " + map.get("overrideSmallRaAdjustment") + ""); // } if (toupdate_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount") != null && !toupdate_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount") .equals (original_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount"))) { sets.add(set("data.$.adjustedReferenceAmount", map.get("adjustedReferenceAmount"))); ++changes; logger.debug("value changed: " + map.get("adjustedReferenceAmount") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("commitDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("commitDate") .equals (original_values_map .get (map .get ("code")) .get ("commitDate"))) { } logger.debug("size: " + sets.size() + ""); logger.debug("code: " + map.get("code") + ""); if (sets.size() > 0) { collection.updateOne(and(eq("_id", new ObjectId(id)), eq("data.code", map.get("code"))), combine(sets)); } } if (changes != 0) { firstLevelSets.add(currentDate("modifiedDate")); collection.updateOne(eq("_id", new ObjectId(id)), combine(firstLevelSets)); } mongoClient.close(); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Successfully updated dataset"); return getResponse(PUT, Response.Status.OK, msg); } @OPTIONS @Path("/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response classifyDatasetPreflightOne(Dataset dataset) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @POST @Path("/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response classifyDataset(Dataset dataset) { Response response = null; Map<String, String> msg = new HashMap<String, String>(); if (dataset.getEnv().equals("sandbox")) { /** * * first, create a new transient dataset * */ Map<?, ?> tmp = (Map<?, ?>)saveDataset(dataset).getEntity(); Map<String, String> map = new HashMap<String, String>(); for (Entry<?, ?> entry : tmp.entrySet()) { map.put((String)entry.getKey(), (String)entry.getValue()); } String id = map.get("id"); /** * * second, with newly created ID, classify dataset * */ response = classifyDataset(id); /** * * third, delete transient dataset * */ deleteDataset(id); return response; } else { msg.put("message", "Invalid environment: " + dataset.getEnv() + ""); return getResponse(POST, Response.Status.BAD_REQUEST, msg); } } @OPTIONS @Path("/{id}/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response classifyDatasetPreflightTwo(String id) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @POST @Path("/{id}/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) @SuppressWarnings("unchecked") public Response classifyDataset(@PathParam("id") String id) { Map<String, Object> map = null; MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); List<Object> list = null; List<Document> dox = new ArrayList<Document>(); if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(POST, Response.Status.NOT_FOUND, msg); } /** * * first server-side validation: required for classification * */ List<Map<String, Object>> dataToBeValidated = new ArrayList<Map<String, Object>>(); Map<String, String> requiredForClassification = new HashMap<String, String>(); requiredForClassification.put("type", "Scalar"); // Type Y CFG Indicates if the item is a Food or Recipe -- requiredForClassification.put("code", "Scalar"); // Code Y CNF/NSS CNF Food Code or NSS Recipe Code -- requiredForClassification.put("name", "Scalar"); // Name Y CNF/NSS Food or Recipe Name -- requiredForClassification.put("cfgCode", "Object"); // CFG Code Y (at least three digits) CFG Up to four digit CFG Code (includes tier, if available) -- requiredForClassification.put("sodiumAmountPer100g", "Object"); // Sodium Amount (per 100g) Y CNF/NSS Amount of Sodium per 100 g -- requiredForClassification.put("sugarAmountPer100g", "Object"); // Sugar Amount (per 100g) Y CNF/NSS Amount of Sugar per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. -- requiredForClassification.put("satfatAmountPer100g", "Object"); // SatFat Amount (per 100g) Y CNF/NSS Amount of Saturated Fat per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. -- requiredForClassification.put("totalFatAmountPer100g", "Object"); // TotalFat Amount (per 100g) Y CNF/NSS Amount of Total Fat per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. -- // requiredForClassification.put("containsAddedSodium", "Object"); // Contains Added Sodium Y CFG Indicates if the item contains added sodium -- // requiredForClassification.put("containsAddedSugar", "Object"); // Contains Added Sugar Y CFG Indicates if the item contains added sugar -- // requiredForClassification.put("containsAddedFat", "Object"); // Contains Added Fat Y CFG Indicates if the item contains added fat -- // requiredForClassification.put("referenceAmountG", "Scalar"); // Reference Amount (g) Y CNF/NSS -- // requiredForClassification.put("toddlerItem", "Scalar"); // Toddler Item Y CFG -- // requiredForClassification.put("overrideSmallRaAdjustment", "Object"); // Override Small RA Adjustment Y CFG Overrides the Small RA Adjustment that is made for foods that have RA lower than the Small RA Threshold (ie 30g) -- while (cursorDocMap.hasNext()) { Boolean isInvalid = false; Document doc = cursorDocMap.next(); if (doc != null) { list = castList(doc.get("data"), Object.class); for (Object obj : list) { Map<String, Object> requiredOnly = new HashMap<String, Object>(); for (String key : requiredForClassification.keySet()) { if (requiredForClassification.get(key).equals("Object")) { Document objectifiedValue = (Document)((Document)obj).get(key + ""); if (objectifiedValue.get("value") != null) { requiredOnly.put(key, objectifiedValue.get("value")); if (key.equals("cfgCode") && ((Integer)requiredOnly.get(key)).toString().length() != 3 && ((Integer)requiredOnly.get(key)).toString().length() != 4) { isInvalid = true; } } else { isInvalid = true; } } if (requiredForClassification.get(key).equals("Scalar")) { if (((Document)obj).get(key + "") != null) { requiredOnly.put(key, ((Document)obj).get(key + "")); } else { isInvalid = true; } } } dataToBeValidated.add(requiredOnly); } } // use validation rules on "data" property and return response if invalid logger.debug("" + "only required fields:\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(dataToBeValidated) + ""); if (isInvalid) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Expected required field(s) failed to pass validation in preparation for classification."); return getResponse(POST, Response.Status.EXPECTATION_FAILED, msg); } } /** * * rewind dataset to do the actual classification * */ cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); /** * * objectified properties * */ Map<String, String> updateDatePair = new HashMap<String, String>(); updateDatePair.put("cfgCode", "cfgCodeUpdateDate" ); updateDatePair.put("comments", "" ); updateDatePair.put("containsAddedFat", "containsAddedFatUpdateDate" ); updateDatePair.put("containsAddedSodium", "containsAddedSodiumUpdateDate" ); updateDatePair.put("containsAddedSugar", "containsAddedSugarUpdateDate" ); updateDatePair.put("containsAddedTransfat", "containsAddedTransfatUpdateDate" ); updateDatePair.put("containsCaffeine", "containsCaffeineUpdateDate" ); updateDatePair.put("containsFreeSugars", "containsFreeSugarsUpdateDate" ); updateDatePair.put("containsSugarSubstitutes", "containsSugarSubstitutesUpdateDate" ); updateDatePair.put("foodGuideServingG", "foodGuideUpdateDate" ); updateDatePair.put("foodGuideServingMeasure", "foodGuideUpdateDate" ); updateDatePair.put("marketedToKids", "" ); updateDatePair.put("overrideSmallRaAdjustment", "" ); updateDatePair.put("replacementCode", "" ); updateDatePair.put("rolledUp", "rolledUpUpdateDate" ); updateDatePair.put("satfatAmountPer100g", "satfatImputationDate" ); updateDatePair.put("satfatImputationReference", "satfatImputationDate" ); updateDatePair.put("sodiumAmountPer100g", "sodiumImputationDate" ); updateDatePair.put("sodiumImputationReference", "sodiumImputationDate" ); updateDatePair.put("sugarAmountPer100g", "sugarImputationDate" ); updateDatePair.put("sugarImputationReference", "sugarImputationDate" ); updateDatePair.put("tier4ServingG", "tier4ServingUpdateDate" ); updateDatePair.put("tier4ServingMeasure", "tier4ServingUpdateDate" ); updateDatePair.put("totalFatAmountPer100g", "totalFatImputationDate" ); updateDatePair.put("totalFatImputationReference", "totalFatImputationDate" ); updateDatePair.put("transfatAmountPer100g", "transfatImputationDate" ); updateDatePair.put("transfatImputationReference", "transfatImputationDate" ); /** * * only transform objectified values to literal values * */ while (cursorDocMap.hasNext()) { Document doc = cursorDocMap.next(); map = new HashMap<String, Object>(); logger.debug("Dataset ID: " + doc.get("_id") + ""); if (doc != null) { list = castList(doc.get("data"), Object.class); for (Object obj : list) { for (String key : updateDatePair.keySet()) { Document objectifiedValue = (Document)((Document)obj).get(key + ""); ((Document)obj).put(key, objectifiedValue.get("value")); } dox.add((Document)obj); } map.put("data", dox); map.put("name", doc.get("name")); map.put("env", doc.get("env")); map.put("owner", doc.get("owner")); map.put("status", doc.get("status")); map.put("comments", doc.get("comments")); map.put("modifiedDate", doc.get("modifiedDate")); } } // mongoClient.close(); // String target = "http://" + request.getServerName() + ":" + request.getServerPort() + ClassificationProperties.getEndPoint(); String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-"); // logger.debug("" + "request URI : " + RequestURI.getUri() + ""); logger.debug("" + "request URI : " + request.getRequestURI() + ""); logger.debug("" + "request URL : " + request.getRequestURL() + ""); logger.debug("" + "request target : " + request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-") + ""); logger.debug("" + "request Name : " + request.getServerName() + ""); logger.debug("" + "request Port : " + request.getServerPort() + ""); logger.debug("" + "request Protocol : " + request.getProtocol() + ""); logger.debug("" + "request target : " + target + ""); SSLContext sslcontext = null; try { sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new java.security.SecureRandom()); } catch(NoSuchAlgorithmException nsae) { } catch(KeyManagementException kme) { } Response response = ClientBuilder .newBuilder() .sslContext(sslcontext) .build() .target(target) .path("/classify") .request() // .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE) .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(map, MediaType.APPLICATION_JSON)); logger.debug("" + "response status : " + response.getStatusInfo() + ""); Map<String, Object> deserialized = (Map<String, Object>)response.readEntity(Object.class); List<Object> dataArray = (List<Object>)(deserialized).get("data"); for (Object obj : dataArray) { for (String key : updateDatePair.keySet()) { Object value = ((Map<String, Object>)obj).get(key + ""); Map<String, Object> metadataObject = new HashMap<String, Object>(); metadataObject.put("value", value); metadataObject.put("modified", false); ((Map<String, Object>)obj).put(key, metadataObject); } } deserialized.put("id", id); logger.debug("" + "response status: " + ((Map<String, Object>)dataArray.get(0)).get("sodiumAmountPer100g") + ""); logger.debug("" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(deserialized) + ""); return getResponse(POST, Response.Status.OK, deserialized); } @POST @Path("/{id}/flags") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response flagsDataset(@PathParam("id") String id, Dataset dataset) { Response response = ClientBuilder .newClient() .target(RequestURI.getUri() + ClassificationProperties.getEndPoint()) .path("/flags") .request() .post(Entity.entity(dataset, MediaType.APPLICATION_JSON)); return response; } @POST @Path("/{id}/init") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response initDataset(@PathParam("id") String id, Dataset dataset) { Response response = ClientBuilder .newClient() .target(RequestURI.getUri() + ClassificationProperties.getEndPoint()) .path("/init") .request() .post(Entity.entity(dataset, MediaType.APPLICATION_JSON)); return response; } @POST @Path("/{id}/adjustment") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response adjustmentDataset(@PathParam("id") String id, Dataset dataset) { Response response = ClientBuilder .newClient() .target(RequestURI.getUri() + ClassificationProperties.getEndPoint()) .path("/adjustment") .request() .post(Entity.entity(dataset, MediaType.APPLICATION_JSON)); return response; } @POST @Path("/{id}/commit") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public void commitDataset() { } @GET @Path("/status") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response getStatusCodes() { Map<Integer, String> list = new HashMap<Integer, String>(); String sql = ContentHandler.read("schema_test.sql", getClass()); Map<Integer, String> map = new HashMap<Integer, String>(); for (Response.Status obj : Response.Status.values()) { map.put(obj.getStatusCode(), obj.name()); } int len = 0; for (Integer key : map.keySet()) { String value = map.get(key); if (value.length() > len) { len = value.length(); } } String format = new StringBuffer() .append(" %d %-") .append(len) .append("s") .toString(); // String tamrof = new StringBuffer() // .append("%-") // .append(len + 6) // .append("s") // .toString(); Integer[][] arr = new Integer[6][18]; Integer[][] brr = new Integer[2][18]; Integer series = 0; int i = 0; int k = 0; for (Integer key : map.keySet()) { if (key / 100 != series) { series = key / 100; i = 0; } if (series == 4) { brr[0][i] = key; } else { brr[1][k++] = key; } arr[series][i++] = key; } for (int j = 0; j < 18; ++j) { arr[0][j] = null; arr[1][j] = null; } for (int l = 0; l < 18; ++l) { for (int m = 0; m < 2; ++m) { Integer key = brr[m][l]; System.out.printf("[01;03;%dm" + format + "", l % 2 == 0 ? 34 : 31, key, Response.Status.fromStatusCode(key)); } System.out.println(); } try { if (conn != null) { PreparedStatement stmt = conn.prepareStatement(sql); // Create PreparedStatement ResultSet rs = stmt.executeQuery(); while (rs.next()) { list.put(rs.getInt("canada_food_guide_food_item_count"), rs.getString("canada_food_guide_food_item_desc")); } sql = ContentHandler.read("connectivity_test.sql", getClass()); stmt = conn.prepareStatement(sql); // Create PreparedStatement rs = stmt.executeQuery(); while (rs.next()) { list.put(rs.getInt("canada_food_group_id"), rs.getString("canada_food_group_desc_e")); } list.put(666, "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version")); conn.close(); } else { list.put(Response.Status.SERVICE_UNAVAILABLE.getStatusCode(), "PostgreSQL database connectivity test: failed - service unavailable"); return getResponse(GET, Response.Status.SERVICE_UNAVAILABLE, list); } } catch(SQLException e) { // TODO: proper response to handle exceptions logger.debug("" + e.getMessage() + ""); for (Response.Status status : Response.Status.values()) { list.put(new Integer(status.getStatusCode()), status.getReasonPhrase()); } list.put(666, "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version")); } try { logger.debug("" + "new mongo connectivity test: " + mongoClient.getAddress() + ""); logger.debug("" + "new mongo connectivity test: " + mongoClient.getConnectPoint() + ""); logger.debug("" + "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version") + ""); } catch(Exception e) { // TODO: proper response to handle exceptions Map<String, String> msg = new HashMap<String, String>(); msg.put("message", e.getMessage()); logger.debug("" + e.getMessage() + ""); mongoClient.close(); return getResponse(GET, Response.Status.GATEWAY_TIMEOUT, msg); } mongoClient.close(); // return getResponse(GET, Response.Status.OK, Response.Status.values()); return getResponse(GET, Response.Status.OK, list); } private /* List<CanadaFoodGuideFoodItem> */ Response doSearchCriteria(CfgFilter search) { List<CanadaFoodGuideFoodItem> list = new ArrayList<CanadaFoodGuideFoodItem>(); if (search != null) { StringBuffer sb = new StringBuffer(search.getSql()); logger.debug("" + search.getDataSource() + ""); sb.append(" WHERE length('this where-clause is an artifact') = 32").append("\n"); if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) { sb.append(" AND type = ?").append("\n"); } logger.debug("" + search.getFoodRecipeName() + ""); if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) { sb.append(" AND LOWER(name) LIKE ?").append("\n"); } logger.debug("" + search.getFoodRecipeCode() + ""); if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) { sb.append(" AND code = ? OR CAST(code AS text) LIKE ?").append("\n"); } logger.debug("" + search.getCnfCode() + ""); if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) { sb.append(" AND cnf_group_code = ?").append("\n"); } logger.debug("" + search.getSubgroupCode() + ""); if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) { sb.append(" AND CAST(cfg_code AS text) LIKE ?").append("\n"); } if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) { switch (search.getCfgTier()) { case 1: case 2: case 3: case 4: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 12: case 13: case 14: case 23: case 24: case 34: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 123: case 124: case 134: case 234: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 1234: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 9: logger.debug("Calling all codes with missing Tier!"); sb.append(" AND LENGTH(CAST(cfg_code AS text)) < 4").append("\n"); break; } } if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) { logger.debug("" + search.getRecipe() + ""); switch (search.getRecipe()) { case 1: case 2: sb.append(" AND rolled_up = ?").append("\n"); break; case 3: sb.append(" AND (rolled_up = 1 OR rolled_up = 2)").append("\n"); break; } } boolean notIgnore = false; if (search.getContainsAdded() != null) { String[] arr = new String[search.getContainsAdded().size()]; arr = search.getContainsAdded().toArray(arr); for (String i : arr) { logger.debug("" + i + ""); if (!i.equals("0")) { notIgnore = true; } } } Map<String, String> map = null; if (search.getContainsAdded() != null && notIgnore) { map = new HashMap<String, String>(); logger.debug("" + search.getContainsAdded() + ""); String[] arr = new String[search.getContainsAdded().size()]; arr = search.getContainsAdded().toArray(arr); for (String keyValue : arr) { StringTokenizer tokenizer = new StringTokenizer(keyValue, "="); map.put(tokenizer.nextToken(), tokenizer.nextToken()); logger.debug("" + keyValue + ""); } logger.debug("\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + ""); Set<String> keys = map.keySet(); for (String key : keys) { switch (ContainsAdded.valueOf(key)) { case sodium: sb.append(" AND contains_added_sodium = ? ").append("\n"); break; case sugar: sb.append(" AND contains_added_sugar = ? ").append("\n"); break; case fat: sb.append(" AND contains_added_fat = ? ").append("\n"); break; case transfat: sb.append(" AND contains_added_transfat = ? ").append("\n"); break; case caffeine: sb.append(" AND contains_caffeine = ? ").append("\n"); break; case freeSugars: sb.append(" AND contains_free_sugars = ? ").append("\n"); break; case sugarSubstitute: sb.append(" AND contains_sugar_substitutes = ? ").append("\n"); break; } } } if (search.getMissingValues() != null) { logger.debug("" + search.getMissingValues() + ""); logger.debug("\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(search.getMissingValues()) + ""); for (String name : search.getMissingValues()) { switch (Missing.valueOf(name)) { case refAmount: sb.append(" AND reference_amount_g IS NULL").append("\n"); break; case cfgServing: sb.append(" AND food_guide_serving_g IS NULL").append("\n"); break; case tier4Serving: sb.append(" AND tier_4_serving_g IS NULL").append("\n"); break; case energy: sb.append(" AND energy_kcal IS NULL").append("\n"); break; case cnfCode: sb.append(" AND cnf_group_code IS NULL").append("\n"); break; case rollUp: sb.append(" AND rolled_up IS NULL").append("\n"); break; case sodiumPer100g: sb.append(" AND sodium_amount_per_100g IS NULL").append("\n"); break; case sugarPer100g: sb.append(" AND sugar_amount_per_100g IS NULL").append("\n"); break; case fatPer100g: sb.append(" AND totalfat_amount_per_100g IS NULL").append("\n"); break; case transfatPer100g: sb.append(" AND transfat_amount_per_100g IS NULL").append("\n"); break; case satFatPer100g: sb.append(" AND satfat_amount_per_100g IS NULL").append("\n"); break; case addedSodium: sb.append(" AND contains_added_sodium IS NULL").append("\n"); break; case addedSugar: sb.append(" AND contains_added_sugar IS NULL").append("\n"); break; case addedFat: sb.append(" AND contains_added_fat IS NULL").append("\n"); break; case addedTransfat: sb.append(" AND contains_added_transfat IS NULL").append("\n"); break; case caffeine: sb.append(" AND contains_caffeine IS NULL").append("\n"); break; case freeSugars: sb.append(" AND contains_free_sugars IS NULL").append("\n"); break; case sugarSubstitute: sb.append(" AND contains_sugar_substitutes IS NULL").append("\n"); break; } } } if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { if (search.getLastUpdatedFilter() != null) { logger.debug("" + search.getLastUpdatedFilter() + ""); for (String name : search.getLastUpdatedFilter()) { switch (Missing.valueOf(name)) { case refAmount: sb.append(" AND reference_amount_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case cfgServing: sb.append(" AND food_guide_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case tier4Serving: sb.append(" AND tier_4_serving_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case energy: case cnfCode: break; case rollUp: sb.append(" AND rolled_up_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case sodiumPer100g: sb.append(" AND sodium_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case sugarPer100g: sb.append(" AND sugar_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case fatPer100g: sb.append(" AND totalfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case transfatPer100g: sb.append(" AND transfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case satFatPer100g: sb.append(" AND satfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedSodium: sb.append(" AND contains_added_sodium_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedSugar: sb.append(" AND contains_added_sugar_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedFat: sb.append(" AND contains_added_fat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedTransfat: sb.append(" AND contains_added_transfat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case caffeine: sb.append(" AND contains_caffeine_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case freeSugars: sb.append(" AND contains_free_sugars_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case sugarSubstitute: sb.append(" AND contains_sugar_substitutes_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; } } } } if (search.getComments() != null && !search.getComments().isEmpty()) { sb.append(" AND LOWER(comments) LIKE ?").append("\n"); } if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { sb.append(" AND commit_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n"); } search.setSql(sb.toString()); try { meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object logger.debug("JDBC driver version is " + meta.getDriverVersion() + ""); // Retrieve driver information PreparedStatement stmt = conn.prepareStatement(search.getSql(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Create PreparedStatement int i = 0; // keeps count of the number of placeholders if (search != null) { if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) { stmt.setInt(++i, search.getDataSource().equals("food") ? 1 : 2); } if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) { stmt.setString(++i, new String("%" + search.getFoodRecipeName() + "%").toLowerCase()); } if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) { stmt.setInt(++i, Integer.parseInt(search.getFoodRecipeCode())); stmt.setString(++i, new String("" + search.getFoodRecipeCode() + "%")); } if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) { stmt.setInt(++i, Integer.parseInt(search.getCnfCode())); } if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) { stmt.setString(++i, new String("" + search.getSubgroupCode() + "%")); } if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) { switch (search.getCfgTier()) { case 1: case 2: case 3: case 4: stmt.setInt(++i, search.getCfgTier()); break; } } if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) { switch (search.getRecipe()) { case 1: case 2: stmt.setInt(++i, search.getRecipe()); break; } } if (search.getContainsAdded() != null && notIgnore) { Set<String> keys = map.keySet(); for (String key : keys) { switch (ContainsAdded.valueOf(key)) { case sodium: case sugar: case fat: case transfat: case caffeine: case freeSugars: case sugarSubstitute: stmt.setBoolean(++i, map.get(key).equals("true")); break; } } } if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { if (search.getLastUpdatedFilter() != null) { logger.debug("" + search.getLastUpdatedFilter() + ""); for (String name : search.getLastUpdatedFilter()) { switch (Missing.valueOf(name)) { case refAmount: case cfgServing: case tier4Serving: stmt.setString(++i, search.getLastUpdateDateFrom()); stmt.setString(++i, search.getLastUpdateDateTo()); break; case energy: case cnfCode: break; case rollUp: case sodiumPer100g: case sugarPer100g: case fatPer100g: case transfatPer100g: case satFatPer100g: case addedSodium: case addedSugar: case addedFat: case addedTransfat: case caffeine: case freeSugars: case sugarSubstitute: stmt.setString(++i, search.getLastUpdateDateFrom()); stmt.setString(++i, search.getLastUpdateDateTo()); break; } } } } if (search.getComments() != null && !search.getComments().isEmpty()) { stmt.setString(++i, new String("%" + search.getComments() + "%").toLowerCase()); } if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { stmt.setString(++i, search.getCommitDateFrom()); stmt.setString(++i, search.getCommitDateTo()); } } logger.debug("SQL query to follow:\n" + stmt.toString() + ""); ResultSet rs = stmt.executeQuery(); rs.last(); logger.debug("" + rs.getRow() + " row" + (rs.getRow() == 1 ? "" : "s") + ""); rs.beforeFirst(); while (rs.next()) { CanadaFoodGuideFoodItem foodItem = new CanadaFoodGuideFoodItem(); foodItem.setType(rs.getInt ("type") == 1 ? "food" : "recipe" ); foodItem.setCode(rs.getInt ("code") ); foodItem.setName(rs.getString ("name") ); if (rs.getString("cnf_group_code") != null) { foodItem.setCnfGroupCode(rs.getInt ("cnf_group_code") ); } if (rs.getString("cfg_code") != null) { foodItem.setCfgCode(new PseudoInteger(rs.getInt ("cfg_code")) ); // editable } else { foodItem.setCfgCode(new PseudoInteger() ); } foodItem.setCommitDate(rs.getDate ("cfg_code_update_date") ); if (rs.getString("energy_kcal") != null) { foodItem.setEnergyKcal(rs.getDouble ("energy_kcal") ); } if (rs.getString("sodium_amount_per_100g") != null) { foodItem.setSodiumAmountPer100g(new PseudoDouble(rs.getDouble ("sodium_amount_per_100g")) ); // editable } else { foodItem.setSodiumAmountPer100g(new PseudoDouble() ); } foodItem.setSodiumImputationReference(new PseudoString(rs.getString ("sodium_imputation_reference")) ); foodItem.setSodiumImputationDate(rs.getDate ("sodium_imputation_date") ); if (rs.getString("sugar_amount_per_100g") != null) { foodItem.setSugarAmountPer100g(new PseudoDouble(rs.getDouble ("sugar_amount_per_100g")) ); // editable } else { foodItem.setSugarAmountPer100g(new PseudoDouble() ); } foodItem.setSugarImputationReference(new PseudoString(rs.getString ("sugar_imputation_reference")) ); foodItem.setSugarImputationDate(rs.getDate ("sugar_imputation_date") ); if (rs.getString("transfat_amount_per_100g") != null) { foodItem.setTransfatAmountPer100g(new PseudoDouble(rs.getDouble ("transfat_amount_per_100g")) ); // editable } else { foodItem.setTransfatAmountPer100g(new PseudoDouble() ); } foodItem.setTransfatImputationReference(new PseudoString(rs.getString ("transfat_imputation_reference")) ); foodItem.setTransfatImputationDate(rs.getDate ("transfat_imputation_date") ); if (rs.getString("satfat_amount_per_100g") != null) { foodItem.setSatfatAmountPer100g(new PseudoDouble(rs.getDouble ("satfat_amount_per_100g")) ); // editable } else { foodItem.setSatfatAmountPer100g(new PseudoDouble() ); } foodItem.setSatfatImputationReference(new PseudoString(rs.getString ("satfat_imputation_reference")) ); foodItem.setSatfatImputationDate(rs.getDate ("satfat_imputation_date") ); if (rs.getString("totalfat_amount_per_100g") != null) { foodItem.setTotalFatAmountPer100g(new PseudoDouble(rs.getDouble ("totalfat_amount_per_100g")) ); // editable } else { foodItem.setTotalFatAmountPer100g(new PseudoDouble() ); } foodItem.setTotalFatImputationReference(new PseudoString(rs.getString ("totalfat_imputation_reference")) ); foodItem.setTotalFatImputationDate(rs.getDate ("totalfat_imputation_date") ); if (rs.getString("contains_added_sodium") != null) { foodItem.setContainsAddedSodium(new PseudoBoolean(rs.getBoolean ("contains_added_sodium")) ); // editable } else { foodItem.setContainsAddedSodium(new PseudoBoolean() ); } foodItem.setContainsAddedSodiumUpdateDate(rs.getDate ("contains_added_sodium_update_date") ); if (rs.getString("contains_added_sugar") != null) { foodItem.setContainsAddedSugar(new PseudoBoolean(rs.getBoolean ("contains_added_sugar")) ); // editable } else { foodItem.setContainsAddedSugar(new PseudoBoolean() ); } foodItem.setContainsAddedSugarUpdateDate(rs.getDate ("contains_added_sugar_update_date") ); if (rs.getString("contains_free_sugars") != null) { foodItem.setContainsFreeSugars(new PseudoBoolean(rs.getBoolean ("contains_free_sugars")) ); // editable } else { foodItem.setContainsFreeSugars(new PseudoBoolean() ); } foodItem.setContainsFreeSugarsUpdateDate(rs.getDate ("contains_free_sugars_update_date") ); if (rs.getString("contains_added_fat") != null) { foodItem.setContainsAddedFat(new PseudoBoolean(rs.getBoolean ("contains_added_fat")) ); // editable } else { foodItem.setContainsAddedFat(new PseudoBoolean() ); } foodItem.setContainsAddedFatUpdateDate(rs.getDate ("contains_added_fat_update_date") ); if (rs.getString("contains_added_transfat") != null) { foodItem.setContainsAddedTransfat(new PseudoBoolean(rs.getBoolean ("contains_added_transfat")) ); // editable } else { foodItem.setContainsAddedTransfat(new PseudoBoolean() ); } foodItem.setContainsAddedTransfatUpdateDate(rs.getDate ("contains_added_transfat_update_date") ); if (rs.getString("contains_caffeine") != null) { foodItem.setContainsCaffeine(new PseudoBoolean(rs.getBoolean ("contains_caffeine")) ); // editable } else { foodItem.setContainsCaffeine(new PseudoBoolean() ); } foodItem.setContainsCaffeineUpdateDate(rs.getDate ("contains_caffeine_update_date") ); if (rs.getString("contains_sugar_substitutes") != null) { foodItem.setContainsSugarSubstitutes(new PseudoBoolean(rs.getBoolean ("contains_sugar_substitutes")) ); // editable } else { foodItem.setContainsSugarSubstitutes(new PseudoBoolean() ); } foodItem.setContainsSugarSubstitutesUpdateDate(rs.getDate ("contains_sugar_substitutes_update_date") ); if (rs.getString("reference_amount_g") != null) { foodItem.setReferenceAmountG(rs.getDouble ("reference_amount_g") ); // editable } foodItem.setReferenceAmountMeasure(rs.getString ("reference_amount_measure") ); // foodItem.setReferenceAmountUpdateDate(rs.getDate ("reference_amount_update_date") ); if (rs.getString("food_guide_serving_g") != null) { foodItem.setFoodGuideServingG(new PseudoDouble(rs.getDouble ("food_guide_serving_g")) ); // editable } else { foodItem.setFoodGuideServingG(new PseudoDouble() ); } foodItem.setFoodGuideServingMeasure(new PseudoString(rs.getString ("food_guide_serving_measure")) ); foodItem.setFoodGuideUpdateDate(rs.getDate ("food_guide_update_date") ); if (rs.getString("tier_4_serving_g") != null) { foodItem.setTier4ServingG(new PseudoDouble(rs.getDouble ("tier_4_serving_g")) ); // editable } else { foodItem.setTier4ServingG(new PseudoDouble() ); } foodItem.setTier4ServingMeasure(new PseudoString(rs.getString ("tier_4_serving_measure")) ); foodItem.setTier4ServingUpdateDate(rs.getDate ("tier_4_serving_update_date") ); if (rs.getString("rolled_up") != null) { foodItem.setRolledUp(new PseudoBoolean(rs.getBoolean ("rolled_up")) ); // editable } else { foodItem.setRolledUp(new PseudoBoolean() ); } foodItem.setRolledUpUpdateDate(rs.getDate ("rolled_up_update_date") ); if (rs.getString("override_small_ra_adjustment") != null) { foodItem.setOverrideSmallRaAdjustment(new PseudoBoolean(rs.getBoolean ("override_small_ra_adjustment")) ); } else { foodItem.setOverrideSmallRaAdjustment(new PseudoBoolean() ); } if (rs.getString("replacement_code") != null) { foodItem.setReplacementCode(new PseudoInteger(rs.getInt ("replacement_code")) ); // editable } else { foodItem.setReplacementCode(new PseudoInteger() ); } foodItem.setCommitDate(rs.getDate ("commit_date") ); foodItem.setComments(new PseudoString(rs.getString ("comments")) ); // editable foodItem.setValidated( false ); list.add(foodItem); } conn.close(); } catch(SQLException e) { // TODO: proper response to handle exceptions logger.debug("" + "" + e.getMessage() + ""); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", e.getMessage()); return getResponse(GET, Response.Status.SERVICE_UNAVAILABLE, msg); } } return getResponse(GET, Response.Status.OK, list); } // public static Client IgnoreSSLClient() throws Exception { // SSLContext sslcontext = SSLContext.getInstance("TLS"); // sslcontext.init(null, new TrustManager[] { // new X509TrustManager() { // public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} // public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} // public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } // } // }, new java.security.SecureRandom()); // return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((s1, s2) -> true).build(); // } public static Response getResponse(String method, Response.Status status, Object obj) { List<String> allowedHttpOrigins = null; List<String> allowedHttpHeaders = null; List<String> allowedHttpMethods = null; List<String> requestHttpMethods = null; allowedHttpOrigins = new ArrayList<String>(); allowedHttpOrigins.add("*"); // allowedHttpOrigins.add("http://10.148.178.250"); allowedHttpHeaders = new ArrayList<String>(); allowedHttpHeaders.add(ORIGIN); allowedHttpHeaders.add(CONTENT_TYPE); allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_HEADERS); allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_METHODS); allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN); allowedHttpHeaders.add(X_REQUESTED_WITH); allowedHttpHeaders.add(ACCEPT); allowedHttpHeaders.add(AUTHORIZATION); allowedHttpMethods = new ArrayList<String>(); allowedHttpMethods.add(GET); allowedHttpMethods.add(POST); allowedHttpMethods.add(OPTIONS); allowedHttpMethods.add(DELETE); allowedHttpMethods.add(PUT); allowedHttpMethods.add(HEAD); requestHttpMethods = new ArrayList<String>(); requestHttpMethods.add(GET); requestHttpMethods.add(POST); requestHttpMethods.add(OPTIONS); requestHttpMethods.add(DELETE); logger.printf(DEBUG, "%s%-29s: %s%s", "", ACCESS_CONTROL_ALLOW_ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", "), ""); logger.printf(DEBUG, "%s%-29s: %s%s", "", ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", "), ""); logger.printf(DEBUG, "%s%-29s: %s%s", "", ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowedHttpMethods.toArray(), ", "), ""); ResponseBuilder rb = Response.status(status); // rb.header( ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", ")); // rb.header(ACCESS_CONTROL_ALLOW_ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", ")); // rb.header(ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", ")); // rb.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); // rb.header(ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowedHttpMethods.toArray(), ", ")); // if (method.equals(OPTIONS)) { // rb.header(ACCESS_CONTROL_REQUEST_METHOD, StringUtils.join(requestHttpMethods.toArray(), ", ")); // rb.header(ACCESS_CONTROL_REQUEST_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", ")); // rb.header(CONTENT_TYPE, MediaType.APPLICATION_JSON); // } // rb.header(ACCESS_CONTROL_MAX_AGE, "1209600"); return rb.entity(obj).build(); } private static <T> List<T> castList(Object obj, Class<T> clazz) { List<T> result = new ArrayList<T>(); if (obj instanceof List<?>) { for (Object o : (List<?>)obj) { result.add(clazz.cast(o)); } return result; } return null; } @SuppressWarnings("unchecked") private int updateIfModified(String key, String value, List<Bson> sets, int changes, Map<Integer, Map<String, Object>> original_values_map, Map<Integer, Map<String, Object>> toupdate_values_map, Map<String, Object> map) { logger.debug("" + "key/value - " + key + ": " + ((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value") + ""); if (((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value") != null && !((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value").equals(((Map<String, Object>)original_values_map.get(map.get("code")).get(key)).get("value"))) { sets.add(set("data.$." + key + ".value", ((Map<String, Object>)map.get(key)).get("value"))); if (!value.isEmpty()) { sets.add(currentDate("data.$." + value)); } ++changes; logger.debug("value changed: " + ((Map<String, Object>)map.get(key)).get("value") + ""); } if (((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("modified") != null && !((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("modified").equals(((Map<String, Object>)original_values_map.get(map.get("code")).get(key)).get("modified"))) { sets.add(set("data.$." + key + ".modified", ((Map<String, Object>)map.get(key)).get("modified"))); } return changes; } }
src/main/java/ca/gc/ip346/classification/resource/FoodsResource.java
package ca.gc.ip346.classification.resource; import static com.google.common.net.HttpHeaders.ACCEPT; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static com.google.common.net.HttpHeaders.CONTENT_TYPE; import static com.google.common.net.HttpHeaders.ORIGIN; import static com.google.common.net.HttpHeaders.X_REQUESTED_WITH; import static com.mongodb.client.model.Filters.and; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Updates.combine; import static com.mongodb.client.model.Updates.currentDate; import static com.mongodb.client.model.Updates.set; import static javax.ws.rs.HttpMethod.DELETE; import static javax.ws.rs.HttpMethod.GET; import static javax.ws.rs.HttpMethod.HEAD; import static javax.ws.rs.HttpMethod.OPTIONS; import static javax.ws.rs.HttpMethod.POST; import static javax.ws.rs.HttpMethod.PUT; import static org.apache.logging.log4j.Level.DEBUG; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.glassfish.jersey.client.ClientProperties; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures; import com.google.gson.GsonBuilder; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; // import ca.gc.ip346.classification.model.Added; import ca.gc.ip346.classification.model.CanadaFoodGuideFoodItem; import ca.gc.ip346.classification.model.CfgFilter; import ca.gc.ip346.classification.model.CfgTier; import ca.gc.ip346.classification.model.ContainsAdded; import ca.gc.ip346.classification.model.Dataset; import ca.gc.ip346.classification.model.Missing; import ca.gc.ip346.classification.model.PseudoBoolean; import ca.gc.ip346.classification.model.PseudoDouble; import ca.gc.ip346.classification.model.PseudoInteger; import ca.gc.ip346.classification.model.PseudoString; import ca.gc.ip346.classification.model.RecipeRolled; import ca.gc.ip346.util.ClassificationProperties; import ca.gc.ip346.util.DBConnection; import ca.gc.ip346.util.MongoClientFactory; import ca.gc.ip346.util.RequestURI; @Path("/datasets") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public class FoodsResource { private static final Logger logger = LogManager.getLogger(FoodsResource.class); private Connection conn = null; private DatabaseMetaData meta = null; private MongoClient mongoClient = null; private MongoCollection<Document> collection = null; @Context private HttpServletRequest request; public FoodsResource() { mongoClient = MongoClientFactory.getMongoClient(); collection = mongoClient.getDatabase(MongoClientFactory.getDatabase()).getCollection(MongoClientFactory.getCollection()); try { conn = DBConnection.getConnection(); } catch(Exception e) { // TODO: proper response to handle exceptions logger.debug("" + e.getMessage() + ""); logger.debug("" + e.getMessage() + ""); } } @OPTIONS @Path("/search") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response getFoodListPreflight() { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @GET @Path("/search") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* List<CanadaFoodGuideFoodItem> */ Response getFoodList(@BeanParam CfgFilter search) { String sql = ContentHandler.read("canada_food_guide_food_item.sql", getClass()); search.setSql(sql); mongoClient.close(); return doSearchCriteria(search); } @OPTIONS @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response saveDatasetPreflight() { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* Map<String, Object> */ Response saveDataset(Dataset dataset) { ResponseBuilder response = null; Status status = null; Map<String, Object> map = new HashMap<String, Object>(); if (dataset.getData() != null && dataset.getName() != null && dataset.getName() != null) { Document doc = new Document() .append("data", dataset.getData()) .append("name", dataset.getName()) .append("env", dataset.getEnv()) .append("owner", dataset.getOwner()) .append("status", dataset.getStatus()) .append("comments", dataset.getComments()); collection.insertOne(doc); ObjectId id = (ObjectId)doc.get("_id"); collection.updateOne( eq("_id", id), combine( set("name", dataset.getName()), set("comments", dataset.getComments()), currentDate("modifiedDate")) ); logger.debug("Last inserted Dataset id: " + id + ""); logger.debug("Current number of Datasets: " + collection.count() + ""); map.put("id", id.toString()); logger.debug("" + Response.Status.CREATED.getStatusCode() + " " + Response.Status.CREATED.toString() + ""); status = Response.Status.CREATED; response = Response.status(status); } else { List<String> list = new ArrayList<String>(); if (dataset.getData() == null) list.add("data"); if (dataset.getName() == null) list.add("name"); if (dataset.getEnv() == null) list.add("env"); if (dataset.getComments() == null) list.add("comments"); map.put("code", Response.Status.BAD_REQUEST.getStatusCode()); map.put("description", Response.Status.BAD_REQUEST.toString() + " - Unable to insert Dataset!"); map.put("fields", StringUtils.join(list, ", ")); logger.debug("" + Response.Status.BAD_REQUEST.toString() + " - Unable to insert Dataset!" + ""); logger.debug("" + Response.Status.BAD_REQUEST.getStatusCode() + " " + Response.Status.BAD_REQUEST.toString() + ""); status = Response.Status.BAD_REQUEST; response = Response.status(status); } // mongoClient.close(); logger.debug("" + "response status: " + response.build().getStatusInfo() + ""); return getResponse(POST, status, map); } // @OPTIONS // @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) // @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) // public Response getDatasetsPreflight() { // Map<String, String> msg = new HashMap<String, String>(); // msg.put("message", "options-catch-all"); // return getResponse(OPTIONS, Response.Status.OK, msg); // } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* List<Map<String, String>> */ Response getDatasets(@QueryParam("env") String env) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); MongoCursor<Document> cursorDocMap = collection.find(eq("env", env)).iterator(); while (cursorDocMap.hasNext()) { Map<String, String> map = new HashMap<String, String>(); Document doc = cursorDocMap.next(); map.put("id", doc.get("_id").toString()); if (doc.get("name" ) != null) map.put("name", doc.get("name" ).toString()); if (doc.get("env" ) != null) map.put("env", doc.get("env" ).toString()); if (doc.get("owner" ) != null) map.put("owner", doc.get("owner" ).toString()); if (doc.get("status" ) != null) map.put("status", doc.get("status" ).toString()); if (doc.get("comments" ) != null) map.put("comments", doc.get("comments" ).toString()); if (doc.get("modifiedDate") != null) map.put("modifiedDate", doc.get("modifiedDate").toString()); list.add(map); logger.debug("Dataset ID: " + doc.get("_id") + ""); } logger.debug("" + "request URI : " + RequestURI.getUri() + ""); logger.debug("" + "request URI : " + request.getRequestURI() + ""); logger.debug("" + "request URL : " + request.getRequestURL() + ""); logger.debug("" + "request Name : " + request.getServerName() + ""); logger.debug("" + "request Port : " + request.getServerPort() + ""); logger.debug("" + "request Protocol : " + request.getProtocol() + ""); mongoClient.close(); return getResponse(GET, Response.Status.OK, list); } @GET @Path("/{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public /* List<Map<String, Object>> */ Response getDataset(@PathParam("id") String id) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); MongoCursor<Document> cursorDocMap = null; if (ObjectId.isValid(id)) { System.out.println("" + "Valid hexadecimal representation of ObjectId " + id + ""); cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); } else { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Invalid hexadecimal representation of ObjectId " + id + ""); System.out.println("" + "Invalid hexadecimal representation of ObjectId " + id + ""); mongoClient.close(); return getResponse(GET, Response.Status.BAD_REQUEST, msg); } if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(GET, Response.Status.NOT_FOUND, msg); } while (cursorDocMap.hasNext()) { Map<String, Object> map = new HashMap<String, Object>(); Document doc = cursorDocMap.next(); logger.debug("Dataset ID: " + doc.get("_id") + ""); if (doc != null) { map.put("id", id); map.put("data", doc.get("data")); map.put("name", doc.get("name")); map.put("env", doc.get("env")); map.put("owner", doc.get("owner")); map.put("status", doc.get("status")); map.put("comments", doc.get("comments")); map.put("modifiedDate", doc.get("modifiedDate")); list.add(map); } } mongoClient.close(); return getResponse(GET, Response.Status.OK, list.get(0)); } @OPTIONS @Path("/{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response deleteDatasetPreflight() { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @DELETE @Path("/{id}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response deleteDataset(@PathParam("id") String id) { MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(DELETE, Response.Status.NOT_FOUND, msg); } while (cursorDocMap.hasNext()) { Document doc = cursorDocMap.next(); logger.debug("Dataset ID: " + doc.get("_id") + ""); collection.deleteOne(doc); } mongoClient.close(); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Successfully deleted dataset with ID: " + id); return getResponse(DELETE, Response.Status.OK, msg); } @DELETE @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response deleteAllDatasets() { collection.deleteMany(new Document()); mongoClient.close(); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Successfully deleted all datasets"); return getResponse(DELETE, Response.Status.OK, msg); } @PUT @Path("/{id}") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response updateDataset(@PathParam("id") String id, Dataset dataset) { Map<Integer, Map<String, Object>> original_values_map = new HashMap<Integer, Map<String, Object>>(); Map<Integer, Map<String, Object>> toupdate_values_map = new HashMap<Integer, Map<String, Object>>(); List<Object> list = null; List<Bson> firstLevelSets = new ArrayList<Bson>(); int changes = 0; // retrive the corresponding dataset with the given id MongoCursor<Document> cursorDocMap = null; if (ObjectId.isValid(id)) { System.out.println("" + "Valid hexadecimal representation of ObjectId " + id + ""); cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); } else { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Invalid hexadecimal representation of ObjectId " + id + ""); System.out.println("" + "Invalid hexadecimal representation of ObjectId " + id + ""); mongoClient.close(); return getResponse(PUT, Response.Status.BAD_REQUEST, msg); } if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(PUT, Response.Status.NOT_FOUND, msg); } while (cursorDocMap.hasNext()) { Document doc = cursorDocMap.next(); list = castList(doc.get("data"), Object.class); for (Object obj : list) { Map<?, ?> mObj = (Map<?, ?>)obj; Map<String, Object> tmp = new HashMap<String, Object>(); Iterator<?> it = mObj.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); tmp.put(key, mObj.get(key)); } original_values_map.put((Integer)tmp.get("code"), tmp); } logger.debug("Update: " + "casting property 'data' seems to have passed!" + ""); if (dataset.getName() != null && !dataset.getName().equals(doc.get("name"))) { firstLevelSets.add(set("name", dataset.getName())); ++changes; } if (dataset.getEnv() != null && !dataset.getEnv().equals(doc.get("env"))) { firstLevelSets.add(set("env", dataset.getEnv())); ++changes; } if (dataset.getOwner() != null && !dataset.getOwner().equals(doc.get("owner"))) { firstLevelSets.add(set("owner", dataset.getOwner())); ++changes; } if (dataset.getStatus() != null && !dataset.getStatus().equals(doc.get("status"))) { firstLevelSets.add(set("status", dataset.getStatus())); ++changes; } if (dataset.getComments() != null && !dataset.getComments().equals(doc.get("comments"))) { firstLevelSets.add(set("comments", dataset.getComments())); ++changes; } } List<Map<String, Object>> updates = dataset.getData(); for (Map<String, Object> map : updates) { toupdate_values_map.put((Integer)map.get("code"), map); logger.debug("Dataset: " + toupdate_values_map.get(map.get("code")) + ""); logger.debug("name: " + toupdate_values_map.get(map.get("code")).get("name") + ""); } Map<String, String> updateDatePair = new HashMap<String, String>(); updateDatePair.put("cfgCode", "cfgCodeUpdateDate" ); updateDatePair.put("comments", "" ); updateDatePair.put("containsAddedFat", "containsAddedFatUpdateDate" ); updateDatePair.put("containsAddedSodium", "containsAddedSodiumUpdateDate" ); updateDatePair.put("containsAddedSugar", "containsAddedSugarUpdateDate" ); updateDatePair.put("containsAddedTransfat", "containsAddedTransfatUpdateDate" ); updateDatePair.put("containsCaffeine", "containsCaffeineUpdateDate" ); updateDatePair.put("containsFreeSugars", "containsFreeSugarsUpdateDate" ); updateDatePair.put("containsSugarSubstitutes", "containsSugarSubstitutesUpdateDate" ); updateDatePair.put("foodGuideServingG", "foodGuideUpdateDate" ); updateDatePair.put("foodGuideServingMeasure", "foodGuideUpdateDate" ); updateDatePair.put("marketedToKids", "" ); updateDatePair.put("overrideSmallRaAdjustment", "" ); updateDatePair.put("replacementCode", "" ); updateDatePair.put("rolledUp", "rolledUpUpdateDate" ); updateDatePair.put("satfatAmountPer100g", "satfatImputationDate" ); updateDatePair.put("satfatImputationReference", "satfatImputationDate" ); updateDatePair.put("sodiumAmountPer100g", "sodiumImputationDate" ); updateDatePair.put("sodiumImputationReference", "sodiumImputationDate" ); updateDatePair.put("sugarAmountPer100g", "sugarImputationDate" ); updateDatePair.put("sugarImputationReference", "sugarImputationDate" ); updateDatePair.put("tier4ServingG", "tier4ServingUpdateDate" ); updateDatePair.put("tier4ServingMeasure", "tier4ServingUpdateDate" ); updateDatePair.put("totalFatAmountPer100g", "totalFatImputationDate" ); updateDatePair.put("totalFatImputationReference", "totalFatImputationDate" ); updateDatePair.put("transfatAmountPer100g", "transfatImputationDate" ); updateDatePair.put("transfatImputationReference", "transfatImputationDate" ); logger.debug(new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(updateDatePair)); for (Map<String, Object> map : updates) { List<Bson> sets = new ArrayList<Bson>(); logger.debug("size: " + sets.size() + ""); if (toupdate_values_map.get(map.get("code")).get("name") != null && !toupdate_values_map .get (map .get ("code")) .get ("name") .equals (original_values_map .get (map .get ("code")) .get ("name"))) { sets.add(set("data.$.name", map.get("name"))); ++changes; logger.debug("value changed: " + map.get("name") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("cnfGroupCode") != null && !toupdate_values_map .get (map .get ("code")) .get ("cnfGroupCode") .equals (original_values_map .get (map .get ("code")) .get ("cnfGroupCode"))) { sets.add(set("data.$.cnfGroupCode", map.get("cnfGroupCode"))); ++changes; logger.debug("value changed: " + map.get("cnfGroupCode") + ""); } for (String key : updateDatePair.keySet()) { changes = updateIfModified(key, updateDatePair.get(key), sets, changes, original_values_map, toupdate_values_map, map); } if (toupdate_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("cfgCodeUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("energyKcal") != null && !toupdate_values_map .get (map .get ("code")) .get ("energyKcal") .equals (original_values_map .get (map .get ("code")) .get ("energyKcal"))) { sets.add(set("data.$.energyKcal", map.get("energyKcal"))); ++changes; logger.debug("value changed: " + map.get("energyKcal") + ""); } logger.debug("" + "before: " + original_values_map .get (map .get ("code")) .get ("validated") + " - validated" + ""); logger.debug("" + " after: " + toupdate_values_map .get (map .get ("code")) .get ("validated") + " - validated" + ""); if (toupdate_values_map .get (map .get ("code")) .get ("validated") != null && !toupdate_values_map .get (map .get ("code")) .get ("validated") .equals (original_values_map .get (map .get ("code")) .get ("validated"))) { sets.add(set("data.$.validated", map.get("validated"))); ++changes; logger.debug("value changed: " + map.get("validated") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("sodiumImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("sodiumImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("sodiumImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("sugarImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("sugarImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("sugarImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("transfatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("transfatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("transfatImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("satfatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("satfatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("satfatImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("totalFatImputationDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("totalFatImputationDate") .equals (original_values_map .get (map .get ("code")) .get ("totalFatImputationDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedSodiumUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedSugarUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsFreeSugarsUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedFatUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsAddedTransfatUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsCaffeineUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("containsSugarSubstitutesUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountG") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountG") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountG"))) { sets.add(set("data.$.referenceAmountG", map.get("referenceAmountG"))); sets.add(currentDate("data.$.referenceAmountUpdateDate")); ++changes; logger.debug("value changed: " + map.get("referenceAmountG") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountMeasure") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountMeasure") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountMeasure"))) { sets.add(set("data.$.referenceAmountMeasure", map.get("referenceAmountMeasure"))); ++changes; logger.debug("value changed: " + map.get("referenceAmountMeasure") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("referenceAmountUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("foodGuideUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("tier4ServingUpdateDate"))) { } if (toupdate_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate") .equals (original_values_map .get (map .get ("code")) .get ("rolledUpUpdateDate"))) { } // if (toupdate_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment") != null && !toupdate_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment") .equals (original_values_map .get (map .get ("code")) .get ("overrideSmallRaAdjustment"))) { // sets.add(set("data.$.overrideSmallRaAdjustment", map.get("overrideSmallRaAdjustment"))); // ++changes; // logger.debug("value changed: " + map.get("overrideSmallRaAdjustment") + ""); // } if (toupdate_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount") != null && !toupdate_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount") .equals (original_values_map .get (map .get ("code")) .get ("adjustedReferenceAmount"))) { sets.add(set("data.$.adjustedReferenceAmount", map.get("adjustedReferenceAmount"))); ++changes; logger.debug("value changed: " + map.get("adjustedReferenceAmount") + ""); } if (toupdate_values_map .get (map .get ("code")) .get ("commitDate") != null && !toupdate_values_map .get (map .get ("code")) .get ("commitDate") .equals (original_values_map .get (map .get ("code")) .get ("commitDate"))) { } logger.debug("size: " + sets.size() + ""); logger.debug("code: " + map.get("code") + ""); if (sets.size() > 0) { collection.updateOne(and(eq("_id", new ObjectId(id)), eq("data.code", map.get("code"))), combine(sets)); } } if (changes != 0) { firstLevelSets.add(currentDate("modifiedDate")); collection.updateOne(eq("_id", new ObjectId(id)), combine(firstLevelSets)); } mongoClient.close(); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Successfully updated dataset"); return getResponse(PUT, Response.Status.OK, msg); } @OPTIONS @Path("/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response classifyDatasetPreflightOne(Dataset dataset) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @POST @Path("/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response classifyDataset(Dataset dataset) { Response response = null; Map<String, String> msg = new HashMap<String, String>(); if (dataset.getEnv().equals("sandbox")) { /** * * first, create a new transient dataset * */ Map<?, ?> tmp = (Map<?, ?>)saveDataset(dataset).getEntity(); Map<String, String> map = new HashMap<String, String>(); for (Entry<?, ?> entry : tmp.entrySet()) { map.put((String)entry.getKey(), (String)entry.getValue()); } String id = map.get("id"); /** * * second, with newly created ID, classify dataset * */ response = classifyDataset(id); /** * * third, delete transient dataset * */ deleteDataset(id); return response; } else { msg.put("message", "Invalid environment: " + dataset.getEnv() + ""); return getResponse(POST, Response.Status.BAD_REQUEST, msg); } } @OPTIONS @Path("/{id}/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response classifyDatasetPreflightTwo(String id) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "options-catch-all"); return getResponse(OPTIONS, Response.Status.OK, msg); } @POST @Path("/{id}/classify") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) @SuppressWarnings("unchecked") public Response classifyDataset(@PathParam("id") String id) { Map<String, Object> map = null; MongoCursor<Document> cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); List<Object> list = null; List<Document> dox = new ArrayList<Document>(); if (!cursorDocMap.hasNext()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Dataset with ID " + id + " does not exist!"); logger.debug("" + "Dataset with ID " + id + " does not exist!" + ""); mongoClient.close(); return getResponse(POST, Response.Status.NOT_FOUND, msg); } /** * * first server-side validation: required for classification * */ List<Map<String, Object>> dataToBeValidated = new ArrayList<Map<String, Object>>(); Map<String, String> requiredForClassification = new HashMap<String, String>(); requiredForClassification.put("type", "Scalar"); // Type Y CFG Indicates if the item is a Food or Recipe -- requiredForClassification.put("code", "Scalar"); // Code Y CNF/NSS CNF Food Code or NSS Recipe Code -- requiredForClassification.put("name", "Scalar"); // Name Y CNF/NSS Food or Recipe Name -- requiredForClassification.put("cfgCode", "Object"); // CFG Code Y (at least three digits) CFG Up to four digit CFG Code (includes tier, if available) -- requiredForClassification.put("sodiumAmountPer100g", "Object"); // Sodium Amount (per 100g) Y CNF/NSS Amount of Sodium per 100 g -- requiredForClassification.put("sugarAmountPer100g", "Object"); // Sugar Amount (per 100g) Y CNF/NSS Amount of Sugar per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. -- requiredForClassification.put("satfatAmountPer100g", "Object"); // SatFat Amount (per 100g) Y CNF/NSS Amount of Saturated Fat per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. -- requiredForClassification.put("totalFatAmountPer100g", "Object"); // TotalFat Amount (per 100g) Y CNF/NSS Amount of Total Fat per 100g - Provided by source database, unless blank in which case it can be filled in by CFG Classification. -- // requiredForClassification.put("containsAddedSodium", "Object"); // Contains Added Sodium Y CFG Indicates if the item contains added sodium -- // requiredForClassification.put("containsAddedSugar", "Object"); // Contains Added Sugar Y CFG Indicates if the item contains added sugar -- // requiredForClassification.put("containsAddedFat", "Object"); // Contains Added Fat Y CFG Indicates if the item contains added fat -- // requiredForClassification.put("referenceAmountG", "Scalar"); // Reference Amount (g) Y CNF/NSS -- // requiredForClassification.put("toddlerItem", "Scalar"); // Toddler Item Y CFG -- // requiredForClassification.put("overrideSmallRaAdjustment", "Object"); // Override Small RA Adjustment Y CFG Overrides the Small RA Adjustment that is made for foods that have RA lower than the Small RA Threshold (ie 30g) -- while (cursorDocMap.hasNext()) { Boolean isInvalid = false; Document doc = cursorDocMap.next(); if (doc != null) { list = castList(doc.get("data"), Object.class); for (Object obj : list) { Map<String, Object> requiredOnly = new HashMap<String, Object>(); for (String key : requiredForClassification.keySet()) { if (requiredForClassification.get(key).equals("Object")) { Document objectifiedValue = (Document)((Document)obj).get(key + ""); if (objectifiedValue.get("value") != null) { requiredOnly.put(key, objectifiedValue.get("value")); if (key.equals("cfgCode") && ((Integer)requiredOnly.get(key)).toString().length() != 3 && ((Integer)requiredOnly.get(key)).toString().length() != 4) { isInvalid = true; } } else { isInvalid = true; } } if (requiredForClassification.get(key).equals("Scalar")) { if (((Document)obj).get(key + "") != null) { requiredOnly.put(key, ((Document)obj).get(key + "")); } else { isInvalid = true; } } } dataToBeValidated.add(requiredOnly); } } // use validation rules on "data" property and return response if invalid logger.debug("" + "only required fields:\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(dataToBeValidated) + ""); if (isInvalid) { Map<String, String> msg = new HashMap<String, String>(); msg.put("message", "Expected required field(s) failed to pass validation in preparation for classification."); return getResponse(POST, Response.Status.EXPECTATION_FAILED, msg); } } /** * * rewind dataset to do the actual classification * */ cursorDocMap = collection.find(new Document("_id", new ObjectId(id))).iterator(); /** * * objectified properties * */ Map<String, String> updateDatePair = new HashMap<String, String>(); updateDatePair.put("cfgCode", "cfgCodeUpdateDate" ); updateDatePair.put("comments", "" ); updateDatePair.put("containsAddedFat", "containsAddedFatUpdateDate" ); updateDatePair.put("containsAddedSodium", "containsAddedSodiumUpdateDate" ); updateDatePair.put("containsAddedSugar", "containsAddedSugarUpdateDate" ); updateDatePair.put("containsAddedTransfat", "containsAddedTransfatUpdateDate" ); updateDatePair.put("containsCaffeine", "containsCaffeineUpdateDate" ); updateDatePair.put("containsFreeSugars", "containsFreeSugarsUpdateDate" ); updateDatePair.put("containsSugarSubstitutes", "containsSugarSubstitutesUpdateDate" ); updateDatePair.put("foodGuideServingG", "foodGuideUpdateDate" ); updateDatePair.put("foodGuideServingMeasure", "foodGuideUpdateDate" ); updateDatePair.put("marketedToKids", "" ); updateDatePair.put("overrideSmallRaAdjustment", "" ); updateDatePair.put("replacementCode", "" ); updateDatePair.put("rolledUp", "rolledUpUpdateDate" ); updateDatePair.put("satfatAmountPer100g", "satfatImputationDate" ); updateDatePair.put("satfatImputationReference", "satfatImputationDate" ); updateDatePair.put("sodiumAmountPer100g", "sodiumImputationDate" ); updateDatePair.put("sodiumImputationReference", "sodiumImputationDate" ); updateDatePair.put("sugarAmountPer100g", "sugarImputationDate" ); updateDatePair.put("sugarImputationReference", "sugarImputationDate" ); updateDatePair.put("tier4ServingG", "tier4ServingUpdateDate" ); updateDatePair.put("tier4ServingMeasure", "tier4ServingUpdateDate" ); updateDatePair.put("totalFatAmountPer100g", "totalFatImputationDate" ); updateDatePair.put("totalFatImputationReference", "totalFatImputationDate" ); updateDatePair.put("transfatAmountPer100g", "transfatImputationDate" ); updateDatePair.put("transfatImputationReference", "transfatImputationDate" ); /** * * only transform objectified values to literal values * */ while (cursorDocMap.hasNext()) { Document doc = cursorDocMap.next(); map = new HashMap<String, Object>(); logger.debug("Dataset ID: " + doc.get("_id") + ""); if (doc != null) { list = castList(doc.get("data"), Object.class); for (Object obj : list) { for (String key : updateDatePair.keySet()) { Document objectifiedValue = (Document)((Document)obj).get(key + ""); ((Document)obj).put(key, objectifiedValue.get("value")); } dox.add((Document)obj); } map.put("data", dox); map.put("name", doc.get("name")); map.put("env", doc.get("env")); map.put("owner", doc.get("owner")); map.put("status", doc.get("status")); map.put("comments", doc.get("comments")); map.put("modifiedDate", doc.get("modifiedDate")); } } // mongoClient.close(); // String target = "http://" + request.getServerName() + ":" + request.getServerPort() + ClassificationProperties.getEndPoint(); String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-"); // logger.debug("" + "request URI : " + RequestURI.getUri() + ""); logger.debug("" + "request URI : " + request.getRequestURI() + ""); logger.debug("" + "request URL : " + request.getRequestURL() + ""); logger.debug("" + "request target : " + request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-") + ""); logger.debug("" + "request Name : " + request.getServerName() + ""); logger.debug("" + "request Port : " + request.getServerPort() + ""); logger.debug("" + "request Protocol : " + request.getProtocol() + ""); logger.debug("" + "request target : " + target + ""); SSLContext sslcontext = null; try { sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new java.security.SecureRandom()); } catch(NoSuchAlgorithmException nsae) { } catch(KeyManagementException kme) { } Response response = ClientBuilder .newBuilder() .sslContext(sslcontext) .build() .target(target) .path("/classify") .request() .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE) .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(map, MediaType.APPLICATION_JSON)); logger.debug("" + "response status : " + response.getStatusInfo() + ""); Map<String, Object> deserialized = (Map<String, Object>)response.readEntity(Object.class); List<Object> dataArray = (List<Object>)(deserialized).get("data"); for (Object obj : dataArray) { for (String key : updateDatePair.keySet()) { Object value = ((Map<String, Object>)obj).get(key + ""); Map<String, Object> metadataObject = new HashMap<String, Object>(); metadataObject.put("value", value); metadataObject.put("modified", false); ((Map<String, Object>)obj).put(key, metadataObject); } } deserialized.put("id", id); logger.debug("" + "response status: " + ((Map<String, Object>)dataArray.get(0)).get("sodiumAmountPer100g") + ""); logger.debug("" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(deserialized) + ""); return getResponse(POST, Response.Status.OK, deserialized); } @POST @Path("/{id}/flags") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response flagsDataset(@PathParam("id") String id, Dataset dataset) { Response response = ClientBuilder .newClient() .target(RequestURI.getUri() + ClassificationProperties.getEndPoint()) .path("/flags") .request() .post(Entity.entity(dataset, MediaType.APPLICATION_JSON)); return response; } @POST @Path("/{id}/init") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response initDataset(@PathParam("id") String id, Dataset dataset) { Response response = ClientBuilder .newClient() .target(RequestURI.getUri() + ClassificationProperties.getEndPoint()) .path("/init") .request() .post(Entity.entity(dataset, MediaType.APPLICATION_JSON)); return response; } @POST @Path("/{id}/adjustment") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response adjustmentDataset(@PathParam("id") String id, Dataset dataset) { Response response = ClientBuilder .newClient() .target(RequestURI.getUri() + ClassificationProperties.getEndPoint()) .path("/adjustment") .request() .post(Entity.entity(dataset, MediaType.APPLICATION_JSON)); return response; } @POST @Path("/{id}/commit") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public void commitDataset() { } @GET @Path("/status") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response getStatusCodes() { Map<Integer, String> list = new HashMap<Integer, String>(); String sql = ContentHandler.read("schema_test.sql", getClass()); Map<Integer, String> map = new HashMap<Integer, String>(); for (Response.Status obj : Response.Status.values()) { map.put(obj.getStatusCode(), obj.name()); } int len = 0; for (Integer key : map.keySet()) { String value = map.get(key); if (value.length() > len) { len = value.length(); } } String format = new StringBuffer() .append(" %d %-") .append(len) .append("s") .toString(); // String tamrof = new StringBuffer() // .append("%-") // .append(len + 6) // .append("s") // .toString(); Integer[][] arr = new Integer[6][18]; Integer[][] brr = new Integer[2][18]; Integer series = 0; int i = 0; int k = 0; for (Integer key : map.keySet()) { if (key / 100 != series) { series = key / 100; i = 0; } if (series == 4) { brr[0][i] = key; } else { brr[1][k++] = key; } arr[series][i++] = key; } for (int j = 0; j < 18; ++j) { arr[0][j] = null; arr[1][j] = null; } for (int l = 0; l < 18; ++l) { for (int m = 0; m < 2; ++m) { Integer key = brr[m][l]; System.out.printf("[01;03;%dm" + format + "", l % 2 == 0 ? 34 : 31, key, Response.Status.fromStatusCode(key)); } System.out.println(); } try { if (conn != null) { PreparedStatement stmt = conn.prepareStatement(sql); // Create PreparedStatement ResultSet rs = stmt.executeQuery(); while (rs.next()) { list.put(rs.getInt("canada_food_guide_food_item_count"), rs.getString("canada_food_guide_food_item_desc")); } sql = ContentHandler.read("connectivity_test.sql", getClass()); stmt = conn.prepareStatement(sql); // Create PreparedStatement rs = stmt.executeQuery(); while (rs.next()) { list.put(rs.getInt("canada_food_group_id"), rs.getString("canada_food_group_desc_e")); } list.put(666, "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version")); conn.close(); } else { list.put(Response.Status.SERVICE_UNAVAILABLE.getStatusCode(), "PostgreSQL database connectivity test: failed - service unavailable"); return getResponse(GET, Response.Status.SERVICE_UNAVAILABLE, list); } } catch(SQLException e) { // TODO: proper response to handle exceptions logger.debug("" + e.getMessage() + ""); for (Response.Status status : Response.Status.values()) { list.put(new Integer(status.getStatusCode()), status.getReasonPhrase()); } list.put(666, "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version")); } try { logger.debug("" + "new mongo connectivity test: " + mongoClient.getAddress() + ""); logger.debug("" + "new mongo connectivity test: " + mongoClient.getConnectPoint() + ""); logger.debug("" + "new mongo connectivity test: " + mongoClient.getDatabase(MongoClientFactory.getDatabase()).runCommand(new Document("buildInfo", 1)).getString("version") + ""); } catch(Exception e) { // TODO: proper response to handle exceptions Map<String, String> msg = new HashMap<String, String>(); msg.put("message", e.getMessage()); logger.debug("" + e.getMessage() + ""); mongoClient.close(); return getResponse(GET, Response.Status.GATEWAY_TIMEOUT, msg); } mongoClient.close(); // return getResponse(GET, Response.Status.OK, Response.Status.values()); return getResponse(GET, Response.Status.OK, list); } private /* List<CanadaFoodGuideFoodItem> */ Response doSearchCriteria(CfgFilter search) { List<CanadaFoodGuideFoodItem> list = new ArrayList<CanadaFoodGuideFoodItem>(); if (search != null) { StringBuffer sb = new StringBuffer(search.getSql()); logger.debug("" + search.getDataSource() + ""); sb.append(" WHERE length('this where-clause is an artifact') = 32").append("\n"); if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) { sb.append(" AND type = ?").append("\n"); } logger.debug("" + search.getFoodRecipeName() + ""); if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) { sb.append(" AND LOWER(name) LIKE ?").append("\n"); } logger.debug("" + search.getFoodRecipeCode() + ""); if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) { sb.append(" AND code = ? OR CAST(code AS text) LIKE ?").append("\n"); } logger.debug("" + search.getCnfCode() + ""); if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) { sb.append(" AND cnf_group_code = ?").append("\n"); } logger.debug("" + search.getSubgroupCode() + ""); if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) { sb.append(" AND CAST(cfg_code AS text) LIKE ?").append("\n"); } if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) { switch (search.getCfgTier()) { case 1: case 2: case 3: case 4: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 12: case 13: case 14: case 23: case 24: case 34: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 123: case 124: case 134: case 234: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 1234: logger.debug("Calling all codes with Tier " + search.getCfgTier() + ""); sb.append(" AND LENGTH(CAST(cfg_code AS text)) = 4").append("\n"); sb.append(" AND CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); sb.append(" OR CAST(SUBSTR(CAST(cfg_code AS text), 4, 1) AS integer) = ?").append("\n"); break; case 9: logger.debug("Calling all codes with missing Tier!"); sb.append(" AND LENGTH(CAST(cfg_code AS text)) < 4").append("\n"); break; } } if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) { logger.debug("" + search.getRecipe() + ""); switch (search.getRecipe()) { case 1: case 2: sb.append(" AND rolled_up = ?").append("\n"); break; case 3: sb.append(" AND (rolled_up = 1 OR rolled_up = 2)").append("\n"); break; } } boolean notIgnore = false; if (search.getContainsAdded() != null) { String[] arr = new String[search.getContainsAdded().size()]; arr = search.getContainsAdded().toArray(arr); for (String i : arr) { logger.debug("" + i + ""); if (!i.equals("0")) { notIgnore = true; } } } Map<String, String> map = null; if (search.getContainsAdded() != null && notIgnore) { map = new HashMap<String, String>(); logger.debug("" + search.getContainsAdded() + ""); String[] arr = new String[search.getContainsAdded().size()]; arr = search.getContainsAdded().toArray(arr); for (String keyValue : arr) { StringTokenizer tokenizer = new StringTokenizer(keyValue, "="); map.put(tokenizer.nextToken(), tokenizer.nextToken()); logger.debug("" + keyValue + ""); } logger.debug("\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + ""); Set<String> keys = map.keySet(); for (String key : keys) { switch (ContainsAdded.valueOf(key)) { case sodium: sb.append(" AND contains_added_sodium = ? ").append("\n"); break; case sugar: sb.append(" AND contains_added_sugar = ? ").append("\n"); break; case fat: sb.append(" AND contains_added_fat = ? ").append("\n"); break; case transfat: sb.append(" AND contains_added_transfat = ? ").append("\n"); break; case caffeine: sb.append(" AND contains_caffeine = ? ").append("\n"); break; case freeSugars: sb.append(" AND contains_free_sugars = ? ").append("\n"); break; case sugarSubstitute: sb.append(" AND contains_sugar_substitutes = ? ").append("\n"); break; } } } if (search.getMissingValues() != null) { logger.debug("" + search.getMissingValues() + ""); logger.debug("\n" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(search.getMissingValues()) + ""); for (String name : search.getMissingValues()) { switch (Missing.valueOf(name)) { case refAmount: sb.append(" AND reference_amount_g IS NULL").append("\n"); break; case cfgServing: sb.append(" AND food_guide_serving_g IS NULL").append("\n"); break; case tier4Serving: sb.append(" AND tier_4_serving_g IS NULL").append("\n"); break; case energy: sb.append(" AND energy_kcal IS NULL").append("\n"); break; case cnfCode: sb.append(" AND cnf_group_code IS NULL").append("\n"); break; case rollUp: sb.append(" AND rolled_up IS NULL").append("\n"); break; case sodiumPer100g: sb.append(" AND sodium_amount_per_100g IS NULL").append("\n"); break; case sugarPer100g: sb.append(" AND sugar_amount_per_100g IS NULL").append("\n"); break; case fatPer100g: sb.append(" AND totalfat_amount_per_100g IS NULL").append("\n"); break; case transfatPer100g: sb.append(" AND transfat_amount_per_100g IS NULL").append("\n"); break; case satFatPer100g: sb.append(" AND satfat_amount_per_100g IS NULL").append("\n"); break; case addedSodium: sb.append(" AND contains_added_sodium IS NULL").append("\n"); break; case addedSugar: sb.append(" AND contains_added_sugar IS NULL").append("\n"); break; case addedFat: sb.append(" AND contains_added_fat IS NULL").append("\n"); break; case addedTransfat: sb.append(" AND contains_added_transfat IS NULL").append("\n"); break; case caffeine: sb.append(" AND contains_caffeine IS NULL").append("\n"); break; case freeSugars: sb.append(" AND contains_free_sugars IS NULL").append("\n"); break; case sugarSubstitute: sb.append(" AND contains_sugar_substitutes IS NULL").append("\n"); break; } } } if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { if (search.getLastUpdatedFilter() != null) { logger.debug("" + search.getLastUpdatedFilter() + ""); for (String name : search.getLastUpdatedFilter()) { switch (Missing.valueOf(name)) { case refAmount: sb.append(" AND reference_amount_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case cfgServing: sb.append(" AND food_guide_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case tier4Serving: sb.append(" AND tier_4_serving_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case energy: case cnfCode: break; case rollUp: sb.append(" AND rolled_up_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case sodiumPer100g: sb.append(" AND sodium_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case sugarPer100g: sb.append(" AND sugar_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case fatPer100g: sb.append(" AND totalfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case transfatPer100g: sb.append(" AND transfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case satFatPer100g: sb.append(" AND satfat_imputation_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedSodium: sb.append(" AND contains_added_sodium_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedSugar: sb.append(" AND contains_added_sugar_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedFat: sb.append(" AND contains_added_fat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case addedTransfat: sb.append(" AND contains_added_transfat_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case caffeine: sb.append(" AND contains_caffeine_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case freeSugars: sb.append(" AND contains_free_sugars_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; case sugarSubstitute: sb.append(" AND contains_sugar_substitutes_update_date BETWEEN CAST(? AS date) AND CAST(? AS date)").append("\n"); break; } } } } if (search.getComments() != null && !search.getComments().isEmpty()) { sb.append(" AND LOWER(comments) LIKE ?").append("\n"); } if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { sb.append(" AND commit_date BETWEEN CAST(? AS date) AND CAST(? AS date)") .append("\n"); } search.setSql(sb.toString()); try { meta = conn.getMetaData(); // Create Oracle DatabaseMetaData object logger.debug("JDBC driver version is " + meta.getDriverVersion() + ""); // Retrieve driver information PreparedStatement stmt = conn.prepareStatement(search.getSql(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Create PreparedStatement int i = 0; // keeps count of the number of placeholders if (search != null) { if (search.getDataSource() != null && search.getDataSource().matches("food|recipe")) { stmt.setInt(++i, search.getDataSource().equals("food") ? 1 : 2); } if (search.getFoodRecipeName() != null && !search.getFoodRecipeName().isEmpty()) { stmt.setString(++i, new String("%" + search.getFoodRecipeName() + "%").toLowerCase()); } if (search.getFoodRecipeCode() != null && !search.getFoodRecipeCode().isEmpty()) { stmt.setInt(++i, Integer.parseInt(search.getFoodRecipeCode())); stmt.setString(++i, new String("" + search.getFoodRecipeCode() + "%")); } if (search.getCnfCode() != null && !search.getCnfCode().isEmpty()) { stmt.setInt(++i, Integer.parseInt(search.getCnfCode())); } if (search.getSubgroupCode() != null && !search.getSubgroupCode().isEmpty()) { stmt.setString(++i, new String("" + search.getSubgroupCode() + "%")); } if (search.getCfgTier() != null && !search.getCfgTier().equals(CfgTier.ALL.getCode())) { switch (search.getCfgTier()) { case 1: case 2: case 3: case 4: stmt.setInt(++i, search.getCfgTier()); break; } } if (search.getRecipe() != null && !search.getRecipe().equals(RecipeRolled.IGNORE.getCode())) { switch (search.getRecipe()) { case 1: case 2: stmt.setInt(++i, search.getRecipe()); break; } } if (search.getContainsAdded() != null && notIgnore) { Set<String> keys = map.keySet(); for (String key : keys) { switch (ContainsAdded.valueOf(key)) { case sodium: case sugar: case fat: case transfat: case caffeine: case freeSugars: case sugarSubstitute: stmt.setBoolean(++i, map.get(key).equals("true")); break; } } } if (search.getLastUpdateDateFrom() != null && search.getLastUpdateDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getLastUpdateDateTo() != null && search.getLastUpdateDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { if (search.getLastUpdatedFilter() != null) { logger.debug("" + search.getLastUpdatedFilter() + ""); for (String name : search.getLastUpdatedFilter()) { switch (Missing.valueOf(name)) { case refAmount: case cfgServing: case tier4Serving: stmt.setString(++i, search.getLastUpdateDateFrom()); stmt.setString(++i, search.getLastUpdateDateTo()); break; case energy: case cnfCode: break; case rollUp: case sodiumPer100g: case sugarPer100g: case fatPer100g: case transfatPer100g: case satFatPer100g: case addedSodium: case addedSugar: case addedFat: case addedTransfat: case caffeine: case freeSugars: case sugarSubstitute: stmt.setString(++i, search.getLastUpdateDateFrom()); stmt.setString(++i, search.getLastUpdateDateTo()); break; } } } } if (search.getComments() != null && !search.getComments().isEmpty()) { stmt.setString(++i, new String("%" + search.getComments() + "%").toLowerCase()); } if (search.getCommitDateFrom() != null && search.getCommitDateFrom().matches("\\d{4}-\\d{2}-\\d{2}") && search.getCommitDateTo() != null && search.getCommitDateTo().matches("\\d{4}-\\d{2}-\\d{2}")) { stmt.setString(++i, search.getCommitDateFrom()); stmt.setString(++i, search.getCommitDateTo()); } } logger.debug("SQL query to follow:\n" + stmt.toString() + ""); ResultSet rs = stmt.executeQuery(); rs.last(); logger.debug("" + rs.getRow() + " row" + (rs.getRow() == 1 ? "" : "s") + ""); rs.beforeFirst(); while (rs.next()) { CanadaFoodGuideFoodItem foodItem = new CanadaFoodGuideFoodItem(); foodItem.setType(rs.getInt ("type") == 1 ? "food" : "recipe" ); foodItem.setCode(rs.getInt ("code") ); foodItem.setName(rs.getString ("name") ); if (rs.getString("cnf_group_code") != null) { foodItem.setCnfGroupCode(rs.getInt ("cnf_group_code") ); } if (rs.getString("cfg_code") != null) { foodItem.setCfgCode(new PseudoInteger(rs.getInt ("cfg_code")) ); // editable } else { foodItem.setCfgCode(new PseudoInteger() ); } foodItem.setCommitDate(rs.getDate ("cfg_code_update_date") ); if (rs.getString("energy_kcal") != null) { foodItem.setEnergyKcal(rs.getDouble ("energy_kcal") ); } if (rs.getString("sodium_amount_per_100g") != null) { foodItem.setSodiumAmountPer100g(new PseudoDouble(rs.getDouble ("sodium_amount_per_100g")) ); // editable } else { foodItem.setSodiumAmountPer100g(new PseudoDouble() ); } foodItem.setSodiumImputationReference(new PseudoString(rs.getString ("sodium_imputation_reference")) ); foodItem.setSodiumImputationDate(rs.getDate ("sodium_imputation_date") ); if (rs.getString("sugar_amount_per_100g") != null) { foodItem.setSugarAmountPer100g(new PseudoDouble(rs.getDouble ("sugar_amount_per_100g")) ); // editable } else { foodItem.setSugarAmountPer100g(new PseudoDouble() ); } foodItem.setSugarImputationReference(new PseudoString(rs.getString ("sugar_imputation_reference")) ); foodItem.setSugarImputationDate(rs.getDate ("sugar_imputation_date") ); if (rs.getString("transfat_amount_per_100g") != null) { foodItem.setTransfatAmountPer100g(new PseudoDouble(rs.getDouble ("transfat_amount_per_100g")) ); // editable } else { foodItem.setTransfatAmountPer100g(new PseudoDouble() ); } foodItem.setTransfatImputationReference(new PseudoString(rs.getString ("transfat_imputation_reference")) ); foodItem.setTransfatImputationDate(rs.getDate ("transfat_imputation_date") ); if (rs.getString("satfat_amount_per_100g") != null) { foodItem.setSatfatAmountPer100g(new PseudoDouble(rs.getDouble ("satfat_amount_per_100g")) ); // editable } else { foodItem.setSatfatAmountPer100g(new PseudoDouble() ); } foodItem.setSatfatImputationReference(new PseudoString(rs.getString ("satfat_imputation_reference")) ); foodItem.setSatfatImputationDate(rs.getDate ("satfat_imputation_date") ); if (rs.getString("totalfat_amount_per_100g") != null) { foodItem.setTotalFatAmountPer100g(new PseudoDouble(rs.getDouble ("totalfat_amount_per_100g")) ); // editable } else { foodItem.setTotalFatAmountPer100g(new PseudoDouble() ); } foodItem.setTotalFatImputationReference(new PseudoString(rs.getString ("totalfat_imputation_reference")) ); foodItem.setTotalFatImputationDate(rs.getDate ("totalfat_imputation_date") ); if (rs.getString("contains_added_sodium") != null) { foodItem.setContainsAddedSodium(new PseudoBoolean(rs.getBoolean ("contains_added_sodium")) ); // editable } else { foodItem.setContainsAddedSodium(new PseudoBoolean() ); } foodItem.setContainsAddedSodiumUpdateDate(rs.getDate ("contains_added_sodium_update_date") ); if (rs.getString("contains_added_sugar") != null) { foodItem.setContainsAddedSugar(new PseudoBoolean(rs.getBoolean ("contains_added_sugar")) ); // editable } else { foodItem.setContainsAddedSugar(new PseudoBoolean() ); } foodItem.setContainsAddedSugarUpdateDate(rs.getDate ("contains_added_sugar_update_date") ); if (rs.getString("contains_free_sugars") != null) { foodItem.setContainsFreeSugars(new PseudoBoolean(rs.getBoolean ("contains_free_sugars")) ); // editable } else { foodItem.setContainsFreeSugars(new PseudoBoolean() ); } foodItem.setContainsFreeSugarsUpdateDate(rs.getDate ("contains_free_sugars_update_date") ); if (rs.getString("contains_added_fat") != null) { foodItem.setContainsAddedFat(new PseudoBoolean(rs.getBoolean ("contains_added_fat")) ); // editable } else { foodItem.setContainsAddedFat(new PseudoBoolean() ); } foodItem.setContainsAddedFatUpdateDate(rs.getDate ("contains_added_fat_update_date") ); if (rs.getString("contains_added_transfat") != null) { foodItem.setContainsAddedTransfat(new PseudoBoolean(rs.getBoolean ("contains_added_transfat")) ); // editable } else { foodItem.setContainsAddedTransfat(new PseudoBoolean() ); } foodItem.setContainsAddedTransfatUpdateDate(rs.getDate ("contains_added_transfat_update_date") ); if (rs.getString("contains_caffeine") != null) { foodItem.setContainsCaffeine(new PseudoBoolean(rs.getBoolean ("contains_caffeine")) ); // editable } else { foodItem.setContainsCaffeine(new PseudoBoolean() ); } foodItem.setContainsCaffeineUpdateDate(rs.getDate ("contains_caffeine_update_date") ); if (rs.getString("contains_sugar_substitutes") != null) { foodItem.setContainsSugarSubstitutes(new PseudoBoolean(rs.getBoolean ("contains_sugar_substitutes")) ); // editable } else { foodItem.setContainsSugarSubstitutes(new PseudoBoolean() ); } foodItem.setContainsSugarSubstitutesUpdateDate(rs.getDate ("contains_sugar_substitutes_update_date") ); if (rs.getString("reference_amount_g") != null) { foodItem.setReferenceAmountG(rs.getDouble ("reference_amount_g") ); // editable } foodItem.setReferenceAmountMeasure(rs.getString ("reference_amount_measure") ); // foodItem.setReferenceAmountUpdateDate(rs.getDate ("reference_amount_update_date") ); if (rs.getString("food_guide_serving_g") != null) { foodItem.setFoodGuideServingG(new PseudoDouble(rs.getDouble ("food_guide_serving_g")) ); // editable } else { foodItem.setFoodGuideServingG(new PseudoDouble() ); } foodItem.setFoodGuideServingMeasure(new PseudoString(rs.getString ("food_guide_serving_measure")) ); foodItem.setFoodGuideUpdateDate(rs.getDate ("food_guide_update_date") ); if (rs.getString("tier_4_serving_g") != null) { foodItem.setTier4ServingG(new PseudoDouble(rs.getDouble ("tier_4_serving_g")) ); // editable } else { foodItem.setTier4ServingG(new PseudoDouble() ); } foodItem.setTier4ServingMeasure(new PseudoString(rs.getString ("tier_4_serving_measure")) ); foodItem.setTier4ServingUpdateDate(rs.getDate ("tier_4_serving_update_date") ); if (rs.getString("rolled_up") != null) { foodItem.setRolledUp(new PseudoBoolean(rs.getBoolean ("rolled_up")) ); // editable } else { foodItem.setRolledUp(new PseudoBoolean() ); } foodItem.setRolledUpUpdateDate(rs.getDate ("rolled_up_update_date") ); if (rs.getString("override_small_ra_adjustment") != null) { foodItem.setOverrideSmallRaAdjustment(new PseudoBoolean(rs.getBoolean ("override_small_ra_adjustment")) ); } else { foodItem.setOverrideSmallRaAdjustment(new PseudoBoolean() ); } if (rs.getString("replacement_code") != null) { foodItem.setReplacementCode(new PseudoInteger(rs.getInt ("replacement_code")) ); // editable } else { foodItem.setReplacementCode(new PseudoInteger() ); } foodItem.setCommitDate(rs.getDate ("commit_date") ); foodItem.setComments(new PseudoString(rs.getString ("comments")) ); // editable foodItem.setValidated( false ); list.add(foodItem); } conn.close(); } catch(SQLException e) { // TODO: proper response to handle exceptions logger.debug("" + "" + e.getMessage() + ""); Map<String, String> msg = new HashMap<String, String>(); msg.put("message", e.getMessage()); return getResponse(GET, Response.Status.SERVICE_UNAVAILABLE, msg); } } return getResponse(GET, Response.Status.OK, list); } // public static Client IgnoreSSLClient() throws Exception { // SSLContext sslcontext = SSLContext.getInstance("TLS"); // sslcontext.init(null, new TrustManager[] { // new X509TrustManager() { // public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} // public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} // public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } // } // }, new java.security.SecureRandom()); // return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((s1, s2) -> true).build(); // } public static Response getResponse(String method, Response.Status status, Object obj) { List<String> allowedHttpOrigins = null; List<String> allowedHttpHeaders = null; List<String> allowedHttpMethods = null; List<String> requestHttpMethods = null; allowedHttpOrigins = new ArrayList<String>(); allowedHttpOrigins.add("*"); // allowedHttpOrigins.add("http://10.148.178.250"); allowedHttpHeaders = new ArrayList<String>(); allowedHttpHeaders.add(ORIGIN); allowedHttpHeaders.add(CONTENT_TYPE); allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_HEADERS); allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_METHODS); allowedHttpHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN); allowedHttpHeaders.add(X_REQUESTED_WITH); allowedHttpHeaders.add(ACCEPT); allowedHttpHeaders.add(AUTHORIZATION); allowedHttpMethods = new ArrayList<String>(); allowedHttpMethods.add(GET); allowedHttpMethods.add(POST); allowedHttpMethods.add(OPTIONS); allowedHttpMethods.add(DELETE); allowedHttpMethods.add(PUT); allowedHttpMethods.add(HEAD); requestHttpMethods = new ArrayList<String>(); requestHttpMethods.add(GET); requestHttpMethods.add(POST); requestHttpMethods.add(OPTIONS); requestHttpMethods.add(DELETE); logger.printf(DEBUG, "%s%-29s: %s%s", "", ACCESS_CONTROL_ALLOW_ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", "), ""); logger.printf(DEBUG, "%s%-29s: %s%s", "", ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", "), ""); logger.printf(DEBUG, "%s%-29s: %s%s", "", ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowedHttpMethods.toArray(), ", "), ""); ResponseBuilder rb = Response.status(status); // rb.header( ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", ")); // rb.header(ACCESS_CONTROL_ALLOW_ORIGIN, StringUtils.join(allowedHttpOrigins.toArray(), ", ")); // rb.header(ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", ")); // rb.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); // rb.header(ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowedHttpMethods.toArray(), ", ")); // if (method.equals(OPTIONS)) { // rb.header(ACCESS_CONTROL_REQUEST_METHOD, StringUtils.join(requestHttpMethods.toArray(), ", ")); // rb.header(ACCESS_CONTROL_REQUEST_HEADERS, StringUtils.join(allowedHttpHeaders.toArray(), ", ")); // rb.header(CONTENT_TYPE, MediaType.APPLICATION_JSON); // } // rb.header(ACCESS_CONTROL_MAX_AGE, "1209600"); return rb.entity(obj).build(); } private static <T> List<T> castList(Object obj, Class<T> clazz) { List<T> result = new ArrayList<T>(); if (obj instanceof List<?>) { for (Object o : (List<?>)obj) { result.add(clazz.cast(o)); } return result; } return null; } @SuppressWarnings("unchecked") private int updateIfModified(String key, String value, List<Bson> sets, int changes, Map<Integer, Map<String, Object>> original_values_map, Map<Integer, Map<String, Object>> toupdate_values_map, Map<String, Object> map) { logger.debug("" + "key/value - " + key + ": " + ((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value") + ""); if (((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value") != null && !((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("value").equals(((Map<String, Object>)original_values_map.get(map.get("code")).get(key)).get("value"))) { sets.add(set("data.$." + key + ".value", ((Map<String, Object>)map.get(key)).get("value"))); if (!value.isEmpty()) { sets.add(currentDate("data.$." + value)); } ++changes; logger.debug("value changed: " + ((Map<String, Object>)map.get(key)).get("value") + ""); } if (((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("modified") != null && !((Map<String, Object>)toupdate_values_map.get(map.get("code")).get(key)).get("modified").equals(((Map<String, Object>)original_values_map.get(map.get("code")).get(key)).get("modified"))) { sets.add(set("data.$." + key + ".modified", ((Map<String, Object>)map.get(key)).get("modified"))); } return changes; } }
Removed client properties in particular FOLLOW_REDIRECTS
src/main/java/ca/gc/ip346/classification/resource/FoodsResource.java
Removed client properties in particular FOLLOW_REDIRECTS
<ide><path>rc/main/java/ca/gc/ip346/classification/resource/FoodsResource.java <ide> } catch(KeyManagementException kme) { <ide> } <ide> <del> Response response = <del> ClientBuilder <add> Response response = ClientBuilder <ide> .newBuilder() <ide> .sslContext(sslcontext) <ide> .build() <ide> .target(target) <ide> .path("/classify") <ide> .request() <del> .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE) <add> // .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE) <ide> .accept(MediaType.APPLICATION_JSON) <ide> .post(Entity.entity(map, MediaType.APPLICATION_JSON)); <ide>
JavaScript
mit
9260cf778bd7311e0339b3622bd69eeb3253c5d5
0
xcv58/atom-autohide-tree-view,modulexcite/atom-autohide-tree-view,olmokramer/atom-autohide-tree-view
'use babel'; import SubAtom from 'sub-atom'; // some generic functions function logError(error) { console.error(error.message); } function getConfig(key, ns = 'autohide-tree-view') { return atom.config.get(`${ns}.${key}`); } function setConfig(key, value, ns = 'autohide-tree-view') { atom.config.set(`${ns}.${key}`, value); } function toggleConfig(key, ns) { setConfig(key, !getConfig(key, ns), ns); } function isChildOf(childNode, parentNode) { while(childNode != parentNode && childNode != document.body) { childNode = childNode.parentNode; } return childNode == parentNode; } // private API var disposables, enabled; function enable() { if(enabled) return; enabled = true; disposables = new SubAtom(); // wait until the tree view package is activated atom.packages.activatePackage('tree-view').then(function(treeViewPkg) { registerTreeView(treeViewPkg); handleEvents(); // start with pushEditor = true, we'll change it back later return update(true); }).then(function() { return update(); }).catch(logError); } function disable() { if(!enabled) return; enabled = false; disposables.dispose(); // the stylesheet will be removed before the animation is finished // making it look ugly... set minWidth on the element to prevent this treeViewEl.style.minWidth = '1px'; // update with pushEditor = true for a nicer animation update(true).then(function() { // show the tree view return show(); }).then(function() { // finally dispose of the tree view and reset all used variables resetTreeView(); [ disposables, enabled, visible, focusedElement, hoverEventsEnabled, currentSwipe, currentAnimation ] = []; }).catch(logError); } var treeView, treeViewEl; // keep references to the tree view model and element function registerTreeView(treeViewPkg) { treeView = treeViewPkg.mainModule.createView(); treeViewEl = treeView.element; treeViewEl.classList.add('autohide'); } // reset the styles etc. on the tree view function resetTreeView() { treeViewEl.classList.remove('autohide'); treeViewEl.style.position = ''; treeViewEl.style.minWidth = ''; treeView.scroller[0].style.display = ''; var panelView = atom.views.getView(treeView.panel); if(panelView) { panelView.style.width = ''; } [treeView, treeViewEl] = []; } function handleEvents() { // changes to these settings should trigger an update disposables.add(atom.config.onDidChange('autohide-tree-view.pushEditor', update)); disposables.add(atom.config.onDidChange('autohide-tree-view.hiddenWidth', update)); disposables.add(atom.config.onDidChange('tree-view.showOnRightSide', update)); disposables.add(atom.config.onDidChange('tree-view.hideIgnoredNames', update)); disposables.add(atom.config.onDidChange('tree-view.hideVcsIgnoredFiles', update)); disposables.add(atom.config.onDidChange('core.ignoredNames', update)); // changes to the showOn config should enable hover events (the enableHoverEvents // function checks if it actually *should* enable hover events) disposables.add(atom.config.onDidChange('autohide-tree-view.showOn', enableHoverEvents)); // add listeners for mouse events // show the tree view when it is hovered disposables.add(treeViewEl, 'mouseenter', function onMouseEnter() { if(hoverEventsEnabled) show(getConfig('showDelay'), false); }); disposables.add(treeViewEl, 'mouseleave', function onMouseLeave() { if(hoverEventsEnabled) hide(getConfig('hideDelay')); }); // disable the tree view from showing during text selection disposables.add('atom-workspace', 'mousedown', 'atom-text-editor', disableHoverEvents); disposables.add('atom-workspace', 'mouseup', 'atom-text-editor', enableHoverEvents); // toggle the tree view if it is clicked disposables.add(treeViewEl, 'click', function onClick() { if(getConfig('showOn').match('click')) toggle(); }); disposables.add(treeView.list, 'blur', function onBlur() { if(hoverEventsEnabled) return; // clear the focused element so the element the user // clicked will get focus clearFocusedElement(); hide(); }); // resize the tree view when project.paths changes disposables.add(atom.project.onDidChangePaths(resize)); // add command listeners disposables.add(atom.commands.add('atom-workspace', { // own commands 'autohide-tree-view:toggle-push-editor': () => toggleConfig('pushEditor'), // atom core commands 'tool-panel:unfocus': hide, // tree-view commands 'tree-view:show': function treeViewShowOverride(event) { event.stopImmediatePropagation(); show(); }, 'tree-view:hide': function treeViewHideOverride(event) { event.stopImmediatePropagation(); hide(); }, 'tree-view:toggle': function treeViewToggleOverride(event) { event.stopImmediatePropagation(); toggle(); }, 'tree-view:reveal-active-file': () => process.nextTick(show), 'tree-view:toggle-focus': toggle, 'tree-view:remove': resize, 'tree-view:paste': resize, 'tree-view:expand-directory': resize, 'tree-view:recursive-expand-directory': resize, 'tree-view:collapse-directory': resize, 'tree-view:recursive-collapse-directory': resize, // tree-view-resizer package commands 'tree-view-finder:toggle': () => resize().then(show) })); // resize the tree view when opening/closing a directory disposables.add(treeViewEl, 'click', '.entry.directory', function(event) { event.stopPropagation(); resize(); }); // hide the tree view when a file is opened by a command for(let direction of ['', '-right', '-left', '-up', '-down']) { disposables.add(atom.commands.add('atom-workspace', `tree-view:open-selected-entry${direction}`, hide)); } for(let i of [1, 2, 3, 4, 5, 6, 7, 8, 9]) { disposables.add(atom.commands.add('atom-workspace', `tree-view:open-selected-entry-in-pane-${i}`, hide)); } // these commands create a dialog that should keep focus // when the tree view hides for(let command of ['add-file', 'add-folder', 'duplicate', 'rename', 'move']) { disposables.add(atom.commands.add('atom-workspace', `tree-view:${command}`, clearFocusedElement)); } } // updates styling on the .tree-view-resizer and the panel (container) function update(pushEditor) { if(typeof pushEditor != 'boolean') pushEditor = getConfig('pushEditor'); return Promise.resolve().then(function updater() { treeViewEl.style.position = pushEditor ? '' : 'absolute'; updatePanel(pushEditor); }).then(resize).catch(logError); } function updatePanel(pushEditor) { var panelView = atom.views.getView(treeView.panel); if(!panelView) return; panelView.style.width = pushEditor ? '' : `${getConfig('hiddenWidth')}px`; panelView.parentNode.insertBefore(panelView, panelView.parentNode.firstChild); } var visible; // shows the tree view function show(delay, shouldDisableHoverEvents = true) { if(typeof delay != 'number') delay = 0; visible = true; // disable hover events on the tree view when this // show is not triggered by a hover event if(shouldDisableHoverEvents) disableHoverEvents(); // keep a reference to the currently focused element // so we can restore focus when the tree view will hide if(!focusedElement) storeFocusedElement(); // show the tree view content treeView.scroller[0].style.display = ''; return animate(treeView.list[0].clientWidth, delay).then(function(finished) { // focus the tree view if the animation // finished (i.e. wasn't cancelled) if(finished) treeView.focus(); }); } // hides the tree view function hide(delay) { if(typeof delay != 'number') delay = 0; visible = false; // enable hover events enableHoverEvents(); // focus the element that had focus when show() was triggered restoreFocus(); return animate(getConfig('hiddenWidth'), delay).then(function(finished) { // hide the tree view content if(finished) treeView.scroller[0].style.display = 'none'; }); } // toggles the tree view function toggle(delay) { if(typeof delay != 'number') delay = 0; return visible ? hide(delay) : show(delay); } // resizes the tree view when its content width might change function resize() { return Promise.resolve().then(function() { return visible ? show(0, false) : hide(); }); } var focusedElement; // cache the element that currently has focus function storeFocusedElement() { focusedElement = document.activeElement; } // clear the reference to the focusedElement. useful // when we want to invalidate the next restoreFocus function clearFocusedElement() { focusedElement = null; } // recovers focus on focusedElement function restoreFocus() { if(!focusedElement) return; if(typeof focusedElement.focused === 'function') focusedElement.focused(); else if(typeof focusedElement.focus === 'function') focusedElement.focus(); clearFocusedElement(); } var hoverEventsEnabled; // enable hover events on the tree view // (but only if showOn is 'hover' or 'hover + click') function enableHoverEvents() { hoverEventsEnabled = !!getConfig('showOn').match('hover'); } // disable hover events on the tree view function disableHoverEvents() { hoverEventsEnabled = false; } var currentSwipe = null; function shouldInitSwipe(event, source) { // return if autohide or touch events is disabled if(!enabled || !getConfig('showOn').match('touch')) return false; var pageX = event.touches[0].pageX; // always swipe when target is tree view if(!isChildOf(source, treeViewEl.parentNode)) { // check if in touch area if(getConfig('showOnRightSide', 'tree-view')) { if(pageX < window.innerWidth - getConfig('touchAreaSize')) return false; } else { if(pageX > getConfig('touchAreaSize')) return false; } } currentSwipe = event; return true; } // triggered while swiping the tree view function swipeChange({args: event, source, deltaX}) { // check if swipe should show the tree view if(!currentSwipe && !shouldInitSwipe(event, source)) return; // show tree view contents treeView.scroller[0].style.display = 'block'; // calculate new tree view width if(getConfig('showOnRightSide', 'tree-view')) deltaX *= -1 var newWidth = treeViewEl.clientWidth + deltaX; newWidth = Math.max(getConfig('hiddenWidth'), newWidth); newWidth = Math.min(treeView.list[0].clientWidth, newWidth); // request the frame requestAnimationFrame(function frame() { treeViewEl.style.width = `${newWidth}px`; }); } // triggered after swipe left function swipeEndLeft() { if(!currentSwipe) return; currentSwipe = null; if(getConfig('showOnRightSide', 'tree-view')) show(); else hide(); } // triggered after swipe right function swipeEndRight() { if(!currentSwipe) return; currentSwipe = null; if(getConfig('showOnRightSide', 'tree-view')) hide(); else show(); } var currentAnimation = null; // the animation function resolves with 'true' if the // animation finished, with 'false' if cancelled function animate(targetWidth, delay) { // get the initial width of the element var initialWidth = treeViewEl.clientWidth; // set animationSpeed to Infinity if it equals 0 var animationSpeed = getConfig('animationSpeed') || Infinity; // calculate the animation duration if animationSpeed // equals 0 divide by Infinity for a duration of 0 var duration = Math.abs(targetWidth - initialWidth) / animationSpeed; // cancel any current animation if(currentAnimation && currentAnimation.playState !== 'finished') { currentAnimation.cancel(); delay = 0; // immediately trigger the next animation } return new Promise(function(resolve) { // check if animation necessary if(duration == 0) return void setTimeout(function() { treeViewEl.style.width = `${targetWidth}px`; resolve(true); }, delay); // cache the current animationPlayer so we can // cancel it as soon as another animation begins var animation = currentAnimation = treeViewEl.animate([ {width: initialWidth}, {width: targetWidth} ], {duration, delay}); animation.addEventListener('finish', function finish() { animation.removeEventListener('finish', finish); // if cancelled, resolve with false if(animation.playState != 'finished') { resolve(false); return; } // prevent tree view from resetting its width to initialWidth treeViewEl.style.width = `${targetWidth}px`; // reset the currentAnimation reference currentAnimation = null; resolve(true); }); }).catch(logError); } function onDidResizeWindow(maxWindowWidth) { if(typeof maxWindowWidth != 'number') maxWindowWidth = getConfig('maxWindowWidth'); if(!maxWindowWidth || window.innerWidth < maxWindowWidth) enable(); else disable(); } // public API const config = { showOn: { description: 'The type of event that triggers the tree view to show or hide. The touch events require atom-touch-events (https://atom.io/packages/atom-touch-events) to be installed. You\'ll need to restart this package after installing atom-touch-events for touch events to become available.', type: 'string', default: 'hover + touch', enum: [ 'hover', 'click', 'touch', 'hover + click', 'hover + touch', 'click + touch', 'hover + click + touch', 'none' ], order: 0 }, showDelay: { description: 'The delay in milliseconds before the tree view will show. Only applies to hover events.', type: 'integer', default: 200, minimum: 0, order: 1 }, hideDelay: { description: 'The delay in milliseconds before the tree view will hide. Only applies to hover events.', type: 'integer', default: 200, minimum: 0, order: 2 }, hiddenWidth: { description: 'The width in pixels of the tree view when it is hidden.', type: 'integer', default: 5, minimum: 1, order: 3 }, animationSpeed: { description: 'The speed in 1000 pixels per second of the animation. Set to 0 to disable the animation.', type: 'number', default: 1, minimum: 0, order: 4 }, pushEditor: { description: 'Push the edge of the editor around to keep the entire editor contents visible.', type: 'boolean', default: false, order: 5 }, touchAreaSize: { description: 'Width of the area at the edges of the screen where the tree view touch events will be triggered.', type: 'integer', default: 50, order: 6 }, maxWindowWidth: { description: 'Autohide will be disabled when the window is wider than this. Set to 0 to always enable autohide.', type: 'integer', default: 0, minimum: 0 } }; var staticDisposables; function activate() { staticDisposables = new SubAtom(); // these commands are handled here, because we don't want to dispose them on disable() staticDisposables.add(atom.commands.add('atom-workspace', { 'autohide-tree-view:enable': enable, 'autohide-tree-view:disable': disable })); staticDisposables.add(window, 'resize', onDidResizeWindow); staticDisposables.add(atom.config.observe('autohide-tree-view.maxWindowWidth', onDidResizeWindow)); } function deactivate() { staticDisposables.dispose(); disable(); } // provide service for other packages to function provideService() { return { show, hide, enable, disable }; } function consumeTouchSwipeLeftService(onDidTouchSwipeLeft) { staticDisposables.add(onDidTouchSwipeLeft(swipeChange, swipeEndLeft)); } function consumeTouchSwipeRightService(onDidTouchSwipeRight) { staticDisposables.add(onDidTouchSwipeRight(swipeChange, swipeEndRight)); } export {config, activate, deactivate, provideService, consumeTouchSwipeLeftService, consumeTouchSwipeRightService};
lib/autohide-tree-view.js
'use babel'; import SubAtom from 'sub-atom'; // some generic functions function logError(error) { console.error(error.message); } function getConfig(key, ns = 'autohide-tree-view') { return atom.config.get(`${ns}.${key}`); } function setConfig(key, value, ns = 'autohide-tree-view') { atom.config.set(`${ns}.${key}`, value); } function toggleConfig(key, ns) { setConfig(key, !getConfig(key, ns), ns); } function isChildOf(childNode, parentNode) { while(childNode != parentNode && childNode != document.body) { childNode = childNode.parentNode; } return childNode == parentNode; } // private API var disposables, enabled; function enable() { if(enabled) return; disposables = new SubAtom(); // wait until the tree view package is activated atom.packages.activatePackage('tree-view').then(function(treeViewPkg) { registerTreeView(treeViewPkg); handleEvents(); // start with pushEditor = true, we'll change it back later return update(true); }).then(function() { return update(); }).then(function() { enabled = true; }).catch(logError); } function disable() { if(!enabled) return; enabled = false; disposables.dispose(); // the stylesheet will be removed before the animation is finished // making it look ugly... set minWidth on the element to prevent this treeViewEl.style.minWidth = '1px'; // update with pushEditor = true for a nicer animation update(true).then(function() { // show the tree view return show(); }).then(function() { // finally dispose of the tree view and reset all used variables resetTreeView(); [ disposables, enabled, visible, focusedElement, hoverEventsEnabled, currentSwipe, currentAnimation ] = []; }).catch(logError); } var treeView, treeViewEl; // keep references to the tree view model and element function registerTreeView(treeViewPkg) { treeView = treeViewPkg.mainModule.createView(); treeViewEl = treeView.element; treeViewEl.classList.add('autohide'); } // reset the styles etc. on the tree view function resetTreeView() { treeViewEl.classList.remove('autohide'); treeViewEl.style.position = ''; treeViewEl.style.minWidth = ''; treeView.scroller[0].style.display = ''; var panelView = atom.views.getView(treeView.panel); if(panelView) { panelView.style.width = ''; } [treeView, treeViewEl] = []; } function handleEvents() { // changes to these settings should trigger an update disposables.add(atom.config.onDidChange('autohide-tree-view.pushEditor', update)); disposables.add(atom.config.onDidChange('autohide-tree-view.hiddenWidth', update)); disposables.add(atom.config.onDidChange('tree-view.showOnRightSide', update)); disposables.add(atom.config.onDidChange('tree-view.hideIgnoredNames', update)); disposables.add(atom.config.onDidChange('tree-view.hideVcsIgnoredFiles', update)); disposables.add(atom.config.onDidChange('core.ignoredNames', update)); // changes to the showOn config should enable hover events (the enableHoverEvents // function checks if it actually *should* enable hover events) disposables.add(atom.config.onDidChange('autohide-tree-view.showOn', enableHoverEvents)); // add listeners for mouse events // show the tree view when it is hovered disposables.add(treeViewEl, 'mouseenter', function onMouseEnter() { if(hoverEventsEnabled) show(getConfig('showDelay'), false); }); disposables.add(treeViewEl, 'mouseleave', function onMouseLeave() { if(hoverEventsEnabled) hide(getConfig('hideDelay')); }); // disable the tree view from showing during text selection disposables.add('atom-workspace', 'mousedown', 'atom-text-editor', disableHoverEvents); disposables.add('atom-workspace', 'mouseup', 'atom-text-editor', enableHoverEvents); // toggle the tree view if it is clicked disposables.add(treeViewEl, 'click', function onClick() { if(getConfig('showOn').match('click')) toggle(); }); disposables.add(treeView.list, 'blur', function onBlur() { if(hoverEventsEnabled) return; // clear the focused element so the element the user // clicked will get focus clearFocusedElement(); hide(); }); // resize the tree view when project.paths changes disposables.add(atom.project.onDidChangePaths(resize)); // add command listeners disposables.add(atom.commands.add('atom-workspace', { // own commands 'autohide-tree-view:toggle-push-editor': () => toggleConfig('pushEditor'), // atom core commands 'tool-panel:unfocus': hide, // tree-view commands 'tree-view:show': function treeViewShowOverride(event) { event.stopImmediatePropagation(); show(); }, 'tree-view:hide': function treeViewHideOverride(event) { event.stopImmediatePropagation(); hide(); }, 'tree-view:toggle': function treeViewToggleOverride(event) { event.stopImmediatePropagation(); toggle(); }, 'tree-view:reveal-active-file': () => process.nextTick(show), 'tree-view:toggle-focus': toggle, 'tree-view:remove': resize, 'tree-view:paste': resize, 'tree-view:expand-directory': resize, 'tree-view:recursive-expand-directory': resize, 'tree-view:collapse-directory': resize, 'tree-view:recursive-collapse-directory': resize, // tree-view-resizer package commands 'tree-view-finder:toggle': () => resize().then(show) })); // resize the tree view when opening/closing a directory disposables.add(treeViewEl, 'click', '.entry.directory', function(event) { event.stopPropagation(); resize(); }); // hide the tree view when a file is opened by a command for(let direction of ['', '-right', '-left', '-up', '-down']) { disposables.add(atom.commands.add('atom-workspace', `tree-view:open-selected-entry${direction}`, hide)); } for(let i of [1, 2, 3, 4, 5, 6, 7, 8, 9]) { disposables.add(atom.commands.add('atom-workspace', `tree-view:open-selected-entry-in-pane-${i}`, hide)); } // these commands create a dialog that should keep focus // when the tree view hides for(let command of ['add-file', 'add-folder', 'duplicate', 'rename', 'move']) { disposables.add(atom.commands.add('atom-workspace', `tree-view:${command}`, clearFocusedElement)); } } // updates styling on the .tree-view-resizer and the panel (container) function update(pushEditor) { if(typeof pushEditor != 'boolean') pushEditor = getConfig('pushEditor'); return Promise.resolve().then(function updater() { treeViewEl.style.position = pushEditor ? '' : 'absolute'; updatePanel(pushEditor); }).then(resize).catch(logError); } function updatePanel(pushEditor) { var panelView = atom.views.getView(treeView.panel); if(!panelView) return; panelView.style.width = pushEditor ? '' : `${getConfig('hiddenWidth')}px`; panelView.parentNode.insertBefore(panelView, panelView.parentNode.firstChild); } var visible; // shows the tree view function show(delay, shouldDisableHoverEvents = true) { if(typeof delay != 'number') delay = 0; visible = true; // disable hover events on the tree view when this // show is not triggered by a hover event if(shouldDisableHoverEvents) disableHoverEvents(); // keep a reference to the currently focused element // so we can restore focus when the tree view will hide if(!focusedElement) storeFocusedElement(); // show the tree view content treeView.scroller[0].style.display = ''; return animate(treeView.list[0].clientWidth, delay).then(function(finished) { // focus the tree view if the animation // finished (i.e. wasn't cancelled) if(finished) treeView.focus(); }); } // hides the tree view function hide(delay) { if(typeof delay != 'number') delay = 0; visible = false; // enable hover events enableHoverEvents(); // focus the element that had focus when show() was triggered restoreFocus(); return animate(getConfig('hiddenWidth'), delay).then(function(finished) { // hide the tree view content if(finished) treeView.scroller[0].style.display = 'none'; }); } // toggles the tree view function toggle(delay) { if(typeof delay != 'number') delay = 0; return visible ? hide(delay) : show(delay); } // resizes the tree view when its content width might change function resize() { return Promise.resolve().then(function() { return visible ? show(0, false) : hide(); }); } var focusedElement; // cache the element that currently has focus function storeFocusedElement() { focusedElement = document.activeElement; } // clear the reference to the focusedElement. useful // when we want to invalidate the next restoreFocus function clearFocusedElement() { focusedElement = null; } // recovers focus on focusedElement function restoreFocus() { if(!focusedElement) return; if(typeof focusedElement.focused === 'function') focusedElement.focused(); else if(typeof focusedElement.focus === 'function') focusedElement.focus(); clearFocusedElement(); } var hoverEventsEnabled; // enable hover events on the tree view // (but only if showOn is 'hover' or 'hover + click') function enableHoverEvents() { hoverEventsEnabled = !!getConfig('showOn').match('hover'); } // disable hover events on the tree view function disableHoverEvents() { hoverEventsEnabled = false; } var currentSwipe = null; function shouldInitSwipe(event, source) { // return if autohide or touch events is disabled if(!enabled || !getConfig('showOn').match('touch')) return false; var pageX = event.touches[0].pageX; // always swipe when target is tree view if(!isChildOf(source, treeViewEl.parentNode)) { // check if in touch area if(getConfig('showOnRightSide', 'tree-view')) { if(pageX < window.innerWidth - getConfig('touchAreaSize')) return false; } else { if(pageX > getConfig('touchAreaSize')) return false; } } currentSwipe = event; return true; } // triggered while swiping the tree view function swipeChange({args: event, source, deltaX}) { // check if swipe should show the tree view if(!currentSwipe && !shouldInitSwipe(event, source)) return; // show tree view contents treeView.scroller[0].style.display = 'block'; // calculate new tree view width if(getConfig('showOnRightSide', 'tree-view')) deltaX *= -1 var newWidth = treeViewEl.clientWidth + deltaX; newWidth = Math.max(getConfig('hiddenWidth'), newWidth); newWidth = Math.min(treeView.list[0].clientWidth, newWidth); // request the frame requestAnimationFrame(function frame() { treeViewEl.style.width = `${newWidth}px`; }); } // triggered after swipe left function swipeEndLeft() { if(!currentSwipe) return; currentSwipe = null; if(getConfig('showOnRightSide', 'tree-view')) show(); else hide(); } // triggered after swipe right function swipeEndRight() { if(!currentSwipe) return; currentSwipe = null; if(getConfig('showOnRightSide', 'tree-view')) hide(); else show(); } var currentAnimation = null; // the animation function resolves with 'true' if the // animation finished, with 'false' if cancelled function animate(targetWidth, delay) { // get the initial width of the element var initialWidth = treeViewEl.clientWidth; // set animationSpeed to Infinity if it equals 0 var animationSpeed = getConfig('animationSpeed') || Infinity; // calculate the animation duration if animationSpeed // equals 0 divide by Infinity for a duration of 0 var duration = Math.abs(targetWidth - initialWidth) / animationSpeed; // cancel any current animation if(currentAnimation && currentAnimation.playState !== 'finished') { currentAnimation.cancel(); delay = 0; // immediately trigger the next animation } return new Promise(function(resolve) { // check if animation necessary if(duration == 0) return void setTimeout(function() { treeViewEl.style.width = `${targetWidth}px`; resolve(true); }, delay); // cache the current animationPlayer so we can // cancel it as soon as another animation begins var animation = currentAnimation = treeViewEl.animate([ {width: initialWidth}, {width: targetWidth} ], {duration, delay}); animation.addEventListener('finish', function finish() { animation.removeEventListener('finish', finish); // if cancelled, resolve with false if(animation.playState != 'finished') { resolve(false); return; } // prevent tree view from resetting its width to initialWidth treeViewEl.style.width = `${targetWidth}px`; // reset the currentAnimation reference currentAnimation = null; resolve(true); }); }).catch(logError); } function onDidResizeWindow(maxWindowWidth) { if(typeof maxWindowWidth != 'number') maxWindowWidth = getConfig('maxWindowWidth'); if(!maxWindowWidth || window.innerWidth < maxWindowWidth) enable(); else disable(); } // public API const config = { showOn: { description: 'The type of event that triggers the tree view to show or hide. The touch events require atom-touch-events (https://atom.io/packages/atom-touch-events) to be installed. You\'ll need to restart this package after installing atom-touch-events for touch events to become available.', type: 'string', default: 'hover + touch', enum: [ 'hover', 'click', 'touch', 'hover + click', 'hover + touch', 'click + touch', 'hover + click + touch', 'none' ], order: 0 }, showDelay: { description: 'The delay in milliseconds before the tree view will show. Only applies to hover events.', type: 'integer', default: 200, minimum: 0, order: 1 }, hideDelay: { description: 'The delay in milliseconds before the tree view will hide. Only applies to hover events.', type: 'integer', default: 200, minimum: 0, order: 2 }, hiddenWidth: { description: 'The width in pixels of the tree view when it is hidden.', type: 'integer', default: 5, minimum: 1, order: 3 }, animationSpeed: { description: 'The speed in 1000 pixels per second of the animation. Set to 0 to disable the animation.', type: 'number', default: 1, minimum: 0, order: 4 }, pushEditor: { description: 'Push the edge of the editor around to keep the entire editor contents visible.', type: 'boolean', default: false, order: 5 }, touchAreaSize: { description: 'Width of the area at the edges of the screen where the tree view touch events will be triggered.', type: 'integer', default: 50, order: 6 }, maxWindowWidth: { description: 'Autohide will be disabled when the window is wider than this. Set to 0 to always enable autohide.', type: 'integer', default: 0, minimum: 0 } }; var staticDisposables; function activate() { staticDisposables = new SubAtom(); // these commands are handled here, because we don't want to dispose them on disable() staticDisposables.add(atom.commands.add('atom-workspace', { 'autohide-tree-view:enable': enable, 'autohide-tree-view:disable': disable })); staticDisposables.add(window, 'resize', onDidResizeWindow); staticDisposables.add(atom.config.observe('autohide-tree-view.maxWindowWidth', onDidResizeWindow)); } function deactivate() { staticDisposables.dispose(); disable(); } // provide service for other packages to function provideService() { return { show, hide, enable, disable }; } function consumeTouchSwipeLeftService(onDidTouchSwipeLeft) { staticDisposables.add(onDidTouchSwipeLeft(swipeChange, swipeEndLeft)); } function consumeTouchSwipeRightService(onDidTouchSwipeRight) { staticDisposables.add(onDidTouchSwipeRight(swipeChange, swipeEndRight)); } export {config, activate, deactivate, provideService, consumeTouchSwipeLeftService, consumeTouchSwipeRightService};
fix issue where show/hide delay were could be ignored
lib/autohide-tree-view.js
fix issue where show/hide delay were could be ignored
<ide><path>ib/autohide-tree-view.js <ide> <ide> function enable() { <ide> if(enabled) return; <add> enabled = true; <ide> disposables = new SubAtom(); <ide> // wait until the tree view package is activated <ide> atom.packages.activatePackage('tree-view').then(function(treeViewPkg) { <ide> return update(true); <ide> }).then(function() { <ide> return update(); <del> }).then(function() { <del> enabled = true; <ide> }).catch(logError); <ide> } <ide>
Java
apache-2.0
81bcd3c45ba102b7fdfc6f50873a22b4f5038b0f
0
stelar7/L4J8
package no.stelar7.api.l4j8.basic.constants.types; import java.util.Optional; import java.util.stream.Stream; public enum LeaguePositionType implements CodedEnum { /** * MASTER+ rank gets this for some reason? */ APEX, /** * Top lane */ TOP, /** * Jungle */ JUNGLE, /** * Mid lane */ MIDDLE, /** * Bottom lane */ BOTTOM, /** * Support */ UTILITY, /** * Not a positional queue */ NONE; /** * Returns an LeaguePositionType from the provided value * * @param type the type to check * @return LeaguePositionType */ public Optional<LeaguePositionType> getFromCode(final String type) { return Stream.of(LeaguePositionType.values()).filter(t -> t.name().equalsIgnoreCase(type)).findFirst(); } /** * The value used to map strings to objects * * @return String */ public String getCode() { return this.name(); } }
src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
package no.stelar7.api.l4j8.basic.constants.types; import java.util.Optional; import java.util.stream.Stream; public enum LeaguePositionType implements CodedEnum { /** * Top lane */ TOP, /** * Jungle */ JUNGLE, /** * Mid lane */ MIDDLE, /** * Bottom lane */ BOTTOM, /** * Support */ UTILITY; /** * Returns an LeaguePositionType from the provided value * * @param type the type to check * @return LeaguePositionType */ public Optional<LeaguePositionType> getFromCode(final String type) { return Stream.of(LeaguePositionType.values()).filter(t -> t.name().equalsIgnoreCase(type)).findFirst(); } /** * The value used to map strings to objects * * @return String */ public String getCode() { return this.name(); } }
Add missing params to league position
src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
Add missing params to league position
<ide><path>rc/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java <ide> <ide> public enum LeaguePositionType implements CodedEnum <ide> { <add> /** <add> * MASTER+ rank gets this for some reason? <add> */ <add> APEX, <ide> /** <ide> * Top lane <ide> */ <ide> /** <ide> * Support <ide> */ <del> UTILITY; <add> UTILITY, <add> /** <add> * Not a positional queue <add> */ <add> NONE; <ide> <ide> /** <ide> * Returns an LeaguePositionType from the provided value
Java
apache-2.0
973c76e4f29df4f8d8c817de5271b0711a721ef4
0
cristianonicolai/guvnor,yurloc/guvnor,mswiderski/guvnor,wmedvede/guvnor,mbiarnes/guvnor,psiroky/guvnor,etirelli/guvnor,etirelli/guvnor,hxf0801/guvnor,adrielparedes/guvnor,wmedvede/guvnor,adrielparedes/guvnor,adrielparedes/guvnor,nmirasch/guvnor,nmirasch/guvnor,cristianonicolai/guvnor,porcelli-forks/guvnor,nmirasch/guvnor,baldimir/guvnor,baldimir/guvnor,baldimir/guvnor,mbiarnes/guvnor,cristianonicolai/guvnor,wmedvede/guvnor,yurloc/guvnor,kiereleaseuser/guvnor,hxf0801/guvnor,psiroky/guvnor,mbiarnes/guvnor,etirelli/guvnor,droolsjbpm/guvnor,kiereleaseuser/guvnor,kiereleaseuser/guvnor,droolsjbpm/guvnor,droolsjbpm/guvnor,hxf0801/guvnor,porcelli-forks/guvnor,porcelli-forks/guvnor,psiroky/guvnor
/* * Copyright 2011 JBoss 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 org.drools.guvnor.client.decisiontable.widget; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import org.drools.guvnor.client.configurations.ApplicationPreferences; import org.drools.guvnor.client.widgets.decoratedgrid.ColumnResizeEvent; import org.drools.guvnor.client.widgets.decoratedgrid.DecoratedGridHeaderWidget; import org.drools.guvnor.client.widgets.decoratedgrid.DecoratedGridWidget; import org.drools.guvnor.client.widgets.decoratedgrid.DynamicColumn; import org.drools.guvnor.client.widgets.decoratedgrid.ResourcesProvider; import org.drools.guvnor.client.widgets.decoratedgrid.SortConfiguration; import org.drools.guvnor.client.widgets.tables.SortDirection; import org.drools.ide.common.client.modeldriven.brl.BaseSingleFieldConstraint; import org.drools.ide.common.client.modeldriven.dt52.ActionCol52; import org.drools.ide.common.client.modeldriven.dt52.ActionInsertFactCol52; import org.drools.ide.common.client.modeldriven.dt52.ActionSetFieldCol52; import org.drools.ide.common.client.modeldriven.dt52.AnalysisCol52; import org.drools.ide.common.client.modeldriven.dt52.AttributeCol52; import org.drools.ide.common.client.modeldriven.dt52.ConditionCol52; import org.drools.ide.common.client.modeldriven.dt52.DTCellValue52; import org.drools.ide.common.client.modeldriven.dt52.DTColumnConfig52; import org.drools.ide.common.client.modeldriven.dt52.DTDataTypes52; import org.drools.ide.common.client.modeldriven.dt52.DescriptionCol52; import org.drools.ide.common.client.modeldriven.dt52.GuidedDecisionTable52; import org.drools.ide.common.client.modeldriven.dt52.LimitedEntryCol; import org.drools.ide.common.client.modeldriven.dt52.MetadataCol52; import org.drools.ide.common.client.modeldriven.dt52.Pattern52; import org.drools.ide.common.client.modeldriven.dt52.RowNumberCol52; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.dom.client.Style.Overflow; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.dom.client.TableCellElement; import com.google.gwt.dom.client.TableElement; import com.google.gwt.dom.client.TableRowElement; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.CellPanel; import com.google.gwt.user.client.ui.FocusPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Header for a Vertical Decision Table */ public class VerticalDecisionTableHeaderWidget extends DecoratedGridHeaderWidget<DTColumnConfig52> { private static final String DATE_FORMAT = ApplicationPreferences.getDroolsDateFormat(); private static final DateTimeFormat format = DateTimeFormat.getFormat( DATE_FORMAT ); // UI Components private HeaderWidget widget; private GuidedDecisionTable52 model; //Offsets from the left most column private int multiRowColumnOffset = -1; private int multiRowColumnActionsOffset = -1; /** * This is the guts of the widget. */ private class HeaderWidget extends CellPanel { /** * A Widget to display sort order */ private class HeaderSorter extends FocusPanel { private final HorizontalPanel hp = new HorizontalPanel(); private final DynamicColumn<DTColumnConfig52> col; private HeaderSorter(final DynamicColumn<DTColumnConfig52> col) { this.col = col; hp.setHorizontalAlignment( HorizontalPanel.ALIGN_CENTER ); hp.setVerticalAlignment( VerticalPanel.ALIGN_MIDDLE ); hp.setHeight( resources.rowHeaderSorterHeight() + "px" ); hp.setWidth( "100%" ); setIconImage(); add( hp ); // Ensure our icon is updated when the SortDirection changes col.addValueChangeHandler( new ValueChangeHandler<SortConfiguration>() { public void onValueChange(ValueChangeEvent<SortConfiguration> event) { setIconImage(); } } ); } // Set icon's resource accordingly private void setIconImage() { hp.clear(); switch ( col.getSortDirection() ) { case ASCENDING : switch ( col.getSortIndex() ) { case 0 : hp.add( new Image( resources.upArrowIcon() ) ); break; default : hp.add( new Image( resources.smallUpArrowIcon() ) ); } break; case DESCENDING : switch ( col.getSortIndex() ) { case 0 : hp.add( new Image( resources.downArrowIcon() ) ); break; default : hp.add( new Image( resources.smallDownArrowIcon() ) ); } break; default : hp.add( new Image( resources.arrowSpacerIcon() ) ); } } } /** * A Widget to split Conditions section */ private class HeaderSplitter extends FocusPanel { /** * Animation to change the height of a row */ private class HeaderRowAnimation extends Animation { private TableRowElement tre; private int startHeight; private int endHeight; private HeaderRowAnimation(TableRowElement tre, int startHeight, int endHeight) { this.tre = tre; this.startHeight = startHeight; this.endHeight = endHeight; } // Set row height by setting height of children private void setHeight(int height) { for ( int i = 0; i < tre.getChildCount(); i++ ) { tre.getChild( i ).getFirstChild().<DivElement> cast().getStyle().setHeight( height, Unit.PX ); } fireResizeEvent(); } @Override protected void onComplete() { super.onComplete(); setHeight( endHeight ); } @Override protected void onUpdate(double progress) { int height = (int) (startHeight + (progress * (endHeight - startHeight))); setHeight( height ); } } private Element[] rowHeaders; private final HorizontalPanel hp = new HorizontalPanel(); private final Image icon = new Image(); private boolean isCollapsed = true; private HeaderSplitter() { hp.setHorizontalAlignment( HorizontalPanel.ALIGN_CENTER ); hp.setVerticalAlignment( VerticalPanel.ALIGN_MIDDLE ); hp.setWidth( "100%" ); setIconImage(); hp.add( icon ); add( hp ); // Handle action addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { if ( isCollapsed ) { showRow( 2 ); showRow( 3 ); } else { hideRow( 2 ); hideRow( 3 ); } isCollapsed = !isCollapsed; setIconImage(); } } ); } // Hide a row using our animation private void hideRow(int iRow) { if ( rowHeaders == null || (rowHeaders.length - 1) < iRow ) { return; } TableRowElement tre = rowHeaders[iRow].<TableRowElement> cast(); HeaderRowAnimation anim = new HeaderRowAnimation( tre, resources.rowHeaderHeight(), 0 ); anim.run( 250 ); } // Set icon's resource accordingly private void setIconImage() { if ( isCollapsed ) { icon.setResource( resources.smallDownArrowIcon() ); } else { icon.setResource( resources.smallUpArrowIcon() ); } } // Set rows to animate private void setRowHeaders(Element[] rowHeaders) { this.rowHeaders = rowHeaders; } // Show a row using our animation private void showRow(int iRow) { if ( rowHeaders == null || (rowHeaders.length - 1) < iRow ) { return; } TableRowElement tre = rowHeaders[iRow].<TableRowElement> cast(); HeaderRowAnimation anim = new HeaderRowAnimation( tre, 0, resources.rowHeaderHeight() ); anim.run( 250 ); } } // Child Widgets used in this Widget private List<HeaderSorter> sorters = new ArrayList<HeaderSorter>(); private HeaderSplitter splitter = new HeaderSplitter(); // UI Components private Element[] rowHeaders = new Element[5]; private List<DynamicColumn<DTColumnConfig52>> visibleCols = new ArrayList<DynamicColumn<DTColumnConfig52>>(); private List<DynamicColumn<DTColumnConfig52>> visibleConditionCols = new ArrayList<DynamicColumn<DTColumnConfig52>>(); private List<DynamicColumn<DTColumnConfig52>> visibleActionCols = new ArrayList<DynamicColumn<DTColumnConfig52>>(); // Constructor private HeaderWidget() { for ( int iRow = 0; iRow < rowHeaders.length; iRow++ ) { rowHeaders[iRow] = DOM.createTR(); getBody().appendChild( rowHeaders[iRow] ); } getBody().getParentElement().<TableElement> cast().setCellSpacing( 0 ); getBody().getParentElement().<TableElement> cast().setCellPadding( 0 ); } // Make default header label private Element makeLabel(String text, int width, int height) { Element div = DOM.createDiv(); div.getStyle().setWidth( width, Unit.PX ); div.getStyle().setHeight( height, Unit.PX ); div.getStyle().setOverflow( Overflow.HIDDEN ); div.setInnerText( text ); return div; } // Populate a default header element private void populateTableCellElement(DynamicColumn<DTColumnConfig52> col, Element tce) { DTColumnConfig52 modelCol = col.getModelColumn(); if ( modelCol instanceof RowNumberCol52 ) { tce.appendChild( makeLabel( "#", col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof DescriptionCol52 ) { tce.appendChild( makeLabel( constants.Description(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof MetadataCol52 ) { tce.appendChild( makeLabel( ((MetadataCol52) modelCol).getMetadata(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof AttributeCol52 ) { tce.appendChild( makeLabel( ((AttributeCol52) modelCol).getAttribute(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof ConditionCol52 ) { tce.appendChild( makeLabel( ((ConditionCol52) modelCol).getHeader(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof ActionCol52 ) { tce.appendChild( makeLabel( ((ActionCol52) modelCol).getHeader(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof AnalysisCol52) { tce.appendChild( makeLabel( constants.Analysis(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } } // Redraw entire header private void redraw() { // Remove existing widgets from the DOM hierarchy if ( splitter != null ) { remove( splitter ); } for ( HeaderSorter sorter : sorters ) { remove( sorter ); } sorters.clear(); // Extracting visible columns makes life easier visibleCols.clear(); visibleConditionCols.clear(); visibleActionCols.clear(); multiRowColumnOffset = -1; multiRowColumnActionsOffset = -1; for ( int iCol = 0; iCol < grid.getGridWidget().getColumns().size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = grid.getGridWidget().getColumns().get( iCol ); if ( col.isVisible() ) { visibleCols.add( col ); DTColumnConfig52 modelCol = col.getModelColumn(); if ( modelCol instanceof ConditionCol52 ) { if ( multiRowColumnOffset == -1 ) { multiRowColumnOffset = iCol; } visibleConditionCols.add( col ); } if ( modelCol instanceof ActionCol52 ) { if ( multiRowColumnOffset == -1 ) { multiRowColumnOffset = iCol; } if ( multiRowColumnActionsOffset == -1 ) { multiRowColumnActionsOffset = iCol; } visibleActionCols.add( col ); } } } // Draw rows for ( int iRow = 0; iRow < rowHeaders.length; iRow++ ) { redrawHeaderRow( iRow ); } fireResizeEvent(); } // Redraw a single row obviously private void redrawHeaderRow(int iRow) { Element tce = null; Element tre = DOM.createTR(); switch ( iRow ) { case 0 : // General row, all visible cells included for ( DynamicColumn<DTColumnConfig52> col : grid.getGridWidget().getColumns() ) { if ( col.isVisible() ) { tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tre.appendChild( tce ); populateTableCellElement( col, tce ); } } break; case 1 : // Splitter between "general" and "technical" condition details if ( visibleConditionCols.size() > 0 || visibleActionCols.size() > 0 ) { splitter.setRowHeaders( rowHeaders ); tce = DOM.createTD(); tce.<TableCellElement> cast().setColSpan( visibleConditionCols.size() + visibleActionCols.size() ); tce.addClassName( resources.headerSplitter() ); tre.appendChild( tce ); add( splitter, tce ); } break; case 2 : // Condition FactType, merged between identical for ( int iCol = 0; iCol < visibleConditionCols.size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = visibleConditionCols.get( iCol ); ConditionCol52 cc = (ConditionCol52) col.getModelColumn(); Pattern52 ccPattern = model.getPattern( cc ); tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tce.addClassName( resources.headerRowIntermediate() ); tre.appendChild( tce ); // Merging int colSpan = 1; int width = col.getWidth(); while ( iCol + colSpan < visibleConditionCols.size() ) { DynamicColumn<DTColumnConfig52> mergeCol = visibleConditionCols.get( iCol + colSpan ); ConditionCol52 mergeCondCol = (ConditionCol52) mergeCol.getModelColumn(); Pattern52 mergeCondColPattern = model.getPattern( mergeCondCol ); //Only merge columns if FactType and BoundName are identical if ( mergeCondColPattern.getFactType() == null || mergeCondColPattern.getFactType().length() == 0 ) { break; } if ( !mergeCondColPattern.getFactType().equals( ccPattern.getFactType() ) || !mergeCondColPattern.getBoundName().equals( ccPattern.getBoundName() ) ) { break; } width = width + mergeCol.getWidth(); colSpan++; } // Make cell iCol = iCol + colSpan - 1; StringBuilder label = new StringBuilder(); String factType = ccPattern.getFactType(); if ( factType != null && factType.length() > 0 ) { label.append( (ccPattern.isNegated() ? constants.negatedPattern() + " " : "") ); label.append( ccPattern.getFactType() ); label.append( " [" + ccPattern.getBoundName() + "]" ); } tce.appendChild( makeLabel( label.toString(), width, (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); tce.<TableCellElement> cast().setColSpan( colSpan ); } //Action FactType for ( int iCol = 0; iCol < visibleActionCols.size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = visibleActionCols.get( iCol ); ActionCol52 ac = (ActionCol52) col.getModelColumn(); tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); String factType = ""; String binding = null; if ( ac instanceof ActionInsertFactCol52 ) { ActionInsertFactCol52 aifc = (ActionInsertFactCol52) ac; factType = aifc.getFactType(); binding = aifc.getBoundName(); } else if ( ac instanceof ActionSetFieldCol52 ) { factType = ((ActionSetFieldCol52) ac).getBoundName(); } tce.addClassName( resources.headerRowIntermediate() ); StringBuilder label = new StringBuilder(); if ( factType != null && factType.length() > 0 ) { label.append( factType ); if ( binding != null ) { label.append( " [" + binding + "]" ); } } tce.appendChild( makeLabel( label.toString(), col.getWidth(), (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); } break; case 3 : // Condition Fact Fields for ( DynamicColumn<DTColumnConfig52> col : visibleConditionCols ) { tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); ConditionCol52 cc = (ConditionCol52) col.getModelColumn(); StringBuilder label = new StringBuilder(); String factField = cc.getFactField(); if ( factField != null && factField.length() > 0 ) { label.append( factField ); } if ( cc.getConstraintValueType() != BaseSingleFieldConstraint.TYPE_PREDICATE ) { String lev = getLimitedEntryValue( cc ); label.append( " [" ); label.append( cc.getOperator() ); if ( lev != null ) { label.append( lev ); } label.append( "]" ); } tce.appendChild( makeLabel( label.toString(), col.getWidth(), (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); } // Action Fact Fields for ( DynamicColumn<DTColumnConfig52> col : visibleActionCols ) { tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); ActionCol52 ac = (ActionCol52) col.getModelColumn(); StringBuilder label = new StringBuilder(); String factField = ""; if ( ac instanceof ActionInsertFactCol52 ) { ActionInsertFactCol52 aifc = (ActionInsertFactCol52) ac; factField = aifc.getFactField(); } else if ( ac instanceof ActionSetFieldCol52 ) { factField = ((ActionSetFieldCol52) ac).getFactField(); } if ( factField != null && factField.length() > 0 ) { String lev = getLimitedEntryValue( ac ); label.append( factField ); if ( lev != null ) { label.append( " [" ); label.append( lev ); label.append( "]" ); } } tce.appendChild( makeLabel( label.toString(), col.getWidth(), (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); } break; case 4 : // Sorters for ( DynamicColumn<DTColumnConfig52> col : grid.getGridWidget().getColumns() ) { if ( col.isVisible() ) { final HeaderSorter shp = new HeaderSorter( col ); final DynamicColumn<DTColumnConfig52> sortableColumn = col; shp.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { if ( sortableColumn.isSortable() ) { updateSortOrder( sortableColumn ); grid.sort(); } } } ); sorters.add( shp ); tce = DOM.createTD(); tce.addClassName( resources.headerRowBottom() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); add( shp, tce ); } } break; } getBody().replaceChild( tre, rowHeaders[iRow] ); rowHeaders[iRow] = tre; } private String getLimitedEntryValue(DTColumnConfig52 c) { if ( !(c instanceof LimitedEntryCol) ) { return null; } LimitedEntryCol lec = (LimitedEntryCol) c; DTCellValue52 cv = lec.getValue(); if ( cv == null ) { return null; } DTDataTypes52 type = cv.getDataType(); switch ( type ) { case BOOLEAN : return cv.getBooleanValue().toString(); case NUMERIC : return cv.getNumericValue().toPlainString(); case DATE : return format.format( cv.getDateValue() ); default : return cv.getStringValue(); } } // Update sort order. The column clicked becomes the primary sort column // and the other, previously sorted, columns degrade in priority private void updateSortOrder(DynamicColumn<DTColumnConfig52> column) { int sortIndex; TreeMap<Integer, DynamicColumn<DTColumnConfig52>> sortedColumns = new TreeMap<Integer, DynamicColumn<DTColumnConfig52>>(); switch ( column.getSortIndex() ) { case -1 : //A new column is added to the sort group for ( DynamicColumn<DTColumnConfig52> sortedColumn : grid.getGridWidget().getColumns() ) { if ( sortedColumn.getSortDirection() != SortDirection.NONE ) { sortedColumns.put( sortedColumn.getSortIndex(), sortedColumn ); } } sortIndex = 1; for ( DynamicColumn<DTColumnConfig52> sortedColumn : sortedColumns.values() ) { sortedColumn.setSortIndex( sortIndex ); sortIndex++; } column.setSortIndex( 0 ); column.setSortDirection( SortDirection.ASCENDING ); break; case 0 : //The existing "lead" column's sort direction is changed if ( column.getSortDirection() == SortDirection.ASCENDING ) { column.setSortDirection( SortDirection.DESCENDING ); } else if ( column.getSortDirection() == SortDirection.DESCENDING ) { column.setSortDirection( SortDirection.NONE ); column.clearSortIndex(); for ( DynamicColumn<DTColumnConfig52> sortedColumn : grid.getGridWidget().getColumns() ) { if ( sortedColumn.getSortDirection() != SortDirection.NONE ) { sortedColumns.put( sortedColumn.getSortIndex(), sortedColumn ); } } sortIndex = 0; for ( DynamicColumn<DTColumnConfig52> sortedColumn : sortedColumns.values() ) { sortedColumn.setSortIndex( sortIndex ); sortIndex++; } } break; default : //An existing column is promoted to "lead" for ( DynamicColumn<DTColumnConfig52> sortedColumn : grid.getGridWidget().getColumns() ) { if ( sortedColumn.getSortDirection() != SortDirection.NONE ) { if ( !sortedColumn.equals( column ) ) { sortedColumns.put( sortedColumn.getSortIndex() + 1, sortedColumn ); } } } column.setSortIndex( 0 ); sortIndex = 1; for ( DynamicColumn<DTColumnConfig52> sortedColumn : sortedColumns.values() ) { sortedColumn.setSortIndex( sortIndex ); sortIndex++; } break; } } } /** * Construct a "Header" for the provided DecisionTable * * @param decisionTable */ public VerticalDecisionTableHeaderWidget(final ResourcesProvider<DTColumnConfig52> resources, final DecoratedGridWidget<DTColumnConfig52> grid) { super( resources, grid ); } /** * Inject the model * * @param model */ void setModel(GuidedDecisionTable52 model) { if ( model == null ) { throw new IllegalArgumentException( "model cannot be null" ); } this.model = model; } @Override public void redraw() { widget.redraw(); } @Override public void setScrollPosition(int position) { if ( position < 0 ) { throw new IllegalArgumentException( "position cannot be null" ); } ((ScrollPanel) this.panel).setHorizontalScrollPosition( position ); } // Schedule resize event after header has been drawn or resized private void fireResizeEvent() { Scheduler.get().scheduleFinally( new ScheduledCommand() { public void execute() { ResizeEvent.fire( VerticalDecisionTableHeaderWidget.this, getBody().getOffsetWidth(), getBody().getOffsetHeight() ); } } ); } // Set the cursor type for all cells on the table as // we only use rowHeader[0] to check which column // needs resizing however the mouse could be over any // row private void setCursorType(Cursor cursor) { for ( int iRow = 0; iRow < widget.rowHeaders.length; iRow++ ) { TableRowElement tre = widget.rowHeaders[iRow].<TableRowElement> cast(); for ( int iCol = 0; iCol < tre.getCells().getLength(); iCol++ ) { TableCellElement tce = tre.getCells().getItem( iCol ); tce.getStyle().setCursor( cursor ); } } } @Override protected Widget getHeaderWidget() { if ( this.widget == null ) { this.widget = new HeaderWidget(); } return widget; } @Override protected ResizerInformation getResizerInformation(int mx) { boolean isPrimed = false; ResizerInformation resizerInfo = new ResizerInformation(); for ( int iCol = 0; iCol < widget.rowHeaders[0].getChildCount(); iCol++ ) { TableCellElement tce = widget.rowHeaders[0].getChild( iCol ).<TableCellElement> cast(); int cx = tce.getAbsoluteRight(); if ( Math.abs( mx - cx ) <= 5 ) { isPrimed = true; resizerInfo.setResizePrimed( isPrimed ); resizerInfo.setResizeColumn( widget.visibleCols.get( iCol ) ); resizerInfo.setResizeColumnLeft( tce.getAbsoluteLeft() ); break; } } if ( isPrimed ) { setCursorType( Cursor.COL_RESIZE ); } else { setCursorType( Cursor.DEFAULT ); } return resizerInfo; } // Resize the inner DIV in each table cell protected void resizeColumn(DynamicColumn<DTColumnConfig52> resizeColumn, int resizeColumnWidth) { DivElement div; TableCellElement tce; int colOffsetIndex; // This is also set in the ColumnResizeEvent handler, however it makes // resizing columns in the header more simple too resizeColumn.setWidth( resizeColumnWidth ); int resizeColumnIndex = widget.visibleCols.indexOf( resizeColumn ); // Row 0 (General\Fact Type) tce = widget.rowHeaders[0].getChild( resizeColumnIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( resizeColumnWidth, Unit.PX ); // Row 4 (Sorters) tce = widget.rowHeaders[4].getChild( resizeColumnIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( resizeColumnWidth, Unit.PX ); // Row 3 (Fact Fields) if ( multiRowColumnOffset != -1 ) { colOffsetIndex = resizeColumnIndex - multiRowColumnOffset; if ( colOffsetIndex >= 0 && !(resizeColumn.getModelColumn() instanceof AnalysisCol52) ) { DynamicColumn<DTColumnConfig52> col = widget.visibleCols.get( resizeColumnIndex ); tce = widget.rowHeaders[3].getChild( colOffsetIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( col.getWidth(), Unit.PX ); } } // Row 2 (Fact Types) - Condition Columns int iColColumn = 0; for ( int iCol = 0; iCol < widget.visibleConditionCols.size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = widget.visibleConditionCols.get( iCol ); ConditionCol52 cc = (ConditionCol52) col.getModelColumn(); Pattern52 ccPattern = model.getPattern( cc ); // Merging int colSpan = 1; int width = col.getWidth(); while ( iCol + colSpan < widget.visibleConditionCols.size() ) { DynamicColumn<DTColumnConfig52> mergeCol = widget.visibleConditionCols.get( iCol + colSpan ); ConditionCol52 mergeCondCol = (ConditionCol52) mergeCol.getModelColumn(); Pattern52 mergeCondColPattern = model.getPattern( mergeCondCol ); //Only merge columns if FactType and BoundName are identical if ( mergeCondColPattern.getFactType() == null || mergeCondColPattern.getFactType().length() == 0 ) { break; } if ( !mergeCondColPattern.getFactType().equals( ccPattern.getFactType() ) || !mergeCondColPattern.getBoundName().equals( ccPattern.getBoundName() ) ) { break; } width = width + mergeCol.getWidth(); colSpan++; } // Make cell iCol = iCol + colSpan - 1; tce = widget.rowHeaders[2].getChild( iColColumn ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( width, Unit.PX ); iColColumn++; } // Row 2 (Fact Types) - Action Columns if ( multiRowColumnActionsOffset != -1 ) { colOffsetIndex = resizeColumnIndex - multiRowColumnActionsOffset; if ( colOffsetIndex >= 0 && !(resizeColumn.getModelColumn() instanceof AnalysisCol52) ) { colOffsetIndex = colOffsetIndex + iColColumn; DynamicColumn<DTColumnConfig52> col = widget.visibleCols.get( resizeColumnIndex ); tce = widget.rowHeaders[2].getChild( colOffsetIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( col.getWidth(), Unit.PX ); } } // Fire event to any interested consumers ColumnResizeEvent.fire( this, widget.visibleCols.get( resizeColumnIndex ), resizeColumnWidth ); } }
guvnor-webapp/src/main/java/org/drools/guvnor/client/decisiontable/widget/VerticalDecisionTableHeaderWidget.java
/* * Copyright 2011 JBoss 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 org.drools.guvnor.client.decisiontable.widget; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import org.drools.guvnor.client.configurations.ApplicationPreferences; import org.drools.guvnor.client.widgets.decoratedgrid.ColumnResizeEvent; import org.drools.guvnor.client.widgets.decoratedgrid.DecoratedGridHeaderWidget; import org.drools.guvnor.client.widgets.decoratedgrid.DecoratedGridWidget; import org.drools.guvnor.client.widgets.decoratedgrid.DynamicColumn; import org.drools.guvnor.client.widgets.decoratedgrid.ResourcesProvider; import org.drools.guvnor.client.widgets.decoratedgrid.SortConfiguration; import org.drools.guvnor.client.widgets.tables.SortDirection; import org.drools.ide.common.client.modeldriven.brl.BaseSingleFieldConstraint; import org.drools.ide.common.client.modeldriven.dt52.ActionCol52; import org.drools.ide.common.client.modeldriven.dt52.ActionInsertFactCol52; import org.drools.ide.common.client.modeldriven.dt52.ActionSetFieldCol52; import org.drools.ide.common.client.modeldriven.dt52.AnalysisCol52; import org.drools.ide.common.client.modeldriven.dt52.AttributeCol52; import org.drools.ide.common.client.modeldriven.dt52.ConditionCol52; import org.drools.ide.common.client.modeldriven.dt52.DTCellValue52; import org.drools.ide.common.client.modeldriven.dt52.DTColumnConfig52; import org.drools.ide.common.client.modeldriven.dt52.DTDataTypes52; import org.drools.ide.common.client.modeldriven.dt52.DescriptionCol52; import org.drools.ide.common.client.modeldriven.dt52.GuidedDecisionTable52; import org.drools.ide.common.client.modeldriven.dt52.LimitedEntryCol; import org.drools.ide.common.client.modeldriven.dt52.MetadataCol52; import org.drools.ide.common.client.modeldriven.dt52.Pattern52; import org.drools.ide.common.client.modeldriven.dt52.RowNumberCol52; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.dom.client.Style.Overflow; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.dom.client.TableCellElement; import com.google.gwt.dom.client.TableElement; import com.google.gwt.dom.client.TableRowElement; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.CellPanel; import com.google.gwt.user.client.ui.FocusPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Header for a Vertical Decision Table */ public class VerticalDecisionTableHeaderWidget extends DecoratedGridHeaderWidget<DTColumnConfig52> { private static final String DATE_FORMAT = ApplicationPreferences.getDroolsDateFormat(); private static final DateTimeFormat format = DateTimeFormat.getFormat( DATE_FORMAT ); // UI Components private HeaderWidget widget; private GuidedDecisionTable52 model; //Offsets from the left most column private int multiRowColumnOffset = -1; private int multiRowColumnActionsOffset = -1; /** * This is the guts of the widget. */ private class HeaderWidget extends CellPanel { /** * A Widget to display sort order */ private class HeaderSorter extends FocusPanel { private final HorizontalPanel hp = new HorizontalPanel(); private final DynamicColumn<DTColumnConfig52> col; private HeaderSorter(final DynamicColumn<DTColumnConfig52> col) { this.col = col; hp.setHorizontalAlignment( HorizontalPanel.ALIGN_CENTER ); hp.setVerticalAlignment( VerticalPanel.ALIGN_MIDDLE ); hp.setHeight( resources.rowHeaderSorterHeight() + "px" ); hp.setWidth( "100%" ); setIconImage(); add( hp ); // Ensure our icon is updated when the SortDirection changes col.addValueChangeHandler( new ValueChangeHandler<SortConfiguration>() { public void onValueChange(ValueChangeEvent<SortConfiguration> event) { setIconImage(); } } ); } // Set icon's resource accordingly private void setIconImage() { hp.clear(); switch ( col.getSortDirection() ) { case ASCENDING : switch ( col.getSortIndex() ) { case 0 : hp.add( new Image( resources.upArrowIcon() ) ); break; default : hp.add( new Image( resources.smallUpArrowIcon() ) ); } break; case DESCENDING : switch ( col.getSortIndex() ) { case 0 : hp.add( new Image( resources.downArrowIcon() ) ); break; default : hp.add( new Image( resources.smallDownArrowIcon() ) ); } break; default : hp.add( new Image( resources.arrowSpacerIcon() ) ); } } } /** * A Widget to split Conditions section */ private class HeaderSplitter extends FocusPanel { /** * Animation to change the height of a row */ private class HeaderRowAnimation extends Animation { private TableRowElement tre; private int startHeight; private int endHeight; private HeaderRowAnimation(TableRowElement tre, int startHeight, int endHeight) { this.tre = tre; this.startHeight = startHeight; this.endHeight = endHeight; } // Set row height by setting height of children private void setHeight(int height) { for ( int i = 0; i < tre.getChildCount(); i++ ) { tre.getChild( i ).getFirstChild().<DivElement> cast().getStyle().setHeight( height, Unit.PX ); } fireResizeEvent(); } @Override protected void onComplete() { super.onComplete(); setHeight( endHeight ); } @Override protected void onUpdate(double progress) { int height = (int) (startHeight + (progress * (endHeight - startHeight))); setHeight( height ); } } private Element[] rowHeaders; private final HorizontalPanel hp = new HorizontalPanel(); private final Image icon = new Image(); private boolean isCollapsed = true; private HeaderSplitter() { hp.setHorizontalAlignment( HorizontalPanel.ALIGN_CENTER ); hp.setVerticalAlignment( VerticalPanel.ALIGN_MIDDLE ); hp.setWidth( "100%" ); setIconImage(); hp.add( icon ); add( hp ); // Handle action addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { if ( isCollapsed ) { showRow( 2 ); showRow( 3 ); } else { hideRow( 2 ); hideRow( 3 ); } isCollapsed = !isCollapsed; setIconImage(); } } ); } // Hide a row using our animation private void hideRow(int iRow) { if ( rowHeaders == null || (rowHeaders.length - 1) < iRow ) { return; } TableRowElement tre = rowHeaders[iRow].<TableRowElement> cast(); HeaderRowAnimation anim = new HeaderRowAnimation( tre, resources.rowHeaderHeight(), 0 ); anim.run( 250 ); } // Set icon's resource accordingly private void setIconImage() { if ( isCollapsed ) { icon.setResource( resources.smallDownArrowIcon() ); } else { icon.setResource( resources.smallUpArrowIcon() ); } } // Set rows to animate private void setRowHeaders(Element[] rowHeaders) { this.rowHeaders = rowHeaders; } // Show a row using our animation private void showRow(int iRow) { if ( rowHeaders == null || (rowHeaders.length - 1) < iRow ) { return; } TableRowElement tre = rowHeaders[iRow].<TableRowElement> cast(); HeaderRowAnimation anim = new HeaderRowAnimation( tre, 0, resources.rowHeaderHeight() ); anim.run( 250 ); } } // Child Widgets used in this Widget private List<HeaderSorter> sorters = new ArrayList<HeaderSorter>(); private HeaderSplitter splitter = new HeaderSplitter(); // UI Components private Element[] rowHeaders = new Element[5]; private List<DynamicColumn<DTColumnConfig52>> visibleCols = new ArrayList<DynamicColumn<DTColumnConfig52>>(); private List<DynamicColumn<DTColumnConfig52>> visibleConditionCols = new ArrayList<DynamicColumn<DTColumnConfig52>>(); private List<DynamicColumn<DTColumnConfig52>> visibleActionCols = new ArrayList<DynamicColumn<DTColumnConfig52>>(); // Constructor private HeaderWidget() { for ( int iRow = 0; iRow < rowHeaders.length; iRow++ ) { rowHeaders[iRow] = DOM.createTR(); getBody().appendChild( rowHeaders[iRow] ); } getBody().getParentElement().<TableElement> cast().setCellSpacing( 0 ); getBody().getParentElement().<TableElement> cast().setCellPadding( 0 ); } // Make default header label private Element makeLabel(String text, int width, int height) { Element div = DOM.createDiv(); div.getStyle().setWidth( width, Unit.PX ); div.getStyle().setHeight( height, Unit.PX ); div.getStyle().setOverflow( Overflow.HIDDEN ); div.setInnerText( text ); return div; } // Populate a default header element private void populateTableCellElement(DynamicColumn<DTColumnConfig52> col, Element tce) { DTColumnConfig52 modelCol = col.getModelColumn(); if ( modelCol instanceof RowNumberCol52 ) { tce.appendChild( makeLabel( "#", col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof DescriptionCol52 ) { tce.appendChild( makeLabel( constants.Description(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof MetadataCol52 ) { tce.appendChild( makeLabel( ((MetadataCol52) modelCol).getMetadata(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof AttributeCol52 ) { tce.appendChild( makeLabel( ((AttributeCol52) modelCol).getAttribute(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof ConditionCol52 ) { tce.appendChild( makeLabel( ((ConditionCol52) modelCol).getHeader(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof ActionCol52 ) { tce.appendChild( makeLabel( ((ActionCol52) modelCol).getHeader(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } else if ( modelCol instanceof AnalysisCol52) { tce.appendChild( makeLabel( constants.Analysis(), col.getWidth(), resources.rowHeaderHeight() ) ); tce.<TableCellElement> cast().setRowSpan( 4 ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); } } // Redraw entire header private void redraw() { // Remove existing widgets from the DOM hierarchy if ( splitter != null ) { remove( splitter ); } for ( HeaderSorter sorter : sorters ) { remove( sorter ); } sorters.clear(); // Extracting visible columns makes life easier visibleCols.clear(); visibleConditionCols.clear(); visibleActionCols.clear(); multiRowColumnOffset = -1; multiRowColumnActionsOffset = -1; for ( int iCol = 0; iCol < grid.getGridWidget().getColumns().size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = grid.getGridWidget().getColumns().get( iCol ); if ( col.isVisible() ) { visibleCols.add( col ); DTColumnConfig52 modelCol = col.getModelColumn(); if ( modelCol instanceof ConditionCol52 ) { if ( multiRowColumnOffset == -1 ) { multiRowColumnOffset = iCol; } visibleConditionCols.add( col ); } if ( modelCol instanceof ActionCol52 ) { if ( multiRowColumnOffset == -1 ) { multiRowColumnOffset = iCol; } if ( multiRowColumnActionsOffset == -1 ) { multiRowColumnActionsOffset = iCol; } visibleActionCols.add( col ); } } } // Draw rows for ( int iRow = 0; iRow < rowHeaders.length; iRow++ ) { redrawHeaderRow( iRow ); } fireResizeEvent(); } // Redraw a single row obviously private void redrawHeaderRow(int iRow) { Element tce = null; Element tre = DOM.createTR(); switch ( iRow ) { case 0 : // General row, all visible cells included for ( DynamicColumn<DTColumnConfig52> col : grid.getGridWidget().getColumns() ) { if ( col.isVisible() ) { tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tre.appendChild( tce ); populateTableCellElement( col, tce ); } } break; case 1 : // Splitter between "general" and "technical" condition details if ( visibleConditionCols.size() > 0 || visibleActionCols.size() > 0 ) { splitter.setRowHeaders( rowHeaders ); tce = DOM.createTD(); tce.<TableCellElement> cast().setColSpan( visibleConditionCols.size() + visibleActionCols.size() ); tce.addClassName( resources.headerSplitter() ); tre.appendChild( tce ); add( splitter, tce ); } break; case 2 : // Condition FactType, merged between identical for ( int iCol = 0; iCol < visibleConditionCols.size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = visibleConditionCols.get( iCol ); ConditionCol52 cc = (ConditionCol52) col.getModelColumn(); Pattern52 ccPattern = model.getPattern( cc ); tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tce.addClassName( resources.headerRowIntermediate() ); tre.appendChild( tce ); // Merging int colSpan = 1; int width = col.getWidth(); while ( iCol + colSpan < visibleConditionCols.size() ) { DynamicColumn<DTColumnConfig52> mergeCol = visibleConditionCols.get( iCol + colSpan ); ConditionCol52 mergeCondCol = (ConditionCol52) mergeCol.getModelColumn(); Pattern52 mergeCondColPattern = model.getPattern( mergeCondCol ); //Only merge columns if FactType and BoundName are identical if ( mergeCondColPattern.getFactType() == null || mergeCondColPattern.getFactType().length() == 0 ) { break; } if ( !mergeCondColPattern.getFactType().equals( ccPattern.getFactType() ) || !mergeCondColPattern.getBoundName().equals( ccPattern.getBoundName() ) ) { break; } width = width + mergeCol.getWidth(); colSpan++; } // Make cell iCol = iCol + colSpan - 1; StringBuilder label = new StringBuilder(); String factType = ccPattern.getFactType(); if ( factType != null && factType.length() > 0 ) { label.append( (ccPattern.isNegated() ? constants.negatedPattern() + " " : "") ); label.append( ccPattern.getFactType() ); label.append( " [" + ccPattern.getBoundName() + "]" ); } tce.appendChild( makeLabel( label.toString(), width, (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); tce.<TableCellElement> cast().setColSpan( colSpan ); } //Action FactType for ( int iCol = 0; iCol < visibleActionCols.size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = visibleActionCols.get( iCol ); ActionCol52 ac = (ActionCol52) col.getModelColumn(); tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); String factType = ""; String binding = null; if ( ac instanceof ActionInsertFactCol52 ) { ActionInsertFactCol52 aifc = (ActionInsertFactCol52) ac; factType = aifc.getFactType(); binding = aifc.getBoundName(); } else if ( ac instanceof ActionSetFieldCol52 ) { factType = ((ActionSetFieldCol52) ac).getBoundName(); } tce.addClassName( resources.headerRowIntermediate() ); StringBuilder label = new StringBuilder(); if ( factType != null && factType.length() > 0 ) { label.append( factType ); if ( binding != null ) { label.append( " [" + binding + "]" ); } } tce.appendChild( makeLabel( label.toString(), col.getWidth(), (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); } break; case 3 : // Condition Fact Fields for ( DynamicColumn<DTColumnConfig52> col : visibleConditionCols ) { tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); ConditionCol52 cc = (ConditionCol52) col.getModelColumn(); StringBuilder label = new StringBuilder(); String factField = cc.getFactField(); if ( factField != null && factField.length() > 0 ) { label.append( factField ); } if ( cc.getConstraintValueType() != BaseSingleFieldConstraint.TYPE_PREDICATE ) { String lev = getLimitedEntryValue( cc ); label.append( " [" ); label.append( cc.getOperator() ); if ( lev != null ) { label.append( lev ); } label.append( "]" ); } tce.appendChild( makeLabel( label.toString(), col.getWidth(), (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); } // Action Fact Fields for ( DynamicColumn<DTColumnConfig52> col : visibleActionCols ) { tce = DOM.createTD(); tce.addClassName( resources.headerText() ); tce.addClassName( resources.headerRowIntermediate() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); ActionCol52 ac = (ActionCol52) col.getModelColumn(); StringBuilder label = new StringBuilder(); String factField = ""; if ( ac instanceof ActionInsertFactCol52 ) { ActionInsertFactCol52 aifc = (ActionInsertFactCol52) ac; factField = aifc.getFactField(); } else if ( ac instanceof ActionSetFieldCol52 ) { factField = ((ActionSetFieldCol52) ac).getFactField(); } if ( factField != null && factField.length() > 0 ) { String lev = getLimitedEntryValue( ac ); label.append( factField ); if ( lev != null ) { label.append( " [" ); label.append( lev ); label.append( "]" ); } } tce.appendChild( makeLabel( label.toString(), col.getWidth(), (splitter.isCollapsed ? 0 : resources.rowHeaderHeight()) ) ); } break; case 4 : // Sorters for ( DynamicColumn<DTColumnConfig52> col : grid.getGridWidget().getColumns() ) { if ( col.isVisible() ) { final HeaderSorter shp = new HeaderSorter( col ); final DynamicColumn<DTColumnConfig52> sortableColumn = col; shp.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { if ( sortableColumn.isSortable() ) { updateSortOrder( sortableColumn ); grid.sort(); } } } ); sorters.add( shp ); tce = DOM.createTD(); tce.addClassName( resources.headerRowBottom() ); tce.addClassName( resources.cellTableColumn( col.getModelColumn() ) ); tre.appendChild( tce ); add( shp, tce ); } } break; } getBody().replaceChild( tre, rowHeaders[iRow] ); rowHeaders[iRow] = tre; } private String getLimitedEntryValue(DTColumnConfig52 c) { if ( !(c instanceof LimitedEntryCol) ) { return null; } LimitedEntryCol lec = (LimitedEntryCol) c; DTCellValue52 cv = lec.getValue(); if ( cv == null ) { return null; } DTDataTypes52 type = cv.getDataType(); switch ( type ) { case BOOLEAN : return cv.getBooleanValue().toString(); case NUMERIC : return cv.getNumericValue().toPlainString(); case DATE : return format.format( cv.getDateValue() ); default : return cv.getStringValue(); } } // Update sort order. The column clicked becomes the primary sort column // and the other, previously sorted, columns degrade in priority private void updateSortOrder(DynamicColumn<DTColumnConfig52> column) { int sortIndex; TreeMap<Integer, DynamicColumn<DTColumnConfig52>> sortedColumns = new TreeMap<Integer, DynamicColumn<DTColumnConfig52>>(); switch ( column.getSortIndex() ) { case -1 : //A new column is added to the sort group for ( DynamicColumn<DTColumnConfig52> sortedColumn : grid.getGridWidget().getColumns() ) { if ( sortedColumn.getSortDirection() != SortDirection.NONE ) { sortedColumns.put( sortedColumn.getSortIndex(), sortedColumn ); } } sortIndex = 1; for ( DynamicColumn<DTColumnConfig52> sortedColumn : sortedColumns.values() ) { sortedColumn.setSortIndex( sortIndex ); sortIndex++; } column.setSortIndex( 0 ); column.setSortDirection( SortDirection.ASCENDING ); break; case 0 : //The existing "lead" column's sort direction is changed if ( column.getSortDirection() == SortDirection.ASCENDING ) { column.setSortDirection( SortDirection.DESCENDING ); } else if ( column.getSortDirection() == SortDirection.DESCENDING ) { column.setSortDirection( SortDirection.NONE ); column.clearSortIndex(); for ( DynamicColumn<DTColumnConfig52> sortedColumn : grid.getGridWidget().getColumns() ) { if ( sortedColumn.getSortDirection() != SortDirection.NONE ) { sortedColumns.put( sortedColumn.getSortIndex(), sortedColumn ); } } sortIndex = 0; for ( DynamicColumn<DTColumnConfig52> sortedColumn : sortedColumns.values() ) { sortedColumn.setSortIndex( sortIndex ); sortIndex++; } } break; default : //An existing column is promoted to "lead" for ( DynamicColumn<DTColumnConfig52> sortedColumn : grid.getGridWidget().getColumns() ) { if ( sortedColumn.getSortDirection() != SortDirection.NONE ) { if ( !sortedColumn.equals( column ) ) { sortedColumns.put( sortedColumn.getSortIndex() + 1, sortedColumn ); } } } column.setSortIndex( 0 ); sortIndex = 1; for ( DynamicColumn<DTColumnConfig52> sortedColumn : sortedColumns.values() ) { sortedColumn.setSortIndex( sortIndex ); sortIndex++; } break; } } } /** * Construct a "Header" for the provided DecisionTable * * @param decisionTable */ public VerticalDecisionTableHeaderWidget(final ResourcesProvider<DTColumnConfig52> resources, final DecoratedGridWidget<DTColumnConfig52> grid) { super( resources, grid ); } /** * Inject the model * * @param model */ void setModel(GuidedDecisionTable52 model) { if ( model == null ) { throw new IllegalArgumentException( "model cannot be null" ); } this.model = model; } @Override public void redraw() { widget.redraw(); } @Override public void setScrollPosition(int position) { if ( position < 0 ) { throw new IllegalArgumentException( "position cannot be null" ); } ((ScrollPanel) this.panel).setHorizontalScrollPosition( position ); } // Schedule resize event after header has been drawn or resized private void fireResizeEvent() { Scheduler.get().scheduleFinally( new ScheduledCommand() { public void execute() { ResizeEvent.fire( VerticalDecisionTableHeaderWidget.this, getBody().getOffsetWidth(), getBody().getOffsetHeight() ); } } ); } // Set the cursor type for all cells on the table as // we only use rowHeader[0] to check which column // needs resizing however the mouse could be over any // row private void setCursorType(Cursor cursor) { for ( int iRow = 0; iRow < widget.rowHeaders.length; iRow++ ) { TableRowElement tre = widget.rowHeaders[iRow].<TableRowElement> cast(); for ( int iCol = 0; iCol < tre.getCells().getLength(); iCol++ ) { TableCellElement tce = tre.getCells().getItem( iCol ); tce.getStyle().setCursor( cursor ); } } } @Override protected Widget getHeaderWidget() { if ( this.widget == null ) { this.widget = new HeaderWidget(); } return widget; } @Override protected ResizerInformation getResizerInformation(int mx) { boolean isPrimed = false; ResizerInformation resizerInfo = new ResizerInformation(); for ( int iCol = 0; iCol < widget.rowHeaders[0].getChildCount(); iCol++ ) { TableCellElement tce = widget.rowHeaders[0].getChild( iCol ).<TableCellElement> cast(); int cx = tce.getAbsoluteRight(); if ( Math.abs( mx - cx ) <= 5 ) { isPrimed = true; resizerInfo.setResizePrimed( isPrimed ); resizerInfo.setResizeColumn( widget.visibleCols.get( iCol ) ); resizerInfo.setResizeColumnLeft( tce.getAbsoluteLeft() ); break; } } if ( isPrimed ) { setCursorType( Cursor.COL_RESIZE ); } else { setCursorType( Cursor.DEFAULT ); } return resizerInfo; } // Resize the inner DIV in each table cell protected void resizeColumn(DynamicColumn<DTColumnConfig52> resizeColumn, int resizeColumnWidth) { DivElement div; TableCellElement tce; int colOffsetIndex; // This is also set in the ColumnResizeEvent handler, however it makes // resizing columns in the header more simple too resizeColumn.setWidth( resizeColumnWidth ); int resizeColumnIndex = widget.visibleCols.indexOf( resizeColumn ); // Row 0 (General\Fact Type) tce = widget.rowHeaders[0].getChild( resizeColumnIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( resizeColumnWidth, Unit.PX ); // Row 4 (Sorters) tce = widget.rowHeaders[4].getChild( resizeColumnIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( resizeColumnWidth, Unit.PX ); // Row 3 (Fact Fields) if ( multiRowColumnOffset != -1 ) { colOffsetIndex = resizeColumnIndex - multiRowColumnOffset; if ( colOffsetIndex >= 0 ) { DynamicColumn<DTColumnConfig52> col = widget.visibleCols.get( resizeColumnIndex ); tce = widget.rowHeaders[3].getChild( colOffsetIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( col.getWidth(), Unit.PX ); } } // Row 2 (Fact Types) - Condition Columns int iColColumn = 0; for ( int iCol = 0; iCol < widget.visibleConditionCols.size(); iCol++ ) { DynamicColumn<DTColumnConfig52> col = widget.visibleConditionCols.get( iCol ); ConditionCol52 cc = (ConditionCol52) col.getModelColumn(); Pattern52 ccPattern = model.getPattern( cc ); // Merging int colSpan = 1; int width = col.getWidth(); while ( iCol + colSpan < widget.visibleConditionCols.size() ) { DynamicColumn<DTColumnConfig52> mergeCol = widget.visibleConditionCols.get( iCol + colSpan ); ConditionCol52 mergeCondCol = (ConditionCol52) mergeCol.getModelColumn(); Pattern52 mergeCondColPattern = model.getPattern( mergeCondCol ); //Only merge columns if FactType and BoundName are identical if ( mergeCondColPattern.getFactType() == null || mergeCondColPattern.getFactType().length() == 0 ) { break; } if ( !mergeCondColPattern.getFactType().equals( ccPattern.getFactType() ) || !mergeCondColPattern.getBoundName().equals( ccPattern.getBoundName() ) ) { break; } width = width + mergeCol.getWidth(); colSpan++; } // Make cell iCol = iCol + colSpan - 1; tce = widget.rowHeaders[2].getChild( iColColumn ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( width, Unit.PX ); iColColumn++; } // Row 2 (Fact Types) - Action Columns if ( multiRowColumnActionsOffset != -1 ) { colOffsetIndex = resizeColumnIndex - multiRowColumnActionsOffset; if ( colOffsetIndex >= 0 ) { colOffsetIndex = colOffsetIndex + iColColumn; DynamicColumn<DTColumnConfig52> col = widget.visibleCols.get( resizeColumnIndex ); tce = widget.rowHeaders[2].getChild( colOffsetIndex ).<TableCellElement> cast(); div = tce.getFirstChild().<DivElement> cast(); div.getStyle().setWidth( col.getWidth(), Unit.PX ); } } // Fire event to any interested consumers ColumnResizeEvent.fire( this, widget.visibleCols.get( resizeColumnIndex ), resizeColumnWidth ); } }
fix analys column resizing bug
guvnor-webapp/src/main/java/org/drools/guvnor/client/decisiontable/widget/VerticalDecisionTableHeaderWidget.java
fix analys column resizing bug
<ide><path>uvnor-webapp/src/main/java/org/drools/guvnor/client/decisiontable/widget/VerticalDecisionTableHeaderWidget.java <ide> // Row 3 (Fact Fields) <ide> if ( multiRowColumnOffset != -1 ) { <ide> colOffsetIndex = resizeColumnIndex - multiRowColumnOffset; <del> if ( colOffsetIndex >= 0 ) { <add> if ( colOffsetIndex >= 0 && !(resizeColumn.getModelColumn() instanceof AnalysisCol52) ) { <ide> DynamicColumn<DTColumnConfig52> col = widget.visibleCols.get( resizeColumnIndex ); <ide> tce = widget.rowHeaders[3].getChild( colOffsetIndex ).<TableCellElement> cast(); <ide> div = tce.getFirstChild().<DivElement> cast(); <ide> // Row 2 (Fact Types) - Action Columns <ide> if ( multiRowColumnActionsOffset != -1 ) { <ide> colOffsetIndex = resizeColumnIndex - multiRowColumnActionsOffset; <del> if ( colOffsetIndex >= 0 ) { <add> if ( colOffsetIndex >= 0 && !(resizeColumn.getModelColumn() instanceof AnalysisCol52) ) { <ide> colOffsetIndex = colOffsetIndex + iColColumn; <ide> DynamicColumn<DTColumnConfig52> col = widget.visibleCols.get( resizeColumnIndex ); <ide> tce = widget.rowHeaders[2].getChild( colOffsetIndex ).<TableCellElement> cast();
JavaScript
mit
error: pathspec 'role.wallbuilder.js' did not match any file(s) known to git
a9db7e7bc1a4aec929326628f36dcfbeb369e82f
1
Ditchbuster/screeps
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('role.wallbuilder'); * mod.thing == 'a thing'; // true */ var roleWallRepairer = { /** @param {Creep} creep **/ run: function(creep) { if(creep.carry.energy < 5 && creep.memory.filling == false){ creep.memory.filling = true; } if(creep.carry.energy == creep.carryCapacity && creep.memory.filling == true){ creep.memory.filling = false; } if(creep.memory.filling == true) { var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0]); } } else { var targets = creep.room.find(FIND_STRUCTURES, { filter: object => (object.hits < object.hitsMax && object.structureType == STRUCTURE_CONTAINER) }); //targets.sort((a,b) => a.hits - b.hits); if(targets.length > 0) { if(creep.repair(targets[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(targets[0]); } }else{ var targets = creep.room.find(FIND_STRUCTURES, { filter: object => object.hits < object.hitsMax }); //targets.sort((a,b) => a.hits - b.hits); if(targets.length > 0) { if(creep.repair(targets[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(targets[0]); } }else{ creep.moveTo(7,24); } } } } }; module.exports = roleWallRepairer;
role.wallbuilder.js
add creep to just build walls copied file from repairer
role.wallbuilder.js
add creep to just build walls
<ide><path>ole.wallbuilder.js <add>/* <add> * Module code goes here. Use 'module.exports' to export things: <add> * module.exports.thing = 'a thing'; <add> * <add> * You can import it from another modules like this: <add> * var mod = require('role.wallbuilder'); <add> * mod.thing == 'a thing'; // true <add> */ <add> <add>var roleWallRepairer = { <add> <add> /** @param {Creep} creep **/ <add> run: function(creep) { <add> if(creep.carry.energy < 5 && creep.memory.filling == false){ <add> creep.memory.filling = true; <add> } <add> if(creep.carry.energy == creep.carryCapacity && creep.memory.filling == true){ <add> creep.memory.filling = false; <add> } <add> <add> if(creep.memory.filling == true) { <add> var sources = creep.room.find(FIND_SOURCES); <add> if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { <add> creep.moveTo(sources[0]); <add> } <add> } <add> else { <add> var targets = creep.room.find(FIND_STRUCTURES, { <add> filter: object => (object.hits < object.hitsMax && object.structureType == STRUCTURE_CONTAINER) <add> }); <add> <add> //targets.sort((a,b) => a.hits - b.hits); <add> <add> if(targets.length > 0) { <add> if(creep.repair(targets[0]) == ERR_NOT_IN_RANGE) { <add> creep.moveTo(targets[0]); <add> } <add> }else{ <add> var targets = creep.room.find(FIND_STRUCTURES, { <add> filter: object => object.hits < object.hitsMax <add> }); <add> <add> //targets.sort((a,b) => a.hits - b.hits); <add> <add> if(targets.length > 0) { <add> if(creep.repair(targets[0]) == ERR_NOT_IN_RANGE) { <add> creep.moveTo(targets[0]); <add> } <add> }else{ <add> creep.moveTo(7,24); <add> } <add> } <add> <add> } <add> } <add>}; <add> <add>module.exports = roleWallRepairer;
JavaScript
mit
f55838926f725776966220c457a136b46d0bb88c
0
Salesflare/hapi-plugin-mysql
'use strict'; var MySQL = require('mysql'); var Hoek = require('hoek'); var pool = null; var useTransactions = false; var _rollback = function (server, connection, callback) { connection.rollback(function () { if (process.env.NODE_ENV !== 'prod' || process.argv[2] !== 'prod') server.log(['hapi-plugin-mysql', 'database'], 'Rolling back transaction'); connection.release(); return callback(); }); }; var _endConnection = function (server, connection, callback) { connection.commit(function (err) { if (err) { _rollback(server, connection, callback); } else { connection.release(); return callback(); } }); }; exports.register = function (server, base_options, next) { Hoek.assert(base_options.hasOwnProperty('host'), 'Options must include host property'); var options = Hoek.clone(base_options); useTransactions = Hoek.clone(options.useTransactions); delete options.useTransactions; pool = MySQL.createPool(options); // test connection pool.getConnection(function (err, connection) { Hoek.assert(!err, err); Hoek.assert(connection, 'Got no connection from pool'); connection.ping(function (err) { Hoek.assert(!err, err); // release test connection connection.release(); server.log(['hapi-plugin-mysql', 'database'], 'Connection to the database succesfull'); // end connection after handler finishes server.ext('onPostHandler', function (request, reply) { _endConnection(server, request.app.db, function () { return reply.continue(); }); }); // add data to request object server.ext('onPreAuth', function (request, reply) { Hoek.assert(pool, 'No mysql pool found'); pool.getConnection(function (err, connection) { if (err) return reply(err); if (useTransactions) { connection.beginTransaction(function (err) { if (err) _endConnection(server, connection, function () { return reply(err); }); request.app.db = connection; return reply.continue(); }); } else { request.app.db = connection; return reply.continue(); } }); }); // close pool on server end server.on('stop', function (server) { pool.end(function (err) { if (err) server.log(['hapi-plugin-mysql', 'database'], 'Failed to gracefully end the pool'); pool = null; }); }); return next(); }); }); }; exports.register.attributes = { pkg: require('../package.json') };
lib/index.js
'use strict'; var MySQL = require('mysql'); var Hoek = require('hoek'); var pool = null; var useTransactions = false; var _rollback = function (server, connection, callback) { connection.rollback(function () { if (process.env.NODE_ENV !== 'prod' || process.argv[2] !== 'prod') server.log(['hapi-plugin-mysql', 'database'], 'Rolling back transaction'); connection.release(); return callback(); }); }; var _endConnection = function (server, connection, callback) { connection.commit(function (err) { if (err) { _rollback(server, connection, callback); } else { connection.release(); return callback(); } }); }; exports.register = function (server, base_options, next) { Hoek.assert(base_options.hasOwnProperty('host'), 'Options must include host property'); var options = Hoek.clone(base_options); useTransactions = Hoek.clone(options.useTransactions); delete options.useTransactions; pool = MySQL.createPool(options); // test connection pool.getConnection(function (err, connection) { Hoek.assert(!err, err); Hoek.assert(connection, 'Got no connection from pool'); connection.ping(function (err) { Hoek.assert(!err, err); // release test connection connection.release(); server.log(['hapi-plugin-mysql', 'database'], 'Connection to the database succesfull'); // end connection after handler finishes server.ext('onPostHandler', function (request, reply) { _endConnection(server, request.app.db, function () { return reply.continue(); }); }); // add data to request object server.ext('onPreHandler', function (request, reply) { Hoek.assert(pool, 'No mysql pool found'); pool.getConnection(function (err, connection) { if (err) return reply(err); if (useTransactions) { connection.beginTransaction(function (err) { if (err) _endConnection(server, connection, function () { return reply(err); }); request.app.db = connection; return reply.continue(); }); } else { request.app.db = connection; return reply.continue(); } }); }); // close pool on server end server.on('stop', function (server) { pool.end(function (err) { if (err) server.log(['hapi-plugin-mysql', 'database'], 'Failed to gracefully end the pool'); pool = null; }); }); return next(); }); }); }; exports.register.attributes = { pkg: require('../package.json') };
add connction on preAuth instead of preHandler to allow usage of the connection for auth
lib/index.js
add connction on preAuth instead of preHandler to allow usage of the connection for auth
<ide><path>ib/index.js <ide> }); <ide> <ide> // add data to request object <del> server.ext('onPreHandler', function (request, reply) { <add> server.ext('onPreAuth', function (request, reply) { <ide> Hoek.assert(pool, 'No mysql pool found'); <ide> <ide> pool.getConnection(function (err, connection) {
JavaScript
agpl-3.0
04fe18d6414f0f6fec8c05b514b9c7494728bff3
0
nextcloud/spreed,nextcloud/spreed,nextcloud/spreed
/** @global console */ (function(OCA, OC, $) { 'use strict'; OCA.Talk = OCA.Talk || {}; OCA.Talk.Signaling = { Base: {}, Internal: {}, Standalone: {}, /** * Loads the signaling settings. * * The signaling settings are set in the DOM element in which * "createConnection" expects to find them; if the DOM element already * exists it is assumed that the settings are already loaded. * * @return Deferred a Deferred object that will be resolved once the * settings are loaded. */ loadSettings: function() { var deferred = $.Deferred(); if ($('#app #signaling-settings').length > 0) { deferred.resolve(); return deferred.promise(); } if ($('#app').length === 0) { $('body').append('<div id="app"></div>'); } $('#app').append('<script type="text/json" id="signaling-settings"></script>'); $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + 'settings', type: 'GET', dataType: 'json', success: function (result) { $('#app #signaling-settings').text(JSON.stringify(result.ocs.data)); deferred.resolve(); }, error: function (xhr, textStatus, errorThrown) { deferred.reject(xhr, textStatus, errorThrown); } }); return deferred.promise(); }, createConnection: function() { var settings = $("#app #signaling-settings").text(); if (settings) { settings = JSON.parse(settings); } else { settings = {}; } var urls = settings.server; if (urls && urls.length) { return new OCA.Talk.Signaling.Standalone(settings, urls); } else { return new OCA.Talk.Signaling.Internal(settings); } } }; function Base(settings) { this.settings = settings; this.sessionId = ''; this.currentRoomToken = null; this.currentCallToken = null; this.currentCallFlags = null; this.handlers = {}; this.features = {}; this.pendingChatRequests = []; this._lastChatMessagesFetch = null; this.chatBatchSize = 100; this._sendVideoIfAvailable = true; } OCA.Talk.Signaling.Base = Base; OCA.Talk.Signaling.Base.prototype.on = function(ev, handler) { if (!this.handlers.hasOwnProperty(ev)) { this.handlers[ev] = [handler]; } else { this.handlers[ev].push(handler); } switch (ev) { case 'stunservers': case 'turnservers': var servers = this.settings[ev] || []; if (servers.length) { // The caller expects the handler to be called when the data // is available, so defer to simulate a delayed response. _.defer(function() { handler(servers); }); } break; } }; OCA.Talk.Signaling.Base.prototype.off = function(ev, handler) { if (!this.handlers.hasOwnProperty(ev)) { return; } var pos = this.handlers[ev].indexOf(handler); while (pos !== -1) { this.handlers[ev].splice(pos, 1); pos = this.handlers[ev].indexOf(handler); } }; OCA.Talk.Signaling.Base.prototype._trigger = function(ev, args) { var handlers = this.handlers[ev]; if (!handlers) { return; } handlers = handlers.slice(0); for (var i = 0, len = handlers.length; i < len; i++) { var handler = handlers[i]; handler.apply(handler, args); } }; OCA.Talk.Signaling.Base.prototype.isNoMcuWarningEnabled = function() { return !this.settings.hideWarning; }; OCA.Talk.Signaling.Base.prototype.getSessionid = function() { return this.sessionId; }; OCA.Talk.Signaling.Base.prototype.getCurrentCallFlags = function() { return this.currentCallFlags; }; OCA.Talk.Signaling.Base.prototype.disconnect = function() { this.sessionId = ''; this.currentCallToken = null; this.currentCallFlags = null; }; OCA.Talk.Signaling.Base.prototype.hasFeature = function(feature) { return this.features && this.features[feature]; }; OCA.Talk.Signaling.Base.prototype.emit = function(ev, data) { switch (ev) { case 'joinRoom': this.joinRoom(data); break; case 'joinCall': this.joinCall(data, arguments[2]); break; case 'leaveRoom': this.leaveCurrentRoom(); break; case 'leaveCall': this.leaveCurrentCall(); break; case 'message': this.sendCallMessage(data); break; } }; OCA.Talk.Signaling.Base.prototype.leaveCurrentRoom = function() { if (this.currentRoomToken) { this.leaveRoom(this.currentRoomToken); this.currentRoomToken = null; } }; OCA.Talk.Signaling.Base.prototype.leaveCurrentCall = function() { if (this.currentCallToken) { this.leaveCall(this.currentCallToken); this.currentCallToken = null; this.currentCallFlags = null; } }; OCA.Talk.Signaling.Base.prototype.setRoomCollection = function(rooms) { this.roomCollection = rooms; return this.syncRooms(); }; /** * Sets a single room to be synced. * * If there is a RoomCollection set the synchronization will be performed on * the RoomCollection instead and the given room will be ignored; setting a * single room is intended to be used only on public pages. * * @param OCA.SpreedMe.Models.Room room the room to sync. */ OCA.Talk.Signaling.Base.prototype.setRoom = function(room) { this.room = room; return this.syncRooms(); }; OCA.Talk.Signaling.Base.prototype.syncRooms = function() { var defer = $.Deferred(); if (this.roomCollection && OC.getCurrentUser().uid) { this.roomCollection.fetch({ success: function(roomCollection) { defer.resolve(roomCollection); } }); } else if (this.room) { this.room.fetch({ success: function(room) { defer.resolve(room); } }); } else { defer.resolve([]); } return defer; }; OCA.Talk.Signaling.Base.prototype.joinRoom = function(token, password) { $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/room', 2) + token + '/participants/active', type: 'POST', beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, data: { password: password }, success: function (result) { console.log("Joined", result); this.currentRoomToken = token; this._trigger('joinRoom', [token]); this._runPendingChatRequests(); if (this.currentCallToken === token) { // We were in this call before, join again. this.joinCall(token, this.currentCallFlags); } else { this.currentCallToken = null; this.currentCallFlags = null; } this._joinRoomSuccess(token, result.ocs.data.sessionId); }.bind(this), error: function (result) { if (result.status === 404 || result.status === 503) { // Room not found or maintenance mode OC.redirect(OC.generateUrl('apps/spreed')); } if (result.status === 403) { // This should not happen anymore since we ask for the password before // even trying to join the call, but let's keep it for now. OC.dialogs.prompt( t('spreed', 'Please enter the password for this call'), t('spreed','Password required'), function (result, password) { if (result && password !== '') { this.joinRoom(token, password); } }.bind(this), true, t('spreed','Password'), true ).then(function() { var $dialog = $('.oc-dialog:visible'); $dialog.find('.ui-icon').remove(); var $buttons = $dialog.find('button'); $buttons.eq(0).text(t('core', 'Cancel')); $buttons.eq(1).text(t('core', 'Submit')); }); } }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype._leaveRoomSuccess = function(/* token */) { // Override in subclasses if necessary. }; OCA.Talk.Signaling.Base.prototype.leaveRoom = function(token) { this.leaveCurrentCall(); this._trigger('leaveRoom', [token]); this._doLeaveRoom(token); $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/room', 2) + token + '/participants/active', method: 'DELETE', async: false, success: function () { this._leaveRoomSuccess(token); // We left the current room. if (token === this.currentRoomToken) { this.currentRoomToken = null; } }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype.getSendVideoIfAvailable = function() { return this._sendVideoIfAvailable; }; OCA.Talk.Signaling.Base.prototype.setSendVideoIfAvailable = function(sendVideoIfAvailable) { this._sendVideoIfAvailable = sendVideoIfAvailable; }; OCA.Talk.Signaling.Base.prototype._joinCallSuccess = function(/* token */) { // Override in subclasses if necessary. }; OCA.Talk.Signaling.Base.prototype.joinCall = function(token, flags) { $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/call', 2) + token, type: 'POST', data: { flags: flags }, beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, success: function () { this.currentCallToken = token; this.currentCallFlags = flags; this._trigger('joinCall', [token]); this._joinCallSuccess(token); }.bind(this), error: function () { // Room not found or maintenance mode OC.redirect(OC.generateUrl('apps/spreed')); }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype._leaveCallSuccess = function(/* token */) { // Override in subclasses if necessary. }; OCA.Talk.Signaling.Base.prototype.leaveCall = function(token, keepToken) { if (!token) { return; } $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/call', 2) + token, method: 'DELETE', async: false, success: function () { this._trigger('leaveCall', [token, keepToken]); this._leaveCallSuccess(token); // We left the current call. if (!keepToken && token === this.currentCallToken) { this.currentCallToken = null; this.currentCallFlags = null; } }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype._runPendingChatRequests = function() { while (this.pendingChatRequests.length) { var item = this.pendingChatRequests.shift(); this._doReceiveChatMessages.apply(this, item); } }; OCA.Talk.Signaling.Base.prototype.receiveChatMessages = function(lastKnownMessageId) { var defer = $.Deferred(); if (!this.currentRoomToken) { // Not in a room yet, defer loading of messages. this.pendingChatRequests.push([defer, lastKnownMessageId]); return defer; } return this._doReceiveChatMessages(defer, lastKnownMessageId); }; OCA.Talk.Signaling.Base.prototype._getChatRequestData = function(lastKnownMessageId) { return { lastKnownMessageId: lastKnownMessageId, limit: this.chatBatchSize, lookIntoFuture: 1 }; }; OCA.Talk.Signaling.Base.prototype._doReceiveChatMessages = function(defer, lastKnownMessageId) { $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/chat', 2) + this.currentRoomToken, method: 'GET', data: this._getChatRequestData(lastKnownMessageId), beforeSend: function (request) { defer.notify(request); request.setRequestHeader('Accept', 'application/json'); }, success: function (data, status, request) { if (status === "notmodified") { defer.resolve(null, request); } else { defer.resolve(data.ocs.data, request); } }.bind(this), error: function (result) { defer.reject(result); } }); return defer; }; OCA.Talk.Signaling.Base.prototype.startReceiveMessages = function() { this._waitTimeUntilRetry = 1; this.receiveMessagesAgain = true; this.lastKnownMessageId = 0; this._receiveChatMessages(); }; OCA.Talk.Signaling.Base.prototype.stopReceiveMessages = function() { this.receiveMessagesAgain = false; if (this._lastChatMessagesFetch !== null) { this._lastChatMessagesFetch.abort(); } }; OCA.Talk.Signaling.Base.prototype._receiveChatMessages = function() { if (this._lastChatMessagesFetch !== null) { // Another request is currently in progress. return; } this.receiveChatMessages(this.lastKnownMessageId) .progress(this._messagesReceiveStart.bind(this)) .done(this._messagesReceiveSuccess.bind(this)) .fail(this._messagesReceiveError.bind(this)); }; OCA.Talk.Signaling.Base.prototype._messagesReceiveStart = function(xhr) { this._lastChatMessagesFetch = xhr; }; OCA.Talk.Signaling.Base.prototype._messagesReceiveSuccess = function(messages, xhr) { var lastKnownMessageId = xhr.getResponseHeader("X-Chat-Last-Given"); if (lastKnownMessageId !== null) { this.lastKnownMessageId = lastKnownMessageId; } this._lastChatMessagesFetch = null; this._waitTimeUntilRetry = 1; // Fetch more messages if PHP backend, or if the returned status is not // "304 Not modified" (as in that case there could be more messages that // need to be fetched). if (this.receiveMessagesAgain || xhr.status !== 304) { this._receiveChatMessages(); } if (messages && messages.length) { this._trigger("chatMessagesReceived", [messages]); } }; OCA.Talk.Signaling.Base.prototype._retryChatLoadingOnError = function() { return this.receiveMessagesAgain; }; OCA.Talk.Signaling.Base.prototype._messagesReceiveError = function(/* result */) { this._lastChatMessagesFetch = null; if (this._retryChatLoadingOnError()) { _.delay(_.bind(this._receiveChatMessages, this), this._waitTimeUntilRetry * 1000); // Increase the wait time until retry to at most 64 seconds. if (this._waitTimeUntilRetry < 64) { this._waitTimeUntilRetry *= 2; } } }; // Connection to the internal signaling server provided by the app. function Internal(settings) { OCA.Talk.Signaling.Base.prototype.constructor.apply(this, arguments); this.hideWarning = settings.hideWarning; this.spreedArrayConnection = []; this.pullMessagesFails = 0; this.pullMessagesRequest = null; this.isSendingMessages = false; this.sendInterval = window.setInterval(function(){ this.sendPendingMessages(); }.bind(this), 500); } Internal.prototype = new OCA.Talk.Signaling.Base(); Internal.prototype.constructor = Internal; OCA.Talk.Signaling.Internal = Internal; OCA.Talk.Signaling.Internal.prototype.disconnect = function() { this.spreedArrayConnection = []; if (this.sendInterval) { window.clearInterval(this.sendInterval); this.sendInterval = null; } if (this.roomPoller) { window.clearInterval(this.roomPoller); this.roomPoller = null; } OCA.Talk.Signaling.Base.prototype.disconnect.apply(this, arguments); }; OCA.Talk.Signaling.Internal.prototype.on = function(ev/*, handler*/) { OCA.Talk.Signaling.Base.prototype.on.apply(this, arguments); switch (ev) { case 'connect': // A connection is established if we can perform a request // through it. this._sendMessageWithCallback(ev); break; } }; OCA.Talk.Signaling.Internal.prototype.forceReconnect = function(newSession, flags) { if (newSession) { console.log('Forced reconnects with a new session are not supported in the internal signaling; same session as before will be used'); } if (flags !== undefined) { this.currentCallFlags = flags; } // FIXME Naive reconnection routine; as the same session is kept peers // must be explicitly ended before the reconnection is forced. this.leaveCall(this.currentCallToken, true); this.joinCall(this.currentCallToken); }; OCA.Talk.Signaling.Internal.prototype._sendMessageWithCallback = function(ev) { var message = [{ ev: ev }]; this._sendMessages(message).done(function(result) { this._trigger(ev, [result.ocs.data]); }.bind(this)).fail(function(/*xhr, textStatus, errorThrown*/) { console.log('Sending signaling message with callback has failed.'); // TODO: Add error handling }); }; OCA.Talk.Signaling.Internal.prototype._sendMessages = function(messages) { var defer = $.Deferred(); $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + this.currentRoomToken, type: 'POST', data: {messages: JSON.stringify(messages)}, beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, success: function (result) { defer.resolve(result); }, error: function (xhr, textStatus, errorThrown) { defer.reject(xhr, textStatus, errorThrown); } }); return defer; }; OCA.Talk.Signaling.Internal.prototype._joinRoomSuccess = function(token, sessionId) { this.sessionId = sessionId; this._startPullingMessages(); }; OCA.Talk.Signaling.Internal.prototype._doLeaveRoom = function(token) { if (token === this.currentRoomToken && !this.roomCollection) { window.clearInterval(this.roomPoller); this.roomPoller = null; } }; OCA.Talk.Signaling.Internal.prototype.sendCallMessage = function(data) { if(data.type === 'answer') { console.log("ANSWER", data); } else if(data.type === 'offer') { console.log("OFFER", data); } this.spreedArrayConnection.push({ ev: "message", fn: JSON.stringify(data), sessionId: this.sessionId }); }; OCA.Talk.Signaling.Internal.prototype.setRoomCollection = function(/*rooms*/) { this._pollForRoomChanges(); return OCA.Talk.Signaling.Base.prototype.setRoomCollection.apply(this, arguments); }; OCA.Talk.Signaling.Internal.prototype.setRoom = function(/*room*/) { this._pollForRoomChanges(); return OCA.Talk.Signaling.Base.prototype.setRoom.apply(this, arguments); }; OCA.Talk.Signaling.Internal.prototype._pollForRoomChanges = function() { if (this.roomPoller) { window.clearInterval(this.roomPoller); } this.roomPoller = window.setInterval(function() { this.syncRooms(); }.bind(this), 10000); }; /** * @private */ OCA.Talk.Signaling.Internal.prototype._startPullingMessages = function() { if (!this.currentRoomToken) { return; } // Abort ongoing request if (this.pullMessagesRequest !== null) { this.pullMessagesRequest.abort(); } // Connect to the messages endpoint and pull for new messages this.pullMessagesRequest = $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + this.currentRoomToken, type: 'GET', dataType: 'json', beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, success: function (result) { this.pullMessagesFails = 0; $.each(result.ocs.data, function(id, message) { this._trigger('onBeforeReceiveMessage', [message]); switch(message.type) { case "usersInRoom": this._trigger('usersInRoom', [message.data]); this._trigger('participantListChanged'); break; case "message": if (typeof(message.data) === 'string') { message.data = JSON.parse(message.data); } this._trigger('message', [message.data]); break; default: console.log('Unknown Signaling Message'); break; } this._trigger('onAfterReceiveMessage', [message]); }.bind(this)); this._startPullingMessages(); }.bind(this), error: function (jqXHR, textStatus/*, errorThrown*/) { if (jqXHR.status === 0 && textStatus === 'abort') { // Request has been aborted. Ignore. } else if (this.currentRoomToken) { if (this.pullMessagesFails >= 3) { console.log('Stop pulling messages after repeated failures'); this._trigger('pullMessagesStoppedOnFail'); return; } this.pullMessagesFails++; //Retry to pull messages after 5 seconds window.setTimeout(function() { this._startPullingMessages(); }.bind(this), 5000); } }.bind(this) }); }; /** * @private */ OCA.Talk.Signaling.Internal.prototype.sendPendingMessages = function() { if (!this.spreedArrayConnection.length || this.isSendingMessages) { return; } var pendingMessagesLength = this.spreedArrayConnection.length; this.isSendingMessages = true; this._sendMessages(this.spreedArrayConnection).done(function(/*result*/) { this.spreedArrayConnection.splice(0, pendingMessagesLength); this.isSendingMessages = false; }.bind(this)).fail(function(/*xhr, textStatus, errorThrown*/) { console.log('Sending pending signaling messages has failed.'); this.isSendingMessages = false; }.bind(this)); }; function Standalone(settings, urls) { OCA.Talk.Signaling.Base.prototype.constructor.apply(this, arguments); if (typeof(urls) === "string") { urls = [urls]; } // We can connect to any of the servers. var idx = Math.floor(Math.random() * urls.length); // TODO(jojo): Try other server if connection fails. var url = urls[idx]; // Make sure we are using websocket urls. if (url.indexOf("https://") === 0) { url = "wss://" + url.substr(8); } else if (url.indexOf("http://") === 0) { url = "ws://" + url.substr(7); } if (url[url.length - 1] === "/") { url = url.substr(0, url.length - 1); } this.url = url + "/spreed"; this.initialReconnectIntervalMs = 1000; this.maxReconnectIntervalMs = 16000; this.reconnectIntervalMs = this.initialReconnectIntervalMs; this.joinedUsers = {}; this.rooms = []; window.setInterval(function() { // Update the room list all 30 seconds to check for new messages and // mentions as well as marking them read via other devices. this.internalSyncRooms(); }.bind(this), 30000); this.connect(); } Standalone.prototype = new OCA.Talk.Signaling.Base(); Standalone.prototype.constructor = Standalone; OCA.Talk.Signaling.Standalone = Standalone; OCA.Talk.Signaling.Standalone.prototype.reconnect = function() { if (this.reconnectTimer) { return; } // Wiggle interval a little bit to prevent all clients from connecting // simultaneously in case the server connection is interrupted. var interval = this.reconnectIntervalMs - (this.reconnectIntervalMs / 2) + (this.reconnectIntervalMs * Math.random()); console.log("Reconnect in", interval); this.reconnected = true; this.reconnectTimer = window.setTimeout(function() { this.reconnectTimer = null; this.connect(); }.bind(this), interval); this.reconnectIntervalMs = this.reconnectIntervalMs * 2; if (this.reconnectIntervalMs > this.maxReconnectIntervalMs) { this.reconnectIntervalMs = this.maxReconnectIntervalMs; } if (this.socket) { this.socket.close(); this.socket = null; } }; OCA.Talk.Signaling.Standalone.prototype.connect = function() { console.log("Connecting to", this.url); this.callbacks = {}; this.id = 1; this.pendingMessages = []; this.connected = false; this._forceReconnect = false; this.socket = new WebSocket(this.url); window.signalingSocket = this.socket; this.socket.onopen = function(event) { console.log("Connected", event); this.reconnectIntervalMs = this.initialReconnectIntervalMs; this.sendHello(); }.bind(this); this.socket.onerror = function(event) { console.log("Error", event); this.reconnect(); }.bind(this); this.socket.onclose = function(event) { console.log("Close", event); this.reconnect(); }.bind(this); this.socket.onmessage = function(event) { var data = event.data; if (typeof(data) === "string") { data = JSON.parse(data); } console.log("Received", data); var id = data.id; if (id && this.callbacks.hasOwnProperty(id)) { var cb = this.callbacks[id]; delete this.callbacks[id]; cb(data); } this._trigger('onBeforeReceiveMessage', [data]); switch (data.type) { case "hello": if (!id) { // Only process if not received as result of our "hello". this.helloResponseReceived(data); } break; case "room": if (this.currentRoomToken && data.room.roomid !== this.currentRoomToken) { this._trigger('roomChanged', [this.currentRoomToken, data.room.roomid]); this.joinedUsers = {}; this.currentRoomToken = null; } else { // TODO(fancycode): Only fetch properties of room that was modified. this.internalSyncRooms(); } break; case "event": this.processEvent(data); break; case "message": data.message.data.from = data.message.sender.sessionid; this._trigger("message", [data.message.data]); break; default: if (!id) { console.log("Ignore unknown event", data); } break; } this._trigger('onAfterReceiveMessage', [data]); }.bind(this); }; OCA.Talk.Signaling.Standalone.prototype.sendBye = function() { if (this.connected) { this.doSend({ "type": "bye", "bye": {} }); } this.resumeId = null; this.signalingRoomJoined = null; }; OCA.Talk.Signaling.Standalone.prototype.disconnect = function() { this.sendBye(); if (this.socket) { this.socket.close(); this.socket = null; } OCA.Talk.Signaling.Base.prototype.disconnect.apply(this, arguments); }; OCA.Talk.Signaling.Standalone.prototype.forceReconnect = function(newSession, flags) { if (flags !== undefined) { this.currentCallFlags = flags; } if (!this.connected) { if (!newSession) { // Not connected, will do reconnect anyway. return; } this._forceReconnect = true; return; } this._forceReconnect = false; if (newSession) { if (this.currentCallToken) { // Mark this session as "no longer in the call". this.leaveCall(this.currentCallToken, true); } this.sendBye(); } if (this.socket) { // Trigger reconnect. this.socket.close(); } }; OCA.Talk.Signaling.Standalone.prototype.sendCallMessage = function(data) { this.doSend({ "type": "message", "message": { "recipient": { "type": "session", "sessionid": data.to }, "data": data } }); }; OCA.Talk.Signaling.Standalone.prototype.sendRoomMessage = function(data) { if (!this.currentCallToken) { console.warn("Not in a room, not sending room message", data); return; } this.doSend({ "type": "message", "message": { "recipient": { "type": "room" }, "data": data } }); }; OCA.Talk.Signaling.Standalone.prototype.doSend = function(msg, callback) { if (!this.connected && msg.type !== "hello" || this.socket === null) { // Defer sending any messages until the hello response has been // received and when the socket is open this.pendingMessages.push([msg, callback]); return; } if (callback) { var id = this.id++; this.callbacks[id] = callback; msg["id"] = ""+id; } console.log("Sending", msg); this.socket.send(JSON.stringify(msg)); }; OCA.Talk.Signaling.Standalone.prototype.sendHello = function() { var msg; if (this.resumeId) { console.log("Trying to resume session", this.sessionId); msg = { "type": "hello", "hello": { "version": "1.0", "resumeid": this.resumeId } }; } else { // Already reconnected with a new session. this._forceReconnect = false; var user = OC.getCurrentUser(); var url = OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + 'backend'; msg = { "type": "hello", "hello": { "version": "1.0", "auth": { "url": url, "params": { "userid": user.uid, "ticket": this.settings.ticket } } } }; } this.doSend(msg, this.helloResponseReceived.bind(this)); }; OCA.Talk.Signaling.Standalone.prototype.helloResponseReceived = function(data) { console.log("Hello response received", data); if (data.type !== "hello") { if (this.resumeId) { // Resuming the session failed, reconnect as new session. this.resumeId = ''; this.sendHello(); return; } // TODO(fancycode): How should this be handled better? console.error("Could not connect to server", data); this.reconnect(); return; } var resumedSession = !!this.resumeId; this.connected = true; if (this._forceReconnect && resumedSession) { console.log("Perform pending forced reconnect"); this.forceReconnect(true); return; } this.sessionId = data.hello.sessionid; this.resumeId = data.hello.resumeid; this.features = {}; var i; if (data.hello.server && data.hello.server.features) { var features = data.hello.server.features; for (i = 0; i < features.length; i++) { this.features[features[i]] = true; } } var messages = this.pendingMessages; this.pendingMessages = []; for (i = 0; i < messages.length; i++) { var msg = messages[i][0]; var callback = messages[i][1]; this.doSend(msg, callback); } this._trigger("connect"); if (this.reconnected) { // The list of rooms might have changed while we were not connected, // so perform resync once. this.internalSyncRooms(); // Load any chat messages that might have been missed. this._receiveChatMessages(); } if (!resumedSession && this.currentRoomToken) { this.joinRoom(this.currentRoomToken); } }; OCA.Talk.Signaling.Standalone.prototype.setRoom = function(/* room */) { OCA.Talk.Signaling.Base.prototype.setRoom.apply(this, arguments); return this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.joinRoom = function(token /*, password */) { if (!this.sessionId) { // If we would join without a connection to the signaling server here, // the room would be re-joined again in the "helloResponseReceived" // callback, leading to two entries for anonymous participants. console.log("Not connected to signaling server yet, defer joining room", token); this.currentRoomToken = token; return; } return OCA.Talk.Signaling.Base.prototype.joinRoom.apply(this, arguments); }; OCA.Talk.Signaling.Standalone.prototype._joinRoomSuccess = function(token, nextcloudSessionId) { if (!this.sessionId) { console.log("No hello response received yet, not joining room", token); return; } console.log("Join room", token); this.doSend({ "type": "room", "room": { "roomid": token, // Pass the Nextcloud session id to the signaling server. The // session id will be passed through to Nextcloud to check if // the (Nextcloud) user is allowed to join the room. "sessionid": nextcloudSessionId, } }, function(data) { this.joinResponseReceived(data, token); }.bind(this)); }; OCA.Talk.Signaling.Standalone.prototype.joinCall = function(token, flags) { if (this.signalingRoomJoined !== token) { console.log("Not joined room yet, not joining call", token); this.pendingJoinCall = { token: token, flags: flags }; return; } OCA.Talk.Signaling.Base.prototype.joinCall.apply(this, arguments); }; OCA.Talk.Signaling.Standalone.prototype._joinCallSuccess = function(/* token */) { // Update room list to fetch modified properties. this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype._leaveCallSuccess = function(/* token */) { // Update room list to fetch modified properties. this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.joinResponseReceived = function(data, token) { console.log("Joined", data, token); this.signalingRoomJoined = token; if (this.pendingJoinCall && token === this.pendingJoinCall.token) { this.joinCall(this.pendingJoinCall.token, this.pendingJoinCall.flags); this.pendingJoinCall = null; } if (this.roomCollection) { // The list of rooms is not fetched from the server. Update ping // of joined room so it gets sorted to the top. this.roomCollection.forEach(function(room) { if (room.get('token') === token) { room.set('lastPing', (new Date()).getTime() / 1000); } }); this.roomCollection.sort(); } }; OCA.Talk.Signaling.Standalone.prototype._doLeaveRoom = function(token) { console.log("Leave room", token); this.doSend({ "type": "room", "room": { "roomid": "" } }, function(data) { console.log("Left", data); this.signalingRoomJoined = null; // Any users we previously had in the room also "left" for us. var leftUsers = _.keys(this.joinedUsers); if (leftUsers.length) { this._trigger("usersLeft", [leftUsers]); } this.joinedUsers = {}; }.bind(this)); }; OCA.Talk.Signaling.Standalone.prototype.processEvent = function(data) { switch (data.event.target) { case "room": this.processRoomEvent(data); break; case "roomlist": this.processRoomListEvent(data); break; case "participants": this.processRoomParticipantsEvent(data); break; default: console.log("Unsupported event target", data); break; } }; OCA.Talk.Signaling.Standalone.prototype.processRoomEvent = function(data) { var i; switch (data.event.type) { case "join": var joinedUsers = data.event.join || []; if (joinedUsers.length) { console.log("Users joined", joinedUsers); var leftUsers = {}; if (this.reconnected) { this.reconnected = false; // The browser reconnected, some of the previous sessions // may now no longer exist. leftUsers = _.extend({}, this.joinedUsers); } for (i = 0; i < joinedUsers.length; i++) { this.joinedUsers[joinedUsers[i].sessionid] = true; delete leftUsers[joinedUsers[i].sessionid]; } leftUsers = _.keys(leftUsers); if (leftUsers.length) { this._trigger("usersLeft", [leftUsers]); } this._trigger("usersJoined", [joinedUsers]); this._trigger('participantListChanged'); } break; case "leave": var leftSessionIds = data.event.leave || []; if (leftSessionIds.length) { console.log("Users left", leftSessionIds); for (i = 0; i < leftSessionIds.length; i++) { delete this.joinedUsers[leftSessionIds[i]]; } this._trigger("usersLeft", [leftSessionIds]); this._trigger('participantListChanged'); } break; case "message": this.processRoomMessageEvent(data.event.message.data); break; default: console.log("Unknown room event", data); break; } }; OCA.Talk.Signaling.Standalone.prototype.processRoomMessageEvent = function(data) { switch (data.type) { case "chat": this._receiveChatMessages(); break; default: console.log("Unknown room message event", data); } }; OCA.Talk.Signaling.Standalone.prototype.setRoomCollection = function(/* rooms */) { OCA.Talk.Signaling.Base.prototype.setRoomCollection.apply(this, arguments); // Retrieve initial list of rooms for this user. return this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.syncRooms = function() { if (this._pendingSyncRooms) { // A sync request is already in progress, don't start another one. return this._pendingSyncRooms; } // Never manually sync rooms, will be done based on notifications // from the signaling server. var defer = $.Deferred(); defer.resolve(this.rooms); return defer; }; OCA.Talk.Signaling.Standalone.prototype.internalSyncRooms = function() { if (this._pendingSyncRooms) { // A sync request is already in progress, don't start another one. return this._pendingSyncRooms; } var defer = $.Deferred(); this._pendingSyncRooms = OCA.Talk.Signaling.Base.prototype.syncRooms.apply(this, arguments); this._pendingSyncRooms.then(function(rooms) { this._pendingSyncRooms = null; this.rooms = rooms; defer.resolve(rooms); }.bind(this)); return defer; }; OCA.Talk.Signaling.Standalone.prototype.processRoomListEvent = function(data) { console.log("Room list event", data); this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.processRoomParticipantsEvent = function(data) { switch (data.event.type) { case "update": this._trigger("usersChanged", [data.event.update.users || []]); this._trigger('participantListChanged'); this.internalSyncRooms(); break; default: console.log("Unknown room participant event", data); break; } }; OCA.Talk.Signaling.Standalone.prototype._getChatRequestData = function(/* lastKnownMessageId */) { var data = OCA.Talk.Signaling.Base.prototype._getChatRequestData.apply(this, arguments); // Don't keep connection open and wait for more messages, will be done // through another event on the WebSocket. data.timeout = 0; return data; }; OCA.Talk.Signaling.Standalone.prototype._retryChatLoadingOnError = function() { // We don't regularly poll for changes, so need to always retry loading // of chat messages in case of errors. return true; }; OCA.Talk.Signaling.Standalone.prototype.startReceiveMessages = function() { OCA.Talk.Signaling.Base.prototype.startReceiveMessages.apply(this, arguments); // We will be notified when to load new messages. this.receiveMessagesAgain = false; }; OCA.Talk.Signaling.Standalone.prototype.requestOffer = function(sessionid, roomType) { if (!this.hasFeature("mcu")) { console.warn("Can't request an offer without a MCU."); return; } if (typeof(sessionid) !== "string") { // Got a user object. sessionid = sessionid.sessionId || sessionid.sessionid; } console.log("Request offer from", sessionid); this.doSend({ "type": "message", "message": { "recipient": { "type": "session", "sessionid": sessionid }, "data": { "type": "requestoffer", "roomType": roomType } } }); }; OCA.Talk.Signaling.Standalone.prototype.sendOffer = function(sessionid, roomType) { // TODO(jojo): This should go away and "requestOffer" should be used // instead by peers that want an offer by the MCU. See the calling // location for further details. if (!this.hasFeature("mcu")) { console.warn("Can't send an offer without a MCU."); return; } if (typeof(sessionid) !== "string") { // Got a user object. sessionid = sessionid.sessionId || sessionid.sessionid; } console.log("Send offer to", sessionid); this.doSend({ "type": "message", "message": { "recipient": { "type": "session", "sessionid": sessionid }, "data": { "type": "sendoffer", "roomType": roomType } } }); }; })(OCA, OC, $);
js/signaling.js
/** @global console */ (function(OCA, OC, $) { 'use strict'; OCA.Talk = OCA.Talk || {}; OCA.Talk.Signaling = { Base: {}, Internal: {}, Standalone: {}, /** * Loads the signaling settings. * * The signaling settings are set in the DOM element in which * "createConnection" expects to find them; if the DOM element already * exists it is assumed that the settings are already loaded. * * @return Deferred a Deferred object that will be resolved once the * settings are loaded. */ loadSettings: function() { var deferred = $.Deferred(); if ($('#app #signaling-settings').length > 0) { deferred.resolve(); return deferred.promise(); } if ($('#app').length === 0) { $('body').append('<div id="app"></div>'); } $('#app').append('<script type="text/json" id="signaling-settings"></script>'); $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + 'settings', type: 'GET', dataType: 'json', success: function (result) { $('#app #signaling-settings').text(JSON.stringify(result.ocs.data)); deferred.resolve(); }, error: function (xhr, textStatus, errorThrown) { deferred.reject(xhr, textStatus, errorThrown); } }); return deferred.promise(); }, createConnection: function() { var settings = $("#app #signaling-settings").text(); if (settings) { settings = JSON.parse(settings); } else { settings = {}; } var urls = settings.server; if (urls && urls.length) { return new OCA.Talk.Signaling.Standalone(settings, urls); } else { return new OCA.Talk.Signaling.Internal(settings); } } }; function Base(settings) { this.settings = settings; this.sessionId = ''; this.currentRoomToken = null; this.currentCallToken = null; this.currentCallFlags = null; this.handlers = {}; this.features = {}; this.pendingChatRequests = []; this._lastChatMessagesFetch = null; this.chatBatchSize = 100; this._sendVideoIfAvailable = true; } OCA.Talk.Signaling.Base = Base; OCA.Talk.Signaling.Base.prototype.on = function(ev, handler) { if (!this.handlers.hasOwnProperty(ev)) { this.handlers[ev] = [handler]; } else { this.handlers[ev].push(handler); } switch (ev) { case 'stunservers': case 'turnservers': var servers = this.settings[ev] || []; if (servers.length) { // The caller expects the handler to be called when the data // is available, so defer to simulate a delayed response. _.defer(function() { handler(servers); }); } break; } }; OCA.Talk.Signaling.Base.prototype.off = function(ev, handler) { if (!this.handlers.hasOwnProperty(ev)) { return; } var pos = this.handlers[ev].indexOf(handler); while (pos !== -1) { this.handlers[ev].splice(pos, 1); pos = this.handlers[ev].indexOf(handler); } }; OCA.Talk.Signaling.Base.prototype._trigger = function(ev, args) { var handlers = this.handlers[ev]; if (!handlers) { return; } handlers = handlers.slice(0); for (var i = 0, len = handlers.length; i < len; i++) { var handler = handlers[i]; handler.apply(handler, args); } }; OCA.Talk.Signaling.Base.prototype.isNoMcuWarningEnabled = function() { return !this.settings.hideWarning; }; OCA.Talk.Signaling.Base.prototype.getSessionid = function() { return this.sessionId; }; OCA.Talk.Signaling.Base.prototype.getCurrentCallFlags = function() { return this.currentCallFlags; }; OCA.Talk.Signaling.Base.prototype.disconnect = function() { this.sessionId = ''; this.currentCallToken = null; this.currentCallFlags = null; }; OCA.Talk.Signaling.Base.prototype.hasFeature = function(feature) { return this.features && this.features[feature]; }; OCA.Talk.Signaling.Base.prototype.emit = function(ev, data) { switch (ev) { case 'joinRoom': this.joinRoom(data); break; case 'joinCall': this.joinCall(data, arguments[2]); break; case 'leaveRoom': this.leaveCurrentRoom(); break; case 'leaveCall': this.leaveCurrentCall(); break; case 'message': this.sendCallMessage(data); break; } }; OCA.Talk.Signaling.Base.prototype.leaveCurrentRoom = function() { if (this.currentRoomToken) { this.leaveRoom(this.currentRoomToken); this.currentRoomToken = null; } }; OCA.Talk.Signaling.Base.prototype.leaveCurrentCall = function() { if (this.currentCallToken) { this.leaveCall(this.currentCallToken); this.currentCallToken = null; this.currentCallFlags = null; } }; OCA.Talk.Signaling.Base.prototype.setRoomCollection = function(rooms) { this.roomCollection = rooms; return this.syncRooms(); }; /** * Sets a single room to be synced. * * If there is a RoomCollection set the synchronization will be performed on * the RoomCollection instead and the given room will be ignored; setting a * single room is intended to be used only on public pages. * * @param OCA.SpreedMe.Models.Room room the room to sync. */ OCA.Talk.Signaling.Base.prototype.setRoom = function(room) { this.room = room; return this.syncRooms(); }; OCA.Talk.Signaling.Base.prototype.syncRooms = function() { var defer = $.Deferred(); if (this.roomCollection && OC.getCurrentUser().uid) { this.roomCollection.fetch({ success: function(roomCollection) { defer.resolve(roomCollection); } }); } else if (this.room) { this.room.fetch({ success: function(room) { defer.resolve(room); } }); } else { defer.resolve([]); } return defer; }; OCA.Talk.Signaling.Base.prototype.joinRoom = function(token, password) { $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/room', 2) + token + '/participants/active', type: 'POST', beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, data: { password: password }, success: function (result) { console.log("Joined", result); this.currentRoomToken = token; this._trigger('joinRoom', [token]); this._runPendingChatRequests(); if (this.currentCallToken === token) { // We were in this call before, join again. this.joinCall(token, this.currentCallFlags); } else { this.currentCallToken = null; this.currentCallFlags = null; } this._joinRoomSuccess(token, result.ocs.data.sessionId); }.bind(this), error: function (result) { if (result.status === 404 || result.status === 503) { // Room not found or maintenance mode OC.redirect(OC.generateUrl('apps/spreed')); } if (result.status === 403) { // This should not happen anymore since we ask for the password before // even trying to join the call, but let's keep it for now. OC.dialogs.prompt( t('spreed', 'Please enter the password for this call'), t('spreed','Password required'), function (result, password) { if (result && password !== '') { this.joinRoom(token, password); } }.bind(this), true, t('spreed','Password'), true ).then(function() { var $dialog = $('.oc-dialog:visible'); $dialog.find('.ui-icon').remove(); var $buttons = $dialog.find('button'); $buttons.eq(0).text(t('core', 'Cancel')); $buttons.eq(1).text(t('core', 'Submit')); }); } }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype._leaveRoomSuccess = function(/* token */) { // Override in subclasses if necessary. }; OCA.Talk.Signaling.Base.prototype.leaveRoom = function(token) { this.leaveCurrentCall(); this._trigger('leaveRoom', [token]); this._doLeaveRoom(token); $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/room', 2) + token + '/participants/active', method: 'DELETE', async: false, success: function () { this._leaveRoomSuccess(token); // We left the current room. if (token === this.currentRoomToken) { this.currentRoomToken = null; } }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype.getSendVideoIfAvailable = function() { return this._sendVideoIfAvailable; }; OCA.Talk.Signaling.Base.prototype.setSendVideoIfAvailable = function(sendVideoIfAvailable) { this._sendVideoIfAvailable = sendVideoIfAvailable; }; OCA.Talk.Signaling.Base.prototype._joinCallSuccess = function(/* token */) { // Override in subclasses if necessary. }; OCA.Talk.Signaling.Base.prototype.joinCall = function(token, flags) { $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/call', 2) + token, type: 'POST', data: { flags: flags }, beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, success: function () { this.currentCallToken = token; this.currentCallFlags = flags; this._trigger('joinCall', [token]); this._joinCallSuccess(token); }.bind(this), error: function () { // Room not found or maintenance mode OC.redirect(OC.generateUrl('apps/spreed')); }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype._leaveCallSuccess = function(/* token */) { // Override in subclasses if necessary. }; OCA.Talk.Signaling.Base.prototype.leaveCall = function(token, keepToken) { if (!token) { return; } $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/call', 2) + token, method: 'DELETE', async: false, success: function () { this._trigger('leaveCall', [token, keepToken]); this._leaveCallSuccess(token); // We left the current call. if (!keepToken && token === this.currentCallToken) { this.currentCallToken = null; this.currentCallFlags = null; } }.bind(this) }); }; OCA.Talk.Signaling.Base.prototype._runPendingChatRequests = function() { while (this.pendingChatRequests.length) { var item = this.pendingChatRequests.shift(); this._doReceiveChatMessages.apply(this, item); } }; OCA.Talk.Signaling.Base.prototype.receiveChatMessages = function(lastKnownMessageId) { var defer = $.Deferred(); if (!this.currentRoomToken) { // Not in a room yet, defer loading of messages. this.pendingChatRequests.push([defer, lastKnownMessageId]); return defer; } return this._doReceiveChatMessages(defer, lastKnownMessageId); }; OCA.Talk.Signaling.Base.prototype._getChatRequestData = function(lastKnownMessageId) { return { lastKnownMessageId: lastKnownMessageId, limit: this.chatBatchSize, lookIntoFuture: 1 }; }; OCA.Talk.Signaling.Base.prototype._doReceiveChatMessages = function(defer, lastKnownMessageId) { $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/chat', 2) + this.currentRoomToken, method: 'GET', data: this._getChatRequestData(lastKnownMessageId), beforeSend: function (request) { defer.notify(request); request.setRequestHeader('Accept', 'application/json'); }, success: function (data, status, request) { if (status === "notmodified") { defer.resolve(null, request); } else { defer.resolve(data.ocs.data, request); } }.bind(this), error: function (result) { defer.reject(result); } }); return defer; }; OCA.Talk.Signaling.Base.prototype.startReceiveMessages = function() { this._waitTimeUntilRetry = 1; this.receiveMessagesAgain = true; this.lastKnownMessageId = 0; this._receiveChatMessages(); }; OCA.Talk.Signaling.Base.prototype.stopReceiveMessages = function() { this.receiveMessagesAgain = false; if (this._lastChatMessagesFetch !== null) { this._lastChatMessagesFetch.abort(); } }; OCA.Talk.Signaling.Base.prototype._receiveChatMessages = function() { if (this._lastChatMessagesFetch !== null) { // Another request is currently in progress. return; } this.receiveChatMessages(this.lastKnownMessageId) .progress(this._messagesReceiveStart.bind(this)) .done(this._messagesReceiveSuccess.bind(this)) .fail(this._messagesReceiveError.bind(this)); }; OCA.Talk.Signaling.Base.prototype._messagesReceiveStart = function(xhr) { this._lastChatMessagesFetch = xhr; }; OCA.Talk.Signaling.Base.prototype._messagesReceiveSuccess = function(messages, xhr) { var lastKnownMessageId = xhr.getResponseHeader("X-Chat-Last-Given"); if (lastKnownMessageId !== null) { this.lastKnownMessageId = lastKnownMessageId; } this._lastChatMessagesFetch = null; this._waitTimeUntilRetry = 1; // Fetch more messages if PHP backend, or if the returned status is not // "304 Not modified" (as in that case there could be more messages that // need to be fetched). if (this.receiveMessagesAgain || xhr.status !== 304) { this._receiveChatMessages(); } if (messages && messages.length) { this._trigger("chatMessagesReceived", [messages]); } }; OCA.Talk.Signaling.Base.prototype._retryChatLoadingOnError = function() { return this.receiveMessagesAgain; }; OCA.Talk.Signaling.Base.prototype._messagesReceiveError = function(/* result */) { this._lastChatMessagesFetch = null; if (this._retryChatLoadingOnError()) { _.delay(_.bind(this._receiveChatMessages, this), this._waitTimeUntilRetry * 1000); // Increase the wait time until retry to at most 64 seconds. if (this._waitTimeUntilRetry < 64) { this._waitTimeUntilRetry *= 2; } } }; // Connection to the internal signaling server provided by the app. function Internal(settings) { OCA.Talk.Signaling.Base.prototype.constructor.apply(this, arguments); this.hideWarning = settings.hideWarning; this.spreedArrayConnection = []; this.pullMessagesFails = 0; this.pullMessagesRequest = null; this.isSendingMessages = false; this.sendInterval = window.setInterval(function(){ this.sendPendingMessages(); }.bind(this), 500); } Internal.prototype = new OCA.Talk.Signaling.Base(); Internal.prototype.constructor = Internal; OCA.Talk.Signaling.Internal = Internal; OCA.Talk.Signaling.Internal.prototype.disconnect = function() { this.spreedArrayConnection = []; if (this.sendInterval) { window.clearInterval(this.sendInterval); this.sendInterval = null; } if (this.roomPoller) { window.clearInterval(this.roomPoller); this.roomPoller = null; } OCA.Talk.Signaling.Base.prototype.disconnect.apply(this, arguments); }; OCA.Talk.Signaling.Internal.prototype.on = function(ev/*, handler*/) { OCA.Talk.Signaling.Base.prototype.on.apply(this, arguments); switch (ev) { case 'connect': // A connection is established if we can perform a request // through it. this._sendMessageWithCallback(ev); break; } }; OCA.Talk.Signaling.Internal.prototype.forceReconnect = function(newSession, flags) { if (newSession) { console.log('Forced reconnects with a new session are not supported in the internal signaling; same session as before will be used'); } if (flags !== undefined) { this.currentCallFlags = flags; } // FIXME Naive reconnection routine; as the same session is kept peers // must be explicitly ended before the reconnection is forced. this.leaveCall(this.currentCallToken, true); this.joinCall(this.currentCallToken); }; OCA.Talk.Signaling.Internal.prototype._sendMessageWithCallback = function(ev) { var message = [{ ev: ev }]; this._sendMessages(message).done(function(result) { this._trigger(ev, [result.ocs.data]); }.bind(this)).fail(function(/*xhr, textStatus, errorThrown*/) { console.log('Sending signaling message with callback has failed.'); // TODO: Add error handling }); }; OCA.Talk.Signaling.Internal.prototype._sendMessages = function(messages) { var defer = $.Deferred(); $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + this.currentRoomToken, type: 'POST', data: {messages: JSON.stringify(messages)}, beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, success: function (result) { defer.resolve(result); }, error: function (xhr, textStatus, errorThrown) { defer.reject(xhr, textStatus, errorThrown); } }); return defer; }; OCA.Talk.Signaling.Internal.prototype._joinRoomSuccess = function(token, sessionId) { this.sessionId = sessionId; this._startPullingMessages(); }; OCA.Talk.Signaling.Internal.prototype._doLeaveRoom = function(token) { if (token === this.currentRoomToken && !this.roomCollection) { window.clearInterval(this.roomPoller); this.roomPoller = null; } }; OCA.Talk.Signaling.Internal.prototype.sendCallMessage = function(data) { if(data.type === 'answer') { console.log("ANSWER", data); } else if(data.type === 'offer') { console.log("OFFER", data); } this.spreedArrayConnection.push({ ev: "message", fn: JSON.stringify(data), sessionId: this.sessionId }); }; OCA.Talk.Signaling.Internal.prototype.setRoomCollection = function(/*rooms*/) { this._pollForRoomChanges(); return OCA.Talk.Signaling.Base.prototype.setRoomCollection.apply(this, arguments); }; OCA.Talk.Signaling.Internal.prototype.setRoom = function(/*room*/) { this._pollForRoomChanges(); return OCA.Talk.Signaling.Base.prototype.setRoom.apply(this, arguments); }; OCA.Talk.Signaling.Internal.prototype._pollForRoomChanges = function() { if (this.roomPoller) { window.clearInterval(this.roomPoller); } this.roomPoller = window.setInterval(function() { this.syncRooms(); }.bind(this), 10000); }; /** * @private */ OCA.Talk.Signaling.Internal.prototype._startPullingMessages = function() { if (!this.currentRoomToken) { return; } // Abort ongoing request if (this.pullMessagesRequest !== null) { this.pullMessagesRequest.abort(); } // Connect to the messages endpoint and pull for new messages this.pullMessagesRequest = $.ajax({ url: OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + this.currentRoomToken, type: 'GET', dataType: 'json', beforeSend: function (request) { request.setRequestHeader('Accept', 'application/json'); }, success: function (result) { this.pullMessagesFails = 0; $.each(result.ocs.data, function(id, message) { this._trigger('onBeforeReceiveMessage', [message]); switch(message.type) { case "usersInRoom": this._trigger('usersInRoom', [message.data]); this._trigger('participantListChanged'); break; case "message": if (typeof(message.data) === 'string') { message.data = JSON.parse(message.data); } this._trigger('message', [message.data]); break; default: console.log('Unknown Signaling Message'); break; } this._trigger('onAfterReceiveMessage', [message]); }.bind(this)); this._startPullingMessages(); }.bind(this), error: function (jqXHR, textStatus/*, errorThrown*/) { if (jqXHR.status === 0 && textStatus === 'abort') { // Request has been aborted. Ignore. } else if (this.currentRoomToken) { if (this.pullMessagesFails >= 3) { console.log('Stop pulling messages after repeated failures'); this._trigger('pullMessagesStoppedOnFail'); return; } this.pullMessagesFails++; //Retry to pull messages after 5 seconds window.setTimeout(function() { this._startPullingMessages(); }.bind(this), 5000); } }.bind(this) }); }; /** * @private */ OCA.Talk.Signaling.Internal.prototype.sendPendingMessages = function() { if (!this.spreedArrayConnection.length || this.isSendingMessages) { return; } var pendingMessagesLength = this.spreedArrayConnection.length; this.isSendingMessages = true; this._sendMessages(this.spreedArrayConnection).done(function(/*result*/) { this.spreedArrayConnection.splice(0, pendingMessagesLength); this.isSendingMessages = false; }.bind(this)).fail(function(/*xhr, textStatus, errorThrown*/) { console.log('Sending pending signaling messages has failed.'); this.isSendingMessages = false; }.bind(this)); }; function Standalone(settings, urls) { OCA.Talk.Signaling.Base.prototype.constructor.apply(this, arguments); if (typeof(urls) === "string") { urls = [urls]; } // We can connect to any of the servers. var idx = Math.floor(Math.random() * urls.length); // TODO(jojo): Try other server if connection fails. var url = urls[idx]; // Make sure we are using websocket urls. if (url.indexOf("https://") === 0) { url = "wss://" + url.substr(8); } else if (url.indexOf("http://") === 0) { url = "ws://" + url.substr(7); } if (url[url.length - 1] === "/") { url = url.substr(0, url.length - 1); } this.url = url + "/spreed"; this.initialReconnectIntervalMs = 1000; this.maxReconnectIntervalMs = 16000; this.reconnectIntervalMs = this.initialReconnectIntervalMs; this.joinedUsers = {}; this.rooms = []; window.setInterval(function() { // Update the room list all 30 seconds to check for new messages and // mentions as well as marking them read via other devices. this.internalSyncRooms(); }.bind(this), 30000); this.connect(); } Standalone.prototype = new OCA.Talk.Signaling.Base(); Standalone.prototype.constructor = Standalone; OCA.Talk.Signaling.Standalone = Standalone; OCA.Talk.Signaling.Standalone.prototype.reconnect = function() { if (this.reconnectTimer) { return; } // Wiggle interval a little bit to prevent all clients from connecting // simultaneously in case the server connection is interrupted. var interval = this.reconnectIntervalMs - (this.reconnectIntervalMs / 2) + (this.reconnectIntervalMs * Math.random()); console.log("Reconnect in", interval); this.reconnected = true; this.reconnectTimer = window.setTimeout(function() { this.reconnectTimer = null; this.connect(); }.bind(this), interval); this.reconnectIntervalMs = this.reconnectIntervalMs * 2; if (this.reconnectIntervalMs > this.maxReconnectIntervalMs) { this.reconnectIntervalMs = this.maxReconnectIntervalMs; } if (this.socket) { this.socket.close(); this.socket = null; } }; OCA.Talk.Signaling.Standalone.prototype.connect = function() { console.log("Connecting to", this.url); this.callbacks = {}; this.id = 1; this.pendingMessages = []; this.connected = false; this._forceReconnect = false; this.socket = new WebSocket(this.url); window.signalingSocket = this.socket; this.socket.onopen = function(event) { console.log("Connected", event); this.reconnectIntervalMs = this.initialReconnectIntervalMs; this.sendHello(); }.bind(this); this.socket.onerror = function(event) { console.log("Error", event); this.reconnect(); }.bind(this); this.socket.onclose = function(event) { console.log("Close", event); this.reconnect(); }.bind(this); this.socket.onmessage = function(event) { var data = event.data; if (typeof(data) === "string") { data = JSON.parse(data); } console.log("Received", data); var id = data.id; if (id && this.callbacks.hasOwnProperty(id)) { var cb = this.callbacks[id]; delete this.callbacks[id]; cb(data); } this._trigger('onBeforeReceiveMessage', [data]); switch (data.type) { case "hello": if (!id) { // Only process if not received as result of our "hello". this.helloResponseReceived(data); } break; case "room": if (this.currentRoomToken && data.room.roomid !== this.currentRoomToken) { this._trigger('roomChanged', [this.currentRoomToken, data.room.roomid]); this.joinedUsers = {}; this.currentRoomToken = null; } else { // TODO(fancycode): Only fetch properties of room that was modified. this.internalSyncRooms(); } break; case "event": this.processEvent(data); break; case "message": data.message.data.from = data.message.sender.sessionid; this._trigger("message", [data.message.data]); break; default: if (!id) { console.log("Ignore unknown event", data); } break; } this._trigger('onAfterReceiveMessage', [data]); }.bind(this); }; OCA.Talk.Signaling.Standalone.prototype.sendBye = function() { if (this.connected) { this.doSend({ "type": "bye", "bye": {} }); } this.resumeId = null; this.signalingRoomJoined = null; }; OCA.Talk.Signaling.Standalone.prototype.disconnect = function() { this.sendBye(); if (this.socket) { this.socket.close(); this.socket = null; } OCA.Talk.Signaling.Base.prototype.disconnect.apply(this, arguments); }; OCA.Talk.Signaling.Standalone.prototype.forceReconnect = function(newSession, flags) { if (flags !== undefined) { this.currentCallFlags = flags; } if (!this.connected) { if (!newSession) { // Not connected, will do reconnect anyway. return; } this._forceReconnect = true; return; } this._forceReconnect = false; if (newSession) { if (this.currentCallToken) { // Mark this session as "no longer in the call". this.leaveCall(this.currentCallToken, true); } this.sendBye(); } if (this.socket) { // Trigger reconnect. this.socket.close(); } }; OCA.Talk.Signaling.Standalone.prototype.sendCallMessage = function(data) { this.doSend({ "type": "message", "message": { "recipient": { "type": "session", "sessionid": data.to }, "data": data } }); }; OCA.Talk.Signaling.Standalone.prototype.sendRoomMessage = function(data) { if (!this.currentCallToken) { console.warn("Not in a room, not sending room message", data); return; } this.doSend({ "type": "message", "message": { "recipient": { "type": "room" }, "data": data } }); }; OCA.Talk.Signaling.Standalone.prototype.doSend = function(msg, callback) { if (!this.connected && msg.type !== "hello" || this.socket === null) { // Defer sending any messages until the hello response has been // received and when the socket is open this.pendingMessages.push([msg, callback]); return; } if (callback) { var id = this.id++; this.callbacks[id] = callback; msg["id"] = ""+id; } console.log("Sending", msg); this.socket.send(JSON.stringify(msg)); }; OCA.Talk.Signaling.Standalone.prototype.sendHello = function() { var msg; if (this.resumeId) { console.log("Trying to resume session", this.sessionId); msg = { "type": "hello", "hello": { "version": "1.0", "resumeid": this.resumeId } }; } else { // Already reconnected with a new session. this._forceReconnect = false; var user = OC.getCurrentUser(); var url = OC.linkToOCS('apps/spreed/api/v1/signaling', 2) + 'backend'; msg = { "type": "hello", "hello": { "version": "1.0", "auth": { "url": url, "params": { "userid": user.uid, "ticket": this.settings.ticket } } } }; } this.doSend(msg, this.helloResponseReceived.bind(this)); }; OCA.Talk.Signaling.Standalone.prototype.helloResponseReceived = function(data) { console.log("Hello response received", data); if (data.type !== "hello") { if (this.resumeId) { // Resuming the session failed, reconnect as new session. this.resumeId = ''; this.sendHello(); return; } // TODO(fancycode): How should this be handled better? console.error("Could not connect to server", data); this.reconnect(); return; } var resumedSession = !!this.resumeId; this.connected = true; if (this._forceReconnect && resumedSession) { console.log("Perform pending forced reconnect"); this.forceReconnect(true); return; } this.sessionId = data.hello.sessionid; this.resumeId = data.hello.resumeid; this.features = {}; var i; if (data.hello.server && data.hello.server.features) { var features = data.hello.server.features; for (i = 0; i < features.length; i++) { this.features[features[i]] = true; } } var messages = this.pendingMessages; this.pendingMessages = []; for (i = 0; i < messages.length; i++) { var msg = messages[i][0]; var callback = messages[i][1]; this.doSend(msg, callback); } this._trigger("connect"); if (this.reconnected) { // The list of rooms might have changed while we were not connected, // so perform resync once. this.internalSyncRooms(); // Load any chat messages that might have been missed. this._receiveChatMessages(); } if (!resumedSession && this.currentRoomToken) { this.joinRoom(this.currentRoomToken); } }; OCA.Talk.Signaling.Standalone.prototype.setRoom = function(/* room */) { OCA.Talk.Signaling.Base.prototype.setRoom.apply(this, arguments); return this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.joinRoom = function(token /*, password */) { if (!this.sessionId) { // If we would join without a connection to the signaling server here, // the room would be re-joined again in the "helloResponseReceived" // callback, leading to two entries for anonymous participants. console.log("Not connected to signaling server yet, defer joining room", token); this.currentRoomToken = token; return; } return OCA.Talk.Signaling.Base.prototype.joinRoom.apply(this, arguments); }; OCA.Talk.Signaling.Standalone.prototype._joinRoomSuccess = function(token, nextcloudSessionId) { if (!this.sessionId) { console.log("No hello response received yet, not joining room", token); return; } console.log("Join room", token); this.doSend({ "type": "room", "room": { "roomid": token, // Pass the Nextcloud session id to the signaling server. The // session id will be passed through to Nextcloud to check if // the (Nextcloud) user is allowed to join the room. "sessionid": nextcloudSessionId, } }, function(data) { this.joinResponseReceived(data, token); }.bind(this)); }; OCA.Talk.Signaling.Standalone.prototype.joinCall = function(token, flags) { if (this.signalingRoomJoined !== token) { console.log("Not joined room yet, not joining call", token); this.pendingJoinCall = { token: token, flags: flags }; return; } OCA.Talk.Signaling.Base.prototype.joinCall.apply(this, arguments); }; OCA.Talk.Signaling.Standalone.prototype._joinCallSuccess = function(/* token */) { // Update room list to fetch modified properties. this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype._leaveCallSuccess = function(/* token */) { // Update room list to fetch modified properties. this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.joinResponseReceived = function(data, token) { console.log("Joined", data, token); this.signalingRoomJoined = token; if (this.pendingJoinCall && token === this.pendingJoinCall.token) { this.joinCall(this.pendingJoinCall.token, this.pendingJoinCall.flags); this.pendingJoinCall = null; } if (this.roomCollection) { // The list of rooms is not fetched from the server. Update ping // of joined room so it gets sorted to the top. this.roomCollection.forEach(function(room) { if (room.get('token') === token) { room.set('lastPing', (new Date()).getTime() / 1000); } }); this.roomCollection.sort(); } }; OCA.Talk.Signaling.Standalone.prototype._doLeaveRoom = function(token) { console.log("Leave room", token); this.doSend({ "type": "room", "room": { "roomid": "" } }, function(data) { console.log("Left", data); this.signalingRoomJoined = null; // Any users we previously had in the room also "left" for us. var leftUsers = _.keys(this.joinedUsers); if (leftUsers.length) { this._trigger("usersLeft", [leftUsers]); } this.joinedUsers = {}; }.bind(this)); }; OCA.Talk.Signaling.Standalone.prototype.processEvent = function(data) { switch (data.event.target) { case "room": this.processRoomEvent(data); break; case "roomlist": this.processRoomListEvent(data); break; case "participants": this.processRoomParticipantsEvent(data); break; default: console.log("Unsupported event target", data); break; } }; OCA.Talk.Signaling.Standalone.prototype.processRoomEvent = function(data) { var i; switch (data.event.type) { case "join": var joinedUsers = data.event.join || []; if (joinedUsers.length) { console.log("Users joined", joinedUsers); var leftUsers = {}; if (this.reconnected) { this.reconnected = false; // The browser reconnected, some of the previous sessions // may now no longer exist. leftUsers = _.extend({}, this.joinedUsers); } for (i = 0; i < joinedUsers.length; i++) { this.joinedUsers[joinedUsers[i].sessionid] = true; delete leftUsers[joinedUsers[i].sessionid]; } leftUsers = _.keys(leftUsers); if (leftUsers.length) { this._trigger("usersLeft", [leftUsers]); } this._trigger("usersJoined", [joinedUsers]); this._trigger('participantListChanged'); } break; case "leave": var leftSessionIds = data.event.leave || []; if (leftSessionIds.length) { console.log("Users left", leftSessionIds); for (i = 0; i < leftSessionIds.length; i++) { delete this.joinedUsers[leftSessionIds[i]]; } this._trigger("usersLeft", [leftSessionIds]); this._trigger('participantListChanged'); } break; case "message": this.processRoomMessageEvent(data.event.message.data); break; default: console.log("Unknown room event", data); break; } }; OCA.Talk.Signaling.Standalone.prototype.processRoomMessageEvent = function(data) { switch (data.type) { case "chat": this._receiveChatMessages(); break; default: console.log("Unknown room message event", data); } }; OCA.Talk.Signaling.Standalone.prototype.setRoomCollection = function(/* rooms */) { OCA.Talk.Signaling.Base.prototype.setRoomCollection.apply(this, arguments); // Retrieve initial list of rooms for this user. return this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.syncRooms = function() { if (this.pending_sync) { // A sync request is already in progress, don't start another one. return this.pending_sync; } // Never manually sync rooms, will be done based on notifications // from the signaling server. var defer = $.Deferred(); defer.resolve(this.rooms); return defer; }; OCA.Talk.Signaling.Standalone.prototype.internalSyncRooms = function() { if (this.pending_sync) { // A sync request is already in progress, don't start another one. return this.pending_sync; } var defer = $.Deferred(); this.pending_sync = OCA.Talk.Signaling.Base.prototype.syncRooms.apply(this, arguments); this.pending_sync.then(function(rooms) { this.pending_sync = null; this.rooms = rooms; defer.resolve(rooms); }.bind(this)); return defer; }; OCA.Talk.Signaling.Standalone.prototype.processRoomListEvent = function(data) { console.log("Room list event", data); this.internalSyncRooms(); }; OCA.Talk.Signaling.Standalone.prototype.processRoomParticipantsEvent = function(data) { switch (data.event.type) { case "update": this._trigger("usersChanged", [data.event.update.users || []]); this._trigger('participantListChanged'); this.internalSyncRooms(); break; default: console.log("Unknown room participant event", data); break; } }; OCA.Talk.Signaling.Standalone.prototype._getChatRequestData = function(/* lastKnownMessageId */) { var data = OCA.Talk.Signaling.Base.prototype._getChatRequestData.apply(this, arguments); // Don't keep connection open and wait for more messages, will be done // through another event on the WebSocket. data.timeout = 0; return data; }; OCA.Talk.Signaling.Standalone.prototype._retryChatLoadingOnError = function() { // We don't regularly poll for changes, so need to always retry loading // of chat messages in case of errors. return true; }; OCA.Talk.Signaling.Standalone.prototype.startReceiveMessages = function() { OCA.Talk.Signaling.Base.prototype.startReceiveMessages.apply(this, arguments); // We will be notified when to load new messages. this.receiveMessagesAgain = false; }; OCA.Talk.Signaling.Standalone.prototype.requestOffer = function(sessionid, roomType) { if (!this.hasFeature("mcu")) { console.warn("Can't request an offer without a MCU."); return; } if (typeof(sessionid) !== "string") { // Got a user object. sessionid = sessionid.sessionId || sessionid.sessionid; } console.log("Request offer from", sessionid); this.doSend({ "type": "message", "message": { "recipient": { "type": "session", "sessionid": sessionid }, "data": { "type": "requestoffer", "roomType": roomType } } }); }; OCA.Talk.Signaling.Standalone.prototype.sendOffer = function(sessionid, roomType) { // TODO(jojo): This should go away and "requestOffer" should be used // instead by peers that want an offer by the MCU. See the calling // location for further details. if (!this.hasFeature("mcu")) { console.warn("Can't send an offer without a MCU."); return; } if (typeof(sessionid) !== "string") { // Got a user object. sessionid = sessionid.sessionId || sessionid.sessionid; } console.log("Send offer to", sessionid); this.doSend({ "type": "message", "message": { "recipient": { "type": "session", "sessionid": sessionid }, "data": { "type": "sendoffer", "roomType": roomType } } }); }; })(OCA, OC, $);
Rename "pending_sync" private property to "_pendingSyncRooms" Signed-off-by: Daniel Calviño Sánchez <[email protected]>
js/signaling.js
Rename "pending_sync" private property to "_pendingSyncRooms"
<ide><path>s/signaling.js <ide> }; <ide> <ide> OCA.Talk.Signaling.Standalone.prototype.syncRooms = function() { <del> if (this.pending_sync) { <add> if (this._pendingSyncRooms) { <ide> // A sync request is already in progress, don't start another one. <del> return this.pending_sync; <add> return this._pendingSyncRooms; <ide> } <ide> <ide> // Never manually sync rooms, will be done based on notifications <ide> }; <ide> <ide> OCA.Talk.Signaling.Standalone.prototype.internalSyncRooms = function() { <del> if (this.pending_sync) { <add> if (this._pendingSyncRooms) { <ide> // A sync request is already in progress, don't start another one. <del> return this.pending_sync; <add> return this._pendingSyncRooms; <ide> } <ide> <ide> var defer = $.Deferred(); <del> this.pending_sync = OCA.Talk.Signaling.Base.prototype.syncRooms.apply(this, arguments); <del> this.pending_sync.then(function(rooms) { <del> this.pending_sync = null; <add> this._pendingSyncRooms = OCA.Talk.Signaling.Base.prototype.syncRooms.apply(this, arguments); <add> this._pendingSyncRooms.then(function(rooms) { <add> this._pendingSyncRooms = null; <ide> this.rooms = rooms; <ide> defer.resolve(rooms); <ide> }.bind(this));
Java
apache-2.0
e0c7aaa00977e1b990991276346978848530b403
0
apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena
/** * 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.jena.riot.writer ; import static org.apache.jena.graph.Triple.ANY; import static org.apache.jena.rdf.model.impl.Util.isLangString; import static org.apache.jena.rdf.model.impl.Util.isSimpleString; import java.io.IOException ; import java.io.OutputStream ; import java.io.OutputStreamWriter ; import java.io.Writer ; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import org.apache.jena.atlas.io.IO ; import org.apache.jena.atlas.lib.Chars ; import org.apache.jena.atlas.lib.Pair; import org.apache.jena.graph.Graph ; import org.apache.jena.graph.Node ; import org.apache.jena.graph.Triple ; import org.apache.jena.iri.IRI ; import org.apache.jena.riot.Lang ; import org.apache.jena.riot.RDFFormat ; import org.apache.jena.riot.RiotException ; import org.apache.jena.riot.WriterDatasetRIOT ; import org.apache.jena.riot.system.PrefixMap ; import org.apache.jena.riot.system.PrefixMapFactory; import org.apache.jena.sparql.core.DatasetGraph ; import org.apache.jena.sparql.util.Context ; import org.apache.jena.sparql.util.Symbol; import org.apache.jena.vocabulary.RDF ; import com.fasterxml.jackson.core.JsonGenerationException ; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException ; import com.github.jsonldjava.core.JsonLdApi; import com.github.jsonldjava.core.JsonLdError ; import com.github.jsonldjava.core.JsonLdOptions ; import com.github.jsonldjava.core.JsonLdProcessor ; import com.github.jsonldjava.core.RDFDataset; import com.github.jsonldjava.utils.JsonUtils ; /** * Writer that prints out JSON-LD. * * By default, the output is "compact" (in JSON-LD terminology), and the JSON is "pretty" (using line breaks). * One can choose another form using one of the dedicated RDFFormats (JSONLD_EXPAND_PRETTY, etc.). * * For formats using a context (that is, which have an "@context" node), (compact and expand), * this automatically generates a default one. * * One can pass a jsonld context using the (jena) Context mechanism, defining a (jena) Context * (sorry for this clash of "contexts"), (cf. last argument in * {@link WriterDatasetRIOT#write(OutputStream out, DatasetGraph datasetGraph, PrefixMap prefixMap, String baseURI, Context context)}) * with: * <pre> * Context jenaContext = new Context() * jenaCtx.set(JsonLDWriter.JSONLD_CONTEXT, contextAsJsonString); * </pre> * where contextAsJsonString is a JSON string containing the value of the "@context". * * It is possible to change the content of the "@context" node in the output using the {@link #JSONLD_CONTEXT_SUBSTITUTION} Symbol. * * For a frame output, one must pass a frame in the jenaContext using the {@link #JSONLD_FRAME} Symbol. * * It is also possible to define the different options supported * by JSONLD-java using the {@link #JSONLD_OPTIONS} Symbol * * The {@link org.apache.jena.riot.JsonLDWriteContext} is a convenience class that extends Context and * provides methods to set the values of these different Symbols that are used in controlling the writing of JSON-LD. * * Note that this class also provides a static method to convert jena RDF data to the corresponding object in JsonLD API: * {@link #toJsonLDJavaAPI(org.apache.jena.riot.RDFFormat.JSONLDVariant, DatasetGraph, PrefixMap, String, Context)} */ public class JsonLDWriter extends WriterDatasetRIOTBase { private static final String SYMBOLS_NS = "http://jena.apache.org/riot/jsonld#" ; private static Symbol createSymbol(String localName) { return Symbol.create(SYMBOLS_NS + localName); } /** * Expected value: the value of the "@context" * (a JSON String, or the object expected by the JSONLD-java API) */ public static final Symbol JSONLD_CONTEXT = createSymbol("JSONLD_CONTEXT"); /** * Expected value: the value of the "@context" to be put in final output (a JSON String) * This is NOT the context used to produce the output (given by JSONLD_CONTEXT, * or computed from the input RDF. It is something that will replace the @context content. * This is useful<ol><li>for the cases you want to have a URI as value of @context, * without having JSON-LD java to download it and</li><li>as a trick to * change the URIs in your result.</li></ol> * * Only for compact and flatten formats. * * Note that it is supposed to be a JSON String: to set the value of @context to a URI, * the String must be quoted.*/ public static final Symbol JSONLD_CONTEXT_SUBSTITUTION = createSymbol("JSONLD_CONTEXT_SUBSTITUTION"); /** value: a JSON String, or the frame object expected by JsonLdProcessor.frame */ public static final Symbol JSONLD_FRAME = createSymbol("JSONLD_FRAME"); /** value: the option object expected by JsonLdProcessor (instance of JsonLdOptions) */ public static final Symbol JSONLD_OPTIONS = createSymbol("JSONLD_OPTIONS"); /** * if creating a (jsonld) context from dataset, should we include all the prefixes defined in graph's prefix mappings * value: a Boolean (default: true) */ public static final Symbol JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT = createSymbol("JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT"); private final RDFFormat format ; public JsonLDWriter(RDFFormat syntaxForm) { format = syntaxForm ; } @Override public Lang getLang() { return format.getLang() ; } @Override public void write(Writer out, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context context) { serialize(out, dataset, prefixMap, baseURI, context) ; } @Override public void write(OutputStream out, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context context) { Writer w = new OutputStreamWriter(out, Chars.charsetUTF8) ; write(w, dataset, prefixMap, baseURI, context) ; IO.flush(w) ; } private RDFFormat.JSONLDVariant getVariant() { return (RDFFormat.JSONLDVariant) format.getVariant(); } static private JsonLdOptions getJsonLdOptions(String baseURI, Context jenaContext) { JsonLdOptions opts = null; if (jenaContext != null) { opts = (JsonLdOptions) jenaContext.get(JSONLD_OPTIONS); } if (opts == null) { opts = defaultJsonLdOptions(baseURI); } return opts; } // jena is not using same default as JSONLD-java // maybe we should have, but it's too late now: // changing it now would imply some unexpected changes in current users' outputs static private JsonLdOptions defaultJsonLdOptions(String baseURI) { JsonLdOptions opts = new JsonLdOptions(baseURI); opts.useNamespaces = true ; // this is NOT jsonld-java's default // opts.setUseRdfType(true); // false -> use "@type" opts.setUseNativeTypes(true); // this is NOT jsonld-java's default opts.setCompactArrays(true); // this is jsonld-java's default return opts; } private void serialize(Writer writer, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context jenaContext) { try { Object obj = toJsonLDJavaAPI(getVariant(), dataset, prefixMap, baseURI, jenaContext); if (getVariant().isPretty()) { JsonUtils.writePrettyPrint(writer, obj) ; } else { JsonUtils.write(writer, obj) ; } writer.write("\n") ; } catch (JsonLdError | JsonMappingException | JsonGenerationException e) { throw new RiotException(e) ; } catch (IOException e) { IO.exception(e) ; } } /** * the JsonLD-java API object corresponding to a dataset and a JsonLD format. */ static public Object toJsonLDJavaAPI(RDFFormat.JSONLDVariant variant, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context jenaContext) throws JsonLdError, JsonParseException, IOException { JsonLdOptions opts = getJsonLdOptions(baseURI, jenaContext) ; // we can benefit from the fact we know that there are no duplicates in the jsonld RDFDataset that we create // (optimization in jsonld-java 0.8.3) // see https://github.com/jsonld-java/jsonld-java/pull/173 // with this, we cannot call the json-ld fromRDF method that assumes no duplicates in RDFDataset // Object obj = JsonLdProcessor.fromRDF(dataset, opts, new JenaRDF2JSONLD()) ; final RDFDataset jsonldDataset = (new JenaRDF2JSONLD()).parse(dataset); @SuppressWarnings("deprecation") // JsonLdApi.fromRDF(RDFDataset, boolean) is "experimental" rather than "deprecated" Object obj = (new JsonLdApi(opts)).fromRDF(jsonldDataset, true); // true because we know that we don't have any duplicate in jsonldDataset if (variant.isExpand()) { // nothing more to do } else if (variant.isFrame()) { Object frame = null; if (jenaContext != null) { frame = jenaContext.get(JSONLD_FRAME); } if (frame == null) { throw new IllegalArgumentException("No frame object found in jena Context"); } if (frame instanceof String) { frame = JsonUtils.fromString((String) frame); } obj = JsonLdProcessor.frame(obj, frame, opts); } else { // compact or flatten // we need a (jsonld) context. Get it from jenaContext, or create one: Object ctx = getJsonldContext(dataset, prefixMap, jenaContext); if (variant.isCompact()) { obj = JsonLdProcessor.compact(obj, ctx, opts); } else if (variant.isFlatten()) { obj = JsonLdProcessor.flatten(obj, ctx, opts); } else { throw new IllegalArgumentException("Unexpected " + RDFFormat.JSONLDVariant.class.getName() + ": " + variant); } // replace @context in output? if (jenaContext != null) { Object ctxReplacement = jenaContext.get(JSONLD_CONTEXT_SUBSTITUTION); if (ctxReplacement != null) { if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; if (map.containsKey("@context")) { map.put("@context", JsonUtils.fromString(ctxReplacement.toString())); } } } } } return obj; } // // getting / creating a (jsonld) context // /** Get the (jsonld) context from the jena context, or create one */ private static Object getJsonldContext(DatasetGraph dataset, PrefixMap prefixMap, Context jenaContext) throws JsonParseException, IOException { Object ctx = null; boolean isCtxDefined = false; // to allow jenaContext to set ctx to null. Useful? if (jenaContext != null) { if (jenaContext.isDefined(JSONLD_CONTEXT)) { isCtxDefined = true; Object o = jenaContext.get(JSONLD_CONTEXT); if (o != null) { if (o instanceof String) { // supposed to be a json string String jsonString = (String) o; ctx = JsonUtils.fromString(jsonString); } else { ctx = o; } } } } if (!isCtxDefined) { // if no ctx passed via jenaContext, create one in order to have localnames as keys for properties ctx = createJsonldContext(dataset.getDefaultGraph(), prefixMap, addAllPrefixesToContextFlag(jenaContext)) ; // I don't think this should be done: the JsonLdProcessor begins // by looking whether the argument passed is a map with key "@context" and if so, takes corresponding value // Then, better not to do this: we create a map for nothing, and worse, // if the context object has been created by a user and passed through the (jena) context // in case he got the same idea, we would end up with 2 levels of maps and it would not work // Map<String, Object> localCtx = new HashMap<>() ; // localCtx.put("@context", ctx) ; } return ctx; } static Object createJsonldContext(Graph g) { return createJsonldContext(g, PrefixMapFactory.create(g.getPrefixMapping()), true); } private static Object createJsonldContext(Graph g, PrefixMap prefixMap, boolean addAllPrefixesToContext) { final Map<String, Object> ctx = new LinkedHashMap<>() ; // Add properties (in order to get: "localname": ....) addProperties(ctx, g); // Add prefixes addPrefixes(ctx, g, prefixMap, addAllPrefixesToContext); return ctx ; } /** Add properties to jsonld context. */ static void addProperties(Map<String, Object> ctx, Graph g) { Consumer<Triple> x = new Consumer<Triple>() { @Override public void accept(Triple item) { Node p = item.getPredicate() ; Node o = item.getObject() ; if ( p.equals(RDF.type.asNode()) ) return ; String x = p.getLocalName() ; if ( ctx.containsKey(x) ) { } else if ( o.isBlank() || o.isURI() ) { // add property as a property (the object is an IRI) Map<String, Object> x2 = new LinkedHashMap<>() ; x2.put("@id", p.getURI()) ; x2.put("@type", "@id") ; ctx.put(x, x2) ; } else if ( o.isLiteral() ) { String literalDatatypeURI = o.getLiteralDatatypeURI() ; if ( literalDatatypeURI != null ) { // add property as a typed attribute (the object is a // typed literal) Map<String, Object> x2 = new LinkedHashMap<>() ; x2.put("@id", p.getURI()) ; if (! isLangString(o) && ! isSimpleString(o) ) // RDF 1.1 : Skip if rdf:langString or xsd:string. x2.put("@type", literalDatatypeURI) ; ctx.put(x, x2) ; } else { // add property as an untyped attribute (the object is // an untyped literal) ctx.put(x, p.getURI()) ; } } } } ; g.find(ANY).forEachRemaining(x); } /** * Add the prefixes to jsonld context. * * @param ctx * @param g * @param prefixMap * @param addAllPrefixesToContext true to add all prefixes in prefixMap to the jsonld context, * false to only add those which are actually used in g (false is useful for instance * when downloading schema.org: we get a very long list of prefixes. */ // if adding all the prefixes in PrefixMap to ctx // one pb is, many of the prefixes may be actually unused in the graph. // This happens for instance when downloading schema.org: a very long list of prefixes // hence the addAllPrefixesToContext param private static void addPrefixes(Map<String, Object> ctx, Graph g, PrefixMap prefixMap, boolean addAllPrefixesToContext) { if (prefixMap != null) { Map<String, IRI> mapping = prefixMap.getMapping(); if (addAllPrefixesToContext) { for ( Entry<String, IRI> e : mapping.entrySet() ) { addOnePrefix(ctx, e.getKey(), e.getValue().toString()); } } else { // only add those that are actually used Consumer<Triple> x = new Consumer<Triple>() { @Override public void accept(Triple item) { Node node = item.getSubject(); if (node.isURI()) addPrefix2Ctx(node.getURI()); node = item.getPredicate() ; addPrefix2Ctx(node.getURI()); node = item.getObject() ; if (node.isURI()) addPrefix2Ctx(node.getURI()); } private void addPrefix2Ctx(String resUri) { Pair<String, String> pair = prefixMap.abbrev(resUri); if (pair != null) { String prefix = pair.getLeft(); addOnePrefix(ctx, prefix, mapping.get(prefix).toString()); } } } ; g.find(ANY).forEachRemaining(x); } } } /** Add one prefix to jsonld context */ static void addOnePrefix(Map<String, Object> ctx, String prefix, String value) { if (!prefix.isEmpty()) { // Prefix "" is not allowed in JSON-LD -- could probably be replaced by "@vocab" ctx.put(prefix, value); } } private static boolean addAllPrefixesToContextFlag(Context jenaContext) { if (jenaContext != null) { Object o = jenaContext.get(JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT); if (o != null) { if (o instanceof Boolean) { return ((Boolean) o).booleanValue(); } else { throw new IllegalArgumentException("Value attached to JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT shoud be a Boolean"); } } } // default return true; } }
jena-arq/src/main/java/org/apache/jena/riot/writer/JsonLDWriter.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.jena.riot.writer ; import static org.apache.jena.graph.Triple.ANY; import static org.apache.jena.rdf.model.impl.Util.isLangString; import static org.apache.jena.rdf.model.impl.Util.isSimpleString; import java.io.IOException ; import java.io.OutputStream ; import java.io.OutputStreamWriter ; import java.io.Writer ; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import org.apache.jena.atlas.io.IO ; import org.apache.jena.atlas.lib.Chars ; import org.apache.jena.atlas.lib.Pair; import org.apache.jena.graph.Graph ; import org.apache.jena.graph.Node ; import org.apache.jena.graph.Triple ; import org.apache.jena.iri.IRI ; import org.apache.jena.riot.Lang ; import org.apache.jena.riot.RDFFormat ; import org.apache.jena.riot.RiotException ; import org.apache.jena.riot.WriterDatasetRIOT ; import org.apache.jena.riot.system.PrefixMap ; import org.apache.jena.riot.system.PrefixMapFactory; import org.apache.jena.sparql.core.DatasetGraph ; import org.apache.jena.sparql.util.Context ; import org.apache.jena.sparql.util.Symbol; import org.apache.jena.vocabulary.RDF ; import com.fasterxml.jackson.core.JsonGenerationException ; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException ; import com.github.jsonldjava.core.JsonLdApi; import com.github.jsonldjava.core.JsonLdError ; import com.github.jsonldjava.core.JsonLdOptions ; import com.github.jsonldjava.core.JsonLdProcessor ; import com.github.jsonldjava.core.RDFDataset; import com.github.jsonldjava.utils.JsonUtils ; /** * Writer that prints out JSON-LD. * * By default, the output is "compact" (in JSON-LD terminology), and the JSON is "pretty" (using line breaks). * One can choose another form using one of the dedicated RDFFormats (JSONLD_EXPAND_PRETTY, etc.). * * For formats using a context (that is, which have an "@context" node), (compact and expand), * this automatically generates a default one. * * One can pass a jsonld context using the (jena) Context mechanism, defining a (jena) Context * (sorry for this clash of "contexts"), (cf. last argument in * {@link WriterDatasetRIOT#write(OutputStream out, DatasetGraph datasetGraph, PrefixMap prefixMap, String baseURI, Context context)}) * with: * <pre> * Context jenaContext = new Context() * jenaCtx.set(JsonLDWriter.JSONLD_CONTEXT, contextAsJsonString); * </pre> * where contextAsJsonString is a JSON string containing the value of the "@context". * * It is possible to change the content of the "@context" node in the output using the {@link #JSONLD_CONTEXT_SUBSTITUTION} Symbol. * * For a frame output, one must pass a frame in the jenaContext using the {@link #JSONLD_FRAME} Symbol. * * It is also possible to define the different options supported * by JSONLD-java using the {@link #JSONLD_OPTIONS} Symbol * * The {@link org.apache.jena.riot.JsonLDWriteContext} is a convenience class that extends Context and * provides methods to set the values of these different Symbols that are used in controlling the writing of JSON-LD. * * Note that this class also provides a static method to convert jena RDF data to the corresponding object in JsonLD API: * {@link #jsonLDJavaAPIObject(DatasetGraph, PrefixMap, String, org.apache.jena.riot.RDFFormat.JSONLDVariant, Context)} */ public class JsonLDWriter extends WriterDatasetRIOTBase { private static final String SYMBOLS_NS = "http://jena.apache.org/riot/jsonld#" ; private static Symbol createSymbol(String localName) { return Symbol.create(SYMBOLS_NS + localName); } /** * Expected value: the value of the "@context" * (a JSON String, or the object expected by the JSONLD-java API) */ public static final Symbol JSONLD_CONTEXT = createSymbol("JSONLD_CONTEXT"); /** * Expected value: the value of the "@context" to be put in final output (a JSON String) * This is NOT the context used to produce the output (given by JSONLD_CONTEXT, * or computed from the input RDF. It is something that will replace the @context content. * This is useful<ol><li>for the cases you want to have a URI as value of @context, * without having JSON-LD java to download it and</li><li>as a trick to * change the URIs in your result.</li></ol> * * Only for compact and flatten formats. * * Note that it is supposed to be a JSON String: to set the value of @context to a URI, * the String must be quoted.*/ public static final Symbol JSONLD_CONTEXT_SUBSTITUTION = createSymbol("JSONLD_CONTEXT_SUBSTITUTION"); /** value: a JSON String, or the frame object expected by JsonLdProcessor.frame */ public static final Symbol JSONLD_FRAME = createSymbol("JSONLD_FRAME"); /** value: the option object expected by JsonLdProcessor (instance of JsonLdOptions) */ public static final Symbol JSONLD_OPTIONS = createSymbol("JSONLD_OPTIONS"); /** * if creating a (jsonld) context from dataset, should we include all the prefixes defined in graph's prefix mappings * value: a Boolean (default: true) */ public static final Symbol JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT = createSymbol("JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT"); private final RDFFormat format ; public JsonLDWriter(RDFFormat syntaxForm) { format = syntaxForm ; } @Override public Lang getLang() { return format.getLang() ; } @Override public void write(Writer out, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context context) { serialize(out, dataset, prefixMap, baseURI, context) ; } @Override public void write(OutputStream out, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context context) { Writer w = new OutputStreamWriter(out, Chars.charsetUTF8) ; write(w, dataset, prefixMap, baseURI, context) ; IO.flush(w) ; } private RDFFormat.JSONLDVariant getVariant() { return (RDFFormat.JSONLDVariant) format.getVariant(); } static private JsonLdOptions getJsonLdOptions(String baseURI, Context jenaContext) { JsonLdOptions opts = null; if (jenaContext != null) { opts = (JsonLdOptions) jenaContext.get(JSONLD_OPTIONS); } if (opts == null) { opts = defaultJsonLdOptions(baseURI); } return opts; } // jena is not using same default as JSONLD-java // maybe we should have, but it's too late now: // changing it now would imply some unexpected changes in current users' outputs static private JsonLdOptions defaultJsonLdOptions(String baseURI) { JsonLdOptions opts = new JsonLdOptions(baseURI); opts.useNamespaces = true ; // this is NOT jsonld-java's default // opts.setUseRdfType(true); // false -> use "@type" opts.setUseNativeTypes(true); // this is NOT jsonld-java's default opts.setCompactArrays(true); // this is jsonld-java's default return opts; } private void serialize(Writer writer, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context jenaContext) { try { Object obj = jsonLDJavaAPIObject(dataset, prefixMap, baseURI, getVariant(), jenaContext); if (getVariant().isPretty()) { JsonUtils.writePrettyPrint(writer, obj) ; } else { JsonUtils.write(writer, obj) ; } writer.write("\n") ; } catch (JsonLdError | JsonMappingException | JsonGenerationException e) { throw new RiotException(e) ; } catch (IOException e) { IO.exception(e) ; } } /** * the JsonLD-java API object corresponding to a dataset and a JsonLD format. */ static public Object jsonLDJavaAPIObject(DatasetGraph dataset, PrefixMap prefixMap, String baseURI, RDFFormat.JSONLDVariant variant, Context jenaContext) throws JsonLdError, JsonParseException, IOException { JsonLdOptions opts = getJsonLdOptions(baseURI, jenaContext) ; // we can benefit from the fact we know that there are no duplicates in the jsonld RDFDataset that we create // (optimization in jsonld-java 0.8.3) // see https://github.com/jsonld-java/jsonld-java/pull/173 // with this, we cannot call the json-ld fromRDF method that assumes no duplicates in RDFDataset // Object obj = JsonLdProcessor.fromRDF(dataset, opts, new JenaRDF2JSONLD()) ; final RDFDataset jsonldDataset = (new JenaRDF2JSONLD()).parse(dataset); @SuppressWarnings("deprecation") // JsonLdApi.fromRDF(RDFDataset, boolean) is "experimental" rather than "deprecated" Object obj = (new JsonLdApi(opts)).fromRDF(jsonldDataset, true); // true because we know that we don't have any duplicate in jsonldDataset if (variant.isExpand()) { // nothing more to do } else if (variant.isFrame()) { Object frame = null; if (jenaContext != null) { frame = jenaContext.get(JSONLD_FRAME); } if (frame == null) { throw new IllegalArgumentException("No frame object found in jena Context"); } if (frame instanceof String) { frame = JsonUtils.fromString((String) frame); } obj = JsonLdProcessor.frame(obj, frame, opts); } else { // compact or flatten // we need a (jsonld) context. Get it from jenaContext, or create one: Object ctx = getJsonldContext(dataset, prefixMap, jenaContext); if (variant.isCompact()) { obj = JsonLdProcessor.compact(obj, ctx, opts); } else if (variant.isFlatten()) { obj = JsonLdProcessor.flatten(obj, ctx, opts); } else { throw new IllegalArgumentException("Unexpected " + RDFFormat.JSONLDVariant.class.getName() + ": " + variant); } // replace @context in output? if (jenaContext != null) { Object ctxReplacement = jenaContext.get(JSONLD_CONTEXT_SUBSTITUTION); if (ctxReplacement != null) { if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; if (map.containsKey("@context")) { map.put("@context", JsonUtils.fromString(ctxReplacement.toString())); } } } } } return obj; } // // getting / creating a (jsonld) context // /** Get the (jsonld) context from the jena context, or create one */ private static Object getJsonldContext(DatasetGraph dataset, PrefixMap prefixMap, Context jenaContext) throws JsonParseException, IOException { Object ctx = null; boolean isCtxDefined = false; // to allow jenaContext to set ctx to null. Useful? if (jenaContext != null) { if (jenaContext.isDefined(JSONLD_CONTEXT)) { isCtxDefined = true; Object o = jenaContext.get(JSONLD_CONTEXT); if (o != null) { if (o instanceof String) { // supposed to be a json string String jsonString = (String) o; ctx = JsonUtils.fromString(jsonString); } else { ctx = o; } } } } if (!isCtxDefined) { // if no ctx passed via jenaContext, create one in order to have localnames as keys for properties ctx = createJsonldContext(dataset.getDefaultGraph(), prefixMap, addAllPrefixesToContextFlag(jenaContext)) ; // I don't think this should be done: the JsonLdProcessor begins // by looking whether the argument passed is a map with key "@context" and if so, takes corresponding value // Then, better not to do this: we create a map for nothing, and worse, // if the context object has been created by a user and passed through the (jena) context // in case he got the same idea, we would end up with 2 levels of maps and it would not work // Map<String, Object> localCtx = new HashMap<>() ; // localCtx.put("@context", ctx) ; } return ctx; } static Object createJsonldContext(Graph g) { return createJsonldContext(g, PrefixMapFactory.create(g.getPrefixMapping()), true); } private static Object createJsonldContext(Graph g, PrefixMap prefixMap, boolean addAllPrefixesToContext) { final Map<String, Object> ctx = new LinkedHashMap<>() ; // Add properties (in order to get: "localname": ....) addProperties(ctx, g); // Add prefixes addPrefixes(ctx, g, prefixMap, addAllPrefixesToContext); return ctx ; } /** Add properties to jsonld context. */ static void addProperties(Map<String, Object> ctx, Graph g) { Consumer<Triple> x = new Consumer<Triple>() { @Override public void accept(Triple item) { Node p = item.getPredicate() ; Node o = item.getObject() ; if ( p.equals(RDF.type.asNode()) ) return ; String x = p.getLocalName() ; if ( ctx.containsKey(x) ) { } else if ( o.isBlank() || o.isURI() ) { // add property as a property (the object is an IRI) Map<String, Object> x2 = new LinkedHashMap<>() ; x2.put("@id", p.getURI()) ; x2.put("@type", "@id") ; ctx.put(x, x2) ; } else if ( o.isLiteral() ) { String literalDatatypeURI = o.getLiteralDatatypeURI() ; if ( literalDatatypeURI != null ) { // add property as a typed attribute (the object is a // typed literal) Map<String, Object> x2 = new LinkedHashMap<>() ; x2.put("@id", p.getURI()) ; if (! isLangString(o) && ! isSimpleString(o) ) // RDF 1.1 : Skip if rdf:langString or xsd:string. x2.put("@type", literalDatatypeURI) ; ctx.put(x, x2) ; } else { // add property as an untyped attribute (the object is // an untyped literal) ctx.put(x, p.getURI()) ; } } } } ; g.find(ANY).forEachRemaining(x); } /** * Add the prefixes to jsonld context. * * @param ctx * @param g * @param prefixMap * @param addAllPrefixesToContext true to add all prefixes in prefixMap to the jsonld context, * false to only add those which are actually used in g (false is useful for instance * when downloading schema.org: we get a very long list of prefixes. */ // if adding all the prefixes in PrefixMap to ctx // one pb is, many of the prefixes may be actually unused in the graph. // This happens for instance when downloading schema.org: a very long list of prefixes // hence the addAllPrefixesToContext param private static void addPrefixes(Map<String, Object> ctx, Graph g, PrefixMap prefixMap, boolean addAllPrefixesToContext) { if (prefixMap != null) { Map<String, IRI> mapping = prefixMap.getMapping(); if (addAllPrefixesToContext) { for ( Entry<String, IRI> e : mapping.entrySet() ) { addOnePrefix(ctx, e.getKey(), e.getValue().toString()); } } else { // only add those that are actually used Consumer<Triple> x = new Consumer<Triple>() { @Override public void accept(Triple item) { Node node = item.getSubject(); if (node.isURI()) addPrefix2Ctx(node.getURI()); node = item.getPredicate() ; addPrefix2Ctx(node.getURI()); node = item.getObject() ; if (node.isURI()) addPrefix2Ctx(node.getURI()); } private void addPrefix2Ctx(String resUri) { Pair<String, String> pair = prefixMap.abbrev(resUri); if (pair != null) { String prefix = pair.getLeft(); addOnePrefix(ctx, prefix, mapping.get(prefix).toString()); } } } ; g.find(ANY).forEachRemaining(x); } } } /** Add one prefix to jsonld context */ static void addOnePrefix(Map<String, Object> ctx, String prefix, String value) { if (!prefix.isEmpty()) { // Prefix "" is not allowed in JSON-LD -- could probably be replaced by "@vocab" ctx.put(prefix, value); } } private static boolean addAllPrefixesToContextFlag(Context jenaContext) { if (jenaContext != null) { Object o = jenaContext.get(JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT); if (o != null) { if (o instanceof Boolean) { return ((Boolean) o).booleanValue(); } else { throw new IllegalArgumentException("Value attached to JSONLD_ADD_ALL_PREFIXES_TO_CONTEXT shoud be a Boolean"); } } } // default return true; } }
toJsonLDJavaAPI: name and order of params changed
jena-arq/src/main/java/org/apache/jena/riot/writer/JsonLDWriter.java
toJsonLDJavaAPI: name and order of params changed
<ide><path>ena-arq/src/main/java/org/apache/jena/riot/writer/JsonLDWriter.java <ide> * provides methods to set the values of these different Symbols that are used in controlling the writing of JSON-LD. <ide> * <ide> * Note that this class also provides a static method to convert jena RDF data to the corresponding object in JsonLD API: <del> * {@link #jsonLDJavaAPIObject(DatasetGraph, PrefixMap, String, org.apache.jena.riot.RDFFormat.JSONLDVariant, Context)} <add> * {@link #toJsonLDJavaAPI(org.apache.jena.riot.RDFFormat.JSONLDVariant, DatasetGraph, PrefixMap, String, Context)} <ide> */ <ide> public class JsonLDWriter extends WriterDatasetRIOTBase <ide> { <ide> <ide> private void serialize(Writer writer, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context jenaContext) { <ide> try { <del> Object obj = jsonLDJavaAPIObject(dataset, prefixMap, baseURI, getVariant(), jenaContext); <add> Object obj = toJsonLDJavaAPI(getVariant(), dataset, prefixMap, baseURI, jenaContext); <ide> if (getVariant().isPretty()) { <ide> JsonUtils.writePrettyPrint(writer, obj) ; <ide> } else { <ide> /** <ide> * the JsonLD-java API object corresponding to a dataset and a JsonLD format. <ide> */ <del> static public Object jsonLDJavaAPIObject(DatasetGraph dataset, PrefixMap prefixMap, String baseURI, RDFFormat.JSONLDVariant variant, Context jenaContext) throws JsonLdError, JsonParseException, IOException { <add> static public Object toJsonLDJavaAPI(RDFFormat.JSONLDVariant variant, DatasetGraph dataset, PrefixMap prefixMap, String baseURI, Context jenaContext) throws JsonLdError, JsonParseException, IOException { <ide> JsonLdOptions opts = getJsonLdOptions(baseURI, jenaContext) ; <ide> <ide> // we can benefit from the fact we know that there are no duplicates in the jsonld RDFDataset that we create
Java
apache-2.0
03438ca534deaf170a2a2c80323b29f7036a147b
0
chasehd/openwayback,JesseWeinstein/openwayback,chasehd/openwayback,kris-sigur/openwayback,ukwa/openwayback,ukwa/openwayback,SpiralsSeminaire/openwayback,bitzl/openwayback,nlnwa/openwayback,SpiralsSeminaire/openwayback,MohammedElsayyed/openwayback,kris-sigur/openwayback,bitzl/openwayback,bitzl/openwayback,chasehd/openwayback,nlnwa/openwayback,SpiralsSeminaire/openwayback,iipc/openwayback,nlnwa/openwayback,JesseWeinstein/openwayback,iipc/openwayback,iipc/openwayback,SpiralsSeminaire/openwayback,bitzl/openwayback,JesseWeinstein/openwayback,MohammedElsayyed/openwayback,kris-sigur/openwayback,bitzl/openwayback,ukwa/openwayback,MohammedElsayyed/openwayback,SpiralsSeminaire/openwayback,nlnwa/openwayback,JesseWeinstein/openwayback,nlnwa/openwayback,JesseWeinstein/openwayback,kris-sigur/openwayback,kris-sigur/openwayback
package org.archive.wayback.resourceindex; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static com.sun.nio.file.SensitivityWatchEventModifier.HIGH; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.SKIP_SUBTREE; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.archive.wayback.resourceindex.cdx.CDXIndex; /** * SearchResultSource that watches a single directory for new * SearchResultSources. * * <pre> * {@code * <property name="source"> * <bean class="org.archive.wayback.resourceindex.WatchedCDXSource"> * <property name="recursive" value="false" /> * <property name="filters"> * <list> * <value>^.+\.cdx$</value> * </list> * </property> * <property name="path" value="/wayback/cdx-index/" /> * </bean> * </property> * } * </pre> * * @author rcoram * */ public class WatchedCDXSource extends CompositeSearchResultSource { private static final Logger LOGGER = Logger .getLogger(WatchedCDXSource.class.getName()); private Thread watcherThread; private Path path; private boolean recursive = false; private List<String> filters; private ArrayList<Pattern> includePatterns = new ArrayList<Pattern>(); private final Set<FileVisitOption> visitOptions = EnumSet .noneOf(FileVisitOption.class); public WatchedCDXSource() { visitOptions.add(FileVisitOption.FOLLOW_LINKS); } { setFilters(Arrays.asList("^.+\\.cdx$")); } public void setFilters(List<String> filters) { for (String filter : filters) { includePatterns.add(Pattern.compile(filter)); } this.filters = filters; } public List<String> getFilters() { return this.filters; } public void setRecursive(boolean recursive) { this.recursive = recursive; } public boolean getRecursive() { return this.recursive; } public void setPath(String path) { this.path = Paths.get(path); if (watcherThread == null) { try { watcherThread = new WatcherThread(this.path, this.recursive); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not watch CDX directory: " + e.getMessage(), e); } watcherThread.start(); } } public String getPath() { return this.path.toString(); } /** * removes a SearchResultSource upon from the list of sources. * * @param deleted * @return */ public boolean removeSource(CDXIndex deleted) { return sources.remove(deleted); } /** * Monitors a directory for ENTRY_CREATE/ENTRY_DELETE events, creating * SearchResultSources. * * @author rcoram * */ private class WatcherThread extends Thread { private final WatchService watcher; private final HashMap<WatchKey, Path> keys = new HashMap<WatchKey, Path>(); private final int depth; private final FileVisitor<Path> visitor = new CDXFileVisitor(); public WatcherThread(Path path, boolean recursive) throws IOException { if (recursive) { LOGGER.finest("Watching recursively."); this.depth = Integer.MAX_VALUE; } else { this.depth = 1; } this.watcher = FileSystems.getDefault().newWatchService(); Files.walkFileTree(path, visitOptions, depth, visitor); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void run() { while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); Path dir = keys.get(key); if (kind == ENTRY_CREATE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path path = dir.resolve(ev.context()); try { Files.walkFileTree(path, visitOptions, depth, visitor); } catch (IOException e) { LOGGER.log(Level.WARNING, "Problem walking: " + path.toString(), e); } } if (kind == ENTRY_DELETE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path path = dir.resolve(ev.context()); CDXIndex index = new CDXIndex(); index.setPath(path.toString()); if (!removeSource(index)) { LOGGER.info("CDX " + path + " not found in list of sources."); } else { LOGGER.info("Removed " + path); } } } // "If the key is no longer valid, the directory is inaccessible // so exit the loop." boolean valid = key.reset(); if (!valid) { break; } } } /** * handles traversal of CDX (sub)directories. * * @author rcoram * */ public class CDXFileVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { if (attrs.isRegularFile()) { String spath = path.toString(); Matcher matcher; for (Pattern pattern : includePatterns) { matcher = pattern.matcher(spath); if (matcher.matches()) { CDXIndex index = new CDXIndex(); index.setPath(spath); if (!sources.contains(index)) { LOGGER.info("Adding CDX: " + index.getPath()); addSource(index); } } break; } } return CONTINUE; } @SuppressWarnings("restriction") @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (keys.keySet().size() < depth) { WatchKey key = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE}, HIGH); LOGGER.info("Watching: " + dir.toString()); keys.put(key, dir); return CONTINUE; } else { return SKIP_SUBTREE; } } } } }
wayback-core/src/main/java/org/archive/wayback/resourceindex/WatchedCDXSource.java
package org.archive.wayback.resourceindex; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.SKIP_SUBTREE; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.archive.wayback.resourceindex.cdx.CDXIndex; /** * SearchResultSource that watches a single directory for new * SearchResultSources. * * <pre> * {@code * <property name="source"> * <bean class="org.archive.wayback.resourceindex.WatchedCDXSource"> * <property name="recursive" value="false" /> * <property name="filters"> * <list> * <value>^.+\.cdx$</value> * </list> * </property> * <property name="path" value="/wayback/cdx-index/" /> * </bean> * </property> * } * </pre> * * @author rcoram * */ public class WatchedCDXSource extends CompositeSearchResultSource { private static final Logger LOGGER = Logger .getLogger(WatchedCDXSource.class.getName()); private Thread watcherThread; private Path path; private boolean recursive = false; private List<String> filters; private ArrayList<Pattern> includePatterns = new ArrayList<Pattern>(); private final Set<FileVisitOption> visitOptions = EnumSet .noneOf(FileVisitOption.class); public WatchedCDXSource() { visitOptions.add(FileVisitOption.FOLLOW_LINKS); } { setFilters(Arrays.asList("^.+\\.cdx$")); } public void setFilters(List<String> filters) { for (String filter : filters) { includePatterns.add(Pattern.compile(filter)); } this.filters = filters; } public List<String> getFilters() { return this.filters; } public void setRecursive(boolean recursive) { this.recursive = recursive; } public boolean getRecursive() { return this.recursive; } public void setPath(String path) { this.path = Paths.get(path); if (watcherThread == null) { try { watcherThread = new WatcherThread(this.path, this.recursive); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not watch CDX directory: " + e.getMessage(), e); } watcherThread.start(); } } public String getPath() { return this.path.toString(); } /** * removes a SearchResultSource upon from the list of sources. * * @param deleted * @return */ public boolean removeSource(CDXIndex deleted) { return sources.remove(deleted); } /** * Monitors a directory for ENTRY_CREATE/ENTRY_DELETE events, creating * SearchResultSources. * * @author rcoram * */ private class WatcherThread extends Thread { private final WatchService watcher; private final HashMap<WatchKey, Path> keys = new HashMap<WatchKey, Path>(); private final int depth; private final FileVisitor<Path> visitor = new CDXFileVisitor(); public WatcherThread(Path path, boolean recursive) throws IOException { if (recursive) { LOGGER.finest("Watching recursively."); this.depth = Integer.MAX_VALUE; } else { this.depth = 1; } this.watcher = FileSystems.getDefault().newWatchService(); Files.walkFileTree(path, visitOptions, depth, visitor); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void run() { while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); Path dir = keys.get(key); if (kind == ENTRY_CREATE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path path = dir.resolve(ev.context()); try { Files.walkFileTree(path, visitOptions, depth, visitor); } catch (IOException e) { LOGGER.log(Level.WARNING, "Problem walking: " + path.toString(), e); } } if (kind == ENTRY_DELETE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path path = dir.resolve(ev.context()); CDXIndex index = new CDXIndex(); index.setPath(path.toString()); if (!removeSource(index)) { LOGGER.info("CDX " + path + " not found in list of sources."); } else { LOGGER.info("Removed " + path); } } } // "If the key is no longer valid, the directory is inaccessible // so exit the loop." boolean valid = key.reset(); if (!valid) { break; } } } /** * handles traversal of CDX (sub)directories. * * @author rcoram * */ public class CDXFileVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { if (attrs.isRegularFile()) { String spath = path.toString(); Matcher matcher; for (Pattern pattern : includePatterns) { matcher = pattern.matcher(spath); if (matcher.matches()) { CDXIndex index = new CDXIndex(); index.setPath(spath); if (!sources.contains(index)) { LOGGER.info("Adding CDX: " + index.getPath()); addSource(index); } } break; } } return CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (keys.keySet().size() < depth) { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE); LOGGER.info("Watching: " + dir.toString()); keys.put(key, dir); return CONTINUE; } else { return SKIP_SUBTREE; } } } } }
Fix for WatchedCDXSource on Mac.
wayback-core/src/main/java/org/archive/wayback/resourceindex/WatchedCDXSource.java
Fix for WatchedCDXSource on Mac.
<ide><path>ayback-core/src/main/java/org/archive/wayback/resourceindex/WatchedCDXSource.java <ide> <ide> import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; <ide> import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; <add>import static com.sun.nio.file.SensitivityWatchEventModifier.HIGH; <ide> import static java.nio.file.FileVisitResult.CONTINUE; <ide> import static java.nio.file.FileVisitResult.SKIP_SUBTREE; <ide> <ide> return CONTINUE; <ide> } <ide> <del> @Override <add> @SuppressWarnings("restriction") <add> @Override <ide> public FileVisitResult preVisitDirectory(Path dir, <ide> BasicFileAttributes attrs) throws IOException { <ide> if (keys.keySet().size() < depth) { <del> WatchKey key = dir.register(watcher, ENTRY_CREATE, <del> ENTRY_DELETE); <add> WatchKey key = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE}, HIGH); <ide> LOGGER.info("Watching: " + dir.toString()); <ide> keys.put(key, dir); <ide> return CONTINUE;
Java
mit
1736e79861a2b17923e0b4e5b35ffccd729b3026
0
jhy/jsoup,offa/jsoup,jhy/jsoup,offa/jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.parser.Parser; import javax.annotation.Nullable; import java.io.IOException; /** A comment node. @author Jonathan Hedley, [email protected] */ public class Comment extends LeafNode { /** Create a new comment node. @param data The contents of the comment */ public Comment(String data) { value = data; } public String nodeName() { return "#comment"; } /** Get the contents of the comment. @return comment content */ public String getData() { return coreValue(); } public Comment setData(String data) { coreValue(data); return this; } void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException { if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock()) || (out.outline() ))) indent(accum, depth, out); accum .append("<!--") .append(getData()) .append("-->"); } void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {} @Override public String toString() { return outerHtml(); } @Override public Comment clone() { return (Comment) super.clone(); } /** * Check if this comment looks like an XML Declaration. * @return true if it looks like, maybe, it's an XML Declaration. */ public boolean isXmlDeclaration() { String data = getData(); return (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))); } /** * Attempt to cast this comment to an XML Declaration node. * @return an XML declaration if it could be parsed as one, null otherwise. */ public @Nullable XmlDeclaration asXmlDeclaration() { String data = getData(); Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser()); XmlDeclaration decl = null; if (doc.children().size() > 0) { Element el = doc.child(0); decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!")); decl.attributes().addAll(el.attributes()); } return decl; } }
src/main/java/org/jsoup/nodes/Comment.java
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.parser.Parser; import javax.annotation.Nullable; import java.io.IOException; /** A comment node. @author Jonathan Hedley, [email protected] */ public class Comment extends LeafNode { /** Create a new comment node. @param data The contents of the comment */ public Comment(String data) { value = data; } public String nodeName() { return "#comment"; } /** Get the contents of the comment. @return comment content */ public String getData() { return coreValue(); } public Comment setData(String data) { coreValue(data); return this; } void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException { if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock()) || (out.outline() ))) indent(accum, depth, out); accum .append("<!--") .append(getData()) .append("-->"); } void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {} @Override public String toString() { return outerHtml(); } @Override public Comment clone() { return (Comment) super.clone(); } /** * Check if this comment looks like an XML Declaration. * @return true if it looks like, maybe, it's an XML Declaration. */ public boolean isXmlDeclaration() { String data = getData(); return (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))); } /** * Attempt to cast this comment to an XML Declaration note. * @return an XML declaration if it could be parsed as one, null otherwise. */ public @Nullable XmlDeclaration asXmlDeclaration() { String data = getData(); Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser()); XmlDeclaration decl = null; if (doc.children().size() > 0) { Element el = doc.child(0); decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!")); decl.attributes().addAll(el.attributes()); } return decl; } }
Javadoc typo
src/main/java/org/jsoup/nodes/Comment.java
Javadoc typo
<ide><path>rc/main/java/org/jsoup/nodes/Comment.java <ide> } <ide> <ide> /** <del> * Attempt to cast this comment to an XML Declaration note. <add> * Attempt to cast this comment to an XML Declaration node. <ide> * @return an XML declaration if it could be parsed as one, null otherwise. <ide> */ <ide> public @Nullable XmlDeclaration asXmlDeclaration() {
Java
apache-2.0
7f937d41ee2e99e6ea34033398781fc201f29cca
0
signed/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,signed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,signed/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,youdonghai/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,xfournet/intellij-community,apixandru/intellij-community,retomerz/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,da1z/intellij-community,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,semonte/intellij-community,retomerz/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,allotria/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,FHannes/intellij-community,signed/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,semonte/intellij-community,xfournet/intellij-community,asedunov/intellij-community,signed/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ibinti/intellij-community,apixandru/intellij-community,asedunov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,xfournet/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,signed/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,fitermay/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fitermay/intellij-community,allotria/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ibinti/intellij-community,asedunov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,hurricup/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,signed/intellij-community,signed/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,FHannes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,asedunov/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,allotria/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ibinti/intellij-community,retomerz/intellij-community,FHannes/intellij-community,hurricup/intellij-community,ibinti/intellij-community
/* * Copyright 2000-2015 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.jetbrains.python.inspections; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.lang.ASTNode; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.codeInsight.intentions.PyAnnotateTypesIntention; import com.jetbrains.python.debugger.PySignature; import com.jetbrains.python.debugger.PySignatureCacheManager; import com.jetbrains.python.inspections.quickfix.PyQuickFixUtil; import com.jetbrains.python.psi.PyElementVisitor; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.psi.PyNamedParameter; import com.jetbrains.python.psi.PyParameter; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * @author traff */ public class PyMissingTypeHintsInspection extends PyInspection { /** * @noinspection PublicField */ public boolean m_onlyWhenTypesAreKnown = true; @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { return new PyElementVisitor() { @Override public void visitPyFunction(PyFunction function) { if (!(function.getTypeComment() != null || typeAnnotationsExist(function))) { boolean flag = shouldRegisterProblem(function); if (flag) { ASTNode nameNode = function.getNameNode(); if (nameNode != null) { holder.registerProblem(nameNode.getPsi(), "Type hinting is missing for function definition", new AddTypeHintsQuickFix(function.getName())); } } } } }; } private boolean shouldRegisterProblem(PyFunction function) { if (m_onlyWhenTypesAreKnown) { PySignature signature = PySignatureCacheManager.getInstance(function.getProject()).findSignature(function); return signature != null && canAnnotate(signature); } else { return true; } } private static boolean canAnnotate(@NotNull PySignature signature) { return !"NoneType".equals(signature.getReturnTypeQualifiedName()) || signature.getArgs().size() > 1 || (signature.getArgs().size() == 1 && !"self".equals(signature.getArgs().get(0).getName())); } private static boolean typeAnnotationsExist(PyFunction function) { for (PyParameter param : function.getParameterList().getParameters()) { PyNamedParameter namedParameter = param.getAsNamed(); if (namedParameter != null) { if (namedParameter.getAnnotation() != null) { return true; } } } if (function.getAnnotation() != null) { return true; } return false; } public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel("Only when types are known(collected from run-time or inferred)", this, "m_onlyWhenTypesAreKnown"); } private static class AddTypeHintsQuickFix implements LocalQuickFix { private String myName; public AddTypeHintsQuickFix(@NotNull String name) { myName = name; } @Nls @NotNull @Override public String getName() { return "Add type hints for '" + myName + "'"; } @Nls @NotNull @Override public String getFamilyName() { return "Add type hints"; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PyFunction function = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PyFunction.class); if (function != null) { PyAnnotateTypesIntention.annotateTypes(PyQuickFixUtil.getEditor(function), function); } } } }
python/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java
/* * Copyright 2000-2015 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.jetbrains.python.inspections; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.lang.ASTNode; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.codeInsight.intentions.PyAnnotateTypesIntention; import com.jetbrains.python.debugger.PySignature; import com.jetbrains.python.debugger.PySignatureCacheManager; import com.jetbrains.python.inspections.quickfix.PyQuickFixUtil; import com.jetbrains.python.psi.PyElementVisitor; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.psi.PyNamedParameter; import com.jetbrains.python.psi.PyParameter; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * @author traff */ public class PyMissingTypeHintsInspection extends PyInspection { /** * @noinspection PublicField */ public boolean m_onlyWhenTypesAreKnown = true; @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { return new PyElementVisitor() { @Override public void visitPyFunction(PyFunction function) { if (!(function.getTypeComment() != null || typeAnnotationsExist(function))) { boolean flag = shouldRegisterProblem(function); if (flag) { ASTNode nameNode = function.getNameNode(); if (nameNode != null) { holder.registerProblem(nameNode.getPsi(), "Type hinting is missing for function definition", new AddTypeHintsQuickFix(function.getName())); } } } } }; } private boolean shouldRegisterProblem(PyFunction function) { if (m_onlyWhenTypesAreKnown) { PySignature signature = PySignatureCacheManager.getInstance(function.getProject()).findSignature(function); return signature != null; } else { return true; } } private static boolean typeAnnotationsExist(PyFunction function) { for (PyParameter param : function.getParameterList().getParameters()) { PyNamedParameter namedParameter = param.getAsNamed(); if (namedParameter != null) { if (namedParameter.getAnnotation() != null) { return true; } } } if (function.getAnnotation() != null) { return true; } return false; } public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel("Only when types are known(collected from run-time or inferred)", this, "m_onlyWhenTypesAreKnown"); } private static class AddTypeHintsQuickFix implements LocalQuickFix { private String myName; public AddTypeHintsQuickFix(@NotNull String name) { myName = name; } @Nls @NotNull @Override public String getName() { return "Add type hints for '" + myName + "'"; } @Nls @NotNull @Override public String getFamilyName() { return "Add type hints"; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PyFunction function = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PyFunction.class); if (function != null) { PyAnnotateTypesIntention.annotateTypes(PyQuickFixUtil.getEditor(function), function); } } } }
Suggest to add hints only if there is something to add
python/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java
Suggest to add hints only if there is something to add
<ide><path>ython/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java <ide> if (flag) { <ide> ASTNode nameNode = function.getNameNode(); <ide> if (nameNode != null) { <del> holder.registerProblem(nameNode.getPsi(), <add> holder.registerProblem(nameNode.getPsi(), <ide> "Type hinting is missing for function definition", <ide> new AddTypeHintsQuickFix(function.getName())); <ide> } <ide> private boolean shouldRegisterProblem(PyFunction function) { <ide> if (m_onlyWhenTypesAreKnown) { <ide> PySignature signature = PySignatureCacheManager.getInstance(function.getProject()).findSignature(function); <del> return signature != null; <add> return signature != null && canAnnotate(signature); <ide> } <ide> else { <ide> return true; <ide> } <add> } <add> <add> private static boolean canAnnotate(@NotNull PySignature signature) { <add> return !"NoneType".equals(signature.getReturnTypeQualifiedName()) <add> || signature.getArgs().size() > 1 <add> || (signature.getArgs().size() == 1 && !"self".equals(signature.getArgs().get(0).getName())); <ide> } <ide> <ide> private static boolean typeAnnotationsExist(PyFunction function) {
JavaScript
mit
d8de916a61e6931d4c85f109b44e682484b6b04f
0
ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring ([email protected]), Duncan Mitchell ([email protected]), or Johannes Kinder ([email protected]) for details or support | LICENSE.md for license details */ "use strict"; import ObjectHelper from './Utilities/ObjectHelper'; import Log from './Utilities/Log'; import Z3 from 'z3javascript'; import Config from './Config'; import { WrappedValue, ConcolicValue } from './Values/WrappedValue'; const find = Array.prototype.find; const map = Array.prototype.map; function Exists(array1, array2, pred) { for (let i = 0; i < array1.length; i++) { if (pred(array1[i], array2[i])) { return true; } } return false; } function DoesntMatch(l, r) { if (l === undefined) { return r !== ''; } else { return l !== r; } } function CloneReplace(list, item, n) { let clone = list.slice(0); clone[clone.indexOf(item)] = n; return clone; } function CloneRemove(list, item) { let c = list.slice(0); c.splice(list.indexOf(item), 1); return c; } function BuildModels() { let models = {}; for (let item in Object.getOwnPropertyNames(Object.prototype)) { if (!ObjectHelper.startsWith(item, '__')) { delete models[item]; } } function EnableCaptures(regex, real, string_s) { if (!Config.capturesEnabled) { Log.log('Captures disabled - potential loss of precision'); } Log.logMid('Captures Enabled - Adding Implications'); let implies = this.state.ctx.mkImplies(this.state.ctx.mkSeqInRe(string_s, regex.ast), this.state.ctx.mkEq(string_s, regex.implier)) //Mock the symbolic conditional if (regex.test(/.../) then regex.match => true) regex.assertions.forEach(binder => this.state.pushCondition(binder, true)); this.state.pushCondition(implies, true); } function BuildRefinements(regex, real, string_s) { if (!(Config.capturesEnabled && Config.refinementsEnabled)) { Log.log('Refinements disabled - potential accuracy loss'); return { trueCheck: [], falseCheck: [] }; } Log.log('Refinements Enabled - Adding checks'); function CheckCorrect(model) { let real_match = real.exec(model.eval(string_s).asConstant()); let sym_match = regex.captures.map(cap => model.eval(cap).asConstant()); Log.logMid('Regex sanity check ' + JSON.stringify(real_match) + ' vs ' + JSON.stringify(sym_match)); return real_match && !Exists(real_match, sym_match, DoesntMatch); } function CheckFailed(model) { return !real.test(model.eval(string_s).asConstant()); } let NotMatch = Z3.Check(CheckCorrect, (query, model) => { let not = this.state.ctx.mkNot(this.state.ctx.mkEq(string_s, this.state.ctx.mkString(model.eval(string_s).asConstant()))); return [new Z3.Query(query.exprs.slice(0).concat([not]), [CheckFixed, NotMatch])]; }); let CheckFixed = Z3.Check(CheckCorrect, (query, model) => { //CheckCorrect will check model has a proper match let real_match = real.exec(model.eval(string_s).asConstant()); if (real_match) { real_match = real_match.map(match => match || ''); let query_list = regex.captures.map((cap, idx) => this.state.ctx.mkEq(this.state.ctx.mkString(real_match[idx]), cap)); /*Log.logMid("WARN: TODO: Removing CheckFixed and NotMatch from checks may break stuff"); let next_list = CloneReplace(query.checks, CheckFixed, Z3.Check(CheckCorrect, () => [])); next_list = CloneReplace(query.checks, NotMatch, Z3.Check(CheckCorrect, () => [])); */ return [new Z3.Query(query.exprs.slice(0).concat(query_list), [])]; } else { Log.log('WARN: Broken regex detected ' + regex.ast.toString() + ' vs ' + real); Log.log('WARN: No Highly Specific Refinements'); return []; } }); let CheckNotIn = Z3.Check(CheckFailed, (query, model) => { Log.log('BIG WARN: False check failed, possible divergence'); return []; }); return { trueCheck: [NotMatch, CheckFixed], falseCheck: [CheckNotIn] }; } function RegexTest(regex, real, string, forceCaptures) { let in_s = this.state.ctx.mkSeqInRe(this.state.asSymbolic(string), regex.ast); let in_c = real.test(this.state.getConcrete(string)); let result = new ConcolicValue(in_c, in_s); if (regex.backreferences || forceCaptures) { EnableCaptures.call(this, regex, real, this.state.asSymbolic(string)); let checks = BuildRefinements.call(this, regex, real, this.state.asSymbolic(string)); console.log('CReating Checks ' + checks.trueCheck.length); in_s.checks.trueCheck = checks.trueCheck; //in_s.checks.falseCheck = checks.false; } console.log(JSON.stringify(in_s)); return result; } function RegexSearch(real, string, result) { let regex = Z3.Regex(this.state.ctx, real); //TODO: There is only the need to force back references if anchors are not set let in_regex = RegexTest.apply(this, [regex, real, string, true]); let search_in_re = this.state.ctx.mkIte(this.state.getSymbolic(in_regex), regex.startIndex, this.state.wrapConstant(-1)); return new ConcolicValue(result, search_in_re); } function RegexMatch(real, string, result) { let regex = Z3.Regex(this.state.ctx, real); let in_regex = RegexTest.apply(this, [regex, real, string, true]); this.state.symbolicConditional(in_regex); let string_s = this.state.asSymbolic(string); if (this.state.getConcrete(in_regex)) { let rewrittenResult = []; if (Config.capturesEnabled) { rewrittenResult = result.map((current_c, idx) => { //TODO: This is really nasty, current_c should be a return new ConcolicValue(current_c === undefined ? '' : current_c, regex.captures[idx]); }); } rewrittenResult.index = new ConcolicValue(result.index, regex.startIndex); rewrittenResult.input = string; result = rewrittenResult; } return result; } function substringHelper(c, _f, base, args, result) { Log.log('WARNING: Symbolic substring support new and buggy ' + JSON.stringify(args)); let target = c.state.asSymbolic(base); let start_off = c.state.ctx.mkRealToInt(c.state.asSymbolic(args[0])); let len; if (args[1]) { len = c.state.asSymbolic(args[1]); len = c.state.ctx.mkRealToInt(len); } else { len = c.state.ctx.mkSub(c.state.ctx.mkSeqLength(target), start_off); } return new ConcolicValue(result, c.state.ctx.mkSeqSubstr(target, start_off, len)); } //TODO - Ouch function rewriteTestSticky(real, target, result) { if (real.sticky || real.global) { let lastIndex = real.lastIndex; let lastIndex_s = this.state.asSymbolic(real.lastIndex); let lastIndex_c = this.state.getConcrete(real.lastIndex); real.lastIndex = lastIndex_c; let realResult = real.exec(this.state.getConcrete(target)); if (lastIndex_c) { let part_c = this.state.getConcrete(target); let part_s = this.state.getSymbolic(target); let real_cut = part_c.substring(lastIndex_c, part_c.length); target = substringHelper.call(this, this, null, target, [lastIndex, new ConcolicValue(part_c.length, this.state.ctx.mkSeqLength(part_s))], real_cut ); } let matchResult = RegexMatch.call(this, real, target, realResult); if (matchResult) { let firstAdd = new ConcolicValue(lastIndex_c + this.state.getConcrete(matchResult.index), this.state.symbolicBinary('+', lastIndex_c, lastIndex_s, this.state.getConcrete(matchResult.index), this.state.asSymbolic(matchResult.index))); let secondAdd = new ConcolicValue(this.state.getConcrete(firstAdd), this.state.getConcrete(matchResult[0]).length, this.state.symbolicBinary('+', this.state.getConcrete(firstAdd), this.state.asSymbolic(firstAdd), this.state.getConcrete(matchResult[0].length), this.state.ctx.mkSeqLength(this.state.asSymbolic(matchResult[0])))); real.lastIndex = secondAdd; return true; } else { return false; } } else { return RegexTest.call(this, Z3.Regex(this.state.ctx, real), real, target, false); } } /** * Symbolic hook is a helper function which builds concrete results and then, * if condition() -> true executes a symbolic helper specified by hook * Both hook and condition are called with (context (SymbolicExecutor), f, base, args, result) * * A function which makes up the new function model is returned */ function symbolicHook(condition, hook, featureDisabled) { return function(f, base, args, result) { result = undefined; let thrown = undefined; //Defer throw until after hook has run try { result = f.apply(this.state.getConcrete(base), map.call(args, arg => this.state.getConcrete(arg))); } catch (e) { thrown = e; } Log.logMid(`Symbolic Testing ${f.name} with base ${ObjectHelper.asString(base)} and ${ObjectHelper.asString(args)} and initial result ${ObjectHelper.asString(result)}`); if (!featureDisabled && condition(this, f, base, args, result)) { result = hook(this, f, base, args, result); } Log.logMid(`Result: ${'' + result} Thrown: ${'' + thrown}`); if (thrown) { throw thrown; } return result; }; } function symbolicHookRe(condition, hook) { return symbolicHook(condition, function(env) { env.state.stats.seen('regex'); hook.apply(this, arguments); }, !Config.regexEnabled); } function NoOp() { return function(f, base, args, result) { Log.logMid(`NoOp ${f.name} with base ${ObjectHelper.asString(base)} and ${ObjectHelper.asString(args)}`); return f.apply(base, args); }; } /** * Model for String(xxx) in code to coerce something to a string */ models[String] = symbolicHook( (c, _f, _base, args, _result) => c.state.isSymbolic(args[0]), (c, _f, _base, args, result) => new ConcolicValue(result, c.state.asSymbolic(c._concretizeToString(args[0]))) ); models[String.prototype.substr] = symbolicHook( (c, _f, base, args, _) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]) || c.state.isSymbolic(args[1]), substringHelper ); models[String.prototype.substring] = models[String.prototype.substr]; models[String.prototype.charAt] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]), (c, _f, base, args, result) => new ConcolicValue(result, c.state.ctx.mkSeqAt(c.state.asSymbolic(base), c.state.ctx.mkRealToInt(c.state.asSymbolic(args[0])))) ); models[String.prototype.concat] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || find.call(args, arg => c.state.isSymbolic(arg)), (c, _f, base, args, result) => new ConcolicValue(result, c.state.ctx.mkSeqConcat([c.state.asSymbolic(base)].concat(args.map(arg => c.state.asSymbolic(arg))))) ); models[String.prototype.indexOf] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]) || c.state.isSymbolic(args[1]), (c, _f, base, args, result) => { let off = args[1] ? c.state.asSymbolic(args[1]) : c.state.asSymbolic(0); off = c.state.ctx.mkRealToInt(off); result = new ConcolicValue(result, c.state.ctx.mkSeqIndexOf(c.state.asSymbolic(base), c.state.asSymbolic(c._concretizeToString(args[0])), off)); return result; } ); models[String.prototype.search] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp, (c, _f, base, args, result) => RegexSearch.call(c, args[0], base, result) ); models[String.prototype.match] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp, (c, _f, base, args, result) => RegexMatch.call(c, args[0], base, result) ); models[RegExp.prototype.exec] = symbolicHookRe( (c, _f, base, args, _r) => base instanceof RegExp && c.state.isSymbolic(args[0]), (c, _f, base, args, result) => RegexMatch.call(c, base, args[0], result) ); models[RegExp.prototype.test] = symbolicHookRe( (c, _f, _base, args, _r) => c.state.isSymbolic(args[0]), (c, _f, base, args, result) => rewriteTestSticky.call(c, base, c._concretizeToString(args[0]), result) ); //Replace model for replace regex by string. Does not model replace with callback. models[String.prototype.replace] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp && typeof args[1] === 'string', (c, _f, base, args, result) => { return c.state.getConcrete(base).secret_replace.apply(base, args); } ); models[String.prototype.split] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp, (c, _f, base, args, result) => { return c.state.getConcrete(base).secret_split.apply(base, args); } ); models[String.prototype.trim] = symbolicHook( (c, _f, base, _a, _r) => c.state.isSymbolic(base), (c, _f, base, _a, result) => { Log.log('TODO: Trim model does not currently do anything'); return new ConcolicValue(result, c.state.getSymbolic(base)); } ); models[String.prototype.toLowerCase] = function(f, base, args, result) { result = f.apply(this.state.getConcrete(base)); if (this.state.isSymbolic(base)) { Log.log('TODO: Awful String.prototype.toLowerCase model will reduce search space'); base = this._concretizeToString(base); let azRegex = Z3.Regex(this.state.ctx, /^[^A-Z]+$/); this.state.pushCondition(this.state.ctx.mkSeqInRe(this.state.getSymbolic(base), azRegex.ast), true); result = new ConcolicValue(result, this.state.getSymbolic(base)); } return result; }; models[Number.prototype.toFixed] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]), (c, _f, base, args, result) => { const toFix = c.state.asSymbolic(base); const requiredDigits = c.state.asSymbolic(args[0]); const gte0 = c.state.ctx.mkGe(requiredDigits, c.state.ctx.mkIntVal(0)); const lte20 = c.state.ctx.mkLe(requiredDigits, c.state.ctx.mkIntVal(20)); const validRequiredDigitsSymbolic = c.state.ctx.mkAnd(lte20, gte0); const validRequiredDigits = c.state.getConcrete(args[0]) >= 0 && c.state.getConcrete(args[0]) <= 20; c.state.symbolicConditional(new ConcolicValue(!!validRequiredDigits, validRequiredDigitsSymbolic)); if (validRequiredDigits) { //TODO: Need to coerce result to string // const pow = c.state.ctx.mkPower(c.state.asSymbolic(10), requiredDigits) // const symbolicValue = c.state.ctx.mkDiv(c.state.ctx.mkInt2Real(c.state.ctx.mkReal2Int(c.state.ctx.mkMul(pow, toFix))), c.state.asSymbolic(10.0)) //return new ConcolicValue(result, symbolicValue); return result; } else { // f.Apply() will throw } } ); models[Array.prototype.push] = NoOp(); models[Array.prototype.keys] = NoOp(); models[Array.prototype.concat] = NoOp(); models[Array.prototype.forEach] = NoOp(); models[Array.prototype.slice] = NoOp(); models[Array.prototype.filter] = NoOp(); models[Array.prototype.map] = NoOp(); models[Array.prototype.shift] = NoOp(); models[Array.prototype.unshift] = NoOp(); models[Array.prototype.fill] = NoOp(); return models; } export default BuildModels();
Analyser/src/FunctionModels.js
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring ([email protected]), Duncan Mitchell ([email protected]), or Johannes Kinder ([email protected]) for details or support | LICENSE.md for license details */ "use strict"; import ObjectHelper from './Utilities/ObjectHelper'; import Log from './Utilities/Log'; import Z3 from 'z3javascript'; import Config from './Config'; import { WrappedValue, ConcolicValue } from './Values/WrappedValue'; const find = Array.prototype.find; const map = Array.prototype.map; function Exists(array1, array2, pred) { for (let i = 0; i < array1.length; i++) { if (pred(array1[i], array2[i])) { return true; } } return false; } function DoesntMatch(l, r) { if (l === undefined) { return r !== ''; } else { return l !== r; } } function CloneReplace(list, item, n) { let clone = list.slice(0); clone[clone.indexOf(item)] = n; return clone; } function CloneRemove(list, item) { let c = list.slice(0); c.splice(list.indexOf(item), 1); return c; } function BuildModels() { let models = {}; for (let item in Object.getOwnPropertyNames(Object.prototype)) { if (!ObjectHelper.startsWith(item, '__')) { delete models[item]; } } function EnableCaptures(regex, real, string_s) { if (!Config.capturesEnabled) { Log.log('Captures disabled - potential loss of precision'); } Log.logMid('Captures Enabled - Adding Implications'); let implies = this.state.ctx.mkImplies(this.state.ctx.mkSeqInRe(string_s, regex.ast), this.state.ctx.mkEq(string_s, regex.implier)) //Mock the symbolic conditional if (regex.test(/.../) then regex.match => true) regex.assertions.forEach(binder => this.state.pushCondition(binder, true)); this.state.pushCondition(implies, true); } function BuildRefinements(regex, real, string_s) { if (!(Config.capturesEnabled && Config.refinementsEnabled)) { Log.log('Refinements disabled - potential accuracy loss'); return { trueCheck: [], falseCheck: [] }; } Log.log('Refinements Enabled - Adding checks'); function CheckCorrect(model) { let real_match = real.exec(model.eval(string_s).asConstant()); let sym_match = regex.captures.map(cap => model.eval(cap).asConstant()); Log.logMid('Regex sanity check ' + JSON.stringify(real_match) + ' vs ' + JSON.stringify(sym_match)); return real_match && !Exists(real_match, sym_match, DoesntMatch); } function CheckFailed(model) { return !real.test(model.eval(string_s).asConstant()); } let NotMatch = Z3.Check(CheckCorrect, (query, model) => { let not = this.state.ctx.mkNot(this.state.ctx.mkEq(string_s, this.state.ctx.mkString(model.eval(string_s).asConstant()))); return [new Z3.Query(query.exprs.slice(0).concat([not]), [CheckFixed, NotMatch])]; }); let CheckFixed = Z3.Check(CheckCorrect, (query, model) => { //CheckCorrect will check model has a proper match let real_match = real.exec(model.eval(string_s).asConstant()); if (real_match) { real_match = real_match.map(match => match || ''); let query_list = regex.captures.map((cap, idx) => this.state.ctx.mkEq(this.state.ctx.mkString(real_match[idx]), cap)); /*Log.logMid("WARN: TODO: Removing CheckFixed and NotMatch from checks may break stuff"); let next_list = CloneReplace(query.checks, CheckFixed, Z3.Check(CheckCorrect, () => [])); next_list = CloneReplace(query.checks, NotMatch, Z3.Check(CheckCorrect, () => [])); */ return [new Z3.Query(query.exprs.slice(0).concat(query_list), [])]; } else { Log.log('WARN: Broken regex detected ' + regex.ast.toString() + ' vs ' + real); Log.log('WARN: No Highly Specific Refinements'); return []; } }); let CheckNotIn = Z3.Check(CheckFailed, (query, model) => { Log.log('BIG WARN: False check failed, possible divergence'); return []; }); return { trueCheck: [NotMatch, CheckFixed], falseCheck: [CheckNotIn] }; } function RegexTest(regex, real, string, forceCaptures) { let in_s = this.state.ctx.mkSeqInRe(this.state.asSymbolic(string), regex.ast); let in_c = real.test(this.state.getConcrete(string)); let result = new ConcolicValue(in_c, in_s); if (regex.backreferences || forceCaptures) { EnableCaptures.call(this, regex, real, this.state.asSymbolic(string)); let checks = BuildRefinements.call(this, regex, real, this.state.asSymbolic(string)); console.log('CReating Checks ' + checks.trueCheck.length); in_s.checks.trueCheck = checks.trueCheck; //in_s.checks.falseCheck = checks.false; } console.log(JSON.stringify(in_s)); return result; } function RegexSearch(real, string, result) { let regex = Z3.Regex(this.state.ctx, real); //TODO: There is only the need to force back references if anchors are not set let in_regex = RegexTest.apply(this, [regex, real, string, true]); let search_in_re = this.state.ctx.mkIte(this.state.getSymbolic(in_regex), regex.startIndex, this.state.wrapConstant(-1)); return new ConcolicValue(result, search_in_re); } function RegexMatch(real, string, result) { let regex = Z3.Regex(this.state.ctx, real); let in_regex = RegexTest.apply(this, [regex, real, string, true]); this.state.symbolicConditional(in_regex); let string_s = this.state.asSymbolic(string); if (this.state.getConcrete(in_regex)) { let rewrittenResult = []; if (Config.capturesEnabled) { rewrittenResult = result.map((current_c, idx) => { //TODO: This is really nasty, current_c should be a return new ConcolicValue(current_c === undefined ? '' : current_c, regex.captures[idx]); }); } rewrittenResult.index = new ConcolicValue(result.index, regex.startIndex); rewrittenResult.input = string; result = rewrittenResult; } return result; } function substringHelper(c, _f, base, args, result) { Log.log('WARNING: Symbolic substring support new and buggy ' + JSON.stringify(args)); let target = c.state.asSymbolic(base); let start_off = c.state.ctx.mkRealToInt(c.state.asSymbolic(args[0])); let len; if (args[1]) { len = c.state.asSymbolic(args[1]); len = c.state.ctx.mkRealToInt(len); } else { len = c.state.ctx.mkSub(c.state.ctx.mkSeqLength(target), start_off); } return new ConcolicValue(result, c.state.ctx.mkSeqSubstr(target, start_off, len)); } //TODO - Ouch function rewriteTestSticky(real, target, result) { if (real.sticky || real.global) { let lastIndex = real.lastIndex; let lastIndex_s = this.state.asSymbolic(real.lastIndex); let lastIndex_c = this.state.getConcrete(real.lastIndex); real.lastIndex = lastIndex_c; let realResult = real.exec(this.state.getConcrete(target)); if (lastIndex_c) { let part_c = this.state.getConcrete(target); let part_s = this.state.getSymbolic(target); let real_cut = part_c.substring(lastIndex_c, part_c.length); target = substringHelper.call(this, this, null, target, [lastIndex, new ConcolicValue(part_c.length, this.state.ctx.mkSeqLength(part_s))], real_cut ); } let matchResult = RegexMatch.call(this, real, target, realResult); if (matchResult) { let firstAdd = new ConcolicValue(lastIndex_c + this.state.getConcrete(matchResult.index), this.state.symbolicBinary('+', lastIndex_c, lastIndex_s, this.state.getConcrete(matchResult.index), this.state.asSymbolic(matchResult.index))); let secondAdd = new ConcolicValue(this.state.getConcrete(firstAdd), this.state.getConcrete(matchResult[0]).length, this.state.symbolicBinary('+', this.state.getConcrete(firstAdd), this.state.asSymbolic(firstAdd), this.state.getConcrete(matchResult[0].length), this.state.ctx.mkSeqLength(this.state.asSymbolic(matchResult[0])))); real.lastIndex = secondAdd; return true; } else { return false; } } else { return RegexTest.call(this, Z3.Regex(this.state.ctx, real), real, target, false); } } /** * Symbolic hook is a helper function which builds concrete results and then, * if condition() -> true executes a symbolic helper specified by hook * Both hook and condition are called with (context (SymbolicExecutor), f, base, args, result) * * A function which makes up the new function model is returned */ function symbolicHook(condition, hook, featureDisabled) { return function(f, base, args, result) { result = undefined; let thrown = undefined; //Defer throw until after hook has run try { result = f.apply(this.state.getConcrete(base), map.call(args, arg => this.state.getConcrete(arg))); } catch (e) { thrown = e; } Log.logMid(`Symbolic Testing ${f.name} with base ${ObjectHelper.asString(base)} and ${ObjectHelper.asString(args)} and initial result ${ObjectHelper.asString(result)}`); if (!featureDisabled && condition(this, f, base, args, result)) { result = hook(this, f, base, args, result); } Log.logMid(`Result: ${'' + result} Thrown: ${'' + thrown}`); if (thrown) { throw thrown; } return result; }; } function symbolicHookRe(condition, hook) { return symbolicHook(condition, hook, !Config.regexEnabled); } function NoOp() { return function(f, base, args, result) { Log.logMid(`NoOp ${f.name} with base ${ObjectHelper.asString(base)} and ${ObjectHelper.asString(args)}`); return f.apply(base, args); }; } /** * Model for String(xxx) in code to coerce something to a string */ models[String] = symbolicHook( (c, _f, _base, args, _result) => c.state.isSymbolic(args[0]), (c, _f, _base, args, result) => new ConcolicValue(result, c.state.asSymbolic(c._concretizeToString(args[0]))) ); models[String.prototype.substr] = symbolicHook( (c, _f, base, args, _) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]) || c.state.isSymbolic(args[1]), substringHelper ); models[String.prototype.substring] = models[String.prototype.substr]; models[String.prototype.charAt] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]), (c, _f, base, args, result) => new ConcolicValue(result, c.state.ctx.mkSeqAt(c.state.asSymbolic(base), c.state.ctx.mkRealToInt(c.state.asSymbolic(args[0])))) ); models[String.prototype.concat] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || find.call(args, arg => c.state.isSymbolic(arg)), (c, _f, base, args, result) => new ConcolicValue(result, c.state.ctx.mkSeqConcat([c.state.asSymbolic(base)].concat(args.map(arg => c.state.asSymbolic(arg))))) ); models[String.prototype.indexOf] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]) || c.state.isSymbolic(args[1]), (c, _f, base, args, result) => { let off = args[1] ? c.state.asSymbolic(args[1]) : c.state.asSymbolic(0); off = c.state.ctx.mkRealToInt(off); result = new ConcolicValue(result, c.state.ctx.mkSeqIndexOf(c.state.asSymbolic(base), c.state.asSymbolic(c._concretizeToString(args[0])), off)); return result; } ); models[String.prototype.search] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp, (c, _f, base, args, result) => RegexSearch.call(c, args[0], base, result) ); models[String.prototype.match] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp, (c, _f, base, args, result) => RegexMatch.call(c, args[0], base, result) ); models[RegExp.prototype.exec] = symbolicHookRe( (c, _f, base, args, _r) => base instanceof RegExp && c.state.isSymbolic(args[0]), (c, _f, base, args, result) => RegexMatch.call(c, base, args[0], result) ); models[RegExp.prototype.test] = symbolicHookRe( (c, _f, _base, args, _r) => c.state.isSymbolic(args[0]), (c, _f, base, args, result) => rewriteTestSticky.call(c, base, c._concretizeToString(args[0]), result) ); //Replace model for replace regex by string. Does not model replace with callback. models[String.prototype.replace] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp && typeof args[1] === 'string', (c, _f, base, args, result) => { return c.state.getConcrete(base).secret_replace.apply(base, args); } ); models[String.prototype.split] = symbolicHookRe( (c, _f, base, args, _r) => c.state.isSymbolic(base) && args[0] instanceof RegExp, (c, _f, base, args, result) => { return c.state.getConcrete(base).secret_split.apply(base, args); } ); models[String.prototype.trim] = symbolicHook( (c, _f, base, _a, _r) => c.state.isSymbolic(base), (c, _f, base, _a, result) => { Log.log('TODO: Trim model does not currently do anything'); return new ConcolicValue(result, c.state.getSymbolic(base)); } ); models[String.prototype.toLowerCase] = function(f, base, args, result) { result = f.apply(this.state.getConcrete(base)); if (this.state.isSymbolic(base)) { Log.log('TODO: Awful String.prototype.toLowerCase model will reduce search space'); base = this._concretizeToString(base); let azRegex = Z3.Regex(this.state.ctx, /^[^A-Z]+$/); this.state.pushCondition(this.state.ctx.mkSeqInRe(this.state.getSymbolic(base), azRegex.ast), true); result = new ConcolicValue(result, this.state.getSymbolic(base)); } return result; }; models[Number.prototype.toFixed] = symbolicHook( (c, _f, base, args, _r) => c.state.isSymbolic(base) || c.state.isSymbolic(args[0]), (c, _f, base, args, result) => { const toFix = c.state.asSymbolic(base); const requiredDigits = c.state.asSymbolic(args[0]); const gte0 = c.state.ctx.mkGe(requiredDigits, c.state.ctx.mkIntVal(0)); const lte20 = c.state.ctx.mkLe(requiredDigits, c.state.ctx.mkIntVal(20)); const validRequiredDigitsSymbolic = c.state.ctx.mkAnd(lte20, gte0); const validRequiredDigits = c.state.getConcrete(args[0]) >= 0 && c.state.getConcrete(args[0]) <= 20; c.state.symbolicConditional(new ConcolicValue(!!validRequiredDigits, validRequiredDigitsSymbolic)); if (validRequiredDigits) { //TODO: Need to coerce result to string // const pow = c.state.ctx.mkPower(c.state.asSymbolic(10), requiredDigits) // const symbolicValue = c.state.ctx.mkDiv(c.state.ctx.mkInt2Real(c.state.ctx.mkReal2Int(c.state.ctx.mkMul(pow, toFix))), c.state.asSymbolic(10.0)) //return new ConcolicValue(result, symbolicValue); return result; } else { // f.Apply() will throw } } ); models[Array.prototype.push] = NoOp(); models[Array.prototype.keys] = NoOp(); models[Array.prototype.concat] = NoOp(); models[Array.prototype.forEach] = NoOp(); models[Array.prototype.slice] = NoOp(); models[Array.prototype.filter] = NoOp(); models[Array.prototype.map] = NoOp(); models[Array.prototype.shift] = NoOp(); models[Array.prototype.unshift] = NoOp(); models[Array.prototype.fill] = NoOp(); return models; } export default BuildModels();
Count regular expressions
Analyser/src/FunctionModels.js
Count regular expressions
<ide><path>nalyser/src/FunctionModels.js <ide> } <ide> <ide> function symbolicHookRe(condition, hook) { <del> return symbolicHook(condition, hook, !Config.regexEnabled); <add> return symbolicHook(condition, function(env) { <add> env.state.stats.seen('regex'); <add> hook.apply(this, arguments); <add> }, !Config.regexEnabled); <ide> } <ide> <ide> function NoOp() {
JavaScript
agpl-3.0
37a5b926ee89a5e653d2e0440019b3f6f4215ff9
0
mcolom/ipolDevel,mcolom/ipolDevel,mcolom/ipolDevel,mcolom/ipolDevel
var clientApp = clientApp || {}; var editor = editor || {}; var helpers = clientApp.helpers || {}; var upload = clientApp.upload || {}; var zoomController = zoomController || {}; var scrollController = scrollController || {}; var inpaintingController = inpaintingController || {}; var editorBlobs; var crop_info; editor.printEditor = function(crop) { if (helpers.getOrigin() === 'upload') checkTiff(); $("#inputEditorContainer").load("editor.html", function() { if (helpers.getOrigin() === "blobSet") editorBlobs = helpers.getFromStorage("demoSet"); crop_info = crop; printEditorPanel(); }); }; function printEditorPanel() { let inpaintingIsUsed = ddl.inputs.filter(input => { return input.control }).length > 0; inpaintingControls = []; $(".editor-container").removeClass("di-none"); var blobs = Object.keys(editorBlobs); printBlobSetList(blobs); $("#left-container").printEditorBlob(blobs[0], "left"); $("#right-container").printEditorBlob(blobs[0], "right"); if (inpaintingIsUsed) zoomController.inpaintingBlob(); else if (areAllImages()) displayImagesControls(blobs, editorBlobs[blobs[0]]) saveSelectedInput("right", blobs[0]); saveSelectedInput("left", blobs[0]); $(".editor-input-left-0, .editor-input-right-0").addClass("editor-input-selected"); scrollController.addScrollingEvents(); if (!inpaintingIsUsed) $("#left-container").attachDragger("left"); if (!inpaintingIsUsed) $("#right-container").attachDragger("right"); } function displayImagesControls(blobs, blob) { $("#zoom-container").removeClass("di-none"); if (blobs.length > 1) loadMultiBlobControls(); else if (blobs.length == 1 && ((blob.format == "image" && !isTiff(blob)) || blob.vr)) loadSingleBlobControls($("#editor-blob-left")); } function saveSelectedInput(side, index) { blobsKeys = Object.keys(editorBlobs); helpers.addToStorage("selectedInput-" + side, { text: "editor-input-" + side + "-" + index, src: blobsKeys[blobsKeys.indexOf(index)], format: editorBlobs[index].format }); } function isTiff(blob){ var type = blob.blob.split(";")[0].split("/")[1]; if (type === "tiff" || type === "tif") return true; return false; } // Print the chosen set blob list function printBlobSetList(blobs) { for (let i of Object.values(blobs)) { $(".inputListContainerLeft").append( "<span class=editor-input-left-" + i + ">" + ddl.inputs[i].description + "</span>" ); $(".editor-input-left-" + i).addClass("editor-input"); $(".editor-input-left-" + i).loadInputEvents( i, "left" ); $(".inputListContainerRight").append( "<span class=editor-input-right-" + i + ">" + ddl.inputs[i].description + "</span>" ); $(".editor-input-right-" + i).addClass("editor-input"); $(".editor-input-right-" + i).loadInputEvents( i, "right" ); } $(".inputListContainerLeft").loadInputsContainerEvent("left"); $(".inputListContainerRight").loadInputsContainerEvent("right"); } // Single blob sets controls function loadSingleBlobControls($img) { checkImageLoad($img[0].src).then(() => { if (ddl.inputs[0].type == "image" && !ddl.inputs[0].forbid_preprocess) displayCrop($img) zoomController.singleBlob(); }) .catch(() => { zoomController.singleBlob(); }) } function checkImageLoad(src){ return new Promise((resolve, reject) => { img = new Image() img.onload = () => resolve(img) img.onerror = () => reject(img) img.src = src }) } function displayCrop($img){ $(".blobsList-left").append( "<input type=checkbox id=crop-btn class=hand><label for=crop-btn class=hand>Crop</label>" ); if (crop_info == null) { $img.cropper({ viewMode: 1, autoCrop: false, dragMode: "move", wheelZoomRatio: 0.1, responsive: true, toggleDragModeOnDblclick: false, ready: setNaturalZoom }); } else { $img.cropper({ viewMode: 1, autoCrop: true, dragMode: "move", wheelZoomRatio: 0.1, responsive: true, data: crop_info, ready: getData, toggleDragModeOnDblclick: false }); $("#crop-btn").prop("checked", true); $("#canvas-container").removeClass("di-none"); } $img.on("cropmove cropstart cropend", function (e) { if ($("#crop-btn").prop("checked")) { var croppedImage = $("#left-container > img").cropper("getCroppedCanvas"); $("#canvas-container").html($(croppedImage)); } }); $img.on("zoom", function (e) { if (e.ratio >= 0.25 && e.ratio <= 16) { let selector = "#canvas-container > canvas, .blobEditorImage, .cropper-container img"; helpers.checkInterpolation(e.ratio, selector); $("#editor-zoom").val(e.ratio); $("#editor-zoom-value").html(e.ratio.toFixed(2) + "x"); if ($("#crop-btn").prop("checked")) { var croppedImage = $("#left-container > img").cropper( "getCroppedCanvas" ); $("#canvas-container").html($(croppedImage)); } } else { e.preventDefault(); } }); addCropEvent(); } function setNaturalZoom() { $("#editor-blob-left").cropper('zoomTo', 1); } function getData() { var imgData = $("#editor-blob-left").cropper("getImageData"); var zoom = imgData.height / imgData.naturalHeight; $("#editor-zoom").val(zoom); $("#editor-zoom-value").html(zoom.toFixed(2) + "px"); $("#editor-blob-left").cropper('zoomTo', zoom); } // Multiple blob sets controls function loadMultiBlobControls() { $(".blobsList-left").append( "<input type=checkbox id=compare-btn class=hand><label for=compare-btn>Compare</label>" ); zoomController.multiBlob(); addCompareEvent(); } // Check if all blobs are images or have visual representation (image) function areAllImages() { var blobs = Object.keys(editorBlobs); for (var i = 0; i < blobs.length; i++) { if ((editorBlobs[blobs[i]].format != "image" && !editorBlobs[blobs[i]].vr) || editorBlobs[blobs[i]].format == "audio" ||  editorBlobs[blobs[i]].format == "video") return false; } return true; } $.fn.printEditorBlob = function(index, side) { let editorBlob = editorBlobs[index] var blobType = editorBlob.format; var blobSrc = editorBlob.vr ? editorBlob.vr : editorBlob.blob; $("#broken-image-text-" + side).remove(); if (blobType == "video") { $(this).empty(); if (editorBlob.vr) { $(this).append("<img src=" + blobSrc + " id=editor-blob-" + side + " class=blobEditorVideo controls></img>"); } else { $(this).append("<video src=" + blobSrc + " id=editor-blob-" + side + " class=blobEditorVideo controls></video>"); } } else if (blobType == "audio") { $(this).empty(); var audioThumbnail = editorBlob.thumbnail ? editorBlob.thumbnail : "assets/non_viewable_data.png"; $(this).append("<img src=" + audioThumbnail + " class=audioThumbnail><br><audio src=" + editorBlob.blob + " id=editor-blob-" + side + " class=blobEditorAudio controls></audio>"); } else { if (ddl.inputs[index].control && side == "left") { $(this).empty(); $(this).append('<canvas id=editor-blob-' + side + ' class=blobEditorCanvas draggable=false></canvas>'); $("#editor-blob-" + side).css('background-image', 'url(' + blobSrc + ')'); attatchInpaintingControls(index, blobSrc, $('#editor-blob-' + side)[0]); } else if (isPreviousBlobImg(side)) { $("#editor-blob-" + side).attr("src", blobSrc); $("#editor-blob-" + side).attr("name", editorBlob.title); $("#editor-blob-" + side).on('load', function() { $("#editor-blob-" + side).width($(this)[0].naturalWidth * $("#editor-zoom").val()); $("#editor-blob-" + side).height($(this)[0].naturalHeight * $("#editor-zoom").val()); }); $("#editor-blob-" + side).displayImageSize(); } else { $(this).empty(); var img = "<img src=" + blobSrc + " id=editor-blob-" + side + " class=blobEditorImage draggable=false >"; $(img).appendTo($(this)); $(img).displayImageSize(); $("#editor-blob-" + side).css({ width: "auto", height: "auto" }); } $("#editor-blob-" + side).on("error", function(){ imageDisplayError(editorBlob, side)}); } }; function imageDisplayError(editorBlob, side){ $("#editor-blob-" + side).attr("src", "assets/non_viewable_data.png"); $("#editor-blob-left").css({ width: "auto", height: "auto" }); let text = (helpers.getOrigin() === 'upload') ? editorBlob.name : editorBlob.title; if (text == "") text = "Non viewable data" $("#broken-image-text-" + side).remove(); $("#editor-blob-" + side).parent().append('<span class=broken-image-text id=broken-image-text-' + side + '>' + text + '</span>'); $('.inputEditorContainer > .zoom-container').hide(); } function isPreviousBlobImg(side) { var previousBlob = document.getElementById("editor-blob-" + side); if (previousBlob != null && $("#editor-blob-" + side).is("img")) return true; return false; } function addCropEvent() { $("#crop-btn").on("click", function() { if ($("#crop-btn").is(":checked")) { $("#editor-blob-left").cropper("crop"); var croppedImage = $("#left-container > img").cropper("getCroppedCanvas"); $("#canvas-container").html($(croppedImage)); $("#canvas-container").removeClass("di-none"); } else { $("#canvas-container").addClass("di-none"); $("#editor-blob-left").cropper("clear"); $("#canvas-container").html("<div></div>"); } }); } function addCompareEvent() { $("#compare-btn").change(function() { if ($("#compare-btn").is(":checked")) $(".image-container").css({ "flex-basis": "50%" }); else $(".image-container").css({ "flex-basis": "" }); $(".editor-container").toggleClass("space-between"); $(".blobsList-right").toggleClass("di-inline"); $("#right-container").toggleClass("di-none"); $("#right-container").toggleClass("di-inline"); $(".blobsList-right").toggleClass("di-none"); }); } // Initialize input mouseover, mouseout and click event to switch input image. $.fn.loadInputEvents = function(index, side) { var container = $("#" + side + "-container"); $(this).on("mouseover", function() { ddl.inputs[index].control ? $('#inpaintingControls').toggle(true) : $('#inpaintingControls').toggle(false); container.printEditorBlob(index, side); zoomSync(editorBlobs[index], side); }); $(this).on("click", function() { var selectedInput = helpers.getFromStorage("selectedInput-" + side); $("." + selectedInput.text).removeClass("editor-input-selected"); $(this).addClass("editor-input-selected"); container.printEditorBlob(index, side); saveSelectedInput(side, index); zoomSync(editorBlobs[index], side); }); }; $.fn.loadInputsContainerEvent = function(side) { var container = $("#" + side + "-container"); $(this).on("mouseout", function(event) { e = event.toElement || event.relatedTarget; if (e != null && (e.parentNode == this || e == this)) { return; } var inputName = helpers.getFromStorage("selectedInput-" + side); ddl.inputs[parseInt(inputName.src)].control ? $('#inpaintingControls').toggle(true) : $('#inpaintingControls').toggle(false); container.printEditorBlob(inputName.src, side); zoomSync(editorBlobs[inputName.src], side); }); }; function zoomSync(blob, side) { if (blob.format == "image") { zoomController.changeImageZoom(side); } } $.fn.displayImageSize = function() { $(this).on('load', function() { $("#editor-image-size").html($(this)[0].naturalWidth + " x " + $(this)[0].naturalHeight); }); }; attatchInpaintingControls = (index, blobSrc, canvas) => { $.get("inpainting.html", function (data) { $("#inpaintingControls").html(data); inpaintingController.init(index, blobSrc, canvas); $('#erase-btn').hide(); $('#closed-fig-container').hide(); if (ddl.inputs[index].control == 'mask') { $('#erase-btn').show(); } if (ddl.inputs[index].control == 'lines') { $('#closed-fig-container').show(); } }); }
ipol_demo/clientApp/js/demo.editor.js
var clientApp = clientApp || {}; var editor = editor || {}; var helpers = clientApp.helpers || {}; var upload = clientApp.upload || {}; var zoomController = zoomController || {}; var scrollController = scrollController || {}; var inpaintingController = inpaintingController || {}; var editorBlobs; var crop_info; editor.printEditor = function(crop) { if (helpers.getOrigin() === 'upload') checkTiff(); $("#inputEditorContainer").load("editor.html", function() { if (helpers.getOrigin() === "blobSet") editorBlobs = helpers.getFromStorage("demoSet"); crop_info = crop; printEditorPanel(); }); }; function printEditorPanel() { let inpaintingIsUsed = ddl.inputs.filter(input => { return input.control }).length > 0; inpaintingControls = []; $(".editor-container").removeClass("di-none"); var blobs = Object.keys(editorBlobs); printBlobSetList(blobs); $("#left-container").printEditorBlob(blobs[0], "left"); $("#right-container").printEditorBlob(blobs[0], "right"); if (inpaintingIsUsed) zoomController.inpaintingBlob(); else if (areAllImages()) displayImagesControls(blobs, editorBlobs[blobs[0]]) saveSelectedInput("right", blobs[0]); saveSelectedInput("left", blobs[0]); $(".editor-input-left-0, .editor-input-right-0").addClass("editor-input-selected"); scrollController.addScrollingEvents(); if (!inpaintingIsUsed) $("#left-container").attachDragger("left"); if (!inpaintingIsUsed) $("#right-container").attachDragger("right"); } function displayImagesControls(blobs, blob) { $("#zoom-container").removeClass("di-none"); if (blobs.length > 1) loadMultiBlobControls(); else if (blobs.length == 1 && ((blob.format == "image" && !isTiff(blob)) || blob.vr)) loadSingleBlobControls($("#editor-blob-left")); } function saveSelectedInput(side, index) { blobsKeys = Object.keys(editorBlobs); helpers.addToStorage("selectedInput-" + side, { text: "editor-input-" + side + "-" + index, src: blobsKeys[blobsKeys.indexOf(index)], format: editorBlobs[index].format }); } function isTiff(blob){ var type = blob.blob.split(";")[0].split("/")[1]; if (type === "tiff" || type === "tif") return true; return false; } // Print the chosen set blob list function printBlobSetList(blobs) { for (let i of Object.values(blobs)) { $(".inputListContainerLeft").append( "<span class=editor-input-left-" + i + ">" + ddl.inputs[i].description + "</span>" ); $(".editor-input-left-" + i).addClass("editor-input"); $(".editor-input-left-" + i).loadInputEvents( i, "left" ); $(".inputListContainerRight").append( "<span class=editor-input-right-" + i + ">" + ddl.inputs[i].description + "</span>" ); $(".editor-input-right-" + i).addClass("editor-input"); $(".editor-input-right-" + i).loadInputEvents( i, "right" ); } $(".inputListContainerLeft").loadInputsContainerEvent("left"); $(".inputListContainerRight").loadInputsContainerEvent("right"); } // Single blob sets controls function loadSingleBlobControls($img) { checkImageLoad($img[0].src).then(() => { if (ddl.inputs[0].type == "image") displayCrop($img) zoomController.singleBlob(); }) .catch(() => { zoomController.singleBlob(); }) } function checkImageLoad(src){ return new Promise((resolve, reject) => { img = new Image() img.onload = () => resolve(img) img.onerror = () => reject(img) img.src = src }) } function displayCrop($img){ $(".blobsList-left").append( "<input type=checkbox id=crop-btn class=hand><label for=crop-btn class=hand>Crop</label>" ); if (crop_info == null) { $img.cropper({ viewMode: 1, autoCrop: false, dragMode: "move", wheelZoomRatio: 0.1, responsive: true, toggleDragModeOnDblclick: false, ready: setNaturalZoom }); } else { $img.cropper({ viewMode: 1, autoCrop: true, dragMode: "move", wheelZoomRatio: 0.1, responsive: true, data: crop_info, ready: getData, toggleDragModeOnDblclick: false }); $("#crop-btn").prop("checked", true); $("#canvas-container").removeClass("di-none"); } $img.on("cropmove cropstart cropend", function (e) { if ($("#crop-btn").prop("checked")) { var croppedImage = $("#left-container > img").cropper("getCroppedCanvas"); $("#canvas-container").html($(croppedImage)); } }); $img.on("zoom", function (e) { if (e.ratio >= 0.25 && e.ratio <= 16) { let selector = "#canvas-container > canvas, .blobEditorImage, .cropper-container img"; helpers.checkInterpolation(e.ratio, selector); $("#editor-zoom").val(e.ratio); $("#editor-zoom-value").html(e.ratio.toFixed(2) + "x"); if ($("#crop-btn").prop("checked")) { var croppedImage = $("#left-container > img").cropper( "getCroppedCanvas" ); $("#canvas-container").html($(croppedImage)); } } else { e.preventDefault(); } }); addCropEvent(); } function setNaturalZoom() { $("#editor-blob-left").cropper('zoomTo', 1); } function getData() { var imgData = $("#editor-blob-left").cropper("getImageData"); var zoom = imgData.height / imgData.naturalHeight; $("#editor-zoom").val(zoom); $("#editor-zoom-value").html(zoom.toFixed(2) + "px"); $("#editor-blob-left").cropper('zoomTo', zoom); } // Multiple blob sets controls function loadMultiBlobControls() { $(".blobsList-left").append( "<input type=checkbox id=compare-btn class=hand><label for=compare-btn>Compare</label>" ); zoomController.multiBlob(); addCompareEvent(); } // Check if all blobs are images or have visual representation (image) function areAllImages() { var blobs = Object.keys(editorBlobs); for (var i = 0; i < blobs.length; i++) { if ((editorBlobs[blobs[i]].format != "image" && !editorBlobs[blobs[i]].vr) || editorBlobs[blobs[i]].format == "audio" ||  editorBlobs[blobs[i]].format == "video") return false; } return true; } $.fn.printEditorBlob = function(index, side) { let editorBlob = editorBlobs[index] var blobType = editorBlob.format; var blobSrc = editorBlob.vr ? editorBlob.vr : editorBlob.blob; $("#broken-image-text-" + side).remove(); if (blobType == "video") { $(this).empty(); if (editorBlob.vr) { $(this).append("<img src=" + blobSrc + " id=editor-blob-" + side + " class=blobEditorVideo controls></img>"); } else { $(this).append("<video src=" + blobSrc + " id=editor-blob-" + side + " class=blobEditorVideo controls></video>"); } } else if (blobType == "audio") { $(this).empty(); var audioThumbnail = editorBlob.thumbnail ? editorBlob.thumbnail : "assets/non_viewable_data.png"; $(this).append("<img src=" + audioThumbnail + " class=audioThumbnail><br><audio src=" + editorBlob.blob + " id=editor-blob-" + side + " class=blobEditorAudio controls></audio>"); } else { if (ddl.inputs[index].control && side == "left") { $(this).empty(); $(this).append('<canvas id=editor-blob-' + side + ' class=blobEditorCanvas draggable=false></canvas>'); $("#editor-blob-" + side).css('background-image', 'url(' + blobSrc + ')'); attatchInpaintingControls(index, blobSrc, $('#editor-blob-' + side)[0]); } else if (isPreviousBlobImg(side)) { $("#editor-blob-" + side).attr("src", blobSrc); $("#editor-blob-" + side).attr("name", editorBlob.title); $("#editor-blob-" + side).on('load', function() { $("#editor-blob-" + side).width($(this)[0].naturalWidth * $("#editor-zoom").val()); $("#editor-blob-" + side).height($(this)[0].naturalHeight * $("#editor-zoom").val()); }); $("#editor-blob-" + side).displayImageSize(); } else { $(this).empty(); var img = "<img src=" + blobSrc + " id=editor-blob-" + side + " class=blobEditorImage draggable=false >"; $(img).appendTo($(this)); $(img).displayImageSize(); $("#editor-blob-" + side).css({ width: "auto", height: "auto" }); } $("#editor-blob-" + side).on("error", function(){ imageDisplayError(editorBlob, side)}); } }; function imageDisplayError(editorBlob, side){ $("#editor-blob-" + side).attr("src", "assets/non_viewable_data.png"); $("#editor-blob-left").css({ width: "auto", height: "auto" }); let text = (helpers.getOrigin() === 'upload') ? editorBlob.name : editorBlob.title; if (text == "") text = "Non viewable data" $("#broken-image-text-" + side).remove(); $("#editor-blob-" + side).parent().append('<span class=broken-image-text id=broken-image-text-' + side + '>' + text + '</span>'); $('.inputEditorContainer > .zoom-container').hide(); } function isPreviousBlobImg(side) { var previousBlob = document.getElementById("editor-blob-" + side); if (previousBlob != null && $("#editor-blob-" + side).is("img")) return true; return false; } function addCropEvent() { $("#crop-btn").on("click", function() { if ($("#crop-btn").is(":checked")) { $("#editor-blob-left").cropper("crop"); var croppedImage = $("#left-container > img").cropper("getCroppedCanvas"); $("#canvas-container").html($(croppedImage)); $("#canvas-container").removeClass("di-none"); } else { $("#canvas-container").addClass("di-none"); $("#editor-blob-left").cropper("clear"); $("#canvas-container").html("<div></div>"); } }); } function addCompareEvent() { $("#compare-btn").change(function() { if ($("#compare-btn").is(":checked")) $(".image-container").css({ "flex-basis": "50%" }); else $(".image-container").css({ "flex-basis": "" }); $(".editor-container").toggleClass("space-between"); $(".blobsList-right").toggleClass("di-inline"); $("#right-container").toggleClass("di-none"); $("#right-container").toggleClass("di-inline"); $(".blobsList-right").toggleClass("di-none"); }); } // Initialize input mouseover, mouseout and click event to switch input image. $.fn.loadInputEvents = function(index, side) { var container = $("#" + side + "-container"); $(this).on("mouseover", function() { ddl.inputs[index].control ? $('#inpaintingControls').toggle(true) : $('#inpaintingControls').toggle(false); container.printEditorBlob(index, side); zoomSync(editorBlobs[index], side); }); $(this).on("click", function() { var selectedInput = helpers.getFromStorage("selectedInput-" + side); $("." + selectedInput.text).removeClass("editor-input-selected"); $(this).addClass("editor-input-selected"); container.printEditorBlob(index, side); saveSelectedInput(side, index); zoomSync(editorBlobs[index], side); }); }; $.fn.loadInputsContainerEvent = function(side) { var container = $("#" + side + "-container"); $(this).on("mouseout", function(event) { e = event.toElement || event.relatedTarget; if (e != null && (e.parentNode == this || e == this)) { return; } var inputName = helpers.getFromStorage("selectedInput-" + side); ddl.inputs[parseInt(inputName.src)].control ? $('#inpaintingControls').toggle(true) : $('#inpaintingControls').toggle(false); container.printEditorBlob(inputName.src, side); zoomSync(editorBlobs[inputName.src], side); }); }; function zoomSync(blob, side) { if (blob.format == "image") { zoomController.changeImageZoom(side); } } $.fn.displayImageSize = function() { $(this).on('load', function() { $("#editor-image-size").html($(this)[0].naturalWidth + " x " + $(this)[0].naturalHeight); }); }; attatchInpaintingControls = (index, blobSrc, canvas) => { $.get("inpainting.html", function (data) { $("#inpaintingControls").html(data); inpaintingController.init(index, blobSrc, canvas); $('#erase-btn').hide(); $('#closed-fig-container').hide(); if (ddl.inputs[index].control == 'mask') { $('#erase-btn').show(); } if (ddl.inputs[index].control == 'lines') { $('#closed-fig-container').show(); } }); }
[clientApp] forbid preprocess will not allow cropping on inputs
ipol_demo/clientApp/js/demo.editor.js
[clientApp] forbid preprocess will not allow cropping on inputs
<ide><path>pol_demo/clientApp/js/demo.editor.js <ide> // Single blob sets controls <ide> function loadSingleBlobControls($img) { <ide> checkImageLoad($img[0].src).then(() => { <del> if (ddl.inputs[0].type == "image") displayCrop($img) <add> if (ddl.inputs[0].type == "image" && !ddl.inputs[0].forbid_preprocess) displayCrop($img) <ide> zoomController.singleBlob(); <ide> }) <ide> .catch(() => {
Java
agpl-3.0
b7fb2bf424e40e9f1478efdc9cc5329961665f10
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
b2a1ca8a-2e5f-11e5-9284-b827eb9e62be
hello.java
b29c5c76-2e5f-11e5-9284-b827eb9e62be
b2a1ca8a-2e5f-11e5-9284-b827eb9e62be
hello.java
b2a1ca8a-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>b29c5c76-2e5f-11e5-9284-b827eb9e62be <add>b2a1ca8a-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
b805875be914e5cdb5d53e19f37961cf4c35c96e
0
apache/jackrabbit,apache/jackrabbit,apache/jackrabbit
/* * 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.jackrabbit.core; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import javax.jcr.AccessDeniedException; import javax.jcr.InvalidItemStateException; import javax.jcr.ItemNotFoundException; import javax.jcr.NamespaceException; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.PropertyIterator; import javax.jcr.RepositoryException; import javax.jcr.nodetype.ConstraintViolationException; import org.apache.commons.collections.map.ReferenceMap; import org.apache.jackrabbit.core.id.ItemId; import org.apache.jackrabbit.core.id.NodeId; import org.apache.jackrabbit.core.id.PropertyId; import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry; import org.apache.jackrabbit.core.nodetype.EffectiveNodeType; import org.apache.jackrabbit.core.nodetype.NodeTypeConflictException; import org.apache.jackrabbit.core.security.authorization.Permission; import org.apache.jackrabbit.core.state.ChildNodeEntry; import org.apache.jackrabbit.core.state.ItemState; import org.apache.jackrabbit.core.state.ItemStateException; import org.apache.jackrabbit.core.state.ItemStateListener; import org.apache.jackrabbit.core.state.NoSuchItemStateException; import org.apache.jackrabbit.core.state.NodeState; import org.apache.jackrabbit.core.state.PropertyState; import org.apache.jackrabbit.core.state.SessionItemStateManager; import org.apache.jackrabbit.core.version.VersionHistoryImpl; import org.apache.jackrabbit.core.version.VersionImpl; import org.apache.jackrabbit.core.security.AccessManager; import org.apache.jackrabbit.core.session.SessionContext; import org.apache.jackrabbit.spi.Name; import org.apache.jackrabbit.spi.Path; import org.apache.jackrabbit.spi.QPropertyDefinition; import org.apache.jackrabbit.spi.QNodeDefinition; import org.apache.jackrabbit.spi.commons.name.NameConstants; import org.apache.jackrabbit.spi.commons.nodetype.NodeDefinitionImpl; import org.apache.jackrabbit.spi.commons.nodetype.PropertyDefinitionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * There's one <code>ItemManager</code> instance per <code>Session</code> * instance. It is the factory for <code>Node</code> and <code>Property</code> * instances. * <p/> * The <code>ItemManager</code>'s responsibilities are: * <ul> * <li>providing access to <code>Item</code> instances by <code>ItemId</code> * whereas <code>Node</code> and <code>Item</code> are only providing relative access. * <li>returning the instance of an existing <code>Node</code> or <code>Property</code>, * given its absolute path. * <li>creating the per-session instance of a <code>Node</code> * or <code>Property</code> that doesn't exist yet and needs to be created first. * <li>guaranteeing that there aren't multiple instances representing the same * <code>Node</code> or <code>Property</code> associated with the same * <code>Session</code> instance. * <li>maintaining a cache of the item instances it created. * <li>respecting access rights of associated <code>Session</code> in all methods. * </ul> * <p/> * If the parent <code>Session</code> is an <code>XASession</code>, there is * one <code>ItemManager</code> instance per started global transaction. */ public class ItemManager implements ItemStateListener { private static Logger log = LoggerFactory.getLogger(ItemManager.class); private final org.apache.jackrabbit.spi.commons.nodetype.NodeDefinitionImpl rootNodeDef; /** * Component context of the associated session. */ protected final SessionContext sessionContext; protected final SessionImpl session; private final SessionItemStateManager sism; private final HierarchyManager hierMgr; /** * A cache for item instances created by this <code>ItemManager</code> */ private final Map<ItemId, ItemData> itemCache; /** * Shareable node cache. */ private final ShareableNodesCache shareableNodesCache; /** * Creates a new per-session instance <code>ItemManager</code> instance. * * @param sessionContext component context of the associated session */ @SuppressWarnings("unchecked") protected ItemManager(SessionContext sessionContext) { this.sism = sessionContext.getItemStateManager(); this.hierMgr = sessionContext.getHierarchyManager(); this.sessionContext = sessionContext; this.session = sessionContext.getSessionImpl(); this.rootNodeDef = sessionContext.getNodeTypeManager().getRootNodeDefinition(); // setup item cache with weak references to items itemCache = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); // setup shareable nodes cache shareableNodesCache = new ShareableNodesCache(); } /** * Checks that this session is alive. * * @throws RepositoryException if the session has been closed */ private void sanityCheck() throws RepositoryException { sessionContext.getSessionState().checkAlive(); } /** * Disposes this <code>ItemManager</code> and frees resources. */ void dispose() { synchronized (itemCache) { itemCache.clear(); } shareableNodesCache.clear(); } NodeDefinitionImpl getDefinition(NodeState state) throws RepositoryException { if (state.getId().equals(sessionContext.getRootNodeId())) { // special handling required for root node return rootNodeDef; } NodeId parentId = state.getParentId(); if (parentId == null) { // removed state has parentId set to null // get from overlayed state ItemState overlaid = state.getOverlayedState(); if (overlaid != null) { parentId = overlaid.getParentId(); } else { throw new InvalidItemStateException( "Could not find parent of node " + state.getNodeId()); } } NodeState parentState = null; try { // access the parent state circumventing permission check, since // read permission on the parent isn't required in order to retrieve // a node's definition. see also JCR-2418 ItemData parentData = getItemData(parentId, null, false); parentState = (NodeState) parentData.getState(); if (state.getParentId() == null) { // indicates state has been removed, must use // overlayed state of parent, otherwise child node entry // cannot be found. unless the parentState is new, which // means it was recreated in place of a removed node // that used to be the actual parent if (parentState.getStatus() == ItemState.STATUS_NEW) { // force getting parent from attic parentState = null; } else { parentState = (NodeState) parentState.getOverlayedState(); } } } catch (ItemNotFoundException e) { // parent probably removed, get it from attic. see below } if (parentState == null) { try { // use overlayed state if available parentState = (NodeState) sism.getAttic().getItemState( parentId).getOverlayedState(); } catch (ItemStateException ex) { throw new RepositoryException(ex); } } // get child node entry ChildNodeEntry cne = parentState.getChildNodeEntry(state.getNodeId()); if (cne == null) { throw new InvalidItemStateException( "Could not find child " + state.getNodeId() + " of node " + parentState.getNodeId()); } NodeTypeRegistry ntReg = sessionContext.getNodeTypeRegistry(); try { EffectiveNodeType ent = ntReg.getEffectiveNodeType( parentState.getNodeTypeName(), parentState.getMixinTypeNames()); QNodeDefinition def; try { def = ent.getApplicableChildNodeDef( cne.getName(), state.getNodeTypeName(), ntReg); } catch (ConstraintViolationException e) { // fallback to child node definition of a nt:unstructured ent = ntReg.getEffectiveNodeType(NameConstants.NT_UNSTRUCTURED); def = ent.getApplicableChildNodeDef( cne.getName(), state.getNodeTypeName(), ntReg); log.warn("Fallback to nt:unstructured due to unknown child " + "node definition for type '" + state.getNodeTypeName() + "'"); } return sessionContext.getNodeTypeManager().getNodeDefinition(def); } catch (NodeTypeConflictException e) { throw new RepositoryException(e); } } PropertyDefinitionImpl getDefinition(PropertyState state) throws RepositoryException { // this is a bit ugly // there might be cases where otherwise protected items turn into // non-protected items because a mixin has been removed from the parent // node state. // see also: JCR-2408 if (state.getStatus() == ItemState.STATUS_EXISTING_REMOVED && state.getName().equals(NameConstants.JCR_UUID)) { NodeTypeRegistry ntReg = sessionContext.getNodeTypeRegistry(); QPropertyDefinition def = ntReg.getEffectiveNodeType( NameConstants.MIX_REFERENCEABLE).getApplicablePropertyDef( state.getName(), state.getType()); return sessionContext.getNodeTypeManager().getPropertyDefinition(def); } try { // retrieve parent in 2 steps in order to avoid the check for // read permissions on the parent which isn't required in order // to read the property's definition. see also JCR-2418. ItemData parentData = getItemData(state.getParentId(), null, false); NodeImpl parent = (NodeImpl) createItemInstance(parentData); return parent.getApplicablePropertyDefinition( state.getName(), state.getType(), state.isMultiValued(), true); } catch (ItemNotFoundException e) { // parent probably removed, get it from attic } try { NodeState parent = (NodeState) sism.getAttic().getItemState( state.getParentId()).getOverlayedState(); NodeTypeRegistry ntReg = sessionContext.getNodeTypeRegistry(); EffectiveNodeType ent = ntReg.getEffectiveNodeType( parent.getNodeTypeName(), parent.getMixinTypeNames()); QPropertyDefinition def; try { def = ent.getApplicablePropertyDef( state.getName(), state.getType(), state.isMultiValued()); } catch (ConstraintViolationException e) { ent = ntReg.getEffectiveNodeType(NameConstants.NT_UNSTRUCTURED); def = ent.getApplicablePropertyDef(state.getName(), state.getType(), state.isMultiValued()); log.warn("Fallback to nt:unstructured due to unknown property " + "definition for '" + state.getName() + "'"); } return sessionContext.getNodeTypeManager().getPropertyDefinition(def); } catch (ItemStateException e) { throw new RepositoryException(e); } catch (NodeTypeConflictException e) { throw new RepositoryException(e); } } /** * Common implementation for all variants of item/node/propertyExists * with both itemId or path param. * * @param itemId The id of the item to test. * @param path Path of the item to check if known or <code>null</code>. In * the latter case the test for access permission is executed using the * itemId. * @return true if the item with the given <code>itemId</code> exists AND * can be read by this session. */ private boolean itemExists(ItemId itemId, Path path) { try { sanityCheck(); // shortcut: check if state exists for the given item if (!sism.hasItemState(itemId)) { return false; } getItemData(itemId, path, true); return true; } catch (RepositoryException re) { return false; } } /** * Common implementation for all variants of getItem/getNode/getProperty * with both itemId or path parameter. * * @param itemId * @param path Path of the item to retrieve or <code>null</code>. In * the latter case the test for access permission is executed using the * itemId. * @param permissionCheck * @return The item identified by the given <code>itemId</code>. * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ private ItemImpl getItem(ItemId itemId, Path path, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(itemId, path, permissionCheck); return createItemInstance(data); } /** * Retrieves the data of the item with given <code>id</code>. If the * specified item doesn't exist an <code>ItemNotFoundException</code> will * be thrown. * If the item exists but the current session is not granted read access an * <code>AccessDeniedException</code> will be thrown. * * @param itemId id of item to be retrieved * @return state state of said item * @throws ItemNotFoundException if no item with given <code>id</code> exists * @throws AccessDeniedException if the current session is not allowed to * read the said item * @throws RepositoryException if another error occurs */ private ItemData getItemData(ItemId itemId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getItemData(itemId, null, true); } /** * Retrieves the data of the item with given <code>id</code>. If the * specified item doesn't exist an <code>ItemNotFoundException</code> will * be thrown. * If <code>permissionCheck</code> is <code>true</code> and the item exists * but the current session is not granted read access an * <code>AccessDeniedException</code> will be thrown. * * @param itemId id of item to be retrieved * @param path The path of the item to retrieve the data for or * <code>null</code>. In the latter case the id (instead of the path) is * used to test if READ permission is granted. * @param permissionCheck * @return the ItemData for the item identified by the given itemId. * @throws ItemNotFoundException if no item with given <code>id</code> exists * @throws AccessDeniedException if the current session is not allowed to * read the said item * @throws RepositoryException if another error occurs */ ItemData getItemData(ItemId itemId, Path path, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { ItemData data = retrieveItem(itemId); if (data == null) { // not yet in cache, need to create instance: // - retrieve item state // - create instance of item data // NOTE: permission check & caching within createItemData ItemState state; try { state = sism.getItemState(itemId); } catch (NoSuchItemStateException nsise) { throw new ItemNotFoundException(itemId.toString()); } catch (ItemStateException ise) { String msg = "failed to retrieve item state of item " + itemId; log.error(msg, ise); throw new RepositoryException(msg, ise); } // create item data including: perm check and caching. data = createItemData(state, path, permissionCheck); } else { // already cached: if 'permissionCheck' is true, make sure read // permission is granted. if (permissionCheck && !canRead(data, path)) { // item exists but read-perm has been revoked in the mean time. // -> remove from cache evictItems(itemId); throw new AccessDeniedException("cannot read item " + data.getId()); } } return data; } /** * @param data * @param path Path to be used for the permission check or <code>null</code> * in which case the itemId present with the specified <code>data</code> is used. * @return true if the item with the given <code>data</code> can be read; * <code>false</code> otherwise. * @throws AccessDeniedException * @throws RepositoryException */ private boolean canRead(ItemData data, Path path) throws AccessDeniedException, RepositoryException { // JCR-1601: cached item may just have been invalidated ItemState state = data.getState(); if (state == null) { throw new InvalidItemStateException(data.getId() + ": the item does not exist anymore"); } if (state.getStatus() == ItemState.STATUS_NEW) { if (!data.getDefinition().isProtected()) { /* NEW items can always be read as long they have been added through the API and NOT by the system (i.e. protected items). */ return true; } else { /* NEW protected (system) item: need use the path to evaluate the effective permissions. */ return (path == null) ? sessionContext.getAccessManager().isGranted(data.getId(), AccessManager.READ) : sessionContext.getAccessManager().isGranted(path, Permission.READ); } } else { /* item is not NEW -> save to call acMgr.canRead(Path,ItemId) */ return sessionContext.getAccessManager().canRead(path, data.getId()); } } /** * @param parent The item data of the parent node. * @param childId * @return true if the item with the given <code>childId</code> can be read; * <code>false</code> otherwise. * @throws RepositoryException */ private boolean canRead(ItemData parent, ItemId childId) throws RepositoryException { if (parent.getStatus() == ItemState.STATUS_EXISTING) { // child item is for sure not NEW (because then the parent was modified). // safe to use AccessManager#canRead(Path, ItemId). return sessionContext.getAccessManager().canRead(null, childId); } else { // child could be NEW -> don't use AccessManager#canRead(Path, ItemId) return sessionContext.getAccessManager().isGranted(childId, AccessManager.READ); } } //--------------------------------------------------< item access methods > /** * Checks whether an item exists at the specified path. * * @deprecated As of JSR 283, a <code>Path</code> doesn't anymore uniquely * identify an <code>Item</code>, therefore {@link #nodeExists(Path)} and * {@link #propertyExists(Path)} should be used instead. * * @param path path to the item to be checked * @return true if the specified item exists */ public boolean itemExists(Path path) { try { sanityCheck(); ItemId id = hierMgr.resolvePath(path); return (id != null) && itemExists(id, path); } catch (RepositoryException re) { return false; } } /** * Checks whether a node exists at the specified path. * * @param path path to the node to be checked * @return true if a node exists at the specified path */ public boolean nodeExists(Path path) { try { sanityCheck(); NodeId id = hierMgr.resolveNodePath(path); return (id != null) && itemExists(id, path); } catch (RepositoryException re) { return false; } } /** * Checks whether a property exists at the specified path. * * @param path path to the property to be checked * @return true if a property exists at the specified path */ public boolean propertyExists(Path path) { try { sanityCheck(); PropertyId id = hierMgr.resolvePropertyPath(path); return (id != null) && itemExists(id, path); } catch (RepositoryException re) { return false; } } /** * Checks if the item with the given id exists. * * @param id id of the item to be checked * @return true if the specified item exists */ public boolean itemExists(ItemId id) { return itemExists(id, null); } /** * @return * @throws RepositoryException */ NodeImpl getRootNode() throws RepositoryException { return (NodeImpl) getItem(sessionContext.getRootNodeId()); } /** * Returns the node at the specified absolute path in the workspace. * If no such node exists, then it returns the property at the specified path. * If no such property exists a <code>PathNotFoundException</code> is thrown. * * @deprecated As of JSR 283, a <code>Path</code> doesn't anymore uniquely * identify an <code>Item</code>, therefore {@link #getNode(Path)} and * {@link #getProperty(Path)} should be used instead. * @param path * @return * @throws PathNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ public ItemImpl getItem(Path path) throws PathNotFoundException, AccessDeniedException, RepositoryException { ItemId id = hierMgr.resolvePath(path); if (id == null) { throw new PathNotFoundException(safeGetJCRPath(path)); } try { ItemImpl item = getItem(id, path, true); // Test, if this item is a shareable node. if (item.isNode() && ((NodeImpl) item).isShareable()) { return getNode(path); } return item; } catch (ItemNotFoundException infe) { throw new PathNotFoundException(safeGetJCRPath(path)); } } /** * @param path * @return * @throws PathNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ public NodeImpl getNode(Path path) throws PathNotFoundException, AccessDeniedException, RepositoryException { NodeId id = hierMgr.resolveNodePath(path); if (id == null) { throw new PathNotFoundException(safeGetJCRPath(path)); } NodeId parentId = null; if (!path.denotesRoot()) { parentId = hierMgr.resolveNodePath(path.getAncestor(1)); } try { if (parentId == null) { return (NodeImpl) getItem(id, path, true); } // if the node is shareable, it now returns the node with the right // parent return getNode(id, parentId); } catch (ItemNotFoundException infe) { throw new PathNotFoundException(safeGetJCRPath(path)); } } /** * @param path * @return * @throws PathNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ public PropertyImpl getProperty(Path path) throws PathNotFoundException, AccessDeniedException, RepositoryException { PropertyId id = hierMgr.resolvePropertyPath(path); if (id == null) { throw new PathNotFoundException(safeGetJCRPath(path)); } try { return (PropertyImpl) getItem(id, path, true); } catch (ItemNotFoundException infe) { throw new PathNotFoundException(safeGetJCRPath(path)); } } /** * @param id * @return * @throws RepositoryException */ public synchronized ItemImpl getItem(ItemId id) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getItem(id, null, true); } /** * @param id * @return * @throws RepositoryException */ synchronized ItemImpl getItem(ItemId id, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getItem(id, null, permissionCheck); } /** * Returns a node with a given id and parent id. If the indicated node is * shareable, there might be multiple nodes associated with the same id, * but there'is only one node with the given parent id. * * @param id node id * @param parentId parent node id * @return node * @throws RepositoryException if an error occurs */ public synchronized NodeImpl getNode(NodeId id, NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getNode(id, parentId, true); } /** * Returns a node with a given id and parent id. If the indicated node is * shareable, there might be multiple nodes associated with the same id, * but there'is only one node with the given parent id. * * @param id node id * @param parentId parent node id * @param permissionCheck Flag indicating if read permission must be check * upon retrieving the node. * @return node * @throws RepositoryException if an error occurs */ synchronized NodeImpl getNode(NodeId id, NodeId parentId, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { if (parentId == null) { return (NodeImpl) getItem(id); } AbstractNodeData data = retrieveItem(id, parentId); if (data == null) { data = (AbstractNodeData) getItemData(id, null, permissionCheck); } else if (permissionCheck && !canRead(data, id)) { // item exists but read-perm has been revoked in the mean time. // -> remove from cache evictItems(id); throw new AccessDeniedException("cannot read item " + data.getId()); } if (!data.getParentId().equals(parentId)) { // verify that parent actually appears in the shared set if (!data.getNodeState().containsShare(parentId)) { String msg = "Node with id '" + id + "' does not have shared parent with id: " + parentId; throw new ItemNotFoundException(msg); } // TODO: ev. need to check if read perm. is granted. data = new NodeDataRef(data, parentId); cacheItem(data); } return createNodeInstance(data); } /** * Create an item instance from an item state. This method creates a * new <code>ItemData</code> instance without looking at the cache nor * testing if the item can be read and returns a new item instance. * * @param state item state * @return item instance * @throws RepositoryException if an error occurs */ synchronized ItemImpl createItemInstance(ItemState state) throws RepositoryException { ItemData data = createItemData(state, null, false); return createItemInstance(data); } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized boolean hasChildNodes(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child nodes of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } NodeState state = (NodeState) data.getState(); for (ChildNodeEntry entry : state.getChildNodeEntries()) { // make sure any of the properties can be read. if (canRead(data, entry.getId())) { return true; } } return false; } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized NodeIterator getChildNodes(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child nodes of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } ArrayList<ItemId> childIds = new ArrayList<ItemId>(); Iterator<ChildNodeEntry> iter = ((NodeState) data.getState()).getChildNodeEntries().iterator(); while (iter.hasNext()) { ChildNodeEntry entry = iter.next(); // delay check for read-access until item is being built // thus avoid duplicate check childIds.add(entry.getId()); } return new LazyItemIterator(sessionContext, childIds, parentId); } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized boolean hasChildProperties(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child properties of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } Iterator<Name> iter = ((NodeState) data.getState()).getPropertyNames().iterator(); while (iter.hasNext()) { Name propName = iter.next(); // make sure any of the properties can be read. if (canRead(data, new PropertyId(parentId, propName))) { return true; } } return false; } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized PropertyIterator getChildProperties(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child properties of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } ArrayList<PropertyId> childIds = new ArrayList<PropertyId>(); Iterator<Name> iter = ((NodeState) data.getState()).getPropertyNames().iterator(); while (iter.hasNext()) { Name propName = iter.next(); PropertyId id = new PropertyId(parentId, propName); // delay check for read-access until item is being built // thus avoid duplicate check childIds.add(id); } return new LazyItemIterator(sessionContext, childIds); } //-------------------------------------------------< item factory methods > /** * Builds the <code>ItemData</code> for the specified <code>state</code>. * If <code>permissionCheck</code> is <code>true</code>, the access manager * is used to determine if reading that item would be granted. If this is * not the case an <code>AccessDeniedException</code> is thrown. * Before returning the created <code>ItemData</code> it is put into the * cache. In order to benefit from the cache * {@link #getItemData(ItemId, Path, boolean)} should be called. * * @param state * @return * @throws RepositoryException */ private ItemData createItemData(ItemState state, Path path, boolean permissionCheck) throws RepositoryException { ItemData data; if (state.isNode()) { NodeState nodeState = (NodeState) state; data = new NodeData(nodeState, this); } else { PropertyState propertyState = (PropertyState) state; data = new PropertyData(propertyState, this); } // make sure read-perm. is granted before returning the data. if (permissionCheck && !canRead(data, path)) { throw new AccessDeniedException("cannot read item " + state.getId()); } // before returning the data: put them into the cache. cacheItem(data); return data; } private ItemImpl createItemInstance(ItemData data) { if (data.isNode()) { return createNodeInstance((AbstractNodeData) data); } else { return createPropertyInstance((PropertyData) data); } } private NodeImpl createNodeInstance(AbstractNodeData data) { // check special nodes final NodeState state = data.getNodeState(); if (state.getNodeTypeName().equals(NameConstants.NT_VERSION)) { return new VersionImpl(this, sessionContext, data); } else if (state.getNodeTypeName().equals(NameConstants.NT_VERSIONHISTORY)) { return new VersionHistoryImpl(this, sessionContext, data); } else { // create node object return new NodeImpl(this, sessionContext, data); } } private PropertyImpl createPropertyInstance(PropertyData data) { // check special nodes return new PropertyImpl(this, sessionContext, data); } //---------------------------------------------------< item cache methods > /** * Returns an item reference from the cache. * * @param id id of the item that should be retrieved. * @return the item reference stored in the corresponding cache entry * or <code>null</code> if there's no corresponding cache entry. */ private ItemData retrieveItem(ItemId id) { synchronized (itemCache) { ItemData data = itemCache.get(id); if (data == null && id.denotesNode()) { data = shareableNodesCache.retrieveFirst((NodeId) id); } return data; } } /** * Return a node from the cache. * * @param id id of the node that should be retrieved. * @param parentId parent id of the node that should be retrieved * @return reference stored in the corresponding cache entry * or <code>null</code> if there's no corresponding cache entry. */ private AbstractNodeData retrieveItem(NodeId id, NodeId parentId) { synchronized (itemCache) { AbstractNodeData data = shareableNodesCache.retrieve(id, parentId); if (data == null) { data = (AbstractNodeData) itemCache.get(id); } return data; } } /** * Puts the reference of an item in the cache with * the item's path as the key. * * @param data the item data to cache */ private void cacheItem(ItemData data) { synchronized (itemCache) { if (data.isNode()) { AbstractNodeData nd = (AbstractNodeData) data; if (nd.getPrimaryParentId() != null) { shareableNodesCache.cache(nd); return; } } ItemId id = data.getId(); if (itemCache.containsKey(id)) { log.warn("overwriting cached item " + id); } if (log.isDebugEnabled()) { log.debug("caching item " + id); } itemCache.put(id, data); } } /** * Removes all cache entries with the given item id. If the item is * shareable, there might be more than one cache entry for this item. * * @param id id of the items to remove from the cache */ private void evictItems(ItemId id) { if (log.isDebugEnabled()) { log.debug("removing items " + id + " from cache"); } synchronized (itemCache) { itemCache.remove(id); if (id.denotesNode()) { shareableNodesCache.evictAll((NodeId) id); } } } /** * Removes a cache entry for a specific item. * * @param data The item data to remove from the cache */ private void evictItem(ItemData data) { if (log.isDebugEnabled()) { log.debug("removing item " + data.getId() + " from cache"); } synchronized (itemCache) { if (data.isNode()) { shareableNodesCache.evict((AbstractNodeData) data); } ItemData cached = itemCache.get(data.getId()); if (cached == data) { itemCache.remove(data.getId()); } } } //-------------------------------------------------< misc. helper methods > /** * Failsafe conversion of internal <code>Path</code> to JCR path for use in * error messages etc. * * @param path path to convert * @return JCR path */ String safeGetJCRPath(Path path) { try { return session.getJCRPath(path); } catch (NamespaceException e) { log.error("failed to convert " + path.toString() + " to JCR path."); // return string representation of internal path as a fallback return path.toString(); } } /** * Failsafe translation of internal <code>ItemId</code> to JCR path for use in * error messages etc. * * @param id path to convert * @return JCR path */ String safeGetJCRPath(ItemId id) { try { return safeGetJCRPath(hierMgr.getPath(id)); } catch (RepositoryException re) { log.error(id + ": failed to determine path to"); // return string representation if id as a fallback return id.toString(); } } //------------------------------------------------< ItemLifeCycleListener > /** * {@inheritDoc} */ public void itemInvalidated(ItemId id, ItemData data) { if (log.isDebugEnabled()) { log.debug("invalidated item " + id); } evictItem(data); } /** * {@inheritDoc} */ public void itemDestroyed(ItemId id, ItemData data) { if (log.isDebugEnabled()) { log.debug("destroyed item " + id); } synchronized (itemCache) { // remove instance from cache evictItems(id); } } //--------------------------------------------------------------< Object > /** * {@inheritDoc} */ public synchronized String toString() { StringBuilder builder = new StringBuilder(); builder.append("ItemManager (" + super.toString() + ")\n"); builder.append("Items in cache:\n"); synchronized (itemCache) { for (ItemId id : itemCache.keySet()) { ItemData item = itemCache.get(id); if (item.isNode()) { builder.append("Node: "); } else { builder.append("Property: "); } if (item.getState().isTransient()) { builder.append("transient "); } else { builder.append(" "); } builder.append(id + "\t" + safeGetJCRPath(id) + " (" + item + ")\n"); } } return builder.toString(); } //----------------------------------------------------< ItemStateListener > /** * {@inheritDoc} */ public void stateCreated(ItemState created) { ItemData data = retrieveItem(created.getId()); if (data != null) { data.setStatus(ItemImpl.STATUS_NORMAL); } } /** * {@inheritDoc} */ public void stateModified(ItemState modified) { ItemData data = retrieveItem(modified.getId()); if (data != null && data.getState() == modified) { data.setStatus(ItemImpl.STATUS_MODIFIED); /* if (modified.isNode()) { NodeState state = (NodeState) modified; if (state.isShareable()) { //evictItem(modified.getId()); NodeData nodeData = (NodeData) data; NodeData shareSibling = new NodeData(nodeData, state.getParentId()); shareableNodesCache.cache(shareSibling); } } */ } } /** * {@inheritDoc} */ public void stateDestroyed(ItemState destroyed) { ItemData data = retrieveItem(destroyed.getId()); if (data != null && data.getState() == destroyed) { itemDestroyed(destroyed.getId(), data); data.setStatus(ItemImpl.STATUS_DESTROYED); } } /** * {@inheritDoc} */ public void stateDiscarded(ItemState discarded) { ItemData data = retrieveItem(discarded.getId()); if (data != null && data.getState() == discarded) { if (discarded.isTransient()) { switch (discarded.getStatus()) { /** * persistent item that has been transiently removed */ case ItemState.STATUS_EXISTING_REMOVED: case ItemState.STATUS_EXISTING_MODIFIED: ItemState persistentState = discarded.getOverlayedState(); // the state is a transient wrapper for the underlying // persistent state, therefore restore the persistent state // and resurrect this item instance if necessary SessionItemStateManager stateMgr = sessionContext.getItemStateManager(); stateMgr.disconnectTransientItemState(discarded); data.setState(persistentState); return; /** * persistent item that has been transiently modified or * removed and the underlying persistent state has been * externally destroyed since the transient * modification/removal. */ case ItemState.STATUS_STALE_DESTROYED: /** * first notify the listeners that this instance has been * permanently invalidated */ itemDestroyed(discarded.getId(), data); // now set state of this instance to 'destroyed' data.setStatus(ItemImpl.STATUS_DESTROYED); data.setState(null); return; /** * new item that has been transiently added */ case ItemState.STATUS_NEW: /** * first notify the listeners that this instance has been * permanently invalidated */ itemDestroyed(discarded.getId(), data); // now set state of this instance to 'destroyed' // finally dispose state data.setStatus(ItemImpl.STATUS_DESTROYED); data.setState(null); return; } } /** * first notify the listeners that this instance has been * invalidated */ itemInvalidated(discarded.getId(), data); // now render this instance 'invalid' data.setStatus(ItemImpl.STATUS_INVALIDATED); } } /** * Cache of shareable nodes. For performance reasons, methods are not * synchronized and thread-safety must be guaranteed by caller. */ static class ShareableNodesCache { /** * This cache is based on a reference map, that maps an item id to a map, * which again maps a (hard-ref) parent id to a (weak-ref) shareable node. */ private final ReferenceMap cache; /** * Create a new instance of this class. */ public ShareableNodesCache() { cache = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.HARD); } /** * Clear cache. * * @see ReferenceMap#clear() */ public void clear() { cache.clear(); } /** * Return the first available node that maps to the given id. * * @param id node id * @return node or <code>null</code> */ public AbstractNodeData retrieveFirst(NodeId id) { ReferenceMap map = (ReferenceMap) cache.get(id); if (map != null) { Iterator<AbstractNodeData> iter = map.values().iterator(); try { while (iter.hasNext()) { AbstractNodeData data = iter.next(); if (data != null) { return data; } } } finally { iter = null; } } return null; } /** * Return the node with the given id and parent id. * * @param id node id * @param parentId parent id * @return node or <code>null</code> */ public AbstractNodeData retrieve(NodeId id, NodeId parentId) { ReferenceMap map = (ReferenceMap) cache.get(id); if (map != null) { return (AbstractNodeData) map.get(parentId); } return null; } /** * Cache some node. * * @param data data to cache */ public void cache(AbstractNodeData data) { NodeId id = data.getNodeState().getNodeId(); ReferenceMap map = (ReferenceMap) cache.get(id); if (map == null) { map = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); cache.put(id, map); } Object old = map.put(data.getPrimaryParentId(), data); if (old != null) { log.warn("overwriting cached item: " + old); } } /** * Evict some node from the cache. * * @param data data to evict */ public void evict(AbstractNodeData data) { ReferenceMap map = (ReferenceMap) cache.get(data.getId()); if (map != null) { map.remove(data.getPrimaryParentId()); } } /** * Evict all nodes with a given node id from the cache. * * @param id node id to evict */ public synchronized void evictAll(NodeId id) { cache.remove(id); } } }
jackrabbit-core/src/main/java/org/apache/jackrabbit/core/ItemManager.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.jackrabbit.core; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import javax.jcr.AccessDeniedException; import javax.jcr.InvalidItemStateException; import javax.jcr.ItemNotFoundException; import javax.jcr.NamespaceException; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.PropertyIterator; import javax.jcr.RepositoryException; import javax.jcr.nodetype.ConstraintViolationException; import org.apache.commons.collections.map.ReferenceMap; import org.apache.jackrabbit.core.id.ItemId; import org.apache.jackrabbit.core.id.NodeId; import org.apache.jackrabbit.core.id.PropertyId; import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry; import org.apache.jackrabbit.core.nodetype.EffectiveNodeType; import org.apache.jackrabbit.core.nodetype.NodeTypeConflictException; import org.apache.jackrabbit.core.security.authorization.Permission; import org.apache.jackrabbit.core.state.ChildNodeEntry; import org.apache.jackrabbit.core.state.ItemState; import org.apache.jackrabbit.core.state.ItemStateException; import org.apache.jackrabbit.core.state.ItemStateListener; import org.apache.jackrabbit.core.state.NoSuchItemStateException; import org.apache.jackrabbit.core.state.NodeState; import org.apache.jackrabbit.core.state.PropertyState; import org.apache.jackrabbit.core.state.SessionItemStateManager; import org.apache.jackrabbit.core.version.VersionHistoryImpl; import org.apache.jackrabbit.core.version.VersionImpl; import org.apache.jackrabbit.core.security.AccessManager; import org.apache.jackrabbit.core.session.SessionContext; import org.apache.jackrabbit.spi.Name; import org.apache.jackrabbit.spi.Path; import org.apache.jackrabbit.spi.QPropertyDefinition; import org.apache.jackrabbit.spi.QNodeDefinition; import org.apache.jackrabbit.spi.commons.name.NameConstants; import org.apache.jackrabbit.spi.commons.nodetype.NodeDefinitionImpl; import org.apache.jackrabbit.spi.commons.nodetype.PropertyDefinitionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * There's one <code>ItemManager</code> instance per <code>Session</code> * instance. It is the factory for <code>Node</code> and <code>Property</code> * instances. * <p/> * The <code>ItemManager</code>'s responsibilities are: * <ul> * <li>providing access to <code>Item</code> instances by <code>ItemId</code> * whereas <code>Node</code> and <code>Item</code> are only providing relative access. * <li>returning the instance of an existing <code>Node</code> or <code>Property</code>, * given its absolute path. * <li>creating the per-session instance of a <code>Node</code> * or <code>Property</code> that doesn't exist yet and needs to be created first. * <li>guaranteeing that there aren't multiple instances representing the same * <code>Node</code> or <code>Property</code> associated with the same * <code>Session</code> instance. * <li>maintaining a cache of the item instances it created. * <li>respecting access rights of associated <code>Session</code> in all methods. * </ul> * <p/> * If the parent <code>Session</code> is an <code>XASession</code>, there is * one <code>ItemManager</code> instance per started global transaction. */ public class ItemManager implements ItemStateListener { private static Logger log = LoggerFactory.getLogger(ItemManager.class); private final org.apache.jackrabbit.spi.commons.nodetype.NodeDefinitionImpl rootNodeDef; /** * Component context of the associated session. */ protected final SessionContext sessionContext; protected final SessionImpl session; private final SessionItemStateManager sism; private final HierarchyManager hierMgr; /** * A cache for item instances created by this <code>ItemManager</code> */ private final Map<ItemId, ItemData> itemCache; /** * Shareable node cache. */ private final ShareableNodesCache shareableNodesCache; /** * Creates a new per-session instance <code>ItemManager</code> instance. * * @param sessionContext component context of the associated session */ @SuppressWarnings("unchecked") protected ItemManager(SessionContext sessionContext) { this.sism = sessionContext.getItemStateManager(); this.hierMgr = sessionContext.getHierarchyManager(); this.sessionContext = sessionContext; this.session = sessionContext.getSessionImpl(); this.rootNodeDef = sessionContext.getNodeTypeManager().getRootNodeDefinition(); // setup item cache with weak references to items itemCache = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); // setup shareable nodes cache shareableNodesCache = new ShareableNodesCache(); } /** * Checks that this session is alive. * * @throws RepositoryException if the session has been closed */ private void sanityCheck() throws RepositoryException { sessionContext.getSessionState().checkAlive(); } /** * Disposes this <code>ItemManager</code> and frees resources. */ void dispose() { synchronized (itemCache) { itemCache.clear(); } shareableNodesCache.clear(); } NodeDefinitionImpl getDefinition(NodeState state) throws RepositoryException { if (state.getId().equals(sessionContext.getRootNodeId())) { // special handling required for root node return rootNodeDef; } NodeId parentId = state.getParentId(); if (parentId == null) { // removed state has parentId set to null // get from overlayed state ItemState overlaid = state.getOverlayedState(); if (overlaid != null) { parentId = overlaid.getParentId(); } else { throw new InvalidItemStateException( "Could not find parent of node " + state.getNodeId()); } } NodeState parentState = null; try { // access the parent state circumventing permission check, since // read permission on the parent isn't required in order to retrieve // a node's definition. see also JCR-2418 ItemData parentData = getItemData(parentId, null, false); parentState = (NodeState) parentData.getState(); if (state.getParentId() == null) { // indicates state has been removed, must use // overlayed state of parent, otherwise child node entry // cannot be found. unless the parentState is new, which // means it was recreated in place of a removed node // that used to be the actual parent if (parentState.getStatus() == ItemState.STATUS_NEW) { // force getting parent from attic parentState = null; } else { parentState = (NodeState) parentState.getOverlayedState(); } } } catch (ItemNotFoundException e) { // parent probably removed, get it from attic. see below } if (parentState == null) { try { // use overlayed state if available parentState = (NodeState) sism.getAttic().getItemState( parentId).getOverlayedState(); } catch (ItemStateException ex) { throw new RepositoryException(ex); } } // get child node entry ChildNodeEntry cne = parentState.getChildNodeEntry(state.getNodeId()); if (cne == null) { throw new InvalidItemStateException( "Could not find child " + state.getNodeId() + " of node " + parentState.getNodeId()); } NodeTypeRegistry ntReg = sessionContext.getNodeTypeRegistry(); try { EffectiveNodeType ent = ntReg.getEffectiveNodeType( parentState.getNodeTypeName(), parentState.getMixinTypeNames()); QNodeDefinition def; try { def = ent.getApplicableChildNodeDef( cne.getName(), state.getNodeTypeName(), ntReg); } catch (ConstraintViolationException e) { // fallback to child node definition of a nt:unstructured ent = ntReg.getEffectiveNodeType(NameConstants.NT_UNSTRUCTURED); def = ent.getApplicableChildNodeDef( cne.getName(), state.getNodeTypeName(), ntReg); log.warn("Fallback to nt:unstructured due to unknown child " + "node definition for type '" + state.getNodeTypeName() + "'"); } return sessionContext.getNodeTypeManager().getNodeDefinition(def); } catch (NodeTypeConflictException e) { throw new RepositoryException(e); } } PropertyDefinitionImpl getDefinition(PropertyState state) throws RepositoryException { // this is a bit ugly // there might be cases where otherwise protected items turn into // non-protected items because a mixin has been removed from the parent // node state. // see also: JCR-2408 if (state.getStatus() == ItemState.STATUS_EXISTING_REMOVED && state.getName().equals(NameConstants.JCR_UUID)) { NodeTypeRegistry ntReg = sessionContext.getNodeTypeRegistry(); QPropertyDefinition def = ntReg.getEffectiveNodeType( NameConstants.MIX_REFERENCEABLE).getApplicablePropertyDef( state.getName(), state.getType()); return sessionContext.getNodeTypeManager().getPropertyDefinition(def); } try { // retrieve parent in 2 steps in order to avoid the check for // read permissions on the parent which isn't required in order // to read the property's definition. see also JCR-2418. ItemData parentData = getItemData(state.getParentId(), null, false); NodeImpl parent = (NodeImpl) createItemInstance(parentData); return parent.getApplicablePropertyDefinition( state.getName(), state.getType(), state.isMultiValued(), true); } catch (ItemNotFoundException e) { // parent probably removed, get it from attic } try { NodeState parent = (NodeState) sism.getAttic().getItemState( state.getParentId()).getOverlayedState(); NodeTypeRegistry ntReg = sessionContext.getNodeTypeRegistry(); EffectiveNodeType ent = ntReg.getEffectiveNodeType( parent.getNodeTypeName(), parent.getMixinTypeNames()); QPropertyDefinition def; try { def = ent.getApplicablePropertyDef( state.getName(), state.getType(), state.isMultiValued()); } catch (ConstraintViolationException e) { ent = ntReg.getEffectiveNodeType(NameConstants.NT_UNSTRUCTURED); def = ent.getApplicablePropertyDef(state.getName(), state.getType(), state.isMultiValued()); log.warn("Fallback to nt:unstructured due to unknown property " + "definition for '" + state.getName() + "'"); } return sessionContext.getNodeTypeManager().getPropertyDefinition(def); } catch (ItemStateException e) { throw new RepositoryException(e); } catch (NodeTypeConflictException e) { throw new RepositoryException(e); } } /** * Common implementation for all variants of item/node/propertyExists * with both itemId or path param. * * @param itemId The id of the item to test. * @param path Path of the item to check if known or <code>null</code>. In * the latter case the test for access permission is executed using the * itemId. * @return true if the item with the given <code>itemId</code> exists AND * can be read by this session. */ private boolean itemExists(ItemId itemId, Path path) { try { sanityCheck(); // shortcut: check if state exists for the given item if (!sism.hasItemState(itemId)) { return false; } getItemData(itemId, path, true); return true; } catch (RepositoryException re) { return false; } } /** * Common implementation for all variants of getItem/getNode/getProperty * with both itemId or path parameter. * * @param itemId * @param path Path of the item to retrieve or <code>null</code>. In * the latter case the test for access permission is executed using the * itemId. * @param permissionCheck * @return The item identified by the given <code>itemId</code>. * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ private ItemImpl getItem(ItemId itemId, Path path, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(itemId, path, permissionCheck); return createItemInstance(data); } /** * Retrieves the data of the item with given <code>id</code>. If the * specified item doesn't exist an <code>ItemNotFoundException</code> will * be thrown. * If the item exists but the current session is not granted read access an * <code>AccessDeniedException</code> will be thrown. * * @param itemId id of item to be retrieved * @return state state of said item * @throws ItemNotFoundException if no item with given <code>id</code> exists * @throws AccessDeniedException if the current session is not allowed to * read the said item * @throws RepositoryException if another error occurs */ private ItemData getItemData(ItemId itemId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getItemData(itemId, null, true); } /** * Retrieves the data of the item with given <code>id</code>. If the * specified item doesn't exist an <code>ItemNotFoundException</code> will * be thrown. * If <code>permissionCheck</code> is <code>true</code> and the item exists * but the current session is not granted read access an * <code>AccessDeniedException</code> will be thrown. * * @param itemId id of item to be retrieved * @param path The path of the item to retrieve the data for or * <code>null</code>. In the latter case the id (instead of the path) is * used to test if READ permission is granted. * @param permissionCheck * @return the ItemData for the item identified by the given itemId. * @throws ItemNotFoundException if no item with given <code>id</code> exists * @throws AccessDeniedException if the current session is not allowed to * read the said item * @throws RepositoryException if another error occurs */ ItemData getItemData(ItemId itemId, Path path, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { ItemData data = retrieveItem(itemId); if (data == null) { // not yet in cache, need to create instance: // - retrieve item state // - create instance of item data // NOTE: permission check & caching within createItemData ItemState state; try { state = sism.getItemState(itemId); } catch (NoSuchItemStateException nsise) { throw new ItemNotFoundException(itemId.toString()); } catch (ItemStateException ise) { String msg = "failed to retrieve item state of item " + itemId; log.error(msg, ise); throw new RepositoryException(msg, ise); } // create item data including: perm check and caching. data = createItemData(state, path, permissionCheck); } else { // already cached: if 'permissionCheck' is true, make sure read // permission is granted. if (permissionCheck && !canRead(data, path)) { // item exists but read-perm has been revoked in the mean time. // -> remove from cache evictItems(itemId); throw new AccessDeniedException("cannot read item " + data.getId()); } } return data; } /** * @param data * @param path Path to be used for the permission check or <code>null</code> * in which case the itemId present with the specified <code>data</code> is used. * @return true if the item with the given <code>data</code> can be read; * <code>false</code> otherwise. * @throws AccessDeniedException * @throws RepositoryException */ private boolean canRead(ItemData data, Path path) throws AccessDeniedException, RepositoryException { // JCR-1601: cached item may just have been invalidated ItemState state = data.getState(); if (state == null) { throw new InvalidItemStateException(data.getId() + ": the item does not exist anymore"); } if (state.getStatus() == ItemState.STATUS_NEW) { if (!data.getDefinition().isProtected()) { /* NEW items can always be read as long they have been added through the API and NOT by the system (i.e. protected items). */ return true; } else { /* NEW protected (system) item: need use the path to evaluate the effective permissions. */ return (path == null) ? sessionContext.getAccessManager().isGranted(data.getId(), AccessManager.READ) : sessionContext.getAccessManager().isGranted(path, Permission.READ); } } else { /* item is not NEW -> save to call acMgr.canRead(Path,ItemId) */ return sessionContext.getAccessManager().canRead(path, data.getId()); } } /** * @param parent The item data of the parent node. * @param childId * @return true if the item with the given <code>childId</code> can be read; * <code>false</code> otherwise. * @throws RepositoryException */ private boolean canRead(ItemData parent, ItemId childId) throws RepositoryException { if (parent.getStatus() == ItemState.STATUS_EXISTING) { // child item is for sure not NEW (because then the parent was modified). // safe to use AccessManager#canRead(Path, ItemId). return sessionContext.getAccessManager().canRead(null, childId); } else { // child could be NEW -> don't use AccessManager#canRead(Path, ItemId) return sessionContext.getAccessManager().isGranted(childId, AccessManager.READ); } } //--------------------------------------------------< item access methods > /** * Checks whether an item exists at the specified path. * * @deprecated As of JSR 283, a <code>Path</code> doesn't anymore uniquely * identify an <code>Item</code>, therefore {@link #nodeExists(Path)} and * {@link #propertyExists(Path)} should be used instead. * * @param path path to the item to be checked * @return true if the specified item exists */ public boolean itemExists(Path path) { try { sanityCheck(); ItemId id = hierMgr.resolvePath(path); return (id != null) && itemExists(id, path); } catch (RepositoryException re) { return false; } } /** * Checks whether a node exists at the specified path. * * @param path path to the node to be checked * @return true if a node exists at the specified path */ public boolean nodeExists(Path path) { try { sanityCheck(); NodeId id = hierMgr.resolveNodePath(path); return (id != null) && itemExists(id, path); } catch (RepositoryException re) { return false; } } /** * Checks whether a property exists at the specified path. * * @param path path to the property to be checked * @return true if a property exists at the specified path */ public boolean propertyExists(Path path) { try { sanityCheck(); PropertyId id = hierMgr.resolvePropertyPath(path); return (id != null) && itemExists(id, path); } catch (RepositoryException re) { return false; } } /** * Checks if the item with the given id exists. * * @param id id of the item to be checked * @return true if the specified item exists */ public boolean itemExists(ItemId id) { return itemExists(id, null); } /** * @return * @throws RepositoryException */ NodeImpl getRootNode() throws RepositoryException { return (NodeImpl) getItem(sessionContext.getRootNodeId()); } /** * Returns the node at the specified absolute path in the workspace. * If no such node exists, then it returns the property at the specified path. * If no such property exists a <code>PathNotFoundException</code> is thrown. * * @deprecated As of JSR 283, a <code>Path</code> doesn't anymore uniquely * identify an <code>Item</code>, therefore {@link #getNode(Path)} and * {@link #getProperty(Path)} should be used instead. * @param path * @return * @throws PathNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ public ItemImpl getItem(Path path) throws PathNotFoundException, AccessDeniedException, RepositoryException { ItemId id = hierMgr.resolvePath(path); if (id == null) { throw new PathNotFoundException(safeGetJCRPath(path)); } try { ItemImpl item = getItem(id, path, true); // Test, if this item is a shareable node. if (item.isNode() && ((NodeImpl) item).isShareable()) { return getNode(path); } return item; } catch (ItemNotFoundException infe) { throw new PathNotFoundException(safeGetJCRPath(path)); } } /** * @param path * @return * @throws PathNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ public NodeImpl getNode(Path path) throws PathNotFoundException, AccessDeniedException, RepositoryException { NodeId id = hierMgr.resolveNodePath(path); if (id == null) { throw new PathNotFoundException(safeGetJCRPath(path)); } NodeId parentId = null; if (!path.denotesRoot()) { parentId = hierMgr.resolveNodePath(path.getAncestor(1)); } try { if (parentId == null) { return (NodeImpl) getItem(id, path, true); } // if the node is shareable, it now returns the node with the right // parent return getNode(id, parentId); } catch (ItemNotFoundException infe) { throw new PathNotFoundException(safeGetJCRPath(path)); } } /** * @param path * @return * @throws PathNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ public PropertyImpl getProperty(Path path) throws PathNotFoundException, AccessDeniedException, RepositoryException { PropertyId id = hierMgr.resolvePropertyPath(path); if (id == null) { throw new PathNotFoundException(safeGetJCRPath(path)); } try { return (PropertyImpl) getItem(id, path, true); } catch (ItemNotFoundException infe) { throw new PathNotFoundException(safeGetJCRPath(path)); } } /** * @param id * @return * @throws RepositoryException */ public synchronized ItemImpl getItem(ItemId id) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getItem(id, null, true); } /** * @param id * @return * @throws RepositoryException */ synchronized ItemImpl getItem(ItemId id, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getItem(id, null, permissionCheck); } /** * Returns a node with a given id and parent id. If the indicated node is * shareable, there might be multiple nodes associated with the same id, * but there'is only one node with the given parent id. * * @param id node id * @param parentId parent node id * @return node * @throws RepositoryException if an error occurs */ public synchronized NodeImpl getNode(NodeId id, NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { return getNode(id, parentId, true); } /** * Returns a node with a given id and parent id. If the indicated node is * shareable, there might be multiple nodes associated with the same id, * but there'is only one node with the given parent id. * * @param id node id * @param parentId parent node id * @param permissionCheck Flag indicating if read permission must be check * upon retrieving the node. * @return node * @throws RepositoryException if an error occurs */ synchronized NodeImpl getNode(NodeId id, NodeId parentId, boolean permissionCheck) throws ItemNotFoundException, AccessDeniedException, RepositoryException { if (parentId == null) { return (NodeImpl) getItem(id); } AbstractNodeData data = retrieveItem(id, parentId); if (data == null) { data = (AbstractNodeData) getItemData(id, null, permissionCheck); } if (!data.getParentId().equals(parentId)) { // verify that parent actually appears in the shared set if (!data.getNodeState().containsShare(parentId)) { String msg = "Node with id '" + id + "' does not have shared parent with id: " + parentId; throw new ItemNotFoundException(msg); } // TODO: ev. need to check if read perm. is granted. data = new NodeDataRef(data, parentId); cacheItem(data); } return createNodeInstance(data); } /** * Create an item instance from an item state. This method creates a * new <code>ItemData</code> instance without looking at the cache nor * testing if the item can be read and returns a new item instance. * * @param state item state * @return item instance * @throws RepositoryException if an error occurs */ synchronized ItemImpl createItemInstance(ItemState state) throws RepositoryException { ItemData data = createItemData(state, null, false); return createItemInstance(data); } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized boolean hasChildNodes(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child nodes of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } NodeState state = (NodeState) data.getState(); for (ChildNodeEntry entry : state.getChildNodeEntries()) { // make sure any of the properties can be read. if (canRead(data, entry.getId())) { return true; } } return false; } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized NodeIterator getChildNodes(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child nodes of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } ArrayList<ItemId> childIds = new ArrayList<ItemId>(); Iterator<ChildNodeEntry> iter = ((NodeState) data.getState()).getChildNodeEntries().iterator(); while (iter.hasNext()) { ChildNodeEntry entry = iter.next(); // delay check for read-access until item is being built // thus avoid duplicate check childIds.add(entry.getId()); } return new LazyItemIterator(sessionContext, childIds, parentId); } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized boolean hasChildProperties(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child properties of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } Iterator<Name> iter = ((NodeState) data.getState()).getPropertyNames().iterator(); while (iter.hasNext()) { Name propName = iter.next(); // make sure any of the properties can be read. if (canRead(data, new PropertyId(parentId, propName))) { return true; } } return false; } /** * @param parentId * @return * @throws ItemNotFoundException * @throws AccessDeniedException * @throws RepositoryException */ synchronized PropertyIterator getChildProperties(NodeId parentId) throws ItemNotFoundException, AccessDeniedException, RepositoryException { sanityCheck(); ItemData data = getItemData(parentId); if (!data.isNode()) { String msg = "can't list child properties of property " + parentId; log.debug(msg); throw new RepositoryException(msg); } ArrayList<PropertyId> childIds = new ArrayList<PropertyId>(); Iterator<Name> iter = ((NodeState) data.getState()).getPropertyNames().iterator(); while (iter.hasNext()) { Name propName = iter.next(); PropertyId id = new PropertyId(parentId, propName); // delay check for read-access until item is being built // thus avoid duplicate check childIds.add(id); } return new LazyItemIterator(sessionContext, childIds); } //-------------------------------------------------< item factory methods > /** * Builds the <code>ItemData</code> for the specified <code>state</code>. * If <code>permissionCheck</code> is <code>true</code>, the access manager * is used to determine if reading that item would be granted. If this is * not the case an <code>AccessDeniedException</code> is thrown. * Before returning the created <code>ItemData</code> it is put into the * cache. In order to benefit from the cache * {@link #getItemData(ItemId, Path, boolean)} should be called. * * @param state * @return * @throws RepositoryException */ private ItemData createItemData(ItemState state, Path path, boolean permissionCheck) throws RepositoryException { ItemData data; if (state.isNode()) { NodeState nodeState = (NodeState) state; data = new NodeData(nodeState, this); } else { PropertyState propertyState = (PropertyState) state; data = new PropertyData(propertyState, this); } // make sure read-perm. is granted before returning the data. if (permissionCheck && !canRead(data, path)) { throw new AccessDeniedException("cannot read item " + state.getId()); } // before returning the data: put them into the cache. cacheItem(data); return data; } private ItemImpl createItemInstance(ItemData data) { if (data.isNode()) { return createNodeInstance((AbstractNodeData) data); } else { return createPropertyInstance((PropertyData) data); } } private NodeImpl createNodeInstance(AbstractNodeData data) { // check special nodes final NodeState state = data.getNodeState(); if (state.getNodeTypeName().equals(NameConstants.NT_VERSION)) { return new VersionImpl(this, sessionContext, data); } else if (state.getNodeTypeName().equals(NameConstants.NT_VERSIONHISTORY)) { return new VersionHistoryImpl(this, sessionContext, data); } else { // create node object return new NodeImpl(this, sessionContext, data); } } private PropertyImpl createPropertyInstance(PropertyData data) { // check special nodes return new PropertyImpl(this, sessionContext, data); } //---------------------------------------------------< item cache methods > /** * Returns an item reference from the cache. * * @param id id of the item that should be retrieved. * @return the item reference stored in the corresponding cache entry * or <code>null</code> if there's no corresponding cache entry. */ private ItemData retrieveItem(ItemId id) { synchronized (itemCache) { ItemData data = itemCache.get(id); if (data == null && id.denotesNode()) { data = shareableNodesCache.retrieveFirst((NodeId) id); } return data; } } /** * Return a node from the cache. * * @param id id of the node that should be retrieved. * @param parentId parent id of the node that should be retrieved * @return reference stored in the corresponding cache entry * or <code>null</code> if there's no corresponding cache entry. */ private AbstractNodeData retrieveItem(NodeId id, NodeId parentId) { synchronized (itemCache) { AbstractNodeData data = shareableNodesCache.retrieve(id, parentId); if (data == null) { data = (AbstractNodeData) itemCache.get(id); } return data; } } /** * Puts the reference of an item in the cache with * the item's path as the key. * * @param data the item data to cache */ private void cacheItem(ItemData data) { synchronized (itemCache) { if (data.isNode()) { AbstractNodeData nd = (AbstractNodeData) data; if (nd.getPrimaryParentId() != null) { shareableNodesCache.cache(nd); return; } } ItemId id = data.getId(); if (itemCache.containsKey(id)) { log.warn("overwriting cached item " + id); } if (log.isDebugEnabled()) { log.debug("caching item " + id); } itemCache.put(id, data); } } /** * Removes all cache entries with the given item id. If the item is * shareable, there might be more than one cache entry for this item. * * @param id id of the items to remove from the cache */ private void evictItems(ItemId id) { if (log.isDebugEnabled()) { log.debug("removing items " + id + " from cache"); } synchronized (itemCache) { itemCache.remove(id); if (id.denotesNode()) { shareableNodesCache.evictAll((NodeId) id); } } } /** * Removes a cache entry for a specific item. * * @param data The item data to remove from the cache */ private void evictItem(ItemData data) { if (log.isDebugEnabled()) { log.debug("removing item " + data.getId() + " from cache"); } synchronized (itemCache) { if (data.isNode()) { shareableNodesCache.evict((AbstractNodeData) data); } ItemData cached = itemCache.get(data.getId()); if (cached == data) { itemCache.remove(data.getId()); } } } //-------------------------------------------------< misc. helper methods > /** * Failsafe conversion of internal <code>Path</code> to JCR path for use in * error messages etc. * * @param path path to convert * @return JCR path */ String safeGetJCRPath(Path path) { try { return session.getJCRPath(path); } catch (NamespaceException e) { log.error("failed to convert " + path.toString() + " to JCR path."); // return string representation of internal path as a fallback return path.toString(); } } /** * Failsafe translation of internal <code>ItemId</code> to JCR path for use in * error messages etc. * * @param id path to convert * @return JCR path */ String safeGetJCRPath(ItemId id) { try { return safeGetJCRPath(hierMgr.getPath(id)); } catch (RepositoryException re) { log.error(id + ": failed to determine path to"); // return string representation if id as a fallback return id.toString(); } } //------------------------------------------------< ItemLifeCycleListener > /** * {@inheritDoc} */ public void itemInvalidated(ItemId id, ItemData data) { if (log.isDebugEnabled()) { log.debug("invalidated item " + id); } evictItem(data); } /** * {@inheritDoc} */ public void itemDestroyed(ItemId id, ItemData data) { if (log.isDebugEnabled()) { log.debug("destroyed item " + id); } synchronized (itemCache) { // remove instance from cache evictItems(id); } } //--------------------------------------------------------------< Object > /** * {@inheritDoc} */ public synchronized String toString() { StringBuilder builder = new StringBuilder(); builder.append("ItemManager (" + super.toString() + ")\n"); builder.append("Items in cache:\n"); synchronized (itemCache) { for (ItemId id : itemCache.keySet()) { ItemData item = itemCache.get(id); if (item.isNode()) { builder.append("Node: "); } else { builder.append("Property: "); } if (item.getState().isTransient()) { builder.append("transient "); } else { builder.append(" "); } builder.append(id + "\t" + safeGetJCRPath(id) + " (" + item + ")\n"); } } return builder.toString(); } //----------------------------------------------------< ItemStateListener > /** * {@inheritDoc} */ public void stateCreated(ItemState created) { ItemData data = retrieveItem(created.getId()); if (data != null) { data.setStatus(ItemImpl.STATUS_NORMAL); } } /** * {@inheritDoc} */ public void stateModified(ItemState modified) { ItemData data = retrieveItem(modified.getId()); if (data != null && data.getState() == modified) { data.setStatus(ItemImpl.STATUS_MODIFIED); /* if (modified.isNode()) { NodeState state = (NodeState) modified; if (state.isShareable()) { //evictItem(modified.getId()); NodeData nodeData = (NodeData) data; NodeData shareSibling = new NodeData(nodeData, state.getParentId()); shareableNodesCache.cache(shareSibling); } } */ } } /** * {@inheritDoc} */ public void stateDestroyed(ItemState destroyed) { ItemData data = retrieveItem(destroyed.getId()); if (data != null && data.getState() == destroyed) { itemDestroyed(destroyed.getId(), data); data.setStatus(ItemImpl.STATUS_DESTROYED); } } /** * {@inheritDoc} */ public void stateDiscarded(ItemState discarded) { ItemData data = retrieveItem(discarded.getId()); if (data != null && data.getState() == discarded) { if (discarded.isTransient()) { switch (discarded.getStatus()) { /** * persistent item that has been transiently removed */ case ItemState.STATUS_EXISTING_REMOVED: case ItemState.STATUS_EXISTING_MODIFIED: ItemState persistentState = discarded.getOverlayedState(); // the state is a transient wrapper for the underlying // persistent state, therefore restore the persistent state // and resurrect this item instance if necessary SessionItemStateManager stateMgr = sessionContext.getItemStateManager(); stateMgr.disconnectTransientItemState(discarded); data.setState(persistentState); return; /** * persistent item that has been transiently modified or * removed and the underlying persistent state has been * externally destroyed since the transient * modification/removal. */ case ItemState.STATUS_STALE_DESTROYED: /** * first notify the listeners that this instance has been * permanently invalidated */ itemDestroyed(discarded.getId(), data); // now set state of this instance to 'destroyed' data.setStatus(ItemImpl.STATUS_DESTROYED); data.setState(null); return; /** * new item that has been transiently added */ case ItemState.STATUS_NEW: /** * first notify the listeners that this instance has been * permanently invalidated */ itemDestroyed(discarded.getId(), data); // now set state of this instance to 'destroyed' // finally dispose state data.setStatus(ItemImpl.STATUS_DESTROYED); data.setState(null); return; } } /** * first notify the listeners that this instance has been * invalidated */ itemInvalidated(discarded.getId(), data); // now render this instance 'invalid' data.setStatus(ItemImpl.STATUS_INVALIDATED); } } /** * Cache of shareable nodes. For performance reasons, methods are not * synchronized and thread-safety must be guaranteed by caller. */ static class ShareableNodesCache { /** * This cache is based on a reference map, that maps an item id to a map, * which again maps a (hard-ref) parent id to a (weak-ref) shareable node. */ private final ReferenceMap cache; /** * Create a new instance of this class. */ public ShareableNodesCache() { cache = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.HARD); } /** * Clear cache. * * @see ReferenceMap#clear() */ public void clear() { cache.clear(); } /** * Return the first available node that maps to the given id. * * @param id node id * @return node or <code>null</code> */ public AbstractNodeData retrieveFirst(NodeId id) { ReferenceMap map = (ReferenceMap) cache.get(id); if (map != null) { Iterator<AbstractNodeData> iter = map.values().iterator(); try { while (iter.hasNext()) { AbstractNodeData data = iter.next(); if (data != null) { return data; } } } finally { iter = null; } } return null; } /** * Return the node with the given id and parent id. * * @param id node id * @param parentId parent id * @return node or <code>null</code> */ public AbstractNodeData retrieve(NodeId id, NodeId parentId) { ReferenceMap map = (ReferenceMap) cache.get(id); if (map != null) { return (AbstractNodeData) map.get(parentId); } return null; } /** * Cache some node. * * @param data data to cache */ public void cache(AbstractNodeData data) { NodeId id = data.getNodeState().getNodeId(); ReferenceMap map = (ReferenceMap) cache.get(id); if (map == null) { map = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); cache.put(id, map); } Object old = map.put(data.getPrimaryParentId(), data); if (old != null) { log.warn("overwriting cached item: " + old); } } /** * Evict some node from the cache. * * @param data data to evict */ public void evict(AbstractNodeData data) { ReferenceMap map = (ReferenceMap) cache.get(data.getId()); if (map != null) { map.remove(data.getPrimaryParentId()); } } /** * Evict all nodes with a given node id from the cache. * * @param id node id to evict */ public synchronized void evictAll(NodeId id) { cache.remove(id); } } }
JCR-3382 let getNode do a permission check when the item is in the item manager cache: applying patch by Frank van Lankvelt. git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1464059 13f79535-47bb-0310-9956-ffa450edef68
jackrabbit-core/src/main/java/org/apache/jackrabbit/core/ItemManager.java
JCR-3382 let getNode do a permission check when the item is in the item manager cache: applying patch by Frank van Lankvelt.
<ide><path>ackrabbit-core/src/main/java/org/apache/jackrabbit/core/ItemManager.java <ide> AbstractNodeData data = retrieveItem(id, parentId); <ide> if (data == null) { <ide> data = (AbstractNodeData) getItemData(id, null, permissionCheck); <add> } else if (permissionCheck && !canRead(data, id)) { <add> // item exists but read-perm has been revoked in the mean time. <add> // -> remove from cache <add> evictItems(id); <add> throw new AccessDeniedException("cannot read item " + data.getId()); <ide> } <ide> if (!data.getParentId().equals(parentId)) { <ide> // verify that parent actually appears in the shared set
Java
apache-2.0
6f4c16fa2c8983fd9a598f9bb447be90d3b16e58
0
xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services
package org.sagebionetworks.client; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.json.JSONObject; import org.sagebionetworks.client.exceptions.SynapseClientException; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.repo.model.EntityId; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.PaginatedResults; import org.sagebionetworks.repo.model.TrashedEntity; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.auth.NewIntegrationTestUser; import org.sagebionetworks.repo.model.auth.Session; import org.sagebionetworks.repo.model.daemon.BackupRestoreStatus; import org.sagebionetworks.repo.model.daemon.RestoreSubmission; import org.sagebionetworks.repo.model.message.ChangeMessages; import org.sagebionetworks.repo.model.message.FireMessagesResult; import org.sagebionetworks.repo.model.message.PublishResults; import org.sagebionetworks.repo.model.IdList; import org.sagebionetworks.repo.model.migration.MigrationType; import org.sagebionetworks.repo.model.migration.MigrationTypeCount; import org.sagebionetworks.repo.model.migration.MigrationTypeCounts; import org.sagebionetworks.repo.model.migration.MigrationTypeList; import org.sagebionetworks.repo.model.migration.RowMetadataResult; import org.sagebionetworks.repo.model.status.StackStatus; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl; /** * Java Client API for Synapse Administrative REST APIs */ public class SynapseAdminClientImpl extends SynapseClientImpl implements SynapseAdminClient { private static final String DAEMON = ADMIN + "/daemon"; private static final String ADMIN_TRASHCAN_VIEW = ADMIN + "/trashcan/view"; private static final String ADMIN_TRASHCAN_PURGE = ADMIN + "/trashcan/purge"; private static final String ADMIN_CHANGE_MESSAGES = ADMIN + "/messages"; private static final String ADMIN_FIRE_MESSAGES = ADMIN + "/messages/refire"; private static final String ADMIN_GET_CURRENT_CHANGE_NUM = ADMIN + "/messages/currentnumber"; private static final String ADMIN_PUBLISH_MESSAGES = ADMIN_CHANGE_MESSAGES + "/rebroadcast"; private static final String ADMIN_DOI_CLEAR = ADMIN + "/doi/clear"; private static final String MIGRATION = "/migration"; private static final String MIGRATION_COUNTS = MIGRATION + "/counts"; private static final String MIGRATION_ROWS = MIGRATION + "/rows"; private static final String MIGRATION_DELTA = MIGRATION + "/delta"; private static final String MIGRATION_BACKUP = MIGRATION + "/backup"; private static final String MIGRATION_RESTORE = MIGRATION + "/restore"; private static final String MIGRATION_DELETE = MIGRATION + "/delete"; private static final String MIGRATION_STATUS = MIGRATION + "/status"; private static final String MIGRATION_PRIMARY = MIGRATION + "/primarytypes"; private static final String ADMIN_DYNAMO_CLEAR = ADMIN + "/dynamo/clear"; private static final String ADMIN_MIGRATE_WIKIS_TO_V2 = ADMIN + "/migrateWiki"; private static final String ADMIN_USER = ADMIN + "/user"; public SynapseAdminClientImpl() { super(); } public SynapseAdminClientImpl(HttpClientProvider clientProvider, DataUploader dataUploader) { super(new SharedClientConnection(clientProvider), dataUploader); } /** * @param updated * @return status * @throws JSONObjectAdapterException * @throws SynapseException */ public StackStatus updateCurrentStackStatus(StackStatus updated) throws JSONObjectAdapterException, SynapseException { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(updated); jsonObject = getSharedClientConnection().putJson(repoEndpoint, STACK_STATUS, jsonObject.toString(), getUserAgent()); return EntityFactory.createEntityFromJSONObject(jsonObject, StackStatus.class); } @Override public BackupRestoreStatus getDaemonStatus(String daemonId) throws SynapseException, JSONObjectAdapterException { return getJSONEntity(DAEMON + "/" + daemonId, BackupRestoreStatus.class); } @Override public PaginatedResults<TrashedEntity> viewTrash(long offset, long limit) throws SynapseException { String url = ADMIN_TRASHCAN_VIEW + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<TrashedEntity> results = new PaginatedResults<TrashedEntity>(TrashedEntity.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void purgeTrash() throws SynapseException { getSharedClientConnection().putJson(repoEndpoint, ADMIN_TRASHCAN_PURGE, null, getUserAgent()); } @Override public ChangeMessages listMessages(Long startChangeNumber, ObjectType type, Long limit) throws SynapseException, JSONObjectAdapterException{ // Build up the URL String url = buildListMessagesURL(startChangeNumber, type, limit); return getJSONEntity(url, ChangeMessages.class); } // New migration client methods public MigrationTypeList getPrimaryTypes() throws SynapseException, JSONObjectAdapterException { String uri = MIGRATION_PRIMARY; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MigrationTypeList mtl = new MigrationTypeList(); mtl.initializeFromJSONObject(adapter); return mtl; } public MigrationTypeCounts getTypeCounts() throws SynapseException, JSONObjectAdapterException { String uri = MIGRATION_COUNTS; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MigrationTypeCounts mtc = new MigrationTypeCounts(); mtc.initializeFromJSONObject(adapter); return mtc; } public RowMetadataResult getRowMetadata(MigrationType migrationType, Long limit, Long offset) throws SynapseException, JSONObjectAdapterException { String uri = MIGRATION_ROWS + "?type=" + migrationType.name() + "&limit=" + limit + "&offset=" + offset; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); RowMetadataResult results = new RowMetadataResult(); results.initializeFromJSONObject(adapter); return results; } public RowMetadataResult getRowMetadataDelta(MigrationType migrationType, IdList ids) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_DELTA + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(ids); JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); RowMetadataResult result = new RowMetadataResult(); result.initializeFromJSONObject(adapter); return result; } public BackupRestoreStatus startBackup(MigrationType migrationType, IdList ids) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_BACKUP + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(ids); JSONObject jsonObj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonStr, getUserAgent(), null); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); BackupRestoreStatus brStatus = new BackupRestoreStatus(); brStatus.initializeFromJSONObject(adapter); return brStatus; } public BackupRestoreStatus startRestore(MigrationType migrationType, RestoreSubmission req) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_RESTORE + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(req); JSONObject jsonObj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonStr, getUserAgent(), null); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); BackupRestoreStatus brStatus = new BackupRestoreStatus(); brStatus.initializeFromJSONObject(adapter); return brStatus; } public BackupRestoreStatus getStatus(String daemonId) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_STATUS + "?daemonId=" + daemonId; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); BackupRestoreStatus brStatus = new BackupRestoreStatus(); brStatus.initializeFromJSONObject(adapter); return brStatus; } public MigrationTypeCount deleteMigratableObject(MigrationType migrationType, IdList ids) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_DELETE + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(ids); JSONObject jsonObj = getSharedClientConnection().putJson(repoEndpoint, uri, jsonStr, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MigrationTypeCount mtc = new MigrationTypeCount(); mtc.initializeFromJSONObject(adapter); return mtc; } @Override public FireMessagesResult fireChangeMessages(Long startChangeNumber, Long limit) throws SynapseException, JSONObjectAdapterException { if(startChangeNumber == null) throw new IllegalArgumentException("startChangeNumber cannot be null"); String uri = ADMIN_FIRE_MESSAGES + "?startChangeNumber=" + startChangeNumber; if (limit != null){ uri = uri + "&limit=" + limit; } JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); FireMessagesResult res = new FireMessagesResult(); res.initializeFromJSONObject(adapter); return res; } /** * Return current change message number */ @Override public FireMessagesResult getCurrentChangeNumber() throws SynapseException, JSONObjectAdapterException { String uri = ADMIN_GET_CURRENT_CHANGE_NUM; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); FireMessagesResult res = new FireMessagesResult(); res.initializeFromJSONObject(adapter); return res; } /** * Build up the URL for the list change message call. * @param startChangeNumber * @param type * @param limit * @return */ static String buildListMessagesURL(Long startChangeNumber, ObjectType type, Long limit){ if(startChangeNumber == null) throw new IllegalArgumentException("startChangeNumber cannot be null"); StringBuilder builder = new StringBuilder(); builder.append(ADMIN_CHANGE_MESSAGES); builder.append("?"); builder.append("startChangeNumber=").append(startChangeNumber); if(type != null){ builder.append("&type=").append(type.name()); } if(limit != null){ builder.append("&limit=").append(limit); } return builder.toString(); } @Override public PublishResults publishChangeMessages(String queueName, Long startChangeNumber, ObjectType type, Long limit) throws SynapseException, JSONObjectAdapterException{ // Build up the URL String url = buildPublishMessagesURL(queueName, startChangeNumber, type, limit); JSONObject json = getSharedClientConnection().postJson(repoEndpoint, url, null, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(json, PublishResults.class); } /** * Build up the URL for publishing messages. * @param startChangeNumber * @param type * @param limit * @return */ static String buildPublishMessagesURL(String queueName, Long startChangeNumber, ObjectType type, Long limit){ if(queueName == null) throw new IllegalArgumentException("queueName cannot be null"); if(startChangeNumber == null) throw new IllegalArgumentException("startChangeNumber cannot be null"); StringBuilder builder = new StringBuilder(); builder.append(ADMIN_PUBLISH_MESSAGES); builder.append("?"); builder.append("queueName=").append(queueName); builder.append("&startChangeNumber=").append(startChangeNumber); if(type != null){ builder.append("&type=").append(type.name()); } if(limit != null){ builder.append("&limit=").append(limit); } return builder.toString(); } @Override public void clearDoi() throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, ADMIN_DOI_CLEAR, getUserAgent()); } @Override public void clearDynamoTable(String tableName, String hashKeyName, String rangeKeyName) throws SynapseException { if (tableName == null || tableName.isEmpty()) { throw new IllegalArgumentException("Table name cannot be null or empty."); } if (hashKeyName == null || hashKeyName.isEmpty()) { throw new IllegalArgumentException("Hash key name cannot be null or empty."); } if (rangeKeyName == null || rangeKeyName.isEmpty()) { throw new IllegalArgumentException("Range key name cannot be null or empty."); } try { String uri = ADMIN_DYNAMO_CLEAR + "/" + URLEncoder.encode(tableName, "UTF-8"); uri += "?hashKeyName=" + URLEncoder.encode(hashKeyName, "UTF-8"); uri += "&rangeKeyName=" + URLEncoder.encode(rangeKeyName, "UTF-8"); getSharedClientConnection().deleteUri(repoEndpoint, uri, getUserAgent()); } catch (UnsupportedEncodingException e) { throw new SynapseClientException(e); } } @Override public long createUser(NewIntegrationTestUser user) throws SynapseException, JSONObjectAdapterException { if(user.getEmail() == null) throw new IllegalArgumentException("New users must have an email"); if(user.getUsername() == null) throw new IllegalArgumentException("New users must have a username"); JSONObject json = getSharedClientConnection().postJson(repoEndpoint, ADMIN_USER, EntityFactory.createJSONStringForEntity(user), getUserAgent(), null); EntityId id = EntityFactory.createEntityFromJSONObject(json, EntityId.class); return Long.parseLong(id.getId()); } @Override public void deleteUser(Long id) throws SynapseException, JSONObjectAdapterException { String url = ADMIN_USER + "/" + id; getSharedClientConnection().deleteUri(repoEndpoint, url, getUserAgent()); } }
client/synapseJavaClient/src/main/java/org/sagebionetworks/client/SynapseAdminClientImpl.java
package org.sagebionetworks.client; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.json.JSONObject; import org.sagebionetworks.client.exceptions.SynapseClientException; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.repo.model.EntityId; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.PaginatedResults; import org.sagebionetworks.repo.model.TrashedEntity; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.auth.NewIntegrationTestUser; import org.sagebionetworks.repo.model.auth.Session; import org.sagebionetworks.repo.model.daemon.BackupRestoreStatus; import org.sagebionetworks.repo.model.daemon.RestoreSubmission; import org.sagebionetworks.repo.model.message.ChangeMessages; import org.sagebionetworks.repo.model.message.FireMessagesResult; import org.sagebionetworks.repo.model.message.PublishResults; import org.sagebionetworks.repo.model.IdList; import org.sagebionetworks.repo.model.migration.MigrationType; import org.sagebionetworks.repo.model.migration.MigrationTypeCount; import org.sagebionetworks.repo.model.migration.MigrationTypeCounts; import org.sagebionetworks.repo.model.migration.MigrationTypeList; import org.sagebionetworks.repo.model.migration.RowMetadataResult; import org.sagebionetworks.repo.model.status.StackStatus; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl; /** * Java Client API for Synapse Administrative REST APIs */ public class SynapseAdminClientImpl extends SynapseClientImpl implements SynapseAdminClient { private static final String DAEMON = ADMIN + "/daemon"; private static final String ADMIN_TRASHCAN_VIEW = ADMIN + "/trashcan/view"; private static final String ADMIN_TRASHCAN_PURGE = ADMIN + "/trashcan/purge"; private static final String ADMIN_CHANGE_MESSAGES = ADMIN + "/messages"; private static final String ADMIN_FIRE_MESSAGES = ADMIN + "/messages/refire"; private static final String ADMIN_GET_CURRENT_CHANGE_NUM = ADMIN + "/messages/currentnumber"; private static final String ADMIN_PUBLISH_MESSAGES = ADMIN_CHANGE_MESSAGES + "/rebroadcast"; private static final String ADMIN_DOI_CLEAR = ADMIN + "/doi/clear"; private static final String MIGRATION = "/migration"; private static final String MIGRATION_COUNTS = MIGRATION + "/counts"; private static final String MIGRATION_ROWS = MIGRATION + "/rows"; private static final String MIGRATION_DELTA = MIGRATION + "/delta"; private static final String MIGRATION_BACKUP = MIGRATION + "/backup"; private static final String MIGRATION_RESTORE = MIGRATION + "/restore"; private static final String MIGRATION_DELETE = MIGRATION + "/delete"; private static final String MIGRATION_STATUS = MIGRATION + "/status"; private static final String MIGRATION_PRIMARY = MIGRATION + "/primarytypes"; private static final String ADMIN_DYNAMO_CLEAR = ADMIN + "/dynamo/clear"; private static final String ADMIN_MIGRATE_WIKIS_TO_V2 = ADMIN + "/migrateWiki"; private static final String ADMIN_USER = ADMIN + "/user"; public SynapseAdminClientImpl() { super(); } public SynapseAdminClientImpl(HttpClientProvider clientProvider, DataUploader dataUploader) { super(clientProvider, dataUploader); } /** * @param updated * @return status * @throws JSONObjectAdapterException * @throws SynapseException */ public StackStatus updateCurrentStackStatus(StackStatus updated) throws JSONObjectAdapterException, SynapseException { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(updated); jsonObject = getSharedClientConnection().putJson(repoEndpoint, STACK_STATUS, jsonObject.toString(), getUserAgent()); return EntityFactory.createEntityFromJSONObject(jsonObject, StackStatus.class); } @Override public BackupRestoreStatus getDaemonStatus(String daemonId) throws SynapseException, JSONObjectAdapterException { return getJSONEntity(DAEMON + "/" + daemonId, BackupRestoreStatus.class); } @Override public PaginatedResults<TrashedEntity> viewTrash(long offset, long limit) throws SynapseException { String url = ADMIN_TRASHCAN_VIEW + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<TrashedEntity> results = new PaginatedResults<TrashedEntity>(TrashedEntity.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void purgeTrash() throws SynapseException { getSharedClientConnection().putJson(repoEndpoint, ADMIN_TRASHCAN_PURGE, null, getUserAgent()); } @Override public ChangeMessages listMessages(Long startChangeNumber, ObjectType type, Long limit) throws SynapseException, JSONObjectAdapterException{ // Build up the URL String url = buildListMessagesURL(startChangeNumber, type, limit); return getJSONEntity(url, ChangeMessages.class); } // New migration client methods public MigrationTypeList getPrimaryTypes() throws SynapseException, JSONObjectAdapterException { String uri = MIGRATION_PRIMARY; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MigrationTypeList mtl = new MigrationTypeList(); mtl.initializeFromJSONObject(adapter); return mtl; } public MigrationTypeCounts getTypeCounts() throws SynapseException, JSONObjectAdapterException { String uri = MIGRATION_COUNTS; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MigrationTypeCounts mtc = new MigrationTypeCounts(); mtc.initializeFromJSONObject(adapter); return mtc; } public RowMetadataResult getRowMetadata(MigrationType migrationType, Long limit, Long offset) throws SynapseException, JSONObjectAdapterException { String uri = MIGRATION_ROWS + "?type=" + migrationType.name() + "&limit=" + limit + "&offset=" + offset; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); RowMetadataResult results = new RowMetadataResult(); results.initializeFromJSONObject(adapter); return results; } public RowMetadataResult getRowMetadataDelta(MigrationType migrationType, IdList ids) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_DELTA + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(ids); JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); RowMetadataResult result = new RowMetadataResult(); result.initializeFromJSONObject(adapter); return result; } public BackupRestoreStatus startBackup(MigrationType migrationType, IdList ids) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_BACKUP + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(ids); JSONObject jsonObj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonStr, getUserAgent(), null); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); BackupRestoreStatus brStatus = new BackupRestoreStatus(); brStatus.initializeFromJSONObject(adapter); return brStatus; } public BackupRestoreStatus startRestore(MigrationType migrationType, RestoreSubmission req) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_RESTORE + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(req); JSONObject jsonObj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonStr, getUserAgent(), null); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); BackupRestoreStatus brStatus = new BackupRestoreStatus(); brStatus.initializeFromJSONObject(adapter); return brStatus; } public BackupRestoreStatus getStatus(String daemonId) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_STATUS + "?daemonId=" + daemonId; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); BackupRestoreStatus brStatus = new BackupRestoreStatus(); brStatus.initializeFromJSONObject(adapter); return brStatus; } public MigrationTypeCount deleteMigratableObject(MigrationType migrationType, IdList ids) throws JSONObjectAdapterException, SynapseException { String uri = MIGRATION_DELETE + "?type=" + migrationType.name(); String jsonStr = EntityFactory.createJSONStringForEntity(ids); JSONObject jsonObj = getSharedClientConnection().putJson(repoEndpoint, uri, jsonStr, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MigrationTypeCount mtc = new MigrationTypeCount(); mtc.initializeFromJSONObject(adapter); return mtc; } @Override public FireMessagesResult fireChangeMessages(Long startChangeNumber, Long limit) throws SynapseException, JSONObjectAdapterException { if(startChangeNumber == null) throw new IllegalArgumentException("startChangeNumber cannot be null"); String uri = ADMIN_FIRE_MESSAGES + "?startChangeNumber=" + startChangeNumber; if (limit != null){ uri = uri + "&limit=" + limit; } JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); FireMessagesResult res = new FireMessagesResult(); res.initializeFromJSONObject(adapter); return res; } /** * Return current change message number */ @Override public FireMessagesResult getCurrentChangeNumber() throws SynapseException, JSONObjectAdapterException { String uri = ADMIN_GET_CURRENT_CHANGE_NUM; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); FireMessagesResult res = new FireMessagesResult(); res.initializeFromJSONObject(adapter); return res; } /** * Build up the URL for the list change message call. * @param startChangeNumber * @param type * @param limit * @return */ static String buildListMessagesURL(Long startChangeNumber, ObjectType type, Long limit){ if(startChangeNumber == null) throw new IllegalArgumentException("startChangeNumber cannot be null"); StringBuilder builder = new StringBuilder(); builder.append(ADMIN_CHANGE_MESSAGES); builder.append("?"); builder.append("startChangeNumber=").append(startChangeNumber); if(type != null){ builder.append("&type=").append(type.name()); } if(limit != null){ builder.append("&limit=").append(limit); } return builder.toString(); } @Override public PublishResults publishChangeMessages(String queueName, Long startChangeNumber, ObjectType type, Long limit) throws SynapseException, JSONObjectAdapterException{ // Build up the URL String url = buildPublishMessagesURL(queueName, startChangeNumber, type, limit); JSONObject json = getSharedClientConnection().postJson(repoEndpoint, url, null, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(json, PublishResults.class); } /** * Build up the URL for publishing messages. * @param startChangeNumber * @param type * @param limit * @return */ static String buildPublishMessagesURL(String queueName, Long startChangeNumber, ObjectType type, Long limit){ if(queueName == null) throw new IllegalArgumentException("queueName cannot be null"); if(startChangeNumber == null) throw new IllegalArgumentException("startChangeNumber cannot be null"); StringBuilder builder = new StringBuilder(); builder.append(ADMIN_PUBLISH_MESSAGES); builder.append("?"); builder.append("queueName=").append(queueName); builder.append("&startChangeNumber=").append(startChangeNumber); if(type != null){ builder.append("&type=").append(type.name()); } if(limit != null){ builder.append("&limit=").append(limit); } return builder.toString(); } @Override public void clearDoi() throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, ADMIN_DOI_CLEAR, getUserAgent()); } @Override public void clearDynamoTable(String tableName, String hashKeyName, String rangeKeyName) throws SynapseException { if (tableName == null || tableName.isEmpty()) { throw new IllegalArgumentException("Table name cannot be null or empty."); } if (hashKeyName == null || hashKeyName.isEmpty()) { throw new IllegalArgumentException("Hash key name cannot be null or empty."); } if (rangeKeyName == null || rangeKeyName.isEmpty()) { throw new IllegalArgumentException("Range key name cannot be null or empty."); } try { String uri = ADMIN_DYNAMO_CLEAR + "/" + URLEncoder.encode(tableName, "UTF-8"); uri += "?hashKeyName=" + URLEncoder.encode(hashKeyName, "UTF-8"); uri += "&rangeKeyName=" + URLEncoder.encode(rangeKeyName, "UTF-8"); getSharedClientConnection().deleteUri(repoEndpoint, uri, getUserAgent()); } catch (UnsupportedEncodingException e) { throw new SynapseClientException(e); } } @Override public long createUser(NewIntegrationTestUser user) throws SynapseException, JSONObjectAdapterException { if(user.getEmail() == null) throw new IllegalArgumentException("New users must have an email"); if(user.getUsername() == null) throw new IllegalArgumentException("New users must have a username"); JSONObject json = getSharedClientConnection().postJson(repoEndpoint, ADMIN_USER, EntityFactory.createJSONStringForEntity(user), getUserAgent(), null); EntityId id = EntityFactory.createEntityFromJSONObject(json, EntityId.class); return Long.parseLong(id.getId()); } @Override public void deleteUser(Long id) throws SynapseException, JSONObjectAdapterException { String url = ADMIN_USER + "/" + id; getSharedClientConnection().deleteUri(repoEndpoint, url, getUserAgent()); } }
PLFM-2509
client/synapseJavaClient/src/main/java/org/sagebionetworks/client/SynapseAdminClientImpl.java
PLFM-2509
<ide><path>lient/synapseJavaClient/src/main/java/org/sagebionetworks/client/SynapseAdminClientImpl.java <ide> } <ide> <ide> public SynapseAdminClientImpl(HttpClientProvider clientProvider, DataUploader dataUploader) { <del> super(clientProvider, dataUploader); <add> super(new SharedClientConnection(clientProvider), dataUploader); <ide> } <ide> <ide> /**
Java
mit
58e479411b6d7d08b13d5ae46c99ff12192e879c
0
simon04/opacclient,raphaelm/opacclient,raphaelm/opacclient,johan12345/opacclient,opacapp/opacclient,ruediger-w/opacclient,johan12345/opacclient,ruediger-w/opacclient,opacapp/opacclient,thesebas/opacclient,hurzl/opacclient,ruediger-w/opacclient,geomcmaster/opacclient,opacapp/opacclient,opacapp/opacclient,johan12345/opacclient,raphaelm/opacclient,thesebas/opacclient,hurzl/opacclient,geomcmaster/opacclient,johan12345/opacclient,opacapp/opacclient,geomcmaster/opacclient,simon04/opacclient,simon04/opacclient,ruediger-w/opacclient,thesebas/opacclient,hurzl/opacclient,ruediger-w/opacclient,johan12345/opacclient
package de.geeksfactory.opacclient.searchfields; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A DropdownSearchField allows the user to select from a list of values, e.g. * library branches or item formats. */ public class DropdownSearchField extends SearchField { /** * Represents a dropdown option. */ public static class Option implements Map.Entry<String, String> { private final String key; private final String value; public Option(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public String getValue() { return value; } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } } protected List<Option> dropdownValues; public DropdownSearchField() { } /** * A new dropdown SearchField * * @param id ID of the search field, later given to your search() function * @param displayName The name to display for the search field * @param advanced Set if this field should only be shown when showing the * advanced search form * @param dropdownValues The values to show in the dropdown and their keys. If you * include one with an empty key, this is going to be the default * value and will not be given to the search() function */ public DropdownSearchField(String id, String displayName, boolean advanced, List<Option> dropdownValues) { super(id, displayName, advanced); this.dropdownValues = dropdownValues; } /** * Get the list of selectable values. */ public List<Option> getDropdownValues() { return dropdownValues; } /** * Set a list of values for the dropdown list. */ public void setDropdownValues(List<Option> dropdownValues) { this.dropdownValues = dropdownValues; } public void addDropdownValue(String key, String value) { if (dropdownValues == null) { dropdownValues = new ArrayList<>(); } dropdownValues.add(new Option(key, value)); } public void addDropdownValue(int index, String key, String value) { if (dropdownValues == null) { dropdownValues = new ArrayList<>(); } dropdownValues.add(index, new Option(key, value)); } @Override public JSONObject toJSON() throws JSONException { JSONObject json = super.toJSON(); json.put("type", "dropdown"); JSONArray values = new JSONArray(); if (dropdownValues == null) { dropdownValues = new ArrayList<>(); } for (Option map : dropdownValues) { JSONObject value = new JSONObject(); value.put("key", map.getKey()); value.put("value", map.getValue()); values.put(value); } json.put("dropdownValues", values); return json; } }
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/searchfields/DropdownSearchField.java
package de.geeksfactory.opacclient.searchfields; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A DropdownSearchField allows the user to select from a list of values, e.g. * library branches or item formats. */ public class DropdownSearchField extends SearchField { /** * Represents a dropdown option. */ public static class Option implements Map.Entry<String, String> { private final String key; private final String value; public Option(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public String getValue() { return value; } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } } protected List<Option> dropdownValues; public DropdownSearchField() { } /** * A new dropdown SearchField * * @param id ID of the search field, later given to your search() function * @param displayName The name to display for the search field * @param advanced Set if this field should only be shown when showing the * advanced search form * @param dropdownValues The values to show in the dropdown and their keys. If you * include one with an empty key, this is going to be the default * value and will not be given to the search() function */ public DropdownSearchField(String id, String displayName, boolean advanced, List<Option> dropdownValues) { super(id, displayName, advanced); this.dropdownValues = dropdownValues; } /** * Get the list of selectable values. */ public List<Option> getDropdownValues() { return dropdownValues; } /** * Set a list of values for the dropdown list. */ public void setDropdownValues(List<Option> dropdownValues) { this.dropdownValues = dropdownValues; } public void addDropdownValue(String key, String value) { if (dropdownValues == null) { dropdownValues = new ArrayList<>(); } dropdownValues.add(new Option(key, value)); } public void addDropdownValue(int index, String key, String value) { if (dropdownValues == null) { dropdownValues = new ArrayList<>(); } dropdownValues.add(index, new Option(key, value)); } @Override public JSONObject toJSON() throws JSONException { JSONObject json = super.toJSON(); json.put("type", "dropdown"); JSONArray values = new JSONArray(); for (Option map : dropdownValues) { JSONObject value = new JSONObject(); value.put("key", map.getKey()); value.put("value", map.getValue()); values.put(value); } json.put("dropdownValues", values); return json; } }
Fixed a NPE in DropdownSearchField
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/searchfields/DropdownSearchField.java
Fixed a NPE in DropdownSearchField
<ide><path>pacclient/libopac/src/main/java/de/geeksfactory/opacclient/searchfields/DropdownSearchField.java <ide> JSONObject json = super.toJSON(); <ide> json.put("type", "dropdown"); <ide> JSONArray values = new JSONArray(); <add> if (dropdownValues == null) { <add> dropdownValues = new ArrayList<>(); <add> } <ide> for (Option map : dropdownValues) { <ide> JSONObject value = new JSONObject(); <ide> value.put("key", map.getKey());
Java
apache-2.0
96adbc3fbb3ef361f67d4a42467c6f2c629503c2
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * * Copyright 2005-2006 The Apache Software Foundation * * 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.apache.activemq.store.jdbc.adapter; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.SubscriptionInfo; import org.apache.activemq.store.jdbc.JDBCAdapter; import org.apache.activemq.store.jdbc.JDBCMessageRecoveryListener; import org.apache.activemq.store.jdbc.StatementProvider; import org.apache.activemq.store.jdbc.TransactionContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements all the default JDBC operations that are used * by the JDBCPersistenceAdapter. * <p/> * sub-classing is encouraged to override the default * implementation of methods to account for differences * in JDBC Driver implementations. * <p/> * The JDBCAdapter inserts and extracts BLOB data using the * getBytes()/setBytes() operations. * <p/> * The databases/JDBC drivers that use this adapter are: * <ul> * <li></li> * </ul> * * @version $Revision: 1.10 $ */ public class DefaultJDBCAdapter implements JDBCAdapter { private static final Log log = LogFactory.getLog(DefaultJDBCAdapter.class); final protected StatementProvider statementProvider; protected boolean batchStatments=true; protected void setBinaryData(PreparedStatement s, int index, byte data[]) throws SQLException { s.setBytes(index, data); } protected byte[] getBinaryData(ResultSet rs, int index) throws SQLException { return rs.getBytes(index); } /** * @param provider */ public DefaultJDBCAdapter(StatementProvider provider) { this.statementProvider = new CachingStatementProvider(provider); } public DefaultJDBCAdapter() { this(new DefaultStatementProvider()); } public void doCreateTables(TransactionContext c) throws SQLException, IOException { Statement s = null; try { // Check to see if the table already exists. If it does, then don't log warnings during startup. // Need to run the scripts anyways since they may contain ALTER statements that upgrade a previous version of the table boolean alreadyExists = false; ResultSet rs=null; try { rs= c.getConnection().getMetaData().getTables(null,null, statementProvider.getFullMessageTableName(), new String[] {"TABLE"}); alreadyExists = rs.next(); } catch (Throwable ignore) { } finally { close(rs); } s = c.getConnection().createStatement(); String[] createStatments = statementProvider.getCreateSchemaStatments(); for (int i = 0; i < createStatments.length; i++) { // This will fail usually since the tables will be // created already. try { boolean rc = s.execute(createStatments[i]); } catch (SQLException e) { if( alreadyExists ) { log.debug("Could not create JDBC tables; The message table already existed." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode() ); } else { log.warn("Could not create JDBC tables; they could already exist." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode() ); } } } c.getConnection().commit(); } finally { try { s.close(); } catch (Throwable e) { } } } public void doDropTables(TransactionContext c) throws SQLException, IOException { Statement s = null; try { s = c.getConnection().createStatement(); String[] dropStatments = statementProvider.getDropSchemaStatments(); for (int i = 0; i < dropStatments.length; i++) { // This will fail usually since the tables will be // created already. try { boolean rc = s.execute(dropStatments[i]); } catch (SQLException e) { log.warn("Could not drop JDBC tables; they may not exist." + " Failure was: " + dropStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode() ); } } c.getConnection().commit(); } finally { try { s.close(); } catch (Throwable e) { } } } public long doGetLastMessageBrokerSequenceId(TransactionContext c) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindLastSequenceIdInMsgs()); rs = s.executeQuery(); long seq1 = 0; if (rs.next()) { seq1 = rs.getLong(1); } rs.close(); s.close(); s = c.getConnection().prepareStatement(statementProvider.getFindLastSequenceIdInAcks()); rs = s.executeQuery(); long seq2 = 0; if (rs.next()) { seq2 = rs.getLong(1); } return Math.max(seq1, seq2); } finally { close(rs); close(s); } } public void doAddMessage(TransactionContext c, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getAddMessageStatment()); if( batchStatments ) { c.setAddMessageStatement(s); } } s.setLong(1, messageID.getBrokerSequenceId()); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); setBinaryData(s, 6, data); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed add a message"); } } finally { if( !batchStatments ) { s.close(); } } } public void doAddMessageReference(TransactionContext c, MessageId messageID, ActiveMQDestination destination, long expirationTime, String messageRef) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getAddMessageStatment()); if( batchStatments ) { c.setAddMessageStatement(s); } } s.setLong(1, messageID.getBrokerSequenceId()); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expirationTime); s.setString(6, messageRef); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed add a message"); } } finally { if( !batchStatments ) { s.close(); } } } public long getBrokerSequenceId(TransactionContext c, MessageId messageID) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindMessageSequenceIdStatment()); s.setString(1, messageID.getProducerId().toString()); s.setLong(2, messageID.getProducerSequenceId()); rs = s.executeQuery(); if (!rs.next()) { return 0; } return rs.getLong(1); } finally { close(rs); close(s); } } public byte[] doGetMessage(TransactionContext c, long seq) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindMessageStatment()); s.setLong(1, seq); rs = s.executeQuery(); if (!rs.next()) { return null; } return getBinaryData(rs, 1); } finally { close(rs); close(s); } } public String doGetMessageReference(TransactionContext c, long seq) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindMessageStatment()); s.setLong(1, seq); rs = s.executeQuery(); if (!rs.next()) { return null; } return rs.getString(1); } finally { close(rs); close(s); } } public void doRemoveMessage(TransactionContext c, long seq) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getRemoveMessageStatment()); if( batchStatments ) { c.setRemovedMessageStatement(s); } } s.setLong(1, seq); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed to remove message"); } } finally { if( !batchStatments ) { s.close(); } } } public void doRecover(TransactionContext c, ActiveMQDestination destination, JDBCMessageRecoveryListener listener) throws Throwable { // printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllMessagesStatment()); s.setString(1, destination.getQualifiedName()); rs = s.executeQuery(); if( statementProvider.isUseExternalMessageReferences() ) { while (rs.next()) { listener.recoverMessageReference(rs.getString(2)); } } else { while (rs.next()) { listener.recoverMessage(rs.getLong(1), getBinaryData(rs, 2)); } } } finally { close(rs); close(s); } } public void doSetLastAck(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName, long seq) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getUpdateLastAckOfDurableSub()); if( batchStatments ) { c.setUpdateLastAckStatement(s); } } s.setLong(1, seq); s.setString(2, destination.getQualifiedName()); s.setString(3, clientId); s.setString(4, subscriptionName); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed add a message"); } } finally { if( !batchStatments ) { s.close(); } } } public void doRecoverSubscription(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName, JDBCMessageRecoveryListener listener) throws Throwable { // dumpTables(c, destination.getQualifiedName(),clientId,subscriptionName); PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllDurableSubMessagesStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); rs = s.executeQuery(); if( statementProvider.isUseExternalMessageReferences() ) { while (rs.next()) { listener.recoverMessageReference(rs.getString(2)); } } else { while (rs.next()) { listener.recoverMessage(rs.getLong(1), getBinaryData(rs, 2)); } } } finally { close(rs); close(s); } } /** * @see org.apache.activemq.store.jdbc.JDBCAdapter#doSetSubscriberEntry(java.sql.Connection, java.lang.Object, org.apache.activemq.service.SubscriptionInfo) */ public void doSetSubscriberEntry(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName, String selector, boolean retroactive) throws SQLException, IOException { // dumpTables(c, destination.getQualifiedName(), clientId, subscriptionName); PreparedStatement s = null; try { long lastMessageId = -1; if(!retroactive) { s = c.getConnection().prepareStatement(statementProvider.getFindLastSequenceIdInMsgs()); ResultSet rs=null; try { rs = s.executeQuery(); if (rs.next()) { lastMessageId = rs.getLong(1); } } finally { close(rs); close(s); } } s = c.getConnection().prepareStatement(statementProvider.getCreateDurableSubStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); s.setString(4, selector); s.setLong(5, lastMessageId); if (s.executeUpdate() != 1) { throw new IOException("Could not create durable subscription for: "+clientId); } } finally { close(s); } } public SubscriptionInfo doGetSubscriberEntry(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindDurableSubStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); rs = s.executeQuery(); if (!rs.next()) { return null; } SubscriptionInfo subscription = new SubscriptionInfo(); subscription.setDestination(destination); subscription.setClientId(clientId); subscription.setSubcriptionName(subscriptionName); subscription.setSelector(rs.getString(1)); return subscription; } finally { close(rs); close(s); } } public SubscriptionInfo[] doGetAllSubscriptions(TransactionContext c, ActiveMQDestination destination) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllDurableSubsStatment()); s.setString(1, destination.getQualifiedName()); rs = s.executeQuery(); ArrayList rc = new ArrayList(); while(rs.next()) { SubscriptionInfo subscription = new SubscriptionInfo(); subscription.setDestination(destination); subscription.setSelector(rs.getString(1)); subscription.setSubcriptionName(rs.getString(2)); subscription.setClientId(rs.getString(3)); rc.add(subscription); } return (SubscriptionInfo[]) rc.toArray(new SubscriptionInfo[rc.size()]); } finally { close(rs); close(s); } } public void doRemoveAllMessages(TransactionContext c, ActiveMQDestination destinationName) throws SQLException, IOException { PreparedStatement s = null; try { s = c.getConnection().prepareStatement(statementProvider.getRemoveAllMessagesStatment()); s.setString(1, destinationName.getQualifiedName()); s.executeUpdate(); s.close(); s = c.getConnection().prepareStatement(statementProvider.getRemoveAllSubscriptionsStatment()); s.setString(1, destinationName.getQualifiedName()); s.executeUpdate(); } finally { close(s); } } public void doDeleteSubscription(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName) throws SQLException, IOException { PreparedStatement s = null; try { s = c.getConnection().prepareStatement(statementProvider.getDeleteSubscriptionStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); s.executeUpdate(); } finally { close(s); } } public void doDeleteOldMessages(TransactionContext c) throws SQLException, IOException { PreparedStatement s = null; try { s = c.getConnection().prepareStatement(statementProvider.getDeleteOldMessagesStatment()); s.setLong(1, System.currentTimeMillis()); int i = s.executeUpdate(); log.debug("Deleted "+i+" old message(s)."); } finally { close(s); } } static private void close(PreparedStatement s) { try { s.close(); } catch (Throwable e) { } } static private void close(ResultSet rs) { try { rs.close(); } catch (Throwable e) { } } public Set doGetDestinations(TransactionContext c) throws SQLException, IOException { HashSet rc = new HashSet(); PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllDestinationsStatment()); rs = s.executeQuery(); while (rs.next()) { rc.add( ActiveMQDestination.createDestination(rs.getString(1), ActiveMQDestination.QUEUE_TYPE)); } } finally { close(rs); close(s); } return rc; } public boolean isBatchStatments() { return batchStatments; } public void setBatchStatments(boolean batchStatments) { this.batchStatments = batchStatments; } public void setUseExternalMessageReferences(boolean useExternalMessageReferences) { statementProvider.setUseExternalMessageReferences(useExternalMessageReferences); } /* * Useful for debugging. public void dumpTables(Connection c, String destinationName, String clientId, String subscriptionName) throws SQLException { printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); printQuery(c, "Select * from ACTIVEMQ_ACKS", System.out); PreparedStatement s = c.prepareStatement("SELECT M.ID, D.LAST_ACKED_ID FROM " +"ACTIVEMQ_MSGS M, " +"ACTIVEMQ_ACKS D " +"WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" +" AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" +" ORDER BY M.ID"); s.setString(1,destinationName); s.setString(2,clientId); s.setString(3,subscriptionName); printQuery(s,System.out); } public void dumpTables(Connection c) throws SQLException { printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); printQuery(c, "Select * from ACTIVEMQ_ACKS", System.out); } private void printQuery(Connection c, String query, PrintStream out) throws SQLException { printQuery(c.prepareStatement(query), out); } private void printQuery(PreparedStatement s, PrintStream out) throws SQLException { ResultSet set=null; try { set = s.executeQuery(); ResultSetMetaData metaData = set.getMetaData(); for( int i=1; i<= metaData.getColumnCount(); i++ ) { if(i==1) out.print("||"); out.print(metaData.getColumnName(i)+"||"); } out.println(); while(set.next()) { for( int i=1; i<= metaData.getColumnCount(); i++ ) { if(i==1) out.print("|"); out.print(set.getString(i)+"|"); } out.println(); } } finally { try { set.close(); } catch (Throwable ignore) {} try { s.close(); } catch (Throwable ignore) {} } } */ }
activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java
/** * * Copyright 2005-2006 The Apache Software Foundation * * 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.apache.activemq.store.jdbc.adapter; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.SubscriptionInfo; import org.apache.activemq.store.jdbc.JDBCAdapter; import org.apache.activemq.store.jdbc.JDBCMessageRecoveryListener; import org.apache.activemq.store.jdbc.StatementProvider; import org.apache.activemq.store.jdbc.TransactionContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements all the default JDBC operations that are used * by the JDBCPersistenceAdapter. * <p/> * sub-classing is encouraged to override the default * implementation of methods to account for differences * in JDBC Driver implementations. * <p/> * The JDBCAdapter inserts and extracts BLOB data using the * getBytes()/setBytes() operations. * <p/> * The databases/JDBC drivers that use this adapter are: * <ul> * <li></li> * </ul> * * @version $Revision: 1.10 $ */ public class DefaultJDBCAdapter implements JDBCAdapter { private static final Log log = LogFactory.getLog(DefaultJDBCAdapter.class); final protected StatementProvider statementProvider; protected boolean batchStatments=true; protected void setBinaryData(PreparedStatement s, int index, byte data[]) throws SQLException { s.setBytes(index, data); } protected byte[] getBinaryData(ResultSet rs, int index) throws SQLException { return rs.getBytes(index); } /** * @param provider */ public DefaultJDBCAdapter(StatementProvider provider) { this.statementProvider = new CachingStatementProvider(provider); } public DefaultJDBCAdapter() { this(new DefaultStatementProvider()); } public void doCreateTables(TransactionContext c) throws SQLException, IOException { Statement s = null; try { // Check to see if the table already exists. If it does, then don't log warnings during startup. // Need to run the scripts anyways since they may contain ALTER statements that upgrade a previous version of the table boolean alreadyExists = false; ResultSet rs=null; try { rs= c.getConnection().getMetaData().getTables(null,null, statementProvider.getFullMessageTableName(), new String[] {"TABLE"}); alreadyExists = rs.next(); } catch (Throwable ignore) { } finally { close(rs); } s = c.getConnection().createStatement(); String[] createStatments = statementProvider.getCreateSchemaStatments(); for (int i = 0; i < createStatments.length; i++) { // This will fail usually since the tables will be // created already. try { boolean rc = s.execute(createStatments[i]); } catch (SQLException e) { if( alreadyExists ) { log.debug("Could not create JDBC tables; The message table already existed." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode() ); } else { log.warn("Could not create JDBC tables; they could already exist." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode() ); } } } c.getConnection().commit(); } finally { try { s.close(); } catch (Throwable e) { } } } public void doDropTables(TransactionContext c) throws SQLException, IOException { Statement s = null; try { s = c.getConnection().createStatement(); String[] dropStatments = statementProvider.getDropSchemaStatments(); for (int i = 0; i < dropStatments.length; i++) { // This will fail usually since the tables will be // created already. try { boolean rc = s.execute(dropStatments[i]); } catch (SQLException e) { log.warn("Could not drop JDBC tables; they may not exist." + " Failure was: " + dropStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode() ); } } c.getConnection().commit(); } finally { try { s.close(); } catch (Throwable e) { } } } public long doGetLastMessageBrokerSequenceId(TransactionContext c) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindLastSequenceIdInMsgs()); rs = s.executeQuery(); long seq1 = 0; if (rs.next()) { seq1 = rs.getLong(1); } rs.close(); s.close(); s = c.getConnection().prepareStatement(statementProvider.getFindLastSequenceIdInAcks()); rs = s.executeQuery(); long seq2 = 0; if (rs.next()) { seq2 = rs.getLong(1); } return Math.max(seq1, seq2); } finally { close(rs); close(s); } } public void doAddMessage(TransactionContext c, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getAddMessageStatment()); if( batchStatments ) { c.setAddMessageStatement(s); } } s.setLong(1, messageID.getBrokerSequenceId()); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); setBinaryData(s, 6, data); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed add a message"); } } finally { if( !batchStatments ) { s.close(); } } } public void doAddMessageReference(TransactionContext c, MessageId messageID, ActiveMQDestination destination, long expirationTime, String messageRef) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getAddMessageStatment()); if( batchStatments ) { c.setAddMessageStatement(s); } } s.setLong(1, messageID.getBrokerSequenceId()); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expirationTime); s.setString(6, messageRef); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed add a message"); } } finally { if( !batchStatments ) { s.close(); } } } public long getBrokerSequenceId(TransactionContext c, MessageId messageID) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindMessageSequenceIdStatment()); s.setString(1, messageID.getProducerId().toString()); s.setLong(2, messageID.getProducerSequenceId()); rs = s.executeQuery(); if (!rs.next()) { return 0; } return rs.getLong(1); } finally { close(rs); close(s); } } public byte[] doGetMessage(TransactionContext c, long seq) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindMessageStatment()); s.setLong(1, seq); rs = s.executeQuery(); if (!rs.next()) { return null; } return getBinaryData(rs, 1); } finally { close(rs); close(s); } } public String doGetMessageReference(TransactionContext c, long seq) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindMessageStatment()); s.setLong(1, seq); rs = s.executeQuery(); if (!rs.next()) { return null; } return rs.getString(1); } finally { close(rs); close(s); } } public void doRemoveMessage(TransactionContext c, long seq) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getRemoveMessageStatment()); if( batchStatments ) { c.setRemovedMessageStatement(s); } } s.setLong(1, seq); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed to remove message"); } } finally { if( !batchStatments ) { s.close(); } } } public void doRecover(TransactionContext c, ActiveMQDestination destination, JDBCMessageRecoveryListener listener) throws Throwable { // printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllMessagesStatment()); s.setString(1, destination.getQualifiedName()); rs = s.executeQuery(); if( statementProvider.isUseExternalMessageReferences() ) { while (rs.next()) { listener.recoverMessageReference(rs.getString(2)); } } else { while (rs.next()) { listener.recoverMessage(rs.getLong(1), getBinaryData(rs, 2)); } } } finally { close(rs); close(s); } } public void doSetLastAck(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName, long seq) throws SQLException, IOException { PreparedStatement s = c.getAddMessageStatement(); try { if( s == null ) { s = c.getConnection().prepareStatement(statementProvider.getUpdateLastAckOfDurableSub()); if( batchStatments ) { c.setUpdateLastAckStatement(s); } } s.setLong(1, seq); s.setString(2, destination.getQualifiedName()); s.setString(3, clientId); s.setString(4, subscriptionName); if( batchStatments ) { s.addBatch(); } else if ( s.executeUpdate() != 1 ) { throw new SQLException("Failed add a message"); } } finally { if( !batchStatments ) { s.close(); } } } public void doRecoverSubscription(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName, JDBCMessageRecoveryListener listener) throws Throwable { // dumpTables(c, destination.getQualifiedName(),clientId,subscriptionName); PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllDurableSubMessagesStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); rs = s.executeQuery(); if( statementProvider.isUseExternalMessageReferences() ) { while (rs.next()) { listener.recoverMessageReference(rs.getString(2)); } } else { while (rs.next()) { listener.recoverMessage(rs.getLong(1), getBinaryData(rs, 2)); } } } finally { close(rs); close(s); } } /** * @see org.apache.activemq.store.jdbc.JDBCAdapter#doSetSubscriberEntry(java.sql.Connection, java.lang.Object, org.apache.activemq.service.SubscriptionInfo) */ public void doSetSubscriberEntry(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName, String selector, boolean retroactive) throws SQLException, IOException { // dumpTables(c, destination.getQualifiedName(), clientId, subscriptionName); PreparedStatement s = null; try { long lastMessageId = -1; if(!retroactive) { s = c.getConnection().prepareStatement(statementProvider.getFindLastSequenceIdInMsgs()); ResultSet rs=null; try { rs = s.executeQuery(); if (rs.next()) { lastMessageId = rs.getLong(1); } } finally { close(rs); close(s); } } s = c.getConnection().prepareStatement(statementProvider.getCreateDurableSubStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); s.setString(4, selector); s.setLong(5, lastMessageId); if (s.executeUpdate() != 1) { throw new IOException("Could not create durable subscription for: "+clientId); } } finally { close(s); } } public SubscriptionInfo doGetSubscriberEntry(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindDurableSubStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); rs = s.executeQuery(); if (!rs.next()) { return null; } SubscriptionInfo subscription = new SubscriptionInfo(); subscription.setDestination(destination); subscription.setClientId(clientId); subscription.setSubcriptionName(subscriptionName); subscription.setSelector(rs.getString(1)); return subscription; } finally { close(rs); close(s); } } public SubscriptionInfo[] doGetAllSubscriptions(TransactionContext c, ActiveMQDestination destination) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllDurableSubsStatment()); s.setString(1, destination.getQualifiedName()); rs = s.executeQuery(); ArrayList rc = new ArrayList(); while(rs.next()) { SubscriptionInfo subscription = new SubscriptionInfo(); subscription.setDestination(destination); subscription.setSelector(rs.getString(1)); subscription.setSubcriptionName(rs.getString(2)); subscription.setClientId(rs.getString(3)); } return (SubscriptionInfo[]) rc.toArray(new SubscriptionInfo[rc.size()]); } finally { close(rs); close(s); } } public void doRemoveAllMessages(TransactionContext c, ActiveMQDestination destinationName) throws SQLException, IOException { PreparedStatement s = null; try { s = c.getConnection().prepareStatement(statementProvider.getRemoveAllMessagesStatment()); s.setString(1, destinationName.getQualifiedName()); s.executeUpdate(); s.close(); s = c.getConnection().prepareStatement(statementProvider.getRemoveAllSubscriptionsStatment()); s.setString(1, destinationName.getQualifiedName()); s.executeUpdate(); } finally { close(s); } } public void doDeleteSubscription(TransactionContext c, ActiveMQDestination destination, String clientId, String subscriptionName) throws SQLException, IOException { PreparedStatement s = null; try { s = c.getConnection().prepareStatement(statementProvider.getDeleteSubscriptionStatment()); s.setString(1, destination.getQualifiedName()); s.setString(2, clientId); s.setString(3, subscriptionName); s.executeUpdate(); } finally { close(s); } } public void doDeleteOldMessages(TransactionContext c) throws SQLException, IOException { PreparedStatement s = null; try { s = c.getConnection().prepareStatement(statementProvider.getDeleteOldMessagesStatment()); s.setLong(1, System.currentTimeMillis()); int i = s.executeUpdate(); log.debug("Deleted "+i+" old message(s)."); } finally { close(s); } } static private void close(PreparedStatement s) { try { s.close(); } catch (Throwable e) { } } static private void close(ResultSet rs) { try { rs.close(); } catch (Throwable e) { } } public Set doGetDestinations(TransactionContext c) throws SQLException, IOException { HashSet rc = new HashSet(); PreparedStatement s = null; ResultSet rs = null; try { s = c.getConnection().prepareStatement(statementProvider.getFindAllDestinationsStatment()); rs = s.executeQuery(); while (rs.next()) { rc.add( ActiveMQDestination.createDestination(rs.getString(1), ActiveMQDestination.QUEUE_TYPE)); } } finally { close(rs); close(s); } return rc; } public boolean isBatchStatments() { return batchStatments; } public void setBatchStatments(boolean batchStatments) { this.batchStatments = batchStatments; } public void setUseExternalMessageReferences(boolean useExternalMessageReferences) { statementProvider.setUseExternalMessageReferences(useExternalMessageReferences); } /* * Useful for debugging. public void dumpTables(Connection c, String destinationName, String clientId, String subscriptionName) throws SQLException { printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); printQuery(c, "Select * from ACTIVEMQ_ACKS", System.out); PreparedStatement s = c.prepareStatement("SELECT M.ID, D.LAST_ACKED_ID FROM " +"ACTIVEMQ_MSGS M, " +"ACTIVEMQ_ACKS D " +"WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" +" AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" +" ORDER BY M.ID"); s.setString(1,destinationName); s.setString(2,clientId); s.setString(3,subscriptionName); printQuery(s,System.out); } private void printQuery(Connection c, String query, PrintStream out) throws SQLException { printQuery(c.prepareStatement(query), out); } private void printQuery(PreparedStatement s, PrintStream out) throws SQLException { ResultSet set=null; try { set = s.executeQuery(); ResultSetMetaData metaData = set.getMetaData(); for( int i=1; i<= metaData.getColumnCount(); i++ ) { if(i==1) out.print("||"); out.print(metaData.getColumnName(i)+"||"); } out.println(); while(set.next()) { for( int i=1; i<= metaData.getColumnCount(); i++ ) { if(i==1) out.print("|"); out.print(set.getString(i)+"|"); } out.println(); } } finally { try { set.close(); } catch (Throwable ignore) {} try { s.close(); } catch (Throwable ignore) {} } } */ }
Fixing broker DurableConsumerCloseAndReconnectTest, subscriptions were not being added to the result array. git-svn-id: 7f3df76e74c7ad56904d6048df705810748eb1a6@376856 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java
Fixing broker DurableConsumerCloseAndReconnectTest, subscriptions were not being added to the result array.
<ide><path>ctivemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java <ide> subscription.setSelector(rs.getString(1)); <ide> subscription.setSubcriptionName(rs.getString(2)); <ide> subscription.setClientId(rs.getString(3)); <add> rc.add(subscription); <ide> } <ide> <ide> return (SubscriptionInfo[]) rc.toArray(new SubscriptionInfo[rc.size()]); <ide> s.setString(3,subscriptionName); <ide> printQuery(s,System.out); <ide> } <add> <add> public void dumpTables(Connection c) throws SQLException { <add> printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); <add> printQuery(c, "Select * from ACTIVEMQ_ACKS", System.out); <add> } <ide> <ide> private void printQuery(Connection c, String query, PrintStream out) throws SQLException { <ide> printQuery(c.prepareStatement(query), out);
Java
apache-2.0
dfb48bdc3904f7e8dab8f78a768e1a5b243793c3
0
idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,orekyuu/intellij-community,samthor/intellij-community,asedunov/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,FHannes/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,kdwink/intellij-community,allotria/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,izonder/intellij-community,ibinti/intellij-community,retomerz/intellij-community,apixandru/intellij-community,petteyg/intellij-community,amith01994/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,kool79/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,asedunov/intellij-community,dslomov/intellij-community,clumsy/intellij-community,holmes/intellij-community,xfournet/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,caot/intellij-community,caot/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,allotria/intellij-community,slisson/intellij-community,slisson/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,holmes/intellij-community,kdwink/intellij-community,blademainer/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,izonder/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,holmes/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,vladmm/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,da1z/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,signed/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,xfournet/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,xfournet/intellij-community,xfournet/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,diorcety/intellij-community,xfournet/intellij-community,hurricup/intellij-community,semonte/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,holmes/intellij-community,blademainer/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,fitermay/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,caot/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,vladmm/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,FHannes/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,jagguli/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,kool79/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,dslomov/intellij-community,fitermay/intellij-community,izonder/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,da1z/intellij-community,ibinti/intellij-community,samthor/intellij-community,kdwink/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,izonder/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,robovm/robovm-studio,hurricup/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,caot/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,slisson/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,signed/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,jagguli/intellij-community,retomerz/intellij-community,signed/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,signed/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,allotria/intellij-community,supersven/intellij-community,da1z/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ibinti/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,apixandru/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,da1z/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,samthor/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,petteyg/intellij-community,FHannes/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,caot/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ryano144/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,izonder/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,hurricup/intellij-community,holmes/intellij-community,semonte/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,holmes/intellij-community,blademainer/intellij-community,signed/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,fitermay/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,petteyg/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,allotria/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,holmes/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,da1z/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,signed/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,slisson/intellij-community,Lekanich/intellij-community,allotria/intellij-community,signed/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,samthor/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,FHannes/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,robovm/robovm-studio,dslomov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,diorcety/intellij-community,caot/intellij-community,da1z/intellij-community,robovm/robovm-studio,retomerz/intellij-community,allotria/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,supersven/intellij-community,holmes/intellij-community,vladmm/intellij-community,xfournet/intellij-community,supersven/intellij-community,retomerz/intellij-community,allotria/intellij-community,petteyg/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,izonder/intellij-community,fnouama/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,clumsy/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,jagguli/intellij-community,vladmm/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,semonte/intellij-community,kool79/intellij-community,caot/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,samthor/intellij-community,blademainer/intellij-community,vladmm/intellij-community,fitermay/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,allotria/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,diorcety/intellij-community,semonte/intellij-community,da1z/intellij-community,ryano144/intellij-community,amith01994/intellij-community,hurricup/intellij-community,adedayo/intellij-community,caot/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,diorcety/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,da1z/intellij-community,signed/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,kool79/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,signed/intellij-community,vladmm/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,caot/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,apixandru/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,supersven/intellij-community,izonder/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,blademainer/intellij-community,signed/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,amith01994/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 git4idea.checkin; import com.intellij.CommonBundle; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.CheckinProjectPanel; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ObjectsConvertor; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.changes.ui.SelectFilePathsDialog; import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent; import com.intellij.openapi.vcs.checkin.CheckinEnvironment; import com.intellij.openapi.vcs.ui.RefreshableOnComponent; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.ui.NonFocusableCheckBox; import com.intellij.util.ArrayUtil; import com.intellij.util.FunctionUtil; import com.intellij.util.NullableFunction; import com.intellij.util.PairConsumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.UIUtil; import com.intellij.vcsUtil.VcsFileUtil; import com.intellij.vcsUtil.VcsUtil; import git4idea.GitPlatformFacade; import git4idea.GitUtil; import git4idea.commands.GitCommand; import git4idea.commands.GitSimpleHandler; import git4idea.config.GitConfigUtil; import git4idea.config.GitVcsSettings; import git4idea.history.NewGitUsersComponent; import git4idea.history.browser.GitHeavyCommit; import git4idea.i18n.GitBundle; import git4idea.push.GitPusher; import git4idea.repo.GitRepositoryFiles; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitFileUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; /** * Git environment for commit operations. */ public class GitCheckinEnvironment implements CheckinEnvironment { private static final Logger log = Logger.getInstance(GitCheckinEnvironment.class.getName()); @NonNls private static final String GIT_COMMIT_MSG_FILE_PREFIX = "git-commit-msg-"; // the file name prefix for commit message file @NonNls private static final String GIT_COMMIT_MSG_FILE_EXT = ".txt"; // the file extension for commit message file private final Project myProject; public static final SimpleDateFormat COMMIT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private final VcsDirtyScopeManager myDirtyScopeManager; private final GitVcsSettings mySettings; private String myNextCommitAuthor = null; // The author for the next commit private boolean myNextCommitAmend; // If true, the next commit is amended private Boolean myNextCommitIsPushed = null; // The push option of the next commit private Date myNextCommitAuthorDate; public GitCheckinEnvironment(@NotNull Project project, @NotNull final VcsDirtyScopeManager dirtyScopeManager, final GitVcsSettings settings) { myProject = project; myDirtyScopeManager = dirtyScopeManager; mySettings = settings; } public boolean keepChangeListAfterCommit(ChangeList changeList) { return false; } @Override public boolean isRefreshAfterCommitNeeded() { return false; } @Nullable public RefreshableOnComponent createAdditionalOptionsPanel(CheckinProjectPanel panel, PairConsumer<Object, Object> additionalDataConsumer) { return new GitCheckinOptions(myProject, panel.getRoots()); } @Nullable public String getDefaultMessageFor(FilePath[] filesToCheckin) { StringBuilder rc = new StringBuilder(); for (VirtualFile root : GitUtil.gitRoots(Arrays.asList(filesToCheckin))) { VirtualFile mergeMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_MERGE_MSG); VirtualFile squashMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_SQUASH_MSG); if (mergeMsg != null || squashMsg != null) { try { String encoding = GitConfigUtil.getCommitEncoding(myProject, root); if (mergeMsg != null) { rc.append(FileUtil.loadFileText(new File(mergeMsg.getPath()), encoding)); } if (squashMsg != null) { rc.append(FileUtil.loadFileText(new File(squashMsg.getPath()), encoding)); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Unable to load merge message", e); } } } } if (rc.length() != 0) { return rc.toString(); } return null; } public String getHelpId() { return null; } public String getCheckinOperationName() { return GitBundle.getString("commit.action.name"); } public List<VcsException> commit(@NotNull List<Change> changes, @NotNull String message, @NotNull NullableFunction<Object, Object> parametersHolder, Set<String> feedback) { List<VcsException> exceptions = new ArrayList<VcsException>(); Map<VirtualFile, Collection<Change>> sortedChanges = sortChangesByGitRoot(changes, exceptions); log.assertTrue(!sortedChanges.isEmpty(), "Trying to commit an empty list of changes: " + changes); for (Map.Entry<VirtualFile, Collection<Change>> entry : sortedChanges.entrySet()) { final VirtualFile root = entry.getKey(); try { File messageFile = createMessageFile(root, message); try { final Set<FilePath> added = new HashSet<FilePath>(); final Set<FilePath> removed = new HashSet<FilePath>(); for (Change change : entry.getValue()) { switch (change.getType()) { case NEW: case MODIFICATION: added.add(change.getAfterRevision().getFile()); break; case DELETED: removed.add(change.getBeforeRevision().getFile()); break; case MOVED: FilePath afterPath = change.getAfterRevision().getFile(); FilePath beforePath = change.getBeforeRevision().getFile(); added.add(afterPath); if (!GitFileUtils.shouldIgnoreCaseChange(afterPath.getPath(), beforePath.getPath())) { removed.add(beforePath); } break; default: throw new IllegalStateException("Unknown change type: " + change.getType()); } } try { try { Set<FilePath> files = new HashSet<FilePath>(); files.addAll(added); files.addAll(removed); commit(myProject, root, files, messageFile, myNextCommitAuthor, myNextCommitAmend, myNextCommitAuthorDate); } catch (VcsException ex) { PartialOperation partialOperation = isMergeCommit(ex); if (partialOperation == PartialOperation.NONE) { throw ex; } if (!mergeCommit(myProject, root, added, removed, messageFile, myNextCommitAuthor, exceptions, partialOperation)) { throw ex; } } } finally { if (!messageFile.delete()) { log.warn("Failed to remove temporary file: " + messageFile); } } } catch (VcsException e) { exceptions.add(e); } } catch (IOException ex) { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Creation of commit message file failed", ex)); } } if (myNextCommitIsPushed != null && myNextCommitIsPushed.booleanValue() && exceptions.isEmpty()) { // push UIUtil.invokeLaterIfNeeded(new Runnable() { public void run() { GitPusher.showPushDialogAndPerformPush(myProject, ServiceManager.getService(myProject, GitPlatformFacade.class)); } }); } return exceptions; } public List<VcsException> commit(List<Change> changes, String preparedComment) { return commit(changes, preparedComment, FunctionUtil.<Object, Object>nullConstant(), null); } /** * Preform a merge commit * * * @param project a project * @param root a vcs root * @param added added files * @param removed removed files * @param messageFile a message file for commit * @param author an author * @param exceptions the list of exceptions to report * @param partialOperation * @return true if merge commit was successful */ private static boolean mergeCommit(final Project project, final VirtualFile root, final Set<FilePath> added, final Set<FilePath> removed, final File messageFile, final String author, List<VcsException> exceptions, @NotNull final PartialOperation partialOperation) { HashSet<FilePath> realAdded = new HashSet<FilePath>(); HashSet<FilePath> realRemoved = new HashSet<FilePath>(); // perform diff GitSimpleHandler diff = new GitSimpleHandler(project, root, GitCommand.DIFF); diff.setSilent(true); diff.setStdoutSuppressed(true); diff.addParameters("--diff-filter=ADMRUX", "--name-status", "HEAD"); diff.endOptions(); String output; try { output = diff.run(); } catch (VcsException ex) { exceptions.add(ex); return false; } String rootPath = root.getPath(); for (StringTokenizer lines = new StringTokenizer(output, "\n", false); lines.hasMoreTokens();) { String line = lines.nextToken().trim(); if (line.length() == 0) { continue; } String[] tk = line.split("\t"); switch (tk[0].charAt(0)) { case 'M': case 'A': realAdded.add(VcsUtil.getFilePath(rootPath + "/" + tk[1])); break; case 'D': realRemoved.add(VcsUtil.getFilePathForDeletedFile(rootPath + "/" + tk[1], false)); break; default: throw new IllegalStateException("Unexpected status: " + line); } } realAdded.removeAll(added); realRemoved.removeAll(removed); if (realAdded.size() != 0 || realRemoved.size() != 0) { final List<FilePath> files = new ArrayList<FilePath>(); files.addAll(realAdded); files.addAll(realRemoved); final Ref<Boolean> mergeAll = new Ref<Boolean>(); try { GuiUtils.runOrInvokeAndWait(new Runnable() { public void run() { String message = GitBundle.message("commit.partial.merge.message", partialOperation.getName()); SelectFilePathsDialog dialog = new SelectFilePathsDialog(project, files, message, null, "Commit All Files", CommonBundle.getCancelButtonText(), false); dialog.setTitle(GitBundle.getString("commit.partial.merge.title")); dialog.show(); mergeAll.set(dialog.isOK()); } }); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Unable to invoke a message box on AWT thread", ex); } if (!mergeAll.get()) { return false; } // update non-indexed files if (!updateIndex(project, root, realAdded, realRemoved, exceptions)) { return false; } for (FilePath f : realAdded) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } for (FilePath f : realRemoved) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } } // perform merge commit try { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.addParameters("-F", messageFile.getAbsolutePath()); if (author != null) { handler.addParameters("--author=" + author); } handler.endOptions(); handler.run(); GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } catch (VcsException ex) { exceptions.add(ex); return false; } return true; } /** * Check if commit has failed due to unfinished merge or cherry-pick. * * * @param ex an exception to examine * @return true if exception means that there is a partial commit during merge */ private static PartialOperation isMergeCommit(final VcsException ex) { String message = ex.getMessage(); if (message.contains("fatal: cannot do a partial commit during a merge")) { return PartialOperation.MERGE; } if (message.contains("fatal: cannot do a partial commit during a cherry-pick")) { return PartialOperation.CHERRY_PICK; } return PartialOperation.NONE; } /** * Update index (delete and remove files) * * @param project the project * @param root a vcs root * @param added added/modified files to commit * @param removed removed files to commit * @param exceptions a list of exceptions to update * @return true if index was updated successfully */ private static boolean updateIndex(final Project project, final VirtualFile root, final Collection<FilePath> added, final Collection<FilePath> removed, final List<VcsException> exceptions) { boolean rc = true; if (!added.isEmpty()) { try { GitFileUtils.addPaths(project, root, added); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } if (!removed.isEmpty()) { try { GitFileUtils.delete(project, root, removed, "--ignore-unmatch"); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } return rc; } /** * Create a file that contains the specified message * * @param root a git repository root * @param message a message to write * @return a file reference * @throws IOException if file cannot be created */ private File createMessageFile(VirtualFile root, final String message) throws IOException { // filter comment lines File file = FileUtil.createTempFile(GIT_COMMIT_MSG_FILE_PREFIX, GIT_COMMIT_MSG_FILE_EXT); file.deleteOnExit(); @NonNls String encoding = GitConfigUtil.getCommitEncoding(myProject, root); Writer out = new OutputStreamWriter(new FileOutputStream(file), encoding); try { out.write(message); } finally { out.close(); } return file; } /** * {@inheritDoc} */ public List<VcsException> scheduleMissingFileForDeletion(List<FilePath> files) { ArrayList<VcsException> rc = new ArrayList<VcsException>(); Map<VirtualFile, List<FilePath>> sortedFiles; try { sortedFiles = GitUtil.sortFilePathsByGitRoot(files); } catch (VcsException e) { rc.add(e); return rc; } for (Map.Entry<VirtualFile, List<FilePath>> e : sortedFiles.entrySet()) { try { final VirtualFile root = e.getKey(); GitFileUtils.delete(myProject, root, e.getValue()); markRootDirty(root); } catch (VcsException ex) { rc.add(ex); } } return rc; } /** * Prepare delete files handler. * * * * @param project the project * @param root a vcs root * @param files a files to commit * @param message a message file to use * @param nextCommitAuthor a author for the next commit * @param nextCommitAmend true, if the commit should be amended * @param nextCommitAuthorDate Author date timestamp to override the date of the commit or null if this overriding is not needed. * @return a simple handler that does the task * @throws VcsException in case of git problem */ private static void commit(Project project, VirtualFile root, Collection<FilePath> files, File message, final String nextCommitAuthor, boolean nextCommitAmend, Date nextCommitAuthorDate) throws VcsException { boolean amend = nextCommitAmend; for (List<String> paths : VcsFileUtil.chunkPaths(root, files)) { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); if (amend) { handler.addParameters("--amend"); } else { amend = true; } handler.addParameters("--only", "-F", message.getAbsolutePath()); if (nextCommitAuthor != null) { handler.addParameters("--author=" + nextCommitAuthor); } if (nextCommitAuthorDate != null) { handler.addParameters("--date", COMMIT_DATE_FORMAT.format(nextCommitAuthorDate)); } handler.endOptions(); handler.addParameters(paths); handler.run(); } if (!project.isDisposed()) { GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } } /** * {@inheritDoc} */ public List<VcsException> scheduleUnversionedFilesForAddition(List<VirtualFile> files) { ArrayList<VcsException> rc = new ArrayList<VcsException>(); Map<VirtualFile, List<VirtualFile>> sortedFiles; try { sortedFiles = GitUtil.sortFilesByGitRoot(files); } catch (VcsException e) { rc.add(e); return rc; } for (Map.Entry<VirtualFile, List<VirtualFile>> e : sortedFiles.entrySet()) { try { final VirtualFile root = e.getKey(); GitFileUtils.addFiles(myProject, root, e.getValue()); markRootDirty(root); } catch (VcsException ex) { rc.add(ex); } } return rc; } private enum PartialOperation { NONE("none"), MERGE("merge"), CHERRY_PICK("cherry-pick"); private final String myName; PartialOperation(String name) { myName = name; } String getName() { return myName; } } /** * Sort changes by roots * * @param changes a change list * @param exceptions exceptions to collect * @return sorted changes */ private static Map<VirtualFile, Collection<Change>> sortChangesByGitRoot(@NotNull List<Change> changes, List<VcsException> exceptions) { Map<VirtualFile, Collection<Change>> result = new HashMap<VirtualFile, Collection<Change>>(); for (Change change : changes) { final ContentRevision afterRevision = change.getAfterRevision(); final ContentRevision beforeRevision = change.getBeforeRevision(); // nothing-to-nothing change cannot happen. assert beforeRevision != null || afterRevision != null; // note that any path will work, because changes could happen within single vcs root final FilePath filePath = afterRevision != null ? afterRevision.getFile() : beforeRevision.getFile(); final VirtualFile vcsRoot; try { // the parent paths for calculating roots in order to account for submodules that contribute // to the parent change. The path "." is never is valid change, so there should be no problem // with it. vcsRoot = GitUtil.getGitRoot(filePath.getParentPath()); } catch (VcsException e) { exceptions.add(e); continue; } Collection<Change> changeList = result.get(vcsRoot); if (changeList == null) { changeList = new ArrayList<Change>(); result.put(vcsRoot, changeList); } changeList.add(change); } return result; } /** * Mark root as dirty * * @param root a vcs root to rescan */ private void markRootDirty(final VirtualFile root) { // Note that the root is invalidated because changes are detected per-root anyway. // Otherwise it is not possible to detect moves. myDirtyScopeManager.dirDirtyRecursively(root); } public void reset() { myNextCommitAmend = false; myNextCommitAuthor = null; myNextCommitIsPushed = null; myNextCommitAuthorDate = null; } /** * Checkin options for git */ private class GitCheckinOptions implements CheckinChangeListSpecificComponent { /** * A container panel */ private final JPanel myPanel; /** * The author ComboBox, the combobox contains previously selected authors. */ private final JComboBox myAuthor; /** * The amend checkbox */ private final JCheckBox myAmend; private Date myAuthorDate; /** * A constructor * * @param project * @param roots */ GitCheckinOptions(Project project, Collection<VirtualFile> roots) { myPanel = new JPanel(new GridBagLayout()); final Insets insets = new Insets(2, 2, 2, 2); // add authors drop down GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST; c.insets = insets; final JLabel authorLabel = new JLabel(GitBundle.message("commit.author")); myPanel.add(authorLabel, c); c = new GridBagConstraints(); c.anchor = GridBagConstraints.CENTER; c.insets = insets; c.gridx = 1; c.gridy = 0; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; final List<String> usersList = getUsersList(project, roots); final Set<String> authors = usersList == null ? new HashSet<String>() : new HashSet<String>(usersList); ContainerUtil.addAll(authors, mySettings.getCommitAuthors()); List<String> list = new ArrayList<String>(authors); Collections.sort(list); list = ObjectsConvertor.convert(list, new Convertor<String, String>() { @Override public String convert(String o) { return StringUtil.shortenTextWithEllipsis(o, 30, 0); } }); myAuthor = new JComboBox(ArrayUtil.toObjectArray(list)); myAuthor.insertItemAt("", 0); myAuthor.setSelectedItem(""); myAuthor.setEditable(true); authorLabel.setLabelFor(myAuthor); myAuthor.setToolTipText(GitBundle.getString("commit.author.tooltip")); myPanel.add(myAuthor, c); // add amend checkbox c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.anchor = GridBagConstraints.CENTER; c.insets = insets; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; myAmend = new NonFocusableCheckBox(GitBundle.getString("commit.amend")); myAmend.setMnemonic('m'); myAmend.setSelected(false); myAmend.setToolTipText(GitBundle.getString("commit.amend.tooltip")); myPanel.add(myAmend, c); } private List<String> getUsersList(final Project project, final Collection<VirtualFile> roots) { return NewGitUsersComponent.getInstance(project).get(); } /** * {@inheritDoc} */ public JComponent getComponent() { return myPanel; } /** * {@inheritDoc} */ public void refresh() { myAuthor.setSelectedItem(""); myAmend.setSelected(false); reset(); } /** * {@inheritDoc} */ public void saveState() { String author = (String)myAuthor.getEditor().getItem(); myNextCommitAuthor = author.length() == 0 ? null : author; if (author.length() == 0) { myNextCommitAuthor = null; } else { myNextCommitAuthor = author; mySettings.saveCommitAuthor(author); } myNextCommitAmend = myAmend.isSelected(); myNextCommitAuthorDate = myAuthorDate; } /** * {@inheritDoc} */ public void restoreState() { refresh(); } @Override public void onChangeListSelected(LocalChangeList list) { Object data = list.getData(); if (data instanceof GitHeavyCommit) { GitHeavyCommit commit = (GitHeavyCommit)data; String author = String.format("%s <%s>", commit.getAuthor(), commit.getAuthorEmail()); myAuthor.getEditor().setItem(author); myAuthorDate = new Date(commit.getAuthorTime()); } } } public void setNextCommitIsPushed(Boolean nextCommitIsPushed) { myNextCommitIsPushed = nextCommitIsPushed; } }
plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.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 git4idea.checkin; import com.intellij.CommonBundle; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.CheckinProjectPanel; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ObjectsConvertor; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.changes.ui.SelectFilePathsDialog; import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent; import com.intellij.openapi.vcs.checkin.CheckinEnvironment; import com.intellij.openapi.vcs.ui.RefreshableOnComponent; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.util.ArrayUtil; import com.intellij.util.FunctionUtil; import com.intellij.util.NullableFunction; import com.intellij.util.PairConsumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.UIUtil; import com.intellij.vcsUtil.VcsFileUtil; import com.intellij.vcsUtil.VcsUtil; import git4idea.GitPlatformFacade; import git4idea.GitUtil; import git4idea.commands.GitCommand; import git4idea.commands.GitSimpleHandler; import git4idea.config.GitConfigUtil; import git4idea.config.GitVcsSettings; import git4idea.history.NewGitUsersComponent; import git4idea.history.browser.GitHeavyCommit; import git4idea.i18n.GitBundle; import git4idea.push.GitPusher; import git4idea.repo.GitRepositoryFiles; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitFileUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; /** * Git environment for commit operations. */ public class GitCheckinEnvironment implements CheckinEnvironment { private static final Logger log = Logger.getInstance(GitCheckinEnvironment.class.getName()); @NonNls private static final String GIT_COMMIT_MSG_FILE_PREFIX = "git-commit-msg-"; // the file name prefix for commit message file @NonNls private static final String GIT_COMMIT_MSG_FILE_EXT = ".txt"; // the file extension for commit message file private final Project myProject; public static final SimpleDateFormat COMMIT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private final VcsDirtyScopeManager myDirtyScopeManager; private final GitVcsSettings mySettings; private String myNextCommitAuthor = null; // The author for the next commit private boolean myNextCommitAmend; // If true, the next commit is amended private Boolean myNextCommitIsPushed = null; // The push option of the next commit private Date myNextCommitAuthorDate; public GitCheckinEnvironment(@NotNull Project project, @NotNull final VcsDirtyScopeManager dirtyScopeManager, final GitVcsSettings settings) { myProject = project; myDirtyScopeManager = dirtyScopeManager; mySettings = settings; } public boolean keepChangeListAfterCommit(ChangeList changeList) { return false; } @Override public boolean isRefreshAfterCommitNeeded() { return false; } @Nullable public RefreshableOnComponent createAdditionalOptionsPanel(CheckinProjectPanel panel, PairConsumer<Object, Object> additionalDataConsumer) { return new GitCheckinOptions(myProject, panel.getRoots()); } @Nullable public String getDefaultMessageFor(FilePath[] filesToCheckin) { StringBuilder rc = new StringBuilder(); for (VirtualFile root : GitUtil.gitRoots(Arrays.asList(filesToCheckin))) { VirtualFile mergeMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_MERGE_MSG); VirtualFile squashMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_SQUASH_MSG); if (mergeMsg != null || squashMsg != null) { try { String encoding = GitConfigUtil.getCommitEncoding(myProject, root); if (mergeMsg != null) { rc.append(FileUtil.loadFileText(new File(mergeMsg.getPath()), encoding)); } if (squashMsg != null) { rc.append(FileUtil.loadFileText(new File(squashMsg.getPath()), encoding)); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Unable to load merge message", e); } } } } if (rc.length() != 0) { return rc.toString(); } return null; } public String getHelpId() { return null; } public String getCheckinOperationName() { return GitBundle.getString("commit.action.name"); } public List<VcsException> commit(@NotNull List<Change> changes, @NotNull String message, @NotNull NullableFunction<Object, Object> parametersHolder, Set<String> feedback) { List<VcsException> exceptions = new ArrayList<VcsException>(); Map<VirtualFile, Collection<Change>> sortedChanges = sortChangesByGitRoot(changes, exceptions); log.assertTrue(!sortedChanges.isEmpty(), "Trying to commit an empty list of changes: " + changes); for (Map.Entry<VirtualFile, Collection<Change>> entry : sortedChanges.entrySet()) { final VirtualFile root = entry.getKey(); try { File messageFile = createMessageFile(root, message); try { final Set<FilePath> added = new HashSet<FilePath>(); final Set<FilePath> removed = new HashSet<FilePath>(); for (Change change : entry.getValue()) { switch (change.getType()) { case NEW: case MODIFICATION: added.add(change.getAfterRevision().getFile()); break; case DELETED: removed.add(change.getBeforeRevision().getFile()); break; case MOVED: FilePath afterPath = change.getAfterRevision().getFile(); FilePath beforePath = change.getBeforeRevision().getFile(); added.add(afterPath); if (!GitFileUtils.shouldIgnoreCaseChange(afterPath.getPath(), beforePath.getPath())) { removed.add(beforePath); } break; default: throw new IllegalStateException("Unknown change type: " + change.getType()); } } try { try { Set<FilePath> files = new HashSet<FilePath>(); files.addAll(added); files.addAll(removed); commit(myProject, root, files, messageFile, myNextCommitAuthor, myNextCommitAmend, myNextCommitAuthorDate); } catch (VcsException ex) { PartialOperation partialOperation = isMergeCommit(ex); if (partialOperation == PartialOperation.NONE) { throw ex; } if (!mergeCommit(myProject, root, added, removed, messageFile, myNextCommitAuthor, exceptions, partialOperation)) { throw ex; } } } finally { if (!messageFile.delete()) { log.warn("Failed to remove temporary file: " + messageFile); } } } catch (VcsException e) { exceptions.add(e); } } catch (IOException ex) { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Creation of commit message file failed", ex)); } } if (myNextCommitIsPushed != null && myNextCommitIsPushed.booleanValue() && exceptions.isEmpty()) { // push UIUtil.invokeLaterIfNeeded(new Runnable() { public void run() { GitPusher.showPushDialogAndPerformPush(myProject, ServiceManager.getService(myProject, GitPlatformFacade.class)); } }); } return exceptions; } public List<VcsException> commit(List<Change> changes, String preparedComment) { return commit(changes, preparedComment, FunctionUtil.<Object, Object>nullConstant(), null); } /** * Preform a merge commit * * * @param project a project * @param root a vcs root * @param added added files * @param removed removed files * @param messageFile a message file for commit * @param author an author * @param exceptions the list of exceptions to report * @param partialOperation * @return true if merge commit was successful */ private static boolean mergeCommit(final Project project, final VirtualFile root, final Set<FilePath> added, final Set<FilePath> removed, final File messageFile, final String author, List<VcsException> exceptions, @NotNull final PartialOperation partialOperation) { HashSet<FilePath> realAdded = new HashSet<FilePath>(); HashSet<FilePath> realRemoved = new HashSet<FilePath>(); // perform diff GitSimpleHandler diff = new GitSimpleHandler(project, root, GitCommand.DIFF); diff.setSilent(true); diff.setStdoutSuppressed(true); diff.addParameters("--diff-filter=ADMRUX", "--name-status", "HEAD"); diff.endOptions(); String output; try { output = diff.run(); } catch (VcsException ex) { exceptions.add(ex); return false; } String rootPath = root.getPath(); for (StringTokenizer lines = new StringTokenizer(output, "\n", false); lines.hasMoreTokens();) { String line = lines.nextToken().trim(); if (line.length() == 0) { continue; } String[] tk = line.split("\t"); switch (tk[0].charAt(0)) { case 'M': case 'A': realAdded.add(VcsUtil.getFilePath(rootPath + "/" + tk[1])); break; case 'D': realRemoved.add(VcsUtil.getFilePathForDeletedFile(rootPath + "/" + tk[1], false)); break; default: throw new IllegalStateException("Unexpected status: " + line); } } realAdded.removeAll(added); realRemoved.removeAll(removed); if (realAdded.size() != 0 || realRemoved.size() != 0) { final List<FilePath> files = new ArrayList<FilePath>(); files.addAll(realAdded); files.addAll(realRemoved); final Ref<Boolean> mergeAll = new Ref<Boolean>(); try { GuiUtils.runOrInvokeAndWait(new Runnable() { public void run() { String message = GitBundle.message("commit.partial.merge.message", partialOperation.getName()); SelectFilePathsDialog dialog = new SelectFilePathsDialog(project, files, message, null, "Commit All Files", CommonBundle.getCancelButtonText(), false); dialog.setTitle(GitBundle.getString("commit.partial.merge.title")); dialog.show(); mergeAll.set(dialog.isOK()); } }); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Unable to invoke a message box on AWT thread", ex); } if (!mergeAll.get()) { return false; } // update non-indexed files if (!updateIndex(project, root, realAdded, realRemoved, exceptions)) { return false; } for (FilePath f : realAdded) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } for (FilePath f : realRemoved) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } } // perform merge commit try { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.addParameters("-F", messageFile.getAbsolutePath()); if (author != null) { handler.addParameters("--author=" + author); } handler.endOptions(); handler.run(); GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } catch (VcsException ex) { exceptions.add(ex); return false; } return true; } /** * Check if commit has failed due to unfinished merge or cherry-pick. * * * @param ex an exception to examine * @return true if exception means that there is a partial commit during merge */ private static PartialOperation isMergeCommit(final VcsException ex) { String message = ex.getMessage(); if (message.contains("fatal: cannot do a partial commit during a merge")) { return PartialOperation.MERGE; } if (message.contains("fatal: cannot do a partial commit during a cherry-pick")) { return PartialOperation.CHERRY_PICK; } return PartialOperation.NONE; } /** * Update index (delete and remove files) * * @param project the project * @param root a vcs root * @param added added/modified files to commit * @param removed removed files to commit * @param exceptions a list of exceptions to update * @return true if index was updated successfully */ private static boolean updateIndex(final Project project, final VirtualFile root, final Collection<FilePath> added, final Collection<FilePath> removed, final List<VcsException> exceptions) { boolean rc = true; if (!added.isEmpty()) { try { GitFileUtils.addPaths(project, root, added); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } if (!removed.isEmpty()) { try { GitFileUtils.delete(project, root, removed, "--ignore-unmatch"); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } return rc; } /** * Create a file that contains the specified message * * @param root a git repository root * @param message a message to write * @return a file reference * @throws IOException if file cannot be created */ private File createMessageFile(VirtualFile root, final String message) throws IOException { // filter comment lines File file = FileUtil.createTempFile(GIT_COMMIT_MSG_FILE_PREFIX, GIT_COMMIT_MSG_FILE_EXT); file.deleteOnExit(); @NonNls String encoding = GitConfigUtil.getCommitEncoding(myProject, root); Writer out = new OutputStreamWriter(new FileOutputStream(file), encoding); try { out.write(message); } finally { out.close(); } return file; } /** * {@inheritDoc} */ public List<VcsException> scheduleMissingFileForDeletion(List<FilePath> files) { ArrayList<VcsException> rc = new ArrayList<VcsException>(); Map<VirtualFile, List<FilePath>> sortedFiles; try { sortedFiles = GitUtil.sortFilePathsByGitRoot(files); } catch (VcsException e) { rc.add(e); return rc; } for (Map.Entry<VirtualFile, List<FilePath>> e : sortedFiles.entrySet()) { try { final VirtualFile root = e.getKey(); GitFileUtils.delete(myProject, root, e.getValue()); markRootDirty(root); } catch (VcsException ex) { rc.add(ex); } } return rc; } /** * Prepare delete files handler. * * * * @param project the project * @param root a vcs root * @param files a files to commit * @param message a message file to use * @param nextCommitAuthor a author for the next commit * @param nextCommitAmend true, if the commit should be amended * @param nextCommitAuthorDate Author date timestamp to override the date of the commit or null if this overriding is not needed. * @return a simple handler that does the task * @throws VcsException in case of git problem */ private static void commit(Project project, VirtualFile root, Collection<FilePath> files, File message, final String nextCommitAuthor, boolean nextCommitAmend, Date nextCommitAuthorDate) throws VcsException { boolean amend = nextCommitAmend; for (List<String> paths : VcsFileUtil.chunkPaths(root, files)) { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); if (amend) { handler.addParameters("--amend"); } else { amend = true; } handler.addParameters("--only", "-F", message.getAbsolutePath()); if (nextCommitAuthor != null) { handler.addParameters("--author=" + nextCommitAuthor); } if (nextCommitAuthorDate != null) { handler.addParameters("--date", COMMIT_DATE_FORMAT.format(nextCommitAuthorDate)); } handler.endOptions(); handler.addParameters(paths); handler.run(); } if (!project.isDisposed()) { GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } } /** * {@inheritDoc} */ public List<VcsException> scheduleUnversionedFilesForAddition(List<VirtualFile> files) { ArrayList<VcsException> rc = new ArrayList<VcsException>(); Map<VirtualFile, List<VirtualFile>> sortedFiles; try { sortedFiles = GitUtil.sortFilesByGitRoot(files); } catch (VcsException e) { rc.add(e); return rc; } for (Map.Entry<VirtualFile, List<VirtualFile>> e : sortedFiles.entrySet()) { try { final VirtualFile root = e.getKey(); GitFileUtils.addFiles(myProject, root, e.getValue()); markRootDirty(root); } catch (VcsException ex) { rc.add(ex); } } return rc; } private enum PartialOperation { NONE("none"), MERGE("merge"), CHERRY_PICK("cherry-pick"); private final String myName; PartialOperation(String name) { myName = name; } String getName() { return myName; } } /** * Sort changes by roots * * @param changes a change list * @param exceptions exceptions to collect * @return sorted changes */ private static Map<VirtualFile, Collection<Change>> sortChangesByGitRoot(@NotNull List<Change> changes, List<VcsException> exceptions) { Map<VirtualFile, Collection<Change>> result = new HashMap<VirtualFile, Collection<Change>>(); for (Change change : changes) { final ContentRevision afterRevision = change.getAfterRevision(); final ContentRevision beforeRevision = change.getBeforeRevision(); // nothing-to-nothing change cannot happen. assert beforeRevision != null || afterRevision != null; // note that any path will work, because changes could happen within single vcs root final FilePath filePath = afterRevision != null ? afterRevision.getFile() : beforeRevision.getFile(); final VirtualFile vcsRoot; try { // the parent paths for calculating roots in order to account for submodules that contribute // to the parent change. The path "." is never is valid change, so there should be no problem // with it. vcsRoot = GitUtil.getGitRoot(filePath.getParentPath()); } catch (VcsException e) { exceptions.add(e); continue; } Collection<Change> changeList = result.get(vcsRoot); if (changeList == null) { changeList = new ArrayList<Change>(); result.put(vcsRoot, changeList); } changeList.add(change); } return result; } /** * Mark root as dirty * * @param root a vcs root to rescan */ private void markRootDirty(final VirtualFile root) { // Note that the root is invalidated because changes are detected per-root anyway. // Otherwise it is not possible to detect moves. myDirtyScopeManager.dirDirtyRecursively(root); } public void reset() { myNextCommitAmend = false; myNextCommitAuthor = null; myNextCommitIsPushed = null; myNextCommitAuthorDate = null; } /** * Checkin options for git */ private class GitCheckinOptions implements CheckinChangeListSpecificComponent { /** * A container panel */ private final JPanel myPanel; /** * The author ComboBox, the combobox contains previously selected authors. */ private final JComboBox myAuthor; /** * The amend checkbox */ private final JCheckBox myAmend; private Date myAuthorDate; /** * A constructor * * @param project * @param roots */ GitCheckinOptions(Project project, Collection<VirtualFile> roots) { myPanel = new JPanel(new GridBagLayout()); final Insets insets = new Insets(2, 2, 2, 2); // add authors drop down GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST; c.insets = insets; final JLabel authorLabel = new JLabel(GitBundle.message("commit.author")); myPanel.add(authorLabel, c); c = new GridBagConstraints(); c.anchor = GridBagConstraints.CENTER; c.insets = insets; c.gridx = 1; c.gridy = 0; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; final List<String> usersList = getUsersList(project, roots); final Set<String> authors = usersList == null ? new HashSet<String>() : new HashSet<String>(usersList); ContainerUtil.addAll(authors, mySettings.getCommitAuthors()); List<String> list = new ArrayList<String>(authors); Collections.sort(list); list = ObjectsConvertor.convert(list, new Convertor<String, String>() { @Override public String convert(String o) { return StringUtil.shortenTextWithEllipsis(o, 30, 0); } }); myAuthor = new JComboBox(ArrayUtil.toObjectArray(list)); myAuthor.insertItemAt("", 0); myAuthor.setSelectedItem(""); myAuthor.setEditable(true); authorLabel.setLabelFor(myAuthor); myAuthor.setToolTipText(GitBundle.getString("commit.author.tooltip")); myPanel.add(myAuthor, c); // add amend checkbox c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.anchor = GridBagConstraints.CENTER; c.insets = insets; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; myAmend = new JCheckBox(GitBundle.getString("commit.amend")); myAmend.setMnemonic('m'); myAmend.setSelected(false); myAmend.setToolTipText(GitBundle.getString("commit.amend.tooltip")); myPanel.add(myAmend, c); } private List<String> getUsersList(final Project project, final Collection<VirtualFile> roots) { return NewGitUsersComponent.getInstance(project).get(); } /** * {@inheritDoc} */ public JComponent getComponent() { return myPanel; } /** * {@inheritDoc} */ public void refresh() { myAuthor.setSelectedItem(""); myAmend.setSelected(false); reset(); } /** * {@inheritDoc} */ public void saveState() { String author = (String)myAuthor.getEditor().getItem(); myNextCommitAuthor = author.length() == 0 ? null : author; if (author.length() == 0) { myNextCommitAuthor = null; } else { myNextCommitAuthor = author; mySettings.saveCommitAuthor(author); } myNextCommitAmend = myAmend.isSelected(); myNextCommitAuthorDate = myAuthorDate; } /** * {@inheritDoc} */ public void restoreState() { refresh(); } @Override public void onChangeListSelected(LocalChangeList list) { Object data = list.getData(); if (data instanceof GitHeavyCommit) { GitHeavyCommit commit = (GitHeavyCommit)data; String author = String.format("%s <%s>", commit.getAuthor(), commit.getAuthorEmail()); myAuthor.getEditor().setItem(author); myAuthorDate = new Date(commit.getAuthorTime()); } } } public void setNextCommitIsPushed(Boolean nextCommitIsPushed) { myNextCommitIsPushed = nextCommitIsPushed; } }
"Amend commit" should be non-focusable
plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java
"Amend commit" should be non-focusable
<ide><path>lugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java <ide> import com.intellij.openapi.vcs.ui.RefreshableOnComponent; <ide> import com.intellij.openapi.vfs.VirtualFile; <ide> import com.intellij.ui.GuiUtils; <add>import com.intellij.ui.NonFocusableCheckBox; <ide> import com.intellij.util.ArrayUtil; <ide> import com.intellij.util.FunctionUtil; <ide> import com.intellij.util.NullableFunction; <ide> c.insets = insets; <ide> c.weightx = 1; <ide> c.fill = GridBagConstraints.HORIZONTAL; <del> myAmend = new JCheckBox(GitBundle.getString("commit.amend")); <add> myAmend = new NonFocusableCheckBox(GitBundle.getString("commit.amend")); <ide> myAmend.setMnemonic('m'); <ide> myAmend.setSelected(false); <ide> myAmend.setToolTipText(GitBundle.getString("commit.amend.tooltip"));
Java
agpl-3.0
b6efb9dd4160025e87c379c5d66a7b65c0ee7b01
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
f2ad8d52-2e60-11e5-9284-b827eb9e62be
hello.java
f2a82c54-2e60-11e5-9284-b827eb9e62be
f2ad8d52-2e60-11e5-9284-b827eb9e62be
hello.java
f2ad8d52-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>f2a82c54-2e60-11e5-9284-b827eb9e62be <add>f2ad8d52-2e60-11e5-9284-b827eb9e62be
Java
apache-2.0
1895864d387894802699c4b0ba2c29977941b125
0
shelsonjava/netty,gerdriesselmann/netty,bigheary/netty,firebase/netty,wuyinxian124/netty,huuthang1993/netty,moyiguket/netty,yonglehou/netty-1,nmittler/netty,jdivy/netty,zxhfirefox/netty,lugt/netty,MediumOne/netty,satishsaley/netty,Apache9/netty,hgl888/netty,sameira/netty,chanakaudaya/netty,timboudreau/netty,shism/netty,niuxinghua/netty,afds/netty,shuangqiuan/netty,tempbottle/netty,altihou/netty,yonglehou/netty-1,jenskordowski/netty,windie/netty,slandelle/netty,ioanbsu/netty,satishsaley/netty,JungMinu/netty,danny200309/netty,shism/netty,carlbai/netty,smayoorans/netty,nkhuyu/netty,shuangqiuan/netty,woshilaiceshide/netty,zhoffice/netty,liyang1025/netty,f7753/netty,huanyi0723/netty,luyiisme/netty,ninja-/netty,rovarga/netty,netty/netty,normanmaurer/netty,jenskordowski/netty,golovnin/netty,tempbottle/netty,windie/netty,dongjiaqiang/netty,sammychen105/netty,hepin1989/netty,chrisprobst/netty,olupotd/netty,olupotd/netty,gerdriesselmann/netty,hyangtack/netty,kjniemi/netty,shenguoquan/netty,netty/netty,ngocdaothanh/netty,Apache9/netty,maliqq/netty,sja/netty,MediumOne/netty,develar/netty,moyiguket/netty,liyang1025/netty,chrisprobst/netty,olupotd/netty,louiscryan/netty,daschl/netty,buchgr/netty,AnselQiao/netty,sja/netty,jchambers/netty,gerdriesselmann/netty,netty/netty,slandelle/netty,eonezhang/netty,Kalvar/netty,DolphinZhao/netty,jenskordowski/netty,Spikhalskiy/netty,dongjiaqiang/netty,kjniemi/netty,skyao/netty,IBYoung/netty,CliffYuan/netty,eonezhang/netty,BrunoColin/netty,zzcclp/netty,wuyinxian124/netty,BrunoColin/netty,Techcable/netty,kjniemi/netty,fengjiachun/netty,idelpivnitskiy/netty,caoyanwei/netty,brennangaunce/netty,f7753/netty,mx657649013/netty,seetharamireddy540/netty,AnselQiao/netty,chanakaudaya/netty,serioussam/netty,silvaran/netty,yrcourage/netty,maliqq/netty,imangry/netty-zh,ejona86/netty,SinaTadayon/netty,qingsong-xu/netty,ngocdaothanh/netty,Mounika-Chirukuri/netty,kvr000/netty,andsel/netty,chanakaudaya/netty,sunbeansoft/netty,NiteshKant/netty,JungMinu/netty,AchinthaReemal/netty,liyang1025/netty,gigold/netty,louiscryan/netty,satishsaley/netty,louxiu/netty,sverkera/netty,blademainer/netty,golovnin/netty,Scottmitch/netty,zer0se7en/netty,luyiisme/netty,caoyanwei/netty,hgl888/netty,skyao/netty,tbrooks8/netty,hgl888/netty,huanyi0723/netty,fenik17/netty,jchambers/netty,ijuma/netty,Scottmitch/netty,ajaysarda/netty,woshilaiceshide/netty,chinayin/netty,unei66/netty,cnoldtree/netty,danbev/netty,cnoldtree/netty,serioussam/netty,qingsong-xu/netty,jovezhougang/netty,blademainer/netty,orika/netty,zxhfirefox/netty,eincs/netty,olupotd/netty,mubarak/netty,IBYoung/netty,mcobrien/netty,fantayeneh/netty,jdivy/netty,Spikhalskiy/netty,artgon/netty,seetharamireddy540/netty,fenik17/netty,yipen9/netty,Squarespace/netty,kyle-liu/netty4study,phlizik/netty,zer0se7en/netty,nadeeshaan/netty,nat2013/netty,shelsonjava/netty,liuciuse/netty,afds/netty,Scottmitch/netty,kiril-me/netty,eincs/netty,Alwayswithme/netty,silvaran/netty,fengshao0907/netty,wangyikai/netty,zzcclp/netty,slandelle/netty,shelsonjava/netty,huuthang1993/netty,eonezhang/netty,silvaran/netty,Mounika-Chirukuri/netty,unei66/netty,idelpivnitskiy/netty,develar/netty,gerdriesselmann/netty,lukehutch/netty,mx657649013/netty,luyiisme/netty,seetharamireddy540/netty,Squarespace/netty,ichaki5748/netty,xingguang2013/netty,Kalvar/netty,x1957/netty,hgl888/netty,mcobrien/netty,huuthang1993/netty,youprofit/netty,wangyikai/netty,xiexingguang/netty,Kalvar/netty,lukw00/netty,MediumOne/netty,chinayin/netty,DavidAlphaFox/netty,brennangaunce/netty,KatsuraKKKK/netty,imangry/netty-zh,SinaTadayon/netty,ninja-/netty,zhoffice/netty,zhoffice/netty,lznhust/netty,zxhfirefox/netty,exinguu/netty,tbrooks8/netty,caoyanwei/netty,huanyi0723/netty,mcobrien/netty,liuciuse/netty,Squarespace/netty,BrunoColin/netty,KatsuraKKKK/netty,x1957/netty,ioanbsu/netty,liuciuse/netty,fengshao0907/netty,clebertsuconic/netty,lukehutch/netty,ngocdaothanh/netty,fengshao0907/netty,Kingson4Wu/netty,junjiemars/netty,ioanbsu/netty,lugt/netty,nayato/netty,BrunoColin/netty,purplefox/netty-4.0.2.8-hacked,orika/netty,yrcourage/netty,tempbottle/netty,ijuma/netty,johnou/netty,LuminateWireless/netty,liyang1025/netty,LuminateWireless/netty,Kingson4Wu/netty,Apache9/netty,nayato/netty,afds/netty,mway08/netty,LuminateWireless/netty,mx657649013/netty,johnou/netty,hyangtack/netty,fengjiachun/netty,huuthang1993/netty,Apache9/netty,smayoorans/netty,rovarga/netty,KeyNexus/netty,sunbeansoft/netty,normanmaurer/netty,timboudreau/netty,ninja-/netty,fantayeneh/netty,jchambers/netty,afredlyj/learn-netty,ijuma/netty,niuxinghua/netty,gigold/netty,ejona86/netty,ngocdaothanh/netty,AchinthaReemal/netty,DolphinZhao/netty,liyang1025/netty,gigold/netty,blademainer/netty,xiongzheng/netty,caoyanwei/netty,CodingFabian/netty,golovnin/netty,afds/netty,normanmaurer/netty,ioanbsu/netty,lukw00/netty,DavidAlphaFox/netty,mikkokar/netty,gigold/netty,yrcourage/netty,sameira/netty,caoyanwei/netty,mway08/netty,purplefox/netty-4.0.2.8-hacked,cnoldtree/netty,ngocdaothanh/netty,timboudreau/netty,doom369/netty,netty/netty,bob329/netty,woshilaiceshide/netty,kvr000/netty,sja/netty,unei66/netty,fengjiachun/netty,firebase/netty,mosoft521/netty,balaprasanna/netty,xiexingguang/netty,ejona86/netty,hyangtack/netty,bigheary/netty,eincs/netty,xingguang2013/netty,lightsocks/netty,jchambers/netty,s-gheldd/netty,yrcourage/netty,SinaTadayon/netty,mway08/netty,yipen9/netty,sammychen105/netty,mubarak/netty,silvaran/netty,nadeeshaan/netty,duqiao/netty,alkemist/netty,Kingson4Wu/netty,yawkat/netty,firebase/netty,wuxiaowei907/netty,bob329/netty,Mounika-Chirukuri/netty,kiril-me/netty,fenik17/netty,unei66/netty,eincs/netty,skyao/netty,altihou/netty,zhoffice/netty,nkhuyu/netty,Squarespace/netty,slandelle/netty,IBYoung/netty,balaprasanna/netty,windie/netty,xiexingguang/netty,zer0se7en/netty,AnselQiao/netty,jdivy/netty,AnselQiao/netty,balaprasanna/netty,ioanbsu/netty,kvr000/netty,ichaki5748/netty,maliqq/netty,imangry/netty-zh,jovezhougang/netty,mcobrien/netty,brennangaunce/netty,smayoorans/netty,lznhust/netty,kiril-me/netty,djchen/netty,ejona86/netty,jenskordowski/netty,zhujingling/netty,kjniemi/netty,alkemist/netty,nayato/netty,zzcclp/netty,ijuma/netty,orika/netty,Squarespace/netty,carl-mastrangelo/netty,eonezhang/netty,yawkat/netty,louiscryan/netty,tbrooks8/netty,Scottmitch/netty,chinayin/netty,xingguang2013/netty,Alwayswithme/netty,Apache9/netty,sverkera/netty,Techcable/netty,altihou/netty,hepin1989/netty,Kalvar/netty,huanyi0723/netty,Kingson4Wu/netty,jovezhougang/netty,netty/netty,balaprasanna/netty,x1957/netty,idelpivnitskiy/netty,moyiguket/netty,lightsocks/netty,louxiu/netty,timboudreau/netty,carlbai/netty,carl-mastrangelo/netty,codevelop/netty,joansmith/netty,imangry/netty-zh,zhujingling/netty,Techcable/netty,fantayeneh/netty,DavidAlphaFox/netty,Alwayswithme/netty,nadeeshaan/netty,moyiguket/netty,BrunoColin/netty,mosoft521/netty,zer0se7en/netty,Mounika-Chirukuri/netty,andsel/netty,CodingFabian/netty,mx657649013/netty,wuyinxian124/netty,mosoft521/netty,mway08/netty,rovarga/netty,louiscryan/netty,niuxinghua/netty,ajaysarda/netty,liuciuse/netty,junjiemars/netty,shuangqiuan/netty,duqiao/netty,shelsonjava/netty,nat2013/netty,nkhuyu/netty,qingsong-xu/netty,luyiisme/netty,ninja-/netty,daschl/netty,jchambers/netty,jongyeol/netty,JungMinu/netty,fengjiachun/netty,imangry/netty-zh,exinguu/netty,daschl/netty,clebertsuconic/netty,Scottmitch/netty,AnselQiao/netty,huuthang1993/netty,codevelop/netty,idelpivnitskiy/netty,shuangqiuan/netty,bob329/netty,cnoldtree/netty,windie/netty,bryce-anderson/netty,zer0se7en/netty,seetharamireddy540/netty,mosoft521/netty,yrcourage/netty,idelpivnitskiy/netty,IBYoung/netty,andsel/netty,zhoffice/netty,luyiisme/netty,AchinthaReemal/netty,carlbai/netty,zxhfirefox/netty,youprofit/netty,jongyeol/netty,mcanthony/netty,sameira/netty,drowning/netty,lznhust/netty,WangJunTYTL/netty,xiexingguang/netty,xiongzheng/netty,brennangaunce/netty,lightsocks/netty,balaprasanna/netty,yipen9/netty,qingsong-xu/netty,aperepel/netty,WangJunTYTL/netty,fantayeneh/netty,nkhuyu/netty,altihou/netty,f7753/netty,x1957/netty,chanakaudaya/netty,xiongzheng/netty,CodingFabian/netty,niuxinghua/netty,andsel/netty,wangyikai/netty,lightsocks/netty,JungMinu/netty,louxiu/netty,jroper/netty,qingsong-xu/netty,afredlyj/learn-netty,lznhust/netty,joansmith/netty,lznhust/netty,danny200309/netty,mikkokar/netty,lugt/netty,lugt/netty,drowning/netty,Alwayswithme/netty,CliffYuan/netty,moyiguket/netty,youprofit/netty,WangJunTYTL/netty,fenik17/netty,DolphinZhao/netty,shuangqiuan/netty,LuminateWireless/netty,castomer/netty,lightsocks/netty,ifesdjeen/netty,gerdriesselmann/netty,alkemist/netty,WangJunTYTL/netty,dongjiaqiang/netty,nayato/netty,lukw00/netty,maliqq/netty,serioussam/netty,sammychen105/netty,serioussam/netty,mikkokar/netty,joansmith/netty,kiril-me/netty,chrisprobst/netty,yawkat/netty,mcobrien/netty,AchinthaReemal/netty,blucas/netty,exinguu/netty,hepin1989/netty,serioussam/netty,bigheary/netty,CodingFabian/netty,olupotd/netty,zxhfirefox/netty,liuciuse/netty,wangyikai/netty,ijuma/netty,Techcable/netty,skyao/netty,orika/netty,hgl888/netty,drowning/netty,purplefox/netty-4.0.2.8-hacked,wuxiaowei907/netty,eincs/netty,cnoldtree/netty,youprofit/netty,tempbottle/netty,jongyeol/netty,duqiao/netty,orika/netty,CodingFabian/netty,doom369/netty,nat2013/netty,fengjiachun/netty,sunbeansoft/netty,wuxiaowei907/netty,pengzj/netty,lukw00/netty,zhujingling/netty,blucas/netty,joansmith/netty,tbrooks8/netty,louiscryan/netty,zhujingling/netty,shism/netty,shelsonjava/netty,chanakaudaya/netty,menacher/netty,fantayeneh/netty,xingguang2013/netty,rovarga/netty,nadeeshaan/netty,menacher/netty,KeyNexus/netty,sja/netty,exinguu/netty,wuxiaowei907/netty,djchen/netty,chinayin/netty,timboudreau/netty,codevelop/netty,tbrooks8/netty,blucas/netty,sameira/netty,shenguoquan/netty,s-gheldd/netty,doom369/netty,hepin1989/netty,artgon/netty,afds/netty,altihou/netty,johnou/netty,clebertsuconic/netty,ajaysarda/netty,djchen/netty,junjiemars/netty,phlizik/netty,blucas/netty,DolphinZhao/netty,carl-mastrangelo/netty,fenik17/netty,Techcable/netty,Kalvar/netty,s-gheldd/netty,unei66/netty,chinayin/netty,mway08/netty,mcanthony/netty,jovezhougang/netty,blucas/netty,wangyikai/netty,chrisprobst/netty,xiongzheng/netty,NiteshKant/netty,ichaki5748/netty,Mounika-Chirukuri/netty,sameira/netty,dongjiaqiang/netty,buchgr/netty,exinguu/netty,mcanthony/netty,yawkat/netty,NiteshKant/netty,chrisprobst/netty,blademainer/netty,alkemist/netty,louxiu/netty,mubarak/netty,johnou/netty,zzcclp/netty,lukw00/netty,jongyeol/netty,sunbeansoft/netty,maliqq/netty,pengzj/netty,windie/netty,afredlyj/learn-netty,huanyi0723/netty,shism/netty,andsel/netty,IBYoung/netty,zhujingling/netty,djchen/netty,ejona86/netty,KatsuraKKKK/netty,SinaTadayon/netty,artgon/netty,x1957/netty,Spikhalskiy/netty,bryce-anderson/netty,nkhuyu/netty,pengzj/netty,woshilaiceshide/netty,johnou/netty,duqiao/netty,yonglehou/netty-1,bigheary/netty,drowning/netty,blademainer/netty,Spikhalskiy/netty,bob329/netty,jdivy/netty,gigold/netty,firebase/netty,KatsuraKKKK/netty,lugt/netty,nadeeshaan/netty,castomer/netty,golovnin/netty,phlizik/netty,yonglehou/netty-1,sverkera/netty,mikkokar/netty,zzcclp/netty,danny200309/netty,sja/netty,sverkera/netty,yonglehou/netty-1,bryce-anderson/netty,mikkokar/netty,dongjiaqiang/netty,golovnin/netty,silvaran/netty,danbev/netty,f7753/netty,artgon/netty,Kingson4Wu/netty,ajaysarda/netty,mcanthony/netty,mx657649013/netty,shenguoquan/netty,danny200309/netty,wuxiaowei907/netty,kjniemi/netty,sverkera/netty,bryce-anderson/netty,ninja-/netty,clebertsuconic/netty,jdivy/netty,s-gheldd/netty,danny200309/netty,xingguang2013/netty,woshilaiceshide/netty,junjiemars/netty,clebertsuconic/netty,junjiemars/netty,AchinthaReemal/netty,bob329/netty,kvr000/netty,duqiao/netty,jongyeol/netty,xiexingguang/netty,seetharamireddy540/netty,shism/netty,kyle-liu/netty4study,lukehutch/netty,nmittler/netty,jovezhougang/netty,bryce-anderson/netty,tempbottle/netty,yawkat/netty,ichaki5748/netty,djchen/netty,Alwayswithme/netty,MediumOne/netty,louxiu/netty,danbev/netty,purplefox/netty-4.0.2.8-hacked,codevelop/netty,f7753/netty,pengzj/netty,SinaTadayon/netty,shenguoquan/netty,kvr000/netty,ajaysarda/netty,s-gheldd/netty,mubarak/netty,DavidAlphaFox/netty,normanmaurer/netty,carlbai/netty,shenguoquan/netty,joansmith/netty,KatsuraKKKK/netty,doom369/netty,castomer/netty,carlbai/netty,buchgr/netty,hyangtack/netty,phlizik/netty,satishsaley/netty,mubarak/netty,normanmaurer/netty,kiril-me/netty,NiteshKant/netty,jenskordowski/netty,alkemist/netty,carl-mastrangelo/netty,castomer/netty,lukehutch/netty,xiongzheng/netty,youprofit/netty,sunbeansoft/netty,ifesdjeen/netty,carl-mastrangelo/netty,yipen9/netty,Spikhalskiy/netty,skyao/netty,NiteshKant/netty,smayoorans/netty,danbev/netty,buchgr/netty,DolphinZhao/netty,nayato/netty,mcanthony/netty,niuxinghua/netty,LuminateWireless/netty,eonezhang/netty,wuyinxian124/netty,WangJunTYTL/netty,MediumOne/netty,ichaki5748/netty,nmittler/netty,doom369/netty,bigheary/netty,castomer/netty,satishsaley/netty,lukehutch/netty,artgon/netty,mosoft521/netty,danbev/netty,brennangaunce/netty,smayoorans/netty
/* * JBoss, Home of Professional Open Source * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import static org.jboss.netty.channel.Channels.*; import static org.jboss.netty.channel.socket.http.HttpTunnelingContextListener.*; import static org.jboss.netty.channel.socket.http.HttpTunnelingServlet.*; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.local.LocalAddress; /** * A session listener that uses the client bootstrap to create a channel. * * @author The Netty Project ([email protected]) * @author Andy Taylor ([email protected]) * @version $Rev$, $Date$ */ public class HttpTunnelingSessionListener implements HttpSessionListener, ChannelHandler { public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); ClientBootstrap bootstrap = (ClientBootstrap) session.getServletContext().getAttribute(BOOTSTRAP_PROP); Boolean streaming = (Boolean) session.getServletContext().getAttribute(STREAMING_PROP); if (streaming) { session.setMaxInactiveInterval(-1); } final HttpTunnelingChannelHandler handler = new HttpTunnelingChannelHandler(streaming, session, (Long) session.getServletContext().getAttribute(RECONNECT_PROP)); session.setAttribute(HANDLER_PROP, handler); bootstrap.setPipelineFactory(new HttpTunnelingChannelPipelineFactory(handler)); ChannelFuture future = bootstrap.connect(new LocalAddress((String) session.getServletContext().getAttribute(SERVER_CHANNEL_PROP))); future.awaitUninterruptibly(); final Channel ch = future.getChannel(); session.setAttribute(CHANNEL_PROP, ch); } public void sessionDestroyed(HttpSessionEvent event) { Channel channel = (Channel) event.getSession().getAttribute(CHANNEL_PROP); if (channel != null) { channel.close(); } } /** * @author The Netty Project ([email protected]) * @author Trustin Lee ([email protected]) * @version $Rev$, $Date$ */ private static final class HttpTunnelingChannelPipelineFactory implements ChannelPipelineFactory { private final HttpTunnelingChannelHandler handler; HttpTunnelingChannelPipelineFactory(HttpTunnelingChannelHandler handler) { this.handler = handler; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast(HttpTunnelingSessionListener.class.getName(), handler); return pipeline; } } }
src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSessionListener.java
/* * JBoss, Home of Professional Open Source * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import static org.jboss.netty.channel.Channels.*; import static org.jboss.netty.channel.socket.http.HttpTunnelingContextListener.*; import static org.jboss.netty.channel.socket.http.HttpTunnelingServlet.*; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.local.LocalAddress; /** * A session listener that uses the client bootstrap to create a channel. * * @author The Netty Project ([email protected]) * @author Andy Taylor ([email protected]) * @version $Rev$, $Date$ */ public class HttpTunnelingSessionListener implements HttpSessionListener, ChannelHandler { public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); ClientBootstrap bootstrap = (ClientBootstrap) session.getServletContext().getAttribute(BOOTSTRAP_PROP); Boolean streaming = (Boolean) session.getServletContext().getAttribute(STREAMING_PROP); if(streaming) { session.setMaxInactiveInterval(-1); } final HttpTunnelingChannelHandler handler = new HttpTunnelingChannelHandler(streaming, session, (Long) session.getServletContext().getAttribute(RECONNECT_PROP)); session.setAttribute(HANDLER_PROP, handler); bootstrap.setPipelineFactory(new HttpTunnelingChannelPipelineFactory(handler)); ChannelFuture future = bootstrap.connect(new LocalAddress((String) session.getServletContext().getAttribute(SERVER_CHANNEL_PROP))); future.awaitUninterruptibly(); final Channel ch = future.getChannel(); session.setAttribute(CHANNEL_PROP, ch); } public void sessionDestroyed(HttpSessionEvent event) { Channel channel = (Channel) event.getSession().getAttribute(CHANNEL_PROP); if (channel != null) { channel.close(); } } /** * @author The Netty Project ([email protected]) * @author Trustin Lee ([email protected]) * @version $Rev$, $Date$ */ private static final class HttpTunnelingChannelPipelineFactory implements ChannelPipelineFactory { private final HttpTunnelingChannelHandler handler; HttpTunnelingChannelPipelineFactory(HttpTunnelingChannelHandler handler) { this.handler = handler; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast(HttpTunnelingSessionListener.class.getName(), handler); return pipeline; } } }
Code style
src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSessionListener.java
Code style
<ide><path>rc/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSessionListener.java <ide> HttpSession session = event.getSession(); <ide> ClientBootstrap bootstrap = (ClientBootstrap) session.getServletContext().getAttribute(BOOTSTRAP_PROP); <ide> Boolean streaming = (Boolean) session.getServletContext().getAttribute(STREAMING_PROP); <del> if(streaming) { <add> if (streaming) { <ide> session.setMaxInactiveInterval(-1); <ide> } <ide> final HttpTunnelingChannelHandler handler = new HttpTunnelingChannelHandler(streaming, session, (Long) session.getServletContext().getAttribute(RECONNECT_PROP));
Java
lgpl-2.1
c3c59ed7afe018934c302591616cedf37ef16875
0
xwiki/xwiki-commons,xwiki/xwiki-commons
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.job; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import javax.inject.Inject; import org.slf4j.Logger; import org.xwiki.component.annotation.InstantiationStrategy; import org.xwiki.component.descriptor.ComponentInstantiationStrategy; import org.xwiki.component.manager.ComponentManager; import org.xwiki.job.event.JobFinishedEvent; import org.xwiki.job.event.JobStartedEvent; import org.xwiki.job.event.status.JobStatus; import org.xwiki.job.event.status.JobStatus.State; import org.xwiki.job.event.status.PopLevelProgressEvent; import org.xwiki.job.event.status.PushLevelProgressEvent; import org.xwiki.job.event.status.StepProgressEvent; import org.xwiki.job.internal.AbstractJobStatus; import org.xwiki.job.internal.DefaultJobStatus; import org.xwiki.job.internal.JobStatusStorage; import org.xwiki.logging.LoggerManager; import org.xwiki.observation.ObservationManager; /** * Base class for {@link Job} implementations. * * @param <R> the request type associated to the job * @version $Id$ * @since 4.0M1 */ @InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP) public abstract class AbstractJob<R extends Request> implements Job { /** * Component manager. */ @Inject protected ComponentManager componentManager; /** * Used to send extensions installation and upgrade related events. */ @Inject protected ObservationManager observationManager; /** * Used to isolate job related log. */ @Inject protected LoggerManager loggerManager; /** * Used to store the results of the jobs execution. */ @Inject protected JobStatusStorage storage; /** * The logger to log. */ @Inject protected Logger logger; /** * Used to set the current context. */ @Inject protected JobContext jobContext; /** * The job request. */ protected R request; /** * @see #getStatus() */ protected AbstractJobStatus<R> status; /** * Main lock guarding all access. */ private final ReentrantLock lock = new ReentrantLock(); /** * Condition for waiting takes. */ private final Condition finishedCondition = lock.newCondition(); @Override public R getRequest() { return this.request; } @Override public JobStatus getStatus() { return this.status; } @Override public void start(Request request) { this.request = castRequest(request); this.status = createNewStatus(this.request); jobStarting(); Throwable error = null; try { start(); } catch (Throwable t) { this.logger.error("Exception thrown during job execution", t); error = t; } finally { jobFinished(error); } } /** * Called when the job is starting. */ protected void jobStarting() { this.jobContext.pushCurrentJob(this); this.observationManager.notify(new JobStartedEvent(getRequest().getId(), getType(), request), this); this.status.setStartDate(new Date()); this.status.setState(JobStatus.State.RUNNING); this.status.startListening(); } /** * Called when the job is done. * * @param exception the exception throw during execution of the job */ protected void jobFinished(Throwable exception) { this.lock.lock(); try { this.status.stopListening(); this.status.setState(JobStatus.State.FINISHED); this.status.setStartDate(new Date()); this.finishedCondition.signalAll(); this.observationManager.notify(new JobFinishedEvent(getRequest().getId(), getType(), this.request), this, exception); this.jobContext.popCurrentJob(); try { if (this.request.getId() != null) { this.storage.store(this.status); } } catch (Throwable t) { this.logger.warn("Failed to store job status [{}]", this.status, t); } } finally { this.lock.unlock(); } } /** * Should be overridden if R is not Request. * * @param request the request * @return the request in the proper extended type */ @SuppressWarnings("unchecked") protected R castRequest(Request request) { return (R) request; } /** * @param request contains information related to the job to execute * @return the status of the job */ protected AbstractJobStatus<R> createNewStatus(R request) { return new DefaultJobStatus<R>(request, this.observationManager, this.loggerManager); } /** * Push new progression level. * * @param steps number of steps in this new level */ protected void notifyPushLevelProgress(int steps) { this.observationManager.notify(new PushLevelProgressEvent(steps), this); } /** * Next step. */ protected void notifyStepPropress() { this.observationManager.notify(new StepProgressEvent(), this); } /** * Pop progression level. */ protected void notifyPopLevelProgress() { this.observationManager.notify(new PopLevelProgressEvent(), this); } /** * Should be implemented by {@link Job} implementations. * * @throws Exception errors during job execution */ protected abstract void start() throws Exception; @Override public void join() throws InterruptedException { this.lock.lockInterruptibly(); try { if (getStatus() == null || getStatus().getState() != State.FINISHED) { this.finishedCondition.await(); } } finally { this.lock.unlock(); } } @Override public boolean join(long time, TimeUnit unit) throws InterruptedException { this.lock.lockInterruptibly(); try { if (getStatus().getState() != State.FINISHED) { return this.finishedCondition.await(time, unit); } } finally { this.lock.unlock(); } return true; } }
xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.job; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import javax.inject.Inject; import org.slf4j.Logger; import org.xwiki.component.annotation.InstantiationStrategy; import org.xwiki.component.descriptor.ComponentInstantiationStrategy; import org.xwiki.component.manager.ComponentManager; import org.xwiki.job.event.JobFinishedEvent; import org.xwiki.job.event.JobStartedEvent; import org.xwiki.job.event.status.JobStatus; import org.xwiki.job.event.status.JobStatus.State; import org.xwiki.job.event.status.PopLevelProgressEvent; import org.xwiki.job.event.status.PushLevelProgressEvent; import org.xwiki.job.event.status.StepProgressEvent; import org.xwiki.job.internal.AbstractJobStatus; import org.xwiki.job.internal.DefaultJobStatus; import org.xwiki.job.internal.JobStatusStorage; import org.xwiki.logging.LoggerManager; import org.xwiki.observation.ObservationManager; /** * Base class for {@link Job} implementations. * * @param <R> the request type associated to the job * @version $Id$ * @since 4.0M1 */ @InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP) public abstract class AbstractJob<R extends Request> implements Job { /** * Component manager. */ @Inject protected ComponentManager componentManager; /** * Used to send extensions installation and upgrade related events. */ @Inject protected ObservationManager observationManager; /** * Used to isolate job related log. */ @Inject protected LoggerManager loggerManager; /** * Used to store the results of the jobs execution. */ @Inject protected JobStatusStorage storage; /** * The logger to log. */ @Inject protected Logger logger; /** * Used to set the current context. */ @Inject protected JobContext jobContext; /** * The job request. */ protected R request; /** * @see #getStatus() */ protected AbstractJobStatus<R> status; /** * Main lock guarding all access. */ private final ReentrantLock lock = new ReentrantLock(); /** * Condition for waiting takes. */ private final Condition finishedCondition = lock.newCondition(); @Override public R getRequest() { return this.request; } @Override public JobStatus getStatus() { return this.status; } @Override public void start(Request request) { this.request = castRequest(request); this.status = createNewStatus(this.request); jobStarting(); Exception exception = null; try { start(); } catch (Exception e) { this.logger.error("Exception thrown during job execution", e); exception = e; } finally { jobFinished(exception); } } /** * Called when the job is starting. */ protected void jobStarting() { this.jobContext.pushCurrentJob(this); this.observationManager.notify(new JobStartedEvent(getRequest().getId(), getType(), request), this); this.status.setStartDate(new Date()); this.status.setState(JobStatus.State.RUNNING); this.status.startListening(); } /** * Called when the job is done. * * @param exception the exception throw during execution of the job */ protected void jobFinished(Exception exception) { this.lock.lock(); try { this.status.stopListening(); this.status.setState(JobStatus.State.FINISHED); this.status.setStartDate(new Date()); this.finishedCondition.signalAll(); this.observationManager.notify(new JobFinishedEvent(getRequest().getId(), getType(), this.request), this, exception); this.jobContext.popCurrentJob(); try { if (this.request.getId() != null) { this.storage.store(this.status); } } catch (Exception e) { this.logger.warn("Failed to store job status [{}]", this.status, e); } } finally { this.lock.unlock(); } } /** * Should be overridden if R is not Request. * * @param request the request * @return the request in the proper extended type */ @SuppressWarnings("unchecked") protected R castRequest(Request request) { return (R) request; } /** * @param request contains information related to the job to execute * @return the status of the job */ protected AbstractJobStatus<R> createNewStatus(R request) { return new DefaultJobStatus<R>(request, this.observationManager, this.loggerManager); } /** * Push new progression level. * * @param steps number of steps in this new level */ protected void notifyPushLevelProgress(int steps) { this.observationManager.notify(new PushLevelProgressEvent(steps), this); } /** * Next step. */ protected void notifyStepPropress() { this.observationManager.notify(new StepProgressEvent(), this); } /** * Pop progression level. */ protected void notifyPopLevelProgress() { this.observationManager.notify(new PopLevelProgressEvent(), this); } /** * Should be implemented by {@link Job} implementations. * * @throws Exception errors during job execution */ protected abstract void start() throws Exception; @Override public void join() throws InterruptedException { this.lock.lockInterruptibly(); try { if (getStatus() == null || getStatus().getState() != State.FINISHED) { this.finishedCondition.await(); } } finally { this.lock.unlock(); } } @Override public boolean join(long time, TimeUnit unit) throws InterruptedException { this.lock.lockInterruptibly(); try { if (getStatus().getState() != State.FINISHED) { return this.finishedCondition.await(time, unit); } } finally { this.lock.unlock(); } return true; } }
Better protection
xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java
Better protection
<ide><path>wiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java <ide> <ide> jobStarting(); <ide> <del> Exception exception = null; <add> Throwable error = null; <ide> try { <ide> start(); <del> } catch (Exception e) { <del> this.logger.error("Exception thrown during job execution", e); <del> exception = e; <del> } finally { <del> jobFinished(exception); <add> } catch (Throwable t) { <add> this.logger.error("Exception thrown during job execution", t); <add> error = t; <add> } finally { <add> jobFinished(error); <ide> } <ide> } <ide> <ide> * <ide> * @param exception the exception throw during execution of the job <ide> */ <del> protected void jobFinished(Exception exception) <add> protected void jobFinished(Throwable exception) <ide> { <ide> this.lock.lock(); <ide> <ide> if (this.request.getId() != null) { <ide> this.storage.store(this.status); <ide> } <del> } catch (Exception e) { <del> this.logger.warn("Failed to store job status [{}]", this.status, e); <add> } catch (Throwable t) { <add> this.logger.warn("Failed to store job status [{}]", this.status, t); <ide> } <ide> } finally { <ide> this.lock.unlock();
Java
agpl-3.0
bfe3dca0805ee11cf403f09f1e25da1daf612fef
0
Asqatasun/Asqatasun,dzc34/Asqatasun,medsob/Tanaguru,Tanaguru/Tanaguru,Asqatasun/Asqatasun,medsob/Tanaguru,Asqatasun/Asqatasun,dzc34/Asqatasun,Tanaguru/Tanaguru,Tanaguru/Tanaguru,medsob/Tanaguru,medsob/Tanaguru,Asqatasun/Asqatasun,Tanaguru/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun,dzc34/Asqatasun
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2013 Open-S Company * * This file is part of Tanaguru. * * Tanaguru 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/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.tanaguru.rules.accessiweb22; import java.util.LinkedHashSet; import org.opens.tanaguru.entity.audit.ProcessResult; import org.opens.tanaguru.entity.audit.SourceCodeRemark; import org.opens.tanaguru.entity.audit.TestSolution; import org.opens.tanaguru.rules.accessiweb22.test.Aw22RuleImplementationTestCase; import org.opens.tanaguru.rules.keystore.HtmlElementStore; import org.opens.tanaguru.rules.keystore.RemarkMessageStore; /** * Unit test class for the implementation of the rule 11.1.1 of the referential Accessiweb 2.2. * */ public class Aw22Rule11011Test extends Aw22RuleImplementationTestCase { public Aw22Rule11011Test(String testName) { super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.opens.tanaguru.rules.accessiweb22.Aw22Rule11011"); } @Override protected void setUpWebResourceMap() { getWebResourceMap().put("AW22.Test.11.1.1-1Passed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-01.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-02.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-03.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-04.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-05.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-06.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-07.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-08", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-08.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-09", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-09.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-10", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-10.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-11", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-11.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-12", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-12.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-13", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-13.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-14", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-14.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-15", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-15.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-16", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-16.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-01.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-02.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-03.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-04.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-05.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-06.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-07.html")); getWebResourceMap().put("AW22.Test.11.1.1-4NA-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-4NA-01.html")); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------1Passed-01------------------------------ //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("AW22.Test.11.1.1-1Passed-01"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-02"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-03------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-03"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-04------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-04"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-05------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-05"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-06------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-06"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-07------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-07"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-08------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-08"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-09------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-09"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-10------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-10"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-11------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-11"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-12------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-12"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-13------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-13"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-14------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-14"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-15------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-15"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-16------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-16"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------2Failed-01------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-01"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); SourceCodeRemark processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-02"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-03------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-03"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-04------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-04"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-05------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-05"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-06------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-06"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.TEXTAREA_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-07------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-07"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.SELECT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------4NA-01---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-4NA-01"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); } @Override protected void setConsolidate() { assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-01").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-02").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-03").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-04").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-05").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-06").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-07").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-08").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-09").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-10").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-11").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-12").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-13").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-14").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-15").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-16").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-01").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-02").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-03").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-04").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-05").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-06").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-07").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.11.1.1-4NA-01").getValue()); } }
rules/accessiweb2.2/src/test/java/org/opens/tanaguru/rules/accessiweb22/Aw22Rule11011Test.java
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2013 Open-S Company * * This file is part of Tanaguru. * * Tanaguru 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/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.tanaguru.rules.accessiweb22; import java.util.LinkedHashSet; import org.opens.tanaguru.entity.audit.ProcessResult; import org.opens.tanaguru.entity.audit.SourceCodeRemark; import org.opens.tanaguru.entity.audit.TestSolution; import org.opens.tanaguru.rules.accessiweb22.test.Aw22RuleImplementationTestCase; import org.opens.tanaguru.rules.keystore.HtmlElementStore; import org.opens.tanaguru.rules.keystore.RemarkMessageStore; /** * Unit test class for the implementation of the rule 11.1.1 of the referential Accessiweb 2.2. * */ public class Aw22Rule11011Test extends Aw22RuleImplementationTestCase { public Aw22Rule11011Test(String testName) { super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.opens.tanaguru.rules.accessiweb22.Aw22Rule11011"); } @Override protected void setUpWebResourceMap() { getWebResourceMap().put("AW22.Test.11.1.1-1Passed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-01.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-02.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-03.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-04.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-05.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-06.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-07.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-08", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-08.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-09", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-09.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-10", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-10.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-11", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-11.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-12", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-12.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-13", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-13.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-14", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-14.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-15", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-15.html")); getWebResourceMap().put("AW22.Test.11.1.1-1Passed-16", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-1Passed-16.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-01.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-02.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-03.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-04.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-05.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-06.html")); getWebResourceMap().put("AW22.Test.11.1.1-2Failed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-2Failed-07.html")); getWebResourceMap().put("AW22.Test.11.1.1-4NA-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule11011/AW22.Test.11.1.1-4NA-01.html")); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------1Passed-01------------------------------ //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("AW22.Test.11.1.1-1Passed-01"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-02"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-03------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-03"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-04------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-04"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-05------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-05"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-06------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-06"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-07------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-07"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-08------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-08"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-09------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-09"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-10------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-10"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-11------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-11"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-12------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-12"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-13------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-13"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-14------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-14"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-15------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-15"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------1Passed-16------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-1Passed-16"); // check test result assertEquals(TestSolution.PASSED, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); //---------------------------------------------------------------------- //------------------------------2Failed-01------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-01"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); SourceCodeRemark processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-02"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-03------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-03"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-04------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-04"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-05------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-05"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.INPUT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-06------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-06"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.TEXTAREA_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------2Failed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-2Failed-07"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.INVALID_FORM_FIELD_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.SELECT_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //------------------------------4NA-01---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.11.1.1-4NA-01"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); } @Override protected void setConsolidate() { assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-01").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-02").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-03").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-04").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-05").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-06").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-07").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-08").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-09").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-10").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-11").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-12").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-13").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-14").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-15").getValue()); assertEquals(TestSolution.PASSED, consolidate("AW22.Test.11.1.1-1Passed-16").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-01").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-02").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-03").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-04").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-05").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-06").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.11.1.1-2Failed-07").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.11.1.1-4NA-01").getValue()); } }
aw22 : 11.1.1 implementation
rules/accessiweb2.2/src/test/java/org/opens/tanaguru/rules/accessiweb22/Aw22Rule11011Test.java
aw22 : 11.1.1 implementation
<ide><path>ules/accessiweb2.2/src/test/java/org/opens/tanaguru/rules/accessiweb22/Aw22Rule11011Test.java <ide> <ide> <ide> //---------------------------------------------------------------------- <del> //------------------------------2Failed-02------------------------------ <add> //------------------------------2Failed-07------------------------------ <ide> //---------------------------------------------------------------------- <ide> processResult = processPageTest("AW22.Test.11.1.1-2Failed-07"); <ide> // check number of elements in the page
JavaScript
apache-2.0
11c00745a7eb48134e5537181ac462eb250e7e40
0
yp-engineering/marathon-ui,Kosta-Github/marathon-ui,watonyweng/marathon-ui,Kosta-Github/marathon-ui,quamilek/marathon-ui,Raffo/marathon-ui,mesosphere/marathon-ui,cribalik/marathon-ui,yp-engineering/marathon-ui,cribalik/marathon-ui,janisz/marathon-ui,watonyweng/marathon-ui,quamilek/marathon-ui,mesosphere/marathon-ui,Raffo/marathon-ui,janisz/marathon-ui
var _ = require("underscore"); var expect = require("chai").expect; var React = require("react/addons"); var TestUtils = React.addons.TestUtils; var config = require("../js/config/config"); var AppsActions = require("../js/actions/AppsActions"); var AppComponent = require("../js/components/AppComponent"); var AppHealthComponent = require("../js/components/AppHealthComponent"); var AppPageComponent = require("../js/components/AppPageComponent"); var AppsEvents = require("../js/events/AppsEvents"); var AppsStore = require("../js/stores/AppsStore"); var appValidator = require("../js/validators/appValidator"); var AppStatus = require("../js/constants/AppStatus"); var HealthStatus = require("../js/constants/HealthStatus"); var appScheme = require("../js/stores/appScheme"); var expectAsync = require("./helpers/expectAsync"); var HttpServer = require("./helpers/HttpServer").HttpServer; var server = new HttpServer(config.localTestserverURI); config.apiURL = "http://" + server.address + ":" + server.port + "/"; describe("Apps", function () { beforeEach(function (done) { this.server = server .setup({ "apps": [{ id: "/app-1" }, { id: "/app-2" }] }, 200) .start(function () { AppsStore.once(AppsEvents.CHANGE, done); AppsActions.requestApps(); }); }); afterEach(function (done) { this.server.stop(done); }); describe("on apps request", function () { it("updates the AppsStore on success", function (done) { AppsStore.once(AppsEvents.CHANGE, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.requestApps(); }); it("handles failure gracefully", function (done) { this.server.setup({message: "Guru Meditation"}, 404); AppsStore.once(AppsEvents.REQUEST_APPS_ERROR, function (error) { expectAsync(function () { expect(error.message).to.equal("Guru Meditation"); }, done); }); AppsActions.requestApps(); }); }); describe("on single app request", function () { it("updates the AppsStore on success", function (done) { this.server.setup({ "app": { "id": "/single-app" } }, 200); AppsStore.once(AppsEvents.CHANGE, function () { expectAsync(function () { expect(AppsStore.currentApp.id).to.equal("/single-app"); }, done); }); AppsActions.requestApp("/single-app"); }); it("handles failure gracefully", function (done) { this.server.setup({message: "Guru Meditation"}, 404); AppsStore.once(AppsEvents.REQUEST_APP_ERROR, function (error) { expectAsync(function () { expect(error.message).to.equal("Guru Meditation"); }, done); }); AppsActions.requestApp("/non-existing-app"); }); }); describe("on app creation", function () { it("updates the AppsStore on success", function (done) { this.server.setup({ "id": "/app-3" }, 201); AppsStore.once(AppsEvents.CHANGE, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(3); expect(_.where(AppsStore.apps, { id: "/app-3" })).to.be.not.empty; }, done); }); AppsActions.createApp({ "id": "/app-3", "cmd": "app command" }); }); it("sends create event on success", function (done) { this.server.setup({ "id": "/app-3" }, 201); AppsStore.once(AppsEvents.CREATE_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(3); }, done); }); AppsActions.createApp({ "id": "/app-3" }); }); it("handles bad request", function (done) { this.server.setup({message: "Guru Meditation"}, 400); AppsStore.once(AppsEvents.CREATE_APP_ERROR, function (error, status) { expectAsync(function () { expect(error.message).to.equal("Guru Meditation"); expect(status).to.equal(400); }, done); }); AppsActions.createApp({ cmd: "app command" }); }); it("passes response status", function (done) { this.server.setup({message: "Guru Meditation"}, 400); AppsStore.once(AppsEvents.CREATE_APP_ERROR, function (error, status) { expectAsync(function () { expect(status).to.equal(400); }, done); }); AppsActions.createApp({ cmd: "app command" }); }); it("handles atttribute value error", function (done) { this.server.setup({ errors: [{ attribute: "id", error: "attribute has invalid value" } ]}, 422); AppsStore.once(AppsEvents.CREATE_APP_ERROR, function (error) { expectAsync(function () { expect(error.errors[0].attribute).to.equal("id"); expect(error.errors[0].error).to.equal("attribute has invalid value"); }, done); }); AppsActions.createApp({ id: "app 1" }); }); }); describe("on app deletion", function () { it("deletes an app on success", function (done) { // A successful response with a payload of a new delete-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-deletes-app", "version": "v1" }, 200); AppsStore.once(AppsEvents.DELETE_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(1); expect(_.where(AppsStore.apps, { id: "/app-1" })).to.be.empty; }, done); }); AppsActions.deleteApp("/app-1"); }); it("receives a delete error", function (done) { this.server.setup({message: "delete error"}, 404); AppsStore.once(AppsEvents.DELETE_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("delete error"); }, done); }); AppsActions.deleteApp("/non-existing-app"); }); }); describe("on app restart", function () { it("restarts an app on success", function (done) { // A successful response with a payload of a new restart-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-restarts-app", "version": "v1" }, 200); AppsStore.once(AppsEvents.RESTART_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.restartApp("/app-1"); }); it("receives a restart error on non existing app", function (done) { this.server.setup({message: "restart error"}, 404); AppsStore.once(AppsEvents.RESTART_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("restart error"); }, done); }); AppsActions.restartApp("/non-existing-app"); }); it("receives a restart error on locked app", function (done) { this.server.setup({message: "app locked by deployment"}, 409); AppsStore.once(AppsEvents.RESTART_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("app locked by deployment"); }, done); }); AppsActions.restartApp("/app-1"); }); }); describe("on app scale", function () { it("scales an app on success", function (done) { // A successful response with a payload of a new scale-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-scales-app", "version": "v1" }, 200); AppsStore.once(AppsEvents.SCALE_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.scaleApp("/app-1", 10); }); it("receives a scale error on non existing app", function (done) { this.server.setup({message: "scale error"}, 404); AppsStore.once(AppsEvents.SCALE_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("scale error"); }, done); }); AppsActions.scaleApp("/non-existing-app"); }); it("receives a scale error on bad data", function (done) { this.server.setup({message: "scale bad data error"}, 400); AppsStore.once(AppsEvents.SCALE_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("scale bad data error"); }, done); }); AppsActions.scaleApp("/app-1", "needs a number! :P"); }); }); describe("on app apply", function () { it("applies app settings on success", function (done) { // A successful response with a payload of a apply-settings-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-applies-new-settings", "version": "v2" }, 200); AppsStore.once(AppsEvents.APPLY_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.applySettingsOnApp("/app-1", { "cmd": "sleep 10", "id": "/app-1", "instances": 15 }); }); it("receives an apply error on bad data", function (done) { this.server.setup({message: "apply bad data error"}, 400); AppsStore.once(AppsEvents.APPLY_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("apply bad data error"); }, done); }); AppsActions.applySettingsOnApp("/app-1", { "cmd": "sleep 10", "id": "/app-1", "instances": "needs a number! :P" }); }); }); }); describe("App component", function () { beforeEach(function () { var model = { id: "app-123", deployments: [], tasksRunning: 4, instances: 5, mem: 100, cpus: 4, status: 0 }; this.renderer = TestUtils.createRenderer(); this.renderer.render(<AppComponent model={model} router={{}} />); this.component = this.renderer.getRenderOutput(); }); afterEach(function () { this.renderer.unmount(); }); it("has the correct app id", function () { var cellContent = this.component.props.children[0].props.children; expect(cellContent).to.equal("app-123"); }); it("has the correct amount of memory", function () { var cellContent = this.component.props.children[1].props.children; expect(cellContent).to.equal(100); }); it("has the correct amount of cpus", function () { var cellContent = this.component.props.children[2].props.children; expect(cellContent).to.equal(4); }); it("has correct number of tasks running", function () { var tasksRunning = this.component.props.children[3].props.children[0].props.children; expect(tasksRunning).to.equal(4); }); it("has correct number of instances", function () { var totalSteps = this.component.props.children[3].props.children[2]; expect(totalSteps).to.equal(5); }); it("has correct status description", function () { var statusDescription = this.component.props.children[5].props.children.props.children; expect(statusDescription).to.equal("Running"); }); }); describe("App Health component", function () { beforeEach(function () { var model = { id: "app-123", tasksRunning: 4, tasksHealthy: 2, tasksUnhealthy: 1, tasksStaged: 1, instances: 5 }; this.renderer = TestUtils.createRenderer(); this.renderer.render(<AppHealthComponent model={model} />); this.component = this.renderer.getRenderOutput(); }); afterEach(function () { this.renderer.unmount(); }); it("health bar for healthy tasks has correct width", function () { var width = this.component.props.children[0].props.style.width; expect(width).to.equal("40%"); }); it("health bar for unhealthy tasks has correct width", function () { var width = this.component.props.children[1].props.style.width; expect(width).to.equal("20%"); }); it("health bar for running tasks has correct width", function () { var width = this.component.props.children[2].props.style.width; expect(width).to.equal("20%"); }); it("health bar for staged tasks has correct width", function () { var width = this.component.props.children[3].props.style.width; expect(width).to.equal("20%"); }); it("health bar for over capacity tasks has correct width", function () { var width = this.component.props.children[4].props.style.width; expect(width).to.equal("0%"); }); it("health bar for unscheduled tasks has correct width", function () { var width = this.component.props.children[5].props.style.width; expect(width).to.equal("0%"); }); }); describe("App validator", function () { beforeEach(function () { this.model = { cmd: "cmd 1", constraints: [["hostname", "UNIQUE"]], cpus: 2, executor: "", id: "app-1", instances: 1, mem: 16, disk: 24, ports: [0], uris: [] }; }); it("should pass the app model without exception", function () { var errors = appValidator.validate(this.model); expect(errors).to.be.undefined; }); it("should have invalid constraints", function () { this.model.constraints = [["hostname", "INVALID"]]; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("constraints"); }); it("should have invalid cpus", function () { this.model.cpus = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("cpus"); }); it("should have invalid memory", function () { this.model.mem = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("mem"); }); it("should have invalid disk", function () { this.model.disk = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("disk"); }); it("should have invalid instances", function () { this.model.instances = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("instances"); }); it("should have invalid ports if string passed", function () { this.model.ports = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("ports"); }); it("should have invalid ports on wrong numbers", function () { this.model.ports = [2000, -1200]; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("ports"); }); it("should have invalid id", function () { this.model.id = null; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("id"); }); it("should collect errors", function () { this.model.cpus = "invalid string"; this.model.mem = "invalid string"; this.model.disk = "invalid string"; var errors = appValidator.validate(this.model); expect(errors).to.have.length(3); expect(errors[0].attribute).to.equal("mem"); expect(errors[1].attribute).to.equal("cpus"); expect(errors[2].attribute).to.equal("disk"); }); }); describe("App Page component", function () { beforeEach(function () { var app = _.extend(appScheme, { id: "/test-app-1", healthChecks: [{path: "/", protocol: "HTTP"}], status: AppStatus.RUNNING, tasks: [ { id: "test-task-1", appId: "/test-app-1", healthStatus: HealthStatus.UNHEALTHY, healthCheckResults: [ { alive: false, taskId: "test-task-1" } ] } ] }); AppsStore.apps = [app]; this.renderer = TestUtils.createRenderer(); this.renderer.render(<AppPageComponent appId={app.id} router={{}} />); this.component = this.renderer.getRenderOutput(); this.element = this.renderer._instance._instance; }); afterEach(function () { this.renderer.unmount(); }); it("has the correct app id", function () { var appId = this.component.props.children[0].props.appId; expect(appId).to.equal("/test-app-1"); }); it("returns the right health message for failing tasks", function () { var msg = this.element.getTaskHealthMessage("test-task-1"); expect(msg).to.equal("Warning: Health check 'HTTP /' failed."); }); it("returns the right health message for tasks with unknown health", function () { var app = _.extend(appScheme, { id: "/test-app-1", status: AppStatus.RUNNING, tasks: [ { id: "test-task-1", appId: "/test-app-1", healthStatus: HealthStatus.UNKNOWN, } ] }); AppsStore.apps = [app]; var msg = this.element.getTaskHealthMessage("test-task-1"); expect(msg).to.equal("Unknown"); }); it("returns the right health message for healthy tasks", function () { var app = _.extend(appScheme, { id: "/test-app-1", status: AppStatus.RUNNING, tasks: [ { id: "test-task-1", appId: "/test-app-1", healthStatus: HealthStatus.HEALTHY, } ] }); AppsStore.apps = [app]; var msg = this.element.getTaskHealthMessage("test-task-1"); expect(msg).to.equal("Healthy"); }); });
src/test/apps.test.js
var _ = require("underscore"); var expect = require("chai").expect; var React = require("react/addons"); var TestUtils = React.addons.TestUtils; var config = require("../js/config/config"); var AppsActions = require("../js/actions/AppsActions"); var AppComponent = require("../js/components/AppComponent"); var AppHealthComponent = require("../js/components/AppHealthComponent"); var AppPageComponent = require("../js/components/AppPageComponent"); var AppsEvents = require("../js/events/AppsEvents"); var AppsStore = require("../js/stores/AppsStore"); var appValidator = require("../js/validators/appValidator"); var AppStatus = require("../js/constants/AppStatus"); var HealthStatus = require("../js/constants/HealthStatus"); var appScheme = require("../js/stores/appScheme"); var expectAsync = require("./helpers/expectAsync"); var HttpServer = require("./helpers/HttpServer").HttpServer; var server = new HttpServer(config.localTestserverURI); config.apiURL = "http://" + server.address + ":" + server.port + "/"; describe("Apps", function () { beforeEach(function (done) { this.server = server .setup({ "apps": [{ id: "/app-1" }, { id: "/app-2" }] }, 200) .start(function () { AppsStore.once(AppsEvents.CHANGE, done); AppsActions.requestApps(); }); }); afterEach(function (done) { this.server.stop(done); }); describe("on apps request", function () { it("updates the AppsStore on success", function (done) { AppsStore.once(AppsEvents.CHANGE, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.requestApps(); }); it("handles failure gracefully", function (done) { this.server.setup({message: "Guru Meditation"}, 404); AppsStore.once(AppsEvents.REQUEST_APPS_ERROR, function (error) { expectAsync(function () { expect(error.message).to.equal("Guru Meditation"); }, done); }); AppsActions.requestApps(); }); }); describe("on single app request", function () { it("updates the AppsStore on success", function (done) { this.server.setup({ "app": { "id": "/single-app" } }, 200); AppsStore.once(AppsEvents.CHANGE, function () { expectAsync(function () { expect(AppsStore.currentApp.id).to.equal("/single-app"); }, done); }); AppsActions.requestApp("/single-app"); }); it("handles failure gracefully", function (done) { this.server.setup({message: "Guru Meditation"}, 404); AppsStore.once(AppsEvents.REQUEST_APP_ERROR, function (error) { expectAsync(function () { expect(error.message).to.equal("Guru Meditation"); }, done); }); AppsActions.requestApp("/non-existing-app"); }); }); describe("on app creation", function () { it("updates the AppsStore on success", function (done) { this.server.setup({ "id": "/app-3" }, 201); AppsStore.once(AppsEvents.CHANGE, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(3); expect(_.where(AppsStore.apps, { id: "/app-3" })).to.be.not.empty; }, done); }); AppsActions.createApp({ "id": "/app-3", "cmd": "app command" }); }); it("sends create event on success", function (done) { this.server.setup({ "id": "/app-3" }, 201); AppsStore.once(AppsEvents.CREATE_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(3); }, done); }); AppsActions.createApp({ "id": "/app-3" }); }); it("handles bad request", function (done) { this.server.setup({message: "Guru Meditation"}, 400); AppsStore.once(AppsEvents.CREATE_APP_ERROR, function (error, status) { expectAsync(function () { expect(error.message).to.equal("Guru Meditation"); expect(status).to.equal(400); }, done); }); AppsActions.createApp({ cmd: "app command" }); }); it("passes response status", function (done) { this.server.setup({message: "Guru Meditation"}, 400); AppsStore.once(AppsEvents.CREATE_APP_ERROR, function (error, status) { expectAsync(function () { expect(status).to.equal(400); }, done); }); AppsActions.createApp({ cmd: "app command" }); }); it("handles atttribute value error", function (done) { this.server.setup({ errors: [{ attribute: "id", error: "attribute has invalid value" } ]}, 422); AppsStore.once(AppsEvents.CREATE_APP_ERROR, function (error) { expectAsync(function () { expect(error.errors[0].attribute).to.equal("id"); expect(error.errors[0].error).to.equal("attribute has invalid value"); }, done); }); AppsActions.createApp({ id: "app 1" }); }); }); describe("on app deletion", function () { it("deletes an app on success", function (done) { // A successful response with a payload of a new delete-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-deletes-app", "version": "v1" }, 200); AppsStore.once(AppsEvents.DELETE_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(1); expect(_.where(AppsStore.apps, { id: "/app-1" })).to.be.empty; }, done); }); AppsActions.deleteApp("/app-1"); }); it("receives a delete error", function (done) { this.server.setup({message: "delete error"}, 404); AppsStore.once(AppsEvents.DELETE_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("delete error"); }, done); }); AppsActions.deleteApp("/non-existing-app"); }); }); describe("on app restart", function () { it("restarts an app on success", function (done) { // A successful response with a payload of a new restart-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-restarts-app", "version": "v1" }, 200); AppsStore.once(AppsEvents.RESTART_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.restartApp("/app-1"); }); it("receives a restart error on non existing app", function (done) { this.server.setup({message: "restart error"}, 404); AppsStore.once(AppsEvents.RESTART_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("restart error"); }, done); }); AppsActions.restartApp("/non-existing-app"); }); it("receives a restart error on locked app", function (done) { this.server.setup({message: "app locked by deployment"}, 409); AppsStore.once(AppsEvents.RESTART_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("app locked by deployment"); }, done); }); AppsActions.restartApp("/app-1"); }); }); describe("on app scale", function () { it("scales an app on success", function (done) { // A successful response with a payload of a new scale-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-scales-app", "version": "v1" }, 200); AppsStore.once(AppsEvents.SCALE_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.scaleApp("/app-1", 10); }); it("receives a scale error on non existing app", function (done) { this.server.setup({message: "scale error"}, 404); AppsStore.once(AppsEvents.SCALE_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("scale error"); }, done); }); AppsActions.scaleApp("/non-existing-app"); }); it("receives a scale error on bad data", function (done) { this.server.setup({message: "scale bad data error"}, 400); AppsStore.once(AppsEvents.SCALE_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("scale bad data error"); }, done); }); AppsActions.scaleApp("/app-1", "needs a number! :P"); }); }); describe("on app apply", function () { it("applies app settings on success", function (done) { // A successful response with a payload of a apply-settings-deployment, // like the API would do. // Indeed the payload isn't processed by the store yet. this.server.setup({ "deploymentId": "deployment-that-applies-new-settings", "version": "v2" }, 200); AppsStore.once(AppsEvents.APPLY_APP, function () { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); }, done); }); AppsActions.applySettingsOnApp("/app-1", { "cmd": "sleep 10", "id": "/app-1", "instances": 15 }); }); it("receives an apply error on bad data", function (done) { this.server.setup({message: "apply bad data error"}, 400); AppsStore.once(AppsEvents.APPLY_APP_ERROR, function (error) { expectAsync(function () { expect(AppsStore.apps).to.have.length(2); expect(error.message).to.equal("apply bad data error"); }, done); }); AppsActions.applySettingsOnApp("/app-1", { "cmd": "sleep 10", "id": "/app-1", "instances": "needs a number! :P" }); }); }); }); describe("App component", function () { beforeEach(function () { var model = { id: "app-123", deployments: [], tasksRunning: 4, instances: 5, mem: 100, cpus: 4, status: 0 }; this.renderer = TestUtils.createRenderer(); this.renderer.render(<AppComponent model={model} router={{}} />); this.component = this.renderer.getRenderOutput(); }); afterEach(function () { this.renderer.unmount(); }); it("has the correct app id", function () { var cellContent = this.component.props.children[0].props.children; expect(cellContent).to.equal("app-123"); }); it("has the correct amount of memory", function () { var cellContent = this.component.props.children[1].props.children; expect(cellContent).to.equal(100); }); it("has the correct amount of cpus", function () { var cellContent = this.component.props.children[2].props.children; expect(cellContent).to.equal(4); }); it("has correct number of tasks running", function () { var tasksRunning = this.component.props.children[3].props.children[0].props.children; expect(tasksRunning).to.equal(4); }); it("has correct number of instances", function () { var totalSteps = this.component.props.children[3].props.children[2]; expect(totalSteps).to.equal(5); }); it("has correct status description", function () { var statusDescription = this.component.props.children[5].props.children.props.children; expect(statusDescription).to.equal("Running"); }); }); describe("App Health component", function () { beforeEach(function () { var model = { id: "app-123", tasksRunning: 4, tasksHealthy: 2, tasksUnhealthy: 1, tasksStaged: 1, instances: 5 }; this.renderer = TestUtils.createRenderer(); this.renderer.render(<AppHealthComponent model={model} />); this.component = this.renderer.getRenderOutput(); }); afterEach(function () { this.renderer.unmount(); }); it("health bar for healthy tasks has correct width", function () { var width = this.component.props.children[0].props.style.width; expect(width).to.equal("40%"); }); it("health bar for unhealthy tasks has correct width", function () { var width = this.component.props.children[1].props.style.width; expect(width).to.equal("20%"); }); it("health bar for running tasks has correct width", function () { var width = this.component.props.children[2].props.style.width; expect(width).to.equal("20%"); }); it("health bar for staged tasks has correct width", function () { var width = this.component.props.children[3].props.style.width; expect(width).to.equal("20%"); }); it("health bar for over capacity tasks has correct width", function () { var width = this.component.props.children[4].props.style.width; expect(width).to.equal("0%"); }); it("health bar for unscheduled tasks has correct width", function () { var width = this.component.props.children[5].props.style.width; expect(width).to.equal("0%"); }); }); describe("App validator", function () { beforeEach(function () { this.model = { cmd: "cmd 1", constraints: [["hostname", "UNIQUE"]], cpus: 2, executor: "", id: "app-1", instances: 1, mem: 16, disk: 24, ports: [0], uris: [] }; }); it("should pass the app model without exception", function () { var errors = appValidator.validate(this.model); expect(errors).to.be.undefined; }); it("should have invalid constraints", function () { this.model.constraints = [["hostname", "INVALID"]]; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("constraints"); }); it("should have invalid cpus", function () { this.model.cpus = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("cpus"); }); it("should have invalid memory", function () { this.model.mem = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("mem"); }); it("should have invalid disk", function () { this.model.disk = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("disk"); }); it("should have invalid instances", function () { this.model.instances = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("instances"); }); it("should have invalid ports if string passed", function () { this.model.ports = "invalid string"; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("ports"); }); it("should have invalid ports on wrong numbers", function () { this.model.ports = [2000, -1200]; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("ports"); }); it("should have invalid id", function () { this.model.id = null; var errors = appValidator.validate(this.model); expect(errors[0].attribute).to.equal("id"); }); it("should collect errors", function () { this.model.cpus = "invalid string"; this.model.mem = "invalid string"; this.model.disk = "invalid string"; var errors = appValidator.validate(this.model); expect(errors).to.have.length(3); expect(errors[0].attribute).to.equal("mem"); expect(errors[1].attribute).to.equal("cpus"); expect(errors[2].attribute).to.equal("disk"); }); }); describe("App Page component", function () { beforeEach(function () { var app = _.extend(appScheme, { id: "/test-app-1", healthChecks: [{path: "/", protocol: "HTTP"}], status: AppStatus.RUNNING, tasks: [ { id: "test-task-1", appId: "/test-app-1", healthStatus: HealthStatus.UNHEALTHY, healthCheckResults: [ { alive: false, taskId: "test-task-1" } ] } ] }); AppsStore.apps = [app]; this.renderer = TestUtils.createRenderer(); this.renderer.render(<AppPageComponent appId={app.id} router={{}} />); this.component = this.renderer.getRenderOutput(); this.element = this.renderer._instance._instance; }); afterEach(function () { this.renderer.unmount(); }); it("has the correct app id", function () { var appId = this.component.props.children[0].props.appId; expect(appId).to.equal("/test-app-1"); }); it("returns the right health message for failing tasks", function () { var msg = this.element.getTaskHealthMessage("test-task-1"); expect(msg).to.equal("Warning: Health check 'HTTP /' failed."); }); });
Extend tests to cover all HealthStatus states
src/test/apps.test.js
Extend tests to cover all HealthStatus states
<ide><path>rc/test/apps.test.js <ide> expect(msg).to.equal("Warning: Health check 'HTTP /' failed."); <ide> }); <ide> <add> it("returns the right health message for tasks with unknown health", function () { <add> var app = _.extend(appScheme, { <add> id: "/test-app-1", <add> status: AppStatus.RUNNING, <add> tasks: [ <add> { <add> id: "test-task-1", <add> appId: "/test-app-1", <add> healthStatus: HealthStatus.UNKNOWN, <add> } <add> ] <add> }); <add> <add> AppsStore.apps = [app]; <add> var msg = this.element.getTaskHealthMessage("test-task-1"); <add> expect(msg).to.equal("Unknown"); <add> }); <add> <add> it("returns the right health message for healthy tasks", function () { <add> var app = _.extend(appScheme, { <add> id: "/test-app-1", <add> status: AppStatus.RUNNING, <add> tasks: [ <add> { <add> id: "test-task-1", <add> appId: "/test-app-1", <add> healthStatus: HealthStatus.HEALTHY, <add> } <add> ] <add> }); <add> <add> AppsStore.apps = [app]; <add> var msg = this.element.getTaskHealthMessage("test-task-1"); <add> expect(msg).to.equal("Healthy"); <add> }); <ide> });
JavaScript
mit
e89654f9eb540d13d196465bbb2eb8b2542a84f3
0
daanpape/grader,daanpape/grader
// View model for the courses page function pageViewModel(gvm) { // projecttitle gvm.projecttitle = ko.observable(""); gvm.numberOfCompetencesToAdd = 0; gvm.compSubcomp = new array(); // Page specific i18n bindings gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm); gvm.pageHeader = ko.observable("Project"); gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm); gvm.getProjectInfo = function() { $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) { gvm.pageHeader(data[0].code + ' - ' + data[0].name); }); }; } function addCompetence() { var competencePanelWrapper = document.createElement('div'); var competencePanel = document.createElement('div'); var competencePanelHeading = document.createElement('div'); var competencePanelBody = document.createElement('div'); var competencePanelFooter = document.createElement('div'); var competenceCode = document.createElement('input'); var competenceName = document.createElement('input'); var subcompetenceButton = document.createElement('button'); var removeCompetenceButton = document.createElement('button'); competenceCode.type = 'text'; competenceCode.placeholder = "Competence-Code"; $(competenceCode).addClass("form-control"); competenceName.type = 'text'; competenceName.placeholder = "Name of the competence"; $(competenceName).addClass("form-control"); $(subcompetenceButton).addClass("btn"); $(subcompetenceButton).text("Add a subcompetence"); $(subcompetenceButton).val(viewModel.numberOfCompetencesToAdd); $(subcompetenceButton).on('click', function() { addSubCompetence($(subcompetenceButton).val()) }); $(removeCompetenceButton).addClass("btn pull-right"); $(removeCompetenceButton).text("Remove this competence"); $(removeCompetenceButton).val(viewModel.numberOfCompetencesToAdd); $(removeCompetenceButton).on('click', function() { $(this).parent().parent().remove(); }); $(competencePanelWrapper).addClass("col-md-9 compPanel panel-" + $(subcompetenceButton).val()); $(competencePanel).addClass("panel panel-default"); $(competencePanelHeading).addClass("panel-heading comp-" + $(subcompetenceButton).val()); $(competencePanelBody).addClass("panel-body comp-" + $(subcompetenceButton).val()); $(competencePanelFooter).addClass("panel-footer"); if(!$(".compPanel")[0]) { $("#top-col").after(competencePanelWrapper); } else { $(".compPanel:last").after(competencePanelWrapper); } ++viewModel.numberOfCompetencesToAdd; $(competencePanelWrapper).append(competencePanel); $(competencePanel).append(competencePanelHeading); $(competencePanelHeading).append(competenceCode); $(competenceCode).after(competenceName); $(competencePanelHeading).after(competencePanelBody); $(competencePanelBody).after(competencePanelFooter); $(competencePanelFooter).append(subcompetenceButton); $(subcompetenceButton).after(removeCompetenceButton); } function addSubCompetence(competence) { ++viewModel.compSubcomp[competence]; var subcompPanelWrapper = document.createElement('div'); var subcompPanel = document.createElement('div'); var subcompPanelHeading = document.createElement('div'); var subcompPanelBody = document.createElement('div'); var subcompPanelFooter = document.createElement('div'); var subcompCode = document.createElement('input'); var subcompName = document.createElement('input'); var indicatorButton = document.createElement('button'); var removeSubcompButton = document.createElement('button'); subcompCode.type = 'text'; subcompCode.placeholder = "Competence-Code"; $(subcompCode).addClass("form-control"); subcompName.type = 'text'; subcompName.placeholder = "Name of the competence"; $(subcompName).addClass("form-control"); $(indicatorButton).addClass("btn"); $(indicatorButton).text("Add an indicator"); $(indicatorButton).val(viewModel.numberOfCompetencesToAdd); $(indicatorButton).on('click', function() { addIndicator(); }); $(removeSubcompButton).addClass("btn pull-right"); $(removeSubcompButton).text("Remove this subcompetence"); $(removeSubcompButton).val(); $(removeSubcompButton).on('click', function() { $(this).parent().parent().remove(); }); $(subcompPanelWrapper).addClass("subcompPanel panel-"); $(subcompPanel).addClass("panel panel-default"); $(subcompPanelHeading).addClass("panel-heading"); $(subcompPanelBody).addClass("panel-body"); $(subcompPanelFooter).addClass("panel-footer"); $(".panel-body." + competence).append(subcompPanelWrapper); $(subcompPanelWrapper).append(subcompPanel); $(subcompPanel).append(subcompPanelHeading); $(subcompPanelHeading).append(subcompCode); $(subcompCode).after(subcompName); $(subcompPanelHeading).after(subcompPanelBody); $(subcompPanelBody).after(subcompPanelFooter); $(subcompPanelFooter).append(indicatorButton); $(indicatorButton).after(removeSubcompButton); } function addIndicator() { } function initPage() { viewModel.getProjectInfo(); $("#addCompetenceBtn").click(function() { addCompetence(); }) }
js/projectViewModel.js
// View model for the courses page function pageViewModel(gvm) { // projecttitle gvm.projecttitle = ko.observable(""); gvm.numberOfCompetencesToAdd = 0; gvm.compSubcomp = new array(); // Page specific i18n bindings gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm); gvm.pageHeader = ko.observable("Project"); gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm); gvm.getProjectInfo = function() { $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) { gvm.pageHeader(data[0].code + ' - ' + data[0].name); }); }; } function addCompetence() { var competencePanelWrapper = document.createElement('div'); var competencePanel = document.createElement('div'); var competencePanelHeading = document.createElement('div'); var competencePanelBody = document.createElement('div'); var competencePanelFooter = document.createElement('div'); var competenceCode = document.createElement('input'); var competenceName = document.createElement('input'); var subcompetenceButton = document.createElement('button'); var removeCompetenceButton = document.createElement('button'); competenceCode.type = 'text'; competenceCode.placeholder = "Competence-Code"; $(competenceCode).addClass("form-control"); competenceName.type = 'text'; competenceName.placeholder = "Name of the competence"; $(competenceName).addClass("form-control"); $(subcompetenceButton).addClass("btn"); $(subcompetenceButton).text("Add a subcompetence"); $(subcompetenceButton).val(viewModel.numberOfCompetencesToAdd); $(subcompetenceButton).on('click', function() { addSubCompetence($(subcompetenceButton).val()) }); $(removeCompetenceButton).addClass("btn pull-right"); $(removeCompetenceButton).text("Remove this competence"); $(removeCompetenceButton).val(viewModel.numberOfCompetencesToAdd); $(removeCompetenceButton).on('click', function() { $(this).parent().parent().remove(); }); $(competencePanelWrapper).addClass("col-md-9 compPanel panel-" + $(subcompetenceButton).val()); $(competencePanel).addClass("panel panel-default"); $(competencePanelHeading).addClass("panel-heading comp-" + $(subcompetenceButton).val()); $(competencePanelBody).addClass("panel-body comp-" + $(subcompetenceButton).val()); $(competencePanelFooter).addClass("panel-footer"); if(!$(".compPanel")[0]) { $("#top-col").after(competencePanelWrapper); } else { $(".compPanel:last").after(competencePanelWrapper); } ++viewModel.numberOfCompetencesToAdd; $(competencePanelWrapper).append(competencePanel); $(competencePanel).append(competencePanelHeading); $(competencePanelHeading).append(competenceCode); $(competenceCode).after(competenceName); $(competencePanelHeading).after(competencePanelBody); $(competencePanelBody).after(competencePanelFooter); $(competencePanelFooter).append(subcompetenceButton); $(subcompetenceButton).after(removeCompetenceButton); } function addSubCompetence(competence) { ++viewModel.compSubcomp[competence]; var subcompPanelWrapper = document.createElement('div'); var subcompPanel = document.createElement('div'); var subcompPanelHeading = document.createElement('div'); var subcompPanelBody = document.createElement('div'); var subcompPanelFooter = document.createElement('div'); var subcompCode = document.createElement('input'); var subcompName = document.createElement('input'); var indicatorButton = document.createElement('button'); var removeSubcompButton = document.createElement('button'); subcompCode.type = 'text'; subcompCode.placeholder = "Competence-Code"; $(subcompCode).addClass("form-control"); subcompName.type = 'text'; subcompName.placeholder = "Name of the competence"; $(subcompName).addClass("form-control"); $(indicatorButton).addClass("btn"); $(indicatorButton).text("Add an indicator"); $(indicatorButton).val(viewModel.numberOfCompetencesToAdd); $(indicatorButton).on('click', function() { addIndicator(); }); $(removeSubcompButton).addClass("btn pull-right"); $(removeSubcompButton).text("Remove this subcompetence"); $(removeSubcompButton).val(); $(removeSubcompButton).on('click', function() { $(this).parent().parent().remove(); }); $(subcompPanelWrapper).addClass("subcompPanel panel-" + ); $(subcompPanel).addClass("panel panel-default"); $(subcompPanelHeading).addClass("panel-heading"); $(subcompPanelBody).addClass("panel-body"); $(subcompPanelFooter).addClass("panel-footer"); $(".panel-body." + competence).append(subcompPanelWrapper); $(subcompPanelWrapper).append(subcompPanel); $(subcompPanel).append(subcompPanelHeading); $(subcompPanelHeading).append(subcompCode); $(subcompCode).after(subcompName); $(subcompPanelHeading).after(subcompPanelBody); $(subcompPanelBody).after(subcompPanelFooter); $(subcompPanelFooter).append(indicatorButton); $(indicatorButton).after(removeSubcompButton); } function addIndicator() { } function initPage() { viewModel.getProjectInfo(); $("#addCompetenceBtn").click(function() { addCompetence(); }) }
projectpage
js/projectViewModel.js
projectpage
<ide><path>s/projectViewModel.js <ide> $(this).parent().parent().remove(); <ide> }); <ide> <del> $(subcompPanelWrapper).addClass("subcompPanel panel-" + ); <add> $(subcompPanelWrapper).addClass("subcompPanel panel-"); <ide> $(subcompPanel).addClass("panel panel-default"); <ide> $(subcompPanelHeading).addClass("panel-heading"); <ide> $(subcompPanelBody).addClass("panel-body");
Java
agpl-3.0
b40ead9937e894db7c1d8378f72a72f7c7cd735c
0
LibrePlan/libreplan,Marine-22/libre,dgray16/libreplan,Marine-22/libre,LibrePlan/libreplan,PaulLuchyn/libreplan,poum/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,Marine-22/libre,poum/libreplan,poum/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,skylow95/libreplan,LibrePlan/libreplan,dgray16/libreplan,LibrePlan/libreplan,dgray16/libreplan,skylow95/libreplan,poum/libreplan,dgray16/libreplan,dgray16/libreplan,Marine-22/libre,dgray16/libreplan,skylow95/libreplan,Marine-22/libre,LibrePlan/libreplan,LibrePlan/libreplan,skylow95/libreplan,Marine-22/libre,LibrePlan/libreplan,poum/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,poum/libreplan,PaulLuchyn/libreplan
/* * This file is part of ###PROJECT_NAME### * * Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * * 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.navalplanner.web.planner.allocation; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.lang.Validate; import org.navalplanner.business.planner.entities.CalculatedValue; import org.navalplanner.business.planner.entities.ResourceAllocation; import org.navalplanner.business.planner.entities.ResourcesPerDay; import org.navalplanner.business.planner.entities.Task; import org.navalplanner.business.planner.entities.Task.ModifiedAllocation; import org.navalplanner.business.planner.entities.allocationalgorithms.HoursModification; import org.navalplanner.business.planner.entities.allocationalgorithms.ResourcesPerDayModification; import org.navalplanner.business.resources.entities.Resource; import org.navalplanner.web.common.Util; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Constraint; import org.zkoss.zul.Decimalbox; import org.zkoss.zul.Intbox; import org.zkoss.zul.SimpleConstraint; /** * The information that must be introduced to create a * {@link ResourceAllocation} * @author Óscar González Fernández <[email protected]> */ public abstract class AllocationRow { public static final SimpleConstraint CONSTRAINT_FOR_RESOURCES_PER_DAY = new SimpleConstraint( SimpleConstraint.NO_EMPTY | SimpleConstraint.NO_NEGATIVE); public static void assignHours(List<AllocationRow> rows, int[] hours) { int i = 0; for (AllocationRow each : rows) { each.hoursInput.setValue(hours[i++]); } } public static void assignResourcesPerDay(List<AllocationRow> rows, ResourcesPerDay[] resourcesPerDay) { int i = 0; for (AllocationRow each : rows) { each.setResourcesPerDay(resourcesPerDay[i++]); } } public static void loadDataFromLast(Collection<? extends AllocationRow> rows) { for (AllocationRow each : rows) { each.loadDataFromLast(); } } public static List<ResourcesPerDayModification> createAndAssociate( Task task, Collection<? extends AllocationRow> rows) { List<ResourcesPerDayModification> result = new ArrayList<ResourcesPerDayModification>(); for (AllocationRow each : rows) { ResourcesPerDayModification modification = each .toResourcesPerDayModification(task); result.add(modification); each.setTemporal(modification.getBeingModified()); } return result; } public static List<HoursModification> createHoursModificationsAndAssociate( Task task, List<AllocationRow> currentRows) { List<HoursModification> result = new ArrayList<HoursModification>(); for (AllocationRow each : currentRows) { HoursModification hoursModification = each .toHoursModification(task); result.add(hoursModification); each.setTemporal(hoursModification.getBeingModified()); } return result; } public static List<ModifiedAllocation> getModifiedFrom( Collection<? extends AllocationRow> rows) { List<ModifiedAllocation> result = new ArrayList<ModifiedAllocation>(); for (AllocationRow each : rows) { Validate.notNull(each.temporal); if (each.origin != null) { result.add(new ModifiedAllocation(each.origin, each.temporal)); } } return result; } public static List<ResourceAllocation<?>> getNewFrom( List<AllocationRow> rows) { List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); for (AllocationRow each : rows) { Validate.notNull(each.temporal); if (each.origin == null) { result.add(each.temporal); } } return result; } public static List<ResourceAllocation<?>> getTemporalFrom( List<AllocationRow> rows) { List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); for (AllocationRow each : rows) { if (each.temporal != null) { result.add(each.temporal); } } return result; } public static List<GenericAllocationRow> getGeneric( Collection<? extends AllocationRow> all) { List<GenericAllocationRow> result = new ArrayList<GenericAllocationRow>(); for (AllocationRow each : all) { if (each.isGeneric()) { result.add((GenericAllocationRow) each); } } return result; } public static List<AllocationRow> toRows( Collection<? extends ResourceAllocation<?>> resourceAllocations) { List<AllocationRow> result = new ArrayList<AllocationRow>(); result.addAll(GenericAllocationRow .toGenericAllocations(resourceAllocations)); result.addAll(SpecificAllocationRow .toSpecificAllocations(resourceAllocations)); return result; } private ResourceAllocation<?> origin; private ResourceAllocation<?> temporal; private String name; private ResourcesPerDay resourcesPerDay; private Intbox hoursInput = new Intbox(); private final Decimalbox resourcesPerDayInput = new Decimalbox(); private void initializeResourcesPerDayInput() { resourcesPerDayInput.setConstraint(new SimpleConstraint( SimpleConstraint.NO_NEGATIVE)); Util.bind(resourcesPerDayInput, new Util.Getter<BigDecimal>() { @Override public BigDecimal get() { return getResourcesPerDay().getAmount(); } }, new Util.Setter<BigDecimal>() { @Override public void set(BigDecimal value) { BigDecimal amount = value == null ? new BigDecimal(0) : value; resourcesPerDay = ResourcesPerDay.amount(amount); } }); } public AllocationRow() { resourcesPerDay = ResourcesPerDay.amount(0); initializeResourcesPerDayInput(); hoursInput.setValue(0); hoursInput.setDisabled(true); hoursInput.setConstraint(new SimpleConstraint( SimpleConstraint.NO_NEGATIVE)); } public abstract ResourcesPerDayModification toResourcesPerDayModification( Task task); public abstract HoursModification toHoursModification(Task task); public boolean isCreating() { return origin == null; } public boolean isModifying() { return origin != null; } public ResourceAllocation<?> getOrigin() { return origin; } protected void setOrigin(ResourceAllocation<?> allocation) { this.origin = allocation; loadHours(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public ResourcesPerDay getResourcesPerDay() { return this.resourcesPerDay; } public ResourcesPerDay getResourcesPerDayFromInput() { BigDecimal value = resourcesPerDayInput.getValue(); value = value != null ? value : BigDecimal.ZERO; return ResourcesPerDay.amount(value); } public void setResourcesPerDay(ResourcesPerDay resourcesPerDay) { this.resourcesPerDay = resourcesPerDay; resourcesPerDayInput.setValue(this.resourcesPerDay.getAmount()); } public void setTemporal(ResourceAllocation<?> last) { Validate.notNull(last); this.temporal = last; } public abstract boolean isGeneric(); public boolean isEmptyResourcesPerDay() { return getResourcesPerDay().isZero(); } public abstract List<Resource> getAssociatedResources(); public Intbox getHoursInput() { return hoursInput; } public Decimalbox getResourcesPerDayInput() { return resourcesPerDayInput; } public void addListenerForInputChange(EventListener onChangeListener) { getHoursInput().addEventListener(Events.ON_CHANGE, onChangeListener); getResourcesPerDayInput().addEventListener(Events.ON_CHANGE, onChangeListener); } public void loadHours() { hoursInput.setValue(getHours()); } protected int getHoursFromInput() { return hoursInput.getValue() != null ? hoursInput.getValue() : 0; } private Integer getHours() { if (temporal != null) { return temporal.getAssignedHours(); } if (origin != null) { return origin.getAssignedHours(); } return 0; } public void applyDisabledRules(CalculatedValue calculatedValue, boolean recommendedAllocation) { hoursInput .setDisabled(calculatedValue != CalculatedValue.RESOURCES_PER_DAY || recommendedAllocation); hoursInput.setConstraint(constraintForHoursInput()); resourcesPerDayInput .setDisabled(calculatedValue == CalculatedValue.RESOURCES_PER_DAY || recommendedAllocation); resourcesPerDayInput.setConstraint(constraintForResourcesPerDayInput()); } private Constraint constraintForHoursInput() { if (hoursInput.isDisabled()) { return null; } return new SimpleConstraint(SimpleConstraint.NO_EMPTY | SimpleConstraint.NO_NEGATIVE); } private Constraint constraintForResourcesPerDayInput() { if (resourcesPerDayInput.isDisabled()) { return null; } return CONSTRAINT_FOR_RESOURCES_PER_DAY; } public void loadDataFromLast() { hoursInput.setValue(temporal.getAssignedHours()); resourcesPerDayInput.setValue(temporal.getResourcesPerDay().getAmount()); } public void addListenerForHoursInputChange(EventListener listener) { hoursInput.addEventListener(Events.ON_CHANGE, listener); } public void setHoursToInput(Integer hours) { hoursInput.setValue(hours); } public void addListenerForResourcesPerDayInputChange( EventListener resourcesPerDayRowInputChange) { resourcesPerDayInput.addEventListener(Events.ON_CHANGE, resourcesPerDayRowInputChange); } }
navalplanner-webapp/src/main/java/org/navalplanner/web/planner/allocation/AllocationRow.java
/* * This file is part of ###PROJECT_NAME### * * Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * * 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.navalplanner.web.planner.allocation; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.lang.Validate; import org.navalplanner.business.planner.entities.CalculatedValue; import org.navalplanner.business.planner.entities.ResourceAllocation; import org.navalplanner.business.planner.entities.ResourcesPerDay; import org.navalplanner.business.planner.entities.Task; import org.navalplanner.business.planner.entities.Task.ModifiedAllocation; import org.navalplanner.business.planner.entities.allocationalgorithms.HoursModification; import org.navalplanner.business.planner.entities.allocationalgorithms.ResourcesPerDayModification; import org.navalplanner.business.resources.entities.Resource; import org.navalplanner.web.common.Util; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Constraint; import org.zkoss.zul.Decimalbox; import org.zkoss.zul.Intbox; import org.zkoss.zul.SimpleConstraint; /** * The information that must be introduced to create a * {@link ResourceAllocation} * @author Óscar González Fernández <[email protected]> */ public abstract class AllocationRow { public static final SimpleConstraint CONSTRAINT_FOR_RESOURCES_PER_DAY = new SimpleConstraint( SimpleConstraint.NO_EMPTY | SimpleConstraint.NO_NEGATIVE); public static void assignHours(List<AllocationRow> rows, int[] hours) { int i = 0; for (AllocationRow each : rows) { each.hoursInput.setValue(hours[i++]); } } public static void assignResourcesPerDay(List<AllocationRow> rows, ResourcesPerDay[] resourcesPerDay) { int i = 0; for (AllocationRow each : rows) { each.setResourcesPerDay(resourcesPerDay[i++]); } } public static void loadDataFromLast(Collection<? extends AllocationRow> rows) { for (AllocationRow each : rows) { each.loadDataFromLast(); } } public static List<ResourcesPerDayModification> createAndAssociate( Task task, Collection<? extends AllocationRow> rows) { List<ResourcesPerDayModification> result = new ArrayList<ResourcesPerDayModification>(); for (AllocationRow each : rows) { ResourcesPerDayModification modification = each .toResourcesPerDayModification(task); result.add(modification); each.setLast(modification.getBeingModified()); } return result; } public static List<HoursModification> createHoursModificationsAndAssociate( Task task, List<AllocationRow> currentRows) { List<HoursModification> result = new ArrayList<HoursModification>(); for (AllocationRow each : currentRows) { HoursModification hoursModification = each .toHoursModification(task); result.add(hoursModification); each.setLast(hoursModification.getBeingModified()); } return result; } public static List<ModifiedAllocation> getModifiedFrom( Collection<? extends AllocationRow> rows) { List<ModifiedAllocation> result = new ArrayList<ModifiedAllocation>(); for (AllocationRow each : rows) { Validate.notNull(each.last); if (each.origin != null) { result.add(new ModifiedAllocation(each.origin, each.last)); } } return result; } public static List<ResourceAllocation<?>> getNewFrom( List<AllocationRow> rows) { List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); for (AllocationRow each : rows) { Validate.notNull(each.last); if (each.origin == null) { result.add(each.last); } } return result; } public static List<GenericAllocationRow> getGeneric( Collection<? extends AllocationRow> all) { List<GenericAllocationRow> result = new ArrayList<GenericAllocationRow>(); for (AllocationRow each : all) { if (each.isGeneric()) { result.add((GenericAllocationRow) each); } } return result; } public static List<AllocationRow> toRows( Collection<? extends ResourceAllocation<?>> resourceAllocations) { List<AllocationRow> result = new ArrayList<AllocationRow>(); result.addAll(GenericAllocationRow .toGenericAllocations(resourceAllocations)); result.addAll(SpecificAllocationRow .toSpecificAllocations(resourceAllocations)); return result; } private ResourceAllocation<?> origin; private ResourceAllocation<?> last; private String name; private ResourcesPerDay resourcesPerDay; private Intbox hoursInput = new Intbox(); private final Decimalbox resourcesPerDayInput = new Decimalbox(); private void initializeResourcesPerDayInput() { resourcesPerDayInput.setConstraint(new SimpleConstraint( SimpleConstraint.NO_NEGATIVE)); Util.bind(resourcesPerDayInput, new Util.Getter<BigDecimal>() { @Override public BigDecimal get() { return getResourcesPerDay().getAmount(); } }, new Util.Setter<BigDecimal>() { @Override public void set(BigDecimal value) { BigDecimal amount = value == null ? new BigDecimal(0) : value; resourcesPerDay = ResourcesPerDay.amount(amount); } }); } public AllocationRow() { resourcesPerDay = ResourcesPerDay.amount(0); initializeResourcesPerDayInput(); hoursInput.setValue(0); hoursInput.setDisabled(true); hoursInput.setConstraint(new SimpleConstraint( SimpleConstraint.NO_NEGATIVE)); } public abstract ResourcesPerDayModification toResourcesPerDayModification( Task task); public abstract HoursModification toHoursModification(Task task); public boolean isCreating() { return origin == null; } public boolean isModifying() { return origin != null; } public ResourceAllocation<?> getOrigin() { return origin; } protected void setOrigin(ResourceAllocation<?> allocation) { this.origin = allocation; loadHours(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public ResourcesPerDay getResourcesPerDay() { return this.resourcesPerDay; } public ResourcesPerDay getResourcesPerDayFromInput() { BigDecimal value = resourcesPerDayInput.getValue(); value = value != null ? value : BigDecimal.ZERO; return ResourcesPerDay.amount(value); } public void setResourcesPerDay(ResourcesPerDay resourcesPerDay) { this.resourcesPerDay = resourcesPerDay; resourcesPerDayInput.setValue(this.resourcesPerDay.getAmount()); } public void setLast(ResourceAllocation<?> last) { Validate.notNull(last); this.last = last; } public abstract boolean isGeneric(); public boolean isEmptyResourcesPerDay() { return getResourcesPerDay().isZero(); } public abstract List<Resource> getAssociatedResources(); public Intbox getHoursInput() { return hoursInput; } public Decimalbox getResourcesPerDayInput() { return resourcesPerDayInput; } public void addListenerForInputChange(EventListener onChangeListener) { getHoursInput().addEventListener(Events.ON_CHANGE, onChangeListener); getResourcesPerDayInput().addEventListener(Events.ON_CHANGE, onChangeListener); } public void loadHours() { hoursInput.setValue(getHours()); } protected int getHoursFromInput() { return hoursInput.getValue() != null ? hoursInput.getValue() : 0; } private Integer getHours() { if (last != null) { return last.getAssignedHours(); } if (origin != null) { return origin.getAssignedHours(); } return 0; } public void applyDisabledRules(CalculatedValue calculatedValue, boolean recommendedAllocation) { hoursInput .setDisabled(calculatedValue != CalculatedValue.RESOURCES_PER_DAY || recommendedAllocation); hoursInput.setConstraint(constraintForHoursInput()); resourcesPerDayInput .setDisabled(calculatedValue == CalculatedValue.RESOURCES_PER_DAY || recommendedAllocation); resourcesPerDayInput.setConstraint(constraintForResourcesPerDayInput()); } private Constraint constraintForHoursInput() { if (hoursInput.isDisabled()) { return null; } return new SimpleConstraint(SimpleConstraint.NO_EMPTY | SimpleConstraint.NO_NEGATIVE); } private Constraint constraintForResourcesPerDayInput() { if (resourcesPerDayInput.isDisabled()) { return null; } return CONSTRAINT_FOR_RESOURCES_PER_DAY; } public void loadDataFromLast() { hoursInput.setValue(last.getAssignedHours()); resourcesPerDayInput.setValue(last.getResourcesPerDay().getAmount()); } public void addListenerForHoursInputChange(EventListener listener) { hoursInput.addEventListener(Events.ON_CHANGE, listener); } public void setHoursToInput(Integer hours) { hoursInput.setValue(hours); } public void addListenerForResourcesPerDayInputChange( EventListener resourcesPerDayRowInputChange) { resourcesPerDayInput.addEventListener(Events.ON_CHANGE, resourcesPerDayRowInputChange); } }
ItEr39S16CUConfiguracionMaquinasItEr35S09: Renaming last to temporal and adding a method to get all temporal allocations from some rows
navalplanner-webapp/src/main/java/org/navalplanner/web/planner/allocation/AllocationRow.java
ItEr39S16CUConfiguracionMaquinasItEr35S09: Renaming last to temporal and adding a method to get all temporal allocations from some rows
<ide><path>avalplanner-webapp/src/main/java/org/navalplanner/web/planner/allocation/AllocationRow.java <ide> ResourcesPerDayModification modification = each <ide> .toResourcesPerDayModification(task); <ide> result.add(modification); <del> each.setLast(modification.getBeingModified()); <add> each.setTemporal(modification.getBeingModified()); <ide> } <ide> return result; <ide> } <ide> HoursModification hoursModification = each <ide> .toHoursModification(task); <ide> result.add(hoursModification); <del> each.setLast(hoursModification.getBeingModified()); <add> each.setTemporal(hoursModification.getBeingModified()); <ide> } <ide> return result; <ide> } <ide> Collection<? extends AllocationRow> rows) { <ide> List<ModifiedAllocation> result = new ArrayList<ModifiedAllocation>(); <ide> for (AllocationRow each : rows) { <del> Validate.notNull(each.last); <add> Validate.notNull(each.temporal); <ide> if (each.origin != null) { <del> result.add(new ModifiedAllocation(each.origin, each.last)); <add> result.add(new ModifiedAllocation(each.origin, each.temporal)); <ide> } <ide> } <ide> return result; <ide> List<AllocationRow> rows) { <ide> List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); <ide> for (AllocationRow each : rows) { <del> Validate.notNull(each.last); <add> Validate.notNull(each.temporal); <ide> if (each.origin == null) { <del> result.add(each.last); <add> result.add(each.temporal); <add> } <add> } <add> return result; <add> } <add> <add> public static List<ResourceAllocation<?>> getTemporalFrom( <add> List<AllocationRow> rows) { <add> List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); <add> for (AllocationRow each : rows) { <add> if (each.temporal != null) { <add> result.add(each.temporal); <ide> } <ide> } <ide> return result; <ide> <ide> private ResourceAllocation<?> origin; <ide> <del> private ResourceAllocation<?> last; <add> private ResourceAllocation<?> temporal; <ide> <ide> private String name; <ide> <ide> resourcesPerDayInput.setValue(this.resourcesPerDay.getAmount()); <ide> } <ide> <del> public void setLast(ResourceAllocation<?> last) { <add> public void setTemporal(ResourceAllocation<?> last) { <ide> Validate.notNull(last); <del> this.last = last; <add> this.temporal = last; <ide> } <ide> <ide> public abstract boolean isGeneric(); <ide> } <ide> <ide> private Integer getHours() { <del> if (last != null) { <del> return last.getAssignedHours(); <add> if (temporal != null) { <add> return temporal.getAssignedHours(); <ide> } <ide> if (origin != null) { <ide> return origin.getAssignedHours(); <ide> } <ide> <ide> public void loadDataFromLast() { <del> hoursInput.setValue(last.getAssignedHours()); <del> resourcesPerDayInput.setValue(last.getResourcesPerDay().getAmount()); <add> hoursInput.setValue(temporal.getAssignedHours()); <add> resourcesPerDayInput.setValue(temporal.getResourcesPerDay().getAmount()); <ide> } <ide> <ide> public void addListenerForHoursInputChange(EventListener listener) {
JavaScript
mit
9d9105f0faa6ee1a3a65650094208e8ad760d84e
0
HexChronicle/Fwibble,HexChronicle/Fwibble
var React = require('react'); var ReactDOM = require('react-dom'); var ReactRouter = require('react-router'); var Link = ReactRouter.Link; var Logo = require('./../../images/Fwibble-logo-cropped.png') module.exports = React.createClass({ render: function() { return ( <div className='navbar navbar-default navbar-static-top'> <div className='container-fluid'> <div className='navbar-header'> <div><img src={Logo} alt="Fwibble" className="navbar-brand"/></div> </div> <ul className="nav navbar-nav navbar-right"> <li> { this.props.loggedIn ? (<Link to='/signout'>SIGN OUT</Link>) : (<Link to='/signin'>SIGN IN</Link>)} </li> <li><Link to={`/gameview/${this.props.active_game}`} className="menuOptions">MY GAME</Link></li> </ul> </div> </div> ) } });
app/components/navbar/NavBar.js
var React = require('react'); var ReactDOM = require('react-dom'); var ReactRouter = require('react-router'); var Link = ReactRouter.Link; var Logo = require('./../../images/Fwibble-logo-cropped.png') module.exports = React.createClass({ render: function() { return ( <div className='navbar navbar-default navbar-static-top'> <div className='container-fluid'> <div className='navbar-header'> <div><img src={Logo} width='120px' alt="Fwibble" className="img-responsive"/></div> </div> <ul className="nav navbar-nav navbar-right"> <li> { this.props.loggedIn ? (<Link to='/signout'>SIGN OUT</Link>) : (<Link to='/signin'>SIGN IN</Link>)} </li> <li><Link to={`/gameview/${this.props.active_game}`} className="menuOptions">MY GAME</Link></li> </ul> </div> </div> ) } });
fixed navbar logo issue
app/components/navbar/NavBar.js
fixed navbar logo issue
<ide><path>pp/components/navbar/NavBar.js <ide> <div className='navbar navbar-default navbar-static-top'> <ide> <div className='container-fluid'> <ide> <div className='navbar-header'> <del> <div><img src={Logo} width='120px' alt="Fwibble" className="img-responsive"/></div> <add> <div><img src={Logo} alt="Fwibble" className="navbar-brand"/></div> <ide> </div> <ide> <ul className="nav navbar-nav navbar-right"> <ide> <li>
Java
mit
4c5e6f2c9bf3a2ce9bd4439f6cc8b1a9ccee7dab
0
cs2103aug2014-t09-4j/main
package bakatxt.core; import java.util.ArrayList; import java.util.LinkedList; import bakatxt.gui.BakaUI; import bakatxt.international.BakaTongue; public class BakaProcessor { private static String COMMAND_EDIT = "EDIT"; private static String COMMAND_ADD = "ADD"; private static String SPACE = " "; private static String STRING_NULL = "null"; private static Database _database; private static BakaParser _parser; private static LinkedList<Task> _displayTasks; private static ReverseAction _ra; private static Integer editStage = 0; private static Task originalTask; private static Task editTask; private static boolean _choosingLanguage = false; enum CommandType { HELP, ADD, DELETE, SHOW, DISPLAY, CLEAR, DEFAULT, REMOVE, EDIT, UNDO, REDO, LANGUAGE, SEARCH, DONE, EXIT } public BakaProcessor() { _database = Database.getInstance(); _parser = new BakaParser(); _displayTasks = _database.getAllUndoneTasks(); _ra = new ReverseAction(); } private void displayTask(String input) { input = input.trim(); if (input.contains(SPACE)) { String content = _parser.getString(input); if (content.equals("week")) { _displayTasks = _database.getWeekTasks(); } else { String currentDate = _parser.getDate(content).trim(); _displayTasks = _database.getTasksWithDate(currentDate); } } else { _displayTasks = _database.getAllUndoneTasks(); } } private void searchTask(String input) { String title = _parser.getString(input).trim(); _displayTasks = _database.getTaskWithTitle(title); } public LinkedList<Task> getAllTasks() { return _displayTasks; } private void clearTask(String command) { UserAction inputCmd; inputCmd = new UserClear(command); _ra.execute(inputCmd); _database.getAllUndoneTasks(); } public boolean executeCommand(String input) { if (_choosingLanguage) { BakaTongue.setLanguage(input); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); _choosingLanguage = false; input = "display"; } input = BakaTongue.toEnglish(input); String command = _parser.getCommand(input); if (!command.equals(COMMAND_EDIT) && editStage > 0) { executeCommand(COMMAND_EDIT + SPACE + input); return true; } CommandType commandType; /* * The command word will be stored as a string and it will get * CommandType value but will return DEFAULT if a wrong command is * entered */ try { commandType = CommandType.valueOf(command); } catch (IllegalArgumentException e) { commandType = CommandType.DEFAULT; } switch (commandType) { case HELP : showHelp(); return true; case ADD : return addTask(input, command); case REMOVE : case DELETE : return deleteTask(input, command); case SHOW : case DISPLAY : displayTask(input); return true; case CLEAR : clearTask(command); break; case EDIT : return editTask(input, command); case UNDO : return undoTask(); case REDO : return redoTask(); case LANGUAGE : languageSelector(input); return true; case EXIT : _database.close(); System.exit(0); return true; case SEARCH : searchTask(input); return true; case DONE : return markDoneTask(input, command); case DEFAULT : return addTaskWithNoCommandWord(input); default : return false; } _displayTasks = _database.getAllUndoneTasks(); return true; } private boolean undoTask() { boolean isSuccessful = _ra.undo(); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean redoTask() { boolean isSuccessful = _ra.redo(); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private void showHelp() { _displayTasks = new LinkedList<Task>(); for (CommandType c : CommandType.values()) { String cmd = c.toString(); if (cmd.equals("DEFAULT") || cmd.equals("HELP")) { continue; } String languageKey = "COMMAND_" + cmd; Task command = new Task(BakaTongue.getString(languageKey)); command.setDate(BakaTongue.getString("COMMAND_HELP")); _displayTasks.add(command); } } private void languageSelector(String input) { input = input.trim(); if (input.contains(SPACE)) { BakaTongue.setLanguage(_parser.getString(input)); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); _displayTasks = _database.getAllUndoneTasks(); } else { _choosingLanguage = true; _displayTasks = BakaTongue.languageChoices(); BakaUI.setAlertMessageText(BakaTongue .getString("MESSAGE_LANGUAGE_CHOICE")); } } private boolean addTaskWithNoCommandWord(String input) { UserAction inputCmd; Task task; task = _parser.add(COMMAND_ADD + SPACE + input); inputCmd = new UserAction(COMMAND_ADD, task); boolean isSuccessful = _ra.execute(inputCmd); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean editTask(String input, String command) { boolean isSuccessful = false; if (editStage == 0) { editStage = 6; String index = _parser.getString(input).trim(); int trueIndex = Integer.valueOf(index.trim()) - 1; _displayTasks = _database.getAllUndoneTasks(); editTask = _displayTasks.get(trueIndex); originalTask = new Task(editTask); BakaUI.setInputBoxText(editTask.getTitle()); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_TITLE")); isSuccessful = true; } else { input = _parser.getString(input); switch (editStage) { case 6 : isSuccessful = editTitle(input); break; case 5 : isSuccessful = editVenue(input); break; case 4 : isSuccessful = editDate(input); break; case 3 : isSuccessful = editStartTime(input); break; case 2 : isSuccessful = editEndTime(input); break; case 1 : isSuccessful = editDescription(input, command); break; default : break; } editStage--; } _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean editDescription(String input, String command) { UserAction inputCmd; String nextStagePrompt; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_DESCRIPTION").toLowerCase())) { input = null; } editTask.setDescription(input); inputCmd = new UserEditTask(command, originalTask, editTask); boolean isSuccessful = _ra.execute(inputCmd); nextStagePrompt = ""; BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); return isSuccessful; } private boolean editStartTime(String input) { String nextStagePrompt; String parsedDateTime; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_START_TIME").toLowerCase())) { input = null; } parsedDateTime = _parser.getTime(input); editTask.setTime(parsedDateTime); nextStagePrompt = editTask.getEndTime(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_END_TIME"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_END_TIME")); return true; } private boolean editEndTime(String input) { String nextStagePrompt; String parsedDateTime; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_END_TIME").toLowerCase())) { input = null; } parsedDateTime = _parser.getTime(input); editTask.setEndTime(parsedDateTime); nextStagePrompt = editTask.getDescription(); if (nextStagePrompt == null || nextStagePrompt.trim().isEmpty()) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_DESCRIPTION"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_DESCRIPTION")); return true; } private boolean editDate(String input) { String nextStagePrompt; String parsedDateTime; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_DATE").toLowerCase())) { input = null; } parsedDateTime = _parser.getDate(input); editTask.setDate(parsedDateTime); nextStagePrompt = editTask.getTime(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_START_TIME"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_START_TIME")); return true; } private boolean editVenue(String input) { String nextStagePrompt; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_VENUE").toLowerCase())) { input = null; } editTask.setVenue(input); nextStagePrompt = editTask.getDate(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_DATE"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_DATE")); return true; } private boolean editTitle(String input) { String nextStagePrompt; if (input.trim().isEmpty()) { editTask.setTitle(originalTask.getTitle()); } else { editTask.setTitle(input); } nextStagePrompt = editTask.getVenue(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_VENUE"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_VENUE")); return true; } private boolean deleteTask(String input, String command) { UserAction inputCmd; Task task; String content = _parser.getString(input).trim(); ArrayList<Integer> listOfIndex = _parser.getIndexList(content); _displayTasks = _database.getAllUndoneTasks(); boolean isSuccessful = true; for (int i = 0; i < listOfIndex.size(); i++) { int trueIndex = listOfIndex.get(i); task = _displayTasks.get(trueIndex - 1); inputCmd = new UserAction(command, task); isSuccessful = isSuccessful && _ra.execute(inputCmd); } _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean markDoneTask(String input, String command) { Task task; UserAction inputCmd; String content = _parser.getString(input).trim(); ArrayList<Integer> listOfIndex = _parser.getIndexList(content); _displayTasks = _database.getAllUndoneTasks(); boolean isSuccessful = true; for (int i = 0; i < listOfIndex.size(); i++) { int trueIndex = listOfIndex.get(i); task = _displayTasks.get(trueIndex - 1); inputCmd = new UserEditStatus(command, task, true); isSuccessful = isSuccessful && _ra.execute(inputCmd); } _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean addTask(String input, String command) { UserAction inputCmd; Task task; task = _parser.add(input); inputCmd = new UserAction(command, task); boolean isSuccessful = _ra.execute(inputCmd); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } }
src/bakatxt/core/BakaProcessor.java
package bakatxt.core; import java.util.ArrayList; import java.util.LinkedList; import bakatxt.gui.BakaUI; import bakatxt.international.BakaTongue; public class BakaProcessor { private static String COMMAND_EDIT = "EDIT"; private static String COMMAND_ADD = "ADD"; private static String SPACE = " "; private static String STRING_NULL = "null"; private static Database _database; private static BakaParser _parser; private static LinkedList<Task> _displayTasks; private static ReverseAction _ra; private static Integer editStage = 0; private static Task originalTask; private static Task editTask; private static boolean _choosingLanguage = false; enum CommandType { HELP, ADD, DELETE, SHOW, DISPLAY, CLEAR, DEFAULT, REMOVE, EDIT, UNDO, REDO, LANGUAGE, SEARCH, DONE, EXIT } public BakaProcessor() { _database = Database.getInstance(); _parser = new BakaParser(); _displayTasks = _database.getAllUndoneTasks(); _ra = new ReverseAction(); } private void displayTask(String input) { input = input.trim(); if (input.contains(SPACE)) { String content = _parser.getString(input); if (content.equals("week")) { _displayTasks = _database.getWeekTasks(); } else { String currentDate = _parser.getDate(content).trim(); _displayTasks = _database.getTasksWithDate(currentDate); } } else { _displayTasks = _database.getAllUndoneTasks(); } } private void searchTask(String input) { String title = _parser.getString(input).trim(); _displayTasks = _database.getTaskWithTitle(title); } public LinkedList<Task> getAllTasks() { return _displayTasks; } private void clearTask(String command) { UserAction inputCmd; inputCmd = new UserClear(command); _ra.execute(inputCmd); _database.getAllUndoneTasks(); } public boolean executeCommand(String input) { if (_choosingLanguage) { BakaTongue.setLanguage(input); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); _choosingLanguage = false; input = "display"; } input = BakaTongue.toEnglish(input); String command = _parser.getCommand(input); if (!command.equals(COMMAND_EDIT) && editStage > 0) { executeCommand(COMMAND_EDIT + SPACE + input); return true; } CommandType commandType; /* * The command word will be stored as a string and it will get * CommandType value but will return DEFAULT if a wrong command is * entered */ try { commandType = CommandType.valueOf(command); } catch (IllegalArgumentException e) { commandType = CommandType.DEFAULT; } switch (commandType) { case HELP : showHelp(); return true; case ADD : return addTask(input, command); case REMOVE : case DELETE : return deleteTask(input, command); case SHOW : case DISPLAY : displayTask(input); return true; case CLEAR : clearTask(command); break; case EDIT : return editTask(input, command); case UNDO : return undoTask(); case REDO : return redoTask(); case LANGUAGE : languageSelector(input); return true; case EXIT : _database.close(); System.exit(0); return true; case SEARCH : searchTask(input); return true; case DONE : return markDoneTask(input, command); case DEFAULT : return addTaskWithNoCommandWord(input); default : return false; } _displayTasks = _database.getAllUndoneTasks(); return true; } private boolean undoTask() { boolean isSuccessful = _ra.undo(); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean redoTask() { boolean isSuccessful = _ra.redo(); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private void showHelp() { _displayTasks = new LinkedList<Task>(); for (CommandType c : CommandType.values()) { String cmd = c.toString(); if (cmd.equals("DEFAULT") || cmd.equals("HELP")) { continue; } String languageKey = "COMMAND_" + cmd; Task command = new Task(BakaTongue.getString(languageKey)); command.setDate(BakaTongue.getString("COMMAND_HELP")); _displayTasks.add(command); } } private void languageSelector(String input) { input = input.trim(); if (input.contains(SPACE)) { BakaTongue.setLanguage(_parser.getString(input)); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); _displayTasks = _database.getAllUndoneTasks(); } else { _choosingLanguage = true; _displayTasks = BakaTongue.languageChoices(); BakaUI.setAlertMessageText(BakaTongue .getString("MESSAGE_LANGUAGE_CHOICE")); } } private boolean addTaskWithNoCommandWord(String input) { UserAction inputCmd; Task task; task = _parser.add(COMMAND_ADD + SPACE + input); inputCmd = new UserAction(COMMAND_ADD, task); boolean isSuccessful = _ra.execute(inputCmd); return isSuccessful; } private boolean editTask(String input, String command) { boolean isSuccessful = false; if (editStage == 0) { editStage = 6; String index = _parser.getString(input).trim(); int trueIndex = Integer.valueOf(index.trim()) - 1; _displayTasks = _database.getAllUndoneTasks(); editTask = _displayTasks.get(trueIndex); originalTask = new Task(editTask); BakaUI.setInputBoxText(editTask.getTitle()); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_TITLE")); isSuccessful = true; } else { input = _parser.getString(input); switch (editStage) { case 6 : isSuccessful = editTitle(input); break; case 5 : isSuccessful = editVenue(input); break; case 4 : isSuccessful = editDate(input); break; case 3 : isSuccessful = editStartTime(input); break; case 2 : isSuccessful = editEndTime(input); break; case 1 : isSuccessful = editDescription(input, command); break; default : break; } editStage--; } return isSuccessful; } private boolean editDescription(String input, String command) { UserAction inputCmd; String nextStagePrompt; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_DESCRIPTION").toLowerCase())) { input = null; } editTask.setDescription(input); inputCmd = new UserEditTask(command, originalTask, editTask); boolean isSuccessful = _ra.execute(inputCmd); nextStagePrompt = ""; BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); return isSuccessful; } private boolean editStartTime(String input) { String nextStagePrompt; String parsedDateTime; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_START_TIME").toLowerCase())) { input = null; } parsedDateTime = _parser.getTime(input); editTask.setTime(parsedDateTime); nextStagePrompt = editTask.getEndTime(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_END_TIME"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_END_TIME")); return true; } private boolean editEndTime(String input) { String nextStagePrompt; String parsedDateTime; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_END_TIME").toLowerCase())) { input = null; } parsedDateTime = _parser.getTime(input); editTask.setEndTime(parsedDateTime); nextStagePrompt = editTask.getDescription(); if (nextStagePrompt == null || nextStagePrompt.trim().isEmpty()) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_DESCRIPTION"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_DESCRIPTION")); return true; } private boolean editDate(String input) { String nextStagePrompt; String parsedDateTime; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_DATE").toLowerCase())) { input = null; } parsedDateTime = _parser.getDate(input); editTask.setDate(parsedDateTime); nextStagePrompt = editTask.getTime(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_START_TIME"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_START_TIME")); return true; } private boolean editVenue(String input) { String nextStagePrompt; if (input.toLowerCase().equals( BakaTongue.getString("USER_PROMPT_VENUE").toLowerCase())) { input = null; } editTask.setVenue(input); nextStagePrompt = editTask.getDate(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_DATE"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_DATE")); return true; } private boolean editTitle(String input) { String nextStagePrompt; if (input.trim().isEmpty()) { editTask.setTitle(originalTask.getTitle()); } else { editTask.setTitle(input); } nextStagePrompt = editTask.getVenue(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_VENUE"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_VENUE")); return true; } private boolean deleteTask(String input, String command) { UserAction inputCmd; Task task; String content = _parser.getString(input).trim(); ArrayList<Integer> listOfIndex = _parser.getIndexList(content); _displayTasks = _database.getAllUndoneTasks(); boolean isSuccessful = true; for (int i = 0; i < listOfIndex.size(); i++) { int trueIndex = listOfIndex.get(i); task = _displayTasks.get(trueIndex - 1); inputCmd = new UserAction(command, task); isSuccessful = isSuccessful && _ra.execute(inputCmd); } _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean markDoneTask(String input, String command) { Task task; UserAction inputCmd; String content = _parser.getString(input).trim(); ArrayList<Integer> listOfIndex = _parser.getIndexList(content); _displayTasks = _database.getAllUndoneTasks(); boolean isSuccessful = true; for (int i = 0; i < listOfIndex.size(); i++) { int trueIndex = listOfIndex.get(i); task = _displayTasks.get(trueIndex - 1); inputCmd = new UserEditStatus(command, task, true); isSuccessful = isSuccessful && _ra.execute(inputCmd); } _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } private boolean addTask(String input, String command) { UserAction inputCmd; Task task; task = _parser.add(input); inputCmd = new UserAction(command, task); boolean isSuccessful = _ra.execute(inputCmd); _displayTasks = _database.getAllUndoneTasks(); return isSuccessful; } }
Bug Fix: some commands result in nothing displayed
src/bakatxt/core/BakaProcessor.java
Bug Fix: some commands result in nothing displayed
<ide><path>rc/bakatxt/core/BakaProcessor.java <ide> task = _parser.add(COMMAND_ADD + SPACE + input); <ide> inputCmd = new UserAction(COMMAND_ADD, task); <ide> boolean isSuccessful = _ra.execute(inputCmd); <add> _displayTasks = _database.getAllUndoneTasks(); <ide> return isSuccessful; <ide> } <ide> <ide> } <ide> editStage--; <ide> } <add> _displayTasks = _database.getAllUndoneTasks(); <ide> return isSuccessful; <ide> } <ide>
Java
apache-2.0
f405750e254a45041952bfaeac62b2e6a81a0453
0
SerCeMan/intellij-community,FHannes/intellij-community,hurricup/intellij-community,hurricup/intellij-community,hurricup/intellij-community,jagguli/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,samthor/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,signed/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,supersven/intellij-community,Distrotech/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,caot/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,semonte/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,fitermay/intellij-community,jagguli/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,samthor/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,holmes/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ibinti/intellij-community,samthor/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,adedayo/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,holmes/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,slisson/intellij-community,ryano144/intellij-community,FHannes/intellij-community,amith01994/intellij-community,robovm/robovm-studio,diorcety/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,kool79/intellij-community,robovm/robovm-studio,ryano144/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,diorcety/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,FHannes/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ibinti/intellij-community,asedunov/intellij-community,clumsy/intellij-community,izonder/intellij-community,kdwink/intellij-community,diorcety/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,holmes/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,apixandru/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ryano144/intellij-community,vladmm/intellij-community,fitermay/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,asedunov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,slisson/intellij-community,asedunov/intellij-community,samthor/intellij-community,kdwink/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,supersven/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,kool79/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,holmes/intellij-community,signed/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,supersven/intellij-community,allotria/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,apixandru/intellij-community,adedayo/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,caot/intellij-community,izonder/intellij-community,clumsy/intellij-community,supersven/intellij-community,ibinti/intellij-community,caot/intellij-community,Distrotech/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,izonder/intellij-community,xfournet/intellij-community,signed/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,apixandru/intellij-community,diorcety/intellij-community,samthor/intellij-community,izonder/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,kool79/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,ahb0327/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,apixandru/intellij-community,allotria/intellij-community,dslomov/intellij-community,vladmm/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,signed/intellij-community,asedunov/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,supersven/intellij-community,kdwink/intellij-community,adedayo/intellij-community,da1z/intellij-community,apixandru/intellij-community,holmes/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,semonte/intellij-community,fnouama/intellij-community,apixandru/intellij-community,amith01994/intellij-community,allotria/intellij-community,samthor/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,diorcety/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,kool79/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,asedunov/intellij-community,caot/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,semonte/intellij-community,apixandru/intellij-community,fnouama/intellij-community,kdwink/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,signed/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,caot/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,adedayo/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,retomerz/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,signed/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,jagguli/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,ibinti/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,allotria/intellij-community,da1z/intellij-community,kdwink/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,orekyuu/intellij-community,allotria/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,amith01994/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,caot/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,caot/intellij-community,signed/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,caot/intellij-community,ryano144/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,vladmm/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ryano144/intellij-community,holmes/intellij-community,vladmm/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,samthor/intellij-community,blademainer/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,slisson/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,fitermay/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ryano144/intellij-community,kool79/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,asedunov/intellij-community,hurricup/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,da1z/intellij-community,supersven/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,Distrotech/intellij-community,slisson/intellij-community,holmes/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,caot/intellij-community,samthor/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,semonte/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,xfournet/intellij-community
/* * Copyright 2000-2014 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.util.net; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.util.Base64; import com.intellij.util.SystemProperties; import com.intellij.util.WaitForProgressToShow; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.proxy.CommonProxy; import com.intellij.util.proxy.JavaProxyProperty; import com.intellij.util.xmlb.XmlSerializer; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.Transient; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.*; import java.util.*; @State( name = "HttpConfigurable", storages = { @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml"), @Storage(file = StoragePathMacros.APP_CONFIG + "/proxy.settings.xml") }, storageChooser = HttpConfigurable.StorageChooser.class ) public class HttpConfigurable implements PersistentStateComponent<HttpConfigurable>, ExportableApplicationComponent { public static final int CONNECTION_TIMEOUT = SystemProperties.getIntProperty("idea.connection.timeout", 10000); private static final Logger LOG = Logger.getInstance(HttpConfigurable.class); public boolean PROXY_TYPE_IS_SOCKS = false; public boolean USE_HTTP_PROXY = false; public boolean USE_PROXY_PAC = false; public volatile transient boolean AUTHENTICATION_CANCELLED = false; public String PROXY_HOST = ""; public int PROXY_PORT = 80; public volatile boolean PROXY_AUTHENTICATION = false; public volatile String PROXY_LOGIN = ""; public volatile String PROXY_PASSWORD_CRYPT = ""; public boolean KEEP_PROXY_PASSWORD = false; public transient String LAST_ERROR; private final Map<CommonProxy.HostInfo, ProxyInfo> myGenericPasswords = new THashMap<CommonProxy.HostInfo, ProxyInfo>(); private final Set<CommonProxy.HostInfo> myGenericCancelled = new THashSet<CommonProxy.HostInfo>(); private transient IdeaWideProxySelector mySelector; public String PROXY_EXCEPTIONS = ""; public boolean USE_PAC_URL = false; public String PAC_URL = ""; private transient final Object myLock = new Object(); @SuppressWarnings("UnusedDeclaration") public transient Getter<PasswordAuthentication> myTestAuthRunnable = new StaticGetter<PasswordAuthentication>(null); public transient Getter<PasswordAuthentication> myTestGenericAuthRunnable = new StaticGetter<PasswordAuthentication>(null); public static HttpConfigurable getInstance() { return ServiceManager.getService(HttpConfigurable.class); } public static boolean editConfigurable(@Nullable JComponent parent) { return ShowSettingsUtil.getInstance().editConfigurable(parent, new HTTPProxySettingsPanel(getInstance())); } @Override public HttpConfigurable getState() { CommonProxy.isInstalledAssertion(); final HttpConfigurable state = new HttpConfigurable(); XmlSerializerUtil.copyBean(this, state); if (!KEEP_PROXY_PASSWORD) { state.PROXY_PASSWORD_CRYPT = ""; } correctPasswords(this, state); return state; } @Override public void initComponent() { mySelector = new IdeaWideProxySelector(this); String name = getClass().getName(); CommonProxy.getInstance().setCustom(name, mySelector); CommonProxy.getInstance().setCustomAuth(name, new IdeaWideAuthenticator(this)); } @NotNull public ProxySelector getOnlyBySettingsSelector() { return mySelector; } @Override public void disposeComponent() { final String name = getClass().getName(); CommonProxy.getInstance().removeCustom(name); CommonProxy.getInstance().removeCustomAuth(name); } @NotNull @Override public String getComponentName() { return getClass().getName(); } private void correctPasswords(HttpConfigurable from, HttpConfigurable to) { synchronized (myLock) { to.myGenericPasswords.clear(); for (Map.Entry<CommonProxy.HostInfo, ProxyInfo> entry : from.myGenericPasswords.entrySet()) { if (Boolean.TRUE.equals(entry.getValue().isStore())) { to.myGenericPasswords.put(entry.getKey(), entry.getValue()); } } } } @Override public void loadState(HttpConfigurable state) { XmlSerializerUtil.copyBean(state, this); if (!KEEP_PROXY_PASSWORD) { PROXY_PASSWORD_CRYPT = ""; } correctPasswords(state, this); } public boolean isGenericPasswordCanceled(@NotNull String host, int port) { synchronized (myLock) { return myGenericCancelled.contains(new CommonProxy.HostInfo(null, host, port)); } } public void setGenericPasswordCanceled(final String host, final int port) { synchronized (myLock) { myGenericCancelled.add(new CommonProxy.HostInfo("", host, port)); } } public PasswordAuthentication getGenericPassword(final String host, final int port) { final ProxyInfo proxyInfo; synchronized (myLock) { proxyInfo = myGenericPasswords.get(new CommonProxy.HostInfo("", host, port)); } if (proxyInfo == null) { return null; } return new PasswordAuthentication(proxyInfo.getUsername(), decode(String.valueOf(proxyInfo.getPasswordCrypt())).toCharArray()); } public void putGenericPassword(final String host, final int port, final PasswordAuthentication authentication, final boolean remember) { PasswordAuthentication coded = new PasswordAuthentication(authentication.getUserName(), encode(String.valueOf(authentication.getPassword())).toCharArray()); synchronized (myLock) { myGenericPasswords.put(new CommonProxy.HostInfo("", host, port), new ProxyInfo(remember, coded.getUserName(), String.valueOf(coded.getPassword()))); } } @Transient public String getPlainProxyPassword() { return decode(PROXY_PASSWORD_CRYPT); } private static String decode(String value) { return new String(Base64.decode(value)); } @Transient public void setPlainProxyPassword (String password) { PROXY_PASSWORD_CRYPT = encode(password); } private static String encode(String password) { return new String(Base64.encode(password.getBytes(CharsetToolkit.UTF8_CHARSET))); } public PasswordAuthentication getGenericPromptedAuthentication(final String prefix, final String host, final String prompt, final int port, final boolean remember) { if (ApplicationManager.getApplication().isUnitTestMode()) { return myTestGenericAuthRunnable.get(); } final PasswordAuthentication[] value = new PasswordAuthentication[1]; final Runnable runnable = new Runnable() { @Override public void run() { if (isGenericPasswordCanceled(host, port)) return; final PasswordAuthentication password = getGenericPassword(host, port); if (password != null) { value[0] = password; return; } final AuthenticationDialog dlg = new AuthenticationDialog(PopupUtil.getActiveComponent(), prefix + host, "Please enter credentials for: " + prompt, "", "", remember); dlg.show(); if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) { final AuthenticationPanel panel = dlg.getPanel(); final boolean remember1 = remember && panel.isRememberPassword(); value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); putGenericPassword(host, port, value[0], remember1); } else { setGenericPasswordCanceled(host, port); } } }; runAboveAll(runnable); return value[0]; } public PasswordAuthentication getPromptedAuthentication(final String host, final String prompt) { if (AUTHENTICATION_CANCELLED) return null; final String password = getPlainProxyPassword(); if (PROXY_AUTHENTICATION && ! StringUtil.isEmptyOrSpaces(PROXY_LOGIN) && ! StringUtil.isEmptyOrSpaces(password)) { return new PasswordAuthentication(PROXY_LOGIN, password.toCharArray()); } // do not try to show any dialogs if application is exiting if (ApplicationManager.getApplication() == null || ApplicationManager.getApplication().isDisposeInProgress() || ApplicationManager.getApplication().isDisposed()) return null; if (ApplicationManager.getApplication().isUnitTestMode()) { return myTestGenericAuthRunnable.get(); } final String login = PROXY_LOGIN == null ? "" : PROXY_LOGIN; final PasswordAuthentication[] value = new PasswordAuthentication[1]; final Runnable runnable = new Runnable() { @Override public void run() { if (AUTHENTICATION_CANCELLED) return; // password might have changed, and the check below is for that final String password = getPlainProxyPassword(); if (PROXY_AUTHENTICATION && ! StringUtil.isEmptyOrSpaces(PROXY_LOGIN) && ! StringUtil.isEmptyOrSpaces(password)) { value[0] = new PasswordAuthentication(PROXY_LOGIN, password.toCharArray()); return; } final AuthenticationDialog dlg = new AuthenticationDialog(PopupUtil.getActiveComponent(), "Proxy authentication: " + host, "Please enter credentials for: " + prompt, login, "", KEEP_PROXY_PASSWORD); dlg.show(); if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) { PROXY_AUTHENTICATION = true; final AuthenticationPanel panel = dlg.getPanel(); KEEP_PROXY_PASSWORD = panel.isRememberPassword(); PROXY_LOGIN = panel.getLogin(); setPlainProxyPassword(String.valueOf(panel.getPassword())); value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); } else { AUTHENTICATION_CANCELLED = true; } } }; runAboveAll(runnable); return value[0]; } @SuppressWarnings("MethodMayBeStatic") private void runAboveAll(final Runnable runnable) { final Runnable throughSwing = new Runnable() { @Override public void run() { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); return; } try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException e) { LOG.info(e); } catch (InvocationTargetException e) { LOG.info(e); } } }; if (ProgressManager.getInstance().getProgressIndicator() != null) { if (ProgressManager.getInstance().getProgressIndicator().isModal()) { WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(runnable); } else { throughSwing.run(); } } else { throughSwing.run(); } } //these methods are preserved for compatibility with com.intellij.openapi.project.impl.IdeaServerSettings @Deprecated public void readExternal(Element element) throws InvalidDataException { loadState(XmlSerializer.deserialize(element, HttpConfigurable.class)); } @Deprecated public void writeExternal(Element element) throws WriteExternalException { XmlSerializer.serializeInto(getState(), element); if (USE_PROXY_PAC && USE_HTTP_PROXY && ! ApplicationManager.getApplication().isDisposed()) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); if (frame != null) { USE_PROXY_PAC = false; Messages.showMessageDialog(frame.getComponent(), "Proxy: both 'use proxy' and 'autodetect proxy' settings were set." + "\nOnly one of these options should be selected.\nPlease re-configure.", "Proxy Setup", Messages.getWarningIcon()); editConfigurable(frame.getComponent()); } } }, ModalityState.NON_MODAL); } } /** * todo [all] It is NOT necessary to call anything if you obey common IDEA proxy settings; * todo if you want to define your own behaviour, refer to {@link com.intellij.util.proxy.CommonProxy} * * also, this method is useful in a way that it test connection to the host [through proxy] * * @param url URL for HTTP connection * @throws IOException */ public void prepareURL(@NotNull String url) throws IOException { URLConnection connection = openConnection(url); try { connection.connect(); connection.getInputStream(); } catch (IOException e) { throw e; } catch (Throwable ignored) { } finally { if (connection instanceof HttpURLConnection) { ((HttpURLConnection)connection).disconnect(); } } } @NotNull public URLConnection openConnection(@NotNull String location) throws IOException { CommonProxy.isInstalledAssertion(); final URL url = new URL(location); URLConnection urlConnection = null; final List<Proxy> proxies = CommonProxy.getInstance().select(url); if (ContainerUtil.isEmpty(proxies)) { urlConnection = url.openConnection(); } else { IOException exception = null; for (Proxy proxy : proxies) { try { urlConnection = url.openConnection(proxy); } catch (IOException e) { // continue iteration exception = e; } } if (urlConnection == null && exception != null) { throw exception; } } assert urlConnection != null; urlConnection.setReadTimeout(CONNECTION_TIMEOUT); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); return urlConnection; } /** * Opens HTTP connection to a given location using configured http proxy settings. * @param location url to connect to * @return instance of {@link HttpURLConnection} * @throws IOException in case of any I/O troubles or if created connection isn't instance of HttpURLConnection. */ @NotNull public HttpURLConnection openHttpConnection(@NotNull String location) throws IOException { URLConnection urlConnection = openConnection(location); if (urlConnection instanceof HttpURLConnection) { return (HttpURLConnection) urlConnection; } else { throw new IOException("Expected " + HttpURLConnection.class + ", but got " + urlConnection.getClass()); } } public static List<KeyValue<String, String>> getJvmPropertiesList(final boolean withAutodetection, @Nullable final URI uri) { final HttpConfigurable me = getInstance(); if (! me.USE_HTTP_PROXY && ! me.USE_PROXY_PAC) { return Collections.emptyList(); } final List<KeyValue<String, String>> result = new ArrayList<KeyValue<String, String>>(); if (me.USE_HTTP_PROXY) { final boolean putCredentials = me.KEEP_PROXY_PASSWORD && StringUtil.isNotEmpty(me.PROXY_LOGIN); if (me.PROXY_TYPE_IS_SOCKS) { result.add(KeyValue.create(JavaProxyProperty.SOCKS_HOST, me.PROXY_HOST)); result.add(KeyValue.create(JavaProxyProperty.SOCKS_PORT, String.valueOf(me.PROXY_PORT))); if (putCredentials) { result.add(KeyValue.create(JavaProxyProperty.SOCKS_USERNAME, me.PROXY_LOGIN)); result.add(KeyValue.create(JavaProxyProperty.SOCKS_PASSWORD, me.getPlainProxyPassword())); } } else { result.add(KeyValue.create(JavaProxyProperty.HTTP_HOST, me.PROXY_HOST)); result.add(KeyValue.create(JavaProxyProperty.HTTP_PORT, String.valueOf(me.PROXY_PORT))); result.add(KeyValue.create(JavaProxyProperty.HTTPS_HOST, me.PROXY_HOST)); result.add(KeyValue.create(JavaProxyProperty.HTTPS_PORT, String.valueOf(me.PROXY_PORT))); if (putCredentials) { result.add(KeyValue.create(JavaProxyProperty.HTTP_USERNAME, me.PROXY_LOGIN)); result.add(KeyValue.create(JavaProxyProperty.HTTP_PASSWORD, me.getPlainProxyPassword())); } } } else if (me.USE_PROXY_PAC && withAutodetection && uri != null) { final List<Proxy> proxies = CommonProxy.getInstance().select(uri); // we will just take the first returned proxy, but we have an option to test connection through each of them, // for instance, by calling prepareUrl() if (proxies != null && ! proxies.isEmpty()) { for (Proxy proxy : proxies) { if (isRealProxy(proxy)) { final SocketAddress address = proxy.address(); if (address instanceof InetSocketAddress) { final InetSocketAddress inetSocketAddress = (InetSocketAddress)address; if (Proxy.Type.SOCKS.equals(proxy.type())) { result.add(KeyValue.create(JavaProxyProperty.SOCKS_HOST, inetSocketAddress.getHostName())); result.add(KeyValue.create(JavaProxyProperty.SOCKS_PORT, String.valueOf(inetSocketAddress.getPort()))); } else { result.add(KeyValue.create(JavaProxyProperty.HTTP_HOST, inetSocketAddress.getHostName())); result.add(KeyValue.create(JavaProxyProperty.HTTP_PORT, String.valueOf(inetSocketAddress.getPort()))); result.add(KeyValue.create(JavaProxyProperty.HTTPS_HOST, inetSocketAddress.getHostName())); result.add(KeyValue.create(JavaProxyProperty.HTTPS_PORT, String.valueOf(inetSocketAddress.getPort()))); } } } } } } return result; } public static boolean isRealProxy(Proxy proxy) { return ! Proxy.NO_PROXY.equals(proxy) && ! Proxy.Type.DIRECT.equals(proxy.type()); } public static List<String> convertArguments(@NotNull final List<KeyValue<String, String>> list) { if (list.isEmpty()) return Collections.emptyList(); final List<String> result = new ArrayList<String>(list.size()); for (KeyValue<String, String> value : list) { result.add("-D" + value.getKey() + "=" + value.getValue()); } return result; } public void clearGenericPasswords() { synchronized (myLock) { myGenericPasswords.clear(); myGenericCancelled.clear(); } } public void removeGeneric(CommonProxy.HostInfo info) { synchronized (myLock) { myGenericPasswords.remove(info); } } @NotNull @Override public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile("proxy.settings")}; } @NotNull @Override public String getPresentableName() { return "Proxy Settings"; } public static class StorageChooser implements StateStorageChooser<HttpConfigurable> { @Override public Storage[] selectStorages(Storage[] storages, HttpConfigurable component, StateStorageOperation operation) { if (operation == StateStorageOperation.WRITE) { for (Storage storage : storages) { if (storage.file().equals(StoragePathMacros.APP_CONFIG + "/proxy.settings.xml")) { return new Storage[] {storage}; } } } return storages; } } public static class ProxyInfo { public boolean myStore; public String myUsername; public String myPasswordCrypt; @SuppressWarnings("UnusedDeclaration") public ProxyInfo() { } public ProxyInfo(boolean store, String username, String passwordCrypt) { myStore = store; myUsername = username; myPasswordCrypt = passwordCrypt; } public boolean isStore() { return myStore; } public void setStore(boolean store) { myStore = store; } public String getUsername() { return myUsername; } public void setUsername(String username) { myUsername = username; } public String getPasswordCrypt() { return myPasswordCrypt; } @SuppressWarnings("UnusedDeclaration") public void setPasswordCrypt(String passwordCrypt) { myPasswordCrypt = passwordCrypt; } } }
platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java
/* * Copyright 2000-2014 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.util.net; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.util.Base64; import com.intellij.util.SystemProperties; import com.intellij.util.WaitForProgressToShow; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.proxy.CommonProxy; import com.intellij.util.proxy.JavaProxyProperty; import com.intellij.util.xmlb.XmlSerializer; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.Transient; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.*; import java.util.*; @State( name = "HttpConfigurable", storages = { @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml"), @Storage(file = StoragePathMacros.APP_CONFIG + "/proxy.settings.xml") }, storageChooser = HttpConfigurable.StorageChooser.class ) public class HttpConfigurable implements PersistentStateComponent<HttpConfigurable>, ExportableApplicationComponent { public static final int CONNECTION_TIMEOUT = SystemProperties.getIntProperty("idea.connection.timeout", 10000); private static final Logger LOG = Logger.getInstance(HttpConfigurable.class); public boolean PROXY_TYPE_IS_SOCKS = false; public boolean USE_HTTP_PROXY = false; public boolean USE_PROXY_PAC = false; public volatile transient boolean AUTHENTICATION_CANCELLED = false; public String PROXY_HOST = ""; public int PROXY_PORT = 80; public volatile boolean PROXY_AUTHENTICATION = false; public volatile String PROXY_LOGIN = ""; public volatile String PROXY_PASSWORD_CRYPT = ""; public boolean KEEP_PROXY_PASSWORD = false; public transient String LAST_ERROR; private final Map<CommonProxy.HostInfo, ProxyInfo> myGenericPasswords = new THashMap<CommonProxy.HostInfo, ProxyInfo>(); private final Set<CommonProxy.HostInfo> myGenericCancelled = new THashSet<CommonProxy.HostInfo>(); private transient IdeaWideProxySelector mySelector; public String PROXY_EXCEPTIONS = ""; public boolean USE_PAC_URL = false; public String PAC_URL = ""; private transient final Object myLock = new Object(); @SuppressWarnings("UnusedDeclaration") public transient Getter<PasswordAuthentication> myTestAuthRunnable = new StaticGetter<PasswordAuthentication>(null); public transient Getter<PasswordAuthentication> myTestGenericAuthRunnable = new StaticGetter<PasswordAuthentication>(null); public static HttpConfigurable getInstance() { return ServiceManager.getService(HttpConfigurable.class); } public static boolean editConfigurable(JComponent parent) { return ShowSettingsUtil.getInstance().editConfigurable(parent, new HTTPProxySettingsPanel(getInstance())); } @Override public HttpConfigurable getState() { CommonProxy.isInstalledAssertion(); final HttpConfigurable state = new HttpConfigurable(); XmlSerializerUtil.copyBean(this, state); if (!KEEP_PROXY_PASSWORD) { state.PROXY_PASSWORD_CRYPT = ""; } correctPasswords(this, state); return state; } @Override public void initComponent() { mySelector = new IdeaWideProxySelector(this); String name = getClass().getName(); CommonProxy.getInstance().setCustom(name, mySelector); CommonProxy.getInstance().setCustomAuth(name, new IdeaWideAuthenticator(this)); } @NotNull public ProxySelector getOnlyBySettingsSelector() { return mySelector; } @Override public void disposeComponent() { final String name = getClass().getName(); CommonProxy.getInstance().removeCustom(name); CommonProxy.getInstance().removeCustomAuth(name); } @NotNull @Override public String getComponentName() { return getClass().getName(); } private void correctPasswords(HttpConfigurable from, HttpConfigurable to) { synchronized (myLock) { to.myGenericPasswords.clear(); for (Map.Entry<CommonProxy.HostInfo, ProxyInfo> entry : from.myGenericPasswords.entrySet()) { if (Boolean.TRUE.equals(entry.getValue().isStore())) { to.myGenericPasswords.put(entry.getKey(), entry.getValue()); } } } } @Override public void loadState(HttpConfigurable state) { XmlSerializerUtil.copyBean(state, this); if (!KEEP_PROXY_PASSWORD) { PROXY_PASSWORD_CRYPT = ""; } correctPasswords(state, this); } public boolean isGenericPasswordCanceled(@NotNull String host, int port) { synchronized (myLock) { return myGenericCancelled.contains(new CommonProxy.HostInfo(null, host, port)); } } public void setGenericPasswordCanceled(final String host, final int port) { synchronized (myLock) { myGenericCancelled.add(new CommonProxy.HostInfo("", host, port)); } } public PasswordAuthentication getGenericPassword(final String host, final int port) { final ProxyInfo proxyInfo; synchronized (myLock) { proxyInfo = myGenericPasswords.get(new CommonProxy.HostInfo("", host, port)); } if (proxyInfo == null) return null; return new PasswordAuthentication(proxyInfo.getUsername(), decode(String.valueOf(proxyInfo.getPasswordCrypt())).toCharArray()); } public void putGenericPassword(final String host, final int port, final PasswordAuthentication authentication, final boolean remember) { final PasswordAuthentication coded = new PasswordAuthentication(authentication.getUserName(), encode(String.valueOf(authentication.getPassword())).toCharArray()); synchronized (myLock) { myGenericPasswords.put(new CommonProxy.HostInfo("", host, port), new ProxyInfo(remember, coded.getUserName(), String.valueOf( coded.getPassword()))); } } @Transient public String getPlainProxyPassword() { return decode(PROXY_PASSWORD_CRYPT); } private static String decode(String value) { return new String(Base64.decode(value)); } @Transient public void setPlainProxyPassword (String password) { PROXY_PASSWORD_CRYPT = encode(password); } private static String encode(String password) { return new String(Base64.encode(password.getBytes(CharsetToolkit.UTF8_CHARSET))); } public PasswordAuthentication getGenericPromptedAuthentication(final String prefix, final String host, final String prompt, final int port, final boolean remember) { if (ApplicationManager.getApplication().isUnitTestMode()) { return myTestGenericAuthRunnable.get(); } final PasswordAuthentication[] value = new PasswordAuthentication[1]; final Runnable runnable = new Runnable() { @Override public void run() { if (isGenericPasswordCanceled(host, port)) return; final PasswordAuthentication password = getGenericPassword(host, port); if (password != null) { value[0] = password; return; } final AuthenticationDialog dlg = new AuthenticationDialog(PopupUtil.getActiveComponent(), prefix + host, "Please enter credentials for: " + prompt, "", "", remember); dlg.show(); if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) { final AuthenticationPanel panel = dlg.getPanel(); final boolean remember1 = remember && panel.isRememberPassword(); value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); putGenericPassword(host, port, value[0], remember1); } else { setGenericPasswordCanceled(host, port); } } }; runAboveAll(runnable); return value[0]; } public PasswordAuthentication getPromptedAuthentication(final String host, final String prompt) { if (AUTHENTICATION_CANCELLED) return null; final String password = getPlainProxyPassword(); if (PROXY_AUTHENTICATION && ! StringUtil.isEmptyOrSpaces(PROXY_LOGIN) && ! StringUtil.isEmptyOrSpaces(password)) { return new PasswordAuthentication(PROXY_LOGIN, password.toCharArray()); } // do not try to show any dialogs if application is exiting if (ApplicationManager.getApplication() == null || ApplicationManager.getApplication().isDisposeInProgress() || ApplicationManager.getApplication().isDisposed()) return null; if (ApplicationManager.getApplication().isUnitTestMode()) { return myTestGenericAuthRunnable.get(); } final String login = PROXY_LOGIN == null ? "" : PROXY_LOGIN; final PasswordAuthentication[] value = new PasswordAuthentication[1]; final Runnable runnable = new Runnable() { @Override public void run() { if (AUTHENTICATION_CANCELLED) return; // password might have changed, and the check below is for that final String password = getPlainProxyPassword(); if (PROXY_AUTHENTICATION && ! StringUtil.isEmptyOrSpaces(PROXY_LOGIN) && ! StringUtil.isEmptyOrSpaces(password)) { value[0] = new PasswordAuthentication(PROXY_LOGIN, password.toCharArray()); return; } final AuthenticationDialog dlg = new AuthenticationDialog(PopupUtil.getActiveComponent(), "Proxy authentication: " + host, "Please enter credentials for: " + prompt, login, "", KEEP_PROXY_PASSWORD); dlg.show(); if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) { PROXY_AUTHENTICATION = true; final AuthenticationPanel panel = dlg.getPanel(); KEEP_PROXY_PASSWORD = panel.isRememberPassword(); PROXY_LOGIN = panel.getLogin(); setPlainProxyPassword(String.valueOf(panel.getPassword())); value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); } else { AUTHENTICATION_CANCELLED = true; } } }; runAboveAll(runnable); return value[0]; } @SuppressWarnings("MethodMayBeStatic") private void runAboveAll(final Runnable runnable) { final Runnable throughSwing = new Runnable() { @Override public void run() { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); return; } try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException e) { LOG.info(e); } catch (InvocationTargetException e) { LOG.info(e); } } }; if (ProgressManager.getInstance().getProgressIndicator() != null) { if (ProgressManager.getInstance().getProgressIndicator().isModal()) { WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(runnable); } else { throughSwing.run(); } } else { throughSwing.run(); } } //these methods are preserved for compatibility with com.intellij.openapi.project.impl.IdeaServerSettings @Deprecated public void readExternal(Element element) throws InvalidDataException { loadState(XmlSerializer.deserialize(element, HttpConfigurable.class)); } @Deprecated public void writeExternal(Element element) throws WriteExternalException { XmlSerializer.serializeInto(getState(), element); if (USE_PROXY_PAC && USE_HTTP_PROXY && ! ApplicationManager.getApplication().isDisposed()) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); if (frame != null) { USE_PROXY_PAC = false; Messages.showMessageDialog(frame.getComponent(), "Proxy: both 'use proxy' and 'autodetect proxy' settings were set." + "\nOnly one of these options should be selected.\nPlease re-configure.", "Proxy Setup", Messages.getWarningIcon()); editConfigurable(frame.getComponent()); } } }, ModalityState.NON_MODAL); } } /** * todo [all] It is NOT necessary to call anything if you obey common IDEA proxy settings; * todo if you want to define your own behaviour, refer to {@link com.intellij.util.proxy.CommonProxy} * * also, this method is useful in a way that it test connection to the host [through proxy] * * @param url URL for HTTP connection * @throws IOException */ public void prepareURL(@NotNull String url) throws IOException { URLConnection connection = openConnection(url); try { connection.connect(); connection.getInputStream(); } catch (IOException e) { throw e; } catch (Throwable ignored) { } finally { if (connection instanceof HttpURLConnection) { ((HttpURLConnection)connection).disconnect(); } } } @NotNull public URLConnection openConnection(@NotNull String location) throws IOException { CommonProxy.isInstalledAssertion(); final URL url = new URL(location); URLConnection urlConnection = null; final List<Proxy> proxies = CommonProxy.getInstance().select(url); if (ContainerUtil.isEmpty(proxies)) { urlConnection = url.openConnection(); } else { IOException exception = null; for (Proxy proxy : proxies) { try { urlConnection = url.openConnection(proxy); } catch (IOException e) { // continue iteration exception = e; } } if (urlConnection == null && exception != null) { throw exception; } } assert urlConnection != null; urlConnection.setReadTimeout(CONNECTION_TIMEOUT); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); return urlConnection; } /** * Opens HTTP connection to a given location using configured http proxy settings. * @param location url to connect to * @return instance of {@link HttpURLConnection} * @throws IOException in case of any I/O troubles or if created connection isn't instance of HttpURLConnection. */ @NotNull public HttpURLConnection openHttpConnection(@NotNull String location) throws IOException { URLConnection urlConnection = openConnection(location); if (urlConnection instanceof HttpURLConnection) { return (HttpURLConnection) urlConnection; } else { throw new IOException("Expected " + HttpURLConnection.class + ", but got " + urlConnection.getClass()); } } public static List<KeyValue<String, String>> getJvmPropertiesList(final boolean withAutodetection, @Nullable final URI uri) { final HttpConfigurable me = getInstance(); if (! me.USE_HTTP_PROXY && ! me.USE_PROXY_PAC) { return Collections.emptyList(); } final List<KeyValue<String, String>> result = new ArrayList<KeyValue<String, String>>(); if (me.USE_HTTP_PROXY) { final boolean putCredentials = me.KEEP_PROXY_PASSWORD && StringUtil.isNotEmpty(me.PROXY_LOGIN); if (me.PROXY_TYPE_IS_SOCKS) { result.add(KeyValue.create(JavaProxyProperty.SOCKS_HOST, me.PROXY_HOST)); result.add(KeyValue.create(JavaProxyProperty.SOCKS_PORT, String.valueOf(me.PROXY_PORT))); if (putCredentials) { result.add(KeyValue.create(JavaProxyProperty.SOCKS_USERNAME, me.PROXY_LOGIN)); result.add(KeyValue.create(JavaProxyProperty.SOCKS_PASSWORD, me.getPlainProxyPassword())); } } else { result.add(KeyValue.create(JavaProxyProperty.HTTP_HOST, me.PROXY_HOST)); result.add(KeyValue.create(JavaProxyProperty.HTTP_PORT, String.valueOf(me.PROXY_PORT))); result.add(KeyValue.create(JavaProxyProperty.HTTPS_HOST, me.PROXY_HOST)); result.add(KeyValue.create(JavaProxyProperty.HTTPS_PORT, String.valueOf(me.PROXY_PORT))); if (putCredentials) { result.add(KeyValue.create(JavaProxyProperty.HTTP_USERNAME, me.PROXY_LOGIN)); result.add(KeyValue.create(JavaProxyProperty.HTTP_PASSWORD, me.getPlainProxyPassword())); } } } else if (me.USE_PROXY_PAC && withAutodetection && uri != null) { final List<Proxy> proxies = CommonProxy.getInstance().select(uri); // we will just take the first returned proxy, but we have an option to test connection through each of them, // for instance, by calling prepareUrl() if (proxies != null && ! proxies.isEmpty()) { for (Proxy proxy : proxies) { if (isRealProxy(proxy)) { final SocketAddress address = proxy.address(); if (address instanceof InetSocketAddress) { final InetSocketAddress inetSocketAddress = (InetSocketAddress)address; if (Proxy.Type.SOCKS.equals(proxy.type())) { result.add(KeyValue.create(JavaProxyProperty.SOCKS_HOST, inetSocketAddress.getHostName())); result.add(KeyValue.create(JavaProxyProperty.SOCKS_PORT, String.valueOf(inetSocketAddress.getPort()))); } else { result.add(KeyValue.create(JavaProxyProperty.HTTP_HOST, inetSocketAddress.getHostName())); result.add(KeyValue.create(JavaProxyProperty.HTTP_PORT, String.valueOf(inetSocketAddress.getPort()))); result.add(KeyValue.create(JavaProxyProperty.HTTPS_HOST, inetSocketAddress.getHostName())); result.add(KeyValue.create(JavaProxyProperty.HTTPS_PORT, String.valueOf(inetSocketAddress.getPort()))); } } } } } } return result; } public static boolean isRealProxy(Proxy proxy) { return ! Proxy.NO_PROXY.equals(proxy) && ! Proxy.Type.DIRECT.equals(proxy.type()); } public static List<String> convertArguments(@NotNull final List<KeyValue<String, String>> list) { if (list.isEmpty()) return Collections.emptyList(); final List<String> result = new ArrayList<String>(list.size()); for (KeyValue<String, String> value : list) { result.add("-D" + value.getKey() + "=" + value.getValue()); } return result; } public void clearGenericPasswords() { synchronized (myLock) { myGenericPasswords.clear(); myGenericCancelled.clear(); } } public void removeGeneric(CommonProxy.HostInfo info) { synchronized (myLock) { myGenericPasswords.remove(info); } } @NotNull @Override public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile("proxy.settings")}; } @NotNull @Override public String getPresentableName() { return "Proxy Settings"; } public static class StorageChooser implements StateStorageChooser<HttpConfigurable> { @Override public Storage[] selectStorages(Storage[] storages, HttpConfigurable component, StateStorageOperation operation) { if (operation == StateStorageOperation.WRITE) { for (Storage storage : storages) { if (storage.file().equals(StoragePathMacros.APP_CONFIG + "/proxy.settings.xml")) { return new Storage[] {storage}; } } } return storages; } } public static class ProxyInfo { public boolean myStore; public String myUsername; public String myPasswordCrypt; @SuppressWarnings("UnusedDeclaration") public ProxyInfo() { } public ProxyInfo(boolean store, String username, String passwordCrypt) { myStore = store; myUsername = username; myPasswordCrypt = passwordCrypt; } public boolean isStore() { return myStore; } public void setStore(boolean store) { myStore = store; } public String getUsername() { return myUsername; } public void setUsername(String username) { myUsername = username; } public String getPasswordCrypt() { return myPasswordCrypt; } @SuppressWarnings("UnusedDeclaration") public void setPasswordCrypt(String passwordCrypt) { myPasswordCrypt = passwordCrypt; } } }
cleanup
platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java
cleanup
<ide><path>latform/platform-api/src/com/intellij/util/net/HttpConfigurable.java <ide> return ServiceManager.getService(HttpConfigurable.class); <ide> } <ide> <del> public static boolean editConfigurable(JComponent parent) { <add> public static boolean editConfigurable(@Nullable JComponent parent) { <ide> return ShowSettingsUtil.getInstance().editConfigurable(parent, new HTTPProxySettingsPanel(getInstance())); <ide> } <ide> <ide> synchronized (myLock) { <ide> proxyInfo = myGenericPasswords.get(new CommonProxy.HostInfo("", host, port)); <ide> } <del> if (proxyInfo == null) return null; <add> if (proxyInfo == null) { <add> return null; <add> } <ide> return new PasswordAuthentication(proxyInfo.getUsername(), decode(String.valueOf(proxyInfo.getPasswordCrypt())).toCharArray()); <ide> } <ide> <ide> public void putGenericPassword(final String host, final int port, final PasswordAuthentication authentication, final boolean remember) { <del> final PasswordAuthentication coded = new PasswordAuthentication(authentication.getUserName(), encode(String.valueOf(authentication.getPassword())).toCharArray()); <del> synchronized (myLock) { <del> myGenericPasswords.put(new CommonProxy.HostInfo("", host, port), new ProxyInfo(remember, coded.getUserName(), String.valueOf( <del> coded.getPassword()))); <add> PasswordAuthentication coded = new PasswordAuthentication(authentication.getUserName(), encode(String.valueOf(authentication.getPassword())).toCharArray()); <add> synchronized (myLock) { <add> myGenericPasswords.put(new CommonProxy.HostInfo("", host, port), new ProxyInfo(remember, coded.getUserName(), String.valueOf(coded.getPassword()))); <ide> } <ide> } <ide>
Java
bsd-3-clause
6f330762ddfd5bb77f00c60dba3f973f5cf3790c
0
uzen/byteseek
/* * Copyright Matt Palmer 2009-2011, All rights reserved. * */ package net.domesdaybook.matcher.sequence.searcher; import net.domesdaybook.reader.ByteReader; import net.domesdaybook.matcher.sequence.SequenceMatcher; import net.domesdaybook.matcher.singlebyte.SingleByteMatcher; import net.domesdaybook.searcher.Searcher; /** * BoyerMooreHorspoolSearcher searches for a sequence using the * Boyer-Moore-Horspool algorithm. * * http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm * * This type of search algorithm does not need to examine every byte in * the bytes being searched. It is sub-linear, in general needing to * examine less bytes than actually occur in the bytes being searched. * * It proceeds by searching for the search pattern backwards, from the last byte * in the pattern to the first. It pre-computes a table of minimum safe shifts * for the search pattern. Given a byte in the bytes being searched, * the shift table tells us how many bytes we can safely shift ahead without * missing a possible match. If the shift is zero, then we must validate that * the pattern actually occurs at this position (the last byte of pattern matches * the current position in the bytes being searched). * * A simple example is looking for the bytes 'XYZ' in the sequence 'ABCDEFGXYZ'. * The first attempt is to match 'Z', and we find the byte 'C'. Since 'C' does * not appear anywhere in 'XYZ', we can safely shift 3 bytes ahead and not risk * missing a possible match. In general, the safe shift is either the length of * the pattern, if that byte does not appear in the pattern, or the shortest * distance from the end of the pattern where that byte appears. * * @author matt */ public final class BoyerMooreHorspoolSearcher extends SequenceMatcherSearcher { private long[] shiftForwardFunction; private long[] shiftBackwardFunction; private SingleByteMatcher firstSingleMatcher; private SingleByteMatcher lastSingleMatcher; public BoyerMooreHorspoolSearcher(final SequenceMatcher matcher) { super(matcher); } @Override public final long searchForwards(final ByteReader reader, final long fromPosition, final long toPosition ) { final long[] safeShifts = getForwardShifts(); final SingleByteMatcher lastMatcher = lastSingleMatcher; final int lastBytePositionInSequence = matcher.length() -1; long matchPosition = fromPosition; boolean matchFound = false; while (matchPosition <= toPosition) { // Scan forwards to find a match to the last byte in the sequence: byte lastByte = reader.getByte(matchPosition); while (!lastMatcher.matches(lastByte)) { matchPosition += safeShifts[(int) lastByte & 0xFF]; if ( matchPosition <= toPosition ) { lastByte = reader.getByte(matchPosition); } else { break; } } // If we're still inside the search window, we have a matching last byte. // Verify whether the rest of the sequence matches at this position: if (matchPosition <= toPosition ) { matchFound = matcher.matches(reader, matchPosition - lastBytePositionInSequence); if (matchFound) { break; } } // No match was found. // Shift the match position according to the value of the last byte // observed at the end of the sequence so far in the file. // "Sunday" variant of Boyer-Moore-Horspool sometimes gets better average performance // by shifting based on the next byte of the file, rather than the last byte checked. // This isn't always faster, as it has less "locality of reference": if (matchPosition < toPosition) { matchPosition +=1; lastByte = reader.getByte(matchPosition); } matchPosition += safeShifts[(int) lastByte & 0xFF]; } return matchFound? matchPosition : Searcher.NOT_FOUND; } @Override public final long searchBackwards(final ByteReader reader, final long fromPosition, final long toPosition ) { final long[] safeShifts = getBackwardShifts(); final SingleByteMatcher firstMatcher = firstSingleMatcher; long matchPosition = fromPosition; boolean matchFound = false; while (matchPosition >= toPosition) { // Scan for a match to the first byte in the sequence, scanning backwards from the starting position: byte firstByte = reader.getByte(matchPosition); while (!firstMatcher.matches(firstByte)) { matchPosition += safeShifts[(int) firstByte & 0xFF]; // shifts always add - if the search is backwards, the shift values are already negative. if ( matchPosition >= toPosition ) { firstByte = reader.getByte(matchPosition); } else { break; } } // As long as we're still inside the search window // (greater than the last position we can scan backwards to) // we have a matching first byte - verify that the rest of the sequence matches too. if (matchPosition >= toPosition) { matchFound = matcher.matches(reader, matchPosition); if (matchFound) { break; } } // No match was found. // Shift the match position according to the value of the last byte // observed at the end of the sequence so far in the file. // Note: always add shifts - if the search is backwards, the shifts are precomputed with negative values. // "Sunday" variant of Boyer-Moore-Horspool sometimes gets better average performance // by shifting based on the next byte of the file, rather than the last byte checked. // This isn't always faster, as it has less "locality of reference": if ( matchPosition > toPosition ) { matchPosition -=1; firstByte = reader.getByte(matchPosition); } matchPosition += safeShifts[(int) firstByte & 0xFF]; } return matchFound? matchPosition : Searcher.NOT_FOUND; } private long[] getForwardShifts() { if (this.shiftForwardFunction == null) { calculateForwardShifts(); this.lastSingleMatcher = matcher.getByteMatcherForPosition(matcher.length()-1); } return this.shiftForwardFunction; } private long[] getBackwardShifts() { if (this.shiftBackwardFunction == null) { calculateBackwardShifts(); this.firstSingleMatcher = matcher.getByteMatcherForPosition(0); } return this.shiftBackwardFunction; } private void calculateBackwardShifts() { // First set the default shift to the length of the sequence // (negative if search direction is reversed) this.shiftBackwardFunction = new long[256]; final long[] shifts = this.shiftBackwardFunction; final int numBytes = matcher.length(); final int defaultShift = numBytes * -1; for (int charValueIndex=255; charValueIndex>=0; charValueIndex--) { shifts[charValueIndex] = defaultShift; } // Now set specific byte shifts for the bytes actually in // the sequence itself. The shift is the distance of each character // from the end of the sequence, as a zero-indexed offset. // Each position can match more than one byte (e.g. if a byte class appears). for ( int sequenceByteIndex = numBytes-1; sequenceByteIndex > 0; sequenceByteIndex--) { final SingleByteMatcher aMatcher = matcher.getByteMatcherForPosition(sequenceByteIndex); final byte[] matchingBytes = aMatcher.getMatchingBytes(); for (int byteIndex = 0; byteIndex < matchingBytes.length; byteIndex++) { final int byteSequenceValue = (matchingBytes[byteIndex] & 0xFF); shifts[byteSequenceValue] = -sequenceByteIndex; // 1 - numBytes + sequenceByteIndex; } } } private void calculateForwardShifts() { // First set the default shift to the length of the sequence this.shiftForwardFunction = new long[256]; final long[] shifts = this.shiftForwardFunction; final int numBytes = matcher.length(); final int defaultShift = numBytes; for (int charValueIndex=255; charValueIndex>=0; charValueIndex--) { shifts[charValueIndex] = defaultShift; } // Now set specific byte shifts for the bytes actually in // the sequence itself. The shift is the distance of each character // from the end of the sequence, as a zero-indexed offset. // Each position can match more than one byte (e.g. if a byte class appears). for ( int sequenceByteIndex = 0; sequenceByteIndex < numBytes -1; sequenceByteIndex++ ) { final SingleByteMatcher aMatcher = matcher.getByteMatcherForPosition(sequenceByteIndex); final byte[] matchingBytes = aMatcher.getMatchingBytes(); for (int byteIndex = 0; byteIndex < matchingBytes.length; byteIndex++) { final int byteSequenceValue = ( matchingBytes[byteIndex] & 0xFF ); shifts[byteSequenceValue]=numBytes-sequenceByteIndex-1; } } } }
src/net/domesdaybook/matcher/sequence/searcher/BoyerMooreHorspoolSearcher.java
/* * Copyright Matt Palmer 2009-2011, All rights reserved. * */ package net.domesdaybook.matcher.sequence.searcher; import net.domesdaybook.reader.ByteReader; import net.domesdaybook.matcher.sequence.SequenceMatcher; import net.domesdaybook.matcher.singlebyte.SingleByteMatcher; import net.domesdaybook.searcher.Searcher; /** * * @author matt */ public final class BoyerMooreHorspoolSearcher extends SequenceMatcherSearcher { private long[] shiftForwardFunction; private long[] shiftBackwardFunction; private SingleByteMatcher firstSingleMatcher; private SingleByteMatcher lastSingleMatcher; public BoyerMooreHorspoolSearcher(final SequenceMatcher matcher) { super(matcher); } @Override public final long searchForwards(final ByteReader reader, final long fromPosition, final long toPosition ) { final long[] safeShifts = getForwardShifts(); final SingleByteMatcher lastMatcher = lastSingleMatcher; final int lastBytePositionInSequence = matcher.length() -1; long matchPosition = fromPosition; boolean matchFound = false; while (matchPosition <= toPosition) { // Scan forwards to find a match to the last byte in the sequence: byte lastByte = reader.getByte(matchPosition); while (!lastMatcher.matches(lastByte)) { matchPosition += safeShifts[(int) lastByte & 0xFF]; if ( matchPosition <= toPosition ) { lastByte = reader.getByte(matchPosition); } else { break; } } // If we're still inside the search window, we have a matching last byte. // Verify whether the rest of the sequence matches at this position: if (matchPosition <= toPosition ) { matchFound = matcher.matches(reader, matchPosition - lastBytePositionInSequence); if (matchFound) { break; } } // No match was found. // Shift the match position according to the value of the last byte // observed at the end of the sequence so far in the file. // "Sunday" variant of Boyer-Moore-Horspool sometimes gets better average performance // by shifting based on the next byte of the file, rather than the last byte checked. // This isn't always faster, as it has less "locality of reference": if (matchPosition < toPosition) { matchPosition +=1; lastByte = reader.getByte(matchPosition); } matchPosition += safeShifts[(int) lastByte & 0xFF]; } return matchFound? matchPosition : Searcher.NOT_FOUND; } @Override public final long searchBackwards(final ByteReader reader, final long fromPosition, final long toPosition ) { final long[] safeShifts = getBackwardShifts(); final SingleByteMatcher firstMatcher = firstSingleMatcher; long matchPosition = fromPosition; boolean matchFound = false; while (matchPosition >= toPosition) { // Scan for a match to the first byte in the sequence, scanning backwards from the starting position: byte firstByte = reader.getByte(matchPosition); while (!firstMatcher.matches(firstByte)) { matchPosition += safeShifts[(int) firstByte & 0xFF]; // shifts always add - if the search is backwards, the shift values are already negative. if ( matchPosition >= toPosition ) { firstByte = reader.getByte(matchPosition); } else { break; } } // As long as we're still inside the search window // (greater than the last position we can scan backwards to) // we have a matching first byte - verify that the rest of the sequence matches too. if (matchPosition >= toPosition) { matchFound = matcher.matches(reader, matchPosition); if (matchFound) { break; } } // No match was found. // Shift the match position according to the value of the last byte // observed at the end of the sequence so far in the file. // Note: always add shifts - if the search is backwards, the shifts are precomputed with negative values. // "Sunday" variant of Boyer-Moore-Horspool sometimes gets better average performance // by shifting based on the next byte of the file, rather than the last byte checked. // This isn't always faster, as it has less "locality of reference": if ( matchPosition > toPosition ) { matchPosition -=1; firstByte = reader.getByte(matchPosition); } matchPosition += safeShifts[(int) firstByte & 0xFF]; } return matchFound? matchPosition : Searcher.NOT_FOUND; } private long[] getForwardShifts() { if (this.shiftForwardFunction == null) { calculateForwardShifts(); this.lastSingleMatcher = matcher.getByteMatcherForPosition(matcher.length()-1); } return this.shiftForwardFunction; } private long[] getBackwardShifts() { if (this.shiftBackwardFunction == null) { calculateBackwardShifts(); this.firstSingleMatcher = matcher.getByteMatcherForPosition(0); } return this.shiftBackwardFunction; } private void calculateBackwardShifts() { // First set the default shift to the length of the sequence // (negative if search direction is reversed) this.shiftBackwardFunction = new long[256]; final long[] shifts = this.shiftBackwardFunction; final int numBytes = matcher.length(); final int defaultShift = numBytes * -1; for (int charValueIndex=255; charValueIndex>=0; charValueIndex--) { shifts[charValueIndex] = defaultShift; } // Now set specific byte shifts for the bytes actually in // the sequence itself. The shift is the distance of each character // from the end of the sequence, as a zero-indexed offset. // Each position can match more than one byte (e.g. if a byte class appears). for ( int sequenceByteIndex = numBytes-1; sequenceByteIndex > 0; sequenceByteIndex--) { final SingleByteMatcher aMatcher = matcher.getByteMatcherForPosition(sequenceByteIndex); final byte[] matchingBytes = aMatcher.getMatchingBytes(); for (int byteIndex = 0; byteIndex < matchingBytes.length; byteIndex++) { final int byteSequenceValue = (matchingBytes[byteIndex] & 0xFF); shifts[byteSequenceValue] = -sequenceByteIndex; // 1 - numBytes + sequenceByteIndex; } } } private void calculateForwardShifts() { // First set the default shift to the length of the sequence this.shiftForwardFunction = new long[256]; final long[] shifts = this.shiftForwardFunction; final int numBytes = matcher.length(); final int defaultShift = numBytes; for (int charValueIndex=255; charValueIndex>=0; charValueIndex--) { shifts[charValueIndex] = defaultShift; } // Now set specific byte shifts for the bytes actually in // the sequence itself. The shift is the distance of each character // from the end of the sequence, as a zero-indexed offset. // Each position can match more than one byte (e.g. if a byte class appears). for ( int sequenceByteIndex = 0; sequenceByteIndex < numBytes -1; sequenceByteIndex++ ) { final SingleByteMatcher aMatcher = matcher.getByteMatcherForPosition(sequenceByteIndex); final byte[] matchingBytes = aMatcher.getMatchingBytes(); for (int byteIndex = 0; byteIndex < matchingBytes.length; byteIndex++) { final int byteSequenceValue = ( matchingBytes[byteIndex] & 0xFF ); shifts[byteSequenceValue]=numBytes-sequenceByteIndex-1; } } } }
Added some javadoc
src/net/domesdaybook/matcher/sequence/searcher/BoyerMooreHorspoolSearcher.java
Added some javadoc
<ide><path>rc/net/domesdaybook/matcher/sequence/searcher/BoyerMooreHorspoolSearcher.java <ide> <ide> <ide> /** <del> * <add> * BoyerMooreHorspoolSearcher searches for a sequence using the <add> * Boyer-Moore-Horspool algorithm. <add> * <add> * http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm <add> * <add> * This type of search algorithm does not need to examine every byte in <add> * the bytes being searched. It is sub-linear, in general needing to <add> * examine less bytes than actually occur in the bytes being searched. <add> * <add> * It proceeds by searching for the search pattern backwards, from the last byte <add> * in the pattern to the first. It pre-computes a table of minimum safe shifts <add> * for the search pattern. Given a byte in the bytes being searched, <add> * the shift table tells us how many bytes we can safely shift ahead without <add> * missing a possible match. If the shift is zero, then we must validate that <add> * the pattern actually occurs at this position (the last byte of pattern matches <add> * the current position in the bytes being searched). <add> * <add> * A simple example is looking for the bytes 'XYZ' in the sequence 'ABCDEFGXYZ'. <add> * The first attempt is to match 'Z', and we find the byte 'C'. Since 'C' does <add> * not appear anywhere in 'XYZ', we can safely shift 3 bytes ahead and not risk <add> * missing a possible match. In general, the safe shift is either the length of <add> * the pattern, if that byte does not appear in the pattern, or the shortest <add> * distance from the end of the pattern where that byte appears. <add> * <ide> * @author matt <ide> */ <ide> public final class BoyerMooreHorspoolSearcher extends SequenceMatcherSearcher {
Java
apache-2.0
adc94f317142c0432e37fe47fbce863467649fa0
0
52Jolynn/MyTv,52Jolynn/MyTv,52Jolynn/MyTv
package com.laudandjolynn.mytv.crawler; /** * @author: Laud * @email: [email protected] * @date: 2015年4月22日 下午5:22:20 * @copyright: www.laudandjolynn.com */ public interface CrawlEventListener { public void itemFound(CrawlEvent event); }
src/main/java/com/laudandjolynn/mytv/crawler/CrawlEventListener.java
package com.laudandjolynn.mytv.crawler; /** * @author: Laud * @email: [email protected] * @date: 2015年4月22日 下午5:22:20 * @copyright: www.laudandjolynn.com */ public interface CrawlEventListener { }
add interface
src/main/java/com/laudandjolynn/mytv/crawler/CrawlEventListener.java
add interface
<ide><path>rc/main/java/com/laudandjolynn/mytv/crawler/CrawlEventListener.java <ide> * @copyright: www.laudandjolynn.com <ide> */ <ide> public interface CrawlEventListener { <add> public void itemFound(CrawlEvent event); <ide> }
Java
apache-2.0
bdccd27de2df14ec4cbb6b8119ce5c0cbfb4201c
0
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
/* * 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.felix.ipojo.arch; import java.io.PrintStream; import org.apache.felix.ipojo.architecture.Architecture; import org.apache.felix.ipojo.architecture.HandlerDescription; import org.apache.felix.ipojo.architecture.InstanceDescription; import org.ungoverned.osgi.service.shell.Command; /** * Implementation of the arch command printing the actual architecture. * @author <a href="mailto:[email protected]">Felix Project Team</a> */ public class ArchCommandImpl implements Command { /** * List of archi service */ private Architecture archiService[]; /** * @see org.ungoverned.osgi.service.shell.Command#getName() */ public String getName() { return "arch"; } /** * @see org.ungoverned.osgi.service.shell.Command#getUsage() */ public String getUsage() { return "arch -> Dispaly architecture information"; } /** * @see org.ungoverned.osgi.service.shell.Command#getShortDescription() */ public String getShortDescription() { return "Architecture command : display the architecture"; } /** * Return the String corresponding to a component state. * @param state : the state in int * @return : the string of the state (Stopped, Unresolved, Resolved) or "Unknown" if state is not revelant */ private String getInstanceState(int state) { switch(state) { case(0) : return "STOPPED"; case(1) : return "INVALID"; case(2) : return "VALID"; default : return "UNKNOWN"; } } /** * @see org.ungoverned.osgi.service.shell.Command#execute(java.lang.String, java.io.PrintStream, java.io.PrintStream) */ public void execute(String line, PrintStream out, PrintStream err) { synchronized(this) { for(int i=0; i < archiService.length; i++) { InstanceDescription instance = archiService[i].getInstanceDescription(); out.println("Instance : " + instance.getName() + " (" + instance.getComponentDescription().getClassName() + ")" + " - " + getInstanceState(instance.getState()) + " from bundle " + instance.getBundleId()); for(int j = 0; j < instance.getHandlers().length; j++) { HandlerDescription hd = instance.getHandlers()[j]; String hn = hd.getHandlerName(); String hv = "valid"; if(!hd.isValid()) { hv = "invalid"; } String hi = hd.getHandlerInfo(); out.println("Handler : " + hn + " : " + hv); if(!hi.equals("")) { out.println(hi); } } out.println("Created POJO Objects : "); for(int j=0; j < instance.getCreatedObjects().length; j++) { out.println("\t" + instance.getCreatedObjects()[j]); } out.print("\n"); } } } }
ipojo.arch/src/main/java/org/apache/felix/ipojo/arch/ArchCommandImpl.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.felix.ipojo.arch; import java.io.PrintStream; import org.apache.felix.ipojo.architecture.Architecture; import org.apache.felix.ipojo.architecture.HandlerDescription; import org.apache.felix.ipojo.architecture.InstanceDescription; import org.ungoverned.osgi.service.shell.Command; /** * Implementation of the arch command printing the actual architecture. * @author <a href="mailto:[email protected]">Felix Project Team</a> */ public class ArchCommandImpl implements Command { /** * List of archi service */ private Architecture archiService[]; /** * @see org.ungoverned.osgi.service.shell.Command#getName() */ public String getName() { return "arch"; } /** * @see org.ungoverned.osgi.service.shell.Command#getUsage() */ public String getUsage() { return "arch -> Dispaly architecture information"; } /** * @see org.ungoverned.osgi.service.shell.Command#getShortDescription() */ public String getShortDescription() { return "Architecture command : display the architecture"; } /** * Return the String corresponding to a component state. * @param state : the state in int * @return : the string of the state (Stopped, Unresolved, Resolved) or "Unknown" if state is not revelant */ private String getInstanceState(int state) { switch(state) { case(0) : return "STOPPED"; case(1) : return "INVALID"; case(2) : return "VALID"; default : return "UNKNOWN"; } } /** * @see org.ungoverned.osgi.service.shell.Command#execute(java.lang.String, java.io.PrintStream, java.io.PrintStream) */ public void execute(String line, PrintStream out, PrintStream err) { synchronized(this) { for(int i=0; i < archiService.length; i++) { InstanceDescription instance = archiService[i].getInstanceDescription(); out.println("Instance : " + instance.getName() + " (" + instance.getClassName() + ")" + " - " + getInstanceState(instance.getState()) + " from bundle " + instance.getBundleId()); for(int j = 0; j < instance.getHandlers().length; j++) { HandlerDescription hd = instance.getHandlers()[j]; String hn = hd.getHandlerName(); String hv = "valid"; if(!hd.isValid()) { hv = "invalid"; } String hi = hd.getHandlerInfo(); out.println("Handler : " + hn + " : " + hv); if(!hi.equals("")) { out.println(hi); } } out.println("Created POJO Objects : "); for(int j=0; j < instance.getCreatedObjects().length; j++) { out.println("\t" + instance.getCreatedObjects()[j]); } out.print("\n"); } } } }
Modified method invocation that was changed as a result of patch FELIX-266. git-svn-id: 4fefb534f2df272853cd9ed688fc456ba1c30243@527158 13f79535-47bb-0310-9956-ffa450edef68
ipojo.arch/src/main/java/org/apache/felix/ipojo/arch/ArchCommandImpl.java
Modified method invocation that was changed as a result of patch FELIX-266.
<ide><path>pojo.arch/src/main/java/org/apache/felix/ipojo/arch/ArchCommandImpl.java <ide> synchronized(this) { <ide> for(int i=0; i < archiService.length; i++) { <ide> InstanceDescription instance = archiService[i].getInstanceDescription(); <del> out.println("Instance : " + instance.getName() + " (" + instance.getClassName() + ")" + " - " + getInstanceState(instance.getState()) + " from bundle " + instance.getBundleId()); <add> out.println("Instance : " + instance.getName() + " (" + instance.getComponentDescription().getClassName() + ")" + " - " + getInstanceState(instance.getState()) + " from bundle " + instance.getBundleId()); <ide> for(int j = 0; j < instance.getHandlers().length; j++) { <ide> HandlerDescription hd = instance.getHandlers()[j]; <ide> String hn = hd.getHandlerName();
Java
bsd-3-clause
8e82c627e36aae3cab821ca1dc7c5dc96bc54257
0
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2017, 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. */ package org.hisp.dhis.android.core.enrollment.note; import android.content.ContentValues; import android.database.Cursor; import android.support.annotation.Nullable; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.google.auto.value.AutoValue; import org.hisp.dhis.android.core.common.BaseModel; import org.hisp.dhis.android.core.common.ObjectWithUidInterface; import static org.hisp.dhis.android.core.common.BaseIdentifiableObject.UID; @AutoValue @JsonDeserialize(builder = AutoValue_Note.Builder.class) public abstract class Note extends BaseModel implements ObjectWithUidInterface { @Nullable @JsonProperty(UID) public abstract String uid(); @Nullable @JsonIgnore() public abstract String enrollment(); @Nullable @JsonProperty() public abstract String value(); @Nullable @JsonProperty() public abstract String storedBy(); @Nullable @JsonProperty() public abstract String storedDate(); public static Builder builder() { return new $$AutoValue_Note.Builder(); } static Note create(Cursor cursor) { return $AutoValue_Note.createFromCursor(cursor); } public abstract ContentValues toContentValues(); public abstract Builder toBuilder(); @AutoValue.Builder @JsonPOJOBuilder(withPrefix = "") public static abstract class Builder extends BaseModel.Builder<Builder> { public abstract Builder id(Long id); public abstract Builder uid(String uid); public abstract Builder enrollment(String enrollment); public abstract Builder value(String value); public abstract Builder storedBy(String storedBy); public abstract Builder storedDate(String storedDate); public abstract Note build(); } }
core/src/main/java/org/hisp/dhis/android/core/enrollment/note/Note.java
/* * Copyright (c) 2017, 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. */ package org.hisp.dhis.android.core.enrollment.note; import android.content.ContentValues; import android.database.Cursor; import android.support.annotation.Nullable; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.google.auto.value.AutoValue; import org.hisp.dhis.android.core.common.BaseModel; import org.hisp.dhis.android.core.common.ObjectWithUidInterface; import static org.hisp.dhis.android.core.common.BaseIdentifiableObject.UID; @AutoValue @JsonDeserialize(builder = AutoValue_Note.Builder.class) public abstract class Note extends BaseModel implements ObjectWithUidInterface { @Nullable @JsonProperty(UID) public abstract String uid(); @Nullable public abstract String enrollment(); @Nullable public abstract String value(); @Nullable public abstract String storedBy(); @Nullable public abstract String storedDate(); public static Builder builder() { return new $$AutoValue_Note.Builder(); } static Note create(Cursor cursor) { return $AutoValue_Note.createFromCursor(cursor); } public abstract ContentValues toContentValues(); public abstract Builder toBuilder(); @AutoValue.Builder @JsonPOJOBuilder(withPrefix = "") public static abstract class Builder extends BaseModel.Builder<Builder> { public abstract Builder id(Long id); public abstract Builder uid(String uid); public abstract Builder enrollment(String enrollment); public abstract Builder value(String value); public abstract Builder storedBy(String storedBy); public abstract Builder storedDate(String storedDate); public abstract Note build(); } }
[ANDROSDK-417] Add jsonProperty annotations
core/src/main/java/org/hisp/dhis/android/core/enrollment/note/Note.java
[ANDROSDK-417] Add jsonProperty annotations
<ide><path>ore/src/main/java/org/hisp/dhis/android/core/enrollment/note/Note.java <ide> import android.database.Cursor; <ide> import android.support.annotation.Nullable; <ide> <add>import com.fasterxml.jackson.annotation.JsonIgnore; <ide> import com.fasterxml.jackson.annotation.JsonProperty; <ide> import com.fasterxml.jackson.databind.annotation.JsonDeserialize; <ide> import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; <ide> public abstract String uid(); <ide> <ide> @Nullable <add> @JsonIgnore() <ide> public abstract String enrollment(); <ide> <ide> @Nullable <add> @JsonProperty() <ide> public abstract String value(); <ide> <ide> @Nullable <add> @JsonProperty() <ide> public abstract String storedBy(); <ide> <ide> @Nullable <add> @JsonProperty() <ide> public abstract String storedDate(); <ide> <ide> public static Builder builder() {
Java
apache-2.0
14011223551836b040456fe3543ff9e68ca6c9da
0
GinaHsu/ud851-GinaExercises,GinaHsu/ud851-GinaExercises
/* * Copyright (C) 2016 The Android Open Source Project * * 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.example.android.background; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.android.background.sync.ReminderTasks; import com.example.android.background.sync.ReminderUtilities; import com.example.android.background.sync.WaterReminderIntentService; import com.example.android.background.utilities.PreferenceUtilities; public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private TextView mWaterCountDisplay; private TextView mChargingCountDisplay; private ImageView mChargingImageView; private Toast mToast; ChargingBroadcastReceiver mChargingReceiver; IntentFilter mChargingIntentFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** Get the views **/ mWaterCountDisplay = (TextView) findViewById(R.id.tv_water_count); mChargingCountDisplay = (TextView) findViewById(R.id.tv_charging_reminder_count); mChargingImageView = (ImageView) findViewById(R.id.iv_power_increment); /** Set the original values in the UI **/ updateWaterCount(); updateChargingReminderCount(); ReminderUtilities.scheduleChargingReminder(this); /** Setup the shared preference listener **/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener(this); // TODO (5) Create and instantiate a new instance variable for your ChargingBroadcastReceiver // and an IntentFilter /* * Setup and register the broadcast receiver */ mChargingReceiver = new ChargingBroadcastReceiver(); mChargingIntentFilter = new IntentFilter(); // TODO (6) Call the addAction method on your intent filter and add Intent.ACTION_POWER_CONNECTED // and Intent.ACTION_POWER_DISCONNECTED. This sets up an intent filter which will trigger // when the charging state changes. mChargingIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED); mChargingIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED); } // TODO (7) Override onResume and setup your broadcast receiver. Do this by calling // registerReceiver with the ChargingBroadcastReceiver and IntentFilter. @Override protected void onResume() { super.onResume(); registerReceiver(mChargingReceiver, mChargingIntentFilter); } // TODO (8) Override onPause and unregister your receiver using the unregisterReceiver method @Override protected void onPause() { super.onPause(); unregisterReceiver(mChargingReceiver); } /** * Updates the TextView to display the new water count from SharedPreferences */ private void updateWaterCount() { int waterCount = PreferenceUtilities.getWaterCount(this); mWaterCountDisplay.setText(waterCount+""); } /** * Updates the TextView to display the new charging reminder count from SharedPreferences */ private void updateChargingReminderCount() { int chargingReminders = PreferenceUtilities.getChargingReminderCount(this); String formattedChargingReminders = getResources().getQuantityString( R.plurals.charge_notification_count, chargingReminders, chargingReminders); mChargingCountDisplay.setText(formattedChargingReminders); } // TODO (1) Create a new method called showCharging which takes a boolean. This method should // either change the image of mChargingImageView to ic_power_pink_80px if the boolean is true // or R.drawable.ic_power_grey_80px it it's not. This method will eventually update the UI // when our broadcast receiver is triggered when the charging state changes. private void showCharging (boolean isCharging){ if (isCharging){ mChargingImageView.setImageResource(R.drawable.ic_power_pink_80px); }else{ mChargingImageView.setImageResource(R.drawable.ic_power_grey_80px); } } /** * Adds one to the water count and shows a toast */ public void incrementWater(View view) { if (mToast != null) mToast.cancel(); mToast = Toast.makeText(this, R.string.water_chug_toast, Toast.LENGTH_SHORT); mToast.show(); Intent incrementWaterCountIntent = new Intent(this, WaterReminderIntentService.class); incrementWaterCountIntent.setAction(ReminderTasks.ACTION_INCREMENT_WATER_COUNT); startService(incrementWaterCountIntent); } @Override protected void onDestroy() { super.onDestroy(); /** Cleanup the shared preference listener **/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.unregisterOnSharedPreferenceChangeListener(this); } /** * This is a listener that will update the UI when the water count or charging reminder counts * change */ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (PreferenceUtilities.KEY_WATER_COUNT.equals(key)) { updateWaterCount(); } else if (PreferenceUtilities.KEY_CHARGING_REMINDER_COUNT.equals(key)) { updateChargingReminderCount(); } } // TODO (2) Create an inner class called ChargingBroadcastReceiver that extends BroadcastReceiver private class ChargingBroadcastReceiver extends BroadcastReceiver { // TODO (3) Override onReceive to get the action from the intent and see if it matches the // Intent.ACTION_POWER_CONNECTED. If it matches, it's charging. If it doesn't match, it's not // charging. @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); boolean isCharging = action.equals(Intent.ACTION_POWER_CONNECTED); // TODO (4) Update the UI using the showCharging method you wrote showCharging(isCharging); } } }
Lesson10-Hydration-Reminder/T10.05-Exercise-ChargingBroadcastReceiver/app/src/main/java/com/example/android/background/MainActivity.java
/* * Copyright (C) 2016 The Android Open Source Project * * 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.example.android.background; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.android.background.sync.ReminderTasks; import com.example.android.background.sync.ReminderUtilities; import com.example.android.background.sync.WaterReminderIntentService; import com.example.android.background.utilities.PreferenceUtilities; public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private TextView mWaterCountDisplay; private TextView mChargingCountDisplay; private ImageView mChargingImageView; private Toast mToast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** Get the views **/ mWaterCountDisplay = (TextView) findViewById(R.id.tv_water_count); mChargingCountDisplay = (TextView) findViewById(R.id.tv_charging_reminder_count); mChargingImageView = (ImageView) findViewById(R.id.iv_power_increment); /** Set the original values in the UI **/ updateWaterCount(); updateChargingReminderCount(); ReminderUtilities.scheduleChargingReminder(this); /** Setup the shared preference listener **/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener(this); // TODO (5) Create and instantiate a new instance variable for your ChargingBroadcastReceiver // and an IntentFilter // TODO (6) Call the addAction method on your intent filter and add Intent.ACTION_POWER_CONNECTED // and Intent.ACTION_POWER_DISCONNECTED. This sets up an intent filter which will trigger // when the charging state changes. } // TODO (7) Override onResume and setup your broadcast receiver. Do this by calling // registerReceiver with the ChargingBroadcastReceiver and IntentFilter. // TODO (8) Override onPause and unregister your receiver using the unregisterReceiver method /** * Updates the TextView to display the new water count from SharedPreferences */ private void updateWaterCount() { int waterCount = PreferenceUtilities.getWaterCount(this); mWaterCountDisplay.setText(waterCount+""); } /** * Updates the TextView to display the new charging reminder count from SharedPreferences */ private void updateChargingReminderCount() { int chargingReminders = PreferenceUtilities.getChargingReminderCount(this); String formattedChargingReminders = getResources().getQuantityString( R.plurals.charge_notification_count, chargingReminders, chargingReminders); mChargingCountDisplay.setText(formattedChargingReminders); } // TODO (1) Create a new method called showCharging which takes a boolean. This method should // either change the image of mChargingImageView to ic_power_pink_80px if the boolean is true // or R.drawable.ic_power_grey_80px it it's not. This method will eventually update the UI // when our broadcast receiver is triggered when the charging state changes. /** * Adds one to the water count and shows a toast */ public void incrementWater(View view) { if (mToast != null) mToast.cancel(); mToast = Toast.makeText(this, R.string.water_chug_toast, Toast.LENGTH_SHORT); mToast.show(); Intent incrementWaterCountIntent = new Intent(this, WaterReminderIntentService.class); incrementWaterCountIntent.setAction(ReminderTasks.ACTION_INCREMENT_WATER_COUNT); startService(incrementWaterCountIntent); } @Override protected void onDestroy() { super.onDestroy(); /** Cleanup the shared preference listener **/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.unregisterOnSharedPreferenceChangeListener(this); } /** * This is a listener that will update the UI when the water count or charging reminder counts * change */ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (PreferenceUtilities.KEY_WATER_COUNT.equals(key)) { updateWaterCount(); } else if (PreferenceUtilities.KEY_CHARGING_REMINDER_COUNT.equals(key)) { updateChargingReminderCount(); } } // TODO (2) Create an inner class called ChargingBroadcastReceiver that extends BroadcastReceiver // TODO (3) Override onReceive to get the action from the intent and see if it matches the // Intent.ACTION_POWER_CONNECTED. If it matches, it's charging. If it doesn't match, it's not // charging. // TODO (4) Update the UI using the showCharging method you wrote }
Done T10.05-ChargingBroadcastReceiver
Lesson10-Hydration-Reminder/T10.05-Exercise-ChargingBroadcastReceiver/app/src/main/java/com/example/android/background/MainActivity.java
Done T10.05-ChargingBroadcastReceiver
<ide><path>esson10-Hydration-Reminder/T10.05-Exercise-ChargingBroadcastReceiver/app/src/main/java/com/example/android/background/MainActivity.java <ide> */ <ide> package com.example.android.background; <ide> <add>import android.content.BroadcastReceiver; <add>import android.content.Context; <ide> import android.content.Intent; <add>import android.content.IntentFilter; <ide> import android.content.SharedPreferences; <add>import android.graphics.Bitmap; <ide> import android.os.Bundle; <ide> import android.preference.PreferenceManager; <ide> import android.support.v7.app.AppCompatActivity; <ide> <ide> private Toast mToast; <ide> <add> ChargingBroadcastReceiver mChargingReceiver; <add> IntentFilter mChargingIntentFilter; <add> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> <ide> // TODO (5) Create and instantiate a new instance variable for your ChargingBroadcastReceiver <ide> // and an IntentFilter <add> /* <add> * Setup and register the broadcast receiver <add> */ <add> mChargingReceiver = new ChargingBroadcastReceiver(); <add> mChargingIntentFilter = new IntentFilter(); <add> <ide> // TODO (6) Call the addAction method on your intent filter and add Intent.ACTION_POWER_CONNECTED <ide> // and Intent.ACTION_POWER_DISCONNECTED. This sets up an intent filter which will trigger <ide> // when the charging state changes. <add> mChargingIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED); <add> mChargingIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED); <ide> } <ide> <ide> // TODO (7) Override onResume and setup your broadcast receiver. Do this by calling <ide> // registerReceiver with the ChargingBroadcastReceiver and IntentFilter. <add> @Override <add> protected void onResume() { <add> super.onResume(); <add> registerReceiver(mChargingReceiver, mChargingIntentFilter); <add> } <ide> <ide> // TODO (8) Override onPause and unregister your receiver using the unregisterReceiver method <add> @Override <add> protected void onPause() { <add> super.onPause(); <add> unregisterReceiver(mChargingReceiver); <add> } <ide> <ide> /** <ide> * Updates the TextView to display the new water count from SharedPreferences <ide> // either change the image of mChargingImageView to ic_power_pink_80px if the boolean is true <ide> // or R.drawable.ic_power_grey_80px it it's not. This method will eventually update the UI <ide> // when our broadcast receiver is triggered when the charging state changes. <add> <add> private void showCharging (boolean isCharging){ <add> if (isCharging){ <add> mChargingImageView.setImageResource(R.drawable.ic_power_pink_80px); <add> }else{ <add> mChargingImageView.setImageResource(R.drawable.ic_power_grey_80px); <add> } <add> } <ide> <ide> /** <ide> * Adds one to the water count and shows a toast <ide> <ide> <ide> // TODO (2) Create an inner class called ChargingBroadcastReceiver that extends BroadcastReceiver <add> private class ChargingBroadcastReceiver extends BroadcastReceiver { <add> <ide> // TODO (3) Override onReceive to get the action from the intent and see if it matches the <ide> // Intent.ACTION_POWER_CONNECTED. If it matches, it's charging. If it doesn't match, it's not <ide> // charging. <del> // TODO (4) Update the UI using the showCharging method you wrote <add> @Override <add> public void onReceive(Context context, Intent intent) { <add> String action = intent.getAction(); <add> boolean isCharging = action.equals(Intent.ACTION_POWER_CONNECTED); <add> <add> // TODO (4) Update the UI using the showCharging method you wrote <add> showCharging(isCharging); <add> } <add> <add> } <add> <ide> }
Java
mit
530f6220d7b9a5156df037ccfb0a7769401d0086
0
furkansahin/team-heart-coders-public
package ch.epfl.sweng.swissaffinity.end_to_end; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import ch.epfl.sweng.swissaffinity.MainActivity; import ch.epfl.sweng.swissaffinity.utilities.Location; import ch.epfl.sweng.swissaffinity.utilities.network.DefaultNetworkProvider; import ch.epfl.sweng.swissaffinity.utilities.network.NetworkProvider; import ch.epfl.sweng.swissaffinity.utilities.network.users.NetworkUserClient; import ch.epfl.sweng.swissaffinity.utilities.network.users.UserClient; import ch.epfl.sweng.swissaffinity.utilities.network.users.UserClientException; import ch.epfl.sweng.swissaffinity.utilities.parsers.LocationParser; import ch.epfl.sweng.swissaffinity.utilities.parsers.ParserException; import ch.epfl.sweng.swissaffinity.utilities.parsers.SafeJSONObject; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.EMAIL; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.ENABLED; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.FIRST_NAME; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.GENDER; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.LAST_NAME; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.LOCKED; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.USERNAME; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; /** * Created by Joel on 11/19/2015. * Modified by Dario on 09.12.2015 */ @RunWith(AndroidJUnit4.class) @LargeTest public class RegisterUserToEventTest { private UserClient mUserClient; private NetworkProvider mNetworkProvider; private String mYoungerUserName; private String mOlderUserName; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( MainActivity.class); @Before public void setUp() throws RuntimeException{ mActivityRule.getActivity(); mNetworkProvider = new DefaultNetworkProvider(); mUserClient = new NetworkUserClient(NetworkProvider.SERVER_URL, mNetworkProvider); try { mYoungerUserName = makeTestUserOnServer("Younger").getString(USERNAME.get()); mOlderUserName = makeTestUserOnServer("Older").getString(USERNAME.get()); }catch (IllegalArgumentException | JSONException e){ throw new RuntimeException(e); } } @Test public void alreadyRegistered() { final int eventIdToRegister = 7; final String userToRegister = mOlderUserName; NetworkProvider networkProvider = new DefaultNetworkProvider(); UserClient userClient = new NetworkUserClient(NetworkProvider.SERVER_URL, networkProvider); try { int registrationId = getRegistrationId( userToRegister, eventIdToRegister); if (registrationId > 0) { userClient.unregisterUser(registrationId); } } catch (UserClientException e) { // SUCCESS -> clean the registration for the test } try { if(getRegistrationId(userToRegister,eventIdToRegister) > 0) { fail("User: " + userToRegister + " cannot be registered to event (id) " + eventIdToRegister + "for this test."); } } catch (UserClientException e){ fail(e.getMessage()); } try{ userClient.registerUser(userToRegister, eventIdToRegister); userClient.registerUser(userToRegister, eventIdToRegister); }catch (UserClientException e){ assertEquals("You are already registered to this event", e.getMessage().replace("\"","").replace("\n","")); } try { Integer id = getRegistrationId(userToRegister, eventIdToRegister); userClient.unregisterUser(id); } catch (UserClientException e){ fail(e.getMessage()); } } @Test public void testUnderAge() { final int eventIdToRegister = 7;//Christmas event is for older Users final String userToRegister = mYoungerUserName; try{ mUserClient.registerUser(userToRegister, eventIdToRegister); } catch (UserClientException e){ assertEquals("You are not in the age range of this Event." + " The age range is: 26 - 46 and you are 22", e.getMessage().replace("\"", "").replace("\n", "")); } } @Test public void postRegistrationToEvent() throws UserClientException{ final int eventIdToRegister = 7; final String userToRegister = mOlderUserName; try { int registrationId = getRegistrationId( userToRegister, eventIdToRegister); if (registrationId > 0) { mUserClient.unregisterUser(registrationId); } } catch (UserClientException e) { // SUCCESS -> clean the registration for the test } try { mUserClient.registerUser(userToRegister, eventIdToRegister); } catch (UserClientException e) { fail(e.getMessage()); } Integer testRegistrationId = getRegistrationId(userToRegister, eventIdToRegister); assertTrue("Registration was not successful.", testRegistrationId > 0); try { mUserClient.unregisterUser(testRegistrationId); } catch (UserClientException e) { fail(e.getMessage()); } } @After public void tearDown() throws UserClientException{ mUserClient.deleteUser(String.format("TestRegisterUser%s", "Younger")); mUserClient.deleteUser(String.format("TestRegisterUser%s", "Older")); } @Ignore private int getRegistrationId(String username, int eventId) throws UserClientException { String registrationsString; JSONArray registrations; try { registrationsString = mNetworkProvider.getContent( NetworkProvider.SERVER_URL + "/api/users/" + username + "/registrations"); registrations = new JSONArray(registrationsString); } catch (JSONException | IOException e) { throw new UserClientException(e); } try { HashMap<Integer, Integer> eventToRegistration = new HashMap<>(); for (int i = 0; i < registrations.length(); i++) { JSONObject jsonRegistration = registrations.getJSONObject(i); JSONObject jsonEvent = jsonRegistration.getJSONObject("event"); eventToRegistration.put(jsonEvent.getInt("id"), jsonRegistration.getInt("id")); } return eventToRegistration.get(eventId); } catch (Exception e) { return -1; } } @Ignore /** * Create new users for tests to be independent of the content in the server. */ private JSONObject makeTestUserOnServer(String age) throws IllegalArgumentException{ final String birthdayDDMMYY; final String birthdayT; if (age.equals("Younger")){ birthdayDDMMYY = "18/02/1993"; birthdayT = "1993-02-18T00:00:00+0100"; } else if (age.equals("Older")){ birthdayDDMMYY = "18/02/1980"; birthdayT = "1980-02-18T00:00:00+0100"; } else { throw new IllegalArgumentException(); } List<Location> locationsOfInterest = new ArrayList<>(); locationsOfInterest.add(new Location(2, "Genève")); locationsOfInterest.add(new Location(3, "Lausanne")); locationsOfInterest.add(new Location(4, "Fribourg")); locationsOfInterest.add(new Location(6, "Zürich")); locationsOfInterest.add(new Location(7, "Berne")); locationsOfInterest.add(new Location(8, "Bulle")); try { JSONObject jsonUser = new JSONObject(); jsonUser.put(EMAIL.get(), String.format("testregisteruser%[email protected]", age)); jsonUser.put(USERNAME.get(), String.format("TestRegisterUser%s", age)); jsonUser.put("firstName", "Test"); jsonUser.put("lastName", "Register"); jsonUser.put(GENDER.get(), "male"); jsonUser.put("birthDate", birthdayDDMMYY); jsonUser.put("facebookId", String.format("666%s", Integer.toString(age.length()))); jsonUser.put("plainPassword", "testpassword"); JSONObject responseJSON = mUserClient.postUser(jsonUser); List<Location> areasOfInterest = new ArrayList<>(); JSONArray areas = responseJSON.getJSONArray("locations_of_interest"); for (int i = 0; i < areas.length(); i++) { JSONObject jsonArea = areas.getJSONObject(i); Location location = new LocationParser().parse(new SafeJSONObject(jsonArea)); areasOfInterest.add(location); } String fb_id = responseJSON.getString("facebook_id"); if (!(responseJSON.getString(EMAIL.get()).equals(String.format("testregisteruser%[email protected]", age))) || !(responseJSON.getString(USERNAME.get()).equals(String.format("TestRegisterUser%s", age))) || !(responseJSON.getString(FIRST_NAME.get()).equals("Test")) || !(responseJSON.getString(LAST_NAME.get()).equals("Register")) || !(responseJSON.getString(GENDER.get()).equals("male")) || !(responseJSON.getString("birth_date").equals(birthdayT)) || !(fb_id.equals(String.format("666%s", Integer.toString(age.length())))) || !(responseJSON.getBoolean(LOCKED.get()) == false) || !(responseJSON.getBoolean(ENABLED.get()) == false) || !(new GetUserTest.CollectionComparator<Location>().compare( locationsOfInterest, areasOfInterest)) ){ throw new UserClientException("User was not created successfully."); } return responseJSON; } catch (UserClientException | ParserException | JSONException e) { throw new IllegalArgumentException(e); } } }
SwissAffinity/app/src/androidTest/java/ch/epfl/sweng/swissaffinity/end_to_end/RegisterUserToEventTest.java
package ch.epfl.sweng.swissaffinity.end_to_end; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import ch.epfl.sweng.swissaffinity.MainActivity; import ch.epfl.sweng.swissaffinity.utilities.Location; import ch.epfl.sweng.swissaffinity.utilities.network.DefaultNetworkProvider; import ch.epfl.sweng.swissaffinity.utilities.network.NetworkProvider; import ch.epfl.sweng.swissaffinity.utilities.network.users.NetworkUserClient; import ch.epfl.sweng.swissaffinity.utilities.network.users.UserClient; import ch.epfl.sweng.swissaffinity.utilities.network.users.UserClientException; import ch.epfl.sweng.swissaffinity.utilities.parsers.LocationParser; import ch.epfl.sweng.swissaffinity.utilities.parsers.ParserException; import ch.epfl.sweng.swissaffinity.utilities.parsers.SafeJSONObject; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.EMAIL; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.ENABLED; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.FIRST_NAME; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.GENDER; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.LAST_NAME; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.LOCKED; import static ch.epfl.sweng.swissaffinity.utilities.network.ServerTags.USERNAME; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; /** * Created by Joel on 11/19/2015. * Modified by Dario on 09.12.2015 */ @RunWith(AndroidJUnit4.class) @LargeTest public class RegisterUserToEventTest { private UserClient mUserClient; private NetworkProvider mNetworkProvider; //private String mYoungerUserName; //private String mOlderUserName; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( MainActivity.class); @Before public void setUp() throws RuntimeException{ mActivityRule.getActivity(); mNetworkProvider = new DefaultNetworkProvider(); mUserClient = new NetworkUserClient(NetworkProvider.SERVER_URL, mNetworkProvider); /** try { mYoungerUserName = makeTestUserOnServer("Younger").getString(USERNAME.get()); mOlderUserName = makeTestUserOnServer("Older").getString(USERNAME.get()); }catch (IllegalArgumentException | JSONException e){ throw new RuntimeException(e); } **/ } @Test public void alreadyRegistered() { final int eventIdToRegister = 7; final String userToRegister = "lio"; NetworkProvider networkProvider = new DefaultNetworkProvider(); UserClient userClient = new NetworkUserClient(NetworkProvider.SERVER_URL, networkProvider); try { int registrationId = getRegistrationId( userToRegister, eventIdToRegister); if (registrationId > 0) { userClient.unregisterUser(registrationId); } } catch (UserClientException e) { // SUCCESS -> clean the registration for the test } try { if(getRegistrationId(userToRegister,eventIdToRegister) > 0) { fail("User: " + userToRegister + " cannot be registered to event (id) " + eventIdToRegister + "for this test."); } } catch (UserClientException e){ fail(e.getMessage()); } try{ userClient.registerUser(userToRegister, eventIdToRegister); userClient.registerUser(userToRegister, eventIdToRegister); }catch (UserClientException e){ assertEquals("You are already registered to this event", e.getMessage().replace("\"","").replace("\n","")); } try { Integer id = getRegistrationId(userToRegister, eventIdToRegister); userClient.unregisterUser(id); } catch (UserClientException e){ fail(e.getMessage()); } } @Test public void testUnderAge() { final int eventIdToRegister = 7;//Christmas event is for older Users final String userToRegister = "Admin"; try{ mUserClient.registerUser(userToRegister, eventIdToRegister); } catch (UserClientException e){ assertEquals("You are not in the age range of this Event." + " The age range is: 26 - 46 and you are 22", e.getMessage().replace("\"", "").replace("\n", "")); } } @Test public void postRegistrationToEvent() throws UserClientException{ final int eventIdToRegister = 7; final String userToRegister = "lio"; try { int registrationId = getRegistrationId( userToRegister, eventIdToRegister); if (registrationId > 0) { mUserClient.unregisterUser(registrationId); } } catch (UserClientException e) { // SUCCESS -> clean the registration for the test } try { mUserClient.registerUser(userToRegister, eventIdToRegister); } catch (UserClientException e) { fail(e.getMessage()); } Integer testRegistrationId = getRegistrationId(userToRegister, eventIdToRegister); assertTrue("Registration was not successful.", testRegistrationId > 0); try { mUserClient.unregisterUser(testRegistrationId); } catch (UserClientException e) { fail(e.getMessage()); } } /** @After public void tearDown() throws UserClientException{ mUserClient.deleteUser(String.format("TestRegisterUser%s", "Younger")); mUserClient.deleteUser(String.format("TestRegisterUser%s", "Older")); } **/ @Ignore private int getRegistrationId(String username, int eventId) throws UserClientException { String registrationsString; JSONArray registrations; try { registrationsString = mNetworkProvider.getContent( NetworkProvider.SERVER_URL + "/api/users/" + username + "/registrations"); registrations = new JSONArray(registrationsString); } catch (JSONException | IOException e) { throw new UserClientException(e); } try { HashMap<Integer, Integer> eventToRegistration = new HashMap<>(); for (int i = 0; i < registrations.length(); i++) { JSONObject jsonRegistration = registrations.getJSONObject(i); JSONObject jsonEvent = jsonRegistration.getJSONObject("event"); eventToRegistration.put(jsonEvent.getInt("id"), jsonRegistration.getInt("id")); } return eventToRegistration.get(eventId); } catch (Exception e) { return -1; } } @Ignore /** * Create new users for tests to be independent of the content in the server. */ private JSONObject makeTestUserOnServer(String age) throws IllegalArgumentException{ final String birthdayDDMMYY; final String birthdayT; if (age.equals("Younger")){ birthdayDDMMYY = "18/02/1993"; birthdayT = "1993-02-18T00:00:00+0100"; } else if (age.equals("Older")){ birthdayDDMMYY = "18/02/1980"; birthdayT = "1980-02-18T00:00:00+0100"; } else { throw new IllegalArgumentException(); } List<Location> locationsOfInterest = new ArrayList<>(); locationsOfInterest.add(new Location(2, "Genève")); locationsOfInterest.add(new Location(3, "Lausanne")); locationsOfInterest.add(new Location(4, "Fribourg")); locationsOfInterest.add(new Location(6, "Zürich")); locationsOfInterest.add(new Location(7, "Berne")); locationsOfInterest.add(new Location(8, "Bulle")); try { JSONObject jsonUser = new JSONObject(); jsonUser.put(EMAIL.get(), String.format("testregisteruser%[email protected]", age)); jsonUser.put(USERNAME.get(), String.format("TestRegisterUser%s", age)); jsonUser.put("firstName", "Test"); jsonUser.put("lastName", "Register"); jsonUser.put(GENDER.get(), "male"); jsonUser.put("birthDate", birthdayDDMMYY); jsonUser.put("facebookId", String.format("666%s", Integer.toString(age.length()))); jsonUser.put("plainPassword", "testpassword"); JSONObject responseJSON = mUserClient.postUser(jsonUser); List<Location> areasOfInterest = new ArrayList<>(); JSONArray areas = responseJSON.getJSONArray("locations_of_interest"); for (int i = 0; i < areas.length(); i++) { JSONObject jsonArea = areas.getJSONObject(i); Location location = new LocationParser().parse(new SafeJSONObject(jsonArea)); areasOfInterest.add(location); } String fb_id = responseJSON.getString("facebook_id"); if (!(responseJSON.getString(EMAIL.get()).equals(String.format("testregisteruser%[email protected]", age))) || !(responseJSON.getString(USERNAME.get()).equals(String.format("TestRegisterUser%s", age))) || !(responseJSON.getString(FIRST_NAME.get()).equals("Test")) || !(responseJSON.getString(LAST_NAME.get()).equals("Register")) || !(responseJSON.getString(GENDER.get()).equals("male")) || !(responseJSON.getString("birth_date").equals(birthdayT)) || !(fb_id.equals(String.format("666%s", Integer.toString(age.length())))) || !(responseJSON.getBoolean(LOCKED.get()) == false) || !(responseJSON.getBoolean(ENABLED.get()) == false) || !(new GetUserTest.CollectionComparator<Location>().compare( locationsOfInterest, areasOfInterest)) ){ throw new UserClientException("User was not created successfully."); } return responseJSON; } catch (UserClientException | ParserException | JSONException e) { throw new IllegalArgumentException(e); } } }
End_to_end tests now have mock users.
SwissAffinity/app/src/androidTest/java/ch/epfl/sweng/swissaffinity/end_to_end/RegisterUserToEventTest.java
End_to_end tests now have mock users.
<ide><path>wissAffinity/app/src/androidTest/java/ch/epfl/sweng/swissaffinity/end_to_end/RegisterUserToEventTest.java <ide> import org.json.JSONArray; <ide> import org.json.JSONException; <ide> import org.json.JSONObject; <add>import org.junit.After; <ide> import org.junit.Before; <ide> import org.junit.Ignore; <ide> import org.junit.Rule; <ide> public class RegisterUserToEventTest { <ide> private UserClient mUserClient; <ide> private NetworkProvider mNetworkProvider; <del> //private String mYoungerUserName; <del> //private String mOlderUserName; <add> private String mYoungerUserName; <add> private String mOlderUserName; <ide> <ide> @Rule <ide> public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( <ide> mActivityRule.getActivity(); <ide> mNetworkProvider = new DefaultNetworkProvider(); <ide> mUserClient = new NetworkUserClient(NetworkProvider.SERVER_URL, mNetworkProvider); <del> /** <ide> try { <ide> mYoungerUserName = makeTestUserOnServer("Younger").getString(USERNAME.get()); <ide> mOlderUserName = makeTestUserOnServer("Older").getString(USERNAME.get()); <ide> }catch (IllegalArgumentException | JSONException e){ <ide> throw new RuntimeException(e); <ide> } <del> **/ <ide> } <ide> <ide> @Test <ide> public void alreadyRegistered() { <ide> final int eventIdToRegister = 7; <del> final String userToRegister = "lio"; <add> final String userToRegister = mOlderUserName; <ide> NetworkProvider networkProvider = new DefaultNetworkProvider(); <ide> UserClient userClient = new NetworkUserClient(NetworkProvider.SERVER_URL, networkProvider); <ide> try { <ide> @Test <ide> public void testUnderAge() { <ide> final int eventIdToRegister = 7;//Christmas event is for older Users <del> final String userToRegister = "Admin"; <add> final String userToRegister = mYoungerUserName; <ide> try{ <ide> mUserClient.registerUser(userToRegister, eventIdToRegister); <ide> } catch (UserClientException e){ <ide> @Test <ide> public void postRegistrationToEvent() throws UserClientException{ <ide> final int eventIdToRegister = 7; <del> final String userToRegister = "lio"; <add> final String userToRegister = mOlderUserName; <ide> <ide> try { <ide> int registrationId = getRegistrationId( <ide> fail(e.getMessage()); <ide> } <ide> } <del> /** <add> <ide> @After <ide> public void tearDown() throws UserClientException{ <ide> <ide> mUserClient.deleteUser(String.format("TestRegisterUser%s", "Younger")); <ide> mUserClient.deleteUser(String.format("TestRegisterUser%s", "Older")); <ide> } <del> **/ <add> <ide> @Ignore <ide> private int getRegistrationId(String username, int eventId) <ide> throws UserClientException
Java
mit
94d4c3e0d05dc5dd1de89f0c56685512307e0008
0
jourdanrodrigues/controk-android
package com.example.jourdanrodrigues.controk; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity { private String[] mMenuEntries; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMenuEntries = getResources().getStringArray(R.array.menu_entries); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, mMenuEntries)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); mTitle = mDrawerTitle = getTitle(); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); if (getSupportActionBar() != null) { // Solution source: https://stackoverflow.com/a/35719588/4694834 getSupportActionBar().setTitle(mTitle); } } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(mDrawerTitle); } } }; // Set the drawer toggle as the DrawerListener mDrawerLayout.addDrawerListener(mDrawerToggle); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Highlight the selected item, update the title, and close the drawer mDrawerList.setItemChecked(position, true); setTitle(mMenuEntries[position]); mDrawerLayout.closeDrawer(mDrawerList); } } @Override public boolean onOptionsItemSelected(MenuItem item) { return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void setTitle(CharSequence title) { mTitle = title; if (getSupportActionBar() != null) { getSupportActionBar().setTitle(mTitle); } } }
app/src/main/java/com/example/jourdanrodrigues/controk/MainActivity.java
package com.example.jourdanrodrigues.controk; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity { private String[] mMenuEntries; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMenuEntries = getResources().getStringArray(R.array.menu_entries); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, mMenuEntries)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); if (getSupportActionBar() != null) { // Solution source: https://stackoverflow.com/a/35719588/4694834 getSupportActionBar().setTitle(mTitle); } } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(mDrawerTitle); } } }; // Set the drawer toggle as the DrawerListener mDrawerLayout.addDrawerListener(mDrawerToggle); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Highlight the selected item, update the title, and close the drawer mDrawerList.setItemChecked(position, true); setTitle(mMenuEntries[position]); mDrawerLayout.closeDrawer(mDrawerList); } } @Override public boolean onOptionsItemSelected(MenuItem item) { return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void setTitle(CharSequence title) { mTitle = title; if (getSupportActionBar() != null) { getSupportActionBar().setTitle(mTitle); } } }
:art: Improve code.
app/src/main/java/com/example/jourdanrodrigues/controk/MainActivity.java
:art: Improve code.
<ide><path>pp/src/main/java/com/example/jourdanrodrigues/controk/MainActivity.java <ide> <ide> mMenuEntries = getResources().getStringArray(R.array.menu_entries); <ide> mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); <add> <ide> mDrawerList = (ListView) findViewById(R.id.left_drawer); <del> <ide> mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, mMenuEntries)); <ide> mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); <ide> <ide> mTitle = mDrawerTitle = getTitle(); <del> mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); <ide> <ide> mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { <ide> public void onDrawerClosed(View view) {
Java
apache-2.0
925e867050fbb2e2fce2b350ec947435faa75d06
0
ImpactDevelopment/ClientAPI,ZeroMemes/ClientAPI
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.module; import clientapi.ClientAPI; import clientapi.event.defaults.internal.ModuleStateEvent; import clientapi.module.exception.ModuleInitException; import clientapi.util.ClientAPIUtils; import clientapi.util.Tag; import clientapi.util.interfaces.Describable; import clientapi.util.interfaces.Nameable; import clientapi.util.interfaces.Taggable; import clientapi.util.io.Keybind; import clientapi.value.holder.ValueHolder; import org.lwjgl.input.Keyboard; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * The base for all modules. Contains the data * for values, properties, type, keybind, name * and description. * * @see IModule * @see Category * * @author Brady * @since 1/19/2017 */ public class Module extends AbstractModule implements Taggable { /** * Reference to self-class */ private final Class<? extends Module> self = this.getClass(); /** * The type/category of the module */ private Class<?> type; /** * List of Modes */ private List<ModuleMode> modes; /** * The Current Mode */ private ModuleMode mode; /** * List of Tags */ private final List<Tag> tags = new ArrayList<>(); public Module() { if (!self.isAnnotationPresent(Mod.class)) throw new ModuleInitException("@Mod annotation must be present if required parameters aren't passed through constructor"); Mod data = self.getAnnotation(Mod.class); setup(data.name(), data.description(), data.bind()); } public Module(String name, String description) { this(name, description, Keyboard.KEY_NONE); } public Module(String name, String description, int bind) { setup(name, description, bind); } private void setup(String name, String description, int bind) { this.name = name; this.description = description; this.bind = new Keybind(Keybind.Type.TOGGLE, bind, type -> { if (type == Keybind.Action.CLICK) Module.this.toggle(); }); this.type = Arrays.stream(self.getInterfaces()) .filter(clazz -> clazz.isAnnotationPresent(Category.class)) .findFirst().orElse(Category.Default.class); if (ClientAPIUtils.containsNull(name, description, type)) throw new NullPointerException("One or more Mod members were null!"); } /** * Sets the modes of this module * * @param modes Modes for this mod */ protected final void setModes(ModuleMode... modes) { if (modes.length == 0) return; this.modes = new ArrayList<>(); this.modes.addAll(Arrays.asList(modes)); this.setMode(this.modes.get(0)); } /** * Returns whether or not the module has modes * * @return True if this module has modes, false if not */ public final boolean hasModes() { return this.modes != null; } /** * Sets the module's mode to the specified mode. * Null will be returned if the mode is unable to * be set. * * @param mode Mode being set * @return The new mode */ public final ModuleMode setMode(ModuleMode mode) { checkModes(); if (mode == null || mode.getParent() != this) return null; if (mode == this.mode) return mode; if (this.mode != null) this.mode.setState(false); (this.mode = mode).setState(true); return this.mode; } /** * Sets the module's mode to the mode in the * specified index. An IndexOutOfBoundsException * will be thrown if the index is less than 0 or * exceeds the maximum index of the mode array. * * @param index Index of the mode * @return The new mode */ public final ModuleMode setMode(int index) { checkModes(); return this.setMode(this.modes.get(index)); } /** * Sets the module's mode from the mode's name. * Null will be returned if there isn't a mode * with the specified name * * @param name The mode name * @return The new mode */ public final ModuleMode setMode(String name) { checkModes(); return this.setMode(getMode(name)); } /** * Gets a mode that belongs to this * module from the mode's name * * @return Mode from name */ public final ModuleMode getMode(String name) { checkModes(); return this.modes.stream().filter(mode -> mode.getName().equalsIgnoreCase(name)).findFirst().orElse(null); } /** * Returns the list of modes that this module has, * null will be returned if this module doesn't have * any modes. * * @return List of modes */ public final List<ModuleMode> getModes() { checkModes(); return new ArrayList<>(this.modes); } /** * Switches the mode to the mode following * the current mode in the list of modes. * * @return The new mode */ public final ModuleMode nextMode() { checkModes(); int index = this.modes.indexOf(this.getMode()); if (++index > this.modes.size() - 1) index = 0; return setMode(index); } /** * Switched the mode to the mode preceding * the current mode in the list of modes. * @return The new mode */ public final ModuleMode lastMode() { checkModes(); int index = this.modes.indexOf(this.getMode()); if (--index < 0) index = this.modes.size() - 1; return setMode(index); } /** * Returns this Module's mode, if it has modes * * @return The current mode */ public final ModuleMode getMode() { checkModes(); return this.mode; } /** * Called when mode related actions are carried out, * throws an {@code UnsupportedOperationException} if * modes aren't supported by this module. */ private void checkModes() { if (!hasModes()) throw new UnsupportedOperationException("Cannot use mode required actions when modes aren't supported"); } @Override public final void setState(boolean state) { if (state == this.state) return; ModuleStateEvent event = new ModuleStateEvent(this, state); ClientAPI.EVENT_BUS.post(event); if (event.isCancelled()) return; if (this.state = state) { onEnable(); ClientAPI.EVENT_BUS.subscribe(this); } else { ClientAPI.EVENT_BUS.unsubscribe(this); onDisable(); } if (hasModes() && mode != null) mode.setState(state); } @Override public final Class<?> getType() { return this.type; } @Override public final void addTag(Tag tag) { if (!getTag(tag).isPresent()) tags.add(tag); } @Override public final void removeTag(String id) { getTag(id).ifPresent(tags::remove); } @Override public final boolean hasTag(String id) { return getTag(id).isPresent(); } @Override public final Optional<Tag> getTag(String id) { return this.tags.stream().filter(tag -> tag.getID().equals(id)).findFirst(); } @Override public final List<Tag> getTags() { return this.tags; } }
src/main/java/clientapi/module/Module.java
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.module; import clientapi.ClientAPI; import clientapi.event.defaults.internal.ModuleStateEvent; import clientapi.module.exception.ModuleInitException; import clientapi.util.ClientAPIUtils; import clientapi.util.Tag; import clientapi.util.interfaces.Describable; import clientapi.util.interfaces.Nameable; import clientapi.util.interfaces.Taggable; import clientapi.util.io.Keybind; import clientapi.value.holder.ValueHolder; import org.lwjgl.input.Keyboard; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * The base for all modules. Contains the data * for values, properties, type, keybind, name * and description. * * @see IModule * @see Category * * @author Brady * @since 1/19/2017 */ public abstract class Module extends AbstractModule implements Taggable { /** * Reference to self-class */ private final Class<? extends Module> self = this.getClass(); /** * The type/category of the module */ private Class<?> type; /** * List of Modes */ private List<ModuleMode> modes; /** * The Current Mode */ private ModuleMode mode; /** * List of Tags */ private final List<Tag> tags = new ArrayList<>(); public Module() { if (!self.isAnnotationPresent(Mod.class)) throw new ModuleInitException("@Mod annotation must be present if required parameters aren't passed through constructor"); Mod data = self.getAnnotation(Mod.class); setup(data.name(), data.description(), data.bind()); } public Module(String name, String description) { this(name, description, Keyboard.KEY_NONE); } public Module(String name, String description, int bind) { setup(name, description, bind); } private void setup(String name, String description, int bind) { this.name = name; this.description = description; this.bind = new Keybind(Keybind.Type.TOGGLE, bind, type -> { if (type == Keybind.Action.CLICK) Module.this.toggle(); }); this.type = Arrays.stream(self.getInterfaces()) .filter(clazz -> clazz.isAnnotationPresent(Category.class)) .findFirst().orElse(Category.Default.class); if (ClientAPIUtils.containsNull(name, description, type)) throw new NullPointerException("One or more Mod members were null!"); } /** * Sets the modes of this module * * @param modes Modes for this mod */ protected final void setModes(ModuleMode... modes) { if (modes.length == 0) return; this.modes = new ArrayList<>(); this.modes.addAll(Arrays.asList(modes)); this.setMode(this.modes.get(0)); } /** * Returns whether or not the module has modes * * @return True if this module has modes, false if not */ public final boolean hasModes() { return this.modes != null; } /** * Sets the module's mode to the specified mode. * Null will be returned if the mode is unable to * be set. * * @param mode Mode being set * @return The new mode */ public final ModuleMode setMode(ModuleMode mode) { checkModes(); if (mode == null || mode.getParent() != this) return null; if (mode == this.mode) return mode; if (this.mode != null) this.mode.setState(false); (this.mode = mode).setState(true); return this.mode; } /** * Sets the module's mode to the mode in the * specified index. An IndexOutOfBoundsException * will be thrown if the index is less than 0 or * exceeds the maximum index of the mode array. * * @param index Index of the mode * @return The new mode */ public final ModuleMode setMode(int index) { checkModes(); return this.setMode(this.modes.get(index)); } /** * Sets the module's mode from the mode's name. * Null will be returned if there isn't a mode * with the specified name * * @param name The mode name * @return The new mode */ public final ModuleMode setMode(String name) { checkModes(); return this.setMode(getMode(name)); } /** * Gets a mode that belongs to this * module from the mode's name * * @return Mode from name */ public final ModuleMode getMode(String name) { checkModes(); return this.modes.stream().filter(mode -> mode.getName().equalsIgnoreCase(name)).findFirst().orElse(null); } /** * Returns the list of modes that this module has, * null will be returned if this module doesn't have * any modes. * * @return List of modes */ public final List<ModuleMode> getModes() { checkModes(); return new ArrayList<>(this.modes); } /** * Switches the mode to the mode following * the current mode in the list of modes. * * @return The new mode */ public final ModuleMode nextMode() { checkModes(); int index = this.modes.indexOf(this.getMode()); if (++index > this.modes.size() - 1) index = 0; return setMode(index); } /** * Switched the mode to the mode preceding * the current mode in the list of modes. * @return The new mode */ public final ModuleMode lastMode() { checkModes(); int index = this.modes.indexOf(this.getMode()); if (--index < 0) index = this.modes.size() - 1; return setMode(index); } /** * Returns this Module's mode, if it has modes * * @return The current mode */ public final ModuleMode getMode() { checkModes(); return this.mode; } /** * Called when mode related actions are carried out, * throws an {@code UnsupportedOperationException} if * modes aren't supported by this module. */ private void checkModes() { if (!hasModes()) throw new UnsupportedOperationException("Cannot use mode required actions when modes aren't supported"); } @Override public final void setState(boolean state) { if (state == this.state) return; ModuleStateEvent event = new ModuleStateEvent(this, state); ClientAPI.EVENT_BUS.post(event); if (event.isCancelled()) return; if (this.state = state) { onEnable(); ClientAPI.EVENT_BUS.subscribe(this); } else { ClientAPI.EVENT_BUS.unsubscribe(this); onDisable(); } if (hasModes() && mode != null) mode.setState(state); } @Override public final Class<?> getType() { return this.type; } @Override public final void addTag(Tag tag) { if (!getTag(tag).isPresent()) tags.add(tag); } @Override public final void removeTag(String id) { getTag(id).ifPresent(tags::remove); } @Override public final boolean hasTag(String id) { return getTag(id).isPresent(); } @Override public final Optional<Tag> getTag(String id) { return this.tags.stream().filter(tag -> tag.getID().equals(id)).findFirst(); } @Override public final List<Tag> getTags() { return this.tags; } }
Remove abstract modifier from Module
src/main/java/clientapi/module/Module.java
Remove abstract modifier from Module
<ide><path>rc/main/java/clientapi/module/Module.java <ide> * @author Brady <ide> * @since 1/19/2017 <ide> */ <del>public abstract class Module extends AbstractModule implements Taggable { <add>public class Module extends AbstractModule implements Taggable { <ide> <ide> /** <ide> * Reference to self-class
Java
apache-2.0
51edb8b024f73b56ad9295f59127ecc1de96c947
0
GerritCodeReview/plugins_its-phabricator,GerritCodeReview/plugins_its-phabricator
// Copyright (C) 2017 The Android Open Source Project // // 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.googlesource.gerrit.plugins.its.phabricator.conduit; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ConduitPing; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ManiphestEdit; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ManiphestSearch; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ProjectSearch; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Bindings for Phabricator's Conduit API * * <p>This class is not thread-safe. */ public class Conduit { public interface Factory { Conduit create(@Assisted("baseUrl") String baseUrl, @Assisted("token") String token); } public static final String ACTION_COMMENT = "comment"; public static final String ACTION_PROJECT_ADD = "projects.add"; public static final String ACTION_PROJECT_REMOVE = "projects.remove"; public static final int CONDUIT_VERSION = 7; private final SearchUtils searchUtils; private final ConduitConnection conduitConnection; private final Gson gson; private final String token; @Inject public Conduit( ConduitConnection.Factory conduitConnectionFactory, SearchUtils searchUtils, @Assisted("baseUrl") String baseUrl, @Assisted("token") String token) { this.searchUtils = searchUtils; this.conduitConnection = conduitConnectionFactory.create(baseUrl); this.token = token; this.gson = new Gson(); } /** Runs the API's 'conduit.ping' method */ public ConduitPing conduitPing() throws ConduitException { Map<String, Object> params = new HashMap<>(); JsonElement callResult = conduitConnection.call("conduit.ping", params, token); JsonObject callResultWrapper = new JsonObject(); callResultWrapper.add("hostname", callResult); ConduitPing result = gson.fromJson(callResultWrapper, ConduitPing.class); return result; } /** Runs the API's 'maniphest.search' method */ public ManiphestSearch maniphestSearch(int taskId) throws ConduitException { HashMap<String, Object> params = new HashMap<>(); params.put("constraints", ImmutableMap.of("ids", ImmutableList.of(taskId))); JsonElement callResult = conduitConnection.call("maniphest.search", params, token); return searchUtils.stream(callResult, ManiphestSearch.class) .filter((r) -> r.getId() == taskId) .findFirst() .orElse(null); } /** Runs the API's 'maniphest.edit' method */ public ManiphestEdit maniphestEdit( int taskId, String comment, String projectNameToAdd, String projectNameToRemove) throws ConduitException { ManiphestEdit result = null; List<Object> transactions = new ArrayList<>(); if (!Strings.isNullOrEmpty(comment)) { HashMap<String, Object> transaction = new HashMap<>(); transaction.put("type", ACTION_COMMENT); transaction.put("value", comment); transactions.add(transaction); } if (!Strings.isNullOrEmpty(projectNameToAdd)) { HashMap<String, Object> transaction = new HashMap<>(); transaction.put("type", ACTION_PROJECT_ADD); transaction.put("value", ImmutableList.of(projectSearch(projectNameToAdd).getPhid())); transactions.add(transaction); } if (!Strings.isNullOrEmpty(projectNameToRemove)) { HashMap<String, Object> transaction = new HashMap<>(); transaction.put("type", ACTION_PROJECT_REMOVE); transaction.put("value", ImmutableList.of(projectSearch(projectNameToRemove).getPhid())); transactions.add(transaction); } if (!transactions.isEmpty()) { HashMap<String, Object> params = new HashMap<>(); params.put("objectIdentifier", taskId); params.put("transactions", transactions); JsonElement callResult = conduitConnection.call("maniphest.edit", params, token); result = gson.fromJson(callResult, ManiphestEdit.class); } return result; } /** Runs the API's 'project.search' method to match exactly one project name */ public ProjectSearch projectSearch(String name) throws ConduitException { HashMap<String, Object> params = new HashMap<>(); params.put("constraints", ImmutableMap.of("query", name)); JsonElement callResult = conduitConnection.call("project.search", params, token); return searchUtils.stream(callResult, ProjectSearch.class).findFirst().orElse(null); } }
src/main/java/com/googlesource/gerrit/plugins/its/phabricator/conduit/Conduit.java
// Copyright (C) 2017 The Android Open Source Project // // 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.googlesource.gerrit.plugins.its.phabricator.conduit; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ConduitPing; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ManiphestEdit; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ManiphestSearch; import com.googlesource.gerrit.plugins.its.phabricator.conduit.results.ProjectSearch; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Bindings for Phabricator's Conduit API * * <p>This class is not thread-safe. */ public class Conduit { public interface Factory { Conduit create(@Assisted("baseUrl") String baseUrl, @Assisted("token") String token); } public static final String ACTION_COMMENT = "comment"; public static final String ACTION_PROJECT_ADD = "projects.add"; public static final String ACTION_PROJECT_REMOVE = "projects.remove"; public static final int CONDUIT_VERSION = 7; private final SearchUtils searchUtils; private final ConduitConnection conduitConnection; private final Gson gson; private final String token; @Inject public Conduit( ConduitConnection.Factory conduitConnectionFactory, SearchUtils searchUtils, @Assisted("baseUrl") String baseUrl, @Assisted("token") String token) { this.searchUtils = searchUtils; this.conduitConnection = conduitConnectionFactory.create(baseUrl); this.token = token; this.gson = new Gson(); } /** Runs the API's 'conduit.ping' method */ public ConduitPing conduitPing() throws ConduitException { Map<String, Object> params = new HashMap<>(); JsonElement callResult = conduitConnection.call("conduit.ping", params, token); JsonObject callResultWrapper = new JsonObject(); callResultWrapper.add("hostname", callResult); ConduitPing result = gson.fromJson(callResultWrapper, ConduitPing.class); return result; } /** Runs the API's 'maniphest.search' method */ public ManiphestSearch maniphestSearch(int taskId) throws ConduitException { HashMap<String, Object> params = new HashMap<>(); params.put("constraints", ImmutableMap.of("ids", ImmutableList.of(taskId))); params.put("attachments", ImmutableMap.of("projects", true)); JsonElement callResult = conduitConnection.call("maniphest.search", params, token); return searchUtils.stream(callResult, ManiphestSearch.class) .filter((r) -> r.getId() == taskId) .findFirst() .orElse(null); } /** Runs the API's 'maniphest.edit' method */ public ManiphestEdit maniphestEdit( int taskId, String comment, String projectNameToAdd, String projectNameToRemove) throws ConduitException { ManiphestEdit result = null; List<Object> transactions = new ArrayList<>(); if (!Strings.isNullOrEmpty(comment)) { HashMap<String, Object> transaction = new HashMap<>(); transaction.put("type", ACTION_COMMENT); transaction.put("value", comment); transactions.add(transaction); } if (!Strings.isNullOrEmpty(projectNameToAdd)) { HashMap<String, Object> transaction = new HashMap<>(); transaction.put("type", ACTION_PROJECT_ADD); transaction.put("value", ImmutableList.of(projectSearch(projectNameToAdd).getPhid())); transactions.add(transaction); } if (!Strings.isNullOrEmpty(projectNameToRemove)) { HashMap<String, Object> transaction = new HashMap<>(); transaction.put("type", ACTION_PROJECT_REMOVE); transaction.put("value", ImmutableList.of(projectSearch(projectNameToRemove).getPhid())); transactions.add(transaction); } if (!transactions.isEmpty()) { HashMap<String, Object> params = new HashMap<>(); params.put("objectIdentifier", taskId); params.put("transactions", transactions); JsonElement callResult = conduitConnection.call("maniphest.edit", params, token); result = gson.fromJson(callResult, ManiphestEdit.class); } return result; } /** Runs the API's 'project.search' method to match exactly one project name */ public ProjectSearch projectSearch(String name) throws ConduitException { HashMap<String, Object> params = new HashMap<>(); params.put("constraints", ImmutableMap.of("query", name)); JsonElement callResult = conduitConnection.call("project.search", params, token); return searchUtils.stream(callResult, ProjectSearch.class).findFirst().orElse(null); } }
Drop attachments from `maniphestSearch` After the re-doing of `maniphestEdit`, the projects attachment of `maniphestSearch` is no longer needed, so we drop it to avoid unnecessary load of the Phabricator API. Change-Id: Iee57abb3e60bb6c25214c57fa2989d221353c728
src/main/java/com/googlesource/gerrit/plugins/its/phabricator/conduit/Conduit.java
Drop attachments from `maniphestSearch`
<ide><path>rc/main/java/com/googlesource/gerrit/plugins/its/phabricator/conduit/Conduit.java <ide> public ManiphestSearch maniphestSearch(int taskId) throws ConduitException { <ide> HashMap<String, Object> params = new HashMap<>(); <ide> params.put("constraints", ImmutableMap.of("ids", ImmutableList.of(taskId))); <del> params.put("attachments", ImmutableMap.of("projects", true)); <ide> <ide> JsonElement callResult = conduitConnection.call("maniphest.search", params, token); <ide> return searchUtils.stream(callResult, ManiphestSearch.class)
Java
apache-2.0
8aa61926f18fd14c0a9f1cb981a6aa1e65636c4a
0
VladiMihaylenko/omim,mpimenov/omim,darina/omim,darina/omim,matsprea/omim,milchakov/omim,mapsme/omim,rokuz/omim,milchakov/omim,mapsme/omim,mapsme/omim,darina/omim,darina/omim,milchakov/omim,mpimenov/omim,darina/omim,VladiMihaylenko/omim,matsprea/omim,milchakov/omim,VladiMihaylenko/omim,milchakov/omim,mapsme/omim,darina/omim,rokuz/omim,darina/omim,milchakov/omim,rokuz/omim,VladiMihaylenko/omim,matsprea/omim,matsprea/omim,rokuz/omim,mpimenov/omim,rokuz/omim,darina/omim,matsprea/omim,rokuz/omim,milchakov/omim,mpimenov/omim,mapsme/omim,mapsme/omim,rokuz/omim,mpimenov/omim,rokuz/omim,VladiMihaylenko/omim,mapsme/omim,mpimenov/omim,matsprea/omim,mpimenov/omim,VladiMihaylenko/omim,mpimenov/omim,milchakov/omim,milchakov/omim,VladiMihaylenko/omim,darina/omim,mpimenov/omim,milchakov/omim,mpimenov/omim,VladiMihaylenko/omim,VladiMihaylenko/omim,rokuz/omim,rokuz/omim,mapsme/omim,darina/omim,mapsme/omim,mapsme/omim,milchakov/omim,matsprea/omim,milchakov/omim,VladiMihaylenko/omim,mapsme/omim,milchakov/omim,VladiMihaylenko/omim,mapsme/omim,mpimenov/omim,darina/omim,VladiMihaylenko/omim,rokuz/omim,mpimenov/omim,rokuz/omim,mpimenov/omim,mapsme/omim,VladiMihaylenko/omim,matsprea/omim,matsprea/omim,rokuz/omim,darina/omim,darina/omim,matsprea/omim
package com.mapswithme.util.statistics; import android.app.Activity; import android.content.Context; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Pair; import com.android.billingclient.api.BillingClient; import com.facebook.ads.AdError; import com.facebook.appevents.AppEventsLogger; import com.mapswithme.maps.BuildConfig; import com.mapswithme.maps.Framework; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.PrivateVariables; import com.mapswithme.maps.ads.MwmNativeAd; import com.mapswithme.maps.ads.NativeAdError; import com.mapswithme.maps.analytics.ExternalLibrariesMediator; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.maps.bookmarks.data.BookmarkCategory; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.downloader.MapManager; import com.mapswithme.maps.editor.Editor; import com.mapswithme.maps.editor.OsmOAuth; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.maps.purchase.ValidationStatus; import com.mapswithme.maps.routing.RoutePointInfo; import com.mapswithme.maps.routing.RoutingOptions; import com.mapswithme.maps.settings.RoadType; import com.mapswithme.maps.taxi.TaxiInfoError; import com.mapswithme.maps.taxi.TaxiManager; import com.mapswithme.maps.widget.menu.MainMenu; import com.mapswithme.maps.widget.placepage.Sponsored; import com.mapswithme.util.BatteryState; import com.mapswithme.util.Config; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.Counters; import com.mapswithme.util.PowerManagment; import com.mapswithme.util.SharedPropertiesUtils; import com.my.tracker.MyTracker; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.mapswithme.util.BatteryState.CHARGING_STATUS_PLUGGED; import static com.mapswithme.util.BatteryState.CHARGING_STATUS_UNKNOWN; import static com.mapswithme.util.BatteryState.CHARGING_STATUS_UNPLUGGED; import static com.mapswithme.util.statistics.Statistics.EventName.APPLICATION_COLD_STARTUP_INFO; import static com.mapswithme.util.statistics.Statistics.EventName.BM_GUIDES_DOWNLOADDIALOGUE_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.BM_RESTORE_PROPOSAL_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.BM_RESTORE_PROPOSAL_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.BM_RESTORE_PROPOSAL_SUCCESS; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_APPROVED; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_SHOWN; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_TOGGLE; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_SUCCESS; import static com.mapswithme.util.statistics.Statistics.EventName.DOWNLOADER_DIALOG_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_PREVIEW_SELECT; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_PREVIEW_SHOW; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_PRODUCT_DELIVERED; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_STORE_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_VALIDATION_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_BLANK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_CLOSE; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_SHOW; import static com.mapswithme.util.statistics.Statistics.EventName.PP_OWNERSHIP_BUTTON_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_BOOK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_OPEN; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_SHOWN; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSOR_ITEM_SELECTED; import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_PLAN_TOOLTIP_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_ROUTE_FINISH; import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_ROUTE_START; import static com.mapswithme.util.statistics.Statistics.EventName.SEARCH_FILTER_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.TIPS_TRICKS_CLOSE; import static com.mapswithme.util.statistics.Statistics.EventName.TOOLBAR_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.TOOLBAR_MENU_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_AUTH_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_AUTH_EXTERNAL_REQUEST_SUCCESS; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_AUTH_SHOWN; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_REVIEW_START; import static com.mapswithme.util.statistics.Statistics.EventParam.ACTION; import static com.mapswithme.util.statistics.Statistics.EventParam.BANNER; import static com.mapswithme.util.statistics.Statistics.EventParam.BATTERY; import static com.mapswithme.util.statistics.Statistics.EventParam.BUTTON; import static com.mapswithme.util.statistics.Statistics.EventParam.CATEGORY; import static com.mapswithme.util.statistics.Statistics.EventParam.CHARGING; import static com.mapswithme.util.statistics.Statistics.EventParam.DESTINATION; import static com.mapswithme.util.statistics.Statistics.EventParam.ERROR; import static com.mapswithme.util.statistics.Statistics.EventParam.ERROR_CODE; import static com.mapswithme.util.statistics.Statistics.EventParam.ERROR_MESSAGE; import static com.mapswithme.util.statistics.Statistics.EventParam.FEATURE_ID; import static com.mapswithme.util.statistics.Statistics.EventParam.HAS_AUTH; import static com.mapswithme.util.statistics.Statistics.EventParam.HOTEL; import static com.mapswithme.util.statistics.Statistics.EventParam.HOTEL_LAT; import static com.mapswithme.util.statistics.Statistics.EventParam.HOTEL_LON; import static com.mapswithme.util.statistics.Statistics.EventParam.INTERRUPTED; import static com.mapswithme.util.statistics.Statistics.EventParam.ITEM; import static com.mapswithme.util.statistics.Statistics.EventParam.MAP_DATA_SIZE; import static com.mapswithme.util.statistics.Statistics.EventParam.METHOD; import static com.mapswithme.util.statistics.Statistics.EventParam.MODE; import static com.mapswithme.util.statistics.Statistics.EventParam.MWM_NAME; import static com.mapswithme.util.statistics.Statistics.EventParam.MWM_VERSION; import static com.mapswithme.util.statistics.Statistics.EventParam.NETWORK; import static com.mapswithme.util.statistics.Statistics.EventParam.OBJECT_LAT; import static com.mapswithme.util.statistics.Statistics.EventParam.OBJECT_LON; import static com.mapswithme.util.statistics.Statistics.EventParam.OPTION; import static com.mapswithme.util.statistics.Statistics.EventParam.PLACEMENT; import static com.mapswithme.util.statistics.Statistics.EventParam.PRODUCT; import static com.mapswithme.util.statistics.Statistics.EventParam.PROVIDER; import static com.mapswithme.util.statistics.Statistics.EventParam.PURCHASE; import static com.mapswithme.util.statistics.Statistics.EventParam.RESTAURANT; import static com.mapswithme.util.statistics.Statistics.EventParam.RESTAURANT_LAT; import static com.mapswithme.util.statistics.Statistics.EventParam.RESTAURANT_LON; import static com.mapswithme.util.statistics.Statistics.EventParam.STATE; import static com.mapswithme.util.statistics.Statistics.EventParam.TYPE; import static com.mapswithme.util.statistics.Statistics.EventParam.VALUE; import static com.mapswithme.util.statistics.Statistics.EventParam.VENDOR; import static com.mapswithme.util.statistics.Statistics.ParamValue.BACKUP; import static com.mapswithme.util.statistics.Statistics.ParamValue.BICYCLE; import static com.mapswithme.util.statistics.Statistics.ParamValue.BOOKING_COM; import static com.mapswithme.util.statistics.Statistics.ParamValue.DISK_NO_SPACE; import static com.mapswithme.util.statistics.Statistics.ParamValue.FACEBOOK; import static com.mapswithme.util.statistics.Statistics.ParamValue.GOOGLE; import static com.mapswithme.util.statistics.Statistics.ParamValue.HOLIDAY; import static com.mapswithme.util.statistics.Statistics.ParamValue.MAPSME; import static com.mapswithme.util.statistics.Statistics.ParamValue.NO_BACKUP; import static com.mapswithme.util.statistics.Statistics.ParamValue.OFFSCREEEN; import static com.mapswithme.util.statistics.Statistics.ParamValue.OPENTABLE; import static com.mapswithme.util.statistics.Statistics.ParamValue.PEDESTRIAN; import static com.mapswithme.util.statistics.Statistics.ParamValue.PHONE; import static com.mapswithme.util.statistics.Statistics.ParamValue.RESTORE; import static com.mapswithme.util.statistics.Statistics.ParamValue.SEARCH_BOOKING_COM; import static com.mapswithme.util.statistics.Statistics.ParamValue.TAXI; import static com.mapswithme.util.statistics.Statistics.ParamValue.TRAFFIC; import static com.mapswithme.util.statistics.Statistics.ParamValue.TRANSIT; import static com.mapswithme.util.statistics.Statistics.ParamValue.UNKNOWN; import static com.mapswithme.util.statistics.Statistics.ParamValue.VEHICLE; public enum Statistics { INSTANCE; public void trackCategoryDescChanged() { trackEditSettingsScreenOptionClick(ParamValue.ADD_DESC); } public void trackSharingOptionsClick(@NonNull String value) { ParameterBuilder builder = new ParameterBuilder().add(OPTION, value); trackEvent(EventName.BM_SHARING_OPTIONS_CLICK, builder); } public void trackSharingOptionsError(@NonNull String error, @NonNull NetworkErrorType value) { trackSharingOptionsError(error, value.ordinal()); } public void trackSharingOptionsError(@NonNull String error, int value) { ParameterBuilder builder = new ParameterBuilder().add(EventParam.ERROR, value); trackEvent(error, builder); } public void trackSharingOptionsUploadSuccess(@NonNull BookmarkCategory category) { ParameterBuilder builder = new ParameterBuilder().add(EventParam.TRACKS, category.getTracksCount()) .add(EventParam.POINTS, category.getBookmarksCount()); trackEvent(EventName.BM_SHARING_OPTIONS_UPLOAD_SUCCESS, builder); } public void trackBookmarkListSettingsClick(@NonNull Analytics analytics) { ParameterBuilder builder = ParameterBuilder.from(OPTION, analytics); trackEvent(EventName.BM_BOOKMARKS_LIST_SETTINGS_CLICK, builder); } private void trackEditSettingsScreenOptionClick(@NonNull String value) { ParameterBuilder builder = new ParameterBuilder().add(OPTION, value); trackEvent(EventName.BM_EDIT_SETTINGS_CLICK, builder); } public void trackEditSettingsCancel() { trackEvent(EventName.BM_EDIT_SETTINGS_CANCEL); } public void trackEditSettingsConfirm() { trackEvent(EventName.BM_EDIT_SETTINGS_CONFIRM); } public void trackEditSettingsSharingOptionsClick() { trackEditSettingsScreenOptionClick(Statistics.ParamValue.SHARING_OPTIONS); } public void trackBookmarkListSharingOptions() { trackEvent(Statistics.EventName.BM_BOOKMARKS_LIST_ITEM_SETTINGS, new Statistics.ParameterBuilder().add(OPTION, Statistics.ParamValue.SHARING_OPTIONS)); } public void trackSettingsDrivingOptionsChangeEvent() { boolean hasToll = RoutingOptions.hasOption(RoadType.Toll); boolean hasFerry = RoutingOptions.hasOption(RoadType.Ferry); boolean hasMoto = RoutingOptions.hasOption(RoadType.Motorway); boolean hasDirty = RoutingOptions.hasOption(RoadType.Dirty); ParameterBuilder builder = new ParameterBuilder() ; ParameterBuilder parameterBuilder = builder.add(EventParam.TOLL, hasToll ? 1 : 0) .add(EventParam.FERRY, hasFerry ? 1 : 0) .add(EventParam.MOTORWAY, hasMoto ? 1 : 0) .add(EventParam.UNPAVED, hasDirty ? 1 : 0); parameterBuilder.add(EventParam.FROM, EventParam.SETTINGS); trackEvent(EventName.SETTINGS_DRIVING_OPTIONS_CHANGE, parameterBuilder); } @Retention(RetentionPolicy.SOURCE) @IntDef({PP_BANNER_STATE_PREVIEW, PP_BANNER_STATE_DETAILS}) public @interface BannerState {} public static final int PP_BANNER_STATE_PREVIEW = 0; public static final int PP_BANNER_STATE_DETAILS = 1; // Statistics counters private int mBookmarksCreated; private int mSharedTimes; public static class EventName { // Downloader public static final String DOWNLOADER_MIGRATION_DIALOG_SEEN = "Downloader_Migration_dialogue"; public static final String DOWNLOADER_MIGRATION_STARTED = "Downloader_Migration_started"; public static final String DOWNLOADER_MIGRATION_COMPLETE = "Downloader_Migration_completed"; public static final String DOWNLOADER_MIGRATION_ERROR = "Downloader_Migration_error"; public static final String DOWNLOADER_ERROR = "Downloader_Map_error"; public static final String DOWNLOADER_ACTION = "Downloader_Map_action"; public static final String DOWNLOADER_CANCEL = "Downloader_Cancel_downloading"; public static final String DOWNLOADER_DIALOG_SHOW = "Downloader_OnStartScreen_show"; public static final String DOWNLOADER_DIALOG_MANUAL_DOWNLOAD = "Downloader_OnStartScreen_manual_download"; public static final String DOWNLOADER_DIALOG_DOWNLOAD = "Downloader_OnStartScreen_auto_download"; public static final String DOWNLOADER_DIALOG_LATER = "Downloader_OnStartScreen_select_later"; public static final String DOWNLOADER_DIALOG_HIDE = "Downloader_OnStartScreen_select_hide"; public static final String DOWNLOADER_DIALOG_CANCEL = "Downloader_OnStartScreen_cancel_download"; public static final String SETTINGS_TRACKING_DETAILS = "Settings_Tracking_details"; public static final String SETTINGS_TRACKING_TOGGLE = "Settings_Tracking_toggle"; public static final String PLACEPAGE_DESCRIPTION_MORE = "Placepage_Description_more"; public static final String PLACEPAGE_DESCRIPTION_OUTBOUND_CLICK = "Placepage_Description_Outbound_click"; public static final String SETTINGS_SPEED_CAMS = "Settings. Speed_cameras"; static final String DOWNLOADER_DIALOG_ERROR = "Downloader_OnStartScreen_error"; // bookmarks private static final String BM_SHARING_OPTIONS_UPLOAD_SUCCESS = "Bookmarks_SharingOptions_upload_success"; public static final String BM_SHARING_OPTIONS_UPLOAD_ERROR = "Bookmarks_SharingOptions_upload_error"; public static final String BM_SHARING_OPTIONS_ERROR = "Bookmarks_SharingOptions_error"; public static final String BM_SHARING_OPTIONS_CLICK = "Bookmarks_SharingOptions_click"; public static final String BM_EDIT_SETTINGS_CLICK = "Bookmarks_Bookmark_Settings_click"; public static final String BM_EDIT_SETTINGS_CANCEL = "Bookmarks_Bookmark_Settings_cancel"; public static final String BM_EDIT_SETTINGS_CONFIRM = "Bookmarks_Bookmark_Settings_confirm"; public static final String BM_BOOKMARKS_LIST_SETTINGS_CLICK = "Bookmarks_BookmarksList_settings_click"; public static final String BM_BOOKMARKS_LIST_ITEM_SETTINGS = "Bookmarks_BookmarksListItem_settings"; public static final String BM_GROUP_CREATED = "Bookmark. Group created"; public static final String BM_GROUP_CHANGED = "Bookmark. Group changed"; public static final String BM_COLOR_CHANGED = "Bookmark. Color changed"; public static final String BM_CREATED = "Bookmark. Bookmark created"; public static final String BM_SYNC_PROPOSAL_SHOWN = "Bookmarks_SyncProposal_shown"; public static final String BM_SYNC_PROPOSAL_APPROVED = "Bookmarks_SyncProposal_approved"; public static final String BM_SYNC_PROPOSAL_ERROR = "Bookmarks_SyncProposal_error"; public static final String BM_SYNC_PROPOSAL_ENABLED = "Bookmarks_SyncProposal_enabled"; public static final String BM_SYNC_PROPOSAL_TOGGLE = "Settings_BookmarksSync_toggle"; public static final String BM_SYNC_STARTED = "Bookmarks_sync_started"; public static final String BM_SYNC_ERROR = "Bookmarks_sync_error"; public static final String BM_SYNC_SUCCESS = "Bookmarks_sync_success"; public static final String BM_EDIT_ON_WEB_CLICK = "Bookmarks_EditOnWeb_click"; static final String BM_RESTORE_PROPOSAL_CLICK = "Bookmarks_RestoreProposal_click"; public static final String BM_RESTORE_PROPOSAL_CANCEL = "Bookmarks_RestoreProposal_cancel"; public static final String BM_RESTORE_PROPOSAL_SUCCESS = "Bookmarks_RestoreProposal_success"; static final String BM_RESTORE_PROPOSAL_ERROR = "Bookmarks_RestoreProposal_error"; static final String BM_TAB_CLICK = "Bookmarks_Tab_click"; private static final String BM_DOWNLOADED_CATALOGUE_OPEN = "Bookmarks_Downloaded_Catalogue_open"; private static final String BM_DOWNLOADED_CATALOGUE_ERROR = "Bookmarks_Downloaded_Catalogue_error"; public static final String BM_GUIDEDOWNLOADTOAST_SHOWN = "Bookmarks_GuideDownloadToast_shown"; public static final String BM_GUIDES_DOWNLOADDIALOGUE_CLICK = "Bookmarks_Guides_DownloadDialogue_click"; public static final String SETTINGS_DRIVING_OPTIONS_CHANGE = "Settings_Navigation_DrivingOptions_change"; public static final String PP_DRIVING_OPTIONS_ACTION = "Placepage_DrivingOptions_action"; // search public static final String SEARCH_CAT_CLICKED = "Search. Category clicked"; public static final String SEARCH_ITEM_CLICKED = "Search. Key clicked"; public static final String SEARCH_ON_MAP_CLICKED = "Search. View on map clicked."; public static final String SEARCH_TAB_SELECTED = "Search_Tab_selected"; public static final String SEARCH_SPONSOR_CATEGORY_SHOWN = "Search_SponsoredCategory_shown"; public static final String SEARCH_SPONSOR_CATEGORY_SELECTED = "Search_SponsoredCategory_selected"; public static final String SEARCH_FILTER_OPEN = "Search_Filter_Open"; public static final String SEARCH_FILTER_CANCEL = "Search_Filter_Cancel"; public static final String SEARCH_FILTER_RESET = "Search_Filter_Reset"; public static final String SEARCH_FILTER_APPLY = "Search_Filter_Apply"; public static final String SEARCH_FILTER_CLICK = "Search_Filter_Click"; // place page public static final String PP_DETAILS_OPEN = "Placepage_Details_open"; public static final String PP_SHARE = "PP. Share"; public static final String PP_BOOKMARK = "PP. Bookmark"; public static final String PP_ROUTE = "PP. Route"; public static final String PP_SPONSORED_DETAILS = "Placepage_Hotel_details"; public static final String PP_SPONSORED_BOOK = "Placepage_Hotel_book"; public static final String PP_SPONSORED_OPENTABLE = "Placepage_Restaurant_book"; public static final String PP_SPONSORED_OPEN = "Placepage_SponsoredGalleryPage_opened"; public static final String PP_SPONSORED_SHOWN = "Placepage_SponsoredGallery_shown"; public static final String PP_SPONSORED_ERROR = "Placepage_SponsoredGallery_error"; public static final String PP_SPONSORED_ACTION = "Placepage_SponsoredActionButton_click"; public static final String PP_SPONSOR_ITEM_SELECTED = "Placepage_SponsoredGallery_ProductItem_selected"; public static final String PP_SPONSOR_MORE_SELECTED = "Placepage_SponsoredGallery_MoreItem_selected"; public static final String PP_SPONSOR_LOGO_SELECTED = "Placepage_SponsoredGallery_LogoItem_selected"; public static final String PP_DIRECTION_ARROW = "PP. DirectionArrow"; public static final String PP_DIRECTION_ARROW_CLOSE = "PP. DirectionArrowClose"; public static final String PP_METADATA_COPY = "PP. CopyMetadata"; public static final String PP_BANNER_CLICK = "Placepage_Banner_click"; public static final String PP_BANNER_SHOW = "Placepage_Banner_show"; public static final String PP_BANNER_ERROR = "Placepage_Banner_error"; public static final String PP_BANNER_BLANK = "Placepage_Banner_blank"; public static final String PP_BANNER_CLOSE = "Placepage_Banner_close"; public static final String PP_HOTEL_GALLERY_OPEN = "PlacePage_Hotel_Gallery_open"; public static final String PP_HOTEL_REVIEWS_LAND = "PlacePage_Hotel_Reviews_land"; public static final String PP_HOTEL_DESCRIPTION_LAND = "PlacePage_Hotel_Description_land"; public static final String PP_HOTEL_FACILITIES = "PlacePage_Hotel_Facilities_open"; public static final String PP_HOTEL_SEARCH_SIMILAR = "Placepage_Hotel_search_similar"; static final String PP_OWNERSHIP_BUTTON_CLICK = "Placepage_OwnershipButton_click"; // toolbar actions public static final String TOOLBAR_MY_POSITION = "Toolbar. MyPosition"; static final String TOOLBAR_CLICK = "Toolbar_click"; static final String TOOLBAR_MENU_CLICK = "Toolbar_Menu_click"; // dialogs public static final String PLUS_DIALOG_LATER = "GPlus dialog cancelled."; public static final String RATE_DIALOG_LATER = "GPlay dialog cancelled."; public static final String FACEBOOK_INVITE_LATER = "Facebook invites dialog cancelled."; public static final String FACEBOOK_INVITE_INVITED = "Facebook invites dialog accepted."; public static final String RATE_DIALOG_RATED = "GPlay dialog. Rating set"; // misc public static final String ZOOM_IN = "Zoom. In"; public static final String ZOOM_OUT = "Zoom. Out"; public static final String PLACE_SHARED = "Place Shared"; public static final String API_CALLED = "API called"; public static final String DOWNLOAD_COUNTRY_NOTIFICATION_SHOWN = "Download country notification shown"; public static final String ACTIVE_CONNECTION = "Connection"; public static final String STATISTICS_STATUS_CHANGED = "Statistics status changed"; public static final String TTS_FAILURE_LOCATION = "TTS failure location"; public static final String UGC_NOT_AUTH_NOTIFICATION_SHOWN = "UGC_UnsentNotification_shown"; public static final String UGC_NOT_AUTH_NOTIFICATION_CLICKED = "UGC_UnsentNotification_clicked"; public static final String UGC_REVIEW_NOTIFICATION_SHOWN = "UGC_ReviewNotification_shown"; public static final String UGC_REVIEW_NOTIFICATION_CLICKED = "UGC_ReviewNotification_clicked"; // routing public static final String ROUTING_BUILD = "Routing. Build"; public static final String ROUTING_START_SUGGEST_REBUILD = "Routing. Suggest rebuild"; public static final String ROUTING_ROUTE_START = "Routing_Route_start"; public static final String ROUTING_ROUTE_FINISH = "Routing_Route_finish"; public static final String ROUTING_CANCEL = "Routing. Cancel"; public static final String ROUTING_VEHICLE_SET = "Routing. Set vehicle"; public static final String ROUTING_PEDESTRIAN_SET = "Routing. Set pedestrian"; public static final String ROUTING_BICYCLE_SET = "Routing. Set bicycle"; public static final String ROUTING_TAXI_SET = "Routing. Set taxi"; public static final String ROUTING_TRANSIT_SET = "Routing. Set transit"; public static final String ROUTING_SWAP_POINTS = "Routing. Swap points"; public static final String ROUTING_SETTINGS = "Routing. Settings"; public static final String ROUTING_TAXI_ORDER = "Routing_Taxi_order"; public static final String ROUTING_TAXI_INSTALL = "Routing_Taxi_install"; public static final String ROUTING_TAXI_SHOW = "Placepage_Taxi_show"; public static final String ROUTING_TAXI_CLICK_IN_PP = "Placepage_Taxi_click"; public static final String ROUTING_TAXI_ROUTE_BUILT = "Routing_Build_Taxi"; public static final String ROUTING_POINT_ADD = "Routing_Point_add"; public static final String ROUTING_POINT_REMOVE = "Routing_Point_remove"; public static final String ROUTING_SEARCH_CLICK = "Routing_Search_click"; public static final String ROUTING_BOOKMARKS_CLICK = "Routing_Bookmarks_click"; public static final String ROUTING_PLAN_TOOLTIP_CLICK = "Routing_PlanTooltip_click"; // editor public static final String EDITOR_START_CREATE = "Editor_Add_start"; public static final String EDITOR_ADD_CLICK = "Editor_Add_click"; public static final String EDITOR_START_EDIT = "Editor_Edit_start"; public static final String EDITOR_SUCCESS_CREATE = "Editor_Add_success"; public static final String EDITOR_SUCCESS_EDIT = "Editor_Edit_success"; public static final String EDITOR_ERROR_CREATE = "Editor_Add_error"; public static final String EDITOR_ERROR_EDIT = "Editor_Edit_error"; public static final String EDITOR_AUTH_DECLINED = "Editor_Auth_declined_by_user"; public static final String EDITOR_AUTH_REQUEST = "Editor_Auth_request"; public static final String EDITOR_AUTH_REQUEST_RESULT = "Editor_Auth_request_result"; public static final String EDITOR_REG_REQUEST = "Editor_Reg_request"; public static final String EDITOR_LOST_PASSWORD = "Editor_Lost_password"; public static final String EDITOR_SHARE_SHOW = "Editor_SecondTimeShare_show"; public static final String EDITOR_SHARE_CLICK = "Editor_SecondTimeShare_click"; // Cold start public static final String APPLICATION_COLD_STARTUP_INFO = "Application_ColdStartup_info"; // Ugc. public static final String UGC_REVIEW_START = "UGC_Review_start"; public static final String UGC_REVIEW_CANCEL = "UGC_Review_cancel"; public static final String UGC_REVIEW_SUCCESS = "UGC_Review_success"; public static final String UGC_AUTH_SHOWN = "UGC_Auth_shown"; public static final String UGC_AUTH_DECLINED = "UGC_Auth_declined"; public static final String UGC_AUTH_EXTERNAL_REQUEST_SUCCESS = "UGC_Auth_external_request_success"; public static final String UGC_AUTH_ERROR = "UGC_Auth_error"; public static final String MAP_LAYERS_ACTIVATE = "Map_Layers_activate"; // Purchases. static final String INAPP_PURCHASE_PREVIEW_SHOW = "InAppPurchase_Preview_show"; static final String INAPP_PURCHASE_PREVIEW_SELECT = "InAppPurchase_Preview_select"; public static final String INAPP_PURCHASE_PREVIEW_PAY = "InAppPurchase_Preview_pay"; public static final String INAPP_PURCHASE_PREVIEW_CANCEL = "InAppPurchase_Preview_cancel"; public static final String INAPP_PURCHASE_STORE_SUCCESS = "InAppPurchase_Store_success"; static final String INAPP_PURCHASE_STORE_ERROR = "InAppPurchase_Store_error"; public static final String INAPP_PURCHASE_VALIDATION_SUCCESS = "InAppPurchase_Validation_success"; static final String INAPP_PURCHASE_VALIDATION_ERROR = "InAppPurchase_Validation_error"; static final String INAPP_PURCHASE_PRODUCT_DELIVERED = "InAppPurchase_Product_delivered"; public static final String ONBOARDING_DEEPLINK_SCREEN_SHOW = "OnboardingDeeplinkScreen_show"; public static final String ONBOARDING_DEEPLINK_SCREEN_ACCEPT = "OnboardingDeeplinkScreen_accept"; public static final String ONBOARDING_DEEPLINK_SCREEN_DECLINE = "OnboardingDeeplinkScreen_decline"; public static final String TIPS_TRICKS_SHOW = "TipsTricks_show"; public static final String TIPS_TRICKS_CLOSE = "TipsTricks_close"; public static final String TIPS_TRICKS_CLICK = "TipsTricks_click"; public static class Settings { public static final String WEB_SITE = "Setings. Go to website"; public static final String FEEDBACK_GENERAL = "Send general feedback to [email protected]"; public static final String REPORT_BUG = "Settings. Bug reported"; public static final String RATE = "Settings. Rate app called"; public static final String TELL_FRIEND = "Settings. Tell to friend"; public static final String FACEBOOK = "Settings. Go to FB."; public static final String TWITTER = "Settings. Go to twitter."; public static final String HELP = "Settings. Help."; public static final String ABOUT = "Settings. About."; public static final String OSM_PROFILE = "Settings. Profile."; public static final String COPYRIGHT = "Settings. Copyright."; public static final String UNITS = "Settings. Change units."; public static final String ZOOM = "Settings. Switch zoom."; public static final String MAP_STYLE = "Settings. Map style."; public static final String VOICE_ENABLED = "Settings. Switch voice."; public static final String VOICE_LANGUAGE = "Settings. Voice language."; public static final String ENERGY_SAVING = "Settings_EnergySaving_change"; private Settings() {} } private EventName() {} } public static class EventParam { public static final String FROM = "from"; public static final String TO = "to"; public static final String OPTION = "option"; public static final String TRACKS = "tracks"; public static final String POINTS = "points"; public static final String URL = "url"; public static final String TOLL = "toll"; public static final String UNPAVED = "unpaved"; public static final String FERRY = "ferry"; public static final String MOTORWAY = "motorway"; public static final String SETTINGS = "settings"; public static final String ROUTE = "route"; static final String CATEGORY = "category"; public static final String TAB = "tab"; static final String COUNT = "Count"; static final String CHANNEL = "Channel"; static final String CALLER_ID = "Caller ID"; public static final String ENABLED = "Enabled"; public static final String RATING = "Rating"; static final String CONNECTION_TYPE = "Connection name"; static final String CONNECTION_FAST = "Connection fast"; static final String CONNECTION_METERED = "Connection limit"; static final String MY_POSITION = "my position"; static final String POINT = "point"; public static final String LANGUAGE = "language"; public static final String NAME = "Name"; public static final String ACTION = "action"; public static final String TYPE = "type"; static final String IS_AUTHENTICATED = "is_authenticated"; static final String IS_ONLINE = "is_online"; public static final String IS_SUCCESS = "is_success_message"; static final String FEATURE_ID = "feature_id"; static final String MWM_NAME = "mwm_name"; static final String MWM_VERSION = "mwm_version"; public static final String ERR_MSG = "error_message"; public static final String OSM = "OSM"; public static final String FACEBOOK = "Facebook"; public static final String PROVIDER = "provider"; public static final String HOTEL = "hotel"; static final String HOTEL_LAT = "hotel_lat"; static final String HOTEL_LON = "hotel_lon"; static final String RESTAURANT = "restaurant"; static final String RESTAURANT_LAT = "restaurant_lat"; static final String RESTAURANT_LON = "restaurant_lon"; static final String FROM_LAT = "from_lat"; static final String FROM_LON = "from_lon"; static final String TO_LAT = "to_lat"; static final String TO_LON = "to_lon"; static final String BANNER = "banner"; static final String STATE = "state"; static final String ERROR_CODE = "error_code"; public static final String ERROR = "error"; static final String ERROR_MESSAGE = "error_message"; static final String MAP_DATA_SIZE = "map_data_size:"; static final String BATTERY = "battery"; static final String CHARGING = "charging"; static final String NETWORK = "network"; public static final String VALUE = "value"; static final String METHOD = "method"; static final String MODE = "mode"; static final String OBJECT_LAT = "object_lat"; static final String OBJECT_LON = "object_lon"; static final String ITEM = "item"; static final String DESTINATION = "destination"; static final String PLACEMENT = "placement"; public static final String PRICE_CATEGORY = "price_category"; public static final String DATE = "date"; static final String HAS_AUTH = "has_auth"; public static final String STATUS = "status"; static final String INTERRUPTED = "interrupted"; static final String BUTTON = "button"; static final String VENDOR = "vendor"; static final String PRODUCT = "product"; static final String PURCHASE = "purchase"; private EventParam() {} } public static class ParamValue { public static final String BOOKING_COM = "Booking.Com"; public static final String OSM = "OSM"; public static final String ON = "on"; public static final String OFF = "off"; public static final String CRASH_REPORTS = "crash_reports"; public static final String PERSONAL_ADS = "personal_ads"; public static final String SHARING_OPTIONS = "sharing_options"; public static final String EDIT_ON_WEB = "edit_on_web"; public static final String PUBLIC = "public"; public static final String PRIVATE = "private"; public static final String COPY_LINK = "copy_link"; static final String SEARCH_BOOKING_COM = "Search.Booking.Com"; static final String OPENTABLE = "OpenTable"; static final String LOCALS_EXPERTS = "Locals.Maps.Me"; static final String SEARCH_RESTAURANTS = "Search.Restaurants"; static final String SEARCH_ATTRACTIONS = "Search.Attractions"; static final String HOLIDAY = "Holiday"; public static final String NO_PRODUCTS = "no_products"; static final String ADD = "add"; public static final String EDIT = "edit"; static final String AFTER_SAVE = "after_save"; static final String PLACEPAGE_PREVIEW = "placepage_preview"; static final String PLACEPAGE = "placepage"; static final String NOTIFICATION = "notification"; public static final String FACEBOOK = "facebook"; public static final String CHECKIN = "check_in"; public static final String CHECKOUT = "check_out"; public static final String ANY = "any"; public static final String GOOGLE = "google"; public static final String MAPSME = "mapsme"; public static final String PHONE = "phone"; public static final String UNKNOWN = "unknown"; static final String NETWORK = "network"; static final String DISK = "disk"; static final String AUTH = "auth"; static final String USER_INTERRUPTED = "user_interrupted"; static final String INVALID_CALL = "invalid_call"; static final String NO_BACKUP = "no_backup"; static final String DISK_NO_SPACE = "disk_no_space"; static final String BACKUP = "backup"; static final String RESTORE = "restore"; public static final String NO_INTERNET = "no_internet"; public static final String MY = "my"; public static final String DOWNLOADED = "downloaded"; static final String SUBWAY = "subway"; static final String TRAFFIC = "traffic"; public static final String SUCCESS = "success"; public static final String UNAVAILABLE = "unavailable"; static final String PEDESTRIAN = "pedestrian"; static final String VEHICLE = "vehicle"; static final String BICYCLE = "bicycle"; static final String TAXI = "taxi"; static final String TRANSIT = "transit"; public final static String VIEW_ON_MAP = "view on map"; public final static String NOT_NOW = "not now"; public final static String CLICK_OUTSIDE = "click outside pop-up"; public static final String ADD_DESC = "add_description"; public static final String SEND_AS_FILE = "send_as_file"; public static final String MAKE_INVISIBLE_ON_MAP = "make_invisible_on_map"; public static final String LIST_SETTINGS = "list_settings"; public static final String DELETE_GROUP = "delete_group"; public static final String OFFSCREEEN = "Offscreen"; } // Initialized once in constructor and does not change until the process restarts. // In this way we can correctly finish all statistics sessions and completely // avoid their initialization if user has disabled statistics collection. private final boolean mEnabled; Statistics() { mEnabled = SharedPropertiesUtils.isStatisticsEnabled(); final Context context = MwmApplication.get(); // At the moment we need special handling for Alohalytics to enable/disable logging of events in core C++ code. if (mEnabled) org.alohalytics.Statistics.enable(context); else org.alohalytics.Statistics.disable(context); configure(context); } @SuppressWarnings("NullableProblems") @NonNull private ExternalLibrariesMediator mMediator; public void setMediator(@NonNull ExternalLibrariesMediator mediator) { mMediator = mediator; } private void configure(Context context) { // At the moment, need to always initialize engine for correct JNI http part reusing. // Statistics is still enabled/disabled separately and never sent anywhere if turned off. // TODO (AlexZ): Remove this initialization dependency from JNI part. org.alohalytics.Statistics.setDebugMode(BuildConfig.DEBUG); org.alohalytics.Statistics.setup(PrivateVariables.alohalyticsUrl(), context); } public void trackEvent(@NonNull String name) { if (mEnabled) org.alohalytics.Statistics.logEvent(name); mMediator.getEventLogger().logEvent(name, Collections.emptyMap()); } public void trackEvent(@NonNull String name, @NonNull Map<String, String> params) { if (mEnabled) org.alohalytics.Statistics.logEvent(name, params); mMediator.getEventLogger().logEvent(name, params); } public void trackEvent(@NonNull String name, @Nullable Location location, @NonNull Map<String, String> params) { List<String> eventDictionary = new ArrayList<String>(); for (Map.Entry<String, String> entry : params.entrySet()) { eventDictionary.add(entry.getKey()); eventDictionary.add(entry.getValue()); } params.put("lat", (location == null ? "N/A" : String.valueOf(location.getLatitude()))); params.put("lon", (location == null ? "N/A" : String.valueOf(location.getLongitude()))); if (mEnabled) org.alohalytics.Statistics.logEvent(name, eventDictionary.toArray(new String[0]), location); mMediator.getEventLogger().logEvent(name, params); } public void trackEvent(@NonNull String name, @NonNull ParameterBuilder builder) { trackEvent(name, builder.get()); } public void startActivity(Activity activity) { if (mEnabled) { AppEventsLogger.activateApp(activity); org.alohalytics.Statistics.onStart(activity); } mMediator.getEventLogger().startActivity(activity); } public void stopActivity(Activity activity) { if (mEnabled) { AppEventsLogger.deactivateApp(activity); org.alohalytics.Statistics.onStop(activity); } mMediator.getEventLogger().stopActivity(activity); } public void setStatEnabled(boolean isEnabled) { SharedPropertiesUtils.setStatisticsEnabled(isEnabled); Config.setStatisticsEnabled(isEnabled); // We track if user turned on/off statistics to understand data better. trackEvent(EventName.STATISTICS_STATUS_CHANGED + " " + Counters.getInstallFlavor(), params().add(EventParam.ENABLED, String.valueOf(isEnabled))); } public void trackSearchTabSelected(@NonNull String tab) { trackEvent(EventName.SEARCH_TAB_SELECTED, params().add(EventParam.TAB, tab)); } public void trackSearchCategoryClicked(String category) { trackEvent(EventName.SEARCH_CAT_CLICKED, params().add(EventParam.CATEGORY, category)); } public void trackColorChanged(String from, String to) { trackEvent(EventName.BM_COLOR_CHANGED, params().add(EventParam.FROM, from) .add(EventParam.TO, to)); } public void trackBookmarkCreated() { trackEvent(EventName.BM_CREATED, params().add(EventParam.COUNT, String.valueOf(++mBookmarksCreated))); } public void trackPlaceShared(String channel) { trackEvent(EventName.PLACE_SHARED, params().add(EventParam.CHANNEL, channel).add(EventParam.COUNT, String.valueOf(++mSharedTimes))); } public void trackApiCall(@NonNull ParsedMwmRequest request) { trackEvent(EventName.API_CALLED, params().add(EventParam.CALLER_ID, request.getCallerInfo() == null ? "null" : request.getCallerInfo().packageName)); } public void trackRatingDialog(float rating) { trackEvent(EventName.RATE_DIALOG_RATED, params().add(EventParam.RATING, String.valueOf(rating))); } public void trackConnectionState() { if (ConnectionState.isConnected()) { final NetworkInfo info = ConnectionState.getActiveNetwork(); boolean isConnectionMetered = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) isConnectionMetered = ((ConnectivityManager) MwmApplication.get().getSystemService(Context.CONNECTIVITY_SERVICE)).isActiveNetworkMetered(); //noinspection ConstantConditions trackEvent(EventName.ACTIVE_CONNECTION, params().add(EventParam.CONNECTION_TYPE, info.getTypeName() + ":" + info.getSubtypeName()) .add(EventParam.CONNECTION_FAST, String.valueOf(ConnectionState.isConnectionFast(info))) .add(EventParam.CONNECTION_METERED, String.valueOf(isConnectionMetered))); } else trackEvent(EventName.ACTIVE_CONNECTION, params().add(EventParam.CONNECTION_TYPE, "Not connected.")); } // FIXME Call to track map changes to MyTracker to correctly deal with preinstalls. public void trackMapChanged(String event) { if (mEnabled) { final ParameterBuilder params = params().add(EventParam.COUNT, String.valueOf(MapManager.nativeGetDownloadedCount())); trackEvent(event, params); } } public void trackRouteBuild(int routerType, MapObject from, MapObject to) { trackEvent(EventName.ROUTING_BUILD, params().add(EventParam.FROM, Statistics.getPointType(from)) .add(EventParam.TO, Statistics.getPointType(to))); } public void trackEditorLaunch(boolean newObject) { trackEvent(newObject ? EventName.EDITOR_START_CREATE : EventName.EDITOR_START_EDIT, editorMwmParams().add(EventParam.IS_AUTHENTICATED, String.valueOf(OsmOAuth.isAuthorized())) .add(EventParam.IS_ONLINE, String.valueOf(ConnectionState.isConnected()))); if (newObject) PushwooshHelper.nativeSendEditorAddObjectTag(); else PushwooshHelper.nativeSendEditorEditObjectTag(); } public void trackSubwayEvent(@NonNull String status) { trackMapLayerEvent(ParamValue.SUBWAY, status); } public void trackTrafficEvent(@NonNull String status) { trackMapLayerEvent(ParamValue.TRAFFIC, status); } private void trackMapLayerEvent(@NonNull String eventName, @NonNull String status) { ParameterBuilder builder = params().add(EventParam.NAME, eventName) .add(EventParam.STATUS, status); trackEvent(EventName.MAP_LAYERS_ACTIVATE, builder); } public void trackEditorSuccess(boolean newObject) { trackEvent(newObject ? EventName.EDITOR_SUCCESS_CREATE : EventName.EDITOR_SUCCESS_EDIT, editorMwmParams().add(EventParam.IS_AUTHENTICATED, String.valueOf(OsmOAuth.isAuthorized())) .add(EventParam.IS_ONLINE, String.valueOf(ConnectionState.isConnected()))); } public void trackEditorError(boolean newObject) { trackEvent(newObject ? EventName.EDITOR_ERROR_CREATE : EventName.EDITOR_ERROR_EDIT, editorMwmParams().add(EventParam.IS_AUTHENTICATED, String.valueOf(OsmOAuth.isAuthorized())) .add(EventParam.IS_ONLINE, String.valueOf(ConnectionState.isConnected()))); } public void trackAuthRequest(OsmOAuth.AuthType type) { trackEvent(EventName.EDITOR_AUTH_REQUEST, Statistics.params().add(Statistics.EventParam.TYPE, type.name)); } public void trackTaxiInRoutePlanning(@Nullable MapObject from, @Nullable MapObject to, @Nullable Location location, @NonNull String providerName, boolean isAppInstalled) { Statistics.ParameterBuilder params = Statistics.params(); params.add(Statistics.EventParam.PROVIDER, providerName); params.add(Statistics.EventParam.FROM_LAT, from != null ? String.valueOf(from.getLat()) : "N/A") .add(Statistics.EventParam.FROM_LON, from != null ? String.valueOf(from.getLon()) : "N/A"); params.add(Statistics.EventParam.TO_LAT, to != null ? String.valueOf(to.getLat()) : "N/A") .add(Statistics.EventParam.TO_LON, to != null ? String.valueOf(to.getLon()) : "N/A"); String event = isAppInstalled ? Statistics.EventName.ROUTING_TAXI_ORDER : Statistics.EventName.ROUTING_TAXI_INSTALL; trackEvent(event, location, params.get()); } public void trackTaxiEvent(@NonNull String eventName, @NonNull String providerName) { Statistics.ParameterBuilder params = Statistics.params(); params.add(Statistics.EventParam.PROVIDER, providerName); trackEvent(eventName, params); } public void trackTaxiError(@NonNull TaxiInfoError error) { Statistics.ParameterBuilder params = Statistics.params(); params.add(Statistics.EventParam.PROVIDER, error.getProviderName()); params.add(ERROR_CODE, error.getCode().name()); trackEvent(EventName.ROUTING_TAXI_ROUTE_BUILT, params); } public void trackNoTaxiProvidersError() { Statistics.ParameterBuilder params = Statistics.params(); params.add(ERROR_CODE, TaxiManager.ErrorCode.NoProviders.name()); trackEvent(EventName.ROUTING_TAXI_ROUTE_BUILT, params); } public void trackRestaurantEvent(@NonNull String eventName, @NonNull Sponsored restaurant, @NonNull MapObject mapObject) { String provider = restaurant.getType() == Sponsored.TYPE_OPENTABLE ? OPENTABLE : "Unknown restaurant"; Statistics.INSTANCE.trackEvent(eventName, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params().add(PROVIDER, provider) .add(RESTAURANT, restaurant.getId()) .add(RESTAURANT_LAT, mapObject.getLat()) .add(RESTAURANT_LON, mapObject.getLon()).get()); } public void trackHotelEvent(@NonNull String eventName, @NonNull Sponsored hotel, @NonNull MapObject mapObject) { String provider = hotel.getType() == Sponsored.TYPE_BOOKING ? BOOKING_COM : "Unknown hotel"; Statistics.INSTANCE.trackEvent(eventName, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params().add(PROVIDER, provider) .add(HOTEL, hotel.getId()) .add(HOTEL_LAT, mapObject.getLat()) .add(HOTEL_LON, mapObject.getLon()).get()); } public void trackBookHotelEvent(@NonNull Sponsored hotel, @NonNull MapObject mapObject) { trackHotelEvent(PP_SPONSORED_BOOK, hotel, mapObject); } public void trackBookmarksTabEvent(@NonNull String param) { ParameterBuilder params = params().add(EventParam.VALUE, param); trackEvent(EventName.BM_TAB_CLICK, params); } public void trackOpenCatalogScreen() { trackEvent(EventName.BM_DOWNLOADED_CATALOGUE_OPEN, Collections.emptyMap()); } public void trackDownloadCatalogError(@NonNull String value) { ParameterBuilder params = params().add(EventParam.ERROR, value); trackEvent(EventName.BM_DOWNLOADED_CATALOGUE_ERROR, params); } public void trackPPBanner(@NonNull String eventName, @NonNull MwmNativeAd ad, @BannerState int state) { trackEvent(eventName, Statistics.params() .add(BANNER, ad.getBannerId()) .add(PROVIDER, ad.getProvider()) .add(STATE, String.valueOf(state))); if (!eventName.equals(PP_BANNER_SHOW) || state == PP_BANNER_STATE_PREVIEW) MyTracker.trackEvent(eventName); } public void trackPPBannerError(@NonNull String bannerId, @NonNull String provider, @Nullable NativeAdError error, int state) { boolean isAdBlank = error != null && error.getCode() == AdError.NO_FILL_ERROR_CODE; String eventName = isAdBlank ? PP_BANNER_BLANK : PP_BANNER_ERROR; Statistics.ParameterBuilder builder = Statistics.params(); builder.add(BANNER, !TextUtils.isEmpty(bannerId) ? bannerId : "N/A") .add(ERROR_CODE, error != null ? String.valueOf(error.getCode()) : "N/A") .add(ERROR_MESSAGE, error != null ? error.getMessage() : "N/A") .add(PROVIDER, provider) .add(STATE, String.valueOf(state)); trackEvent(eventName, builder.get()); MyTracker.trackEvent(eventName); } public void trackBookingSearchEvent(@NonNull MapObject mapObject) { trackEvent(PP_SPONSORED_BOOK, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params() .add(PROVIDER, SEARCH_BOOKING_COM) .add(HOTEL, "") .add(HOTEL_LAT, mapObject.getLat()) .add(HOTEL_LON, mapObject.getLon()) .get()); } public void trackDownloaderDialogEvent(@NonNull String eventName, long size) { trackEvent(eventName, Statistics.params() .add(MAP_DATA_SIZE, size)); } public void trackDownloaderDialogError(long size, @NonNull String error) { trackEvent(DOWNLOADER_DIALOG_ERROR, Statistics.params() .add(MAP_DATA_SIZE, size) .add(TYPE, error)); } public void trackPPOwnershipButtonClick(@NonNull MapObject mapObject) { trackEvent(PP_OWNERSHIP_BUTTON_CLICK, LocationHelper.INSTANCE.getLastKnownLocation(), params() .add(MWM_NAME, mapObject.getFeatureId().getMwmName()) .add(MWM_VERSION, mapObject.getFeatureId().getMwmVersion()) .add(FEATURE_ID, mapObject.getFeatureId().getFeatureIndex()) .get()); } public void trackColdStartupInfo() { BatteryState.State state = BatteryState.getState(); final String charging; switch (state.getChargingStatus()) { case CHARGING_STATUS_UNKNOWN: charging = "unknown"; break; case CHARGING_STATUS_PLUGGED: charging = ParamValue.ON; break; case CHARGING_STATUS_UNPLUGGED: charging = ParamValue.OFF; break; default: charging = "unknown"; break; } final String network = getConnectionState(); trackEvent(APPLICATION_COLD_STARTUP_INFO, params() .add(BATTERY, state.getLevel()) .add(CHARGING, charging) .add(NETWORK, network) .get()); } @NonNull private String getConnectionState() { final String network; if (ConnectionState.isWifiConnected()) { network = "wifi"; } else if (ConnectionState.isMobileConnected()) { if (ConnectionState.isInRoaming()) network = "roaming"; else network = "mobile"; } else { network = "off"; } return network; } public void trackSponsoredOpenEvent(@NonNull Sponsored sponsored) { Statistics.ParameterBuilder builder = Statistics.params(); builder.add(NETWORK, getConnectionState()) .add(PROVIDER, convertToSponsor(sponsored)); trackEvent(PP_SPONSORED_OPEN, builder.get()); } public void trackGalleryShown(@NonNull GalleryType type, @NonNull GalleryState state, @NonNull GalleryPlacement placement) { trackEvent(PP_SPONSORED_SHOWN, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT, placement.toString()) .add(STATE, state.toString())); if (state == GalleryState.ONLINE) MyTracker.trackEvent(PP_SPONSORED_SHOWN + "_" + type.getProvider()); } public void trackGalleryError(@NonNull GalleryType type, @NonNull GalleryPlacement placement, @Nullable String code) { trackEvent(PP_SPONSORED_ERROR, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT, placement.toString()) .add(ERROR, code).get()); } public void trackGalleryProductItemSelected(@NonNull GalleryType type, @NonNull GalleryPlacement placement, int position, @NonNull Destination destination) { trackEvent(PP_SPONSOR_ITEM_SELECTED, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT, placement.toString()) .add(ITEM, position) .add(DESTINATION, destination.toString())); } public void trackGalleryEvent(@NonNull String eventName, @NonNull GalleryType type, @NonNull GalleryPlacement placement) { trackEvent(eventName, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT,placement.toString()) .get()); } public void trackSearchPromoCategory(@NonNull String eventName, @NonNull String provider) { trackEvent(eventName, Statistics.params().add(PROVIDER, provider).get()); MyTracker.trackEvent(eventName + "_" + provider); } public void trackSettingsToggle(boolean value) { trackEvent(EventName.SETTINGS_TRACKING_TOGGLE, Statistics.params() .add(TYPE, ParamValue.CRASH_REPORTS) .add(VALUE, value ? ParamValue.ON : ParamValue.OFF).get()); } public void trackSettingsDetails() { trackEvent(EventName.SETTINGS_TRACKING_DETAILS, Statistics.params().add(TYPE, ParamValue.PERSONAL_ADS).get()); } @NonNull private static String convertToSponsor(@NonNull Sponsored sponsored) { if (sponsored.getType() == Sponsored.TYPE_PARTNER) return sponsored.getPartnerName(); return convertToSponsor(sponsored.getType()); } @NonNull private static String convertToSponsor(@Sponsored.SponsoredType int type) { switch (type) { case Sponsored.TYPE_BOOKING: return BOOKING_COM; case Sponsored.TYPE_OPENTABLE: return OPENTABLE; case Sponsored.TYPE_HOLIDAY: return HOLIDAY; case Sponsored.TYPE_NONE: return "N/A"; default: throw new AssertionError("Unknown sponsor type: " + type); } } public void trackRoutingPoint(@NonNull String eventName, @RoutePointInfo.RouteMarkType int type, boolean isPlanning, boolean isNavigating, boolean isMyPosition, boolean isApi) { final String mode; if (isNavigating) mode = "onroute"; else if (isPlanning) mode = "planning"; else mode = null; final String method; if (isPlanning) method = "planning_pp"; else if (isApi) method = "api"; else method = "outside_pp"; ParameterBuilder builder = params() .add(TYPE, convertRoutePointType(type)) .add(VALUE, isMyPosition ? "gps" : "point") .add(METHOD, method); if (mode != null) builder.add(MODE, mode); trackEvent(eventName, builder.get()); } public void trackRoutingEvent(@NonNull String eventName, boolean isPlanning) { trackEvent(eventName, params() .add(MODE, isPlanning ? "planning" : "onroute") .get()); } public void trackRoutingStart(@Framework.RouterType int type, boolean trafficEnabled) { trackEvent(ROUTING_ROUTE_START, prepareRouteParams(type, trafficEnabled)); } public void trackRoutingFinish(boolean interrupted, @Framework.RouterType int type, boolean trafficEnabled) { ParameterBuilder params = prepareRouteParams(type, trafficEnabled); trackEvent(ROUTING_ROUTE_FINISH, params.add(INTERRUPTED, interrupted ? 1 : 0)); } @NonNull private static ParameterBuilder prepareRouteParams(@Framework.RouterType int type, boolean trafficEnabled) { return params().add(MODE, toRouterType(type)).add(TRAFFIC, trafficEnabled ? 1 : 0); } @NonNull private static String toRouterType(@Framework.RouterType int type) { switch (type) { case Framework.ROUTER_TYPE_VEHICLE: return VEHICLE; case Framework.ROUTER_TYPE_PEDESTRIAN: return PEDESTRIAN; case Framework.ROUTER_TYPE_BICYCLE: return BICYCLE; case Framework.ROUTER_TYPE_TAXI: return TAXI; case Framework.ROUTER_TYPE_TRANSIT: return TRANSIT; default: throw new AssertionError("Unsupported router type: " + type); } } public void trackRoutingTooltipEvent(@RoutePointInfo.RouteMarkType int type, boolean isPlanning) { trackEvent(ROUTING_PLAN_TOOLTIP_CLICK, params() .add(TYPE, convertRoutePointType(type)) .add(MODE, isPlanning ? "planning" : "onroute") .get()); } public void trackSponsoredObjectEvent(@NonNull String eventName, @NonNull Sponsored sponsoredObj, @NonNull MapObject mapObject) { // Here we code category by means of rating. Statistics.INSTANCE.trackEvent(eventName, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params().add(PROVIDER, convertToSponsor(sponsoredObj)) .add(CATEGORY, sponsoredObj.getRating()) .add(OBJECT_LAT, mapObject.getLat()) .add(OBJECT_LON, mapObject.getLon()).get()); } @NonNull private static String convertRoutePointType(@RoutePointInfo.RouteMarkType int type) { switch (type) { case RoutePointInfo.ROUTE_MARK_FINISH: return "finish"; case RoutePointInfo.ROUTE_MARK_INTERMEDIATE: return "inter"; case RoutePointInfo.ROUTE_MARK_START: return "start"; default: throw new AssertionError("Wrong parameter 'type'"); } } public void trackUGCStart(boolean isEdit, boolean isPPPreview, boolean isFromNotification) { trackEvent(UGC_REVIEW_START, params() .add(EventParam.IS_AUTHENTICATED, Framework.nativeIsUserAuthenticated()) .add(EventParam.IS_ONLINE, ConnectionState.isConnected()) .add(EventParam.MODE, isEdit ? ParamValue.EDIT : ParamValue.ADD) .add(EventParam.FROM, isPPPreview ? ParamValue.PLACEPAGE_PREVIEW : isFromNotification ? ParamValue.NOTIFICATION : ParamValue.PLACEPAGE) .get()); } public void trackUGCAuthDialogShown() { trackEvent(UGC_AUTH_SHOWN, params().add(EventParam.FROM, ParamValue.AFTER_SAVE).get()); } public void trackUGCExternalAuthSucceed(@NonNull String provider) { trackEvent(UGC_AUTH_EXTERNAL_REQUEST_SUCCESS, params().add(EventParam.PROVIDER, provider)); } public void trackUGCAuthFailed(@Framework.AuthTokenType int type, @Nullable String error) { trackEvent(UGC_AUTH_ERROR, params() .add(EventParam.PROVIDER, getAuthProvider(type)) .add(EventParam.ERROR, error) .get()); } @NonNull public static String getAuthProvider(@Framework.AuthTokenType int type) { switch (type) { case Framework.SOCIAL_TOKEN_FACEBOOK: return FACEBOOK; case Framework.SOCIAL_TOKEN_GOOGLE: return GOOGLE; case Framework.SOCIAL_TOKEN_PHONE: return PHONE; case Framework.TOKEN_MAPSME: return MAPSME; case Framework.SOCIAL_TOKEN_INVALID: return UNKNOWN; default: throw new AssertionError("Unknown social token type: " + type); } } @NonNull public static String getSynchronizationType(@BookmarkManager.SynchronizationType int type) { return type == 0 ? BACKUP : RESTORE; } public void trackFilterEvent(@NonNull String event, @NonNull String category) { trackEvent(event, params() .add(EventParam.CATEGORY, category) .get()); } public void trackFilterClick(@NonNull String category, @NonNull Pair<String, String> params) { trackEvent(SEARCH_FILTER_CLICK, params() .add(EventParam.CATEGORY, category) .add(params.first, params.second) .get()); } public void trackBmSyncProposalShown(boolean hasAuth) { trackEvent(BM_SYNC_PROPOSAL_SHOWN, params().add(HAS_AUTH, hasAuth ? 1 : 0).get()); } public void trackBmSyncProposalApproved(boolean hasAuth) { trackEvent(BM_SYNC_PROPOSAL_APPROVED, params() .add(HAS_AUTH, hasAuth ? 1 : 0) .add(NETWORK, getConnectionState()) .get()); } public void trackBmRestoreProposalClick() { trackEvent(BM_RESTORE_PROPOSAL_CLICK, params() .add(NETWORK, getConnectionState()) .get()); } public void trackBmSyncProposalError(@Framework.AuthTokenType int type, @Nullable String message) { trackEvent(BM_SYNC_PROPOSAL_ERROR, params() .add(PROVIDER, getAuthProvider(type)) .add(ERROR, message) .get()); } public void trackBmSettingsToggle(boolean checked) { trackEvent(BM_SYNC_PROPOSAL_TOGGLE, params() .add(STATE, checked ? 1 : 0) .get()); } public void trackBmSynchronizationFinish(@BookmarkManager.SynchronizationType int type, @BookmarkManager.SynchronizationResult int result, @NonNull String errorString) { if (result == BookmarkManager.CLOUD_SUCCESS) { if (type == BookmarkManager.CLOUD_BACKUP) trackEvent(BM_SYNC_SUCCESS); else trackEvent(BM_RESTORE_PROPOSAL_SUCCESS); return; } trackEvent(type == BookmarkManager.CLOUD_BACKUP ? BM_SYNC_ERROR : BM_RESTORE_PROPOSAL_ERROR, params().add(TYPE, getTypeForErrorSyncResult(result)).add(ERROR, errorString)); } public void trackBmRestoringRequestResult(@BookmarkManager.RestoringRequestResult int result) { if (result == BookmarkManager.CLOUD_BACKUP_EXISTS) return; trackEvent(BM_RESTORE_PROPOSAL_ERROR, params() .add(TYPE, getTypeForRequestRestoringError(result))); } @NonNull private static String getTypeForErrorSyncResult(@BookmarkManager.SynchronizationResult int result) { switch (result) { case BookmarkManager.CLOUD_AUTH_ERROR: return ParamValue.AUTH; case BookmarkManager.CLOUD_NETWORK_ERROR: return ParamValue.NETWORK; case BookmarkManager.CLOUD_DISK_ERROR: return ParamValue.DISK; case BookmarkManager.CLOUD_USER_INTERRUPTED: return ParamValue.USER_INTERRUPTED; case BookmarkManager.CLOUD_INVALID_CALL: return ParamValue.INVALID_CALL; case BookmarkManager.CLOUD_SUCCESS: throw new AssertionError("It's not a error result!"); default: throw new AssertionError("Unsupported error type: " + result); } } @NonNull private static String getTypeForRequestRestoringError(@BookmarkManager.RestoringRequestResult int result) { switch (result) { case BookmarkManager.CLOUD_BACKUP_EXISTS: throw new AssertionError("It's not a error result!"); case BookmarkManager.CLOUD_NOT_ENOUGH_DISK_SPACE: return DISK_NO_SPACE; case BookmarkManager.CLOUD_NO_BACKUP: return NO_BACKUP; default: throw new AssertionError("Unsupported restoring request result: " + result); } } public void trackToolbarClick(@NonNull MainMenu.Item button) { trackEvent(TOOLBAR_CLICK, getToolbarParams(button)); } public void trackToolbarMenu(@NonNull MainMenu.Item button) { trackEvent(TOOLBAR_MENU_CLICK, getToolbarParams(button)); } public void trackDownloadBookmarkDialog(@NonNull String button) { trackEvent(BM_GUIDES_DOWNLOADDIALOGUE_CLICK, params().add(ACTION, button)); } @NonNull private static ParameterBuilder getToolbarParams(@NonNull MainMenu.Item button) { return params().add(BUTTON, button.toStatisticValue()); } public void trackPPBannerClose(@BannerState int state, boolean isCross) { trackEvent(PP_BANNER_CLOSE, params().add(BANNER, state) .add(BUTTON, isCross ? 0 : 1)); } public void trackPurchasePreviewShow(@NonNull String purchaseId, @NonNull String vendor, @NonNull String productId) { trackEvent(INAPP_PURCHASE_PREVIEW_SHOW, params().add(VENDOR, vendor) .add(PRODUCT, productId) .add(PURCHASE, purchaseId)); } public void trackPurchaseEvent(@NonNull String event, @NonNull String purchaseId) { trackEvent(event, params().add(PURCHASE, purchaseId)); } public void trackPurchasePreviewSelect(@NonNull String purchaseId, @NonNull String productId) { trackEvent(INAPP_PURCHASE_PREVIEW_SELECT, params().add(PRODUCT, productId) .add(PURCHASE, productId)); } public void trackPurchaseStoreError(@NonNull String purchaseId, @BillingClient.BillingResponse int error) { trackEvent(INAPP_PURCHASE_STORE_ERROR, params().add(ERROR, "Billing error: " + error) .add(PURCHASE, purchaseId)); } public void trackPurchaseValidationError(@NonNull String purchaseId, @NonNull ValidationStatus status) { if (status == ValidationStatus.VERIFIED) return; int errorCode; switch (status) { case NOT_VERIFIED: errorCode = 0; break; case AUTH_ERROR: errorCode = 1; break; case SERVER_ERROR: errorCode = 2; break; default: throw new UnsupportedOperationException("Unsupported status: " + status); } trackEvent(INAPP_PURCHASE_VALIDATION_ERROR, params().add(ERROR_CODE, errorCode) .add(PURCHASE, purchaseId)); } public void trackPowerManagmentSchemeChanged(@PowerManagment.SchemeType int scheme) { String statisticValue = ""; switch (scheme) { case PowerManagment.NONE: case PowerManagment.MEDIUM: throw new AssertionError("Incorrect scheme type"); case PowerManagment.NORMAL: statisticValue = "never"; break; case PowerManagment.AUTO: statisticValue = "auto"; break; case PowerManagment.HIGH: statisticValue = "max"; break; } trackEvent(EventName.Settings.ENERGY_SAVING, params().add(EventParam.VALUE, statisticValue)); } public void trackPurchaseProductDelivered(@NonNull String purchaseId, @NonNull String vendor) { trackEvent(INAPP_PURCHASE_PRODUCT_DELIVERED, params().add(VENDOR, vendor) .add(PURCHASE, purchaseId)); } public void trackTipsEvent(@NonNull String eventName, int type) { Statistics.INSTANCE.trackEvent(eventName, params().add(TYPE, type)); } public void trackTipsClose(int type) { Statistics.INSTANCE.trackEvent(TIPS_TRICKS_CLOSE, params().add(TYPE, type) .add(OPTION, OFFSCREEEN)); } public static ParameterBuilder params() { return new ParameterBuilder(); } public static ParameterBuilder editorMwmParams() { return params().add(MWM_NAME, Editor.nativeGetMwmName()) .add(MWM_VERSION, Editor.nativeGetMwmVersion()); } public static class ParameterBuilder { private final Map<String, String> mParams = new HashMap<>(); @NonNull public static ParameterBuilder from(@NonNull String key, @NonNull Analytics analytics) { return new ParameterBuilder().add(key, analytics.getName()); } public ParameterBuilder add(String key, String value) { mParams.put(key, value); return this; } public ParameterBuilder add(String key, boolean value) { mParams.put(key, String.valueOf(value)); return this; } public ParameterBuilder add(String key, int value) { mParams.put(key, String.valueOf(value)); return this; } public ParameterBuilder add(String key, float value) { mParams.put(key, String.valueOf(value)); return this; } public ParameterBuilder add(String key, double value) { mParams.put(key, String.valueOf(value)); return this; } public Map<String, String> get() { return mParams; } } public static String getPointType(MapObject point) { return MapObject.isOfType(MapObject.MY_POSITION, point) ? Statistics.EventParam.MY_POSITION : Statistics.EventParam.POINT; } public enum NetworkErrorType { NO_NETWORK, AUTH_FAILED; } }
android/src/com/mapswithme/util/statistics/Statistics.java
package com.mapswithme.util.statistics; import android.app.Activity; import android.content.Context; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Pair; import com.android.billingclient.api.BillingClient; import com.facebook.ads.AdError; import com.facebook.appevents.AppEventsLogger; import com.mapswithme.maps.BuildConfig; import com.mapswithme.maps.Framework; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.PrivateVariables; import com.mapswithme.maps.ads.MwmNativeAd; import com.mapswithme.maps.ads.NativeAdError; import com.mapswithme.maps.analytics.ExternalLibrariesMediator; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.maps.bookmarks.data.BookmarkCategory; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.downloader.MapManager; import com.mapswithme.maps.editor.Editor; import com.mapswithme.maps.editor.OsmOAuth; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.maps.purchase.ValidationStatus; import com.mapswithme.maps.routing.RoutePointInfo; import com.mapswithme.maps.routing.RoutingOptions; import com.mapswithme.maps.settings.RoadType; import com.mapswithme.maps.taxi.TaxiInfoError; import com.mapswithme.maps.taxi.TaxiManager; import com.mapswithme.maps.widget.menu.MainMenu; import com.mapswithme.maps.widget.placepage.Sponsored; import com.mapswithme.util.BatteryState; import com.mapswithme.util.Config; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.Counters; import com.mapswithme.util.PowerManagment; import com.mapswithme.util.SharedPropertiesUtils; import com.my.tracker.MyTracker; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.mapswithme.util.BatteryState.CHARGING_STATUS_PLUGGED; import static com.mapswithme.util.BatteryState.CHARGING_STATUS_UNKNOWN; import static com.mapswithme.util.BatteryState.CHARGING_STATUS_UNPLUGGED; import static com.mapswithme.util.statistics.Statistics.EventName.APPLICATION_COLD_STARTUP_INFO; import static com.mapswithme.util.statistics.Statistics.EventName.BM_GUIDES_DOWNLOADDIALOGUE_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.BM_RESTORE_PROPOSAL_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.BM_RESTORE_PROPOSAL_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.BM_RESTORE_PROPOSAL_SUCCESS; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_APPROVED; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_SHOWN; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_PROPOSAL_TOGGLE; import static com.mapswithme.util.statistics.Statistics.EventName.BM_SYNC_SUCCESS; import static com.mapswithme.util.statistics.Statistics.EventName.DOWNLOADER_DIALOG_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_PREVIEW_SELECT; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_PREVIEW_SHOW; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_PRODUCT_DELIVERED; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_STORE_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.INAPP_PURCHASE_VALIDATION_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_BLANK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_CLOSE; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_SHOW; import static com.mapswithme.util.statistics.Statistics.EventName.PP_OWNERSHIP_BUTTON_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_BOOK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_OPEN; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSORED_SHOWN; import static com.mapswithme.util.statistics.Statistics.EventName.PP_SPONSOR_ITEM_SELECTED; import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_PLAN_TOOLTIP_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_ROUTE_FINISH; import static com.mapswithme.util.statistics.Statistics.EventName.ROUTING_ROUTE_START; import static com.mapswithme.util.statistics.Statistics.EventName.SEARCH_FILTER_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.TIPS_TRICKS_CLOSE; import static com.mapswithme.util.statistics.Statistics.EventName.TOOLBAR_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.TOOLBAR_MENU_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_AUTH_ERROR; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_AUTH_EXTERNAL_REQUEST_SUCCESS; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_AUTH_SHOWN; import static com.mapswithme.util.statistics.Statistics.EventName.UGC_REVIEW_START; import static com.mapswithme.util.statistics.Statistics.EventParam.ACTION; import static com.mapswithme.util.statistics.Statistics.EventParam.BANNER; import static com.mapswithme.util.statistics.Statistics.EventParam.BATTERY; import static com.mapswithme.util.statistics.Statistics.EventParam.BUTTON; import static com.mapswithme.util.statistics.Statistics.EventParam.CATEGORY; import static com.mapswithme.util.statistics.Statistics.EventParam.CHARGING; import static com.mapswithme.util.statistics.Statistics.EventParam.DESTINATION; import static com.mapswithme.util.statistics.Statistics.EventParam.ERROR; import static com.mapswithme.util.statistics.Statistics.EventParam.ERROR_CODE; import static com.mapswithme.util.statistics.Statistics.EventParam.ERROR_MESSAGE; import static com.mapswithme.util.statistics.Statistics.EventParam.FEATURE_ID; import static com.mapswithme.util.statistics.Statistics.EventParam.HAS_AUTH; import static com.mapswithme.util.statistics.Statistics.EventParam.HOTEL; import static com.mapswithme.util.statistics.Statistics.EventParam.HOTEL_LAT; import static com.mapswithme.util.statistics.Statistics.EventParam.HOTEL_LON; import static com.mapswithme.util.statistics.Statistics.EventParam.INTERRUPTED; import static com.mapswithme.util.statistics.Statistics.EventParam.ITEM; import static com.mapswithme.util.statistics.Statistics.EventParam.MAP_DATA_SIZE; import static com.mapswithme.util.statistics.Statistics.EventParam.METHOD; import static com.mapswithme.util.statistics.Statistics.EventParam.MODE; import static com.mapswithme.util.statistics.Statistics.EventParam.MWM_NAME; import static com.mapswithme.util.statistics.Statistics.EventParam.MWM_VERSION; import static com.mapswithme.util.statistics.Statistics.EventParam.NETWORK; import static com.mapswithme.util.statistics.Statistics.EventParam.OBJECT_LAT; import static com.mapswithme.util.statistics.Statistics.EventParam.OBJECT_LON; import static com.mapswithme.util.statistics.Statistics.EventParam.OPTION; import static com.mapswithme.util.statistics.Statistics.EventParam.PLACEMENT; import static com.mapswithme.util.statistics.Statistics.EventParam.PRODUCT; import static com.mapswithme.util.statistics.Statistics.EventParam.PROVIDER; import static com.mapswithme.util.statistics.Statistics.EventParam.PURCHASE; import static com.mapswithme.util.statistics.Statistics.EventParam.RESTAURANT; import static com.mapswithme.util.statistics.Statistics.EventParam.RESTAURANT_LAT; import static com.mapswithme.util.statistics.Statistics.EventParam.RESTAURANT_LON; import static com.mapswithme.util.statistics.Statistics.EventParam.STATE; import static com.mapswithme.util.statistics.Statistics.EventParam.TYPE; import static com.mapswithme.util.statistics.Statistics.EventParam.VALUE; import static com.mapswithme.util.statistics.Statistics.EventParam.VENDOR; import static com.mapswithme.util.statistics.Statistics.ParamValue.BACKUP; import static com.mapswithme.util.statistics.Statistics.ParamValue.BICYCLE; import static com.mapswithme.util.statistics.Statistics.ParamValue.BOOKING_COM; import static com.mapswithme.util.statistics.Statistics.ParamValue.DISK_NO_SPACE; import static com.mapswithme.util.statistics.Statistics.ParamValue.FACEBOOK; import static com.mapswithme.util.statistics.Statistics.ParamValue.GOOGLE; import static com.mapswithme.util.statistics.Statistics.ParamValue.HOLIDAY; import static com.mapswithme.util.statistics.Statistics.ParamValue.MAPSME; import static com.mapswithme.util.statistics.Statistics.ParamValue.NO_BACKUP; import static com.mapswithme.util.statistics.Statistics.ParamValue.OFFSCREEEN; import static com.mapswithme.util.statistics.Statistics.ParamValue.OPENTABLE; import static com.mapswithme.util.statistics.Statistics.ParamValue.PEDESTRIAN; import static com.mapswithme.util.statistics.Statistics.ParamValue.PHONE; import static com.mapswithme.util.statistics.Statistics.ParamValue.RESTORE; import static com.mapswithme.util.statistics.Statistics.ParamValue.SEARCH_BOOKING_COM; import static com.mapswithme.util.statistics.Statistics.ParamValue.TAXI; import static com.mapswithme.util.statistics.Statistics.ParamValue.TRAFFIC; import static com.mapswithme.util.statistics.Statistics.ParamValue.TRANSIT; import static com.mapswithme.util.statistics.Statistics.ParamValue.UNKNOWN; import static com.mapswithme.util.statistics.Statistics.ParamValue.VEHICLE; public enum Statistics { INSTANCE; public void trackCategoryDescChanged() { trackEditSettingsScreenOptionClick(ParamValue.ADD_DESC); } public void trackSharingOptionsClick(@NonNull String value) { ParameterBuilder builder = new ParameterBuilder().add(OPTION, value); trackEvent(EventName.BM_SHARING_OPTIONS_CLICK, builder); } public void trackSharingOptionsError(@NonNull String error, @NonNull NetworkErrorType value) { trackSharingOptionsError(error, value.ordinal()); } public void trackSharingOptionsError(@NonNull String error, int value) { ParameterBuilder builder = new ParameterBuilder().add(EventParam.ERROR, value); trackEvent(error, builder); } public void trackSharingOptionsUploadSuccess(@NonNull BookmarkCategory category) { ParameterBuilder builder = new ParameterBuilder().add(EventParam.TRACKS, category.getTracksCount()) .add(EventParam.POINTS, category.getBookmarksCount()); trackEvent(EventName.BM_SHARING_OPTIONS_UPLOAD_SUCCESS, builder); } public void trackBookmarkListSettingsClick(@NonNull Analytics analytics) { ParameterBuilder builder = ParameterBuilder.from(OPTION, analytics); trackEvent(EventName.BM_BOOKMARKS_LIST_SETTINGS_CLICK, builder); } private void trackEditSettingsScreenOptionClick(@NonNull String value) { ParameterBuilder builder = new ParameterBuilder().add(OPTION, value); trackEvent(EventName.BM_EDIT_SETTINGS_CLICK, builder); } public void trackEditSettingsCancel() { trackEvent(EventName.BM_EDIT_SETTINGS_CANCEL); } public void trackEditSettingsConfirm() { trackEvent(EventName.BM_EDIT_SETTINGS_CONFIRM); } public void trackEditSettingsSharingOptionsClick() { trackEditSettingsScreenOptionClick(Statistics.ParamValue.SHARING_OPTIONS); } public void trackBookmarkListSharingOptions() { trackEvent(Statistics.EventName.BM_BOOKMARKS_LIST_ITEM_SETTINGS, new Statistics.ParameterBuilder().add(OPTION, Statistics.ParamValue.SHARING_OPTIONS)); } public void trackSettingsDrivingOptionsChangeEvent() { boolean hasToll = RoutingOptions.hasOption(RoadType.Toll); boolean hasFerry = RoutingOptions.hasOption(RoadType.Ferry); boolean hasMoto = RoutingOptions.hasOption(RoadType.Motorway); boolean hasDirty = RoutingOptions.hasOption(RoadType.Dirty); ParameterBuilder builder = new ParameterBuilder() ; ParameterBuilder parameterBuilder = builder.add(EventParam.TOLL, hasToll ? 1 : 0) .add(EventParam.FERRY, hasFerry ? 1 : 0) .add(EventParam.MOTORWAY, hasMoto ? 1 : 0) .add(EventParam.UNPAVED, hasDirty ? 1 : 0); parameterBuilder.add(EventParam.FROM, EventParam.SETTINGS); trackEvent(EventName.SETTINGS_DRIVING_OPTIONS_CHANGE, parameterBuilder); } @Retention(RetentionPolicy.SOURCE) @IntDef({PP_BANNER_STATE_PREVIEW, PP_BANNER_STATE_DETAILS}) public @interface BannerState {} public static final int PP_BANNER_STATE_PREVIEW = 0; public static final int PP_BANNER_STATE_DETAILS = 1; // Statistics counters private int mBookmarksCreated; private int mSharedTimes; public static class EventName { // Downloader public static final String DOWNLOADER_MIGRATION_DIALOG_SEEN = "Downloader_Migration_dialogue"; public static final String DOWNLOADER_MIGRATION_STARTED = "Downloader_Migration_started"; public static final String DOWNLOADER_MIGRATION_COMPLETE = "Downloader_Migration_completed"; public static final String DOWNLOADER_MIGRATION_ERROR = "Downloader_Migration_error"; public static final String DOWNLOADER_ERROR = "Downloader_Map_error"; public static final String DOWNLOADER_ACTION = "Downloader_Map_action"; public static final String DOWNLOADER_CANCEL = "Downloader_Cancel_downloading"; public static final String DOWNLOADER_DIALOG_SHOW = "Downloader_OnStartScreen_show"; public static final String DOWNLOADER_DIALOG_MANUAL_DOWNLOAD = "Downloader_OnStartScreen_manual_download"; public static final String DOWNLOADER_DIALOG_DOWNLOAD = "Downloader_OnStartScreen_auto_download"; public static final String DOWNLOADER_DIALOG_LATER = "Downloader_OnStartScreen_select_later"; public static final String DOWNLOADER_DIALOG_HIDE = "Downloader_OnStartScreen_select_hide"; public static final String DOWNLOADER_DIALOG_CANCEL = "Downloader_OnStartScreen_cancel_download"; public static final String SETTINGS_TRACKING_DETAILS = "Settings_Tracking_details"; public static final String SETTINGS_TRACKING_TOGGLE = "Settings_Tracking_toggle"; public static final String PLACEPAGE_DESCRIPTION_MORE = "Placepage_Description_more"; public static final String PLACEPAGE_DESCRIPTION_OUTBOUND_CLICK = "Placepage_Description_Outbound_click"; public static final String SETTINGS_SPEED_CAMS = "Settings. Speed_cameras"; static final String DOWNLOADER_DIALOG_ERROR = "Downloader_OnStartScreen_error"; // bookmarks private static final String BM_SHARING_OPTIONS_UPLOAD_SUCCESS = "Bookmarks_SharingOptions_upload_success"; public static final String BM_SHARING_OPTIONS_UPLOAD_ERROR = "Bookmarks_SharingOptions_upload_error"; public static final String BM_SHARING_OPTIONS_ERROR = "Bookmarks_SharingOptions_error"; public static final String BM_SHARING_OPTIONS_CLICK = "Bookmarks_SharingOptions_click"; public static final String BM_EDIT_SETTINGS_CLICK = "Bookmarks_Bookmark_Settings_click"; public static final String BM_EDIT_SETTINGS_CANCEL = "Bookmarks_Bookmark_Settings_cancel"; public static final String BM_EDIT_SETTINGS_CONFIRM = "Bookmarks_Bookmark_Settings_confirm"; public static final String BM_BOOKMARKS_LIST_SETTINGS_CLICK = "Bookmarks_BookmarksList_settings_click"; public static final String BM_BOOKMARKS_LIST_ITEM_SETTINGS = "Bookmarks_BookmarksListItem_settings"; public static final String BM_GROUP_CREATED = "Bookmark. Group created"; public static final String BM_GROUP_CHANGED = "Bookmark. Group changed"; public static final String BM_COLOR_CHANGED = "Bookmark. Color changed"; public static final String BM_CREATED = "Bookmark. Bookmark created"; public static final String BM_SYNC_PROPOSAL_SHOWN = "Bookmarks_SyncProposal_shown"; public static final String BM_SYNC_PROPOSAL_APPROVED = "Bookmarks_SyncProposal_approved"; public static final String BM_SYNC_PROPOSAL_ERROR = "Bookmarks_SyncProposal_error"; public static final String BM_SYNC_PROPOSAL_ENABLED = "Bookmarks_SyncProposal_enabled"; public static final String BM_SYNC_PROPOSAL_TOGGLE = "Settings_BookmarksSync_toggle"; public static final String BM_SYNC_STARTED = "Bookmarks_sync_started"; public static final String BM_SYNC_ERROR = "Bookmarks_sync_error"; public static final String BM_SYNC_SUCCESS = "Bookmarks_sync_success"; public static final String BM_EDIT_ON_WEB_CLICK = "Bookmarks_EditOnWeb_click"; static final String BM_RESTORE_PROPOSAL_CLICK = "Bookmarks_RestoreProposal_click"; public static final String BM_RESTORE_PROPOSAL_CANCEL = "Bookmarks_RestoreProposal_cancel"; public static final String BM_RESTORE_PROPOSAL_SUCCESS = "Bookmarks_RestoreProposal_success"; static final String BM_RESTORE_PROPOSAL_ERROR = "Bookmarks_RestoreProposal_error"; static final String BM_TAB_CLICK = "Bookmarks_Tab_click"; private static final String BM_DOWNLOADED_CATALOGUE_OPEN = "Bookmarks_Downloaded_Catalogue_open"; private static final String BM_DOWNLOADED_CATALOGUE_ERROR = "Bookmarks_Downloaded_Catalogue_error"; public static final String BM_GUIDEDOWNLOADTOAST_SHOWN = "Bookmarks_GuideDownloadToast_shown"; public static final String BM_GUIDES_DOWNLOADDIALOGUE_CLICK = "Bookmarks_Guides_DownloadDialogue_click"; public static final String SETTINGS_DRIVING_OPTIONS_CHANGE = "Settings_Navigation_DrivingOptions_change"; public static final String PP_DRIVING_OPTIONS_ACTION = "Placepage_DrivingOptions_action"; // search public static final String SEARCH_CAT_CLICKED = "Search. Category clicked"; public static final String SEARCH_ITEM_CLICKED = "Search. Key clicked"; public static final String SEARCH_ON_MAP_CLICKED = "Search. View on map clicked."; public static final String SEARCH_TAB_SELECTED = "Search_Tab_selected"; public static final String SEARCH_SPONSOR_CATEGORY_SHOWN = "Search_SponsoredCategory_shown"; public static final String SEARCH_SPONSOR_CATEGORY_SELECTED = "Search_SponsoredCategory_selected"; public static final String SEARCH_FILTER_OPEN = "Search_Filter_Open"; public static final String SEARCH_FILTER_CANCEL = "Search_Filter_Cancel"; public static final String SEARCH_FILTER_RESET = "Search_Filter_Reset"; public static final String SEARCH_FILTER_APPLY = "Search_Filter_Apply"; public static final String SEARCH_FILTER_CLICK = "Search_Filter_Click"; // place page public static final String PP_DETAILS_OPEN = "Placepage_Details_open"; public static final String PP_SHARE = "PP. Share"; public static final String PP_BOOKMARK = "PP. Bookmark"; public static final String PP_ROUTE = "PP. Route"; public static final String PP_SPONSORED_DETAILS = "Placepage_Hotel_details"; public static final String PP_SPONSORED_BOOK = "Placepage_Hotel_book"; public static final String PP_SPONSORED_OPENTABLE = "Placepage_Restaurant_book"; public static final String PP_SPONSORED_OPEN = "Placepage_SponsoredGalleryPage_opened"; public static final String PP_SPONSORED_SHOWN = "Placepage_SponsoredGallery_shown"; public static final String PP_SPONSORED_ERROR = "Placepage_SponsoredGallery_error"; public static final String PP_SPONSORED_ACTION = "Placepage_SponsoredActionButton_click"; public static final String PP_SPONSOR_ITEM_SELECTED = "Placepage_SponsoredGallery_ProductItem_selected"; public static final String PP_SPONSOR_MORE_SELECTED = "Placepage_SponsoredGallery_MoreItem_selected"; public static final String PP_SPONSOR_LOGO_SELECTED = "Placepage_SponsoredGallery_LogoItem_selected"; public static final String PP_DIRECTION_ARROW = "PP. DirectionArrow"; public static final String PP_DIRECTION_ARROW_CLOSE = "PP. DirectionArrowClose"; public static final String PP_METADATA_COPY = "PP. CopyMetadata"; public static final String PP_BANNER_CLICK = "Placepage_Banner_click"; public static final String PP_BANNER_SHOW = "Placepage_Banner_show"; public static final String PP_BANNER_ERROR = "Placepage_Banner_error"; public static final String PP_BANNER_BLANK = "Placepage_Banner_blank"; public static final String PP_BANNER_CLOSE = "Placepage_Banner_close"; public static final String PP_HOTEL_GALLERY_OPEN = "PlacePage_Hotel_Gallery_open"; public static final String PP_HOTEL_REVIEWS_LAND = "PlacePage_Hotel_Reviews_land"; public static final String PP_HOTEL_DESCRIPTION_LAND = "PlacePage_Hotel_Description_land"; public static final String PP_HOTEL_FACILITIES = "PlacePage_Hotel_Facilities_open"; public static final String PP_HOTEL_SEARCH_SIMILAR = "Placepage_Hotel_search_similar"; static final String PP_OWNERSHIP_BUTTON_CLICK = "Placepage_OwnershipButton_click"; // toolbar actions public static final String TOOLBAR_MY_POSITION = "Toolbar. MyPosition"; static final String TOOLBAR_CLICK = "Toolbar_click"; static final String TOOLBAR_MENU_CLICK = "Toolbar_Menu_click"; // dialogs public static final String PLUS_DIALOG_LATER = "GPlus dialog cancelled."; public static final String RATE_DIALOG_LATER = "GPlay dialog cancelled."; public static final String FACEBOOK_INVITE_LATER = "Facebook invites dialog cancelled."; public static final String FACEBOOK_INVITE_INVITED = "Facebook invites dialog accepted."; public static final String RATE_DIALOG_RATED = "GPlay dialog. Rating set"; // misc public static final String ZOOM_IN = "Zoom. In"; public static final String ZOOM_OUT = "Zoom. Out"; public static final String PLACE_SHARED = "Place Shared"; public static final String API_CALLED = "API called"; public static final String DOWNLOAD_COUNTRY_NOTIFICATION_SHOWN = "Download country notification shown"; public static final String ACTIVE_CONNECTION = "Connection"; public static final String STATISTICS_STATUS_CHANGED = "Statistics status changed"; public static final String TTS_FAILURE_LOCATION = "TTS failure location"; public static final String UGC_NOT_AUTH_NOTIFICATION_SHOWN = "UGC_UnsentNotification_shown"; public static final String UGC_NOT_AUTH_NOTIFICATION_CLICKED = "UGC_UnsentNotification_clicked"; public static final String UGC_REVIEW_NOTIFICATION_SHOWN = "UGC_ReviewNotification_shown"; public static final String UGC_REVIEW_NOTIFICATION_CLICKED = "UGC_ReviewNotification_clicked"; // routing public static final String ROUTING_BUILD = "Routing. Build"; public static final String ROUTING_START_SUGGEST_REBUILD = "Routing. Suggest rebuild"; public static final String ROUTING_ROUTE_START = "Routing_Route_start"; public static final String ROUTING_ROUTE_FINISH = "Routing_Route_finish"; public static final String ROUTING_CANCEL = "Routing. Cancel"; public static final String ROUTING_VEHICLE_SET = "Routing. Set vehicle"; public static final String ROUTING_PEDESTRIAN_SET = "Routing. Set pedestrian"; public static final String ROUTING_BICYCLE_SET = "Routing. Set bicycle"; public static final String ROUTING_TAXI_SET = "Routing. Set taxi"; public static final String ROUTING_TRANSIT_SET = "Routing. Set transit"; public static final String ROUTING_SWAP_POINTS = "Routing. Swap points"; public static final String ROUTING_SETTINGS = "Routing. Settings"; public static final String ROUTING_TAXI_ORDER = "Routing_Taxi_order"; public static final String ROUTING_TAXI_INSTALL = "Routing_Taxi_install"; public static final String ROUTING_TAXI_SHOW = "Placepage_Taxi_show"; public static final String ROUTING_TAXI_CLICK_IN_PP = "Placepage_Taxi_click"; public static final String ROUTING_TAXI_ROUTE_BUILT = "Routing_Build_Taxi"; public static final String ROUTING_POINT_ADD = "Routing_Point_add"; public static final String ROUTING_POINT_REMOVE = "Routing_Point_remove"; public static final String ROUTING_SEARCH_CLICK = "Routing_Search_click"; public static final String ROUTING_BOOKMARKS_CLICK = "Routing_Bookmarks_click"; public static final String ROUTING_PLAN_TOOLTIP_CLICK = "Routing_PlanTooltip_click"; // editor public static final String EDITOR_START_CREATE = "Editor_Add_start"; public static final String EDITOR_ADD_CLICK = "Editor_Add_click"; public static final String EDITOR_START_EDIT = "Editor_Edit_start"; public static final String EDITOR_SUCCESS_CREATE = "Editor_Add_success"; public static final String EDITOR_SUCCESS_EDIT = "Editor_Edit_success"; public static final String EDITOR_ERROR_CREATE = "Editor_Add_error"; public static final String EDITOR_ERROR_EDIT = "Editor_Edit_error"; public static final String EDITOR_AUTH_DECLINED = "Editor_Auth_declined_by_user"; public static final String EDITOR_AUTH_REQUEST = "Editor_Auth_request"; public static final String EDITOR_AUTH_REQUEST_RESULT = "Editor_Auth_request_result"; public static final String EDITOR_REG_REQUEST = "Editor_Reg_request"; public static final String EDITOR_LOST_PASSWORD = "Editor_Lost_password"; public static final String EDITOR_SHARE_SHOW = "Editor_SecondTimeShare_show"; public static final String EDITOR_SHARE_CLICK = "Editor_SecondTimeShare_click"; // Cold start public static final String APPLICATION_COLD_STARTUP_INFO = "Application_ColdStartup_info"; // Ugc. public static final String UGC_REVIEW_START = "UGC_Review_start"; public static final String UGC_REVIEW_CANCEL = "UGC_Review_cancel"; public static final String UGC_REVIEW_SUCCESS = "UGC_Review_success"; public static final String UGC_AUTH_SHOWN = "UGC_Auth_shown"; public static final String UGC_AUTH_DECLINED = "UGC_Auth_declined"; public static final String UGC_AUTH_EXTERNAL_REQUEST_SUCCESS = "UGC_Auth_external_request_success"; public static final String UGC_AUTH_ERROR = "UGC_Auth_error"; public static final String MAP_LAYERS_ACTIVATE = "Map_Layers_activate"; // Purchases. static final String INAPP_PURCHASE_PREVIEW_SHOW = "InAppPurchase_Preview_show"; static final String INAPP_PURCHASE_PREVIEW_SELECT = "InAppPurchase_Preview_select"; public static final String INAPP_PURCHASE_PREVIEW_PAY = "InAppPurchase_Preview_pay"; public static final String INAPP_PURCHASE_PREVIEW_CANCEL = "InAppPurchase_Preview_cancel"; public static final String INAPP_PURCHASE_STORE_SUCCESS = "InAppPurchase_Store_success"; static final String INAPP_PURCHASE_STORE_ERROR = "InAppPurchase_Store_error"; public static final String INAPP_PURCHASE_VALIDATION_SUCCESS = "InAppPurchase_Validation_success"; static final String INAPP_PURCHASE_VALIDATION_ERROR = "InAppPurchase_Validation_error"; static final String INAPP_PURCHASE_PRODUCT_DELIVERED = "InAppPurchase_Product_delivered"; public static final String ONBOARDING_DEEPLINK_SCREEN_SHOW = "OnboardingDeeplinkScreen_show"; public static final String ONBOARDING_DEEPLINK_SCREEN_ACCEPT = "OnboardingDeeplinkScreen_accept"; public static final String ONBOARDING_DEEPLINK_SCREEN_DECLINE = "OnboardingDeeplinkScreen_decline"; public static final String TIPS_TRICKS_SHOW = "TipsTricks_show"; public static final String TIPS_TRICKS_CLOSE = "TipsTricks_close"; public static final String TIPS_TRICKS_CLICK = "TipsTricks_click"; public static class Settings { public static final String WEB_SITE = "Setings. Go to website"; public static final String FEEDBACK_GENERAL = "Send general feedback to [email protected]"; public static final String REPORT_BUG = "Settings. Bug reported"; public static final String RATE = "Settings. Rate app called"; public static final String TELL_FRIEND = "Settings. Tell to friend"; public static final String FACEBOOK = "Settings. Go to FB."; public static final String TWITTER = "Settings. Go to twitter."; public static final String HELP = "Settings. Help."; public static final String ABOUT = "Settings. About."; public static final String OSM_PROFILE = "Settings. Profile."; public static final String COPYRIGHT = "Settings. Copyright."; public static final String UNITS = "Settings. Change units."; public static final String ZOOM = "Settings. Switch zoom."; public static final String MAP_STYLE = "Settings. Map style."; public static final String VOICE_ENABLED = "Settings. Switch voice."; public static final String VOICE_LANGUAGE = "Settings. Voice language."; public static final String ENERGY_SAVING = "Settings_EnergySaving_change"; private Settings() {} } private EventName() {} } public static class EventParam { public static final String FROM = "from"; public static final String TO = "to"; public static final String OPTION = "option"; public static final String TRACKS = "tracks"; public static final String POINTS = "points"; public static final String URL = "url"; public static final String TOLL = "toll"; public static final String UNPAVED = "unpaved"; public static final String FERRY = "ferry"; public static final String MOTORWAY = "motorway"; public static final String SETTINGS = "settings"; public static final String ROUTE = "route"; static final String CATEGORY = "category"; public static final String TAB = "tab"; static final String COUNT = "Count"; static final String CHANNEL = "Channel"; static final String CALLER_ID = "Caller ID"; public static final String ENABLED = "Enabled"; public static final String RATING = "Rating"; static final String CONNECTION_TYPE = "Connection name"; static final String CONNECTION_FAST = "Connection fast"; static final String CONNECTION_METERED = "Connection limit"; static final String MY_POSITION = "my position"; static final String POINT = "point"; public static final String LANGUAGE = "language"; public static final String NAME = "Name"; public static final String ACTION = "action"; public static final String TYPE = "type"; static final String IS_AUTHENTICATED = "is_authenticated"; static final String IS_ONLINE = "is_online"; public static final String IS_SUCCESS = "is_success_message"; static final String FEATURE_ID = "feature_id"; static final String MWM_NAME = "mwm_name"; static final String MWM_VERSION = "mwm_version"; public static final String ERR_MSG = "error_message"; public static final String OSM = "OSM"; public static final String FACEBOOK = "Facebook"; public static final String PROVIDER = "provider"; public static final String HOTEL = "hotel"; static final String HOTEL_LAT = "hotel_lat"; static final String HOTEL_LON = "hotel_lon"; static final String RESTAURANT = "restaurant"; static final String RESTAURANT_LAT = "restaurant_lat"; static final String RESTAURANT_LON = "restaurant_lon"; static final String FROM_LAT = "from_lat"; static final String FROM_LON = "from_lon"; static final String TO_LAT = "to_lat"; static final String TO_LON = "to_lon"; static final String BANNER = "banner"; static final String STATE = "state"; static final String ERROR_CODE = "error_code"; public static final String ERROR = "error"; static final String ERROR_MESSAGE = "error_message"; static final String MAP_DATA_SIZE = "map_data_size:"; static final String BATTERY = "battery"; static final String CHARGING = "charging"; static final String NETWORK = "network"; public static final String VALUE = "value"; static final String METHOD = "method"; static final String MODE = "mode"; static final String OBJECT_LAT = "object_lat"; static final String OBJECT_LON = "object_lon"; static final String ITEM = "item"; static final String DESTINATION = "destination"; static final String PLACEMENT = "placement"; public static final String PRICE_CATEGORY = "price_category"; public static final String DATE = "date"; static final String HAS_AUTH = "has_auth"; public static final String STATUS = "status"; static final String INTERRUPTED = "interrupted"; static final String BUTTON = "button"; static final String VENDOR = "vendor"; static final String PRODUCT = "product"; static final String PURCHASE = "purchase"; private EventParam() {} } public static class ParamValue { public static final String BOOKING_COM = "Booking.Com"; public static final String OSM = "OSM"; public static final String ON = "on"; public static final String OFF = "off"; public static final String CRASH_REPORTS = "crash_reports"; public static final String PERSONAL_ADS = "personal_ads"; public static final String SHARING_OPTIONS = "sharing_options"; public static final String EDIT_ON_WEB = "edit_on_web"; public static final String PUBLIC = "public"; public static final String PRIVATE = "private"; public static final String COPY_LINK = "copy_link"; static final String SEARCH_BOOKING_COM = "Search.Booking.Com"; static final String OPENTABLE = "OpenTable"; static final String LOCALS_EXPERTS = "Locals.Maps.Me"; static final String SEARCH_RESTAURANTS = "Search.Restaurants"; static final String SEARCH_ATTRACTIONS = "Search.Attractions"; static final String HOLIDAY = "Holiday"; public static final String NO_PRODUCTS = "no_products"; static final String ADD = "add"; public static final String EDIT = "edit"; static final String AFTER_SAVE = "after_save"; static final String PLACEPAGE_PREVIEW = "placepage_preview"; static final String PLACEPAGE = "placepage"; static final String NOTIFICATION = "notification"; public static final String FACEBOOK = "facebook"; public static final String CHECKIN = "check_in"; public static final String CHECKOUT = "check_out"; public static final String ANY = "any"; public static final String GOOGLE = "google"; public static final String MAPSME = "mapsme"; public static final String PHONE = "phone"; public static final String UNKNOWN = "unknown"; static final String NETWORK = "network"; static final String DISK = "disk"; static final String AUTH = "auth"; static final String USER_INTERRUPTED = "user_interrupted"; static final String INVALID_CALL = "invalid_call"; static final String NO_BACKUP = "no_backup"; static final String DISK_NO_SPACE = "disk_no_space"; static final String BACKUP = "backup"; static final String RESTORE = "restore"; public static final String NO_INTERNET = "no_internet"; public static final String MY = "my"; public static final String DOWNLOADED = "downloaded"; static final String SUBWAY = "subway"; static final String TRAFFIC = "traffic"; public static final String SUCCESS = "success"; public static final String UNAVAILABLE = "unavailable"; static final String PEDESTRIAN = "pedestrian"; static final String VEHICLE = "vehicle"; static final String BICYCLE = "bicycle"; static final String TAXI = "taxi"; static final String TRANSIT = "transit"; public final static String VIEW_ON_MAP = "view on map"; public final static String NOT_NOW = "not now"; public final static String CLICK_OUTSIDE = "click outside pop-up"; public static final String ADD_DESC = "add_description"; public static final String SEND_AS_FILE = "send_as_file"; public static final String MAKE_INVISIBLE_ON_MAP = "make_invisible_on_map"; public static final String LIST_SETTINGS = "list_settings"; public static final String DELETE_GROUP = "delete_group"; public static final String OFFSCREEEN = "Offscreen"; } // Initialized once in constructor and does not change until the process restarts. // In this way we can correctly finish all statistics sessions and completely // avoid their initialization if user has disabled statistics collection. private final boolean mEnabled; Statistics() { mEnabled = SharedPropertiesUtils.isStatisticsEnabled(); final Context context = MwmApplication.get(); // At the moment we need special handling for Alohalytics to enable/disable logging of events in core C++ code. if (mEnabled) org.alohalytics.Statistics.enable(context); else org.alohalytics.Statistics.disable(context); configure(context); } @SuppressWarnings("NullableProblems") @NonNull private ExternalLibrariesMediator mMediator; public void setMediator(@NonNull ExternalLibrariesMediator mediator) { mMediator = mediator; } private void configure(Context context) { // At the moment, need to always initialize engine for correct JNI http part reusing. // Statistics is still enabled/disabled separately and never sent anywhere if turned off. // TODO (AlexZ): Remove this initialization dependency from JNI part. org.alohalytics.Statistics.setDebugMode(BuildConfig.DEBUG); org.alohalytics.Statistics.setup(PrivateVariables.alohalyticsUrl(), context); } public void trackEvent(@NonNull String name) { if (mEnabled) org.alohalytics.Statistics.logEvent(name); mMediator.getEventLogger().logEvent(name, Collections.emptyMap()); } public void trackEvent(@NonNull String name, @NonNull Map<String, String> params) { if (mEnabled) org.alohalytics.Statistics.logEvent(name, params); mMediator.getEventLogger().logEvent(name, params); } public void trackEvent(@NonNull String name, @Nullable Location location, @NonNull Map<String, String> params) { List<String> eventDictionary = new ArrayList<String>(); for (Map.Entry<String, String> entry : params.entrySet()) { eventDictionary.add(entry.getKey()); eventDictionary.add(entry.getValue()); } params.put("lat", (location == null ? "N/A" : String.valueOf(location.getLatitude()))); params.put("lon", (location == null ? "N/A" : String.valueOf(location.getLongitude()))); if (mEnabled) org.alohalytics.Statistics.logEvent(name, eventDictionary.toArray(new String[0]), location); mMediator.getEventLogger().logEvent(name, params); } public void trackEvent(@NonNull String name, @NonNull ParameterBuilder builder) { trackEvent(name, builder.get()); } public void startActivity(Activity activity) { if (mEnabled) { AppEventsLogger.activateApp(activity); org.alohalytics.Statistics.onStart(activity); } mMediator.getEventLogger().startActivity(activity); } public void stopActivity(Activity activity) { if (mEnabled) { AppEventsLogger.deactivateApp(activity); org.alohalytics.Statistics.onStop(activity); } mMediator.getEventLogger().stopActivity(activity); } public void setStatEnabled(boolean isEnabled) { SharedPropertiesUtils.setStatisticsEnabled(isEnabled); Config.setStatisticsEnabled(isEnabled); // We track if user turned on/off statistics to understand data better. trackEvent(EventName.STATISTICS_STATUS_CHANGED + " " + Counters.getInstallFlavor(), params().add(EventParam.ENABLED, String.valueOf(isEnabled))); } public void trackSearchTabSelected(@NonNull String tab) { trackEvent(EventName.SEARCH_TAB_SELECTED, params().add(EventParam.TAB, tab)); } public void trackSearchCategoryClicked(String category) { trackEvent(EventName.SEARCH_CAT_CLICKED, params().add(EventParam.CATEGORY, category)); } public void trackColorChanged(String from, String to) { trackEvent(EventName.BM_COLOR_CHANGED, params().add(EventParam.FROM, from) .add(EventParam.TO, to)); } public void trackBookmarkCreated() { trackEvent(EventName.BM_CREATED, params().add(EventParam.COUNT, String.valueOf(++mBookmarksCreated))); } public void trackPlaceShared(String channel) { trackEvent(EventName.PLACE_SHARED, params().add(EventParam.CHANNEL, channel).add(EventParam.COUNT, String.valueOf(++mSharedTimes))); } public void trackApiCall(@NonNull ParsedMwmRequest request) { trackEvent(EventName.API_CALLED, params().add(EventParam.CALLER_ID, request.getCallerInfo() == null ? "null" : request.getCallerInfo().packageName)); } public void trackRatingDialog(float rating) { trackEvent(EventName.RATE_DIALOG_RATED, params().add(EventParam.RATING, String.valueOf(rating))); } public void trackConnectionState() { if (ConnectionState.isConnected()) { final NetworkInfo info = ConnectionState.getActiveNetwork(); boolean isConnectionMetered = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) isConnectionMetered = ((ConnectivityManager) MwmApplication.get().getSystemService(Context.CONNECTIVITY_SERVICE)).isActiveNetworkMetered(); //noinspection ConstantConditions trackEvent(EventName.ACTIVE_CONNECTION, params().add(EventParam.CONNECTION_TYPE, info.getTypeName() + ":" + info.getSubtypeName()) .add(EventParam.CONNECTION_FAST, String.valueOf(ConnectionState.isConnectionFast(info))) .add(EventParam.CONNECTION_METERED, String.valueOf(isConnectionMetered))); } else trackEvent(EventName.ACTIVE_CONNECTION, params().add(EventParam.CONNECTION_TYPE, "Not connected.")); } // FIXME Call to track map changes to MyTracker to correctly deal with preinstalls. public void trackMapChanged(String event) { if (mEnabled) { final ParameterBuilder params = params().add(EventParam.COUNT, String.valueOf(MapManager.nativeGetDownloadedCount())); trackEvent(event, params); } } public void trackRouteBuild(int routerType, MapObject from, MapObject to) { trackEvent(EventName.ROUTING_BUILD, params().add(EventParam.FROM, Statistics.getPointType(from)) .add(EventParam.TO, Statistics.getPointType(to))); } public void trackEditorLaunch(boolean newObject) { trackEvent(newObject ? EventName.EDITOR_START_CREATE : EventName.EDITOR_START_EDIT, editorMwmParams().add(EventParam.IS_AUTHENTICATED, String.valueOf(OsmOAuth.isAuthorized())) .add(EventParam.IS_ONLINE, String.valueOf(ConnectionState.isConnected()))); if (newObject) PushwooshHelper.nativeSendEditorAddObjectTag(); else PushwooshHelper.nativeSendEditorEditObjectTag(); } public void trackSubwayEvent(@NonNull String status) { trackMapLayerEvent(ParamValue.SUBWAY, status); } public void trackTrafficEvent(@NonNull String status) { trackMapLayerEvent(ParamValue.TRAFFIC, status); } private void trackMapLayerEvent(@NonNull String eventName, @NonNull String status) { ParameterBuilder builder = params().add(EventParam.NAME, eventName) .add(EventParam.STATUS, status); trackEvent(EventName.MAP_LAYERS_ACTIVATE, builder); } public void trackEditorSuccess(boolean newObject) { trackEvent(newObject ? EventName.EDITOR_SUCCESS_CREATE : EventName.EDITOR_SUCCESS_EDIT, editorMwmParams().add(EventParam.IS_AUTHENTICATED, String.valueOf(OsmOAuth.isAuthorized())) .add(EventParam.IS_ONLINE, String.valueOf(ConnectionState.isConnected()))); } public void trackEditorError(boolean newObject) { trackEvent(newObject ? EventName.EDITOR_ERROR_CREATE : EventName.EDITOR_ERROR_EDIT, editorMwmParams().add(EventParam.IS_AUTHENTICATED, String.valueOf(OsmOAuth.isAuthorized())) .add(EventParam.IS_ONLINE, String.valueOf(ConnectionState.isConnected()))); } public void trackAuthRequest(OsmOAuth.AuthType type) { trackEvent(EventName.EDITOR_AUTH_REQUEST, Statistics.params().add(Statistics.EventParam.TYPE, type.name)); } public void trackTaxiInRoutePlanning(@Nullable MapObject from, @Nullable MapObject to, @Nullable Location location, @NonNull String providerName, boolean isAppInstalled) { Statistics.ParameterBuilder params = Statistics.params(); params.add(Statistics.EventParam.PROVIDER, providerName); params.add(Statistics.EventParam.FROM_LAT, from != null ? String.valueOf(from.getLat()) : "N/A") .add(Statistics.EventParam.FROM_LON, from != null ? String.valueOf(from.getLon()) : "N/A"); params.add(Statistics.EventParam.TO_LAT, to != null ? String.valueOf(to.getLat()) : "N/A") .add(Statistics.EventParam.TO_LON, to != null ? String.valueOf(to.getLon()) : "N/A"); String event = isAppInstalled ? Statistics.EventName.ROUTING_TAXI_ORDER : Statistics.EventName.ROUTING_TAXI_INSTALL; trackEvent(event, location, params.get()); } public void trackTaxiEvent(@NonNull String eventName, @NonNull String providerName) { Statistics.ParameterBuilder params = Statistics.params(); params.add(Statistics.EventParam.PROVIDER, providerName); trackEvent(eventName, params); } public void trackTaxiError(@NonNull TaxiInfoError error) { Statistics.ParameterBuilder params = Statistics.params(); params.add(Statistics.EventParam.PROVIDER, error.getProviderName()); params.add(ERROR_CODE, error.getCode().name()); trackEvent(EventName.ROUTING_TAXI_ROUTE_BUILT, params); } public void trackNoTaxiProvidersError() { Statistics.ParameterBuilder params = Statistics.params(); params.add(ERROR_CODE, TaxiManager.ErrorCode.NoProviders.name()); trackEvent(EventName.ROUTING_TAXI_ROUTE_BUILT, params); } public void trackRestaurantEvent(@NonNull String eventName, @NonNull Sponsored restaurant, @NonNull MapObject mapObject) { String provider = restaurant.getType() == Sponsored.TYPE_OPENTABLE ? OPENTABLE : "Unknown restaurant"; Statistics.INSTANCE.trackEvent(eventName, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params().add(PROVIDER, provider) .add(RESTAURANT, restaurant.getId()) .add(RESTAURANT_LAT, mapObject.getLat()) .add(RESTAURANT_LON, mapObject.getLon()).get()); } public void trackHotelEvent(@NonNull String eventName, @NonNull Sponsored hotel, @NonNull MapObject mapObject) { String provider = hotel.getType() == Sponsored.TYPE_BOOKING ? BOOKING_COM : "Unknown hotel"; Statistics.INSTANCE.trackEvent(eventName, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params().add(PROVIDER, provider) .add(HOTEL, hotel.getId()) .add(HOTEL_LAT, mapObject.getLat()) .add(HOTEL_LON, mapObject.getLon()).get()); } public void trackBookHotelEvent(@NonNull Sponsored hotel, @NonNull MapObject mapObject) { trackHotelEvent(PP_SPONSORED_BOOK, hotel, mapObject); } public void trackBookmarksTabEvent(@NonNull String param) { ParameterBuilder params = params().add(EventParam.VALUE, param); trackEvent(EventName.BM_TAB_CLICK, params); } public void trackOpenCatalogScreen() { trackEvent(EventName.BM_DOWNLOADED_CATALOGUE_OPEN, Collections.emptyMap()); } public void trackDownloadCatalogError(@NonNull String value) { ParameterBuilder params = params().add(EventParam.ERROR, value); trackEvent(EventName.BM_DOWNLOADED_CATALOGUE_ERROR, params); } public void trackPPBanner(@NonNull String eventName, @NonNull MwmNativeAd ad, @BannerState int state) { trackEvent(eventName, Statistics.params() .add(BANNER, ad.getBannerId()) .add(PROVIDER, ad.getProvider()) .add(STATE, String.valueOf(state))); if (!eventName.equals(PP_BANNER_SHOW) || state == PP_BANNER_STATE_PREVIEW) MyTracker.trackEvent(eventName); } public void trackPPBannerError(@NonNull String bannerId, @NonNull String provider, @Nullable NativeAdError error, int state) { boolean isAdBlank = error != null && error.getCode() == AdError.NO_FILL_ERROR_CODE; String eventName = isAdBlank ? PP_BANNER_BLANK : PP_BANNER_ERROR; Statistics.ParameterBuilder builder = Statistics.params(); builder.add(BANNER, !TextUtils.isEmpty(bannerId) ? bannerId : "N/A") .add(ERROR_CODE, error != null ? String.valueOf(error.getCode()) : "N/A") .add(ERROR_MESSAGE, error != null ? error.getMessage() : "N/A") .add(PROVIDER, provider) .add(STATE, String.valueOf(state)); trackEvent(eventName, builder.get()); MyTracker.trackEvent(eventName); } public void trackBookingSearchEvent(@NonNull MapObject mapObject) { trackEvent(PP_SPONSORED_BOOK, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params() .add(PROVIDER, SEARCH_BOOKING_COM) .add(HOTEL, "") .add(HOTEL_LAT, mapObject.getLat()) .add(HOTEL_LON, mapObject.getLon()) .get()); } public void trackDownloaderDialogEvent(@NonNull String eventName, long size) { trackEvent(eventName, Statistics.params() .add(MAP_DATA_SIZE, size)); } public void trackDownloaderDialogError(long size, @NonNull String error) { trackEvent(DOWNLOADER_DIALOG_ERROR, Statistics.params() .add(MAP_DATA_SIZE, size) .add(TYPE, error)); } public void trackPPOwnershipButtonClick(@NonNull MapObject mapObject) { trackEvent(PP_OWNERSHIP_BUTTON_CLICK, LocationHelper.INSTANCE.getLastKnownLocation(), params() .add(MWM_NAME, mapObject.getFeatureId().getMwmName()) .add(MWM_VERSION, mapObject.getFeatureId().getMwmVersion()) .add(FEATURE_ID, mapObject.getFeatureId().getFeatureIndex()) .get()); } public void trackColdStartupInfo() { BatteryState.State state = BatteryState.getState(); final String charging; switch (state.getChargingStatus()) { case CHARGING_STATUS_UNKNOWN: charging = "unknown"; break; case CHARGING_STATUS_PLUGGED: charging = ParamValue.ON; break; case CHARGING_STATUS_UNPLUGGED: charging = ParamValue.OFF; break; default: charging = "unknown"; break; } final String network = getConnectionState(); trackEvent(APPLICATION_COLD_STARTUP_INFO, params() .add(BATTERY, state.getLevel()) .add(CHARGING, charging) .add(NETWORK, network) .get()); } @NonNull private String getConnectionState() { final String network; if (ConnectionState.isWifiConnected()) { network = "wifi"; } else if (ConnectionState.isMobileConnected()) { if (ConnectionState.isInRoaming()) network = "roaming"; else network = "mobile"; } else { network = "off"; } return network; } public void trackSponsoredOpenEvent(@NonNull Sponsored sponsored) { Statistics.ParameterBuilder builder = Statistics.params(); builder.add(NETWORK, getConnectionState()) .add(PROVIDER, convertToSponsor(sponsored)); trackEvent(PP_SPONSORED_OPEN, builder.get()); } public void trackGalleryShown(@NonNull GalleryType type, @NonNull GalleryState state, @NonNull GalleryPlacement placement) { trackEvent(PP_SPONSORED_SHOWN, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT, placement.toString()) .add(STATE, state.toString())); if (state == GalleryState.ONLINE) MyTracker.trackEvent(PP_SPONSORED_SHOWN + "_" + type.getProvider()); } public void trackGalleryError(@NonNull GalleryType type, @NonNull GalleryPlacement placement, @Nullable String code) { trackEvent(PP_SPONSORED_ERROR, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT, placement.toString()) .add(ERROR, code).get()); } public void trackGalleryProductItemSelected(@NonNull GalleryType type, @NonNull GalleryPlacement placement, int position, @NonNull Destination destination) { trackEvent(PP_SPONSOR_ITEM_SELECTED, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT, placement.toString()) .add(ITEM, position) .add(DESTINATION, destination.toString())); } public void trackGalleryEvent(@NonNull String eventName, @NonNull GalleryType type, @NonNull GalleryPlacement placement) { trackEvent(eventName, Statistics.params() .add(PROVIDER, type.getProvider()) .add(PLACEMENT,placement.toString()) .get()); } public void trackSearchPromoCategory(@NonNull String eventName, @NonNull String provider) { trackEvent(eventName, Statistics.params().add(PROVIDER, provider).get()); MyTracker.trackEvent(eventName + "_" + provider); } public void trackSettingsToggle(boolean value) { trackEvent(EventName.SETTINGS_TRACKING_TOGGLE, Statistics.params() .add(TYPE, ParamValue.CRASH_REPORTS) .add(VALUE, value ? ParamValue.ON : ParamValue.OFF).get()); } public void trackSettingsDetails() { trackEvent(EventName.SETTINGS_TRACKING_DETAILS, Statistics.params().add(TYPE, ParamValue.PERSONAL_ADS).get()); } @NonNull private static String convertToSponsor(@NonNull Sponsored sponsored) { if (sponsored.getType() == Sponsored.TYPE_PARTNER) return sponsored.getPartnerName(); return convertToSponsor(sponsored.getType()); } @NonNull private static String convertToSponsor(@Sponsored.SponsoredType int type) { switch (type) { case Sponsored.TYPE_BOOKING: return BOOKING_COM; case Sponsored.TYPE_OPENTABLE: return OPENTABLE; case Sponsored.TYPE_HOLIDAY: return HOLIDAY; case Sponsored.TYPE_NONE: return "N/A"; default: throw new AssertionError("Unknown sponsor type: " + type); } } public void trackRoutingPoint(@NonNull String eventName, @RoutePointInfo.RouteMarkType int type, boolean isPlanning, boolean isNavigating, boolean isMyPosition, boolean isApi) { final String mode; if (isNavigating) mode = "onroute"; else if (isPlanning) mode = "planning"; else mode = null; final String method; if (isPlanning) method = "planning_pp"; else if (isApi) method = "api"; else method = "outside_pp"; ParameterBuilder builder = params() .add(TYPE, convertRoutePointType(type)) .add(VALUE, isMyPosition ? "gps" : "point") .add(METHOD, method); if (mode != null) builder.add(MODE, mode); trackEvent(eventName, builder.get()); } public void trackRoutingEvent(@NonNull String eventName, boolean isPlanning) { trackEvent(eventName, params() .add(MODE, isPlanning ? "planning" : "onroute") .get()); } public void trackRoutingStart(@Framework.RouterType int type, boolean trafficEnabled) { trackEvent(ROUTING_ROUTE_START, prepareRouteParams(type, trafficEnabled)); } public void trackRoutingFinish(boolean interrupted, @Framework.RouterType int type, boolean trafficEnabled) { ParameterBuilder params = prepareRouteParams(type, trafficEnabled); trackEvent(ROUTING_ROUTE_FINISH, params.add(INTERRUPTED, interrupted ? 1 : 0)); } @NonNull private static ParameterBuilder prepareRouteParams(@Framework.RouterType int type, boolean trafficEnabled) { return params().add(MODE, toRouterType(type)).add(TRAFFIC, trafficEnabled ? 1 : 0); } @NonNull private static String toRouterType(@Framework.RouterType int type) { switch (type) { case Framework.ROUTER_TYPE_VEHICLE: return VEHICLE; case Framework.ROUTER_TYPE_PEDESTRIAN: return PEDESTRIAN; case Framework.ROUTER_TYPE_BICYCLE: return BICYCLE; case Framework.ROUTER_TYPE_TAXI: return TAXI; case Framework.ROUTER_TYPE_TRANSIT: return TRANSIT; default: throw new AssertionError("Unsupported router type: " + type); } } public void trackRoutingTooltipEvent(@RoutePointInfo.RouteMarkType int type, boolean isPlanning) { trackEvent(ROUTING_PLAN_TOOLTIP_CLICK, params() .add(TYPE, convertRoutePointType(type)) .add(MODE, isPlanning ? "planning" : "onroute") .get()); } public void trackSponsoredObjectEvent(@NonNull String eventName, @NonNull Sponsored sponsoredObj, @NonNull MapObject mapObject) { // Here we code category by means of rating. Statistics.INSTANCE.trackEvent(eventName, LocationHelper.INSTANCE.getLastKnownLocation(), Statistics.params().add(PROVIDER, convertToSponsor(sponsoredObj)) .add(CATEGORY, sponsoredObj.getRating()) .add(OBJECT_LAT, mapObject.getLat()) .add(OBJECT_LON, mapObject.getLon()).get()); } @NonNull private static String convertRoutePointType(@RoutePointInfo.RouteMarkType int type) { switch (type) { case RoutePointInfo.ROUTE_MARK_FINISH: return "finish"; case RoutePointInfo.ROUTE_MARK_INTERMEDIATE: return "inter"; case RoutePointInfo.ROUTE_MARK_START: return "start"; default: throw new AssertionError("Wrong parameter 'type'"); } } public void trackUGCStart(boolean isEdit, boolean isPPPreview, boolean isFromNotification) { trackEvent(UGC_REVIEW_START, params() .add(EventParam.IS_AUTHENTICATED, Framework.nativeIsUserAuthenticated()) .add(EventParam.IS_ONLINE, ConnectionState.isConnected()) .add(EventParam.MODE, isEdit ? ParamValue.EDIT : ParamValue.ADD) .add(EventParam.FROM, isPPPreview ? ParamValue.PLACEPAGE_PREVIEW : isFromNotification ? ParamValue.NOTIFICATION : ParamValue.PLACEPAGE) .get()); } public void trackUGCAuthDialogShown() { trackEvent(UGC_AUTH_SHOWN, params().add(EventParam.FROM, ParamValue.AFTER_SAVE).get()); } public void trackUGCExternalAuthSucceed(@NonNull String provider) { trackEvent(UGC_AUTH_EXTERNAL_REQUEST_SUCCESS, params().add(EventParam.PROVIDER, provider)); } public void trackUGCAuthFailed(@Framework.AuthTokenType int type, @Nullable String error) { trackEvent(UGC_AUTH_ERROR, params() .add(EventParam.PROVIDER, getAuthProvider(type)) .add(EventParam.ERROR, error) .get()); } @NonNull public static String getAuthProvider(@Framework.AuthTokenType int type) { switch (type) { case Framework.SOCIAL_TOKEN_FACEBOOK: return FACEBOOK; case Framework.SOCIAL_TOKEN_GOOGLE: return GOOGLE; case Framework.SOCIAL_TOKEN_PHONE: return PHONE; case Framework.TOKEN_MAPSME: return MAPSME; case Framework.SOCIAL_TOKEN_INVALID: return UNKNOWN; default: throw new AssertionError("Unknown social token type: " + type); } } @NonNull public static String getSynchronizationType(@BookmarkManager.SynchronizationType int type) { return type == 0 ? BACKUP : RESTORE; } public void trackFilterEvent(@NonNull String event, @NonNull String category) { trackEvent(event, params() .add(EventParam.CATEGORY, category) .get()); } public void trackFilterClick(@NonNull String category, @NonNull Pair<String, String> params) { trackEvent(SEARCH_FILTER_CLICK, params() .add(EventParam.CATEGORY, category) .add(params.first, params.second) .get()); } public void trackBmSyncProposalShown(boolean hasAuth) { trackEvent(BM_SYNC_PROPOSAL_SHOWN, params().add(HAS_AUTH, hasAuth ? 1 : 0).get()); } public void trackBmSyncProposalApproved(boolean hasAuth) { trackEvent(BM_SYNC_PROPOSAL_APPROVED, params() .add(HAS_AUTH, hasAuth ? 1 : 0) .add(NETWORK, getConnectionState()) .get()); } public void trackBmRestoreProposalClick() { trackEvent(BM_RESTORE_PROPOSAL_CLICK, params() .add(NETWORK, getConnectionState()) .get()); } public void trackBmSyncProposalError(@Framework.AuthTokenType int type, @Nullable String message) { trackEvent(BM_SYNC_PROPOSAL_ERROR, params() .add(PROVIDER, getAuthProvider(type)) .add(ERROR, message) .get()); } public void trackBmSettingsToggle(boolean checked) { trackEvent(BM_SYNC_PROPOSAL_TOGGLE, params() .add(STATE, checked ? 1 : 0) .get()); } public void trackBmSynchronizationFinish(@BookmarkManager.SynchronizationType int type, @BookmarkManager.SynchronizationResult int result, @NonNull String errorString) { if (result == BookmarkManager.CLOUD_SUCCESS) { if (type == BookmarkManager.CLOUD_BACKUP) trackEvent(BM_SYNC_SUCCESS); else trackEvent(BM_RESTORE_PROPOSAL_SUCCESS); return; } trackEvent(type == BookmarkManager.CLOUD_BACKUP ? BM_SYNC_ERROR : BM_RESTORE_PROPOSAL_ERROR, params().add(TYPE, getTypeForErrorSyncResult(result)).add(ERROR, errorString)); } public void trackBmRestoringRequestResult(@BookmarkManager.RestoringRequestResult int result) { if (result == BookmarkManager.CLOUD_BACKUP_EXISTS) return; trackEvent(BM_RESTORE_PROPOSAL_ERROR, params() .add(TYPE, getTypeForRequestRestoringError(result))); } @NonNull private static String getTypeForErrorSyncResult(@BookmarkManager.SynchronizationResult int result) { switch (result) { case BookmarkManager.CLOUD_AUTH_ERROR: return ParamValue.AUTH; case BookmarkManager.CLOUD_NETWORK_ERROR: return ParamValue.NETWORK; case BookmarkManager.CLOUD_DISK_ERROR: return ParamValue.DISK; case BookmarkManager.CLOUD_USER_INTERRUPTED: return ParamValue.USER_INTERRUPTED; case BookmarkManager.CLOUD_INVALID_CALL: return ParamValue.INVALID_CALL; case BookmarkManager.CLOUD_SUCCESS: throw new AssertionError("It's not a error result!"); default: throw new AssertionError("Unsupported error type: " + result); } } @NonNull private static String getTypeForRequestRestoringError(@BookmarkManager.RestoringRequestResult int result) { switch (result) { case BookmarkManager.CLOUD_BACKUP_EXISTS: throw new AssertionError("It's not a error result!"); case BookmarkManager.CLOUD_NOT_ENOUGH_DISK_SPACE: return DISK_NO_SPACE; case BookmarkManager.CLOUD_NO_BACKUP: return NO_BACKUP; default: throw new AssertionError("Unsupported restoring request result: " + result); } } public void trackToolbarClick(@NonNull MainMenu.Item button) { trackEvent(TOOLBAR_CLICK, getToolbarParams(button)); } public void trackToolbarMenu(@NonNull MainMenu.Item button) { trackEvent(TOOLBAR_MENU_CLICK, getToolbarParams(button)); } public void trackDownloadBookmarkDialog(@NonNull String button) { trackEvent(BM_GUIDES_DOWNLOADDIALOGUE_CLICK, params().add(ACTION, button)); } @NonNull private static ParameterBuilder getToolbarParams(@NonNull MainMenu.Item button) { return params().add(BUTTON, button.toStatisticValue()); } public void trackPPBannerClose(@BannerState int state, boolean isCross) { trackEvent(PP_BANNER_CLOSE, params().add(BANNER, state) .add(BUTTON, isCross ? 0 : 1)); } public void trackPurchasePreviewShow(@NonNull String purchaseId, @NonNull String vendor, @NonNull String productId) { trackEvent(INAPP_PURCHASE_PREVIEW_SHOW, params().add(VENDOR, vendor) .add(PRODUCT, productId) .add(PURCHASE, purchaseId)); } public void trackPurchaseEvent(@NonNull String event, @NonNull String purchaseId) { trackEvent(event, params().add(PURCHASE, purchaseId)); } public void trackPurchasePreviewSelect(@NonNull String purchaseId, @NonNull String productId) { trackEvent(INAPP_PURCHASE_PREVIEW_SELECT, params().add(PRODUCT, productId) .add(PURCHASE, productId)); } public void trackPurchaseStoreError(@NonNull String purchaseId, @BillingClient.BillingResponse int error) { trackEvent(INAPP_PURCHASE_STORE_ERROR, params().add(ERROR, "Billing error: " + error) .add(PURCHASE, purchaseId)); } public void trackPurchaseValidationError(@NonNull String purchaseId, @NonNull ValidationStatus status) { if (status == ValidationStatus.VERIFIED) return; int errorCode; if (status == ValidationStatus.NOT_VERIFIED) errorCode = 0; else if (status == ValidationStatus.SERVER_ERROR) errorCode = 2; else return; trackEvent(INAPP_PURCHASE_VALIDATION_ERROR, params().add(ERROR_CODE, errorCode) .add(PURCHASE, purchaseId)); } public void trackPowerManagmentSchemeChanged(@PowerManagment.SchemeType int scheme) { String statisticValue = ""; switch (scheme) { case PowerManagment.NONE: case PowerManagment.MEDIUM: throw new AssertionError("Incorrect scheme type"); case PowerManagment.NORMAL: statisticValue = "never"; break; case PowerManagment.AUTO: statisticValue = "auto"; break; case PowerManagment.HIGH: statisticValue = "max"; break; } trackEvent(EventName.Settings.ENERGY_SAVING, params().add(EventParam.VALUE, statisticValue)); } public void trackPurchaseProductDelivered(@NonNull String purchaseId, @NonNull String vendor) { trackEvent(INAPP_PURCHASE_PRODUCT_DELIVERED, params().add(VENDOR, vendor) .add(PURCHASE, purchaseId)); } public void trackTipsEvent(@NonNull String eventName, int type) { Statistics.INSTANCE.trackEvent(eventName, params().add(TYPE, type)); } public void trackTipsClose(int type) { Statistics.INSTANCE.trackEvent(TIPS_TRICKS_CLOSE, params().add(TYPE, type) .add(OPTION, OFFSCREEEN)); } public static ParameterBuilder params() { return new ParameterBuilder(); } public static ParameterBuilder editorMwmParams() { return params().add(MWM_NAME, Editor.nativeGetMwmName()) .add(MWM_VERSION, Editor.nativeGetMwmVersion()); } public static class ParameterBuilder { private final Map<String, String> mParams = new HashMap<>(); @NonNull public static ParameterBuilder from(@NonNull String key, @NonNull Analytics analytics) { return new ParameterBuilder().add(key, analytics.getName()); } public ParameterBuilder add(String key, String value) { mParams.put(key, value); return this; } public ParameterBuilder add(String key, boolean value) { mParams.put(key, String.valueOf(value)); return this; } public ParameterBuilder add(String key, int value) { mParams.put(key, String.valueOf(value)); return this; } public ParameterBuilder add(String key, float value) { mParams.put(key, String.valueOf(value)); return this; } public ParameterBuilder add(String key, double value) { mParams.put(key, String.valueOf(value)); return this; } public Map<String, String> get() { return mParams; } } public static String getPointType(MapObject point) { return MapObject.isOfType(MapObject.MY_POSITION, point) ? Statistics.EventParam.MY_POSITION : Statistics.EventParam.POINT; } public enum NetworkErrorType { NO_NETWORK, AUTH_FAILED; } }
[android] Manual cherry-pick(940d0e766beb26762e7f681db163ac6d15aedfb7) of server_error/auth_error separation for inaap validation statistics
android/src/com/mapswithme/util/statistics/Statistics.java
[android] Manual cherry-pick(940d0e766beb26762e7f681db163ac6d15aedfb7) of server_error/auth_error separation for inaap validation statistics
<ide><path>ndroid/src/com/mapswithme/util/statistics/Statistics.java <ide> return; <ide> <ide> int errorCode; <del> if (status == ValidationStatus.NOT_VERIFIED) <del> errorCode = 0; <del> else if (status == ValidationStatus.SERVER_ERROR) <del> errorCode = 2; <del> else <del> return; <add> switch (status) <add> { <add> case NOT_VERIFIED: <add> errorCode = 0; <add> break; <add> case AUTH_ERROR: <add> errorCode = 1; <add> break; <add> case SERVER_ERROR: <add> errorCode = 2; <add> break; <add> default: <add> throw new UnsupportedOperationException("Unsupported status: " + status); <add> } <ide> <ide> trackEvent(INAPP_PURCHASE_VALIDATION_ERROR, params().add(ERROR_CODE, errorCode) <ide> .add(PURCHASE, purchaseId));
Java
lgpl-2.1
ca3880fcd5a9c1122e3dd6397b8b2718831ac14d
0
alkacon/opencms-core,sbonoc/opencms-core,victos/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,victos/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,victos/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,victos/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core
/* * File : $Source$ * Date : $Date$ * Version: $Revision$ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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.opencms.workplace.tools.modules; import org.opencms.ade.configuration.CmsADEManager; import org.opencms.configuration.CmsConfigurationCopyResource; import org.opencms.configuration.Messages; import org.opencms.db.CmsExportPoint; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.A_CmsResourceType; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypeUnknown; import org.opencms.file.types.CmsResourceTypeXmlContainerPage; import org.opencms.file.types.I_CmsResourceType; import org.opencms.i18n.CmsLocaleManager; import org.opencms.i18n.CmsVfsBundleManager; import org.opencms.jsp.CmsJspActionElement; import org.opencms.loader.CmsLoaderException; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.main.CmsIllegalArgumentException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.module.CmsModule; import org.opencms.report.CmsLogReport; import org.opencms.search.replace.CmsSearchReplaceSettings; import org.opencms.search.replace.CmsSearchReplaceThread; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.explorer.CmsExplorerTypeSettings; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import org.apache.commons.logging.Log; /** * Clones a module.<p> */ public class CmsCloneModule extends CmsJspActionElement { /** The icon path. */ public static final String ICON_PATH = CmsWorkplace.VFS_PATH_RESOURCES + CmsWorkplace.RES_PATH_FILETYPES; /** Classes folder within the module. */ public static final String PATH_CLASSES = "classes/"; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsCloneModule.class); /** The action class used for the clone. */ private String m_actionClass; /** The author's email used for the clone. */ private String m_authorEmail = "[email protected]"; /** The author's name used for the clone. */ private String m_authorName = "Alkacon Software GmbH"; /** Option to change the resource types (optional flag). */ private String m_changeResourceTypes; /** If 'true' resource types in all sites will be adjusted. */ private String m_changeResourceTypesEverywhere; /** Option to delete the source module after cloning (optional flag). */ private String m_deleteModule; /** The description used for the clone. */ private String m_description = "This module provides the template layout."; /** A module name where the formatters are located that are referenced within the XSDs of the module to clone. */ private String m_formatterSourceModule = "com.alkacon.bootstrap.formatters"; /** A module name where the formatters are located that should be referenced by the XSDs of the clone. */ private String m_formatterTargetModule; /** The module group used for the clone. */ private String m_group; /** The nice name used for the clone. */ private String m_niceName = "My new template module."; /** The new module name used for the clone. */ private String m_packageName = "my.company.template"; /** The name of the source module to be cloned. */ private String m_sourceModuleName = "com.alkacon.bootstrap.formatters"; /** The prefix that is used by the source module. */ private String m_sourceNamePrefix = "bs"; /** The prefix that is used by the target module. */ private String m_targetNamePrefix = "my"; /** * Public constructor.<p> */ public CmsCloneModule() { // NOOP } /** * Constructor, with parameters.<p> * * @param context the JSP page context object * @param req the JSP request * @param res the JSP response */ public CmsCloneModule(PageContext context, HttpServletRequest req, HttpServletResponse res) { super(context, req, res); } /** * Bean constructor.<p> * * @param actionClass action class * @param authorEmail author email * @param authorName author name * @param changeResourceTypes change resource type flags * @param description module description * @param formatterSourceModule formatter source module * @param formatterTargetModule formatter target module * @param group module group * @param niceName nice name * @param packageName package/module name * @param sourceModuleName source module package/name * @param sourceNamePrefix source name prefix * @param targetNamePrefix source name prefix */ public CmsCloneModule( String actionClass, String authorEmail, String authorName, String changeResourceTypes, String description, String formatterSourceModule, String formatterTargetModule, String group, String niceName, String packageName, String sourceModuleName, String sourceNamePrefix, String targetNamePrefix) { super(); m_actionClass = actionClass; m_authorEmail = authorEmail; m_authorName = authorName; m_changeResourceTypes = changeResourceTypes; m_description = description; m_formatterSourceModule = formatterSourceModule; m_formatterTargetModule = formatterTargetModule; m_group = group; m_niceName = niceName; m_packageName = packageName; m_sourceModuleName = sourceModuleName; m_sourceNamePrefix = sourceNamePrefix; m_targetNamePrefix = targetNamePrefix; } /** * Executes the module clone and returns the new module.<p> */ public void executeModuleClone() { CmsModule sourceModule = OpenCms.getModuleManager().getModule(m_sourceModuleName); // clone the module object CmsModule targetModule = (CmsModule)sourceModule.clone(); targetModule.setName(m_packageName); targetModule.setNiceName(m_niceName); targetModule.setDescription(m_description); targetModule.setAuthorEmail(m_authorEmail); targetModule.setAuthorName(m_authorName); targetModule.setGroup(m_group); targetModule.setActionClass(m_actionClass); try { // store the module paths String sourceModulePath = CmsWorkplace.VFS_PATH_MODULES + sourceModule.getName() + "/"; String targetModulePath = CmsWorkplace.VFS_PATH_MODULES + targetModule.getName() + "/"; // store the package name as path part String sourcePathPart = sourceModule.getName().replaceAll("\\.", "/"); String targetPathPart = targetModule.getName().replaceAll("\\.", "/"); // store the classes folder paths String sourceClassesPath = targetModulePath + PATH_CLASSES + sourcePathPart + "/"; String targetClassesPath = targetModulePath + PATH_CLASSES + targetPathPart + "/"; // copy the resources getCmsObject().copyResource(sourceModulePath, targetModulePath); // check if we have to create the classes folder if (getCmsObject().existsResource(sourceClassesPath)) { // in the source module a classes folder was defined, // now create all sub-folders for the package structure in the new module folder createTargetClassesFolder(targetModule, sourceClassesPath, targetModulePath + PATH_CLASSES); // delete the origin classes folder deleteSourceClassesFolder(targetModulePath, sourcePathPart, targetPathPart); } // TODO: clone module dependencies // adjust the export points cloneExportPoints(sourceModule, targetModule, sourcePathPart, targetPathPart); // adjust the resource type names and IDs Map<String, String> descKeys = new HashMap<String, String>(); Map<I_CmsResourceType, I_CmsResourceType> resTypeMap = cloneResourceTypes( sourceModule, targetModule, sourcePathPart, targetPathPart, descKeys); // adjust the explorer type names and store referred icons and message keys Map<String, String> iconPaths = new HashMap<String, String>(); cloneExplorerTypes(targetModule, iconPaths, descKeys); // rename the icon file names cloneExplorerTypeIcons(iconPaths); // adjust the module resources adjustModuleResources(sourceModule, targetModule, sourcePathPart, targetPathPart, iconPaths); // search and replace the localization keys List<CmsResource> props = getCmsObject().readResources(targetClassesPath, CmsResourceFilter.DEFAULT_FILES); replacesMessages(descKeys, props); int type = OpenCms.getResourceManager().getResourceType(CmsVfsBundleManager.TYPE_XML_BUNDLE).getTypeId(); CmsResourceFilter filter = CmsResourceFilter.requireType(type); List<CmsResource> resources = getCmsObject().readResources(targetModulePath, filter); replacesMessages(descKeys, resources); renameXmlVfsBundles(resources, targetModule, sourceModule.getName()); List<CmsResource> allModuleResources = getCmsObject().readResources(targetModulePath, CmsResourceFilter.ALL); replacePath(sourceModulePath, targetModulePath, allModuleResources); // search and replace paths CmsSearchReplaceThread t = initializePathThread(); t.start(); t.join(); // search and replace module name t = initializeNameThread(); t.start(); t.join(); // replace formatter paths if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_formatterTargetModule) && !targetModule.getResourceTypes().isEmpty()) { replaceFormatterPaths(targetModule); } adjustModuleConfig(targetModule, resTypeMap); // publish the new module for (String res : targetModule.getResources()) { OpenCms.getPublishManager().publishResource(getCmsObject(), res); OpenCms.getPublishManager().waitWhileRunning(); } // add the imported module to the module manager OpenCms.getModuleManager().addModule(getCmsObject(), targetModule); // reinitialize the resource manager with additional module resource types if necessary if (targetModule.getResourceTypes() != Collections.EMPTY_LIST) { OpenCms.getResourceManager().initialize(getCmsObject()); } // reinitialize the workplace manager with additional module explorer types if necessary if (targetModule.getExplorerTypes() != Collections.EMPTY_LIST) { OpenCms.getWorkplaceManager().addExplorerTypeSettings(targetModule); } // re-initialize the workplace OpenCms.getWorkplaceManager().initialize(getCmsObject()); // fire "clear caches" event to reload all cached resource bundles OpenCms.fireCmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, new HashMap<String, Object>()); // change resource types and schema locations if (Boolean.valueOf(m_changeResourceTypes).booleanValue()) { changeResourceTypes(resTypeMap); } // adjust container pages CmsObject cms = OpenCms.initCmsObject(getCmsObject()); if (Boolean.valueOf(m_changeResourceTypesEverywhere).booleanValue()) { cms.getRequestContext().setSiteRoot("/"); } CmsResourceFilter f = CmsResourceFilter.requireType(CmsResourceTypeXmlContainerPage.getContainerPageTypeId()); List<CmsResource> allContainerPages = cms.readResources("/", f); replacePath(sourceModulePath, targetModulePath, allContainerPages); // delete the old module if (Boolean.valueOf(m_deleteModule).booleanValue()) { OpenCms.getModuleManager().deleteModule( getCmsObject(), sourceModule.getName(), false, new CmsLogReport(getCmsObject().getRequestContext().getLocale(), CmsCloneModule.class)); } } catch (CmsIllegalArgumentException e) { LOG.error(e.getMessage(), e); } catch (CmsException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } } /** * Returns the action class.<p> * * @return the action class */ public String getActionClass() { return m_actionClass; } /** * Returns a list of all module names.<p> * * @return a list of all module names */ public List<String> getAllModuleNames() { List<String> sortedModuleNames = new ArrayList<String>(OpenCms.getModuleManager().getModuleNames()); java.util.Collections.sort(sortedModuleNames); return sortedModuleNames; } /** * Returns the author email.<p> * * @return the author email */ public String getAuthorEmail() { return m_authorEmail; } /** * Returns the author name.<p> * * @return the author name */ public String getAuthorName() { return m_authorName; } /** * Returns the change resource types flag as String.<p> * * @return the change resource types flag as String */ public String getChangeResourceTypes() { return m_changeResourceTypes; } /** * Returns the changeResourceTypesEverywhere.<p> * * @return the changeResourceTypesEverywhere */ public String getChangeResourceTypesEverywhere() { return m_changeResourceTypesEverywhere; } /** * Returns the delete module flag String.<p> * * @return the delete module flag as String */ public String getDeleteModule() { return m_deleteModule; } /** * Returns the description.<p> * * @return the description */ public String getDescription() { return m_description; } /** * Returns the formatter source module package/name.<p> * * @return the formatter source module package/name */ public String getFormatterSourceModule() { return m_formatterSourceModule; } /** * Returns the formatter target module package/name.<p> * * @return the formatter target module package/name */ public String getFormatterTargetModule() { return m_formatterTargetModule; } /** * Returns the group.<p> * * @return the group */ public String getGroup() { return m_group; } /** * Returns the nice name.<p> * * @return the nice name */ public String getNiceName() { return m_niceName; } /** * Returns the package/module name for the clone/target.<p> * * @return the package/module name for the clone/target */ public String getPackageName() { return m_packageName; } /** * Returns the source module package/name (the module to clone).<p> * * @return the source module package/name (the module to clone) */ public String getSourceModuleName() { return m_sourceModuleName; } /** * Returns the source name prefix.<p> * * @return the source name prefix */ public String getSourceNamePrefix() { return m_sourceNamePrefix; } /** * Returns the target name prefix.<p> * * @return the target name prefix */ public String getTargetNamePrefix() { return m_targetNamePrefix; } /** * Sets the action class.<p> * * @param actionClass the action class */ public void setActionClass(String actionClass) { m_actionClass = actionClass; } /** * Sets the author email.<p> * * @param authorEmail the author email to set */ public void setAuthorEmail(String authorEmail) { m_authorEmail = authorEmail; } /** * Sets the author name.<p> * * @param authorName the author name to set */ public void setAuthorName(String authorName) { m_authorName = authorName; } /** * Sets the change resource types flag.<p> * * @param changeResourceTypes the change resource types falg to set */ public void setChangeResourceTypes(String changeResourceTypes) { m_changeResourceTypes = changeResourceTypes; } /** * Sets the changeResourceTypesEverywhere.<p> * * @param changeResourceTypesEverywhere the changeResourceTypesEverywhere to set */ public void setChangeResourceTypesEverywhere(String changeResourceTypesEverywhere) { m_changeResourceTypesEverywhere = changeResourceTypesEverywhere; } /** * Sets the delete module flag.<p> * * @param deleteModule the delete module flag to set */ public void setDeleteModule(String deleteModule) { m_deleteModule = deleteModule; } /** * Sets the description.<p> * * @param description the description to set */ public void setDescription(String description) { m_description = description; } /** * Sets the formatter source module name.<p> * * @param formatterSourceModule the formatter source module name to set */ public void setFormatterSourceModule(String formatterSourceModule) { m_formatterSourceModule = formatterSourceModule; } /** * Sets the formatter target module name.<p> * * @param formatterTargetModule the formatter target module name to set */ public void setFormatterTargetModule(String formatterTargetModule) { m_formatterTargetModule = formatterTargetModule; } /** * Sets the group.<p> * * @param group the group to set */ public void setGroup(String group) { m_group = group; } /** * Sets the nice name.<p> * * @param niceName the nice name to set */ public void setNiceName(String niceName) { m_niceName = niceName; } /** * Sets the package name.<p> * * @param packageName the package name to set */ public void setPackageName(String packageName) { m_packageName = packageName; } /** * Sets the source module name.<p> * * @param sourceModuleName the source module name to set */ public void setSourceModuleName(String sourceModuleName) { m_sourceModuleName = sourceModuleName; } /** * Sets the source name prefix.<p> * * @param sourceNamePrefix the source name prefix to set */ public void setSourceNamePrefix(String sourceNamePrefix) { m_sourceNamePrefix = sourceNamePrefix; } /** * Sets the target name prefix.<p> * * @param targetNamePrefix the target name prefix to set */ public void setTargetNamePrefix(String targetNamePrefix) { m_targetNamePrefix = targetNamePrefix; } /** * Returns <code>true</code> if the module has been created successful.<p> * * @return <code>true</code> if the module has been created successful */ public boolean success() { return OpenCms.getModuleManager().getModule(m_packageName) != null; } /** * Adjusts the module configuration file.<p> * * @param targetModule the target moodule * @param resTypeMap the resource type mapping * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void adjustModuleConfig(CmsModule targetModule, Map<I_CmsResourceType, I_CmsResourceType> resTypeMap) throws CmsException, UnsupportedEncodingException { String modPath = CmsWorkplace.VFS_PATH_MODULES + targetModule.getName() + "/" + CmsADEManager.CONFIG_FILE_NAME; CmsResource config = getCmsObject().readResource( modPath, CmsResourceFilter.requireType(OpenCms.getResourceManager().getResourceType(CmsADEManager.MODULE_CONFIG_TYPE).getTypeId())); CmsFile file = getCmsObject().readFile(config); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) { content = content.replaceAll(mapping.getKey().getTypeName(), mapping.getValue().getTypeName()); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } /** * Adjusts the paths of the module resources from the source path to the target path.<p> * * @param sourceModule the source module * @param targetModule the target module * @param sourcePathPart the path part of the source module * @param targetPathPart the path part of the target module * @param iconPaths the path where resource type icons are located */ private void adjustModuleResources( CmsModule sourceModule, CmsModule targetModule, String sourcePathPart, String targetPathPart, Map<String, String> iconPaths) { List<String> newTargetResources = new ArrayList<String>(); List<String> targetResources = targetModule.getResources(); for (String modRes : targetResources) { String nIcon = iconPaths.get(modRes.substring(modRes.lastIndexOf('/') + 1)); if (nIcon != null) { // the referenced resource is an resource type icon, add the new icon path newTargetResources.add(ICON_PATH + nIcon); } else if (modRes.contains(sourceModule.getName())) { // there is the name in it newTargetResources.add(modRes.replaceAll(sourceModule.getName(), targetModule.getName())); } else if (modRes.contains(sourcePathPart)) { // there is a path in it newTargetResources.add(modRes.replaceAll(sourcePathPart, targetPathPart)); } else { // there is whether the path nor the name in it newTargetResources.add(modRes); } } targetModule.setResources(newTargetResources); } /** * Changes the resource types and the schema locations of existing content.<p> * * @param resTypeMap a map containing the source types as keys and the target types as values * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void changeResourceTypes(Map<I_CmsResourceType, I_CmsResourceType> resTypeMap) throws CmsException, UnsupportedEncodingException { CmsObject clone = OpenCms.initCmsObject(getCmsObject()); if (Boolean.valueOf(m_changeResourceTypesEverywhere).booleanValue()) { clone.getRequestContext().setSiteRoot("/"); } for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) { CmsResourceFilter filter = CmsResourceFilter.requireType(mapping.getKey().getTypeId()); List<CmsResource> resources = clone.readResources("/", filter); String sourceSchemaPath = mapping.getKey().getConfiguration().get("schema"); String targetSchemaPath = mapping.getValue().getConfiguration().get("schema"); for (CmsResource res : resources) { if (lockResource(getCmsObject(), res)) { CmsFile file = getCmsObject().readFile(res); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); content = content.replaceAll(sourceSchemaPath, targetSchemaPath); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); res.setType(mapping.getValue().getTypeId()); getCmsObject().writeResource(res); } } } } /** * Copies the explorer type icons.<p> * * @param iconPaths the path to the location where the icons are located * * @throws CmsException if something goes wrong */ private void cloneExplorerTypeIcons(Map<String, String> iconPaths) throws CmsException { for (Map.Entry<String, String> entry : iconPaths.entrySet()) { String source = ICON_PATH + entry.getKey(); String target = ICON_PATH + entry.getValue(); if (!getCmsObject().existsResource(target)) { getCmsObject().copyResource(source, target); } } } /** * Copies the explorer type definitions.<p> * * @param targetModule the target module * @param iconPaths the path to the location where the icons are located * @param descKeys a map that contains a mapping of the explorer type definitions messages */ private void cloneExplorerTypes(CmsModule targetModule, Map<String, String> iconPaths, Map<String, String> descKeys) { List<CmsExplorerTypeSettings> targetExplorerTypes = targetModule.getExplorerTypes(); for (CmsExplorerTypeSettings expSetting : targetExplorerTypes) { descKeys.put(expSetting.getKey(), expSetting.getKey().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); String newIcon = expSetting.getIcon().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix); String newBigIcon = expSetting.getBigIconIfAvailable().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix); iconPaths.put(expSetting.getIcon(), newIcon); iconPaths.put(expSetting.getBigIconIfAvailable(), newBigIcon); expSetting.setName(expSetting.getName().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setKey(expSetting.getKey().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setIcon(expSetting.getIcon().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setBigIcon(expSetting.getBigIconIfAvailable().replaceFirst( m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setNewResourceUri(expSetting.getNewResourceUri().replaceFirst( m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setInfo(expSetting.getInfo().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); } } /** * Clones the export points of the module and adjusts its paths.<p> * * @param sourceModule the source module * @param targetModule the target module * @param sourcePathPart the source path part * @param targetPathPart the target path part */ private void cloneExportPoints( CmsModule sourceModule, CmsModule targetModule, String sourcePathPart, String targetPathPart) { for (CmsExportPoint exp : targetModule.getExportPoints()) { if (exp.getUri().contains(sourceModule.getName())) { exp.setUri(exp.getUri().replaceAll(sourceModule.getName(), targetModule.getName())); } if (exp.getUri().contains(sourcePathPart)) { exp.setUri(exp.getUri().replaceAll(sourcePathPart, targetPathPart)); } } } /** * Clones/copies the resource types.<p> * * @param sourceModule the source module * @param targetModule the target module * @param sourcePathPart the source path part * @param targetPathPart the target path part * @param keys the map where to put in the messages of the resource type * * @return a map with source resource types as key and the taregt resource types as value */ private Map<I_CmsResourceType, I_CmsResourceType> cloneResourceTypes( CmsModule sourceModule, CmsModule targetModule, String sourcePathPart, String targetPathPart, Map<String, String> keys) { Map<I_CmsResourceType, I_CmsResourceType> resourceTypeMapping = new HashMap<I_CmsResourceType, I_CmsResourceType>(); List<I_CmsResourceType> targetResourceTypes = new ArrayList<I_CmsResourceType>(); for (I_CmsResourceType sourceResType : targetModule.getResourceTypes()) { // get the class name attribute String className = sourceResType.getClassName(); // create the class instance I_CmsResourceType targetResType; try { if (className != null) { className = className.trim(); } int newId = -1; boolean exists = true; do { newId = new Random().nextInt((99999)) + 10000; try { OpenCms.getResourceManager().getResourceType(newId); } catch (CmsLoaderException e) { exists = false; } } while (exists); targetResType = (I_CmsResourceType)Class.forName(className).newInstance(); for (String mapping : sourceResType.getConfiguredMappings()) { targetResType.addMappingType(mapping); } targetResType.setAdjustLinksFolder(sourceResType.getAdjustLinksFolder()); if (targetResType instanceof A_CmsResourceType) { A_CmsResourceType concreteTargetResType = (A_CmsResourceType)targetResType; for (CmsProperty prop : sourceResType.getConfiguredDefaultProperties()) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(prop.getValue())) { prop.setStructureValue(prop.getStructureValue().replaceAll( sourceModule.getName(), targetModule.getName()).replaceAll(sourcePathPart, targetPathPart)); prop.setResourceValue(prop.getResourceValue().replaceAll( sourceModule.getName(), targetModule.getName()).replaceAll(sourcePathPart, targetPathPart)); } concreteTargetResType.addDefaultProperty(prop); } for (CmsConfigurationCopyResource conres : sourceResType.getConfiguredCopyResources()) { concreteTargetResType.addCopyResource( conres.getSource(), conres.getTarget(), conres.getTypeString()); } } for (Map.Entry<String, String> entry : sourceResType.getConfiguration().entrySet()) { targetResType.addConfigurationParameter( entry.getKey(), entry.getValue().replaceAll(sourceModule.getName(), targetModule.getName())); } targetResType.setAdditionalModuleResourceType(true); targetResType.initConfiguration( sourceResType.getTypeName().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix), newId + "", sourceResType.getClassName()); keys.put(sourceResType.getTypeName(), targetResType.getTypeName()); targetResourceTypes.add(targetResType); resourceTypeMapping.put(sourceResType, targetResType); } catch (Exception e) { // resource type is unknown, use dummy class to import the module resources targetResType = new CmsResourceTypeUnknown(); // write an error to the log LOG.error( Messages.get().getBundle().key( Messages.ERR_UNKNOWN_RESTYPE_CLASS_2, className, targetResType.getClass().getName()), e); } } targetModule.setResourceTypes(targetResourceTypes); return resourceTypeMapping; } /** * Creates the target folder for the module clone.<p> * * @param targetModule the target module * @param sourceClassesPath the source module class path * @param targetBaseClassesPath the 'classes' folder of the target module * * @throws CmsException if something goes wrong */ private void createTargetClassesFolder( CmsModule targetModule, String sourceClassesPath, String targetBaseClassesPath) throws CmsException { StringTokenizer tok = new StringTokenizer(targetModule.getName(), "."); int folderId = CmsResourceTypeFolder.getStaticTypeId(); String targetClassesPath = targetBaseClassesPath; while (tok.hasMoreTokens()) { String folder = tok.nextToken(); targetClassesPath += folder + "/"; if (!getCmsObject().existsResource(targetClassesPath)) { getCmsObject().createResource(targetClassesPath, folderId); } } // move exiting content into new classes sub-folder List<CmsResource> propertyFiles = getCmsObject().readResources(sourceClassesPath, CmsResourceFilter.ALL); for (CmsResource res : propertyFiles) { if (!getCmsObject().existsResource(targetClassesPath + res.getName())) { getCmsObject().copyResource(res.getRootPath(), targetClassesPath + res.getName()); } } } /** * Deletes the temporarily copied classes files.<p> * * @param targetModulePath the target module path * @param sourcePathPart the path part of the source module * @param targetPathPart the target path part * * @throws CmsException if something goes wrong */ private void deleteSourceClassesFolder(String targetModulePath, String sourcePathPart, String targetPathPart) throws CmsException { String sourceFirstFolder = sourcePathPart.substring(0, sourcePathPart.indexOf('/')); String targetFirstFolder = sourcePathPart.substring(0, sourcePathPart.indexOf('/')); if (!sourceFirstFolder.equals(targetFirstFolder)) { getCmsObject().deleteResource( targetModulePath + PATH_CLASSES + sourceFirstFolder, CmsResource.DELETE_PRESERVE_SIBLINGS); return; } String[] targetPathParts = CmsStringUtil.splitAsArray(targetPathPart, '/'); String[] sourcePathParts = CmsStringUtil.splitAsArray(sourcePathPart, '/'); int sourceLength = sourcePathParts.length; int diff = 0; for (int i = 0; i < targetPathParts.length; i++) { if (sourceLength >= i) { if (!targetPathParts[i].equals(sourcePathParts[i])) { diff = i + 1; } } } String topSourceClassesPath = targetModulePath + PATH_CLASSES + sourcePathPart.substring(0, sourcePathPart.indexOf('/')) + "/"; if (diff != 0) { topSourceClassesPath = targetModulePath + PATH_CLASSES; for (int i = 0; i < diff; i++) { topSourceClassesPath += sourcePathParts[i] + "/"; } } getCmsObject().deleteResource(topSourceClassesPath, CmsResource.DELETE_PRESERVE_SIBLINGS); } /** * Initializes a thread to find and replace all occurrence of the module's package name.<p> * * @return the thread */ private CmsSearchReplaceThread initializeNameThread() { CmsSearchReplaceSettings settings = new CmsSearchReplaceSettings(); settings.setPaths(new ArrayList<String>(Arrays.asList(new String[] {"/system/modules/" + m_packageName + "/"}))); settings.setProject(getCmsObject().getRequestContext().getCurrentProject().getName()); settings.setSearchpattern(m_sourceModuleName); settings.setReplacepattern(m_packageName); settings.setResources("/system/modules/" + m_packageName + "/"); HttpSession session = getRequest().getSession(); session.removeAttribute(CmsSearchReplaceSettings.ATTRIBUTE_NAME_SOURCESEARCH_RESULT_LIST); return new CmsSearchReplaceThread(session, getCmsObject(), settings); } /** * Initializes a thread to find and replace all occurrence of the module's path.<p> * * @return the thread */ private CmsSearchReplaceThread initializePathThread() { CmsSearchReplaceSettings settings = new CmsSearchReplaceSettings(); String[] paths = new String[] {CmsWorkplace.VFS_PATH_MODULES + m_packageName + "/"}; settings.setPaths(new ArrayList<String>(Arrays.asList(paths))); settings.setProject(getCmsObject().getRequestContext().getCurrentProject().getName()); settings.setSearchpattern(m_sourceModuleName); settings.setReplacepattern(m_packageName); settings.setResources(CmsWorkplace.VFS_PATH_MODULES + m_packageName + "/"); HttpSession session = getRequest().getSession(); session.removeAttribute(CmsSearchReplaceSettings.ATTRIBUTE_NAME_SOURCESEARCH_RESULT_LIST); return new CmsSearchReplaceThread(session, getCmsObject(), settings); } /** * Locks the current resource.<p> * * @param cms the current CmsObject * @param cmsResource the resource to lock * * @return <code>true</code> if the given resource was locked was successfully * * @throws CmsException if some goes wrong */ private boolean lockResource(CmsObject cms, CmsResource cmsResource) throws CmsException { CmsLock lock = cms.getLock(cms.getSitePath(cmsResource)); // check the lock if ((lock != null) && lock.isOwnedBy(cms.getRequestContext().getCurrentUser()) && lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // prove is current lock from current user in current project return true; } else if ((lock != null) && !lock.isUnlocked() && !lock.isOwnedBy(cms.getRequestContext().getCurrentUser())) { // the resource is not locked by the current user, so can not lock it return false; } else if ((lock != null) && !lock.isUnlocked() && lock.isOwnedBy(cms.getRequestContext().getCurrentUser()) && !lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // prove is current lock from current user but not in current project // file is locked by current user but not in current project // change the lock cms.changeLock(cms.getSitePath(cmsResource)); } else if ((lock != null) && lock.isUnlocked()) { // lock resource from current user in current project cms.lockResource(cms.getSitePath(cmsResource)); } lock = cms.getLock(cms.getSitePath(cmsResource)); if ((lock != null) && lock.isOwnedBy(cms.getRequestContext().getCurrentUser()) && !lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // resource could not be locked return false; } // resource is locked successfully return true; } /** * Renames the vfs resource bundle files within the target module according to the new module's name.<p> * * @param resources the vfs resource bundle files * @param targetModule the target module * @param name the package name of the source module * * @return a list of all xml vfs bundles within the given module * * @throws CmsException if something gows wrong */ private List<CmsResource> renameXmlVfsBundles(List<CmsResource> resources, CmsModule targetModule, String name) throws CmsException { for (CmsResource res : resources) { String newName = res.getName().replaceAll(name, targetModule.getName()); String targetRootPath = CmsResource.getFolderPath(res.getRootPath()) + newName; if (!getCmsObject().existsResource(targetRootPath)) { getCmsObject().moveResource(res.getRootPath(), targetRootPath); } } return resources; } /** * Replaces the referenced formatters within the new XSD files with the new formatter paths.<p> * * @param targetModule the target module * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void replaceFormatterPaths(CmsModule targetModule) throws CmsException, UnsupportedEncodingException { CmsResource formatterSourceFolder = getCmsObject().readResource( "/system/modules/" + m_formatterSourceModule + "/formatters/"); CmsResource formatterTargetFolder = getCmsObject().readResource( "/system/modules/" + m_formatterTargetModule + "/formatters/"); for (I_CmsResourceType type : targetModule.getResourceTypes()) { String schemaPath = type.getConfiguration().get("schema"); CmsResource res = getCmsObject().readResource(schemaPath); CmsFile file = getCmsObject().readFile(res); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); content = content.replaceAll(formatterSourceFolder.getRootPath(), formatterTargetFolder.getRootPath()); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } /** * Replaces the paths within all the given resources and removes all UUIDs by an regex.<p> * * @param sourceModulePath the search path * @param targetModulePath the replace path * @param allModuleResources the resources * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void replacePath(String sourceModulePath, String targetModulePath, List<CmsResource> allModuleResources) throws CmsException, UnsupportedEncodingException { for (CmsResource resource : allModuleResources) { if (resource.isFile()) { CmsFile file = getCmsObject().readFile(resource); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String oldContent = new String(file.getContents(), encoding); String newContent = oldContent.replaceAll(sourceModulePath, targetModulePath); Matcher matcher = Pattern.compile(CmsUUID.UUID_REGEX).matcher(newContent); newContent = matcher.replaceAll(""); newContent = newContent.replaceAll("<uuid></uuid>", ""); if (!oldContent.equals(newContent)) { file.setContents(newContent.getBytes(encoding)); if (!resource.getRootPath().startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) { if (lockResource(getCmsObject(), resource)) { getCmsObject().writeFile(file); } } else { getCmsObject().writeFile(file); } } } } } /** * Replaces the messages for the given resources.<p> * * @param descKeys the replacement mapping * @param resources the resources to consult * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void replacesMessages(Map<String, String> descKeys, List<CmsResource> resources) throws CmsException, UnsupportedEncodingException { for (CmsResource resource : resources) { CmsFile file = getCmsObject().readFile(resource); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); for (Map.Entry<String, String> entry : descKeys.entrySet()) { content = content.replaceAll(entry.getKey(), entry.getValue()); } file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } }
src-modules/org/opencms/workplace/tools/modules/CmsCloneModule.java
/* * File : $Source$ * Date : $Date$ * Version: $Revision$ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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.opencms.workplace.tools.modules; import org.opencms.ade.configuration.CmsADEManager; import org.opencms.configuration.CmsConfigurationCopyResource; import org.opencms.configuration.Messages; import org.opencms.db.CmsExportPoint; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.A_CmsResourceType; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypeUnknown; import org.opencms.file.types.I_CmsResourceType; import org.opencms.i18n.CmsLocaleManager; import org.opencms.i18n.CmsVfsBundleManager; import org.opencms.jsp.CmsJspActionElement; import org.opencms.loader.CmsLoaderException; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.main.CmsIllegalArgumentException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.module.CmsModule; import org.opencms.search.replace.CmsSearchReplaceSettings; import org.opencms.search.replace.CmsSearchReplaceThread; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.explorer.CmsExplorerTypeSettings; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import org.apache.commons.logging.Log; /** * Clones a module.<p> */ public class CmsCloneModule extends CmsJspActionElement { /** The icon path. */ public static final String ICON_PATH = CmsWorkplace.VFS_PATH_RESOURCES + CmsWorkplace.RES_PATH_FILETYPES; /** Classes folder within the module. */ public static final String PATH_CLASSES = "classes/"; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsCloneModule.class); /** The action class used for the clone. */ private String m_actionClass; /** The author's email used for the clone. */ private String m_authorEmail = "[email protected]"; /** The author's name used for the clone. */ private String m_authorName = "Alkacon Software GmbH"; /** Option to change the resource types (optional flag). */ private String m_changeResourceTypes; /** Option to delete the source module after cloning (optional flag). */ private String m_deleteModule; /** The description used for the clone. */ private String m_description = "This module provides the template layout."; /** A module name where the formatters are located that are referenced within the XSDs of the module to clone. */ private String m_formatterSourceModule = "com.alkacon.bootstrap.formatters"; /** A module name where the formatters are located that should be referenced by the XSDs of the clone. */ private String m_formatterTargetModule; /** The module group used for the clone. */ private String m_group; /** The nice name used for the clone. */ private String m_niceName = "My new template module."; /** The new module name used for the clone. */ private String m_packageName = "my.company.template"; /** The name of the source module to be cloned. */ private String m_sourceModuleName = "com.alkacon.bootstrap.formatters"; /** The prefix that is used by the source module. */ private String m_sourceNamePrefix = "bs"; /** The prefix that is used by the target module. */ private String m_targetNamePrefix = "my"; /** * Public constructor.<p> */ public CmsCloneModule() { // NOOP } /** * Constructor, with parameters.<p> * * @param context the JSP page context object * @param req the JSP request * @param res the JSP response */ public CmsCloneModule(PageContext context, HttpServletRequest req, HttpServletResponse res) { super(context, req, res); } /** * Bean constructor.<p> * * @param actionClass action class * @param authorEmail author email * @param authorName author name * @param changeResourceTypes change resource type flags * @param description module description * @param formatterSourceModule formatter source module * @param formatterTargetModule formatter target module * @param group module group * @param niceName nice name * @param packageName package/module name * @param sourceModuleName source module package/name * @param sourceNamePrefix source name prefix * @param targetNamePrefix source name prefix */ public CmsCloneModule( String actionClass, String authorEmail, String authorName, String changeResourceTypes, String description, String formatterSourceModule, String formatterTargetModule, String group, String niceName, String packageName, String sourceModuleName, String sourceNamePrefix, String targetNamePrefix) { super(); m_actionClass = actionClass; m_authorEmail = authorEmail; m_authorName = authorName; m_changeResourceTypes = changeResourceTypes; m_description = description; m_formatterSourceModule = formatterSourceModule; m_formatterTargetModule = formatterTargetModule; m_group = group; m_niceName = niceName; m_packageName = packageName; m_sourceModuleName = sourceModuleName; m_sourceNamePrefix = sourceNamePrefix; m_targetNamePrefix = targetNamePrefix; } /** * Executes the module clone and returns the new module.<p> */ public void executeModuleClone() { CmsModule sourceModule = OpenCms.getModuleManager().getModule(m_sourceModuleName); // clone the module object CmsModule targetModule = (CmsModule)sourceModule.clone(); targetModule.setName(m_packageName); targetModule.setNiceName(m_niceName); targetModule.setDescription(m_description); targetModule.setAuthorEmail(m_authorEmail); targetModule.setAuthorName(m_authorName); targetModule.setGroup(m_group); targetModule.setActionClass(m_actionClass); try { // store the module paths String sourceModulePath = CmsWorkplace.VFS_PATH_MODULES + sourceModule.getName() + "/"; String targetModulePath = CmsWorkplace.VFS_PATH_MODULES + targetModule.getName() + "/"; // store the package name as path part String sourcePathPart = sourceModule.getName().replaceAll("\\.", "/"); String targetPathPart = targetModule.getName().replaceAll("\\.", "/"); // store the classes folder paths String sourceClassesPath = targetModulePath + PATH_CLASSES + sourcePathPart + "/"; String targetClassesPath = targetModulePath + PATH_CLASSES + targetPathPart + "/"; // copy the resources getCmsObject().copyResource(sourceModulePath, targetModulePath); // check if we have to create the classes folder if (getCmsObject().existsResource(sourceClassesPath)) { // in the source module a classes folder was defined, // now create all sub-folders for the package structure in the new module folder createTargetClassesFolder(targetModule, sourceClassesPath, targetModulePath + PATH_CLASSES); // delete the origin classes folder deleteSourceClassesFolder(targetModulePath, sourcePathPart, targetPathPart); } // TODO: clone module dependencies // adjust the export points cloneExportPoints(sourceModule, targetModule, sourcePathPart, targetPathPart); // adjust the resource type names and IDs Map<String, String> descKeys = new HashMap<String, String>(); Map<I_CmsResourceType, I_CmsResourceType> resTypeMap = cloneResourceTypes( sourceModule, targetModule, sourcePathPart, targetPathPart, descKeys); // adjust the explorer type names and store referred icons and message keys Map<String, String> iconPaths = new HashMap<String, String>(); cloneExplorerTypes(targetModule, iconPaths, descKeys); // rename the icon file names cloneExplorerTypeIcons(iconPaths); // adjust the module resources adjustModuleResources(sourceModule, targetModule, sourcePathPart, targetPathPart, iconPaths); // search and replace the localization keys List<CmsResource> props = getCmsObject().readResources(targetClassesPath, CmsResourceFilter.DEFAULT_FILES); replacesMessages(descKeys, props); int type = OpenCms.getResourceManager().getResourceType(CmsVfsBundleManager.TYPE_XML_BUNDLE).getTypeId(); CmsResourceFilter filter = CmsResourceFilter.requireType(type); List<CmsResource> resources = getCmsObject().readResources(targetModulePath, filter); replacesMessages(descKeys, resources); renameXmlVfsBundles(resources, targetModule, sourceModule.getName()); List<CmsResource> allModuleResources = getCmsObject().readResources(targetModulePath, CmsResourceFilter.ALL); replacePath(sourceModulePath, targetModulePath, allModuleResources); // search and replace paths CmsSearchReplaceThread t = initializePathThread(); t.start(); t.join(); // search and replace module name t = initializeNameThread(); t.start(); t.join(); // replace formatter paths if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_formatterTargetModule) && !targetModule.getResourceTypes().isEmpty()) { replaceFormatterPaths(targetModule); } adjustModuleConfig(targetModule, resTypeMap); // publish the new module for (String res : targetModule.getResources()) { OpenCms.getPublishManager().publishResource(getCmsObject(), res); OpenCms.getPublishManager().waitWhileRunning(); } // add the imported module to the module manager OpenCms.getModuleManager().addModule(getCmsObject(), targetModule); // reinitialize the resource manager with additional module resource types if necessary if (targetModule.getResourceTypes() != Collections.EMPTY_LIST) { OpenCms.getResourceManager().initialize(getCmsObject()); } // reinitialize the workplace manager with additional module explorer types if necessary if (targetModule.getExplorerTypes() != Collections.EMPTY_LIST) { OpenCms.getWorkplaceManager().addExplorerTypeSettings(targetModule); } // re-initialize the workplace OpenCms.getWorkplaceManager().initialize(getCmsObject()); // fire "clear caches" event to reload all cached resource bundles OpenCms.fireCmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, new HashMap<String, Object>()); // change resource types and schema locations if (Boolean.valueOf(m_changeResourceTypes).booleanValue()) { changeResourceTypes(resTypeMap); } // delete the old module if (Boolean.valueOf(m_deleteModule).booleanValue()) { OpenCms.getModuleManager().deleteModule(getCmsObject(), sourceModule.getName(), false, null); } } catch (CmsIllegalArgumentException e) { LOG.error(e.getMessage(), e); } catch (CmsException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } } /** * Returns the action class.<p> * * @return the action class */ public String getActionClass() { return m_actionClass; } /** * Returns a list of all module names.<p> * * @return a list of all module names */ public List<String> getAllModuleNames() { List<String> sortedModuleNames = new ArrayList<String>(OpenCms.getModuleManager().getModuleNames()); java.util.Collections.sort(sortedModuleNames); return sortedModuleNames; } /** * Returns the author email.<p> * * @return the author email */ public String getAuthorEmail() { return m_authorEmail; } /** * Returns the author name.<p> * * @return the author name */ public String getAuthorName() { return m_authorName; } /** * Returns the change resource types flag as String.<p> * * @return the change resource types flag as String */ public String getChangeResourceTypes() { return m_changeResourceTypes; } /** * Returns the delete module flag String.<p> * * @return the delete module flag as String */ public String getDeleteModule() { return m_deleteModule; } /** * Returns the description.<p> * * @return the description */ public String getDescription() { return m_description; } /** * Returns the formatter source module package/name.<p> * * @return the formatter source module package/name */ public String getFormatterSourceModule() { return m_formatterSourceModule; } /** * Returns the formatter target module package/name.<p> * * @return the formatter target module package/name */ public String getFormatterTargetModule() { return m_formatterTargetModule; } /** * Returns the group.<p> * * @return the group */ public String getGroup() { return m_group; } /** * Returns the nice name.<p> * * @return the nice name */ public String getNiceName() { return m_niceName; } /** * Returns the package/module name for the clone/target.<p> * * @return the package/module name for the clone/target */ public String getPackageName() { return m_packageName; } /** * Returns the source module package/name (the module to clone).<p> * * @return the source module package/name (the module to clone) */ public String getSourceModuleName() { return m_sourceModuleName; } /** * Returns the source name prefix.<p> * * @return the source name prefix */ public String getSourceNamePrefix() { return m_sourceNamePrefix; } /** * Returns the target name prefix.<p> * * @return the target name prefix */ public String getTargetNamePrefix() { return m_targetNamePrefix; } /** * Sets the action class.<p> * * @param actionClass the action class */ public void setActionClass(String actionClass) { m_actionClass = actionClass; } /** * Sets the author email.<p> * * @param authorEmail the author email to set */ public void setAuthorEmail(String authorEmail) { m_authorEmail = authorEmail; } /** * Sets the author name.<p> * * @param authorName the author name to set */ public void setAuthorName(String authorName) { m_authorName = authorName; } /** * Sets the change resource types flag.<p> * * @param changeResourceTypes the change resource types falg to set */ public void setChangeResourceTypes(String changeResourceTypes) { m_changeResourceTypes = changeResourceTypes; } /** * Sets the delete module flag.<p> * * @param deleteModule the delete module flag to set */ public void setDeleteModule(String deleteModule) { m_deleteModule = deleteModule; } /** * Sets the description.<p> * * @param description the description to set */ public void setDescription(String description) { m_description = description; } /** * Sets the formatter source module name.<p> * * @param formatterSourceModule the formatter source module name to set */ public void setFormatterSourceModule(String formatterSourceModule) { m_formatterSourceModule = formatterSourceModule; } /** * Sets the formatter target module name.<p> * * @param formatterTargetModule the formatter target module name to set */ public void setFormatterTargetModule(String formatterTargetModule) { m_formatterTargetModule = formatterTargetModule; } /** * Sets the group.<p> * * @param group the group to set */ public void setGroup(String group) { m_group = group; } /** * Sets the nice name.<p> * * @param niceName the nice name to set */ public void setNiceName(String niceName) { m_niceName = niceName; } /** * Sets the package name.<p> * * @param packageName the package name to set */ public void setPackageName(String packageName) { m_packageName = packageName; } /** * Sets the source module name.<p> * * @param sourceModuleName the source module name to set */ public void setSourceModuleName(String sourceModuleName) { m_sourceModuleName = sourceModuleName; } /** * Sets the source name prefix.<p> * * @param sourceNamePrefix the source name prefix to set */ public void setSourceNamePrefix(String sourceNamePrefix) { m_sourceNamePrefix = sourceNamePrefix; } /** * Sets the target name prefix.<p> * * @param targetNamePrefix the target name prefix to set */ public void setTargetNamePrefix(String targetNamePrefix) { m_targetNamePrefix = targetNamePrefix; } /** * Returns <code>true</code> if the module has been created successful.<p> * * @return <code>true</code> if the module has been created successful */ public boolean success() { return OpenCms.getModuleManager().getModule(m_packageName) != null; } /** * Adjusts the module configuration file.<p> * * @param targetModule the target moodule * @param resTypeMap the resource type mapping * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void adjustModuleConfig(CmsModule targetModule, Map<I_CmsResourceType, I_CmsResourceType> resTypeMap) throws CmsException, UnsupportedEncodingException { String modPath = CmsWorkplace.VFS_PATH_MODULES + targetModule.getName() + "/" + CmsADEManager.CONFIG_FILE_NAME; CmsResource config = getCmsObject().readResource( modPath, CmsResourceFilter.requireType(OpenCms.getResourceManager().getResourceType(CmsADEManager.MODULE_CONFIG_TYPE).getTypeId())); CmsFile file = getCmsObject().readFile(config); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) { content = content.replaceAll(mapping.getKey().getTypeName(), mapping.getValue().getTypeName()); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } /** * Adjusts the paths of the module resources from the source path to the target path.<p> * * @param sourceModule the source module * @param targetModule the target module * @param sourcePathPart the path part of the source module * @param targetPathPart the path part of the target module * @param iconPaths the path where resource type icons are located */ private void adjustModuleResources( CmsModule sourceModule, CmsModule targetModule, String sourcePathPart, String targetPathPart, Map<String, String> iconPaths) { List<String> newTargetResources = new ArrayList<String>(); List<String> targetResources = targetModule.getResources(); for (String modRes : targetResources) { String nIcon = iconPaths.get(modRes.substring(modRes.lastIndexOf('/') + 1)); if (nIcon != null) { // the referenced resource is an resource type icon, add the new icon path newTargetResources.add(ICON_PATH + nIcon); } else if (modRes.contains(sourceModule.getName())) { // there is the name in it newTargetResources.add(modRes.replaceAll(sourceModule.getName(), targetModule.getName())); } else if (modRes.contains(sourcePathPart)) { // there is a path in it newTargetResources.add(modRes.replaceAll(sourcePathPart, targetPathPart)); } else { // there is whether the path nor the name in it newTargetResources.add(modRes); } } targetModule.setResources(newTargetResources); } /** * Changes the resource types and the schema locations of existing content.<p> * * @param resTypeMap a map containing the source types as keys and the target types as values * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void changeResourceTypes(Map<I_CmsResourceType, I_CmsResourceType> resTypeMap) throws CmsException, UnsupportedEncodingException { for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) { List<CmsResource> resources = getCmsObject().readResources( "/", CmsResourceFilter.requireType(mapping.getKey().getTypeId())); String sourceSchemaPath = mapping.getKey().getConfiguration().get("schema"); String targetSchemaPath = mapping.getValue().getConfiguration().get("schema"); for (CmsResource res : resources) { if (lockResource(getCmsObject(), res)) { CmsFile file = getCmsObject().readFile(res); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); content = content.replaceAll(sourceSchemaPath, targetSchemaPath); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); res.setType(mapping.getValue().getTypeId()); getCmsObject().writeResource(res); } } } } /** * Copies the explorer type icons.<p> * * @param iconPaths the path to the location where the icons are located * * @throws CmsException if something goes wrong */ private void cloneExplorerTypeIcons(Map<String, String> iconPaths) throws CmsException { for (Map.Entry<String, String> entry : iconPaths.entrySet()) { String source = ICON_PATH + entry.getKey(); String target = ICON_PATH + entry.getValue(); if (!getCmsObject().existsResource(target)) { getCmsObject().copyResource(source, target); } } } /** * Copies the explorer type definitions.<p> * * @param targetModule the target module * @param iconPaths the path to the location where the icons are located * @param descKeys a map that contains a mapping of the explorer type definitions messages */ private void cloneExplorerTypes(CmsModule targetModule, Map<String, String> iconPaths, Map<String, String> descKeys) { List<CmsExplorerTypeSettings> targetExplorerTypes = targetModule.getExplorerTypes(); for (CmsExplorerTypeSettings expSetting : targetExplorerTypes) { descKeys.put(expSetting.getKey(), expSetting.getKey().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); String newIcon = expSetting.getIcon().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix); String newBigIcon = expSetting.getBigIconIfAvailable().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix); iconPaths.put(expSetting.getIcon(), newIcon); iconPaths.put(expSetting.getBigIconIfAvailable(), newBigIcon); expSetting.setName(expSetting.getName().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setKey(expSetting.getKey().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setIcon(expSetting.getIcon().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setBigIcon(expSetting.getBigIconIfAvailable().replaceFirst( m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setNewResourceUri(expSetting.getNewResourceUri().replaceFirst( m_sourceNamePrefix, m_targetNamePrefix)); expSetting.setInfo(expSetting.getInfo().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix)); } } /** * Clones the export points of the module and adjusts its paths.<p> * * @param sourceModule the source module * @param targetModule the target module * @param sourcePathPart the source path part * @param targetPathPart the target path part */ private void cloneExportPoints( CmsModule sourceModule, CmsModule targetModule, String sourcePathPart, String targetPathPart) { for (CmsExportPoint exp : targetModule.getExportPoints()) { if (exp.getUri().contains(sourceModule.getName())) { exp.setUri(exp.getUri().replaceAll(sourceModule.getName(), targetModule.getName())); } if (exp.getUri().contains(sourcePathPart)) { exp.setUri(exp.getUri().replaceAll(sourcePathPart, targetPathPart)); } } } /** * Clones/copies the resource types.<p> * * @param sourceModule the source module * @param targetModule the target module * @param sourcePathPart the source path part * @param targetPathPart the target path part * @param keys the map where to put in the messages of the resource type * * @return a map with source resource types as key and the taregt resource types as value */ private Map<I_CmsResourceType, I_CmsResourceType> cloneResourceTypes( CmsModule sourceModule, CmsModule targetModule, String sourcePathPart, String targetPathPart, Map<String, String> keys) { Map<I_CmsResourceType, I_CmsResourceType> resourceTypeMapping = new HashMap<I_CmsResourceType, I_CmsResourceType>(); List<I_CmsResourceType> targetResourceTypes = new ArrayList<I_CmsResourceType>(); for (I_CmsResourceType sourceResType : targetModule.getResourceTypes()) { // get the class name attribute String className = sourceResType.getClassName(); // create the class instance I_CmsResourceType targetResType; try { if (className != null) { className = className.trim(); } int newId = -1; boolean exists = true; do { newId = new Random().nextInt((99999)) + 10000; try { OpenCms.getResourceManager().getResourceType(newId); } catch (CmsLoaderException e) { exists = false; } } while (exists); targetResType = (I_CmsResourceType)Class.forName(className).newInstance(); for (String mapping : sourceResType.getConfiguredMappings()) { targetResType.addMappingType(mapping); } targetResType.setAdjustLinksFolder(sourceResType.getAdjustLinksFolder()); if (targetResType instanceof A_CmsResourceType) { A_CmsResourceType concreteTargetResType = (A_CmsResourceType)targetResType; for (CmsProperty prop : sourceResType.getConfiguredDefaultProperties()) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(prop.getValue())) { prop.setStructureValue(prop.getStructureValue().replaceAll( sourceModule.getName(), targetModule.getName()).replaceAll(sourcePathPart, targetPathPart)); prop.setResourceValue(prop.getResourceValue().replaceAll( sourceModule.getName(), targetModule.getName()).replaceAll(sourcePathPart, targetPathPart)); } concreteTargetResType.addDefaultProperty(prop); } for (CmsConfigurationCopyResource conres : sourceResType.getConfiguredCopyResources()) { concreteTargetResType.addCopyResource( conres.getSource(), conres.getTarget(), conres.getTypeString()); } } for (Map.Entry<String, String> entry : sourceResType.getConfiguration().entrySet()) { targetResType.addConfigurationParameter( entry.getKey(), entry.getValue().replaceAll(sourceModule.getName(), targetModule.getName())); } targetResType.setAdditionalModuleResourceType(true); targetResType.initConfiguration( sourceResType.getTypeName().replaceFirst(m_sourceNamePrefix, m_targetNamePrefix), newId + "", sourceResType.getClassName()); keys.put(sourceResType.getTypeName(), targetResType.getTypeName()); targetResourceTypes.add(targetResType); resourceTypeMapping.put(sourceResType, targetResType); } catch (Exception e) { // resource type is unknown, use dummy class to import the module resources targetResType = new CmsResourceTypeUnknown(); // write an error to the log LOG.error( Messages.get().getBundle().key( Messages.ERR_UNKNOWN_RESTYPE_CLASS_2, className, targetResType.getClass().getName()), e); } } targetModule.setResourceTypes(targetResourceTypes); return resourceTypeMapping; } /** * Creates the target folder for the module clone.<p> * * @param targetModule the target module * @param sourceClassesPath the source module class path * @param targetBaseClassesPath the 'classes' folder of the target module * * @throws CmsException if something goes wrong */ private void createTargetClassesFolder( CmsModule targetModule, String sourceClassesPath, String targetBaseClassesPath) throws CmsException { StringTokenizer tok = new StringTokenizer(targetModule.getName(), "."); int folderId = CmsResourceTypeFolder.getStaticTypeId(); String targetClassesPath = targetBaseClassesPath; while (tok.hasMoreTokens()) { String folder = tok.nextToken(); targetClassesPath += folder + "/"; if (!getCmsObject().existsResource(targetClassesPath)) { getCmsObject().createResource(targetClassesPath, folderId); } } // move exiting content into new classes sub-folder List<CmsResource> propertyFiles = getCmsObject().readResources(sourceClassesPath, CmsResourceFilter.ALL); for (CmsResource res : propertyFiles) { if (!getCmsObject().existsResource(targetClassesPath + res.getName())) { getCmsObject().copyResource(res.getRootPath(), targetClassesPath + res.getName()); } } } /** * Deletes the temporarily copied classes files.<p> * * @param targetModulePath the target module path * @param sourcePathPart the path part of the source module * @param targetPathPart the target path part * * @throws CmsException if something goes wrong */ private void deleteSourceClassesFolder(String targetModulePath, String sourcePathPart, String targetPathPart) throws CmsException { String sourceFirstFolder = sourcePathPart.substring(0, sourcePathPart.indexOf('/')); String targetFirstFolder = sourcePathPart.substring(0, sourcePathPart.indexOf('/')); if (!sourceFirstFolder.equals(targetFirstFolder)) { getCmsObject().deleteResource( targetModulePath + PATH_CLASSES + sourceFirstFolder, CmsResource.DELETE_PRESERVE_SIBLINGS); return; } String[] targetPathParts = CmsStringUtil.splitAsArray(targetPathPart, '/'); String[] sourcePathParts = CmsStringUtil.splitAsArray(sourcePathPart, '/'); int sourceLength = sourcePathParts.length; int diff = 0; for (int i = 0; i < targetPathParts.length; i++) { if (sourceLength >= i) { if (!targetPathParts[i].equals(sourcePathParts[i])) { diff = i + 1; } } } String topSourceClassesPath = targetModulePath + PATH_CLASSES + sourcePathPart.substring(0, sourcePathPart.indexOf('/')) + "/"; if (diff != 0) { topSourceClassesPath = targetModulePath + PATH_CLASSES; for (int i = 0; i < diff; i++) { topSourceClassesPath += sourcePathParts[i] + "/"; } } getCmsObject().deleteResource(topSourceClassesPath, CmsResource.DELETE_PRESERVE_SIBLINGS); } /** * Initializes a thread to find and replace all occurrence of the module's package name.<p> * * @return the thread */ private CmsSearchReplaceThread initializeNameThread() { CmsSearchReplaceSettings settings = new CmsSearchReplaceSettings(); settings.setPaths(new ArrayList<String>(Arrays.asList(new String[] {"/system/modules/" + m_packageName + "/"}))); settings.setProject(getCmsObject().getRequestContext().getCurrentProject().getName()); settings.setSearchpattern(m_sourceModuleName); settings.setReplacepattern(m_packageName); settings.setResources("/system/modules/" + m_packageName + "/"); HttpSession session = getRequest().getSession(); session.removeAttribute(CmsSearchReplaceSettings.ATTRIBUTE_NAME_SOURCESEARCH_RESULT_LIST); return new CmsSearchReplaceThread(session, getCmsObject(), settings); } /** * Initializes a thread to find and replace all occurrence of the module's path.<p> * * @return the thread */ private CmsSearchReplaceThread initializePathThread() { CmsSearchReplaceSettings settings = new CmsSearchReplaceSettings(); String[] paths = new String[] {CmsWorkplace.VFS_PATH_MODULES + m_packageName + "/"}; settings.setPaths(new ArrayList<String>(Arrays.asList(paths))); settings.setProject(getCmsObject().getRequestContext().getCurrentProject().getName()); settings.setSearchpattern(m_sourceModuleName); settings.setReplacepattern(m_packageName); settings.setResources(CmsWorkplace.VFS_PATH_MODULES + m_packageName + "/"); HttpSession session = getRequest().getSession(); session.removeAttribute(CmsSearchReplaceSettings.ATTRIBUTE_NAME_SOURCESEARCH_RESULT_LIST); return new CmsSearchReplaceThread(session, getCmsObject(), settings); } /** * Locks the current resource.<p> * * @param cms the current CmsObject * @param cmsResource the resource to lock * * @return <code>true</code> if the given resource was locked was successfully * * @throws CmsException if some goes wrong */ private boolean lockResource(CmsObject cms, CmsResource cmsResource) throws CmsException { CmsLock lock = cms.getLock(cms.getSitePath(cmsResource)); // check the lock if ((lock != null) && lock.isOwnedBy(cms.getRequestContext().getCurrentUser()) && lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // prove is current lock from current user in current project return true; } else if ((lock != null) && !lock.isUnlocked() && !lock.isOwnedBy(cms.getRequestContext().getCurrentUser())) { // the resource is not locked by the current user, so can not lock it return false; } else if ((lock != null) && !lock.isUnlocked() && lock.isOwnedBy(cms.getRequestContext().getCurrentUser()) && !lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // prove is current lock from current user but not in current project // file is locked by current user but not in current project // change the lock cms.changeLock(cms.getSitePath(cmsResource)); } else if ((lock != null) && lock.isUnlocked()) { // lock resource from current user in current project cms.lockResource(cms.getSitePath(cmsResource)); } lock = cms.getLock(cms.getSitePath(cmsResource)); if ((lock != null) && lock.isOwnedBy(cms.getRequestContext().getCurrentUser()) && !lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // resource could not be locked return false; } // resource is locked successfully return true; } /** * Renames the vfs resource bundle files within the target module according to the new module's name.<p> * * @param resources the vfs resource bundle files * @param targetModule the target module * @param name the package name of the source module * * @return a list of all xml vfs bundles within the given module * * @throws CmsException if something gows wrong */ private List<CmsResource> renameXmlVfsBundles(List<CmsResource> resources, CmsModule targetModule, String name) throws CmsException { for (CmsResource res : resources) { String newName = res.getName().replaceAll(name, targetModule.getName()); String targetRootPath = CmsResource.getFolderPath(res.getRootPath()) + newName; if (!getCmsObject().existsResource(targetRootPath)) { getCmsObject().moveResource(res.getRootPath(), targetRootPath); } } return resources; } /** * Replaces the referenced formatters within the new XSD files with the new formatter paths.<p> * * @param targetModule the target module * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void replaceFormatterPaths(CmsModule targetModule) throws CmsException, UnsupportedEncodingException { CmsResource formatterSourceFolder = getCmsObject().readResource( "/system/modules/" + m_formatterSourceModule + "/formatters/"); CmsResource formatterTargetFolder = getCmsObject().readResource( "/system/modules/" + m_formatterTargetModule + "/formatters/"); for (I_CmsResourceType type : targetModule.getResourceTypes()) { String schemaPath = type.getConfiguration().get("schema"); CmsResource res = getCmsObject().readResource(schemaPath); CmsFile file = getCmsObject().readFile(res); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); content = content.replaceAll(formatterSourceFolder.getRootPath(), formatterTargetFolder.getRootPath()); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } /** * Replaces the paths within all the given resources and removes all UUIDs by an regex.<p> * * @param sourceModulePath the search path * @param targetModulePath the replace path * @param allModuleResources the resources * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void replacePath(String sourceModulePath, String targetModulePath, List<CmsResource> allModuleResources) throws CmsException, UnsupportedEncodingException { for (CmsResource resource : allModuleResources) { if (resource.isFile()) { CmsFile file = getCmsObject().readFile(resource); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); content = content.replaceAll(sourceModulePath, targetModulePath); Matcher matcher = Pattern.compile(CmsUUID.UUID_REGEX).matcher(content); content = matcher.replaceAll(""); content = content.replaceAll("<uuid></uuid>", ""); file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } } /** * Replaces the messages for the given resources.<p> * * @param descKeys the replacement mapping * @param resources the resources to consult * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding */ private void replacesMessages(Map<String, String> descKeys, List<CmsResource> resources) throws CmsException, UnsupportedEncodingException { for (CmsResource resource : resources) { CmsFile file = getCmsObject().readFile(resource); String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); String content = new String(file.getContents(), encoding); for (Map.Entry<String, String> entry : descKeys.entrySet()) { content = content.replaceAll(entry.getKey(), entry.getValue()); } file.setContents(content.getBytes(encoding)); getCmsObject().writeFile(file); } } }
Improved module cloning for adjusting container pages, delete module and added option to change resource types system wide.
src-modules/org/opencms/workplace/tools/modules/CmsCloneModule.java
Improved module cloning for adjusting container pages, delete module and added option to change resource types system wide.
<ide><path>rc-modules/org/opencms/workplace/tools/modules/CmsCloneModule.java <ide> import org.opencms.file.types.A_CmsResourceType; <ide> import org.opencms.file.types.CmsResourceTypeFolder; <ide> import org.opencms.file.types.CmsResourceTypeUnknown; <add>import org.opencms.file.types.CmsResourceTypeXmlContainerPage; <ide> import org.opencms.file.types.I_CmsResourceType; <ide> import org.opencms.i18n.CmsLocaleManager; <ide> import org.opencms.i18n.CmsVfsBundleManager; <ide> import org.opencms.main.I_CmsEventListener; <ide> import org.opencms.main.OpenCms; <ide> import org.opencms.module.CmsModule; <add>import org.opencms.report.CmsLogReport; <ide> import org.opencms.search.replace.CmsSearchReplaceSettings; <ide> import org.opencms.search.replace.CmsSearchReplaceThread; <ide> import org.opencms.util.CmsStringUtil; <ide> <ide> /** Option to change the resource types (optional flag). */ <ide> private String m_changeResourceTypes; <add> <add> /** If 'true' resource types in all sites will be adjusted. */ <add> private String m_changeResourceTypesEverywhere; <ide> <ide> /** Option to delete the source module after cloning (optional flag). */ <ide> private String m_deleteModule; <ide> if (Boolean.valueOf(m_changeResourceTypes).booleanValue()) { <ide> changeResourceTypes(resTypeMap); <ide> } <add> // adjust container pages <add> CmsObject cms = OpenCms.initCmsObject(getCmsObject()); <add> if (Boolean.valueOf(m_changeResourceTypesEverywhere).booleanValue()) { <add> cms.getRequestContext().setSiteRoot("/"); <add> } <add> CmsResourceFilter f = CmsResourceFilter.requireType(CmsResourceTypeXmlContainerPage.getContainerPageTypeId()); <add> List<CmsResource> allContainerPages = cms.readResources("/", f); <add> replacePath(sourceModulePath, targetModulePath, allContainerPages); <ide> <ide> // delete the old module <ide> if (Boolean.valueOf(m_deleteModule).booleanValue()) { <del> OpenCms.getModuleManager().deleteModule(getCmsObject(), sourceModule.getName(), false, null); <add> OpenCms.getModuleManager().deleteModule( <add> getCmsObject(), <add> sourceModule.getName(), <add> false, <add> new CmsLogReport(getCmsObject().getRequestContext().getLocale(), CmsCloneModule.class)); <ide> } <ide> <ide> } catch (CmsIllegalArgumentException e) { <ide> } <ide> <ide> /** <add> * Returns the changeResourceTypesEverywhere.<p> <add> * <add> * @return the changeResourceTypesEverywhere <add> */ <add> public String getChangeResourceTypesEverywhere() { <add> <add> return m_changeResourceTypesEverywhere; <add> } <add> <add> /** <ide> * Returns the delete module flag String.<p> <ide> * <ide> * @return the delete module flag as String <ide> public void setChangeResourceTypes(String changeResourceTypes) { <ide> <ide> m_changeResourceTypes = changeResourceTypes; <add> } <add> <add> /** <add> * Sets the changeResourceTypesEverywhere.<p> <add> * <add> * @param changeResourceTypesEverywhere the changeResourceTypesEverywhere to set <add> */ <add> public void setChangeResourceTypesEverywhere(String changeResourceTypesEverywhere) { <add> <add> m_changeResourceTypesEverywhere = changeResourceTypesEverywhere; <ide> } <ide> <ide> /** <ide> private void changeResourceTypes(Map<I_CmsResourceType, I_CmsResourceType> resTypeMap) <ide> throws CmsException, UnsupportedEncodingException { <ide> <add> CmsObject clone = OpenCms.initCmsObject(getCmsObject()); <add> if (Boolean.valueOf(m_changeResourceTypesEverywhere).booleanValue()) { <add> clone.getRequestContext().setSiteRoot("/"); <add> } <add> <ide> for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) { <del> List<CmsResource> resources = getCmsObject().readResources( <del> "/", <del> CmsResourceFilter.requireType(mapping.getKey().getTypeId())); <add> CmsResourceFilter filter = CmsResourceFilter.requireType(mapping.getKey().getTypeId()); <add> List<CmsResource> resources = clone.readResources("/", filter); <ide> String sourceSchemaPath = mapping.getKey().getConfiguration().get("schema"); <ide> String targetSchemaPath = mapping.getValue().getConfiguration().get("schema"); <ide> for (CmsResource res : resources) { <ide> if (resource.isFile()) { <ide> CmsFile file = getCmsObject().readFile(resource); <ide> String encoding = CmsLocaleManager.getResourceEncoding(getCmsObject(), file); <del> String content = new String(file.getContents(), encoding); <del> content = content.replaceAll(sourceModulePath, targetModulePath); <del> Matcher matcher = Pattern.compile(CmsUUID.UUID_REGEX).matcher(content); <del> content = matcher.replaceAll(""); <del> content = content.replaceAll("<uuid></uuid>", ""); <del> file.setContents(content.getBytes(encoding)); <del> getCmsObject().writeFile(file); <add> String oldContent = new String(file.getContents(), encoding); <add> String newContent = oldContent.replaceAll(sourceModulePath, targetModulePath); <add> Matcher matcher = Pattern.compile(CmsUUID.UUID_REGEX).matcher(newContent); <add> newContent = matcher.replaceAll(""); <add> newContent = newContent.replaceAll("<uuid></uuid>", ""); <add> if (!oldContent.equals(newContent)) { <add> file.setContents(newContent.getBytes(encoding)); <add> if (!resource.getRootPath().startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) { <add> if (lockResource(getCmsObject(), resource)) { <add> getCmsObject().writeFile(file); <add> } <add> } else { <add> getCmsObject().writeFile(file); <add> } <add> } <ide> } <ide> } <ide> }
Java
mit
3279cd940d3d14cb33068a217a0e986888abd4cb
0
xxyy/xyc
/* * Copyright (c) 2013 - 2015 xxyy (Philipp Nowak; [email protected]). All rights reserved. * * Any usage, including, but not limited to, compiling, running, redistributing, printing, * copying and reverse-engineering is strictly prohibited without explicit written permission * from the original author and may result in legal steps being taken. * * See the included LICENSE file (core/src/main/resources) or email [email protected] for details. */ package io.github.xxyy.common.util.inventory; import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.material.MaterialData; import org.bukkit.material.Wool; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * This factory helps with creating {@link org.bukkit.inventory.ItemStack}s. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 30/01/14 */ @SuppressWarnings("UnusedDeclaration") public final class ItemStackFactory { @NotNull private final ItemStack base; private String displayName; private List<String> lore; private MaterialData materialData; private ItemMeta meta; /** * Creates a factory from a base {@link org.bukkit.inventory.ItemStack}. * * @param source Item stack to use as base for this factory. */ public ItemStackFactory(@NotNull final ItemStack source) { base = source; materialData = source.getData(); if (source.hasItemMeta()) { meta = source.getItemMeta(); if (meta.hasDisplayName()) { displayName = meta.getDisplayName(); } if (meta.hasLore()) { lore = meta.getLore(); } } } /** * Creates a factory by a {@link org.bukkit.Material}. * The resulting stack will have an amount of 1. * * @param material Material the product shall be * @see org.bukkit.inventory.ItemStack#ItemStack(org.bukkit.Material) */ public ItemStackFactory(final Material material) { base = new ItemStack(material); } /** * Sets the product's amount. * * @param newAmount New amount * @return This object for chained calls. */ public ItemStackFactory amount(final int newAmount) { base.setAmount(newAmount); return this; } /** * @param displayName Future display name of the product. * @return This object for chained calls. */ public ItemStackFactory displayName(final String displayName) { this.displayName = displayName; return this; } /** * Sets the display name of this factory if the resulting stack would not have a custom display name. * @param defaultDisplayName the display name to ste * @return this object */ public ItemStackFactory defaultDisplayName(final String defaultDisplayName) { if (!(base.hasItemMeta() && base.getItemMeta().hasDisplayName()) || displayName == null) { return displayName(defaultDisplayName); } return this; } /** * Sets the resulting item stack's lore, overriding any previous values. * * @param lore Future lore of the product. * @return This object for chained calls. */ public ItemStackFactory lore(final List<String> lore) { this.lore = lore; return this; } /** * Appends a collection of strings to the resulting item stack's lore, treating every element as a separate line. * If this factory was constructed with a template item stack, this method will append to its existing lore, if any. * @param loreToAppend the lines to add to the lore * @return this object */ public ItemStackFactory appendLore(final Collection<String> loreToAppend) { if (this.lore == null) { return lore(loreToAppend instanceof List ? (List<String>) loreToAppend : new ArrayList<>(loreToAppend)); } this.lore.addAll(loreToAppend); return this; } /** * This method adds a String to the lore of the product. * If given a simple String, it will be added as new line. * If given a String containing newlines, it will split the input by {@code \n} and add each result String to the lore. * If the factory was constructed with a template item stack, this will be appended to its existing lore, if any. * * @param whatToAdd What to add to the future Lore of the product. * @return This object for chained calls. */ public ItemStackFactory lore(final String whatToAdd) { if (lore == null) { lore = new LinkedList<>(); } Collections.addAll(lore, whatToAdd.split("\n")); return this; } /** * Adds an enchmantment to the product. * * @param enchantment Enchantment to apply * @param level Level of the enchantment * @return This object, for chained calls. */ public ItemStackFactory enchant(final Enchantment enchantment, final int level) { base.addEnchantment(enchantment, level); return this; } /** * @param newData Future {@link org.bukkit.material.MaterialData} for the product. * @return This object for chained calls. */ public ItemStackFactory materialData(final MaterialData newData) { materialData = newData; return this; } /** * @param newData the future legacy, byte data value for the product * @return This object for chanined calls */ @SuppressWarnings("deprecation") @Deprecated public ItemStackFactory legacyData(final byte newData) { MaterialData data = base.getData(); data.setData(newData); materialData(data); return this; } /** * Convenience method for making wool stacks. * * @param color Future DyeColor of the product. * @return This object for chained calls. * @throws IllegalArgumentException If the base stack is not of material WOOL. * @see ItemStackFactory#materialData(org.bukkit.material.MaterialData) */ public ItemStackFactory woolColor(final DyeColor color) { Validate.isTrue(base.getType() == Material.WOOL, "Material of base stack must be WOOL (" + base.getType() + ')'); materialData = new Wool(color); return this; } /** * Convenience method for making colored leather armor. * * @param color Future DyeColor of the product. * @return This object for chained calls. * @throws IllegalArgumentException If the base stack is not leather armor. * @see ItemStackFactory#materialData(org.bukkit.material.MaterialData) */ public ItemStackFactory leatherArmorColor(final Color color) { if(meta == null) { meta = base.getItemMeta(); } Validate.isTrue(meta instanceof LeatherArmorMeta, "Base stack must be leather armor (" + base.getType() + ')'); ((LeatherArmorMeta) meta).setColor(color); return this; } /** * Convenience method for making player skulls. * * @param ownerName Future skull owner of the product. * @return This object for chained calls. * @throws IllegalArgumentException If the base stack is not of material SKULL_ITEM. * @see ItemStackFactory#materialData(org.bukkit.material.MaterialData) */ public ItemStackFactory skullOwner(final String ownerName) { Validate.isTrue(base.getType() == Material.SKULL_ITEM, "Material of base stack must be SKULL_ITEM (" + base.getType() + ')'); meta = base.getItemMeta(); ((SkullMeta) meta).setOwner(ownerName); return this; } public ItemStack produce() { final ItemStack product = new ItemStack(base); if (materialData != null) { product.setData(materialData); } if (displayName != null || lore != null) { final ItemMeta finalMeta = (meta == null ? product.getItemMeta() : meta); if (lore != null) { finalMeta.setLore(lore); } if (displayName != null) { finalMeta.setDisplayName(displayName); } product.setItemMeta(finalMeta); } return product; } @NotNull public ItemStack getBase() { return this.base; } public String getDisplayName() { return this.displayName; } public List<String> getLore() { return this.lore; } public MaterialData getMaterialData() { return this.materialData; } }
bukkit/src/main/java/io/github/xxyy/common/util/inventory/ItemStackFactory.java
/* * Copyright (c) 2013 - 2015 xxyy (Philipp Nowak; [email protected]). All rights reserved. * * Any usage, including, but not limited to, compiling, running, redistributing, printing, * copying and reverse-engineering is strictly prohibited without explicit written permission * from the original author and may result in legal steps being taken. * * See the included LICENSE file (core/src/main/resources) or email [email protected] for details. */ package io.github.xxyy.common.util.inventory; import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.material.MaterialData; import org.bukkit.material.Wool; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * This factory helps with creating {@link org.bukkit.inventory.ItemStack}s. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 30/01/14 */ @SuppressWarnings("UnusedDeclaration") public final class ItemStackFactory { @NotNull private final ItemStack base; private String displayName; private List<String> lore; private MaterialData materialData; private ItemMeta meta; /** * Creates a factory from a base {@link org.bukkit.inventory.ItemStack}. * * @param source Item stack to use as base for this factory. */ public ItemStackFactory(@NotNull final ItemStack source) { base = source; materialData = source.getData(); if (source.hasItemMeta()) { meta = source.getItemMeta(); if (meta.hasDisplayName()) { displayName = meta.getDisplayName(); } if (meta.hasLore()) { lore = meta.getLore(); } } } /** * Creates a factory by a {@link org.bukkit.Material}. * The resulting stack will have an amount of 1. * * @param material Material the product shall be * @see org.bukkit.inventory.ItemStack#ItemStack(org.bukkit.Material) */ public ItemStackFactory(final Material material) { base = new ItemStack(material); } /** * Sets the product's amount. * * @param newAmount New amount * @return This object for chained calls. */ public ItemStackFactory amount(final int newAmount) { base.setAmount(newAmount); return this; } /** * @param displayName Future display name of the product. * @return This object for chained calls. */ public ItemStackFactory displayName(final String displayName) { this.displayName = displayName; return this; } /** * Sets the display name of this factory if the resulting stack would not have a custom display name. * @param defaultDisplayName the display name to ste * @return this object */ public ItemStackFactory defaultDisplayName(final String defaultDisplayName) { if (!(base.hasItemMeta() && base.getItemMeta().hasDisplayName()) || displayName == null) { return displayName(defaultDisplayName); } return this; } /** * Sets the resulting item stack's lore, overriding any previous values. * * @param lore Future lore of the product. * @return This object for chained calls. */ public ItemStackFactory lore(final List<String> lore) { this.lore = lore; return this; } /** * Appends a collection of strings to the resulting item stack's lore, treating every element as a separate line. * If this factory was constructed with a template item stack, this method will append to its existing lore, if any. * @param loreToAppend the lines to add to the lore * @return this object */ public ItemStackFactory appendLore(final Collection<String> loreToAppend) { if (this.lore == null) { return lore(loreToAppend instanceof List ? (List<String>) loreToAppend : new ArrayList<>(loreToAppend)); } this.lore.addAll(loreToAppend); return this; } /** * This method adds a String to the lore of the product. * If given a simple String, it will be added as new line. * If given a String containing newlines, it will split the input by {@code \n} and add each result String to the lore. * If the factory was constructed with a template item stack, this will be appended to its existing lore, if any. * * @param whatToAdd What to add to the future Lore of the product. * @return This object for chained calls. */ public ItemStackFactory lore(final String whatToAdd) { if (lore == null) { lore = new LinkedList<>(); } Collections.addAll(lore, whatToAdd.split("\n")); return this; } /** * Adds an enchmantment to the product. * * @param enchantment Enchantment to apply * @param level Level of the enchantment * @return This object, for chained calls. */ public ItemStackFactory enchant(final Enchantment enchantment, final int level) { base.addEnchantment(enchantment, level); return this; } /** * @param newData Future {@link org.bukkit.material.MaterialData} for the product. * @return This object for chained calls. */ public ItemStackFactory materialData(final MaterialData newData) { materialData = newData; return this; } /** * Convenience method for making wool stacks. * * @param color Future DyeColor of the product. * @return This object for chained calls. * @throws IllegalArgumentException If the base stack is not of material WOOL. * @see ItemStackFactory#materialData(org.bukkit.material.MaterialData) */ public ItemStackFactory woolColor(final DyeColor color) { Validate.isTrue(base.getType() == Material.WOOL, "Material of base stack must be WOOL (" + base.getType() + ')'); materialData = new Wool(color); return this; } /** * Convenience method for making colored leather armor. * * @param color Future DyeColor of the product. * @return This object for chained calls. * @throws IllegalArgumentException If the base stack is not leather armor. * @see ItemStackFactory#materialData(org.bukkit.material.MaterialData) */ public ItemStackFactory leatherArmorColor(final Color color) { if(meta == null) { meta = base.getItemMeta(); } Validate.isTrue(meta instanceof LeatherArmorMeta, "Base stack must be leather armor (" + base.getType() + ')'); ((LeatherArmorMeta) meta).setColor(color); return this; } /** * Convenience method for making player skulls. * * @param ownerName Future skull owner of the product. * @return This object for chained calls. * @throws IllegalArgumentException If the base stack is not of material SKULL_ITEM. * @see ItemStackFactory#materialData(org.bukkit.material.MaterialData) */ public ItemStackFactory skullOwner(final String ownerName) { Validate.isTrue(base.getType() == Material.SKULL_ITEM, "Material of base stack must be SKULL_ITEM (" + base.getType() + ')'); meta = base.getItemMeta(); ((SkullMeta) meta).setOwner(ownerName); return this; } public ItemStack produce() { final ItemStack product = new ItemStack(base); if (materialData != null) { product.setData(materialData); } if (displayName != null || lore != null) { final ItemMeta finalMeta = (meta == null ? product.getItemMeta() : meta); if (lore != null) { finalMeta.setLore(lore); } if (displayName != null) { finalMeta.setDisplayName(displayName); } product.setItemMeta(finalMeta); } return product; } @NotNull public ItemStack getBase() { return this.base; } public String getDisplayName() { return this.displayName; } public List<String> getLore() { return this.lore; } public MaterialData getMaterialData() { return this.materialData; } }
Add legacyData(byte) method to ItemStackFactory
bukkit/src/main/java/io/github/xxyy/common/util/inventory/ItemStackFactory.java
Add legacyData(byte) method to ItemStackFactory
<ide><path>ukkit/src/main/java/io/github/xxyy/common/util/inventory/ItemStackFactory.java <ide> } <ide> <ide> /** <add> * @param newData the future legacy, byte data value for the product <add> * @return This object for chanined calls <add> */ <add> @SuppressWarnings("deprecation") <add> @Deprecated <add> public ItemStackFactory legacyData(final byte newData) { <add> MaterialData data = base.getData(); <add> data.setData(newData); <add> materialData(data); <add> <add> return this; <add> } <add> <add> /** <ide> * Convenience method for making wool stacks. <ide> * <ide> * @param color Future DyeColor of the product.
Java
mit
9782e7b7dbad24ae2eda080e4607eb265fa83eaa
0
AvaIre/AvaIre,AvaIre/AvaIre
package com.avairebot.orion.commands.utility; import com.avairebot.orion.AppInfo; import com.avairebot.orion.Orion; import com.avairebot.orion.Statistics; import com.avairebot.orion.cache.CacheType; import com.avairebot.orion.chat.MessageType; import com.avairebot.orion.contracts.commands.Command; import com.avairebot.orion.factories.MessageFactory; import com.google.gson.internal.LinkedTreeMap; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.MessageEmbed; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Collections; import java.util.List; public class StatsCommand extends Command { private final DecimalFormat number; private final DecimalFormat decimalNumber; public StatsCommand(Orion orion) { super(orion); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator('.'); decimalFormatSymbols.setGroupingSeparator(','); number = new DecimalFormat("#,##0", decimalFormatSymbols); decimalNumber = new DecimalFormat("#,##0.00", decimalFormatSymbols); } @Override public String getName() { return "Stats Command"; } @Override public String getDescription() { return "Tells you information about the bot itself."; } @Override public List<String> getUsageInstructions() { return Collections.singletonList("`:command` - Shows some stats about the bot."); } @Override public String getExampleUsage() { return null; } @Override public List<String> getTriggers() { return Arrays.asList("stats", "about"); } @Override public boolean onCommand(Message message, String[] args) { StringBuilder description = new StringBuilder("Created by [Senither#8023](https://senither.com/) using the [JDA](https://github.com/DV8FromTheWorld/JDA) framework!"); if (orion.getCache().getAdapter(CacheType.FILE).has("github.commits")) { description = new StringBuilder("**Latest changes:**\n"); List<LinkedTreeMap<String, Object>> items = (List<LinkedTreeMap<String, Object>>) orion.getCache().getAdapter(CacheType.FILE).get("github.commits"); for (int i = 0; i < 3; i++) { LinkedTreeMap<String, Object> item = items.get(i); LinkedTreeMap<String, Object> commit = (LinkedTreeMap<String, Object>) item.get("commit"); description.append(String.format("[`%s`](%s) %s\n", item.get("sha").toString().substring(0, 7), item.get("html_url"), commit.get("message") )); } } message.getChannel().sendMessage( MessageFactory.makeEmbeddedMessage(MessageType.INFO, new MessageEmbed.Field("Author", "Senither#8023", true), new MessageEmbed.Field("Bot ID", message.getJDA().getSelfUser().getId(), true), new MessageEmbed.Field("Library", "[JDA](https://github.com/DV8FromTheWorld/JDA)", true), new MessageEmbed.Field("DB Queries run", getDatabaseQueriesStats(), true), new MessageEmbed.Field("Messages Received", getMessagesReceivedStats(), true), new MessageEmbed.Field("Shard", "" + message.getJDA().getShardInfo().getShardId(), true), new MessageEmbed.Field("Commands Run", number.format(Statistics.getCommands()), true), new MessageEmbed.Field("Memory Usage", memoryUsage(), true), new MessageEmbed.Field("Uptime", applicationUptime(), true), new MessageEmbed.Field("Members", number.format(orion.getShardEntityCounter().getUsers()), true), new MessageEmbed.Field("Channels", number.format(orion.getShardEntityCounter().getChannels()), true), new MessageEmbed.Field("Servers", number.format(orion.getShardEntityCounter().getGuilds()), true) ) .setTitle("Official Bot Server Invite", "https://discordapp.com/invite/gt2FWER") .setAuthor("Orion v" + AppInfo.getAppInfo().VERSION, "https://discordapp.com/invite/gt2FWER", orion.getSelfUser().getEffectiveAvatarUrl()) .setDescription(description.toString()) .build() ).queue(); return true; } private String applicationUptime() { RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); long seconds = rb.getUptime() / 1000; long d = (long) Math.floor(seconds / 86400); long h = (long) Math.floor((seconds % 86400) / 3600); long m = (long) Math.floor(((seconds % 86400) % 3600) / 60); long s = (long) Math.floor(((seconds % 86400) % 3600) % 60); if (d > 0) { return String.format("%sd %sh %sm %ss", d, h, m, s); } if (h > 0) { return String.format("%sh %sm %ss", h, m, s); } if (m > 0) { return String.format("%sm %ss", m, s); } return String.format("%ss", s); } private String getDatabaseQueriesStats() { return String.format("%s (%s per min)", number.format(Statistics.getQueries()), decimalNumber.format(Statistics.getQueries() / ((double) ManagementFactory.getRuntimeMXBean().getUptime() / (double) (1000 * 60))) ); } private String getMessagesReceivedStats() { return String.format("%s (%s per sec)", number.format(Statistics.getMessages()), decimalNumber.format(Statistics.getMessages() / ((double) ManagementFactory.getRuntimeMXBean().getUptime() / (double) (1000))) ); } private String memoryUsage() { return String.format("%sMb / %sMb", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024), Runtime.getRuntime().totalMemory() / (1024 * 1024) ); } }
src/main/java/com/avairebot/orion/commands/utility/StatsCommand.java
package com.avairebot.orion.commands.utility; import com.avairebot.orion.AppInfo; import com.avairebot.orion.Orion; import com.avairebot.orion.Statistics; import com.avairebot.orion.cache.CacheType; import com.avairebot.orion.chat.MessageType; import com.avairebot.orion.contracts.commands.Command; import com.avairebot.orion.factories.MessageFactory; import com.google.gson.internal.LinkedTreeMap; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.MessageEmbed; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Collections; import java.util.List; public class StatsCommand extends Command { private final DecimalFormat number; private final DecimalFormat decimalNumber; public StatsCommand(Orion orion) { super(orion); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator('.'); decimalFormatSymbols.setGroupingSeparator(','); number = new DecimalFormat("#,##0", decimalFormatSymbols); decimalNumber = new DecimalFormat("#,##0.00", decimalFormatSymbols); } @Override public String getName() { return "Stats Command"; } @Override public String getDescription() { return "Tells you information about the bot itself."; } @Override public List<String> getUsageInstructions() { return Collections.singletonList("`:command` - Shows some stats about the bot."); } @Override public String getExampleUsage() { return null; } @Override public List<String> getTriggers() { return Arrays.asList("stats", "about"); } @Override public boolean onCommand(Message message, String[] args) { StringBuilder description = new StringBuilder("Created by [Senither#8023](https://senither.com/) using the [JDA](https://github.com/DV8FromTheWorld/JDA) framework!"); if (orion.getCache().getAdapter(CacheType.FILE).has("github.commits")) { description = new StringBuilder("**Latest changes:**\n"); List<LinkedTreeMap<String, Object>> items = (List<LinkedTreeMap<String, Object>>) orion.getCache().getAdapter(CacheType.FILE).get("github.commits"); for (int i = 0; i < 3; i++) { LinkedTreeMap<String, Object> item = items.get(i); LinkedTreeMap<String, Object> commit = (LinkedTreeMap<String, Object>) item.get("commit"); description.append(String.format("[`%s`](%s) %s\n", item.get("sha").toString().substring(0, 7), item.get("html_url"), commit.get("message") )); } } message.getChannel().sendMessage( MessageFactory.makeEmbeddedMessage(MessageType.INFO, new MessageEmbed.Field("Author", "Senither#8023", true), new MessageEmbed.Field("Bot ID", message.getJDA().getSelfUser().getId(), true), new MessageEmbed.Field("Library", "[JDA](https://github.com/DV8FromTheWorld/JDA)", true), new MessageEmbed.Field("DB Queries run", getDatabaseQueriesStats(), true), new MessageEmbed.Field("Messages Received", getMessagesReceivedStats(), true), new MessageEmbed.Field("Shard", "" + (message.getJDA().getShardInfo().getShardId() + 1), true), new MessageEmbed.Field("Commands Run", number.format(Statistics.getCommands()), true), new MessageEmbed.Field("Memory Usage", memoryUsage(), true), new MessageEmbed.Field("Uptime", applicationUptime(), true), new MessageEmbed.Field("Members", number.format(orion.getShardEntityCounter().getUsers()), true), new MessageEmbed.Field("Channels", number.format(orion.getShardEntityCounter().getChannels()), true), new MessageEmbed.Field("Servers", number.format(message.getJDA().getGuilds().size()), true) ) .setTitle("Official Bot Server Invite", "https://discordapp.com/invite/gt2FWER") .setAuthor("Orion v" + AppInfo.getAppInfo().VERSION, "https://discordapp.com/invite/gt2FWER", orion.getSelfUser().getEffectiveAvatarUrl()) .setDescription(description.toString()) .build() ).queue(); return true; } private String applicationUptime() { RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); long seconds = rb.getUptime() / 1000; long d = (long) Math.floor(seconds / 86400); long h = (long) Math.floor((seconds % 86400) / 3600); long m = (long) Math.floor(((seconds % 86400) % 3600) / 60); long s = (long) Math.floor(((seconds % 86400) % 3600) % 60); if (d > 0) { return String.format("%sd %sh %sm %ss", d, h, m, s); } if (h > 0) { return String.format("%sh %sm %ss", h, m, s); } if (m > 0) { return String.format("%sm %ss", m, s); } return String.format("%ss", s); } private String getDatabaseQueriesStats() { return String.format("%s (%s per min)", number.format(Statistics.getQueries()), decimalNumber.format(Statistics.getQueries() / ((double) ManagementFactory.getRuntimeMXBean().getUptime() / (double) (1000 * 60))) ); } private String getMessagesReceivedStats() { return String.format("%s (%s per sec)", number.format(Statistics.getMessages()), decimalNumber.format(Statistics.getMessages() / ((double) ManagementFactory.getRuntimeMXBean().getUptime() / (double) (1000))) ); } private String memoryUsage() { return String.format("%sMb / %sMb", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024), Runtime.getRuntime().totalMemory() / (1024 * 1024) ); } }
Fix stats command guild count in sharded mode
src/main/java/com/avairebot/orion/commands/utility/StatsCommand.java
Fix stats command guild count in sharded mode
<ide><path>rc/main/java/com/avairebot/orion/commands/utility/StatsCommand.java <ide> new MessageEmbed.Field("Library", "[JDA](https://github.com/DV8FromTheWorld/JDA)", true), <ide> new MessageEmbed.Field("DB Queries run", getDatabaseQueriesStats(), true), <ide> new MessageEmbed.Field("Messages Received", getMessagesReceivedStats(), true), <del> new MessageEmbed.Field("Shard", "" + (message.getJDA().getShardInfo().getShardId() + 1), true), <add> new MessageEmbed.Field("Shard", "" + message.getJDA().getShardInfo().getShardId(), true), <ide> new MessageEmbed.Field("Commands Run", number.format(Statistics.getCommands()), true), <ide> new MessageEmbed.Field("Memory Usage", memoryUsage(), true), <ide> new MessageEmbed.Field("Uptime", applicationUptime(), true), <ide> new MessageEmbed.Field("Members", number.format(orion.getShardEntityCounter().getUsers()), true), <ide> new MessageEmbed.Field("Channels", number.format(orion.getShardEntityCounter().getChannels()), true), <del> new MessageEmbed.Field("Servers", number.format(message.getJDA().getGuilds().size()), true) <add> new MessageEmbed.Field("Servers", number.format(orion.getShardEntityCounter().getGuilds()), true) <ide> ) <ide> .setTitle("Official Bot Server Invite", "https://discordapp.com/invite/gt2FWER") <ide> .setAuthor("Orion v" + AppInfo.getAppInfo().VERSION, "https://discordapp.com/invite/gt2FWER", orion.getSelfUser().getEffectiveAvatarUrl())
Java
apache-2.0
d8de857c7dc5ad06d24026193805aa4e9214bece
0
torito/wisdom,evrignaud/wisdom,CRDNicolasBourbaki/wisdom,gdelafosse/wisdom,torito/wisdom,gdelafosse/wisdom,evrignaud/wisdom,cheleb/wisdom,cheleb/wisdom,wisdom-framework/wisdom,CRDNicolasBourbaki/wisdom,evrignaud/wisdom,gdelafosse/wisdom,cheleb/wisdom,wisdom-framework/wisdom,torito/wisdom,wisdom-framework/wisdom,wisdom-framework/wisdom,CRDNicolasBourbaki/wisdom,gdelafosse/wisdom
package org.ow2.chameleon.wisdom.maven.utils; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteStreamHandler; import org.apache.commons.exec.PumpStreamHandler; import org.apache.maven.plugin.MojoExecutionException; import org.ow2.chameleon.wisdom.maven.mojos.AbstractWisdomMojo; import java.io.File; import java.io.IOException; /** * Launch the Wisdom Executor. */ public class WisdomExecutor { public static final String CHAMELEON_VERSION = "1.0.1"; public void execute(AbstractWisdomMojo mojo) throws MojoExecutionException { // Get java File java = ExecutableFinder.find("java", new File(mojo.javaHome, "bin")); if (java == null) { throw new MojoExecutionException("Cannot find the java executable"); } CommandLine cmdLine = new CommandLine(java); cmdLine.addArgument("-jar"); cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWorkingDirectory(mojo.getWisdomRootDirectory()); executor.setStreamHandler(new PumpStreamHandler()); try { mojo.getLog().info("Launching Wisdom Server"); mojo.getLog().info("Hit ctrl+c to exit"); // Block execution until ctrl+c executor.execute(cmdLine); } catch (IOException e) { throw new MojoExecutionException("Cannot execute Wisdom", e); } } }
wisdom-maven-plugin/src/main/java/org/ow2/chameleon/wisdom/maven/utils/WisdomExecutor.java
package org.ow2.chameleon.wisdom.maven.utils; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteStreamHandler; import org.apache.commons.exec.PumpStreamHandler; import org.apache.maven.plugin.MojoExecutionException; import org.ow2.chameleon.wisdom.maven.mojos.AbstractWisdomMojo; import java.io.File; import java.io.IOException; /** * Launch the Wisdom Executor. */ public class WisdomExecutor { public static final String CHAMELEON_VERSION = "1.0.0-SNAPSHOT"; public void execute(AbstractWisdomMojo mojo) throws MojoExecutionException { // Get java File java = ExecutableFinder.find("java", new File(mojo.javaHome, "bin")); if (java == null) { throw new MojoExecutionException("Cannot find the java executable"); } CommandLine cmdLine = new CommandLine(java); cmdLine.addArgument("-jar"); cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWorkingDirectory(mojo.getWisdomRootDirectory()); executor.setStreamHandler(new PumpStreamHandler()); try { mojo.getLog().info("Launching Wisdom Server"); mojo.getLog().info("Hit ctrl+c to exit"); // Block execution until ctrl+c executor.execute(cmdLine); } catch (IOException e) { throw new MojoExecutionException("Cannot execute Wisdom", e); } } }
Update chameleon version to 1.0.1 Signed-off-by: Clement Escoffier <[email protected]>
wisdom-maven-plugin/src/main/java/org/ow2/chameleon/wisdom/maven/utils/WisdomExecutor.java
Update chameleon version to 1.0.1
<ide><path>isdom-maven-plugin/src/main/java/org/ow2/chameleon/wisdom/maven/utils/WisdomExecutor.java <ide> * Launch the Wisdom Executor. <ide> */ <ide> public class WisdomExecutor { <del> public static final String CHAMELEON_VERSION = "1.0.0-SNAPSHOT"; <add> public static final String CHAMELEON_VERSION = "1.0.1"; <ide> <ide> public void execute(AbstractWisdomMojo mojo) throws MojoExecutionException { <ide> // Get java
Java
apache-2.0
error: pathspec 'bundle/src/main/java/com/adobe/acs/samples/jobs/impl/SampleEventHandlerAndImmediateJobExecution.java' did not match any file(s) known to git
9f65dce5be716289c06a5a9fb3fe186c8e91e612
1
Adobe-Consulting-Services/acs-aem-samples,Adobe-Consulting-Services/acs-aem-samples,Adobe-Consulting-Services/acs-aem-samples
package com.adobe.acs.samples.jobs.impl; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingConstants; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.commons.scheduler.ScheduleOptions; import org.apache.sling.commons.scheduler.Scheduler; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Map; @Component @Properties({ /** * Use the normal @Property annotations to define which event topics to listen to, and filter in events */ @Property( label = "Event Topics", value = {SlingConstants.TOPIC_RESOURCE_CHANGED}, description = "[Required] Event Topics this event handler will to respond to.", name = EventConstants.EVENT_TOPIC, propertyPrivate = true ), /* Event filters support LDAP filter syntax and have access to event.getProperty(..) values */ /* LDAP Query syntax: https://goo.gl/MCX2or */ @Property( label = "Event Filters", // Only listen on events associated with nodes that end with /jcr:content value = "(path=*/jcr:content)", description = "[Optional] Event Filters used to further restrict this event handler; Uses LDAP expression against event properties.", name = EventConstants.EVENT_FILTER, propertyPrivate = true ) }) @Service public class SampleEventHandlerAndImmediateJobExecution implements EventHandler { private static final Logger log = LoggerFactory.getLogger(SampleEventHandlerAndImmediateJobExecution.class); // Since this is a back-end service, its likely you will need to interact w the JCR. To do this, use the // ResourceResolverFactory to get the appropriate service user for this job. @Reference private ResourceResolverFactory resourceResolverFactory; // The Sling Scheduler will be used to create an immediate job @Reference private Scheduler scheduler; @Override public void handleEvent(Event event) { /* NOTE: HANDLE EVENT MUST COMPLETE QUICKLY ELSE THE EVENT HANDLER MAY BE BLACKLISTED */ // properties passed along w the event can be retrieved. // Apache Felix shows events and their properties: http://localhost:4502/system/console/events String path = (String) event.getProperty("path"); // Perform any fast checks here that you cant perform via Event Filtering above // Create schedule options that executes immediately (aka NOW()) ScheduleOptions options = scheduler.NOW(); // Assign a "unique" name for this job String jobName = this.getClass().getSimpleName().toString().replace(".", "/") + "/" + path; // This jobName would be like: com/adobe/acs/samples/jobs/impl/SampleEventHandlerAndImmediateJobExecution/content/my-site/some-page/jcr:content options.name(jobName); // Note the job name is what determines is a job is considered running concurrently. // In this case, we do not want to process the same resource at the same time, so the jobName options.canRunConcurrently(false); // Create a new job object (must be runnable). ImmediateJob job = new ImmediateJob(path); // Create and schedule the job scheduler.schedule(job, options); } /** * ImmediateJob is an inner class that implements Runnable. * * The benefit of making this an inner class is it allows access ot OSGi services @Reference'd, and consolidates * the logic into a single file. */ private class ImmediateJob implements Runnable { private final String path; /** * The constructor can be used to pass in serializable state that will be used during the Job processing. * * @param path example parameter passed in from the event */ public ImmediateJob(String path) { // Maintain job state this.path = path; } /** * Run is the entry point for initiating the work to be done by this job. * The Sling job management mechanism will call run() to process the job. */ @Override public void run() { final Map<String, Object> authInfo = Collections.singletonMap( ResourceResolverFactory.SUBSERVICE, (Object) "my-service-account"); ResourceResolver resourceResolver = null; try { // Always use service users; never admin resource resolvers for "real" code resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo); // Access data passed into the Job from the Event Resource resource = resourceResolver.getResource(path); if (resource != null) { ValueMap properties = resource.getValueMap(); // Do some work w this resource.. } } catch (LoginException e) { log.error("Could not get service resolver", e); } finally { // Always close resource resolvers you open if (resourceResolver != null) { resourceResolver.close(); } } } } }
bundle/src/main/java/com/adobe/acs/samples/jobs/impl/SampleEventHandlerAndImmediateJobExecution.java
Sample Event Handler and Immediate Job Execution sample
bundle/src/main/java/com/adobe/acs/samples/jobs/impl/SampleEventHandlerAndImmediateJobExecution.java
Sample Event Handler and Immediate Job Execution sample
<ide><path>undle/src/main/java/com/adobe/acs/samples/jobs/impl/SampleEventHandlerAndImmediateJobExecution.java <add>package com.adobe.acs.samples.jobs.impl; <add> <add>import org.apache.felix.scr.annotations.Component; <add>import org.apache.felix.scr.annotations.Properties; <add>import org.apache.felix.scr.annotations.Property; <add>import org.apache.felix.scr.annotations.Reference; <add>import org.apache.felix.scr.annotations.Service; <add>import org.apache.sling.api.SlingConstants; <add>import org.apache.sling.api.resource.LoginException; <add>import org.apache.sling.api.resource.Resource; <add>import org.apache.sling.api.resource.ResourceResolver; <add>import org.apache.sling.api.resource.ResourceResolverFactory; <add>import org.apache.sling.api.resource.ValueMap; <add>import org.apache.sling.commons.scheduler.ScheduleOptions; <add>import org.apache.sling.commons.scheduler.Scheduler; <add>import org.osgi.service.event.Event; <add>import org.osgi.service.event.EventConstants; <add>import org.osgi.service.event.EventHandler; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add> <add>import java.util.Collections; <add>import java.util.Map; <add> <add>@Component <add>@Properties({ <add> /** <add> * Use the normal @Property annotations to define which event topics to listen to, and filter in events <add> */ <add> @Property( <add> label = "Event Topics", <add> value = {SlingConstants.TOPIC_RESOURCE_CHANGED}, <add> description = "[Required] Event Topics this event handler will to respond to.", <add> name = EventConstants.EVENT_TOPIC, <add> propertyPrivate = true <add> ), <add> /* Event filters support LDAP filter syntax and have access to event.getProperty(..) values */ <add> /* LDAP Query syntax: https://goo.gl/MCX2or */ <add> @Property( <add> label = "Event Filters", <add> // Only listen on events associated with nodes that end with /jcr:content <add> value = "(path=*/jcr:content)", <add> description = "[Optional] Event Filters used to further restrict this event handler; Uses LDAP expression against event properties.", <add> name = EventConstants.EVENT_FILTER, <add> propertyPrivate = true <add> ) <add>}) <add>@Service <add>public class SampleEventHandlerAndImmediateJobExecution implements EventHandler { <add> private static final Logger log = LoggerFactory.getLogger(SampleEventHandlerAndImmediateJobExecution.class); <add> <add> // Since this is a back-end service, its likely you will need to interact w the JCR. To do this, use the <add> // ResourceResolverFactory to get the appropriate service user for this job. <add> @Reference <add> private ResourceResolverFactory resourceResolverFactory; <add> <add> // The Sling Scheduler will be used to create an immediate job <add> @Reference <add> private Scheduler scheduler; <add> <add> @Override <add> public void handleEvent(Event event) { <add> /* NOTE: HANDLE EVENT MUST COMPLETE QUICKLY ELSE THE EVENT HANDLER MAY BE BLACKLISTED */ <add> <add> // properties passed along w the event can be retrieved. <add> // Apache Felix shows events and their properties: http://localhost:4502/system/console/events <add> String path = (String) event.getProperty("path"); <add> <add> // Perform any fast checks here that you cant perform via Event Filtering above <add> <add> // Create schedule options that executes immediately (aka NOW()) <add> ScheduleOptions options = scheduler.NOW(); <add> // Assign a "unique" name for this job <add> <add> String jobName = this.getClass().getSimpleName().toString().replace(".", "/") + "/" + path; <add> // This jobName would be like: com/adobe/acs/samples/jobs/impl/SampleEventHandlerAndImmediateJobExecution/content/my-site/some-page/jcr:content <add> options.name(jobName); <add> <add> // Note the job name is what determines is a job is considered running concurrently. <add> // In this case, we do not want to process the same resource at the same time, so the jobName <add> options.canRunConcurrently(false); <add> <add> // Create a new job object (must be runnable). <add> ImmediateJob job = new ImmediateJob(path); <add> <add> // Create and schedule the job <add> scheduler.schedule(job, options); <add> } <add> <add> /** <add> * ImmediateJob is an inner class that implements Runnable. <add> * <add> * The benefit of making this an inner class is it allows access ot OSGi services @Reference'd, and consolidates <add> * the logic into a single file. <add> */ <add> private class ImmediateJob implements Runnable { <add> private final String path; <add> <add> /** <add> * The constructor can be used to pass in serializable state that will be used during the Job processing. <add> * <add> * @param path example parameter passed in from the event <add> */ <add> public ImmediateJob(String path) { <add> // Maintain job state <add> this.path = path; <add> } <add> <add> /** <add> * Run is the entry point for initiating the work to be done by this job. <add> * The Sling job management mechanism will call run() to process the job. <add> */ <add> @Override <add> public void run() { <add> final Map<String, Object> authInfo = Collections.singletonMap( <add> ResourceResolverFactory.SUBSERVICE, <add> (Object) "my-service-account"); <add> <add> ResourceResolver resourceResolver = null; <add> try { <add> // Always use service users; never admin resource resolvers for "real" code <add> resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo); <add> <add> // Access data passed into the Job from the Event <add> Resource resource = resourceResolver.getResource(path); <add> <add> if (resource != null) { <add> ValueMap properties = resource.getValueMap(); <add> // Do some work w this resource.. <add> } <add> } catch (LoginException e) { <add> log.error("Could not get service resolver", e); <add> } finally { <add> // Always close resource resolvers you open <add> if (resourceResolver != null) { <add> resourceResolver.close(); <add> } <add> } <add> } <add> } <add>}
Java
apache-2.0
87722056926bc167d1bf61a45b7d5116e58b81da
0
zangsir/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.paging; import com.vaadin.ui.themes.ChameleonTheme; import com.vaadin.data.Validator; import com.vaadin.data.validator.AbstractStringValidator; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.server.ThemeResource; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.LoggerFactory; import org.w3c.dom.Text; /** * * @author thomas */ public class PagingComponent extends CustomComponent implements Button.ClickListener { private static final org.slf4j.Logger log = LoggerFactory.getLogger( PagingComponent.class); public static final ThemeResource LEFT_ARROW = new ThemeResource( "left_arrow.png"); public static final ThemeResource RIGHT_ARROW = new ThemeResource( "right_arrow.png"); public static final ThemeResource FIRST = new ThemeResource("first.png"); public static final ThemeResource LAST = new ThemeResource("last.png"); private HorizontalLayout layout; private Button btFirst; private Button btLast; private Button btNext; private Button btPrevious; private TextField txtPage; private Label lblMaxPages; private Label lblStatus; private Set<PagingCallback> callbacks; private AtomicInteger count; private int pageSize; private int currentPage; private Label lblInfo; public PagingComponent(int count, int pageSize) { if (pageSize <= 0) { pageSize = 1; } if (count < 0) { count = 0; } currentPage = 1; this.count = new AtomicInteger(pageSize); this.pageSize = pageSize; setWidth("100%"); setHeight("-1px"); addStyleName("toolbar"); callbacks = new HashSet<PagingCallback>(); layout = new HorizontalLayout(); layout.setSpacing(true); layout.setMargin(new MarginInfo(false, true, false, true)); setCompositionRoot(layout); lblInfo = new Label(); lblInfo.setContentMode(ContentMode.HTML); lblInfo.addStyleName("right-aligned-text"); layout.setWidth("100%"); layout.setHeight("-1px"); btFirst = new Button(); btFirst.setIcon(FIRST); btFirst.setDescription("jump to first page"); btFirst.addClickListener((Button.ClickListener) this); btFirst.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btFirst.addStyleName(ChameleonTheme.BUTTON_SMALL); btLast = new Button(); btLast.setIcon(LAST); btLast.setDescription("jump to last page"); btLast.addClickListener((Button.ClickListener) this); btLast.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btLast.addStyleName(ChameleonTheme.BUTTON_SMALL); btNext = new Button(); btNext.setIcon(RIGHT_ARROW); btNext.setDescription("jump to next page"); btNext.addClickListener((Button.ClickListener) this); btNext.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btNext.addStyleName(ChameleonTheme.BUTTON_SMALL); btPrevious = new Button(); btPrevious.setIcon(LEFT_ARROW); btPrevious.setDescription("jump to previous page"); btPrevious.addClickListener((Button.ClickListener) this); btPrevious.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btPrevious.addStyleName(ChameleonTheme.BUTTON_SMALL); txtPage = new TextField(); txtPage.setDescription("current page"); txtPage.setHeight("-1px"); txtPage.setWidth(3.f, UNITS_EM); Validator pageValidator = new PageValidator( "must be an integer greater than zero"); txtPage.addValidator(pageValidator); txtPage.addShortcutListener(new EnterListener(txtPage)); lblMaxPages = new Label(); lblMaxPages.setDescription("maximal pages"); lblMaxPages.setSizeUndefined(); lblStatus = new Label(); lblStatus.setSizeUndefined(); layout.addComponent(btFirst); layout.addComponent(btPrevious); layout.addComponent(txtPage); layout.addComponent(lblMaxPages); layout.addComponent(btNext); layout.addComponent(btLast); layout.addComponent(lblStatus); layout.addComponent(lblInfo); layout.setComponentAlignment(btFirst, Alignment.MIDDLE_LEFT); layout.setComponentAlignment(btPrevious, Alignment.MIDDLE_LEFT); layout.setComponentAlignment(lblStatus, Alignment.MIDDLE_LEFT); layout.setComponentAlignment(lblMaxPages, Alignment.MIDDLE_CENTER); layout.setComponentAlignment(txtPage, Alignment.MIDDLE_RIGHT); layout.setComponentAlignment(btNext, Alignment.MIDDLE_RIGHT); layout.setComponentAlignment(btLast, Alignment.MIDDLE_RIGHT); layout.setExpandRatio(lblStatus, 1.0f); layout.setComponentAlignment(lblInfo, Alignment.MIDDLE_RIGHT); layout.setExpandRatio(lblInfo, 10.0f); update(false); } private void update(boolean informCallbacks) { int myCount = count.get(); txtPage.setValue("" + currentPage); lblMaxPages.setValue("/ " + getMaxPage()); lblStatus.setValue("Displaying Results " + (getStartNumber() + 1) + " - " + Math.min(getStartNumber() + pageSize, myCount) + " of " + myCount); btFirst.setEnabled(currentPage > 1); btPrevious.setEnabled(currentPage > 1); btLast.setEnabled(currentPage < getMaxPage()); btNext.setEnabled(currentPage < getMaxPage()); if (informCallbacks) { for (PagingCallback c : callbacks) { c.switchPage(getStartNumber(), pageSize); } } } public void addCallback(PagingCallback callback) { callbacks.add(callback); } public boolean removeCallback(PagingCallback callback) { return callbacks.remove(callback); } public int getMaxPage() { int mycount = Math.max(0, count.get() - 1); return (1 + (mycount / pageSize)); } public int getStartNumber() { return (currentPage - 1) * pageSize; } public void setStartNumber(int startNumber) { currentPage = (startNumber / pageSize) + 1; update(false); } public int getCount() { return count.get(); } public void setCount(int count, boolean update) { if (count < 0) { count = 0; } this.count.set(count); update(update); } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if (pageSize <= 0) { pageSize = 1; } this.pageSize = pageSize; update(true); } @Override public void buttonClick(ClickEvent event) { if (event.getButton() == btFirst) { currentPage = 1; } else if (event.getButton() == btLast) { currentPage = getMaxPage(); } else if (event.getButton() == btNext) { currentPage++; } else if (event.getButton() == btPrevious) { currentPage--; } // sanitize currentPage = sanitizePage(currentPage); update(true); } private int sanitizePage(int page) { int val = Math.max(1, page); val = Math.min(1 + (count.get() / pageSize), val); return val; } public class EnterListener extends ShortcutListener { private Object registeredTarget; public EnterListener(Object registeredTarget) { super("set page", KeyCode.ENTER, null); this.registeredTarget = registeredTarget; } @Override public void handleAction(Object sender, Object target) { if (target != registeredTarget) { return; } try { int newPage = Integer.parseInt((String) txtPage.getValue()); currentPage = sanitizePage(newPage); update(true); } catch (Exception ex) { log.error(null, ex); } } } /** * Cuts off long queries. Actually they are restricted to 50 characters. The * full query is available with descriptions (tooltip in gui) * * @param text the query to display in the result view panel */ public void setInfo(String text) { if (text != null && text.length() > 0) { String prefix = "Result for: <span class=\"corpus-font-force\">"; lblInfo.setDescription(prefix + text.replaceAll("\n", " ") + "</span>"); lblInfo.setValue(text.length() < 50 ? prefix + text.substring(0, text. length()) : prefix + text.substring(0, 50) + " ... </span>"); } } private static class PageValidator extends AbstractStringValidator { public PageValidator(String errorMessage) { super(errorMessage); } @Override protected boolean isValidValue(String value) { try { int v = Integer.parseInt(value); if (v > 0) { return true; } else { return false; } } catch (Exception ex) { return false; } } } }
annis-gui/src/main/java/annis/gui/paging/PagingComponent.java
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.paging; import com.vaadin.ui.themes.ChameleonTheme; import com.vaadin.data.Validator; import com.vaadin.data.validator.AbstractStringValidator; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.server.ThemeResource; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.LoggerFactory; import org.w3c.dom.Text; /** * * @author thomas */ public class PagingComponent extends CustomComponent implements Button.ClickListener { private static final org.slf4j.Logger log = LoggerFactory.getLogger( PagingComponent.class); public static final ThemeResource LEFT_ARROW = new ThemeResource( "left_arrow.png"); public static final ThemeResource RIGHT_ARROW = new ThemeResource( "right_arrow.png"); public static final ThemeResource FIRST = new ThemeResource("first.png"); public static final ThemeResource LAST = new ThemeResource("last.png"); private HorizontalLayout layout; private Button btFirst; private Button btLast; private Button btNext; private Button btPrevious; private TextField txtPage; private Label lblMaxPages; private Label lblStatus; private Set<PagingCallback> callbacks; private AtomicInteger count; private int pageSize; private int currentPage; private Label lblInfo; public PagingComponent(int count, int pageSize) { if (pageSize <= 0) { pageSize = 1; } if (count < 0) { count = 0; } currentPage = 1; this.count = new AtomicInteger(pageSize); this.pageSize = pageSize; setWidth("100%"); setHeight("-1px"); addStyleName("toolbar"); callbacks = new HashSet<PagingCallback>(); layout = new HorizontalLayout(); layout.setSpacing(true); layout.setMargin(new MarginInfo(false, true, false, true)); setCompositionRoot(layout); lblInfo = new Label(); lblInfo.setContentMode(ContentMode.HTML); lblInfo.addStyleName("right-aligned-text"); layout.setWidth("100%"); layout.setHeight("-1px"); btFirst = new Button(); btFirst.setIcon(FIRST); btFirst.setDescription("jump to first page"); btFirst.addClickListener((Button.ClickListener) this); btFirst.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btFirst.addStyleName(ChameleonTheme.BUTTON_SMALL); btLast = new Button(); btLast.setIcon(LAST); btLast.setDescription("jump to last page"); btLast.addClickListener((Button.ClickListener) this); btLast.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btLast.addStyleName(ChameleonTheme.BUTTON_SMALL); btNext = new Button(); btNext.setIcon(RIGHT_ARROW); btNext.setDescription("jump to next page"); btNext.addClickListener((Button.ClickListener) this); btNext.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btNext.addStyleName(ChameleonTheme.BUTTON_SMALL); btPrevious = new Button(); btPrevious.setIcon(LEFT_ARROW); btPrevious.setDescription("jump to previous page"); btPrevious.addClickListener((Button.ClickListener) this); btPrevious.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btPrevious.addStyleName(ChameleonTheme.BUTTON_SMALL); txtPage = new TextField(); txtPage.setDescription("current page"); txtPage.setHeight("-1px"); txtPage.setWidth(3.f, UNITS_EM); Validator pageValidator = new PageValidator( "must be an integer greater than zero"); txtPage.addValidator(pageValidator); txtPage.addShortcutListener(new EnterListener(txtPage)); lblMaxPages = new Label(); lblMaxPages.setDescription("maximal pages"); lblMaxPages.setSizeUndefined(); lblStatus = new Label(); lblStatus.setSizeUndefined(); layout.addComponent(btFirst); layout.addComponent(btPrevious); layout.addComponent(txtPage); layout.addComponent(lblMaxPages); layout.addComponent(btNext); layout.addComponent(btLast); layout.addComponent(lblStatus); layout.addComponent(lblInfo); layout.setComponentAlignment(btFirst, Alignment.MIDDLE_LEFT); layout.setComponentAlignment(btPrevious, Alignment.MIDDLE_LEFT); layout.setComponentAlignment(lblStatus, Alignment.MIDDLE_LEFT); layout.setComponentAlignment(lblMaxPages, Alignment.MIDDLE_CENTER); layout.setComponentAlignment(txtPage, Alignment.MIDDLE_RIGHT); layout.setComponentAlignment(btNext, Alignment.MIDDLE_RIGHT); layout.setComponentAlignment(btLast, Alignment.MIDDLE_RIGHT); layout.setExpandRatio(lblStatus, 1.0f); layout.setComponentAlignment(lblInfo, Alignment.MIDDLE_RIGHT); layout.setExpandRatio(lblInfo, 10.0f); update(false); } private void update(boolean informCallbacks) { int myCount = count.get(); txtPage.setValue("" + currentPage); lblMaxPages.setValue("/ " + getMaxPage()); lblStatus.setValue("Displaying Results " + (getStartNumber() + 1) + " - " + Math.min(getStartNumber() + pageSize, myCount) + " of " + myCount); btFirst.setEnabled(currentPage > 1); btPrevious.setEnabled(currentPage > 1); btLast.setEnabled(currentPage < getMaxPage()); btNext.setEnabled(currentPage < getMaxPage()); if (informCallbacks) { for (PagingCallback c : callbacks) { c.switchPage(getStartNumber(), pageSize); } } } public void addCallback(PagingCallback callback) { callbacks.add(callback); } public boolean removeCallback(PagingCallback callback) { return callbacks.remove(callback); } public int getMaxPage() { int mycount = Math.max(0, count.get() - 1); return (1 + (mycount / pageSize)); } public int getStartNumber() { return (currentPage - 1) * pageSize; } public void setStartNumber(int startNumber) { currentPage = (startNumber / pageSize) + 1; update(false); } public int getCount() { return count.get(); } public void setCount(int count, boolean update) { if (count < 0) { count = 0; } this.count.set(count); update(update); } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if (pageSize <= 0) { pageSize = 1; } this.pageSize = pageSize; update(true); } @Override public void buttonClick(ClickEvent event) { if (event.getButton() == btFirst) { currentPage = 1; } else if (event.getButton() == btLast) { currentPage = getMaxPage(); } else if (event.getButton() == btNext) { currentPage++; } else if (event.getButton() == btPrevious) { currentPage--; } // sanitize currentPage = sanitizePage(currentPage); update(true); } private int sanitizePage(int page) { int val = Math.max(1, page); val = Math.min(1 + (count.get() / pageSize), val); return val; } public class EnterListener extends ShortcutListener { private Object registeredTarget; public EnterListener(Object registeredTarget) { super("set page", KeyCode.ENTER, null); this.registeredTarget = registeredTarget; } @Override public void handleAction(Object sender, Object target) { if (target != registeredTarget) { return; } try { int newPage = Integer.parseInt((String) txtPage.getValue()); currentPage = sanitizePage(newPage); update(true); } catch (Exception ex) { log.error(null, ex); } } } public void setInfo(String text) { StringBuilder sb = new StringBuilder(); sb.append("Result for \"<span class=\"corpus-font-force\">").append(text. replaceAll("\n", " ")); sb.append("</span>\""); lblInfo.setValue(sb.toString()); } private static class PageValidator extends AbstractStringValidator { public PageValidator(String errorMessage) { super(errorMessage); } @Override protected boolean isValidValue(String value) { try { int v = Integer.parseInt(value); if (v > 0) { return true; } else { return false; } } catch (Exception ex) { return false; } } } }
Restrict the characters of the "Result for:" label in the result view panel.
annis-gui/src/main/java/annis/gui/paging/PagingComponent.java
Restrict the characters of the "Result for:" label in the result view panel.
<ide><path>nnis-gui/src/main/java/annis/gui/paging/PagingComponent.java <ide> } <ide> } <ide> <add> /** <add> * Cuts off long queries. Actually they are restricted to 50 characters. The <add> * full query is available with descriptions (tooltip in gui) <add> * <add> * @param text the query to display in the result view panel <add> */ <ide> public void setInfo(String text) <ide> { <del> StringBuilder sb = new StringBuilder(); <del> sb.append("Result for \"<span class=\"corpus-font-force\">").append(text. <del> replaceAll("\n", " ")); <del> sb.append("</span>\""); <del> lblInfo.setValue(sb.toString()); <add> if (text != null && text.length() > 0) <add> { <add> String prefix = "Result for: <span class=\"corpus-font-force\">"; <add> lblInfo.setDescription(prefix + text.replaceAll("\n", " ") + "</span>"); <add> lblInfo.setValue(text.length() < 50 ? prefix + text.substring(0, text. <add> length()) : prefix + text.substring(0, 50) + " ... </span>"); <add> } <ide> } <ide> <ide> private static class PageValidator extends AbstractStringValidator
JavaScript
agpl-3.0
20a1fba82c3e2bf5127d426441f5ba6e11730d18
0
cnedDI/AccessiDys,cnedDI/AccessiDys,AccessiDys/AccessiDys,AccessiDys/AccessiDys
/* File: apercu.js * * Copyright (c) 2013-2016 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France * ([email protected]) * * GNU Affero General Public License (AGPL) version 3.0 or later version * * This file is part of a program which 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/>. * */ /*global $:false, spyOn:false, CKEDITOR:true */ 'use strict'; describe('Controller:ApercuCtrl', function () { var scope, controller, window, speechService, speechStopped, serviceCheck, deferred, fileStorageService, isOnlineServiceCheck, workspaceService, configuration, filesFound, lienPartage, mapNotes, logedServiceCheck, modal, modalParameters; var profilTags = [{ '__v': 0, '_id': '52fb65eb8856dce835c2ca87', 'coloration': 'Colorer les lignes', 'interligne': '18', 'police': 'opendyslexicregular', 'profil': '52d0598c563380592bc1d703', 'styleValue': 'Normal', 'tag': '52d0598c563380592bc1d704', 'tagName': 'Titre 01', 'taille': '12', 'texte': '<p data-font=\'opendyslexicregular\' data-size=\'12\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Colorer les lignes\'> </p>' }, { 'tag': '52c588a861485ed41c000001', 'texte': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\'> </p>', 'profil': '52d0598c563380592bc1d703', 'tagName': 'Solution', 'police': 'opendyslexicregular', 'taille': '14', 'interligne': '18', 'styleValue': 'Normal', 'coloration': 'Surligner les lignes', '_id': '52fb65eb8856dce835c2ca8d', '__v': 0 }, { 'tag': '52d0598c5633863243545676', 'texte': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\'> </p>', 'profil': '52d0598c563380592bc1d703', 'tagName': 'Annotation', 'police': 'opendyslexicregular', 'taille': '14', 'interligne': '18', 'styleValue': 'Normal', 'coloration': 'Surligner les lignes', '_id': '52fb65eb8856dce835c2ca8d', '__v': 0 }]; var tags = [{ _id: '52c588a861485ed41c000001', libelle: 'Solution', niveau: 0 }, { _id: '52d0598c563380592bc1d704', libelle: 'Titre 01', niveau: 1 }, { _id: '52d0598c5633863243545676', libelle: 'Annotation', niveau: 0 }]; var profile = { _id: '533d350e4952c0d457478243', dropbox: { 'accessToken': '0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV', 'country': 'MA', 'display_name': 'Ahmed BOUKHARI', 'emails': '[email protected]', 'referral_link': 'https://db.tt/8yRfYgRM', 'uid': '274702674' }, local: { 'role': 'user', 'prenom': 'aaaaaaa', 'nom': 'aaaaaaaa', 'password': '$2a$08$53hezQbdhQrrux7pxIftheQwirc.ud8vEuw/IgFOP.tBcXBNftBH.', 'email': '[email protected]' } }; var profilActuel = { nom: 'Nom1', descriptif: 'Descriptif1', photo: '', owner: '5325aa33a21f887257ac2995', _id: '52fb65eb8856dce835c2ca86' }; var user = { 'email': '[email protected]', 'password': 'password example', 'nom': 'test', 'prenom': 'test', 'data': { 'local': 'admin' } }; var notes = [{ 'idNote': '1401965900625976', 'idInPage': 1, 'idDoc': '3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 194, 'xLink': 382, 'yLink': 194, 'styleNote': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\' > Note 1 </p>' }]; var compteId = 'dgsjgddshdhkjshdjkhskdhjghqksggdlsjfhsjkggsqsldsgdjldjlsd'; var appVersions = [{ appVersion: 2 }]; // var source = './files/audio.mp3'; beforeEach(module('cnedApp')); beforeEach(inject(function ($controller, $rootScope, $httpBackend, $location, $injector, $q) { modal = { open: function (params) { modalParameters = params; }, }; speechStopped = false; isOnlineServiceCheck = true; logedServiceCheck = false; window = { location: { href: 'test' }, getSelection: function () { return { toString: function () { return 'textSelected'; } }; }, open: function () { return; } }; speechService = { stopSpeech: function () { speechStopped = true; }, isBrowserSupported: function () { return true; }, speech: function () { return; } }; serviceCheck = { getData: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve({ user: { local: { authorisations: { audio: true } } }, loged: logedServiceCheck }); return deferred.promise; }, isOnline: function () { deferred = $q.defer(); // Place the fake return object here if (isOnlineServiceCheck) { deferred.resolve(isOnlineServiceCheck); } else { deferred.reject(isOnlineServiceCheck); } return deferred.promise; }, htmlPreview: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve({ documentHtml: '<h1>test</h1' }); return deferred.promise; }, checkName: function () { return true; } }; CKEDITOR = { instances: [], inline: function () {}, remove: function () {} }; CKEDITOR.instances.editorAdd = { setData: function () {}, getData: function () { return 'texte'; }, checkDirty: function () { return false; }, destroy: function () {} }; fileStorageService = { getFile: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve('<h1>test</h1>'); return deferred.promise; }, getTempFile: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve('<h1>test</h1>'); return deferred.promise; }, saveTempFileForPrint: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(); return deferred.promise; }, searchFiles: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(filesFound); return deferred.promise; }, shareFile: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(lienPartage); return deferred.promise; } }; workspaceService = { parcourirHtml: function (html) { return ['titre', html]; }, restoreNotesStorage: function () { return notes; }, saveTempNotesForPrint: function () { return; } }; configuration = { 'NODE_ENV': 'test', 'MONGO_URI': 'localhost', 'MONGO_DB': 'adaptation-test', 'URL_REQUEST': 'https://localhost:3000', 'CATALOGUE_NAME': 'adaptation.html', 'DROPBOX_CLIENT_ID': 'xxxx', 'DROPBOX_CLIENT_SECRET': 'xxxx', 'DROPBOX_TYPE': 'sandbox', 'EMAIL_HOST': 'smtp.gmail.com', 'EMAIL_HOST_UID': '[email protected]', 'EMAIL_HOST_PWD': 'xxxx' }; $location = $injector.get('$location'); $location.$$absUrl = 'https://dl.dropboxusercontent.com/s/ytnrsdrp4fr43nu/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html#/apercu'; scope = $rootScope.$new(); controller = $controller('ApercuCtrl', { $scope: scope, $window: window, speechService: speechService, serviceCheck: serviceCheck, fileStorageService: fileStorageService, workspaceService: workspaceService, configuration: configuration, $modal: modal }); scope.testEnv = true; scope.duplDocTitre = 'Titredudocument'; $rootScope.currentUser = profile; $rootScope.currentIndexPage = 1; scope.pageDe = scope.pageA = [1, 2, 3, 4, 5, 6]; mapNotes = { '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232': [{ 'idNote': '1401965900625976', 'idInPage': 1, 'idDoc': '3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 194, 'xLink': 382, 'yLink': 194, 'styleNote': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\' > Note 1 </p>' }] }; var jsonannotation = [{ 'idNote': '1413886387872259', 'idInPage': 1, 'idDoc': '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 54, 'xLink': 510, 'yLink': 49, 'styleNote': '<p data-font=\'Arial\' data-size=\'14\' data-lineheight=\'22\' data-weight=\'Gras\' data-coloration=\'Colorer les syllabes\' data-word-spacing=\'5\' data-letter-spacing=\'7\'> Note 1 </p>' }, { 'idNote': '1413886389688203', 'idInPage': 2, 'idDoc': '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8', 'idPage': 1, 'texte': 'Note 2', 'x': 750, 'y': 122, 'xLink': 658, 'yLink': 122, 'styleNote': '<p data-font=\'Arial\' data-size=\'14\' data-lineheight=\'22\' data-weight=\'Gras\' data-coloration=\'Colorer les syllabes\' data-word-spacing=\'5\' data-letter-spacing=\'7\'> Note 2 </p>' }]; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); // Mock the the tag search service $rootScope.testEnv = true; $httpBackend.whenPOST(configuration.URL_REQUEST + '/chercherProfilActuel').respond(profilActuel); $httpBackend.whenPOST(configuration.URL_REQUEST + '/chercherTagsParProfil').respond(profilTags); $httpBackend.whenGET(configuration.URL_REQUEST + '/readTags?id=' + compteId).respond(tags); $httpBackend.whenPOST(configuration.URL_REQUEST + '/chercherProfilParDefaut').respond(user); $httpBackend.whenGET(configuration.URL_REQUEST + '/profile?id=' + compteId).respond(profile); $httpBackend.whenPOST(configuration.URL_REQUEST + '/allVersion').respond(appVersions); scope.manifestName = 'doc01.appcache'; scope.apercuName = 'doc01.html'; scope.url = 'https://dl.dropboxusercontent.com/s/vnmvpqykdwn7ekq/' + scope.apercuName; scope.listDocumentDropbox = 'test.html'; scope.listDocumentManifest = 'listDocument.appcache'; $httpBackend.whenGET(configuration.URL_REQUEST + '/listDocument.appcache').respond('CACHE MANIFEST # 2010-06-18:v1 # Explicitly cached '); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.manifestName + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/sandbox/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json?access_token=0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV').respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/shares/?access_token=' + profile.dropbox.accessToken + '&path=' + scope.manifestName + '&root=' + configuration.DROPBOX_TYPE + '&short_url=false').respond({ url: 'https://dl.dropboxusercontent.com/s/sy4g4yn0qygxhs5/' + scope.manifestName }); $httpBackend.whenPOST('https://api.dropbox.com/1/shares/?access_token=0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV&path=2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json&root=sandbox&short_url=false').respond({ url: 'https://dl.dropboxusercontent.com/s/sy4g4yn0qygxhs5/' + scope.manifestName }); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.apercuName + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/shares/?access_token=' + profile.dropbox.accessToken + '&path=' + scope.apercuName + '&root=' + configuration.DROPBOX_TYPE + '&short_url=false').respond({ url: 'https://dl.dropboxusercontent.com/s/sy4g4yn0qygxhs5/' + scope.apercuName }); $httpBackend.whenGET(scope.url).respond('<html manifest=""><head><script> var ownerId = null; var blocks = []; </script></head><body></body></html>'); $httpBackend.whenGET('https://api-content.dropbox.com/1/files/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentDropbox + '?access_token=' + profile.dropbox.accessToken).respond('<htlm manifest=""><head><script> var profilId = null; var blocks = []; var listDocument= []; </script></head><body></body></html>'); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentDropbox + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenGET('https://api-content.dropbox.com/1/files/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentManifest + '?access_token=' + profile.dropbox.accessToken).respond(''); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentManifest + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/search/?access_token=0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV&query=Titredudocument_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html&root=sandbox').respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/search/?access_token=' + profile.dropbox.accessToken + '&query=_' + scope.duplDocTitre + '_&root=sandbox').respond({}); $httpBackend.whenGET('https://api-content.dropbox.com/1/files/' + configuration.DROPBOX_TYPE + '/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html?access_token=' + profile.dropbox.accessToken).respond('<html manifest=""><head><script> var profilId = null; var blocks = []; var listDocument= []; </script></head><body></body></html>'); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.appcache?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenGET(configuration.URL_REQUEST + '/index.html').respond('<html manifest=""><head><script> var profilId = null; var blocks = []; var listDocument= []; </script></head><body></body></html>'); $httpBackend.whenGET('https://dl.dropboxusercontent.com/s/gk6ueltm1ckrq9u/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json').respond(jsonannotation); $httpBackend.whenGET(configuration.URL_REQUEST + '/profile?id=gk6ueltm1ckrq9u24b9855644b7c8733a69cd5bf8290bc8').respond(jsonannotation); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPOST(configuration.URL_REQUEST + '/sendMail').respond({}); $httpBackend.whenGET('/2015-9-22_testsAnnotations_cf5ad4f059eb80c206e92be53b9e8d30.json').respond(mapNotes['2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232']); })); /* ApercuCtrl:init */ it('ApercuCtrl:init cas url', inject(function ($rootScope, $timeout, $q) { // case url web spyOn(scope, 'getHTMLContent').andCallFake(function () { var promiseToreturn = $q.defer(); // Place the fake return object here promiseToreturn.resolve(); return promiseToreturn.promise; }); scope.url = 'https://localhost:3000/#/apercu?url=https:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes'; scope.init(); $rootScope.$apply(); expect(scope.loader).toBe(true); expect(scope.urlHost).toEqual('localhost'); expect(scope.urlPort).toEqual(443); expect(scope.url).toEqual('https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Maîtres_anonymes'); expect(scope.docName).toEqual('https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Maîtres_anonymes'); expect(scope.docSignature).toEqual('https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Maîtres_anonymes'); scope.url = 'http://localhost:3000/#/apercu?url=http:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes'; scope.init(); expect(scope.urlPort).toEqual(80); // case url pdf scope.url = 'https://localhost:3000/#/apercu?url=https:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.pdf'; spyOn(scope, 'loadPdfByLien').andReturn(); scope.init(); $rootScope.$apply(); expect(scope.loadPdfByLien).toHaveBeenCalled(); // case url image scope.url = 'https://localhost:3000/#/apercu?url=https:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.png'; spyOn(scope, 'loadPictureByLink').andReturn(); scope.init(); $rootScope.$apply(); expect(scope.loadPictureByLink).toHaveBeenCalled(); })); it('ApercuCtrl:init cas url http', inject(function ($rootScope, $timeout, $q) { // case url web spyOn(scope, 'getHTMLContent').andCallFake(function () { var promiseToreturn = $q.defer(); // Place the fake return object here promiseToreturn.resolve(); return promiseToreturn.promise; }); scope.url = 'http://localhost:3000/#/apercu?url=http:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.pdf'; scope.init(); $rootScope.$apply(); expect(scope.loader).toBe(true); expect(scope.urlHost).toEqual('localhost'); expect(scope.urlPort).toEqual(80); expect(scope.url).toEqual('http://localhost:3000/#/apercu?url=http://fr.wikipedia.org/wiki/Maîtres_anonymes.pdf'); expect(scope.docName).toEqual('http://localhost:3000/#/apercu?url=http://fr.wikipedia.org/wiki/Maîtres_anonymes.pdf'); expect(scope.docSignature).toEqual('http://localhost:3000/#/apercu?url=http://fr.wikipedia.org/wiki/Maîtres_anonymes.pdf'); })); it('ApercuCtrl:init cas document', inject(function ($rootScope, $timeout, $q) { // Case of a document of which the contents were already loaded at least // once. logedServiceCheck = true; scope.url = null; scope.idDocument = 'test'; scope.tmp = null; scope.init(); expect(scope.loader).toBe(true); $rootScope.$apply(); expect(scope.docName).toEqual('test'); expect(scope.content).toEqual(['titre', '<h1>test</h1>']); $timeout(function () { expect(scope.loader).toBe(false); }, 1000); expect(scope.currentPage).toBe(1); // Case of a document of which the contents were never loaded spyOn(scope, 'affichageInfoDeconnecte').andCallThrough(); spyOn(fileStorageService, 'getFile').andCallFake(function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(null); return deferred.promise; }); logedServiceCheck = true; scope.url = null; scope.idDocument = 'test'; scope.tmp = null; scope.init(); expect(scope.loader).toBe(true); $rootScope.$apply(); expect(scope.affichageInfoDeconnecte).toHaveBeenCalled(); $timeout(function () { expect(scope.loader).toBe(false); }, 1000); })); it('ApercuCtrl:init cas temporaire', inject(function ($rootScope, $timeout) { logedServiceCheck = true; scope.url = null; scope.idDocument = null; scope.tmp = true; scope.init(); expect(scope.loader).toBe(true); $rootScope.$apply(); expect(scope.docName).toEqual('Aperçu Temporaire'); expect(scope.content).toEqual(['titre', '<h1>test</h1>']); $timeout(function () { expect(scope.loader).toBe(false); }, 1000); expect(scope.currentPage).toBe(1); })); it('ApercuCtrl:loadPictureByLink()', inject(function () { scope.url = 'http://localhost:3000/#/apercu?url=http:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.pdf'; scope.loadPictureByLink(scope.url); })); /* ApercuCtrl:dupliquerDocument */ it('ApercuCtrl:dupliquerDocument', inject(function ($httpBackend) { localStorage.setItem('compteId', compteId); serviceCheck.checkName = function () { return false; }; scope.dupliquerDocument(); $httpBackend.flush(); expect(scope.dupliquerDocument).toBeDefined(); expect(scope.showMsgSuccesvs).toBe(true); scope.duplDocTitre = null; scope.dupliquerDocument(); scope.duplDocTitre = 'iknonjn_lkjnkljnkj_/khbjhbk'; scope.dupliquerDocument(); })); it('ApercuCtrl:dupliquerDocument', inject(function ($httpBackend) { localStorage.setItem('compteId', compteId); serviceCheck.checkName = function () { return true; }; scope.dupliquerDocument(); $httpBackend.flush(); expect(scope.dupliquerDocument).toBeDefined(); expect(scope.showMsgSuccesvs).toBe(true); scope.duplDocTitre = null; scope.dupliquerDocument(); scope.duplDocTitre = 'iknonjn_lkjnkljnkj_/khbjhbk'; scope.dupliquerDocument(); })); /* ApercuCtrl:ete */ it('ApercuCtrl:ete', inject(function ($httpBackend) { scope.duplDocTitre = null; scope.ete(); })); /* ApercuCtrl:clearDupliquerDocument */ it('ApercuCtrl:clearDupliquerDocument', function () { scope.clearDupliquerDocument(); expect(scope.msgSuccess).toBe(''); expect(scope.showMsgSuccess).toBe(false); }); /* ApercuCtrl:hideLoader */ it('ApercuCtrl:hideLoader', inject(function ($timeout) { scope.hideLoader(); $timeout(function () { expect(scope.loader).toEqual(false); expect(scope.loaderMsg).toEqual(''); }, 1000); $timeout.flush(); })); /* ApercuCtrl:enableNoteAdd */ it('ApercuCtrl:enableNoteAdd', inject(function () { scope.enableNoteAdd(); expect(scope.isEnableNoteAdd).toEqual(true); })); /* ApercuCtrl:collapse */ it('ApercuCtrl:collapse', inject(function () { scope.collapse(); expect(scope.isEnableNoteAdd).toEqual(true); })); /* ApercuCtrl:editer */ it('ApercuCtrl:editer', inject(function () { scope.idDocument = 'test'; scope.editer(); expect(window.location.href).toEqual('https://localhost:3000/#/addDocument?idDocument=test'); })); /* ApercuCtrl:setActive */ it('ApercuCtrl:setActive', inject(function ($timeout) { spyOn(document, 'getElementById').andReturn({ scrollIntoView: function () { return; } }); scope.content = ['page1', 'page2', 'page3']; scope.setActive(0, 1, '52cb095fa8551d800b000012'); expect(scope.currentPage).toBe(1); $timeout.flush(); })); /* ApercuCtrl:setPage */ it('ApercuCtrl:setPage', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 1; scope.setPage(3); expect(scope.currentPage).toBe(1); scope.currentPage = 1; scope.setPage(-1); expect(scope.currentPage).toBe(1); scope.currentPage = 1; scope.setPage(0); expect(scope.currentPage).toBe(0); scope.currentPage = 1; scope.setPage(2); expect(scope.currentPage).toBe(2); }); /* ApercuCtrl:precedent */ it('ApercuCtrl:precedent', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 2; scope.precedent(); expect(scope.currentPage).toBe(1); }); /* ApercuCtrl:suivant */ it('ApercuCtrl:suivant', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 1; scope.suivant(); expect(scope.currentPage).toBe(2); }); /* ApercuCtrl:premier */ it('ApercuCtrl:premier', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 2; scope.premier(); expect(scope.currentPage).toBe(1); }); /* ApercuCtrl:dernier */ it('ApercuCtrl:dernier', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 1; scope.dernier(); expect(scope.currentPage).toBe(2); }); /* ApercuCtrl:plan */ it('ApercuCtrl:plan', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 2; scope.plan(); expect(scope.currentPage).toBe(0); }); /* ApercuCtrl:afficherMenu */ it('ApercuCtrl:afficherMenu', function () { $('<div class="menu_wrapper"><button type="button" class="open_menu shown"></button></div>').appendTo('body'); scope.afficherMenu(); $('<div class="menu_wrapper"><button type="button" class="open_menu"></button></div>').appendTo('body'); scope.afficherMenu(); }); /* ApercuCtrl:socialShare */ it('ApercuCtrl:socialShare', function () { scope.clearSocialShare(); scope.loadMail(); scope.dismissConfirm(); scope.socialShare(); scope.destinataire = 'test@email'; scope.socialShare(); expect(scope.emailMsgError).not.toBe(''); scope.destinataire = '[email protected]'; scope.socialShare(); expect(scope.emailMsgError).toBe(''); localStorage.removeItem('notes'); scope.clearSocialShare(); }); /* ApercuCtrl:clearSocialShare */ it('ApercuCtrl:clearSocialShare', function () { scope.idDocument = '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232'; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); scope.clearSocialShare(); expect(scope.addAnnotation).toBe(true); scope.idDocument = 'docquinapasdenotes'; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); scope.clearSocialShare(); expect(scope.addAnnotation).toBe(false); }); /* ApercuCtrl:sendMail */ it('ApercuCtrl:sendMail', inject(function ($httpBackend) { scope.docApartager = { filename: 'file', lienApercu: 'dropbox.com' }; scope.destinataire = '[email protected]'; scope.encodeURI = 'https%3A%2F%2Flocalhost%3A3000%2F%23%2Fapercu%3Furl%3Dhttps%3A%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes'; scope.sendMail(); $httpBackend.flush(); expect(scope.destinataire).toBe(''); expect(scope.sendVar).toEqual({ to: '[email protected]', content: ' a utilisé Accessidys pour partager un fichier avec vous ! dropbox.com', encoded: '<span> vient d\'utiliser Accessidys pour partager ce fichier avec vous : <a href=' + 'dropbox.com' + '>' + 'file' + '</a> </span>', prenom: 'aaaaaaa', fullName: 'aaaaaaa aaaaaaaa', doc: 'file' }); })); it('ApercuCtrl:selectionnerMultiPage', function () { scope.selectionnerMultiPage(); expect(scope.pageDe).toBe(1); expect(scope.pageA).toBe(1); }); it('ApercuCtrl:selectionnerPageDe', function () { scope.pageA = [1, 2]; scope.selectionnerPageDe(); }); it('ApercuCtrl:printByMode', inject(function ($rootScope) { scope.printMode = 1; scope.printPlan = true; scope.printByMode(); $rootScope.$apply(); scope.printMode = 2; scope.printByMode(); $rootScope.$apply(); })); it('ApercuCtrl:addNote', function () { scope.notes = notes.slice(0); scope.addNote(700, 50); expect(scope.notes.length).toBe(2); }); it('ApercuCtrl:restoreNotesStorage', function () { scope.modeImpression = false; scope.notes = notes.slice(0); scope.currentPage = 1; scope.restoreNotesStorage(1); expect(scope.notes.length).toBe(1); }); it('ApercuCtrl:editNote', function () { scope.notes = notes.slice(0); scope.docSignature = '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232'; scope.editNote(scope.notes[0]); scope.modeImpression = false; scope.editNote(scope.notes[0]); }); it('ApercuCtrl:removeNote', function () { scope.notes = notes.slice(0); scope.docSignature = '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232'; scope.removeNote(scope.notes[0]); expect(scope.notes.length).toBe(0); }); it('ApercuCtrl:drawLineForPrintMode()', inject(function ($timeout) { scope.notes = notes.slice(0); scope.drawLineForPrintMode() $timeout.flush(); })); it('ApercuCtrl:applySharedAnnotation', inject(function ($httpBackend) { // $httpBackend.flush(); scope.annotationURL = 'https://dl.dropboxusercontent.com/s/gk6ueltm1ckrq9u/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json'; scope.annotationDummy = 'gk6ueltm1ckrq9u/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8'; scope.applySharedAnnotation(); localStorage.removeItem('notes'); scope.applySharedAnnotation(); $httpBackend.flush(); scope.annotationURL = undefined; scope.applySharedAnnotation(); })); it('ApercuCtrl:setPasteNote', inject(function () { // $httpBackend.flush(); var $event = { originalEvent: { clipboardData: { getData: function () { return 'abcdg'; } } } }; scope.testEnv = false; scope.setPasteNote($event); expect(scope.pasteNote).toBeTruthy(); })); it('ApercuCtrl:prepareNote', inject(function () { // $httpBackend.flush(); var elem = document.createElement('div'); var trgt = '<span class="image_container"><img id="cut_piece" onclick="simul(event);" ng-show="(child.source!==undefined)" ng-src="data:image/png;base64iVBORw0KGgoAAAANSUhEUgAAAxUAAAQbCAYAAAD+sIb0AAAgAElEQVR4XuydBZgcxd"><span ng-show="(child.source===undefined)" onclick="simul(event);" style="width:142px;height:50px;background-color:white;display: inline-block;" dynamic="child.text | showText:30:true" class="cut_piece ng-hide"><span class="ng-scope">- Vide -</span></span></span>'; elem.className = 'active'; elem.innerHTML = trgt; var $event = { currentTarget: elem.children[0] }; var note = { texte: 'aggljj' }; scope.prepareNote(note, $event); })); it('ApercuCtrl:autoSaveNote', inject(function () { scope.notes = notes.slice(0); localStorage.setItem('notes', JSON.stringify(angular.toJson(notes))); scope.docSignature = 0; // $httpBackend.flush(); var elem = document.createElement('div'); var trgt = '<span class="image_container"><img id="cut_piece" onclick="simul(event);" ng-show="(child.source!==undefined)" ng-src="data:image/png;base64iVBORw0KGgoAAAANSUhEUgAAAxUAAAQbCAYAAAD+sIb0AAAgAElEQVR4XuydBZgcxd"><span ng-show="(child.source===undefined)" onclick="simul(event);" style="width:142px;height:50px;background-color:white;display: inline-block;" dynamic="child.text | showText:30:true" class="cut_piece ng-hide"><span class="ng-scope">- Vide -</span></span></span>'; elem.className = 'active'; elem.innerHTML = trgt; var $event = { currentTarget: elem.children[0] }; var note = { texte: 'aggljj' }; scope.autoSaveNote(note, $event); })); it('ApercuCtrl:addNoteOnClick', inject(function ($rootScope) { $rootScope.currentIndexPag = 2; scope.isEnableNoteAdd = true; var elem = document.createElement('div'); var trgt = '<span class="menu_wrapper"><span class="open_menu shown"><span class="zoneID">- Vide -</span></span></span>'; elem.className = 'active'; elem.innerHTML = trgt; var $event = { currentTarget: elem.children[0] }; scope.addNoteOnClick($event); })); it('ApercuCtrl:processAnnotation', inject(function ($httpBackend) { // $httpBackend.flush(); scope.docApartager = { filename: 'file', lienApercu: 'dropbox.com' }; scope.annotationOk = false; scope.processAnnotation(); scope.annotationOk = true; scope.testEnv = true; scope.docFullName = '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8'; scope.annotationToShare = [{ 'idNote': '1413886387872259', 'idInPage': 1, 'idDoc': '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 54, 'xLink': 510, 'yLink': 49, 'styleNote': '<p data-font=\'Arial\' data-size=\'14\' data-lineheight=\'22\' data-weight=\'Gras\' data-coloration=\'Colorer les syllabes\' data-word-spacing=\'5\' data-letter-spacing=\'7\'> Note 1 </p>' }]; scope.processAnnotation(); $httpBackend.flush(); })); it('ApercuCtrl:getSelectedText', inject(function () { expect(scope.getSelectedText()).toEqual('textSelected'); // test of the selection when the browser does not support the function // getSelection window.getSelection = undefined; document.selection = { type: 'NotControl', createRange: function () { return { text: 'textSelected' }; } }; expect(scope.getSelectedText()).toEqual('textSelected'); // Test if no selection is possible. document.selection = { type: 'Control' }; expect(scope.getSelectedText()).toEqual(''); })); it('ApercuCtrl:closeOfflineSynthesisTips', inject(function () { scope.neverShowOfflineSynthesisTips = false; scope.displayOfflineSynthesisTips = true; scope.closeOfflineSynthesisTips(); expect(scope.displayOfflineSynthesisTips).toBe(false); expect(localStorage.getItem('neverShowOfflineSynthesisTips')).toEqual('false'); scope.neverShowOfflineSynthesisTips = true; scope.displayOfflineSynthesisTips = true; scope.closeOfflineSynthesisTips(); expect(scope.displayOfflineSynthesisTips).toBe(false); expect(localStorage.getItem('neverShowOfflineSynthesisTips')).toEqual('true'); })); it('ApercuCtrl:closeNoAudioRights', inject(function () { scope.displayNoAudioRights = true; scope.closeNoAudioRights(); expect(scope.displayNoAudioRights).toBe(false); })); it('ApercuCtrl:closeBrowserNotSupported', inject(function () { scope.displayBrowserNotSupported = true; scope.closeBrowserNotSupported(); expect(scope.displayBrowserNotSupported).toBe(false); })); it('ApercuCtrl:docPartage', inject(function (configuration, $rootScope) { scope.idDocument = 'test'; filesFound = [{ filepath: '/2015-9-22_monNouveauDoc_cf5ad4f059eb80c206e92be53b9e8d30.html' }]; lienPartage = 'monpartage'; scope.docPartage(); $rootScope.$apply(); expect(scope.docApartager.lienApercu.indexOf('/#/apercu?url=monpartage') > -1).toBe(true); filesFound = []; scope.docApartager = {}; scope.docPartage(); $rootScope.$apply(); expect(scope.docApartager.lienApercu).toBeUndefined(); $rootScope.isAppOnline = false; spyOn(modal, 'open').andCallThrough(); scope.docPartage(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('La fonctionnalité de partage de document nécessite un accès à internet'); var modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); var modalContent = modalParameters.resolve.reason(); var modalContent = modalParameters.resolve.forceClose(); })); it('ApercuCtrl:checkAnnotations', inject(function (configuration, $rootScope, $httpBackend) { scope.annotationURL = '/2015-9-22_testsAnnotations_cf5ad4f059eb80c206e92be53b9e8d30.json'; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); scope.checkAnnotations(); $httpBackend.flush(); expect(scope.docSignature).toEqual('testsAnnotations'); scope.annotationURL = '/2015-9-22_testsAnnotations_cf5ad4f059eb80c206e92be53b9e8d30.json'; localStorage.removeItem('notes'); scope.checkAnnotations(); $httpBackend.flush(); expect(scope.docSignature).toEqual('testsAnnotations'); scope.docSignature = undefined; scope.annotationURL = false; scope.checkAnnotations(); expect(scope.docSignature).toBeUndefined(); })); it('ApercuCtrl:destroyCkeditor', inject(function () { scope.destroyCkeditor(); expect(CKEDITOR.instances.editorAdd).toBeUndefined(); CKEDITOR.instances.secondEditeur = { setData: function () {}, getData: function () { return 'texte'; }, checkDirty: function () { return false; }, destroy: function () {}, filter: function () {} }; scope.destroyCkeditor(); expect(CKEDITOR.instances.secondEditeur).toBeUndefined(); CKEDITOR.instances.editeurUndefined = undefined; scope.destroyCkeditor(); expect(CKEDITOR.instances.editeurUndefined).toBeUndefined(); })); it('ApercuCtrl:speakOnKeyboard', inject(function ($timeout) { var eventShiftLeftArrow = { shiftKey: true, keyCode: 37 }; scope.speakOnKeyboard(eventShiftLeftArrow); var eventShift = { shiftKey: true, keyCode: 16 }; scope.speakOnKeyboard(eventShift); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(false); })); it('ApercuCtrl:checkBrowserSupported', inject(function () { scope.neverShowBrowserNotSupported = false; var result = scope.checkBrowserSupported(); expect(result).toBe(true); expect(scope.displayBrowserNotSupported).toBe(false); scope.neverShowBrowserNotSupported = true; result = scope.checkBrowserSupported(); expect(result).toBe(true); expect(scope.displayBrowserNotSupported).toBe(false); speechService.isBrowserSupported = function () { return false; }; scope.neverShowBrowserNotSupported = false; result = scope.checkBrowserSupported(); expect(result).toBe(false); expect(scope.displayBrowserNotSupported).toBe(true); })); it('ApercuCtrl:checkAudioRights', inject(function ($rootScope, $q) { scope.neverShowNoAudioRights = false; var result; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(true); expect(scope.displayNoAudioRights).toBe(false); var getDataUserResponse = {}; var toResolve = true; spyOn(serviceCheck, 'getData').andCallFake(function () { deferred = $q.defer(); // Place the fake return object here if (toResolve) { deferred.resolve({ user: getDataUserResponse }); } else { deferred.reject(); } return deferred.promise; }); scope.neverShowNoAudioRights = false; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(true); expect(scope.displayNoAudioRights).toBe(false); getDataUserResponse = { local: { authorisations: { audio: false } } }; scope.neverShowNoAudioRights = true; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(false); expect(scope.displayNoAudioRights).toBe(false); scope.neverShowNoAudioRights = false; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(false); expect(scope.displayNoAudioRights).toBe(true); toResolve = false; scope.neverShowNoAudioRights = false; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(true); expect(scope.displayNoAudioRights).toBe(false); })); it('ApercuCtrl:speak', inject(function ($timeout) { scope.speak(); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(false); isOnlineServiceCheck = false; scope.neverShowOfflineSynthesisTips = false; scope.speak(); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(true); isOnlineServiceCheck = false; scope.neverShowOfflineSynthesisTips = true; scope.speak(); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(false); })); // it('ApercuCtrl:browserSupported thruthness', // inject(function($location) { // scope.browserSupported = true; // scope.$apply(); // var hash = $location.hash(); // expect(hash).toEqual('main_header'); // }) // ); it('ApercuCtrl:checkLinkOffline', inject(function ($rootScope) { $rootScope.isAppOnline = false; var event = { target: { nodeName: 'A' }, preventDefault: function () {}, stopPropagation: function () {} }; spyOn(modal, 'open').andCallThrough(); scope.checkLinkOffline(event); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('La navigation adaptée n\'est pas disponible sans accès internet.'); $rootScope.isAppOnline = true; //We resets to 0 the number of calls to the mock. modal.open.reset(); scope.checkLinkOffline(event); // modal.open has not been called expect(modal.open).not.toHaveBeenCalled(); var modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('La navigation adaptée n\'est pas disponible sans accès internet.'); modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); modalContent = modalParameters.resolve.reason(); modalContent = modalParameters.resolve.forceClose(); })); it('ApercuCtrl:affichageInfoDeconnecte()', function () { spyOn(modal, 'open').andCallThrough(); scope.affichageInfoDeconnecte(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.reason(); expect(modalContent).toEqual('/listDocument'); modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); modalContent = modalParameters.resolve.forceClose(); modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('L\'affichage de ce document nécessite au moins un affichage préalable via internet.'); }); it('ApercuCtrl:openDocumentListModal()', function () { spyOn(modal, 'open').andCallThrough(); scope.openDocumentListModal(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/listDocument/listDocumentModal.html'); var modalContent = modalParameters.resolve.reason(); expect(modalContent).toEqual('/listDocument'); modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); modalContent = modalParameters.resolve.forceClose(); modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('L\'affichage de ce document nécessite au moins un affichage préalable via internet.'); }); it('ApercuCtrl:getUserAndInitApercu()', inject(function ($rootScope, $routeParams) { // classic case spyOn(scope, 'init').andReturn(); $rootScope.loged = true; scope.getUserAndInitApercu(); $rootScope.$apply(); expect(scope.init).toHaveBeenCalled(); // The case of a shared document $routeParams.url = 'dropboxusercontent'; scope.getUserAndInitApercu(); $rootScope.$apply(); expect(scope.init).toHaveBeenCalled(); })); it('ApercuCtrl:resizeApercu ', inject(function () { // enlargement scope.resizeDocApercu = 'Réduire'; scope.resizeApercu(); expect(scope.resizeDocApercu).toEqual('Agrandir'); // reduction scope.resizeDocEditor = 'Agrandir'; scope.resizeApercu(); expect(scope.resizeDocApercu).toEqual('Réduire'); })); it('ApercuCtrl:switchModeAffichage', inject(function () { //passing the print mode to the consultation mode. scope.modeImpression = true; scope.switchModeAffichage(); expect(scope.modeImpression).toBe(false); // passing the consultation mode to print mode. scope.modeImpression = false; scope.switchModeAffichage(); expect(scope.modeImpression).toBe(true); scope.testEnv = false; scope.switchModeAffichage(); scope.tmp = false; scope.switchModeAffichage(); })); it('ApercuCtrl:fermerApercu', inject(function ($location) { // Close the overview for a nontemporary document. spyOn($location, 'path').andCallThrough(); scope.tmp = false; scope.fermerApercu(); expect($location.path).toHaveBeenCalled(); // Close the overview for a temporary document. spyOn(modal, 'open').andCallThrough(); scope.tmp = true; scope.fermerApercu(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Fermeture'); modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('Pour fermer l\'aperçu du document, veuillez fermer la fenêtre.'); modalContent = modalParameters.resolve.reason(); modalContent = modalParameters.resolve.forceClose(); })); it('ApercuCtrl:loadPdfPage', inject(function ($q, $rootScope) { var q = $q; var pdf = { getPage: function () { deferred = q.defer(); // Place the fake return object here deferred.resolve(pdfPage); return deferred.promise; }, numPages: 1 }, pdfPage = { error: false, render: function () { deferred = q.defer(); // Place the fake return object here //deferred.resolve(this.internalRenderTask.callback()); deferred.resolve(); return deferred.promise; }, getViewport: function () { return { height: 100, width: 100 }; } }; scope.pdfTohtml = { push: function (arg) { return arg; }, filter: function (arg) { return '--'; } }; expect(scope.loadPdfPage).toBeDefined(); scope.loadPdfPage(pdf, 1); $rootScope.$apply(); })); it('ApercuCtrl:loadPdfPage', inject(function ($q, $rootScope) { var q = $q; var pdf = { getPage: function () { deferred = q.defer(); // Place the fake return object here deferred.resolve(pdfPage); return deferred.promise; }, }, pdfPage = { error: false, render: function () { deferred = q.defer(); // Place the fake return object here //deferred.resolve(this.internalRenderTask.callback()); deferred.resolve({ error: 'error' }); return deferred.promise; }, getViewport: function () { return { height: 100, width: 100 }; } }; expect(scope.loadPdfPage).toBeDefined(); scope.loadPdfPage(pdf, 1); $rootScope.$apply(); })); it('ApercuCtrl:loadPdfByLien', inject(function () { scope.url = 'https://localhost:3000/#/apercu?url=https://www.esprit.presse.fr/whoarewe/historique.pdf'; //$httpBackend.expectPOST(/sendPdfHTTPS.*/).respond(401, ''); scope.loadPdfByLien(scope.url); scope.url = 'http://localhost:3000/#/apercu?url=http://www.esprit.presse.fr/whoarewe/historique.pdf'; scope.loadPdfByLien(scope.url); })); it('ApercuCtrl:loadPictureByLink', inject(function () { scope.url = 'https://localhost:3000/#/apercu?url=https://www.w3.org/Style/Examples/011/gevaar.png'; expect(scope.loadPictureByLink).toBeDefined(); scope.loadPictureByLink(scope.url); })); it('ApercuCtrl:getHTMLContent', function () { scope.url = 'https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Wikip%C3%A9dia'; scope.getHTMLContent(scope.url); }); it('ApercuCtrl:stopSpeech', function () { scope.stopSpeech(); }); });
test/spec/frontend/apercu.js
/* File: apercu.js * * Copyright (c) 2013-2016 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France * ([email protected]) * * GNU Affero General Public License (AGPL) version 3.0 or later version * * This file is part of a program which 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/>. * */ /*global $:false, spyOn:false, CKEDITOR:true */ 'use strict'; describe('Controller:ApercuCtrl', function () { var scope, controller, window, speechService, speechStopped, serviceCheck, deferred, fileStorageService, isOnlineServiceCheck, workspaceService, configuration, filesFound, lienPartage, mapNotes, logedServiceCheck, modal, modalParameters; var profilTags = [{ '__v': 0, '_id': '52fb65eb8856dce835c2ca87', 'coloration': 'Colorer les lignes', 'interligne': '18', 'police': 'opendyslexicregular', 'profil': '52d0598c563380592bc1d703', 'styleValue': 'Normal', 'tag': '52d0598c563380592bc1d704', 'tagName': 'Titre 01', 'taille': '12', 'texte': '<p data-font=\'opendyslexicregular\' data-size=\'12\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Colorer les lignes\'> </p>' }, { 'tag': '52c588a861485ed41c000001', 'texte': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\'> </p>', 'profil': '52d0598c563380592bc1d703', 'tagName': 'Solution', 'police': 'opendyslexicregular', 'taille': '14', 'interligne': '18', 'styleValue': 'Normal', 'coloration': 'Surligner les lignes', '_id': '52fb65eb8856dce835c2ca8d', '__v': 0 }, { 'tag': '52d0598c5633863243545676', 'texte': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\'> </p>', 'profil': '52d0598c563380592bc1d703', 'tagName': 'Annotation', 'police': 'opendyslexicregular', 'taille': '14', 'interligne': '18', 'styleValue': 'Normal', 'coloration': 'Surligner les lignes', '_id': '52fb65eb8856dce835c2ca8d', '__v': 0 }]; var tags = [{ _id: '52c588a861485ed41c000001', libelle: 'Solution', niveau: 0 }, { _id: '52d0598c563380592bc1d704', libelle: 'Titre 01', niveau: 1 }, { _id: '52d0598c5633863243545676', libelle: 'Annotation', niveau: 0 }]; var profile = { _id: '533d350e4952c0d457478243', dropbox: { 'accessToken': '0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV', 'country': 'MA', 'display_name': 'Ahmed BOUKHARI', 'emails': '[email protected]', 'referral_link': 'https://db.tt/8yRfYgRM', 'uid': '274702674' }, local: { 'role': 'user', 'prenom': 'aaaaaaa', 'nom': 'aaaaaaaa', 'password': '$2a$08$53hezQbdhQrrux7pxIftheQwirc.ud8vEuw/IgFOP.tBcXBNftBH.', 'email': '[email protected]' } }; var profilActuel = { nom: 'Nom1', descriptif: 'Descriptif1', photo: '', owner: '5325aa33a21f887257ac2995', _id: '52fb65eb8856dce835c2ca86' }; var user = { 'email': '[email protected]', 'password': 'password example', 'nom': 'test', 'prenom': 'test', 'data': { 'local': 'admin' } }; var notes = [{ 'idNote': '1401965900625976', 'idInPage': 1, 'idDoc': '3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 194, 'xLink': 382, 'yLink': 194, 'styleNote': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\' > Note 1 </p>' }]; var compteId = 'dgsjgddshdhkjshdjkhskdhjghqksggdlsjfhsjkggsqsldsgdjldjlsd'; var appVersions = [{ appVersion: 2 }]; // var source = './files/audio.mp3'; beforeEach(module('cnedApp')); beforeEach(inject(function ($controller, $rootScope, $httpBackend, $location, $injector, $q) { modal = { open: function (params) { modalParameters = params; }, }; speechStopped = false; isOnlineServiceCheck = true; logedServiceCheck = false; window = { location: { href: 'test' }, getSelection: function () { return { toString: function () { return 'textSelected'; } }; }, open: function () { return; } }; speechService = { stopSpeech: function () { speechStopped = true; }, isBrowserSupported: function () { return true; }, speech: function () { return; } }; serviceCheck = { getData: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve({ user: { local: { authorisations: { audio: true } } }, loged: logedServiceCheck }); return deferred.promise; }, isOnline: function () { deferred = $q.defer(); // Place the fake return object here if (isOnlineServiceCheck) { deferred.resolve(isOnlineServiceCheck); } else { deferred.reject(isOnlineServiceCheck); } return deferred.promise; }, htmlPreview: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve({ documentHtml: '<h1>test</h1' }); return deferred.promise; }, checkName: function () { return true; } }; CKEDITOR = { instances: [], inline: function () {}, remove: function () {} }; CKEDITOR.instances.editorAdd = { setData: function () {}, getData: function () { return 'texte'; }, checkDirty: function () { return false; }, destroy: function () {} }; fileStorageService = { getFile: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve('<h1>test</h1>'); return deferred.promise; }, getTempFile: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve('<h1>test</h1>'); return deferred.promise; }, saveTempFileForPrint: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(); return deferred.promise; }, searchFiles: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(filesFound); return deferred.promise; }, shareFile: function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(lienPartage); return deferred.promise; } }; workspaceService = { parcourirHtml: function (html) { return ['titre', html]; }, restoreNotesStorage: function () { return notes; }, saveTempNotesForPrint: function () { return; } }; configuration = { 'NODE_ENV': 'test', 'MONGO_URI': 'localhost', 'MONGO_DB': 'adaptation-test', 'URL_REQUEST': 'https://localhost:3000', 'CATALOGUE_NAME': 'adaptation.html', 'DROPBOX_CLIENT_ID': 'xxxx', 'DROPBOX_CLIENT_SECRET': 'xxxx', 'DROPBOX_TYPE': 'sandbox', 'EMAIL_HOST': 'smtp.gmail.com', 'EMAIL_HOST_UID': '[email protected]', 'EMAIL_HOST_PWD': 'xxxx' }; $location = $injector.get('$location'); $location.$$absUrl = 'https://dl.dropboxusercontent.com/s/ytnrsdrp4fr43nu/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html#/apercu'; scope = $rootScope.$new(); controller = $controller('ApercuCtrl', { $scope: scope, $window: window, speechService: speechService, serviceCheck: serviceCheck, fileStorageService: fileStorageService, workspaceService: workspaceService, configuration: configuration, $modal: modal }); scope.testEnv = true; scope.duplDocTitre = 'Titredudocument'; $rootScope.currentUser = profile; $rootScope.currentIndexPage = 1; scope.pageDe = scope.pageA = [1, 2, 3, 4, 5, 6]; mapNotes = { '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232': [{ 'idNote': '1401965900625976', 'idInPage': 1, 'idDoc': '3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 194, 'xLink': 382, 'yLink': 194, 'styleNote': '<p data-font=\'opendyslexicregular\' data-size=\'14\' data-lineheight=\'18\' data-weight=\'Normal\' data-coloration=\'Surligner les lignes\' > Note 1 </p>' }] }; var jsonannotation = [{ 'idNote': '1413886387872259', 'idInPage': 1, 'idDoc': '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 54, 'xLink': 510, 'yLink': 49, 'styleNote': '<p data-font=\'Arial\' data-size=\'14\' data-lineheight=\'22\' data-weight=\'Gras\' data-coloration=\'Colorer les syllabes\' data-word-spacing=\'5\' data-letter-spacing=\'7\'> Note 1 </p>' }, { 'idNote': '1413886389688203', 'idInPage': 2, 'idDoc': '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8', 'idPage': 1, 'texte': 'Note 2', 'x': 750, 'y': 122, 'xLink': 658, 'yLink': 122, 'styleNote': '<p data-font=\'Arial\' data-size=\'14\' data-lineheight=\'22\' data-weight=\'Gras\' data-coloration=\'Colorer les syllabes\' data-word-spacing=\'5\' data-letter-spacing=\'7\'> Note 2 </p>' }]; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); // Mock the the tag search service $rootScope.testEnv = true; $httpBackend.whenPOST(configuration.URL_REQUEST + '/chercherProfilActuel').respond(profilActuel); $httpBackend.whenPOST(configuration.URL_REQUEST + '/chercherTagsParProfil').respond(profilTags); $httpBackend.whenGET(configuration.URL_REQUEST + '/readTags?id=' + compteId).respond(tags); $httpBackend.whenPOST(configuration.URL_REQUEST + '/chercherProfilParDefaut').respond(user); $httpBackend.whenGET(configuration.URL_REQUEST + '/profile?id=' + compteId).respond(profile); $httpBackend.whenPOST(configuration.URL_REQUEST + '/allVersion').respond(appVersions); scope.manifestName = 'doc01.appcache'; scope.apercuName = 'doc01.html'; scope.url = 'https://dl.dropboxusercontent.com/s/vnmvpqykdwn7ekq/' + scope.apercuName; scope.listDocumentDropbox = 'test.html'; scope.listDocumentManifest = 'listDocument.appcache'; $httpBackend.whenGET(configuration.URL_REQUEST + '/listDocument.appcache').respond('CACHE MANIFEST # 2010-06-18:v1 # Explicitly cached '); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.manifestName + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/sandbox/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json?access_token=0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV').respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/shares/?access_token=' + profile.dropbox.accessToken + '&path=' + scope.manifestName + '&root=' + configuration.DROPBOX_TYPE + '&short_url=false').respond({ url: 'https://dl.dropboxusercontent.com/s/sy4g4yn0qygxhs5/' + scope.manifestName }); $httpBackend.whenPOST('https://api.dropbox.com/1/shares/?access_token=0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV&path=2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json&root=sandbox&short_url=false').respond({ url: 'https://dl.dropboxusercontent.com/s/sy4g4yn0qygxhs5/' + scope.manifestName }); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.apercuName + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/shares/?access_token=' + profile.dropbox.accessToken + '&path=' + scope.apercuName + '&root=' + configuration.DROPBOX_TYPE + '&short_url=false').respond({ url: 'https://dl.dropboxusercontent.com/s/sy4g4yn0qygxhs5/' + scope.apercuName }); $httpBackend.whenGET(scope.url).respond('<html manifest=""><head><script> var ownerId = null; var blocks = []; </script></head><body></body></html>'); $httpBackend.whenGET('https://api-content.dropbox.com/1/files/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentDropbox + '?access_token=' + profile.dropbox.accessToken).respond('<htlm manifest=""><head><script> var profilId = null; var blocks = []; var listDocument= []; </script></head><body></body></html>'); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentDropbox + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenGET('https://api-content.dropbox.com/1/files/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentManifest + '?access_token=' + profile.dropbox.accessToken).respond(''); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/' + scope.listDocumentManifest + '?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/search/?access_token=0beblvS8df0AAAAAAAAAAfpU6yreiprJ0qjwvbnfp3TCqjTESOSYpLIxWHYCA-LV&query=Titredudocument_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html&root=sandbox').respond({}); $httpBackend.whenPOST('https://api.dropbox.com/1/search/?access_token=' + profile.dropbox.accessToken + '&query=_' + scope.duplDocTitre + '_&root=sandbox').respond({}); $httpBackend.whenGET('https://api-content.dropbox.com/1/files/' + configuration.DROPBOX_TYPE + '/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html?access_token=' + profile.dropbox.accessToken).respond('<html manifest=""><head><script> var profilId = null; var blocks = []; var listDocument= []; </script></head><body></body></html>'); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.appcache?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenGET(configuration.URL_REQUEST + '/index.html').respond('<html manifest=""><head><script> var profilId = null; var blocks = []; var listDocument= []; </script></head><body></body></html>'); $httpBackend.whenGET('https://dl.dropboxusercontent.com/s/gk6ueltm1ckrq9u/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json').respond(jsonannotation); $httpBackend.whenGET(configuration.URL_REQUEST + '/profile?id=gk6ueltm1ckrq9u24b9855644b7c8733a69cd5bf8290bc8').respond(jsonannotation); $httpBackend.whenPUT('https://api-content.dropbox.com/1/files_put/' + configuration.DROPBOX_TYPE + '/2014-4-29_doc%20dds%20%C3%A9%C3%A9%20dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232.html?access_token=' + profile.dropbox.accessToken).respond({}); $httpBackend.whenPOST(configuration.URL_REQUEST + '/sendMail').respond({}); $httpBackend.whenGET('/2015-9-22_testsAnnotations_cf5ad4f059eb80c206e92be53b9e8d30.json').respond(mapNotes['2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232']); })); /* ApercuCtrl:init */ it('ApercuCtrl:init cas url', inject(function ($rootScope, $timeout, $q) { // case url web spyOn(scope, 'getHTMLContent').andCallFake(function () { var promiseToreturn = $q.defer(); // Place the fake return object here promiseToreturn.resolve(); return promiseToreturn.promise; }); scope.url = 'https://localhost:3000/#/apercu?url=https:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes'; scope.init(); $rootScope.$apply(); expect(scope.loader).toBe(true); expect(scope.urlHost).toEqual('localhost'); expect(scope.urlPort).toEqual(443); expect(scope.url).toEqual('https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Maîtres_anonymes'); expect(scope.docName).toEqual('https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Maîtres_anonymes'); expect(scope.docSignature).toEqual('https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Maîtres_anonymes'); scope.url = 'http://localhost:3000/#/apercu?url=http:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes'; scope.init(); expect(scope.urlPort).toEqual(80); // case url pdf scope.url = 'https://localhost:3000/#/apercu?url=https:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.pdf'; spyOn(scope, 'loadPdfByLien').andReturn(); scope.init(); $rootScope.$apply(); expect(scope.loadPdfByLien).toHaveBeenCalled(); // case url image scope.url = 'https://localhost:3000/#/apercu?url=https:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.png'; spyOn(scope, 'loadPictureByLink').andReturn(); scope.init(); $rootScope.$apply(); expect(scope.loadPictureByLink).toHaveBeenCalled(); })); it('ApercuCtrl:init cas url http', inject(function ($rootScope, $timeout, $q) { // case url web spyOn(scope, 'getHTMLContent').andCallFake(function () { var promiseToreturn = $q.defer(); // Place the fake return object here promiseToreturn.resolve(); return promiseToreturn.promise; }); scope.url = 'http://localhost:3000/#/apercu?url=http:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.pdf'; scope.init(); $rootScope.$apply(); expect(scope.loader).toBe(true); expect(scope.urlHost).toEqual('localhost'); expect(scope.urlPort).toEqual(80); expect(scope.url).toEqual('http://localhost:3000/#/apercu?url=http://fr.wikipedia.org/wiki/Maîtres_anonymes.pdf'); expect(scope.docName).toEqual('http://localhost:3000/#/apercu?url=http://fr.wikipedia.org/wiki/Maîtres_anonymes.pdf'); expect(scope.docSignature).toEqual('http://localhost:3000/#/apercu?url=http://fr.wikipedia.org/wiki/Maîtres_anonymes.pdf'); })); it('ApercuCtrl:init cas document', inject(function ($rootScope, $timeout, $q) { // Case of a document of which the contents were already loaded at least // once. logedServiceCheck = true; scope.url = null; scope.idDocument = 'test'; scope.tmp = null; scope.init(); expect(scope.loader).toBe(true); $rootScope.$apply(); expect(scope.docName).toEqual('test'); expect(scope.content).toEqual(['titre', '<h1>test</h1>']); $timeout(function () { expect(scope.loader).toBe(false); }, 1000); expect(scope.currentPage).toBe(1); // Case of a document of which the contents were never loaded spyOn(scope, 'affichageInfoDeconnecte').andCallThrough(); spyOn(fileStorageService, 'getFile').andCallFake(function () { deferred = $q.defer(); // Place the fake return object here deferred.resolve(null); return deferred.promise; }); logedServiceCheck = true; scope.url = null; scope.idDocument = 'test'; scope.tmp = null; scope.init(); expect(scope.loader).toBe(true); $rootScope.$apply(); expect(scope.affichageInfoDeconnecte).toHaveBeenCalled(); $timeout(function () { expect(scope.loader).toBe(false); }, 1000); })); it('ApercuCtrl:init cas temporaire', inject(function ($rootScope, $timeout) { logedServiceCheck = true; scope.url = null; scope.idDocument = null; scope.tmp = true; scope.init(); expect(scope.loader).toBe(true); $rootScope.$apply(); expect(scope.docName).toEqual('Aperçu Temporaire'); expect(scope.content).toEqual(['titre', '<h1>test</h1>']); $timeout(function () { expect(scope.loader).toBe(false); }, 1000); expect(scope.currentPage).toBe(1); })); it('ApercuCtrl:loadPictureByLink()', inject(function () { scope.url = 'http://localhost:3000/#/apercu?url=http:%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes.pdf'; scope.loadPictureByLink(scope.url); })); /* ApercuCtrl:dupliquerDocument */ it('ApercuCtrl:dupliquerDocument', inject(function ($httpBackend) { localStorage.setItem('compteId', compteId); serviceCheck.checkName = function () { return false; }; scope.dupliquerDocument(); $httpBackend.flush(); expect(scope.dupliquerDocument).toBeDefined(); expect(scope.showMsgSuccesvs).toBe(true); scope.duplDocTitre = null; scope.dupliquerDocument(); scope.duplDocTitre = 'iknonjn_lkjnkljnkj_/khbjhbk'; scope.dupliquerDocument(); })); it('ApercuCtrl:dupliquerDocument', inject(function ($httpBackend) { localStorage.setItem('compteId', compteId); serviceCheck.checkName = function () { return true; }; scope.dupliquerDocument(); $httpBackend.flush(); expect(scope.dupliquerDocument).toBeDefined(); expect(scope.showMsgSuccesvs).toBe(true); scope.duplDocTitre = null; scope.dupliquerDocument(); scope.duplDocTitre = 'iknonjn_lkjnkljnkj_/khbjhbk'; scope.dupliquerDocument(); })); /* ApercuCtrl:ete */ it('ApercuCtrl:ete', inject(function ($httpBackend) { scope.duplDocTitre = null; scope.ete(); })); /* ApercuCtrl:clearDupliquerDocument */ it('ApercuCtrl:clearDupliquerDocument', function () { scope.clearDupliquerDocument(); expect(scope.msgSuccess).toBe(''); expect(scope.showMsgSuccess).toBe(false); }); /* ApercuCtrl:hideLoader */ it('ApercuCtrl:hideLoader', inject(function ($timeout) { scope.hideLoader(); $timeout(function () { expect(scope.loader).toEqual(false); expect(scope.loaderMsg).toEqual(''); }, 1000); $timeout.flush(); })); /* ApercuCtrl:enableNoteAdd */ it('ApercuCtrl:enableNoteAdd', inject(function () { scope.enableNoteAdd(); expect(scope.isEnableNoteAdd).toEqual(true); })); /* ApercuCtrl:collapse */ it('ApercuCtrl:collapse', inject(function () { scope.collapse(); expect(scope.isEnableNoteAdd).toEqual(true); })); /* ApercuCtrl:editer */ it('ApercuCtrl:editer', inject(function () { scope.idDocument = 'test'; scope.editer(); expect(window.location.href).toEqual('https://localhost:3000/#/addDocument?idDocument=test'); })); /* ApercuCtrl:setActive */ it('ApercuCtrl:setActive', inject(function ($timeout) { spyOn(document, 'getElementById').andReturn({ scrollIntoView: function () { return; } }); scope.content = ['page1', 'page2', 'page3']; scope.setActive(0, 1, '52cb095fa8551d800b000012'); expect(scope.currentPage).toBe(1); $timeout.flush(); })); /* ApercuCtrl:setPage */ it('ApercuCtrl:setPage', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 1; scope.setPage(3); expect(scope.currentPage).toBe(1); scope.currentPage = 1; scope.setPage(-1); expect(scope.currentPage).toBe(1); scope.currentPage = 1; scope.setPage(0); expect(scope.currentPage).toBe(0); scope.currentPage = 1; scope.setPage(2); expect(scope.currentPage).toBe(2); }); /* ApercuCtrl:precedent */ it('ApercuCtrl:precedent', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 2; scope.precedent(); expect(scope.currentPage).toBe(1); }); /* ApercuCtrl:suivant */ it('ApercuCtrl:suivant', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 1; scope.suivant(); expect(scope.currentPage).toBe(2); }); /* ApercuCtrl:premier */ it('ApercuCtrl:premier', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 2; scope.premier(); expect(scope.currentPage).toBe(1); }); /* ApercuCtrl:dernier */ it('ApercuCtrl:dernier', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 1; scope.dernier(); expect(scope.currentPage).toBe(2); }); /* ApercuCtrl:plan */ it('ApercuCtrl:plan', function () { scope.content = ['page1', 'page2', 'page3']; scope.currentPage = 2; scope.plan(); expect(scope.currentPage).toBe(0); }); /* ApercuCtrl:afficherMenu */ it('ApercuCtrl:afficherMenu', function () { $('<div class="menu_wrapper"><button type="button" class="open_menu shown"></button></div>').appendTo('body'); scope.afficherMenu(); $('<div class="menu_wrapper"><button type="button" class="open_menu"></button></div>').appendTo('body'); scope.afficherMenu(); }); /* ApercuCtrl:socialShare */ it('ApercuCtrl:socialShare', function () { scope.clearSocialShare(); scope.loadMail(); scope.dismissConfirm(); scope.socialShare(); scope.destinataire = 'test@email'; scope.socialShare(); expect(scope.emailMsgError).not.toBe(''); scope.destinataire = '[email protected]'; scope.socialShare(); expect(scope.emailMsgError).toBe(''); localStorage.removeItem('notes'); scope.clearSocialShare(); }); /* ApercuCtrl:clearSocialShare */ it('ApercuCtrl:clearSocialShare', function () { scope.idDocument = '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232'; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); scope.clearSocialShare(); expect(scope.addAnnotation).toBe(true); scope.idDocument = 'docquinapasdenotes'; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); scope.clearSocialShare(); expect(scope.addAnnotation).toBe(false); }); /* ApercuCtrl:sendMail */ it('ApercuCtrl:sendMail', inject(function ($httpBackend) { scope.docApartager = { filename: 'file', lienApercu: 'dropbox.com' }; scope.destinataire = '[email protected]'; scope.encodeURI = 'https%3A%2F%2Flocalhost%3A3000%2F%23%2Fapercu%3Furl%3Dhttps%3A%2F%2Ffr.wikipedia.org%2Fwiki%2FMa%C3%AEtres_anonymes'; scope.sendMail(); $httpBackend.flush(); expect(scope.destinataire).toBe(''); expect(scope.sendVar).toEqual({ to: '[email protected]', content: ' a utilisé Accessidys pour partager un fichier avec vous ! dropbox.com', encoded: '<span> vient d\'utiliser Accessidys pour partager ce fichier avec vous : <a href=' + 'dropbox.com' + '>' + 'file' + '</a> </span>', prenom: 'aaaaaaa', fullName: 'aaaaaaa aaaaaaaa', doc: 'file' }); })); it('ApercuCtrl:selectionnerMultiPage', function () { scope.selectionnerMultiPage(); expect(scope.pageDe).toBe(1); expect(scope.pageA).toBe(1); }); it('ApercuCtrl:selectionnerPageDe', function () { scope.pageA = [1, 2]; scope.selectionnerPageDe(); }); it('ApercuCtrl:printByMode', inject(function ($rootScope) { scope.printMode = 1; scope.printPlan = true; scope.printByMode(); $rootScope.$apply(); scope.printMode = 2; scope.printByMode(); $rootScope.$apply(); })); it('ApercuCtrl:addNote', function () { scope.notes = notes.slice(0); scope.addNote(700, 50); expect(scope.notes.length).toBe(2); }); it('ApercuCtrl:restoreNotesStorage', function () { scope.modeImpression = false; scope.notes = notes.slice(0); scope.currentPage = 1; scope.restoreNotesStorage(1); expect(scope.notes.length).toBe(1); }); it('ApercuCtrl:editNote', function () { scope.notes = notes.slice(0); scope.docSignature = '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232'; scope.editNote(scope.notes[0]); scope.modeImpression = false; scope.editNote(scope.notes[0]); }); it('ApercuCtrl:removeNote', function () { scope.notes = notes.slice(0); scope.docSignature = '2014-4-29_doc dds éé dshds_3330b762b5a39aa67b75fc4cc666819c1aab71e2f7de1227b17df8dd73f95232'; scope.removeNote(scope.notes[0]); expect(scope.notes.length).toBe(0); }); it('ApercuCtrl:drawLineForPrintMode()', inject(function ($timeout) { scope.notes = notes.slice(0); scope.drawLineForPrintMode() $timeout.flush(); })); it('ApercuCtrl:applySharedAnnotation', inject(function ($httpBackend) { // $httpBackend.flush(); scope.annotationURL = 'https://dl.dropboxusercontent.com/s/gk6ueltm1ckrq9u/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8.json'; scope.annotationDummy = 'gk6ueltm1ckrq9u/2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8'; scope.applySharedAnnotation(); localStorage.removeItem('notes'); scope.applySharedAnnotation(); $httpBackend.flush(); scope.annotationURL = undefined; scope.applySharedAnnotation(); })); it('ApercuCtrl:setPasteNote', inject(function () { // $httpBackend.flush(); var $event = { originalEvent: { clipboardData: { getData: function () { return 'abcdg'; } } } }; scope.testEnv = false; scope.setPasteNote($event); expect(scope.pasteNote).toBeTruthy(); })); it('ApercuCtrl:prepareNote', inject(function () { // $httpBackend.flush(); var elem = document.createElement('div'); var trgt = '<span class="image_container"><img id="cut_piece" onclick="simul(event);" ng-show="(child.source!==undefined)" ng-src="data:image/png;base64iVBORw0KGgoAAAANSUhEUgAAAxUAAAQbCAYAAAD+sIb0AAAgAElEQVR4XuydBZgcxd"><span ng-show="(child.source===undefined)" onclick="simul(event);" style="width:142px;height:50px;background-color:white;display: inline-block;" dynamic="child.text | showText:30:true" class="cut_piece ng-hide"><span class="ng-scope">- Vide -</span></span></span>'; elem.className = 'active'; elem.innerHTML = trgt; var $event = { currentTarget: elem.children[0] }; var note = { texte: 'aggljj' }; scope.prepareNote(note, $event); })); it('ApercuCtrl:autoSaveNote', inject(function () { scope.notes = notes.slice(0); localStorage.setItem('notes', JSON.stringify(angular.toJson(notes))); scope.docSignature = 0; // $httpBackend.flush(); var elem = document.createElement('div'); var trgt = '<span class="image_container"><img id="cut_piece" onclick="simul(event);" ng-show="(child.source!==undefined)" ng-src="data:image/png;base64iVBORw0KGgoAAAANSUhEUgAAAxUAAAQbCAYAAAD+sIb0AAAgAElEQVR4XuydBZgcxd"><span ng-show="(child.source===undefined)" onclick="simul(event);" style="width:142px;height:50px;background-color:white;display: inline-block;" dynamic="child.text | showText:30:true" class="cut_piece ng-hide"><span class="ng-scope">- Vide -</span></span></span>'; elem.className = 'active'; elem.innerHTML = trgt; var $event = { currentTarget: elem.children[0] }; var note = { texte: 'aggljj' }; scope.autoSaveNote(note, $event); })); it('ApercuCtrl:addNoteOnClick', inject(function ($rootScope) { $rootScope.currentIndexPag = 2; scope.isEnableNoteAdd = true; var elem = document.createElement('div'); var trgt = '<span class="menu_wrapper"><span class="open_menu shown"><span class="zoneID">- Vide -</span></span></span>'; elem.className = 'active'; elem.innerHTML = trgt; var $event = { currentTarget: elem.children[0] }; scope.addNoteOnClick($event); })); it('ApercuCtrl:processAnnotation', inject(function ($httpBackend) { // $httpBackend.flush(); scope.docApartager = { filename: 'file', lienApercu: 'dropbox.com' }; scope.annotationOk = false; scope.processAnnotation(); scope.annotationOk = true; scope.testEnv = true; scope.docFullName = '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8'; scope.annotationToShare = [{ 'idNote': '1413886387872259', 'idInPage': 1, 'idDoc': '2014-10-21_buildeazy_24b9855644b7c8733a69cd5bf8290bc8', 'idPage': 1, 'texte': 'Note 1', 'x': 750, 'y': 54, 'xLink': 510, 'yLink': 49, 'styleNote': '<p data-font=\'Arial\' data-size=\'14\' data-lineheight=\'22\' data-weight=\'Gras\' data-coloration=\'Colorer les syllabes\' data-word-spacing=\'5\' data-letter-spacing=\'7\'> Note 1 </p>' }]; scope.processAnnotation(); $httpBackend.flush(); })); it('ApercuCtrl:getSelectedText', inject(function () { expect(scope.getSelectedText()).toEqual('textSelected'); // test of the selection when the browser does not support the function // getSelection window.getSelection = undefined; document.selection = { type: 'NotControl', createRange: function () { return { text: 'textSelected' }; } }; expect(scope.getSelectedText()).toEqual('textSelected'); // Test if no selection is possible. document.selection = { type: 'Control' }; expect(scope.getSelectedText()).toEqual(''); })); it('ApercuCtrl:closeOfflineSynthesisTips', inject(function () { scope.neverShowOfflineSynthesisTips = false; scope.displayOfflineSynthesisTips = true; scope.closeOfflineSynthesisTips(); expect(scope.displayOfflineSynthesisTips).toBe(false); expect(localStorage.getItem('neverShowOfflineSynthesisTips')).toEqual('false'); scope.neverShowOfflineSynthesisTips = true; scope.displayOfflineSynthesisTips = true; scope.closeOfflineSynthesisTips(); expect(scope.displayOfflineSynthesisTips).toBe(false); expect(localStorage.getItem('neverShowOfflineSynthesisTips')).toEqual('true'); })); it('ApercuCtrl:closeNoAudioRights', inject(function () { scope.displayNoAudioRights = true; scope.closeNoAudioRights(); expect(scope.displayNoAudioRights).toBe(false); })); it('ApercuCtrl:closeBrowserNotSupported', inject(function () { scope.displayBrowserNotSupported = true; scope.closeBrowserNotSupported(); expect(scope.displayBrowserNotSupported).toBe(false); })); it('ApercuCtrl:docPartage', inject(function (configuration, $rootScope) { scope.idDocument = 'test'; filesFound = [{ filepath: '/2015-9-22_monNouveauDoc_cf5ad4f059eb80c206e92be53b9e8d30.html' }]; lienPartage = 'monpartage'; scope.docPartage(); $rootScope.$apply(); expect(scope.docApartager.lienApercu.indexOf('/#/apercu?url=monpartage') > -1).toBe(true); filesFound = []; scope.docApartager = {}; scope.docPartage(); $rootScope.$apply(); expect(scope.docApartager.lienApercu).toBeUndefined(); $rootScope.isAppOnline = false; spyOn(modal, 'open').andCallThrough(); scope.docPartage(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('La fonctionnalité de partage de document nécessite un accès à internet'); var modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); var modalContent = modalParameters.resolve.reason(); var modalContent = modalParameters.resolve.forceClose(); })); it('ApercuCtrl:checkAnnotations', inject(function (configuration, $rootScope, $httpBackend) { scope.annotationURL = '/2015-9-22_testsAnnotations_cf5ad4f059eb80c206e92be53b9e8d30.json'; localStorage.setItem('notes', JSON.stringify(angular.toJson(mapNotes))); scope.checkAnnotations(); $httpBackend.flush(); expect(scope.docSignature).toEqual('testsAnnotations'); scope.annotationURL = '/2015-9-22_testsAnnotations_cf5ad4f059eb80c206e92be53b9e8d30.json'; localStorage.removeItem('notes'); scope.checkAnnotations(); $httpBackend.flush(); expect(scope.docSignature).toEqual('testsAnnotations'); scope.docSignature = undefined; scope.annotationURL = false; scope.checkAnnotations(); expect(scope.docSignature).toBeUndefined(); })); it('ApercuCtrl:destroyCkeditor', inject(function () { scope.destroyCkeditor(); expect(CKEDITOR.instances.editorAdd).toBeUndefined(); CKEDITOR.instances.secondEditeur = { setData: function () {}, getData: function () { return 'texte'; }, checkDirty: function () { return false; }, destroy: function () {}, filter: function () {} }; scope.destroyCkeditor(); expect(CKEDITOR.instances.secondEditeur).toBeUndefined(); CKEDITOR.instances.editeurUndefined = undefined; scope.destroyCkeditor(); expect(CKEDITOR.instances.editeurUndefined).toBeUndefined(); })); it('ApercuCtrl:speakOnKeyboard', inject(function ($timeout) { var eventShiftLeftArrow = { shiftKey: true, keyCode: 37 }; scope.speakOnKeyboard(eventShiftLeftArrow); var eventShift = { shiftKey: true, keyCode: 16 }; scope.speakOnKeyboard(eventShift); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(false); })); it('ApercuCtrl:checkBrowserSupported', inject(function () { scope.neverShowBrowserNotSupported = false; var result = scope.checkBrowserSupported(); expect(result).toBe(true); expect(scope.displayBrowserNotSupported).toBe(false); scope.neverShowBrowserNotSupported = true; result = scope.checkBrowserSupported(); expect(result).toBe(true); expect(scope.displayBrowserNotSupported).toBe(false); speechService.isBrowserSupported = function () { return false; }; scope.neverShowBrowserNotSupported = false; result = scope.checkBrowserSupported(); expect(result).toBe(false); expect(scope.displayBrowserNotSupported).toBe(true); })); it('ApercuCtrl:checkAudioRights', inject(function ($rootScope, $q) { scope.neverShowNoAudioRights = false; var result; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(true); expect(scope.displayNoAudioRights).toBe(false); var getDataUserResponse = {}; var toResolve = true; spyOn(serviceCheck, 'getData').andCallFake(function () { deferred = $q.defer(); // Place the fake return object here if (toResolve) { deferred.resolve({ user: getDataUserResponse }); } else { deferred.reject(); } return deferred.promise; }); scope.neverShowNoAudioRights = false; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(true); expect(scope.displayNoAudioRights).toBe(false); getDataUserResponse = { local: { authorisations: { audio: false } } }; scope.neverShowNoAudioRights = true; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(false); expect(scope.displayNoAudioRights).toBe(false); scope.neverShowNoAudioRights = false; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(false); expect(scope.displayNoAudioRights).toBe(true); toResolve = false; scope.neverShowNoAudioRights = false; scope.checkAudioRights().then(function (data) { result = data; }); $rootScope.$apply(); expect(result).toBe(true); expect(scope.displayNoAudioRights).toBe(false); })); it('ApercuCtrl:speak', inject(function ($timeout) { scope.speak(); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(false); isOnlineServiceCheck = false; scope.neverShowOfflineSynthesisTips = false; scope.speak(); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(true); isOnlineServiceCheck = false; scope.neverShowOfflineSynthesisTips = true; scope.speak(); expect(speechStopped).toBe(true); $timeout.flush(); expect(scope.displayOfflineSynthesisTips).toBe(false); })); // it('ApercuCtrl:browserSupported thruthness', // inject(function($location) { // scope.browserSupported = true; // scope.$apply(); // var hash = $location.hash(); // expect(hash).toEqual('main_header'); // }) // ); it('ApercuCtrl:checkLinkOffline', inject(function ($rootScope) { $rootScope.isAppOnline = false; var event = { target: { nodeName: 'A' }, preventDefault: function () {}, stopPropagation: function () {} }; spyOn(modal, 'open').andCallThrough(); scope.checkLinkOffline(event); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('La navigation adaptée n\'est pas disponible sans accès internet.'); $rootScope.isAppOnline = true; //We resets to 0 the number of calls to the mock. modal.open.reset(); scope.checkLinkOffline(event); // modal.open has not been called expect(modal.open).not.toHaveBeenCalled(); var modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('La navigation adaptée n\'est pas disponible sans accès internet.'); modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); modalContent = modalParameters.resolve.reason(); modalContent = modalParameters.resolve.forceClose(); })); it('ApercuCtrl:affichageInfoDeconnecte()', function () { spyOn(modal, 'open').andCallThrough(); scope.affichageInfoDeconnecte(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.reason(); expect(modalContent).toEqual('/listDocument'); modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); modalContent = modalParameters.resolve.forceClose(); modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('L\'affichage de ce document nécessite au moins un affichage préalable via internet.'); }); it('ApercuCtrl:openDocumentListModal()', function () { spyOn(modal, 'open').andCallThrough(); scope.openDocumentListModal(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/listDocument/listDocumentModal.html'); var modalContent = modalParameters.resolve.reason(); expect(modalContent).toEqual('/listDocument'); modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Pas d\'accès internet'); modalContent = modalParameters.resolve.forceClose(); modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('L\'affichage de ce document nécessite au moins un affichage préalable via internet.'); }); it('ApercuCtrl:getUserAndInitApercu()', inject(function ($rootScope, $routeParams) { // classic case spyOn(scope, 'init').andReturn(); $rootScope.loged = true; scope.getUserAndInitApercu(); $rootScope.$apply(); expect(scope.init).toHaveBeenCalled(); // The case of a shared document $routeParams.url = 'dropboxusercontent'; scope.getUserAndInitApercu(); $rootScope.$apply(); expect(scope.init).toHaveBeenCalled(); })); it('ApercuCtrl:resizeApercu ', inject(function () { // enlargement scope.resizeDocApercu = 'Réduire'; scope.resizeApercu(); expect(scope.resizeDocApercu).toEqual('Agrandir'); // reduction scope.resizeDocEditor = 'Agrandir'; scope.resizeApercu(); expect(scope.resizeDocApercu).toEqual('Réduire'); })); it('ApercuCtrl:switchModeAffichage', inject(function () { //passing the print mode to the consultation mode. scope.modeImpression = true; scope.switchModeAffichage(); expect(scope.modeImpression).toBe(false); // passing the consultation mode to print mode. scope.modeImpression = false; scope.switchModeAffichage(); expect(scope.modeImpression).toBe(true); scope.testEnv = false; scope.switchModeAffichage(); scope.tmp = false; scope.switchModeAffichage(); })); it('ApercuCtrl:fermerApercu', inject(function ($location) { // Close the overview for a nontemporary document. spyOn($location, 'path').andCallThrough(); scope.tmp = false; scope.fermerApercu(); expect($location.path).toHaveBeenCalled(); // Close the overview for a temporary document. spyOn(modal, 'open').andCallThrough(); scope.tmp = true; scope.fermerApercu(); expect(modal.open).toHaveBeenCalled(); expect(modalParameters.templateUrl).toEqual('views/common/informationModal.html'); var modalContent = modalParameters.resolve.title(); expect(modalContent).toEqual('Fermeture'); modalContent = modalParameters.resolve.content(); expect(modalContent).toEqual('Pour fermer l\'aperçu du document, veuillez fermer la fenêtre.'); modalContent = modalParameters.resolve.reason(); modalContent = modalParameters.resolve.forceClose(); })); it('ApercuCtrl:loadPdfPage', inject(function ($q, $rootScope) { var q = $q; var pdf = { getPage: function () { deferred = q.defer(); // Place the fake return object here deferred.resolve(pdfPage); return deferred.promise; }, }, pdfPage = { error: false, render: function () { deferred = q.defer(); // Place the fake return object here //deferred.resolve(this.internalRenderTask.callback()); deferred.resolve(); return deferred.promise; }, getViewport: function () { return { height: 100, width: 100 }; } }; expect(scope.loadPdfPage).toBeDefined(); scope.loadPdfPage(pdf, 1); $rootScope.$apply(); })); it('ApercuCtrl:loadPdfPage', inject(function ($q, $rootScope) { var q = $q; var pdf = { getPage: function () { deferred = q.defer(); // Place the fake return object here deferred.resolve(pdfPage); return deferred.promise; }, }, pdfPage = { error: false, render: function () { deferred = q.defer(); // Place the fake return object here //deferred.resolve(this.internalRenderTask.callback()); deferred.resolve({ error: 'error' }); return deferred.promise; }, getViewport: function () { return { height: 100, width: 100 }; } }; expect(scope.loadPdfPage).toBeDefined(); scope.loadPdfPage(pdf, 1); $rootScope.$apply(); })); it('ApercuCtrl:loadPdfByLien', inject(function () { scope.url = 'https://localhost:3000/#/apercu?url=https://www.esprit.presse.fr/whoarewe/historique.pdf'; //$httpBackend.expectPOST(/sendPdfHTTPS.*/).respond(401, ''); scope.loadPdfByLien(scope.url); scope.url = 'http://localhost:3000/#/apercu?url=http://www.esprit.presse.fr/whoarewe/historique.pdf'; scope.loadPdfByLien(scope.url); })); it('ApercuCtrl:loadPictureByLink', inject(function () { scope.url = 'https://localhost:3000/#/apercu?url=https://www.w3.org/Style/Examples/011/gevaar.png'; expect(scope.loadPictureByLink).toBeDefined(); scope.loadPictureByLink(scope.url); })); it('ApercuCtrl:getHTMLContent', function () { scope.url = 'https://localhost:3000/#/apercu?url=https://fr.wikipedia.org/wiki/Wikip%C3%A9dia'; scope.getHTMLContent(scope.url); }); it('ApercuCtrl:stopSpeech', function () { scope.stopSpeech(); }); });
Unit test Improvements on apercu
test/spec/frontend/apercu.js
Unit test Improvements on apercu
<ide><path>est/spec/frontend/apercu.js <ide> deferred.resolve(pdfPage); <ide> return deferred.promise; <ide> }, <add> numPages: 1 <ide> }, <ide> pdfPage = { <ide> error: false, <ide> }; <ide> } <ide> }; <add> <add> <add> scope.pdfTohtml = { <add> push: function (arg) { <add> return arg; <add> }, <add> filter: function (arg) { <add> return '--'; <add> } <add> }; <ide> <ide> <ide> expect(scope.loadPdfPage).toBeDefined();
Java
mit
f1aa6c673d650f57daf9eb642dc2ddec8c804da4
0
speaking-fish/java-sf-ssp
package com.speakingfish.protocol.ssp; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import static java.util.Arrays.asList; import java.util.Map.Entry; import com.speakingfish.common.annotation.Compatibility.*; import com.speakingfish.common.function.Acceptor; import com.speakingfish.common.function.Getter; import com.speakingfish.common.function.Mapper; import com.speakingfish.common.type.DefaultValue; import com.speakingfish.common.type.LocalNamed; import com.speakingfish.common.type.Named; import com.speakingfish.common.type.Typed; import com.speakingfish.protocol.ssp.type.ArrayImpl; import com.speakingfish.protocol.ssp.type.ByteArrayImpl; import com.speakingfish.protocol.ssp.type.DecimalImpl; import com.speakingfish.protocol.ssp.type.FloatImpl; import com.speakingfish.protocol.ssp.type.HolderImpl; import com.speakingfish.protocol.ssp.type.IntImpl; import com.speakingfish.protocol.ssp.type.ObjectImpl; import com.speakingfish.protocol.ssp.type.StringImpl; import static com.speakingfish.common.Maps.*; import static com.speakingfish.protocol.ssp.Helper.*; public class Types { protected Types() {} @SuppressWarnings("unchecked") public static <T> Any<T> castAnyTo(Any<?> src, Typed<T> castTo) { return (Any<T>) src; } public static <CONTEXT, T> Typed<LocalAny<CONTEXT, T>> localAnyTyped() { return null; } public static Any<String > any(String value) { return new StringImpl <Object>( value) ; } public static Any<Long > any(long value) { return new IntImpl <Object>( value) ; } public static Any<Double > any(double value) { return new FloatImpl <Object>( value) ; } public static Any<BigDecimal> any(BigDecimal value) { return new DecimalImpl <Object>( value) ; } public static Any<byte[] > any(byte[] value) { return new ByteArrayImpl<Object>( value) ; } public static Mapper<Any<?>, String > MAPPER_ANY_STRING = new Mapper<Any<?>, String >() { public Any<String > apply(String v) { return any(v); } }; public static Mapper<Any<?>, Long > MAPPER_ANY_INT = new Mapper<Any<?>, Long >() { public Any<Long > apply(Long v) { return any(v); } }; public static Mapper<Any<?>, Double > MAPPER_ANY_FLOAT = new Mapper<Any<?>, Double >() { public Any<Double > apply(Double v) { return any(v); } }; public static Mapper<Any<?>, BigDecimal> MAPPER_ANY_DECIMAL = new Mapper<Any<?>, BigDecimal>() { public Any<BigDecimal> apply(BigDecimal v) { return any(v); } }; public static Mapper<Any<?>, byte[] > MAPPER_ANY_BYTE_ARRAY= new Mapper<Any<?>, byte[] >() { public Any<byte[] > apply(byte[] v) { return any(v); } }; public static Any<AnyArray> anyArray() { return new ArrayImpl<Object>(); } @SafeVarargs public static Any<AnyArray> anyArray(Any<?>... value) { final ArrayImpl<?> result = new ArrayImpl<Object>(); if(0 < value.length) { result.addAll(asList(value)); } return result; } public static Any<AnyArray> anyArray(Collection<Any<?>> value) { final ArrayImpl<?> result = new ArrayImpl<Object>(); result.addAll(value); return result; } public static Any<AnyArray> anyArray(Iterator<Any<?>> value) { final ArrayImpl<?> result = new ArrayImpl<Object>(); result.addAll(value); return result; } public static Any<AnyObject> anyObject() { return new ObjectImpl<Object>(); } @SafeVarargs public static Any<AnyObject> anyObject(Entry<String, ? extends Any<?>>... value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries(Arrays.asList(value)); return result; } @SuppressWarnings("unchecked") @SafeVarargs public static <X extends Any<?>> Any<AnyObject> anyObjects(Entry<String, X>... value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries((Iterable<Entry<String, ? extends Any<?>>>) (Iterable<?>) asList(value)); return result; } public static Any<AnyObject> anyObject(Iterable<Entry<String, ? extends Any<?>>> value) { //public static Any<AnyObject> anyObject(Iterable<Entry<String, ? extends Any<?>>> value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries(value); return result; } @SuppressWarnings("unchecked") public static <X extends Any<?>> Any<AnyObject> anyObjects(Iterable<Entry<String, X>> value) { //public static Any<AnyObject> anyObject(Iterable<Entry<String, ? extends Any<?>>> value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries((Iterable<Entry<String, ? extends Any<?>>>) (Iterable<?>) value); return result; } @SafeVarargs //public static Any<AnyObject> namedAnyObject(Entry<? extends Named<?>, ? extends Any<?>>... value) { public static <E extends Entry<? extends Named<?>, ? extends Any<?>>> Any<AnyObject> namedAnyObject(E... value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addNamedEntries(asList(value)); return result; } public static Any<AnyObject> namedAnyObject(Iterable<? extends Entry<? extends Named<?>, ? extends Any<?>>> value) { //public static Any<AnyObject> namedAnyObject(Iterable<Entry<Named<?>, Any<?>>> value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addNamedEntries(value); return result; } public static <CONTEXT> LocalAny<CONTEXT, String > localAny(String value) { return new StringImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, Long > localAny(long value) { return new IntImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, Double > localAny(double value) { return new FloatImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, BigDecimal> localAny(BigDecimal value) { return new DecimalImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, byte[] > localAny(byte[] value) { return new ByteArrayImpl<CONTEXT>( value) ; } public static <CONTEXT> LocalAnyArray<CONTEXT> localAnyArray() { return new ArrayImpl<CONTEXT>(); } public static <CONTEXT> LocalAnyObject<CONTEXT> localAnyObject() { return new ObjectImpl<CONTEXT>(); } // /* // @SuppressWarnings("unchecked") // public static <CONTEXT/*, RESULT extends LocalAnyArray<CONTEXT>*/> /*RESULT*/ LocalAny<CONTEXT, AnyArray> localAny( // LocalAny<?, ?>... value // ) { // final ArrayImpl<CONTEXT> result = new ArrayImpl<CONTEXT>(); // result.addAll((Collection<Any<?>>) (Collection<?>) asList(value)); // return /*(RESULT)*/ result; // } // @SuppressWarnings("unchecked") @SafeVarargs public static <CONTEXT> LocalAnyObject<CONTEXT> localAnyObject( Entry<? extends LocalNamed<CONTEXT, ?>, ? extends LocalAny<?, ?>>... value ) { //(Collection<Entry<String, ? extends Any<?>>>) (Collection<?>) asList(value)); final ObjectImpl<CONTEXT> result = new ObjectImpl<CONTEXT>(); result.addLocalEntries(asList(value)); return result; } // */ public static < T> Any < T> anyHolder(Getter<T> value) { return new HolderImpl<Object , T>(value) ; } public static <CONTEXT, T> LocalAny<CONTEXT, T> localAnyHolder(Getter<T> value) { return new HolderImpl<CONTEXT, T>(value) ; } public static < T, ANY_T extends Any<T> > Entry<String, ANY_T> entry( String name , ANY_T value ) { return keyValue(name, value); } public static < T, NAMED_T extends Named<T>, ANY_T extends Any <T> > Entry<NAMED_T, ANY_T> namedEntry( NAMED_T name , ANY_T value ) { return keyValue(name, value); } public static < T, CONTEXT, LOCAL_NAMED_CONTEXT_T extends LocalNamed<CONTEXT, T>, ANY_T extends Any <T > > Entry<LOCAL_NAMED_CONTEXT_T, ANY_T> namedEntry( LOCAL_NAMED_CONTEXT_T name , ANY_T value ) { return keyValue(name, value); } @SuppressWarnings("unchecked") public static < T, T_CONTEXT, T_SUBCONTEXT, T_LocalNamed__CONTEXT_T extends LocalNamed<T_CONTEXT , T>, T_LocalAny__SUBCONTEXT_T extends LocalAny <T_SUBCONTEXT, T>/*, T_Any__T extends Any < T>*/ > Entry<T_LocalNamed__CONTEXT_T, T_LocalAny__SUBCONTEXT_T> localEntry( T_LocalNamed__CONTEXT_T name , //T_Any__T value Any<T> value ) { return keyValue(name, (T_LocalAny__SUBCONTEXT_T) value); } public static Entry<String, Any<String >> named(String name, String value) { return entry(name, any(value)); } public static Entry<String, Any<Long >> named(String name, long value) { return entry(name, any(value)); } public static Entry<String, Any<Double >> named(String name, double value) { return entry(name, any(value)); } public static Entry<String, Any<BigDecimal>> named(String name, BigDecimal value) { return entry(name, any(value)); } public static Entry<String, Any<byte[] >> named(String name, byte[] value) { return entry(name, any(value)); } public static <T> Entry<String, Any<T >> named(String name, Any<T> value) { return entry(name, value); } public static Entry<String, Any<AnyArray >> namedArray(String name, Any<?>... value) { return entry(name, anyArray(value)); } public static Entry<String, Any<AnyArray >> namedArray(String name, Iterable<Any<?>> value) { return entry(name, anyArray(value.iterator())); } @SafeVarargs public static Entry<String, Any<AnyObject >> namedObject(String name, Entry<String, ? extends Any<?>>... value) { return entry(name, anyObject(value)); } public static Entry<String, Any<AnyObject >> namedObject(String name, Iterable<Entry<String, ? extends Any<?>>> value) { return entry(name, anyObject(value)); } public static <T> Entry<String, Any<T>>namedHolder(String name, Getter<T> value) { return entry(name, anyHolder(value)); } public static Entry<Named<String >, Any<String >> named(Named<String > name, String value) { return namedEntry(name, any(value)); } public static Entry<Named<Long >, Any<Long >> named(Named<Long > name, long value) { return namedEntry(name, any(value)); } public static Entry<Named<Double >, Any<Double >> named(Named<Double > name, double value) { return namedEntry(name, any(value)); } public static Entry<Named<BigDecimal>, Any<BigDecimal>> named(Named<BigDecimal> name, BigDecimal value) { return namedEntry(name, any(value)); } public static Entry<Named<byte[] >, Any<byte[] >> named(Named<byte[] > name, byte[] value) { return namedEntry(name, any(value)); } public static <T> Entry<Named<T >, Any<T >> named(Named<T > name, Any<T> value) { return namedEntry(name, value ); } public static Entry<Named<AnyArray >, Any<AnyArray >> namedArray(Named<AnyArray > name, Any<?>... value) { return namedEntry(name, anyArray(value)); } public static Entry<Named<AnyArray >, Any<AnyArray >> namedArray(Named<AnyArray > name, Iterable<Any<?>> value) { return namedEntry(name, anyArray(value.iterator())); } @SafeVarargs public static Entry<Named<AnyObject >, Any<AnyObject >> namedObject(Named<AnyObject> name, Entry<? extends Named<?>, ? extends Any<?>>... value) { return namedEntry(name, namedAnyObject(value)); } public static Entry<Named<AnyObject >, Any<AnyObject >> namedObject(Named<AnyObject> name, Iterable<? extends Entry<? extends Named<?>, ? extends Any<?>>> value) { return namedEntry(name, namedAnyObject(value)); } public static <T> Entry<Named<T >, Any<T >> namedHolder(Named<T > name, Getter<T> value) { return namedEntry(name, anyHolder(value)); } //Entry<T_LocalNamed__CONTEXT_T, T_LocalAny__SUBCONTEXT_T> public static <C, S, LN extends LocalNamed<C, String >, LA extends LocalAny<S, String >> Entry<LN, LA> local(LN name, String value) { return Types.<String , C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, Long >, LA extends LocalAny<S, Long >> Entry<LN, LA> local(LN name, long value) { return Types.<Long , C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, Double >, LA extends LocalAny<S, Double >> Entry<LN, LA> local(LN name, double value) { return Types.<Double , C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, BigDecimal>, LA extends LocalAny<S, BigDecimal>> Entry<LN, LA> local(LN name, BigDecimal value) { return Types.<BigDecimal, C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, byte[] >, LA extends LocalAny<S, byte[] >> Entry<LN, LA> local(LN name, byte[] value) { return Types.<byte[] , C, S, LN, LA>localEntry(name, any(value)); } /// /// "T_" = generic name prefix /// "__" = generic start = "<" /// "_" = generic delimiter = "," /// "___" = generic end = ">" (trailings skipped, "," skipped) /// for ex: T_MyClass1__MyClass2__Integer_Boolean___String /// mean: MyClass1< MyClass2< Integer,Boolean> String> /// postfix ,:MyClass1< MyClass2< Integer,Boolean>, String> // @SafeVarargs // public static < // T_Context, // //T_Subcontext, // T_LocalAnyArray__T_Subcontext extends LocalAny<T_Context, AnyArray>/*LocalAnyArray<?T_Subcontext>*/, // T_LocalNamed__T_Context_T_LocalAnyArray__T_Subcontext extends LocalNamed<T_Context, T_LocalAnyArray__T_Subcontext> // > Entry< // T_LocalNamed__T_Context_T_LocalAnyArray__T_Subcontext, // T_LocalAnyArray__T_Subcontext // > localArray( // T_LocalNamed__T_Context_T_LocalAnyArray__T_Subcontext name , // LocalAny <?/*T_Subcontext*/, ? >... value // ) { // return keyValue(name, Types.<Object/*T_Subcontext*/, T_LocalAnyArray__T_Subcontext>localAny(value)); // } // // @SafeVarargs // public static < // T_Context, // //T_Subcontext, // T_LocalAnyObject__T_SubContext extends LocalAny<?, AnyObject>/*LocalAnyObject<T_Subcontext>*/, // T_LocalNamed__T_Context_T_LocalAnyObject__T_SubContext extends LocalNamed<T_Context, T_LocalAnyObject__T_SubContext> // > Entry< // T_LocalNamed__T_Context_T_LocalAnyObject__T_SubContext, // T_LocalAnyObject__T_SubContext // > local( // T_LocalNamed__T_Context_T_LocalAnyObject__T_SubContext name, // Entry<LocalNamed<?/*T_Subcontext*/, ?>, ? extends LocalAny<?, ?>>... value // ) { // return keyValue(name, Types.<Object/*T_Subcontext*/, T_LocalAnyObject__T_SubContext>localAny(value)); // } public static <T> T valueOf(Any<T> src) { return (null == src) ? null : src.get(); } public static <T> T valueOf(Any<T> any, T defaultValue) { return (null == any) ? defaultValue : any.get(); } public static <T> T valueOf(Any<?> any, Named<T> name, T defaultValue) { return (null == any) ? defaultValue : valueOf(any.item(name), defaultValue); } public static <C, T> T valueOf(LocalAny<C, ?> any, LocalNamed<C, T> name) { return valueOf(any, name, null); } public static <C, T> T valueOf(LocalAny<C, ?> any, LocalNamed<C, T> name, T defaultValue) { return (null == any) ? defaultValue : valueOf(any.item(name), defaultValue); } /* public static <T> T valueOf(Any<?> any, Named<T> name) { return valueOf(any, name, null); } */ public static <T> T valueOf(Any<?> any, DefaultValue<Named<T>, T> name) { return valueOf(any, name.origin(), name.defaultValue()); } public static <C, T> T valueOf(LocalAny<C, ?> any, DefaultValue<LocalNamed<C, T>, T> name) { return valueOf(any, name.origin(), name.defaultValue()); } // public static <CONTEXT, SUBCONTEXT, T> Entry<LocalNamed<CONTEXT, T>, LocalAny<SUBCONTEXT, T>> localHolder( // LocalNamed<CONTEXT, T> name, Getter<T>value // ) { // //return localEntry(name, Types.<SUBCONTEXT, T>localAnyHolder(value)); // return Types.<T, CONTEXT, SUBCONTEXT, LocalNamed<CONTEXT, T>, LocalAny<SUBCONTEXT, T>>localEntry(name, anyHolder(value)); // } public static < T, T_CONTEXT, T_SUBCONTEXT, T_LocalNamed__T_CONTEXT__T extends LocalNamed<T_CONTEXT, T>, T_LocalAny__T_SUBCONTEXT__T extends LocalAny<T_SUBCONTEXT, T> > Entry<T_LocalNamed__T_CONTEXT__T, T_LocalAny__T_SUBCONTEXT__T> localHolder( T_LocalNamed__T_CONTEXT__T name, Getter<T> value ) { //return localEntry(name, Types.<SUBCONTEXT, T>localAnyHolder(value)); //return Types.<T, CONTEXT, SUBCONTEXT, LocalNamed<CONTEXT, T>, LocalAny<SUBCONTEXT, T>>localEntry(name, anyHolder(value)); return Types.<T, T_CONTEXT, T_SUBCONTEXT, T_LocalNamed__T_CONTEXT__T, T_LocalAny__T_SUBCONTEXT__T>localEntry(name, anyHolder(value)); } public static int serializableSize(Any<?> src) { int size = 0; for(int i = 0; i < src.size(); ++i) { if(isSerializable(src.item(i))) { ++size; } } return size; } public static boolean isSerializable(Any<?> item) { return SSP_TYPE_HOLDER != item.type(); } public static final Acceptor<Any<?>> ACCEPTOR_SERIALIZABLE = new Acceptor<Any<?>>() { public boolean test(Any<?> src) { return isSerializable(src); } }; public static boolean matchMask(Any<?> src, Any<?> mask) { if(SSP_TYPE_ARRAY == src.type()) { return false; // src=[] } else if(SSP_TYPE_OBJECT == src.type()) { // src={} if(SSP_TYPE_ARRAY == mask.type()) { return false; // src={} mask=[] } else if(SSP_TYPE_OBJECT == mask.type()) { // src={} mask={} outer: for(int i = 0; i < mask.size(); ++i) { final Any<?> srcField = src.item(mask.nameOf(i)); if(null != srcField) { final Any<?> maskField = mask.item(i); if(SSP_TYPE_ARRAY == maskField.type()) { // src={field:?} mask={field:[]} for(int m = 0; m < maskField.size(); ++m) { if(srcField.equals(maskField)) { continue outer; // src={field:value1} mask={field:[value0,value1,value2]} } } return false; } else if(SSP_TYPE_OBJECT == maskField.type()) { return false; // src={field:?} mask={field:{}} } else if(!srcField.equals(maskField)) { return false; // src={field:?} mask={field:value} } } } return true; } else { return false; // src={} mask=value } } else { return false; // src=value } } public static final Mapper<String, Any<?>> MAPPER_ANY_AS_STRING = new Mapper<String, Any<?>>() { public String apply(Any<?> value) { return value.asString(); } }; public static final Mapper<Object, Any<?>> MAPPER_ANY_VALUE = new Mapper<Object, Any<?>>() { public Object apply(Any<?> value) { return value.get(); } }; public static final Mapper<Entry<String, Object>, Entry<String, Any<?>>> MAPPER_MAKE_ENTRY_ANY_VALUE = makeEntryValueMapper(MAPPER_ANY_VALUE); /** * * @param parent * @param name * @param value * @return previous value or null */ public static final <T> Any<T> addUpdate(Any<?> parent, String name, Any<T> value) { @SuppressWarnings("unchecked") final Any<T> result = (Any<T>) parent.item(name); if(null != result) { parent.update(name, value); return result; } else { parent.add(name, value); return null; } } public static final <T> Any<T> addUpdate(Any<?> parent, Named<T> name, Any<T> value) { return addUpdate(parent, name.id(), value); } public static final <CONTEXT, T> Any<T> addUpdate(LocalAny<CONTEXT, ?> parent, LocalNamed<CONTEXT, T> name, Any<T> value) { return addUpdate(parent, name.id(), value); } /** * * @param parent * @param name * @param value * @return old existing or new added value */ public static final <T> Any<T> addAbsent(Any<?> parent, String name, Any<T> value) { @SuppressWarnings("unchecked") final Any<T> result = (Any<T>) parent.item(name); if(null != result) { return result; } else { parent.add(name, value); return value; } } public static final <T> Any<T> addAbsent(Any<?> parent, Named<T> name, Any<T> value) { return addAbsent(parent, name.id(), value); } public static final <CONTEXT, T> Any<T> addAbsent(LocalAny<CONTEXT, ?> parent, LocalNamed<CONTEXT, T> name, Any<T> value) { return addAbsent(parent, name.id(), value); } static { Dummy.dummy(); } }
src/com/speakingfish/protocol/ssp/Types.java
package com.speakingfish.protocol.ssp; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import static java.util.Arrays.asList; import java.util.Map.Entry; import com.speakingfish.common.annotation.Compatibility.*; import com.speakingfish.common.function.Acceptor; import com.speakingfish.common.function.Getter; import com.speakingfish.common.function.Mapper; import com.speakingfish.common.type.DefaultValue; import com.speakingfish.common.type.LocalNamed; import com.speakingfish.common.type.Named; import com.speakingfish.common.type.Typed; import com.speakingfish.protocol.ssp.type.ArrayImpl; import com.speakingfish.protocol.ssp.type.ByteArrayImpl; import com.speakingfish.protocol.ssp.type.DecimalImpl; import com.speakingfish.protocol.ssp.type.FloatImpl; import com.speakingfish.protocol.ssp.type.HolderImpl; import com.speakingfish.protocol.ssp.type.IntImpl; import com.speakingfish.protocol.ssp.type.ObjectImpl; import com.speakingfish.protocol.ssp.type.StringImpl; import static com.speakingfish.common.Maps.*; import static com.speakingfish.protocol.ssp.Helper.*; public class Types { protected Types() {} @SuppressWarnings("unchecked") public static <T> Any<T> castAnyTo(Any<?> src, Typed<T> castTo) { return (Any<T>) src; } public static <CONTEXT, T> Typed<LocalAny<CONTEXT, T>> localAnyTyped() { return null; } public static Any<String > any(String value) { return new StringImpl <Object>( value) ; } public static Any<Long > any(long value) { return new IntImpl <Object>( value) ; } public static Any<Double > any(double value) { return new FloatImpl <Object>( value) ; } public static Any<BigDecimal> any(BigDecimal value) { return new DecimalImpl <Object>( value) ; } public static Any<byte[] > any(byte[] value) { return new ByteArrayImpl<Object>( value) ; } public static Mapper<Any<?>, String > MAPPER_ANY_STRING = new Mapper<Any<?>, String >() { public Any<String > apply(String v) { return any(v); } }; public static Mapper<Any<?>, Long > MAPPER_ANY_INT = new Mapper<Any<?>, Long >() { public Any<Long > apply(Long v) { return any(v); } }; public static Mapper<Any<?>, Double > MAPPER_ANY_FLOAT = new Mapper<Any<?>, Double >() { public Any<Double > apply(Double v) { return any(v); } }; public static Mapper<Any<?>, BigDecimal> MAPPER_ANY_DECIMAL = new Mapper<Any<?>, BigDecimal>() { public Any<BigDecimal> apply(BigDecimal v) { return any(v); } }; public static Mapper<Any<?>, byte[] > MAPPER_ANY_BYTE_ARRAY= new Mapper<Any<?>, byte[] >() { public Any<byte[] > apply(byte[] v) { return any(v); } }; public static Any<AnyArray> anyArray() { return new ArrayImpl<Object>(); } @SafeVarargs public static Any<AnyArray> anyArray(Any<?>... value) { final ArrayImpl<?> result = new ArrayImpl<Object>(); if(0 < value.length) { result.addAll(asList(value)); } return result; } public static Any<AnyArray> anyArray(Collection<Any<?>> value) { final ArrayImpl<?> result = new ArrayImpl<Object>(); result.addAll(value); return result; } public static Any<AnyArray> anyArray(Iterator<Any<?>> value) { final ArrayImpl<?> result = new ArrayImpl<Object>(); result.addAll(value); return result; } public static Any<AnyObject> anyObject() { return new ObjectImpl<Object>(); } @SafeVarargs public static Any<AnyObject> anyObject(Entry<String, ? extends Any<?>>... value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries(Arrays.asList(value)); return result; } @SuppressWarnings("unchecked") @SafeVarargs public static <X extends Any<?>> Any<AnyObject> anyObjects(Entry<String, X>... value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries((Iterable<Entry<String, ? extends Any<?>>>) (Iterable<?>) asList(value)); return result; } public static Any<AnyObject> anyObject(Iterable<Entry<String, ? extends Any<?>>> value) { //public static Any<AnyObject> anyObject(Iterable<Entry<String, ? extends Any<?>>> value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries(value); return result; } @SuppressWarnings("unchecked") public static <X extends Any<?>> Any<AnyObject> anyObjects(Iterable<Entry<String, X>> value) { //public static Any<AnyObject> anyObject(Iterable<Entry<String, ? extends Any<?>>> value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addStringEntries((Iterable<Entry<String, ? extends Any<?>>>) (Iterable<?>) value); return result; } @SafeVarargs //public static Any<AnyObject> namedAnyObject(Entry<? extends Named<?>, ? extends Any<?>>... value) { public static <E extends Entry<? extends Named<?>, ? extends Any<?>>> Any<AnyObject> namedAnyObject(E... value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addNamedEntries(asList(value)); return result; } public static Any<AnyObject> namedAnyObject(Iterable<? extends Entry<? extends Named<?>, ? extends Any<?>>> value) { //public static Any<AnyObject> namedAnyObject(Iterable<Entry<Named<?>, Any<?>>> value) { final ObjectImpl<?> result = new ObjectImpl<Object>(); result.addNamedEntries(value); return result; } public static <CONTEXT> LocalAny<CONTEXT, String > localAny(String value) { return new StringImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, Long > localAny(long value) { return new IntImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, Double > localAny(double value) { return new FloatImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, BigDecimal> localAny(BigDecimal value) { return new DecimalImpl <CONTEXT>( value) ; } public static <CONTEXT> LocalAny<CONTEXT, byte[] > localAny(byte[] value) { return new ByteArrayImpl<CONTEXT>( value) ; } public static <CONTEXT> LocalAnyArray<CONTEXT> localAnyArray() { return new ArrayImpl<CONTEXT>(); } public static <CONTEXT> LocalAnyObject<CONTEXT> localAnyObject() { return new ObjectImpl<CONTEXT>(); } // /* // @SuppressWarnings("unchecked") // public static <CONTEXT/*, RESULT extends LocalAnyArray<CONTEXT>*/> /*RESULT*/ LocalAny<CONTEXT, AnyArray> localAny( // LocalAny<?, ?>... value // ) { // final ArrayImpl<CONTEXT> result = new ArrayImpl<CONTEXT>(); // result.addAll((Collection<Any<?>>) (Collection<?>) asList(value)); // return /*(RESULT)*/ result; // } // @SuppressWarnings("unchecked") @SafeVarargs public static <CONTEXT> LocalAnyObject<CONTEXT> localAnyObject( Entry<? extends LocalNamed<CONTEXT, ?>, ? extends LocalAny<?, ?>>... value ) { //(Collection<Entry<String, ? extends Any<?>>>) (Collection<?>) asList(value)); final ObjectImpl<CONTEXT> result = new ObjectImpl<CONTEXT>(); result.addLocalEntries(asList(value)); return result; } // */ public static < T> Any < T> anyHolder(Getter<T> value) { return new HolderImpl<Object , T>(value) ; } public static <CONTEXT, T> LocalAny<CONTEXT, T> localAnyHolder(Getter<T> value) { return new HolderImpl<CONTEXT, T>(value) ; } public static < T, ANY_T extends Any<T> > Entry<String, ANY_T> entry( String name , ANY_T value ) { return keyValue(name, value); } public static < T, NAMED_T extends Named<T>, ANY_T extends Any <T> > Entry<NAMED_T, ANY_T> namedEntry( NAMED_T name , ANY_T value ) { return keyValue(name, value); } public static < T, CONTEXT, LOCAL_NAMED_CONTEXT_T extends LocalNamed<CONTEXT, T>, ANY_T extends Any <T > > Entry<LOCAL_NAMED_CONTEXT_T, ANY_T> namedEntry( LOCAL_NAMED_CONTEXT_T name , ANY_T value ) { return keyValue(name, value); } @SuppressWarnings("unchecked") public static < T, T_CONTEXT, T_SUBCONTEXT, T_LocalNamed__CONTEXT_T extends LocalNamed<T_CONTEXT , T>, T_LocalAny__SUBCONTEXT_T extends LocalAny <T_SUBCONTEXT, T>/*, T_Any__T extends Any < T>*/ > Entry<T_LocalNamed__CONTEXT_T, T_LocalAny__SUBCONTEXT_T> localEntry( T_LocalNamed__CONTEXT_T name , //T_Any__T value Any<T> value ) { return keyValue(name, (T_LocalAny__SUBCONTEXT_T) value); } public static Entry<String, Any<String >> named(String name, String value) { return entry(name, any(value)); } public static Entry<String, Any<Long >> named(String name, long value) { return entry(name, any(value)); } public static Entry<String, Any<Double >> named(String name, double value) { return entry(name, any(value)); } public static Entry<String, Any<BigDecimal>> named(String name, BigDecimal value) { return entry(name, any(value)); } public static Entry<String, Any<byte[] >> named(String name, byte[] value) { return entry(name, any(value)); } public static <T> Entry<String, Any<T >> named(String name, Any<T> value) { return entry(name, value); } public static Entry<String, Any<AnyArray >> namedArray(String name, Any<?>... value) { return entry(name, anyArray(value)); } public static Entry<String, Any<AnyArray >> namedArray(String name, Iterable<Any<?>> value) { return entry(name, anyArray(value.iterator())); } @SafeVarargs public static Entry<String, Any<AnyObject >> namedObject(String name, Entry<String, ? extends Any<?>>... value) { return entry(name, anyObject(value)); } public static Entry<String, Any<AnyObject >> namedObject(String name, Iterable<Entry<String, ? extends Any<?>>> value) { return entry(name, anyObject(value)); } public static <T> Entry<String, Any<T>>namedHolder(String name, Getter<T> value) { return entry(name, anyHolder(value)); } public static Entry<Named<String >, Any<String >> named(Named<String > name, String value) { return namedEntry(name, any(value)); } public static Entry<Named<Long >, Any<Long >> named(Named<Long > name, long value) { return namedEntry(name, any(value)); } public static Entry<Named<Double >, Any<Double >> named(Named<Double > name, double value) { return namedEntry(name, any(value)); } public static Entry<Named<BigDecimal>, Any<BigDecimal>> named(Named<BigDecimal> name, BigDecimal value) { return namedEntry(name, any(value)); } public static Entry<Named<byte[] >, Any<byte[] >> named(Named<byte[] > name, byte[] value) { return namedEntry(name, any(value)); } public static <T> Entry<Named<T >, Any<T >> named(Named<T > name, Any<T> value) { return namedEntry(name, value ); } public static Entry<Named<AnyArray >, Any<AnyArray >> namedArray(Named<AnyArray > name, Any<?>... value) { return namedEntry(name, anyArray(value)); } public static Entry<Named<AnyArray >, Any<AnyArray >> namedArray(Named<AnyArray > name, Iterable<Any<?>> value) { return namedEntry(name, anyArray(value.iterator())); } @SafeVarargs public static Entry<Named<AnyObject >, Any<AnyObject >> namedObject(Named<AnyObject> name, Entry<? extends Named<?>, ? extends Any<?>>... value) { return namedEntry(name, namedAnyObject(value)); } public static Entry<Named<AnyObject >, Any<AnyObject >> namedObject(Named<AnyObject> name, Iterable<? extends Entry<? extends Named<?>, ? extends Any<?>>> value) { return namedEntry(name, namedAnyObject(value)); } public static <T> Entry<Named<T >, Any<T >> namedHolder(Named<T > name, Getter<T> value) { return namedEntry(name, anyHolder(value)); } //Entry<T_LocalNamed__CONTEXT_T, T_LocalAny__SUBCONTEXT_T> public static <C, S, LN extends LocalNamed<C, String >, LA extends LocalAny<S, String >> Entry<LN, LA> local(LN name, String value) { return Types.<String , C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, Long >, LA extends LocalAny<S, Long >> Entry<LN, LA> local(LN name, long value) { return Types.<Long , C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, Double >, LA extends LocalAny<S, Double >> Entry<LN, LA> local(LN name, double value) { return Types.<Double , C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, BigDecimal>, LA extends LocalAny<S, BigDecimal>> Entry<LN, LA> local(LN name, BigDecimal value) { return Types.<BigDecimal, C, S, LN, LA>localEntry(name, any(value)); } public static <C, S, LN extends LocalNamed<C, byte[] >, LA extends LocalAny<S, byte[] >> Entry<LN, LA> local(LN name, byte[] value) { return Types.<byte[] , C, S, LN, LA>localEntry(name, any(value)); } /// /// "T_" = generic name prefix /// "__" = generic start = "<" /// "_" = generic delimiter = "," /// "___" = generic end = ">" (trailings skipped, "," skipped) /// for ex: T_MyClass1__MyClass2__Integer_Boolean___String /// mean: MyClass1< MyClass2< Integer,Boolean> String> /// postfix ,:MyClass1< MyClass2< Integer,Boolean>, String> // @SafeVarargs // public static < // T_Context, // //T_Subcontext, // T_LocalAnyArray__T_Subcontext extends LocalAny<T_Context, AnyArray>/*LocalAnyArray<?T_Subcontext>*/, // T_LocalNamed__T_Context_T_LocalAnyArray__T_Subcontext extends LocalNamed<T_Context, T_LocalAnyArray__T_Subcontext> // > Entry< // T_LocalNamed__T_Context_T_LocalAnyArray__T_Subcontext, // T_LocalAnyArray__T_Subcontext // > localArray( // T_LocalNamed__T_Context_T_LocalAnyArray__T_Subcontext name , // LocalAny <?/*T_Subcontext*/, ? >... value // ) { // return keyValue(name, Types.<Object/*T_Subcontext*/, T_LocalAnyArray__T_Subcontext>localAny(value)); // } // // @SafeVarargs // public static < // T_Context, // //T_Subcontext, // T_LocalAnyObject__T_SubContext extends LocalAny<?, AnyObject>/*LocalAnyObject<T_Subcontext>*/, // T_LocalNamed__T_Context_T_LocalAnyObject__T_SubContext extends LocalNamed<T_Context, T_LocalAnyObject__T_SubContext> // > Entry< // T_LocalNamed__T_Context_T_LocalAnyObject__T_SubContext, // T_LocalAnyObject__T_SubContext // > local( // T_LocalNamed__T_Context_T_LocalAnyObject__T_SubContext name, // Entry<LocalNamed<?/*T_Subcontext*/, ?>, ? extends LocalAny<?, ?>>... value // ) { // return keyValue(name, Types.<Object/*T_Subcontext*/, T_LocalAnyObject__T_SubContext>localAny(value)); // } public static <T> T valueOf(Any<T> src) { return (null == src) ? null : src.get(); } public static <T> T valueOf(Any<T> any, T defaultValue) { return (null == any) ? defaultValue : any.get(); } public static <T> T valueOf(Any<?> any, Named<T> name, T defaultValue) { return (null == any) ? defaultValue : valueOf(any.item(name), defaultValue); } public static <C, T> T valueOf(LocalAny<C, ?> any, LocalNamed<C, T> name, T defaultValue) { return (null == any) ? defaultValue : valueOf(any.item(name), defaultValue); } /* public static <T> T valueOf(Any<?> any, Named<T> name) { return valueOf(any, name, null); } */ public static <T> T valueOf(Any<?> any, DefaultValue<Named<T>, T> name) { return valueOf(any, name.origin(), name.defaultValue()); } public static <C, T> T valueOf(LocalAny<C, ?> any, DefaultValue<LocalNamed<C, T>, T> name) { return valueOf(any, name.origin(), name.defaultValue()); } // public static <CONTEXT, SUBCONTEXT, T> Entry<LocalNamed<CONTEXT, T>, LocalAny<SUBCONTEXT, T>> localHolder( // LocalNamed<CONTEXT, T> name, Getter<T>value // ) { // //return localEntry(name, Types.<SUBCONTEXT, T>localAnyHolder(value)); // return Types.<T, CONTEXT, SUBCONTEXT, LocalNamed<CONTEXT, T>, LocalAny<SUBCONTEXT, T>>localEntry(name, anyHolder(value)); // } public static < T, T_CONTEXT, T_SUBCONTEXT, T_LocalNamed__T_CONTEXT__T extends LocalNamed<T_CONTEXT, T>, T_LocalAny__T_SUBCONTEXT__T extends LocalAny<T_SUBCONTEXT, T> > Entry<T_LocalNamed__T_CONTEXT__T, T_LocalAny__T_SUBCONTEXT__T> localHolder( T_LocalNamed__T_CONTEXT__T name, Getter<T> value ) { //return localEntry(name, Types.<SUBCONTEXT, T>localAnyHolder(value)); //return Types.<T, CONTEXT, SUBCONTEXT, LocalNamed<CONTEXT, T>, LocalAny<SUBCONTEXT, T>>localEntry(name, anyHolder(value)); return Types.<T, T_CONTEXT, T_SUBCONTEXT, T_LocalNamed__T_CONTEXT__T, T_LocalAny__T_SUBCONTEXT__T>localEntry(name, anyHolder(value)); } public static int serializableSize(Any<?> src) { int size = 0; for(int i = 0; i < src.size(); ++i) { if(isSerializable(src.item(i))) { ++size; } } return size; } public static boolean isSerializable(Any<?> item) { return SSP_TYPE_HOLDER != item.type(); } public static final Acceptor<Any<?>> ACCEPTOR_SERIALIZABLE = new Acceptor<Any<?>>() { public boolean test(Any<?> src) { return isSerializable(src); } }; public static boolean matchMask(Any<?> src, Any<?> mask) { if(SSP_TYPE_ARRAY == src.type()) { return false; // src=[] } else if(SSP_TYPE_OBJECT == src.type()) { // src={} if(SSP_TYPE_ARRAY == mask.type()) { return false; // src={} mask=[] } else if(SSP_TYPE_OBJECT == mask.type()) { // src={} mask={} outer: for(int i = 0; i < mask.size(); ++i) { final Any<?> srcField = src.item(mask.nameOf(i)); if(null != srcField) { final Any<?> maskField = mask.item(i); if(SSP_TYPE_ARRAY == maskField.type()) { // src={field:?} mask={field:[]} for(int m = 0; m < maskField.size(); ++m) { if(srcField.equals(maskField)) { continue outer; // src={field:value1} mask={field:[value0,value1,value2]} } } return false; } else if(SSP_TYPE_OBJECT == maskField.type()) { return false; // src={field:?} mask={field:{}} } else if(!srcField.equals(maskField)) { return false; // src={field:?} mask={field:value} } } } return true; } else { return false; // src={} mask=value } } else { return false; // src=value } } public static final Mapper<String, Any<?>> MAPPER_ANY_AS_STRING = new Mapper<String, Any<?>>() { public String apply(Any<?> value) { return value.asString(); } }; public static final Mapper<Object, Any<?>> MAPPER_ANY_VALUE = new Mapper<Object, Any<?>>() { public Object apply(Any<?> value) { return value.get(); } }; public static final Mapper<Entry<String, Object>, Entry<String, Any<?>>> MAPPER_MAKE_ENTRY_ANY_VALUE = makeEntryValueMapper(MAPPER_ANY_VALUE); /** * * @param parent * @param name * @param value * @return previous value or null */ public static final <T> Any<T> addUpdate(Any<?> parent, String name, Any<T> value) { @SuppressWarnings("unchecked") final Any<T> result = (Any<T>) parent.item(name); if(null != result) { parent.update(name, value); return result; } else { parent.add(name, value); return null; } } public static final <T> Any<T> addUpdate(Any<?> parent, Named<T> name, Any<T> value) { return addUpdate(parent, name.id(), value); } public static final <CONTEXT, T> Any<T> addUpdate(LocalAny<CONTEXT, ?> parent, LocalNamed<CONTEXT, T> name, Any<T> value) { return addUpdate(parent, name.id(), value); } /** * * @param parent * @param name * @param value * @return old existing or new added value */ public static final <T> Any<T> addAbsent(Any<?> parent, String name, Any<T> value) { @SuppressWarnings("unchecked") final Any<T> result = (Any<T>) parent.item(name); if(null != result) { return result; } else { parent.add(name, value); return value; } } public static final <T> Any<T> addAbsent(Any<?> parent, Named<T> name, Any<T> value) { return addAbsent(parent, name.id(), value); } public static final <CONTEXT, T> Any<T> addAbsent(LocalAny<CONTEXT, ?> parent, LocalNamed<CONTEXT, T> name, Any<T> value) { return addAbsent(parent, name.id(), value); } static { Dummy.dummy(); } }
+valueOf for Local
src/com/speakingfish/protocol/ssp/Types.java
+valueOf for Local
<ide><path>rc/com/speakingfish/protocol/ssp/Types.java <ide> return (null == any) ? defaultValue : valueOf(any.item(name), defaultValue); <ide> } <ide> <add> public static <C, T> T valueOf(LocalAny<C, ?> any, LocalNamed<C, T> name) { <add> return valueOf(any, name, null); <add> } <add> <ide> public static <C, T> T valueOf(LocalAny<C, ?> any, LocalNamed<C, T> name, T defaultValue) { <ide> return (null == any) ? defaultValue : valueOf(any.item(name), defaultValue); <ide> }
Java
apache-2.0
eacfbaf990fd55339617e6ea6792cebabc3c18b3
0
sarah-happy/happy-archive,sarah-happy/happy-archive,sarah-happy/happy-archive,sarah-happy/happy-archive,sarah-happy/happy-archive
package org.yi.happy.archive; import java.io.PrintStream; import java.util.List; import org.yi.happy.archive.block.Block; import org.yi.happy.archive.block.EncodedBlock; import org.yi.happy.archive.block.parser.BlockParse; import org.yi.happy.archive.block.parser.EncodedBlockParse; import org.yi.happy.archive.commandLine.UsesArgs; import org.yi.happy.archive.commandLine.UsesOutput; /** * Verify that a set of blocks in files load, parse, and validate. */ @UsesArgs({ "file..." }) @UsesOutput("result") public class VerifyMain implements MainCommand { private final FileStore files; private final PrintStream out; private final List<String> args; /** * create, injecting the dependencies. * * @param files * the file store to use. * @param out * where to send the output. * @param args * the non-option arguments on the command line. */ public VerifyMain(FileStore files, PrintStream out, List<String> args) { this.files = files; this.out = out; this.args = args; } /** * verify that a set of blocks in files load, parse, and validate. * * @param env * the list of files to verify. * @throws Exception */ @Override public void run() throws Exception { for (String arg : args) { String line; try { /* * load the file */ byte[] data = files.get(arg, Blocks.MAX_SIZE); /* * parse into a block */ Block block = BlockParse.parse(data); /* * try to parse into an encoded block */ EncodedBlock b = EncodedBlockParse.parse(block); /* * on success print ok key arg */ line = "ok " + b.getKey() + " " + arg + "\n"; } catch (Exception e) { /* * on failure print fail arg */ line = "fail " + arg + "\n"; } out.print(line); } out.flush(); } }
src/org/yi/happy/archive/VerifyMain.java
package org.yi.happy.archive; import java.io.PrintStream; import java.util.List; import org.yi.happy.archive.block.Block; import org.yi.happy.archive.block.EncodedBlock; import org.yi.happy.archive.block.parser.BlockParse; import org.yi.happy.archive.block.parser.EncodedBlockParse; import org.yi.happy.archive.commandLine.UsesArgs; import org.yi.happy.archive.commandLine.UsesOutput; /** * Verify that a set of blocks in files load, parse, and validate. */ @UsesArgs({ "file..." }) @UsesOutput("result") public class VerifyMain implements MainCommand { private final FileStore files; private final PrintStream out; private final List<String> args; /** * create, injecting the dependencies. * * @param fileSystem * the file system to use. * @param out * where to send the output. * @param args * the non-option arguments on the command line. */ public VerifyMain(FileStore files, PrintStream out, List<String> args) { this.files = files; this.out = out; this.args = args; } /** * verify that a set of blocks in files load, parse, and validate. * * @param env * the list of files to verify. * @throws Exception */ @Override public void run() throws Exception { for (String arg : args) { String line; try { /* * load the file */ byte[] data = files.get(arg, Blocks.MAX_SIZE); /* * parse into a block */ Block block = BlockParse.parse(data); /* * try to parse into an encoded block */ EncodedBlock b = EncodedBlockParse.parse(block); /* * on success print ok key arg */ line = "ok " + b.getKey() + " " + arg + "\n"; } catch (Exception e) { /* * on failure print fail arg */ line = "fail " + arg + "\n"; } out.print(line); } out.flush(); } }
clean up a comment.
src/org/yi/happy/archive/VerifyMain.java
clean up a comment.
<ide><path>rc/org/yi/happy/archive/VerifyMain.java <ide> /** <ide> * create, injecting the dependencies. <ide> * <del> * @param fileSystem <del> * the file system to use. <add> * @param files <add> * the file store to use. <ide> * @param out <ide> * where to send the output. <ide> * @param args
Java
mit
3aa6afee0902bc893475b7ebcc5f8ea6ade766e0
0
rephormat/ripme,Wiiplay123/ripme_da_desc,metaprime/ripme,cyian-1756/ripme,metaprime/ripme,metaprime/ripme,sleaze/ripme,rephormat/ripme,rephormat/ripme,4pr0n/ripme,4pr0n/ripme,EraYaN/ripme,sleaze/ripme,sleaze/ripme
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.rarchives.ripme.ripper.AlbumRipper; import com.rarchives.ripme.ripper.DownloadThreadPool; public class MotherlessRipper extends AlbumRipper { private static final String DOMAIN = "motherless.com", HOST = "motherless"; private static final Logger logger = Logger.getLogger(MotherlessRipper.class); private DownloadThreadPool motherlessThreadPool; public MotherlessRipper(URL url) throws IOException { super(url); motherlessThreadPool = new DownloadThreadPool(); } @Override public boolean canRip(URL url) { return url.getHost().endsWith(DOMAIN); } @Override public String getHost() { return HOST; } @Override public URL sanitizeURL(URL url) throws MalformedURLException { String gid = getGID(url); URL newURL = new URL("http://motherless.com/G" + gid); logger.debug("Sanitized URL from " + url + " to " + newURL); return newURL; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://(www\\.)?motherless\\.com/G([MVI]?[A-F0-9]{6,8}).*$"); Matcher m = p.matcher(url.toExternalForm()); System.err.println(url.toExternalForm()); if (!m.matches()) { throw new MalformedURLException("Expected URL format: http://motherless.com/GIXXXXXXX, got: " + url); } return m.group(m.groupCount()); } @Override public void rip() throws IOException { int index = 0, page = 1; String nextURL = this.url.toExternalForm(); while (nextURL != null) { logger.info(" Retrieving " + nextURL); Document doc = Jsoup.connect(nextURL) .userAgent(USER_AGENT) .get(); for (Element thumb : doc.select("div.thumb a.img-container")) { URL url = new URL("http://" + DOMAIN + thumb.attr("href")); index += 1; // Create thread for finding image at "url" page MotherlessImageThread mit = new MotherlessImageThread(url, index); motherlessThreadPool.addThread(mit); } // Next page nextURL = null; page++; if (doc.html().contains("?page=" + page)) { nextURL = this.url.toExternalForm() + "?page=" + page; } } motherlessThreadPool.waitForThreads(); waitForThreads(); } /** * Helper class to find and download images found on "image" pages */ private class MotherlessImageThread extends Thread { private URL url; private int index; public MotherlessImageThread(URL url, int index) { super(); this.url = url; this.index = index; } @Override public void run() { try { Document doc = Jsoup.connect(this.url.toExternalForm()) .userAgent(USER_AGENT) .get(); Pattern p = Pattern.compile("^.*__fileurl = '([^']{1,})';.*$", Pattern.DOTALL); Matcher m = p.matcher(doc.outerHtml()); if (m.matches()) { String file = m.group(1); addURLToDownload(new URL(file), String.format("%03d_", index)); } else { logger.warn("[!] could not find '__fileurl' at " + url); } } catch (IOException e) { logger.error("[!] Exception while loading/parsing " + this.url, e); } } } }
src/main/java/com/rarchives/ripme/ripper/rippers/MotherlessRipper.java
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.rarchives.ripme.ripper.AlbumRipper; import com.rarchives.ripme.ripper.DownloadThreadPool; public class MotherlessRipper extends AlbumRipper { private static final String DOMAIN = "motherless.com", HOST = "motherless"; private static final Logger logger = Logger.getLogger(MotherlessRipper.class); private DownloadThreadPool motherlessThreadPool; public MotherlessRipper(URL url) throws IOException { super(url); motherlessThreadPool = new DownloadThreadPool(); } @Override public boolean canRip(URL url) { return url.getHost().endsWith(DOMAIN); } @Override public String getHost() { return HOST; } @Override public URL sanitizeURL(URL url) throws MalformedURLException { String gid = getGID(url); URL newURL = new URL("http://motherless.com/G" + gid); logger.debug("Sanitized URL from " + url + " to " + newURL); return newURL; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://(www\\.)?motherless\\.com/G([MVI][A-F0-9]{6,8}).*$"); Matcher m = p.matcher(url.toExternalForm()); System.err.println(url.toExternalForm()); if (!m.matches()) { throw new MalformedURLException("Expected URL format: http://motherless.com/GIXXXXXXX, got: " + url); } return m.group(m.groupCount()); } @Override public void rip() throws IOException { int index = 0, page = 1; String nextURL = this.url.toExternalForm(); while (nextURL != null) { logger.info(" Retrieving " + nextURL); Document doc = Jsoup.connect(nextURL) .userAgent(USER_AGENT) .get(); for (Element thumb : doc.select("div.thumb a.img-container")) { URL url = new URL("http://" + DOMAIN + thumb.attr("href")); index += 1; // Create thread for finding image at "url" page MotherlessImageThread mit = new MotherlessImageThread(url, index); motherlessThreadPool.addThread(mit); } // Next page nextURL = null; page++; if (doc.html().contains("?page=" + page)) { nextURL = this.url.toExternalForm() + "?page=" + page; } } motherlessThreadPool.waitForThreads(); waitForThreads(); } /** * Helper class to find and download images found on "image" pages */ private class MotherlessImageThread extends Thread { private URL url; private int index; public MotherlessImageThread(URL url, int index) { super(); this.url = url; this.index = index; } @Override public void run() { try { Document doc = Jsoup.connect(this.url.toExternalForm()) .userAgent(USER_AGENT) .get(); Pattern p = Pattern.compile("^.*__fileurl = '([^']{1,})';.*$", Pattern.DOTALL); Matcher m = p.matcher(doc.outerHtml()); if (m.matches()) { String file = m.group(1); addURLToDownload(new URL(file), String.format("%03d_", index)); } else { logger.warn("[!] could not find '__fileurl' at " + url); } } catch (IOException e) { logger.error("[!] Exception while loading/parsing " + this.url, e); } } } }
getGID seems to be throwing errors on valid gallery urls. closes #39
src/main/java/com/rarchives/ripme/ripper/rippers/MotherlessRipper.java
getGID seems to be throwing errors on valid gallery urls. closes #39
<ide><path>rc/main/java/com/rarchives/ripme/ripper/rippers/MotherlessRipper.java <ide> <ide> @Override <ide> public String getGID(URL url) throws MalformedURLException { <del> Pattern p = Pattern.compile("^https?://(www\\.)?motherless\\.com/G([MVI][A-F0-9]{6,8}).*$"); <add> Pattern p = Pattern.compile("^https?://(www\\.)?motherless\\.com/G([MVI]?[A-F0-9]{6,8}).*$"); <ide> Matcher m = p.matcher(url.toExternalForm()); <ide> System.err.println(url.toExternalForm()); <ide> if (!m.matches()) {
Java
apache-2.0
11946f19a204f0dd559ac99ab9cafb41accb2e82
0
statsbiblioteket/newspaper-edition-records-maintainer,statsbiblioteket/newspaper-editionRecord-maintainer,statsbiblioteket/newspaper-edition-records-maintainer,statsbiblioteket/newspaper-editionRecord-maintainer
package dk.statsbiblioteket.medieplatform.newspaper.titleRecords; import org.testng.annotations.Test; import dk.statsbiblioteket.doms.central.connectors.EnhancedFedora; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.FedoraRelation; import dk.statsbiblioteket.medieplatform.autonomous.Item; import dk.statsbiblioteket.medieplatform.autonomous.ItemFactory; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import java.util.Arrays; import java.util.Properties; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class RunnableTitleRecordRelationsMaintainerTest { private static final String URL_PREFIX = "info:fedora/"; private static final String PREDICATE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#isPartOfNewspaper"; private static final String DOMS_SUBJECT = "uuid:0c1969ca-94be-4ebb-abab-0bd8130e59d7"; private static final String DOMS_OBJECT_1 = "uuid:38deefa7-381f-4abf-a6c1-a3531b54f997"; private static final String DOMS_OBJECT_2 = "uuid:781732b1-ca9a-46d4-94cd-ae1c0b7f1ebf"; private static final String DOMS_OBJECT_3 = "uuid:aff7e1f0-4242-4fc1-877d-6382f2bbaaa9"; private static final String MESSAGE = "linking to"; /** * Test where one relation should be added. * * Index query returns three items. DOMS returns two known. * * The result should be that the missing relation is added. * * @throws Exception */ @Test public void testDoWorkOnItemAddOneRelation() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2), new Item(DOMS_OBJECT_3))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //One relation should be added verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where one relation should be removed. * * Index query returns two items. DOMS returns three known. * * The result should be that the superfluous relation is removed. * * @throws Exception */ @Test public void testDoWorkOnItemRemoveOneRelation() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //One relation should be deleted verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where no relations should be added or removed. * * Index query returns three items. DOMS returns the same three known. * * The result should be that no relations should be added or removed. * * @throws Exception */ @Test public void testDoWorkOnItemNoRelationsChanged() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2), new Item(DOMS_OBJECT_3))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where two relations should be added. * * Index query returns three items. DOMS returns one known. * * The result should be that the missing two relations are added. * * @throws Exception */ @Test public void testDoWorkOnItemAddMultipleRelations() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2), new Item(DOMS_OBJECT_3))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //Two relations should be added verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_2, URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where two relations should be removed. * * Index query returns one item. DOMS returns three known. * * The result should be that the superfluous relations are removed. * * @throws Exception */ @Test public void testDoWorkOnItemRemoveMultipleRelations() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //Two relations should be removed verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_2, URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where a mix of relations should be added and removed. * * Index query returns one item. DOMS returns two different items known. * * The result should be that one relation is added and the superfluous relations are removed. * * @throws Exception */ @Test public void testDoWorkOnItemAddAndRemoveMultipleRelations() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //One relation should be added verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_1, URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //Two relations should be deleted verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_2, URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } }
src/test/java/dk/statsbiblioteket/medieplatform/newspaper/titleRecords/RunnableTitleRecordRelationsMaintainerTest.java
package dk.statsbiblioteket.medieplatform.newspaper.titleRecords; import junit.framework.TestCase; import dk.statsbiblioteket.doms.central.connectors.EnhancedFedora; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.FedoraRelation; import dk.statsbiblioteket.medieplatform.autonomous.Item; import dk.statsbiblioteket.medieplatform.autonomous.ItemFactory; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import java.util.Arrays; import java.util.Properties; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class RunnableTitleRecordRelationsMaintainerTest extends TestCase { private static final String URL_PREFIX = "info:fedora/"; private static final String PREDICATE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#isPartOfNewspaper"; private static final String DOMS_SUBJECT = "uuid:0c1969ca-94be-4ebb-abab-0bd8130e59d7"; private static final String DOMS_OBJECT_1 = "uuid:38deefa7-381f-4abf-a6c1-a3531b54f997"; private static final String DOMS_OBJECT_2 = "uuid:781732b1-ca9a-46d4-94cd-ae1c0b7f1ebf"; private static final String DOMS_OBJECT_3 = "uuid:aff7e1f0-4242-4fc1-877d-6382f2bbaaa9"; private static final String MESSAGE = "linking to"; /** * Test where one relation should be added. * * Index query returns three items. DOMS returns two known. * * The result should be that the missing relation is added. * * @throws Exception */ public void testDoWorkOnItemAddOneRelation() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2), new Item(DOMS_OBJECT_3))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //One relation should be added verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where one relation should be removed. * * Index query returns two items. DOMS returns three known. * * The result should be that the superfluous relation is removed. * * @throws Exception */ public void testDoWorkOnItemRemoveOneRelation() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //One relation should be deleted verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where no relations should be added or removed. * * Index query returns three items. DOMS returns the same three known. * * The result should be that no relations should be added or removed. * * @throws Exception */ public void testDoWorkOnItemNoRelationsChanged() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2), new Item(DOMS_OBJECT_3))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where two relations should be added. * * Index query returns three items. DOMS returns one known. * * The result should be that the missing two relations are added. * * @throws Exception */ public void testDoWorkOnItemAddMultipleRelations() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1), new Item(DOMS_OBJECT_2), new Item(DOMS_OBJECT_3))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //Two relations should be added verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_2, URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where two relations should be removed. * * Index query returns one item. DOMS returns three known. * * The result should be that the superfluous relations are removed. * * @throws Exception */ public void testDoWorkOnItemRemoveMultipleRelations() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //Two relations should be removed verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_2, URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } /** * Test where a mix of relations should be added and removed. * * Index query returns one item. DOMS returns two different items known. * * The result should be that one relation is added and the superfluous relations are removed. * * @throws Exception */ public void testDoWorkOnItemAddAndRemoveMultipleRelations() throws Exception { //Mock item, return id when asked Item itemMock = mock(Item.class); when(itemMock.getDomsID()).thenReturn(DOMS_SUBJECT); //Mock item factory, knows how to create the test objects ItemFactory<Item> itemFactoryMock = mock(ItemFactory.class); when(itemFactoryMock.create(DOMS_OBJECT_1)).thenReturn(new Item(DOMS_OBJECT_1)); when(itemFactoryMock.create(DOMS_OBJECT_2)).thenReturn(new Item(DOMS_OBJECT_2)); when(itemFactoryMock.create(DOMS_OBJECT_3)).thenReturn(new Item(DOMS_OBJECT_3)); //Mock result collector. ResultCollector resultCollectorMock = mock(ResultCollector.class); //Mock Fedora. Will return MODS when asked, and list three existing relations EnhancedFedora enhancedFedoraMock = mock(EnhancedFedora.class); when(enhancedFedoraMock.getXMLDatastreamContents(DOMS_SUBJECT, "MODS")).thenReturn("<mods xmlns=\"http://www.loc.gov/mods/v3\"><identifier type=\"ninestars avis id\">avis</identifier><originInfo><dateIssued point=\"start\">1970-01-01T01:00:00.000+01:00</dateIssued><dateIssued point=\"end\">1980-01-01T01:00:00.000+01:00</dateIssued></originInfo></mods>"); when(enhancedFedoraMock.getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE)).thenReturn( Arrays.asList(new FedoraRelation(URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT), new FedoraRelation(URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT))); //Mock newspaper index. Will return three items when asked NewspaperIndex newspaperIndexMock = mock(NewspaperIndex.class); when(newspaperIndexMock.getEditions(anyString(), anyString(), anyString())).thenReturn( Arrays.asList(new Item(DOMS_OBJECT_1))); //Call the component with the mocks new RunnableTitleRecordRelationsMaintainer(new Properties(), enhancedFedoraMock, itemFactoryMock, newspaperIndexMock) .doWorkOnItem(itemMock, resultCollectorMock); //Verify expected DOMS calls verify(enhancedFedoraMock).getXMLDatastreamContents(DOMS_SUBJECT, "MODS"); verify(enhancedFedoraMock).getInverseRelations(URL_PREFIX + DOMS_SUBJECT, PREDICATE); //One relation should be added verify(enhancedFedoraMock).addRelation(DOMS_OBJECT_1, URL_PREFIX + DOMS_OBJECT_1, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //Two relations should be deleted verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_2, URL_PREFIX + DOMS_OBJECT_2, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); verify(enhancedFedoraMock).deleteRelation(DOMS_OBJECT_3, URL_PREFIX + DOMS_OBJECT_3, PREDICATE, URL_PREFIX + DOMS_SUBJECT, false, MESSAGE); //No more calls should be made to DOMS, and none to the result collector verifyNoMoreInteractions(enhancedFedoraMock, resultCollectorMock); } }
Update test to TestNG
src/test/java/dk/statsbiblioteket/medieplatform/newspaper/titleRecords/RunnableTitleRecordRelationsMaintainerTest.java
Update test to TestNG
<ide><path>rc/test/java/dk/statsbiblioteket/medieplatform/newspaper/titleRecords/RunnableTitleRecordRelationsMaintainerTest.java <ide> package dk.statsbiblioteket.medieplatform.newspaper.titleRecords; <ide> <del>import junit.framework.TestCase; <add>import org.testng.annotations.Test; <ide> <ide> import dk.statsbiblioteket.doms.central.connectors.EnhancedFedora; <ide> import dk.statsbiblioteket.doms.central.connectors.fedora.structures.FedoraRelation; <ide> import static org.mockito.Mockito.verifyNoMoreInteractions; <ide> import static org.mockito.Mockito.when; <ide> <del>public class RunnableTitleRecordRelationsMaintainerTest extends TestCase { <add>public class RunnableTitleRecordRelationsMaintainerTest { <ide> <ide> private static final String URL_PREFIX = "info:fedora/"; <ide> private static final String PREDICATE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#isPartOfNewspaper"; <ide> * <ide> * @throws Exception <ide> */ <add> @Test <ide> public void testDoWorkOnItemAddOneRelation() throws Exception { <ide> //Mock item, return id when asked <ide> Item itemMock = mock(Item.class); <ide> * <ide> * @throws Exception <ide> */ <add> @Test <ide> public void testDoWorkOnItemRemoveOneRelation() throws Exception { <ide> //Mock item, return id when asked <ide> Item itemMock = mock(Item.class); <ide> * <ide> * @throws Exception <ide> */ <add> @Test <ide> public void testDoWorkOnItemNoRelationsChanged() throws Exception { <ide> //Mock item, return id when asked <ide> Item itemMock = mock(Item.class); <ide> * <ide> * @throws Exception <ide> */ <add> @Test <ide> public void testDoWorkOnItemAddMultipleRelations() throws Exception { <ide> //Mock item, return id when asked <ide> Item itemMock = mock(Item.class); <ide> * <ide> * @throws Exception <ide> */ <add> @Test <ide> public void testDoWorkOnItemRemoveMultipleRelations() throws Exception { <ide> //Mock item, return id when asked <ide> Item itemMock = mock(Item.class); <ide> * <ide> * @throws Exception <ide> */ <add> @Test <ide> public void testDoWorkOnItemAddAndRemoveMultipleRelations() throws Exception { <ide> //Mock item, return id when asked <ide> Item itemMock = mock(Item.class);
Java
mit
194374322fa0bc55f3f283c285dc09bb9b1b83e7
0
picpromusic/incubator,picpromusic/incubator
package incubator.cfa; import incubator.cfa.jdk.Accessor; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Bootstrapper { public static CallSite getFunction(Lookup lookup, String name, MethodType type, String declaringClass, int mod) throws NoSuchMethodException, IllegalAccessException, ClassNotFoundException { boolean staticProperty = Modifier.isStatic(mod); Class<?> clazz; if (!staticProperty) { clazz = type.parameterArray()[0]; } else { clazz = Class.forName(declaringClass); } try { MethodHandle ret = staticProperty // ? lookup.findStaticGetter(clazz, name, type.returnType()) : lookup.findGetter(clazz, name, type.returnType()); return new ConstantCallSite(ret); } catch (Exception e) { // Should be ReflectiveOperationException | // IllegalAccessException // System.out.println("Expected MethodType:"+type); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) == staticProperty && method.getReturnType().equals(type.returnType())) { Accessor annotation = method.getAnnotation(Accessor.class); if (annotation != null && annotation.value().equals(name)) { // System.out.println(method + " " // + Arrays.toString(method.getAnnotations())); MethodType mt = MethodType .methodType(type.returnType()); // System.out.println("Created MethodType:"+mt); MethodHandle ret = staticProperty // ? lookup.findStatic(clazz, method.getName(), mt) : lookup.findVirtual(clazz, method.getName(), mt); // System.out.println("Loaded MethodHandle:"+ret); // MethodHandle ex = MethodHandles.throwException( // type.returnType(), RuntimeException.class); // System.out.println("MethodHandle Throw:"+ex); // MethodHandle x = MethodHandles.dropArguments(ex, 0, type.parameterArray()[0]); // System.out.println("MethodHandle Throw:"+x); // MethodHandle insertArguments = MethodHandles.insertArguments(x, 0, new RuntimeException()); // System.out.println("MethodHandle insertedArg:"+insertArguments); // return new ConstantCallSite(insertArguments.asType(type)); return new ConstantCallSite(ret.asType(type)); } } } } throw new VerifyError("No get accessor found for " + clazz.getCanonicalName() + "." + name); } public static CallSite setFunction(Lookup lookup, String name, MethodType type, String declaringClass, int mod) throws NoSuchMethodException, IllegalAccessException, ClassNotFoundException { boolean staticProperty = Modifier.isStatic(mod); Class<?> clazz; if (!staticProperty) { clazz = type.parameterArray()[0]; } else { clazz = Class.forName(declaringClass); } try { MethodHandle ret = staticProperty // ? lookup.findStaticSetter(clazz, name, type.parameterType(0)) : lookup.findSetter(clazz, name, type.parameterType(1)); return new ConstantCallSite(ret); } catch (Exception e) { // Should be ReflectiveOperationException | // IllegalAccessException Method[] methods = clazz.getMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) == staticProperty && method.getReturnType().equals(void.class)) { Accessor annotation = method.getAnnotation(Accessor.class); if (annotation != null && annotation.value().equals(name)) { // System.out.println(method + " " // + Arrays.toString(method.getAnnotations())); MethodType mt = MethodType.methodType(void.class, method.getParameterTypes()); MethodHandle ret = staticProperty ? lookup.findStatic( clazz, method.getName(), mt) : lookup.findVirtual(clazz, method.getName(), mt); return new ConstantCallSite(ret.asType(type)); } } } } throw new VerifyError("No set accessor found for " + clazz.getCanonicalName() + "." + name); } }
jdk/compatibleFieldAccess/src/incubator/cfa/Bootstrapper.java
package incubator.cfa; import incubator.cfa.jdk.Accessor; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Bootstrapper { public static CallSite getFunction(Lookup lookup, String name, MethodType type, String declaringClass, int mod) throws NoSuchMethodException, IllegalAccessException, ClassNotFoundException { boolean staticProperty = Modifier.isStatic(mod); Class<?> clazz; if (!staticProperty) { clazz = type.parameterArray()[0]; } else { clazz = Class.forName(declaringClass); } try { MethodHandle ret = staticProperty // ? lookup.findStaticGetter(clazz, name, type.returnType()) : lookup.findGetter(clazz, name, type.returnType()); return new ConstantCallSite(ret); } catch (Exception e) { // Should be ReflectiveOperationException | // IllegalAccessException System.out.println("Expected MethodType:"+type); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) == staticProperty && method.getReturnType().equals(type.returnType())) { Accessor annotation = method.getAnnotation(Accessor.class); if (annotation != null && annotation.value().equals(name)) { // System.out.println(method + " " // + Arrays.toString(method.getAnnotations())); MethodType mt = MethodType .methodType(type.returnType()); System.out.println("Created MethodType:"+mt); MethodHandle ret = staticProperty // ? lookup.findStatic(clazz, method.getName(), mt) : lookup.findVirtual(clazz, method.getName(), mt); System.out.println("Loaded MethodHandle:"+ret); // MethodHandle ex = MethodHandles.throwException( // type.returnType(), RuntimeException.class); // System.out.println("MethodHandle Throw:"+ex); // MethodHandle x = MethodHandles.dropArguments(ex, 0, type.parameterArray()[0]); // System.out.println("MethodHandle Throw:"+x); // MethodHandle insertArguments = MethodHandles.insertArguments(x, 0, new RuntimeException()); // System.out.println("MethodHandle insertedArg:"+insertArguments); // return new ConstantCallSite(insertArguments.asType(type)); return new ConstantCallSite(ret.asType(type)); } } } } throw new VerifyError("No get accessor found for " + clazz.getCanonicalName() + "." + name); } public static CallSite setFunction(Lookup lookup, String name, MethodType type, String declaringClass, int mod) throws NoSuchMethodException, IllegalAccessException, ClassNotFoundException { boolean staticProperty = Modifier.isStatic(mod); Class<?> clazz; if (!staticProperty) { clazz = type.parameterArray()[0]; } else { clazz = Class.forName(declaringClass); } try { MethodHandle ret = staticProperty // ? lookup.findStaticSetter(clazz, name, type.parameterType(0)) : lookup.findSetter(clazz, name, type.parameterType(1)); return new ConstantCallSite(ret); } catch (Exception e) { // Should be ReflectiveOperationException | // IllegalAccessException Method[] methods = clazz.getMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) == staticProperty && method.getReturnType().equals(void.class)) { Accessor annotation = method.getAnnotation(Accessor.class); if (annotation != null && annotation.value().equals(name)) { // System.out.println(method + " " // + Arrays.toString(method.getAnnotations())); MethodType mt = MethodType.methodType(void.class, method.getParameterTypes()); MethodHandle ret = staticProperty ? lookup.findStatic( clazz, method.getName(), mt) : lookup.findVirtual(clazz, method.getName(), mt); return new ConstantCallSite(ret.asType(type)); } } } } throw new VerifyError("No set accessor found for " + clazz.getCanonicalName() + "." + name); } }
remove some unused sysouts
jdk/compatibleFieldAccess/src/incubator/cfa/Bootstrapper.java
remove some unused sysouts
<ide><path>dk/compatibleFieldAccess/src/incubator/cfa/Bootstrapper.java <ide> return new ConstantCallSite(ret); <ide> } catch (Exception e) { // Should be ReflectiveOperationException | <ide> // IllegalAccessException <del> System.out.println("Expected MethodType:"+type); <add>// System.out.println("Expected MethodType:"+type); <ide> Method[] methods = clazz.getMethods(); <ide> for (Method method : methods) { <ide> if (Modifier.isStatic(method.getModifiers()) == staticProperty <ide> // + Arrays.toString(method.getAnnotations())); <ide> MethodType mt = MethodType <ide> .methodType(type.returnType()); <del> System.out.println("Created MethodType:"+mt); <add>// System.out.println("Created MethodType:"+mt); <ide> MethodHandle ret = staticProperty // <ide> ? lookup.findStatic(clazz, method.getName(), mt) <ide> : lookup.findVirtual(clazz, method.getName(), <ide> mt); <del> System.out.println("Loaded MethodHandle:"+ret); <add>// System.out.println("Loaded MethodHandle:"+ret); <ide> <ide> <ide> // MethodHandle ex = MethodHandles.throwException(
JavaScript
bsd-2-clause
7800bb5da151414135682092d3d3166302d17ecb
0
unixpickle/graphalicious,unixpickle/graphalicious,unixpickle/graphalicious,unixpickle/graphalicious
// ScrollBar implements a user-controlled scrollbar. // This will emit a 'change' event whenever the bar is scrolled. function ScrollBar(colorScheme) { EventEmitter.call(this); this._track = document.createElement('div'); this._track.style.backgroundColor = ScrollBar.TRACK_COLOR; this._track.style.width = '100%'; this._track.style.height = '0px'; this._track.style.position = 'absolute'; this._track.style.bottom = '0'; this._thumb = document.createElement('div'); this._thumb.style.height = '100%'; this._thumb.style.position = 'absolute'; this._track.appendChild(this._thumb); this._thumb.style.backgroundColor = colorScheme.getPrimary(); colorScheme.on('change', function() { this._thumb.style.backgroundColor = colorScheme.getPrimary(); }.bind(this)); this._totalPixels = 0; this._visiblePixels = 0; this._scrolledPixels = 0; this._trackWidth = 0; this._thumbWidth = 0; this._thumbLeft = 0; this._moveEventCallback = null; this._registerMouseEvents(); this._registerTouchEvents(); } ScrollBar.THUMB_MIN_WIDTH = 20; ScrollBar.TRACK_COLOR = '#ccc'; ScrollBar.prototype = Object.create(EventEmitter.prototype); ScrollBar.prototype.element = function() { return this._track; }; ScrollBar.prototype.layout = function(width, height) { if (width < ScrollBar.THUMB_MIN_WIDTH) { return; } this._track.style.height = height.toFixed(2) + 'px'; this._track.style.width = width; this._trackWidth = width; this._updateThumb(); }; ScrollBar.prototype.getScrolledPixels = function() { return this._scrolledPixels; }; ScrollBar.prototype.setInfo = function(total, visible, scrolled) { this._totalPixels = total; this._visiblePixels = visible; this._scrolledPixels = scrolled; this._updateThumb(); }; ScrollBar.prototype._updateThumb = function(width) { this._thumbWidth = this._trackWidth * (this._visiblePixels / this._totalPixels); if (this._thumbWidth < ScrollBar.THUMB_MIN_WIDTH) { this._thumbWidth = ScrollBar.THUMB_MIN_WIDTH; } var usableWidth = this._trackWidth - this._thumbWidth; var percentScrolled = this._scrolledPixels / (this._totalPixels - this._visiblePixels); this._thumbLeft = usableWidth * percentScrolled; this._thumb.style.width = Math.round(this._thumbWidth) + 'px'; this._thumb.style.left = Math.round(this._thumbLeft) + 'px'; }; ScrollBar.prototype._eventBegan = function(startX) { var scrollablePixels = this._totalPixels - this._visiblePixels; var maxThumbLeft = this._trackWidth - this._thumbWidth; var startThumbLeft = this._thumbLeft; if (startX < startThumbLeft || startX > startThumbLeft + this._thumbWidth) { startThumbLeft = Math.min(maxThumbLeft, Math.max(0, startX-this._thumbWidth/2)); } this._moveEventCallback = function(x) { var xOffset = x - startX; var newThumbLeft = Math.min(maxThumbLeft, Math.max(0, startThumbLeft + xOffset)); var ratioScrolled = newThumbLeft / maxThumbLeft; this._scrolledPixels = Math.round(scrollablePixels * ratioScrolled); this._updateThumb(); this.emit('change'); }.bind(this); this._moveEventCallback(startX); }; ScrollBar.prototype._registerMouseEvents = function() { var shielding = document.createElement('div'); shielding.style.width = '100%'; shielding.style.height = '100%'; shielding.style.position = 'fixed'; var mouseMove, mouseUp; mouseMove = function(e) { if (this._moveEventCallback !== null) { this._moveEventCallback(e.clientX); // NOTE: this fixes a problem where the cursor becomes an ibeam. e.preventDefault(); e.stopPropagation(); } }.bind(this); mouseUp = function() { if (this._moveEventCallback !== null) { this._moveEventCallback = null; document.body.removeChild(shielding); } window.removeEventListener('mousemove', mouseMove); window.removeEventListener('mouseup', mouseUp); }.bind(this); this._track.addEventListener('mousedown', function(e) { if (this._moveEventCallback) { return; } // NOTE: this fixes a problem where the cursor becomes an ibeam. e.preventDefault(); e.stopPropagation(); this._eventBegan(e.clientX); document.body.appendChild(shielding); window.addEventListener('mousemove', mouseMove); window.addEventListener('mouseup', mouseUp); }.bind(this)); }; ScrollBar.prototype._registerTouchEvents = function() { var e = this._track; e.addEventListener('touchstart', function(e) { this._eventBegan(e.changedTouches[0].clientX); }.bind(this)); e.addEventListener('touchmove', function(e) { if (this._moveEventCallback) { this._moveEventCallback(e.changedTouches[0].clientX); } }.bind(this)); var cancel = function() { this._moveEventCallback = null; }.bind(this); e.addEventListener('touchend', cancel); e.addEventListener('touchcancel', cancel); };
src/scroll_bar.js
// ScrollBar implements a user-controlled scrollbar. // This will emit a 'change' event whenever the bar is scrolled. function ScrollBar(colorScheme) { EventEmitter.call(this); this._track = document.createElement('div'); this._track.style.backgroundColor = ScrollBar.TRACK_COLOR; this._track.style.width = '100%'; this._track.style.height = '0px'; this._track.style.position = 'absolute'; this._track.style.bottom = '0'; this._thumb = document.createElement('div'); this._thumb.style.height = '100%'; this._thumb.style.position = 'absolute'; this._track.appendChild(this._thumb); this._thumb.style.backgroundColor = colorScheme.getPrimary(); colorScheme.on('change', function() { this._thumb.style.backgroundColor = colorScheme.getPrimary(); }.bind(this)); this._totalPixels = 0; this._visiblePixels = 0; this._scrolledPixels = 0; this._trackWidth = 0; this._thumbWidth = 0; this._thumbLeft = 0; this._moveEventCallback = null; this._registerMouseEvents(); this._registerTouchEvents(); } ScrollBar.THUMB_MIN_WIDTH = 20; ScrollBar.TRACK_COLOR = '#ccc'; ScrollBar.prototype = Object.create(EventEmitter.prototype); ScrollBar.prototype.element = function() { return this._track; }; ScrollBar.prototype.layout = function(width, height) { if (width < ScrollBar.THUMB_MIN_WIDTH) { return; } this._track.style.height = height.toFixed(2) + 'px'; this._track.style.width = width; this._trackWidth = width; this._updateThumb(); }; ScrollBar.prototype.getScrolledPixels = function() { return this._scrolledPixels; }; ScrollBar.prototype.setInfo = function(total, visible, scrolled) { this._totalPixels = total; this._visiblePixels = visible; this._scrolledPixels = scrolled; this._updateThumb(); }; ScrollBar.prototype._updateThumb = function(width) { this._thumbWidth = this._trackWidth * (this._visiblePixels / this._totalPixels); if (this._thumbWidth < ScrollBar.THUMB_MIN_WIDTH) { this._thumbWidth = ScrollBar.THUMB_MIN_WIDTH; } var usableWidth = this._trackWidth - this._thumbWidth; var percentScrolled = this._scrolledPixels / (this._totalPixels - this._visiblePixels); this._thumbLeft = usableWidth * percentScrolled; this._thumb.style.width = Math.round(this._thumbWidth) + 'px'; this._thumb.style.left = Math.round(this._thumbLeft) + 'px'; }; ScrollBar.prototype._eventBegan = function(startX) { var scrollablePixels = this._totalPixels - this._visiblePixels; var maxThumbLeft = this._trackWidth - this._thumbWidth; var startThumbLeft = this._thumbLeft; if (startX < startThumbLeft || startX > startThumbLeft + this._thumbWidth) { startThumbLeft = Math.min(maxThumbLeft, Math.max(0, startX-this._thumbWidth/2)); } this._moveEventCallback = function(x) { var xOffset = x - startX; var newThumbLeft = Math.min(maxThumbLeft, Math.max(0, startThumbLeft + xOffset)); var ratioScrolled = newThumbLeft / maxThumbLeft; this._scrolledPixels = Math.round(scrollablePixels * ratioScrolled); this._updateThumb(); this.emit('change'); }.bind(this); this._moveEventCallback(startX); }; ScrollBar.prototype._registerMouseEvents = function() { var shielding = document.createElement('div'); shielding.style.width = '100%'; shielding.style.height = '100%'; shielding.style.position = 'fixed'; var mouseMove, mouseUp; mouseMove = function(e) { this._moveEventCallback(e.clientX); // NOTE: this fixes a problem where the cursor becomes an ibeam. e.preventDefault(); e.stopPropagation(); }.bind(this); mouseUp = function() { this._moveEventCallback = null; document.body.removeChild(shielding); window.removeEventListener('mousemove', mouseMove); window.removeEventListener('mouseup', mouseUp); }.bind(this); this._track.addEventListener('mousedown', function(e) { if (this._moveEventCallback) { return; } // NOTE: this fixes a problem where the cursor becomes an ibeam. e.preventDefault(); e.stopPropagation(); this._eventBegan(e.clientX); document.body.appendChild(shielding); window.addEventListener('mousemove', mouseMove); window.addEventListener('mouseup', mouseUp); }.bind(this)); }; ScrollBar.prototype._registerTouchEvents = function() { var e = this._track; e.addEventListener('touchstart', function(e) { this._eventBegan(e.changedTouches[0].clientX); }.bind(this)); e.addEventListener('touchmove', function(e) { if (this._moveEventCallback) { this._moveEventCallback(e.changedTouches[0].clientX); } }.bind(this)); var cancel = function() { this._moveEventCallback = null; }.bind(this); e.addEventListener('touchend', cancel); e.addEventListener('touchcancel', cancel); };
fixed potential bug with touch screen laptops
src/scroll_bar.js
fixed potential bug with touch screen laptops
<ide><path>rc/scroll_bar.js <ide> var mouseMove, mouseUp; <ide> <ide> mouseMove = function(e) { <del> this._moveEventCallback(e.clientX); <add> if (this._moveEventCallback !== null) { <add> this._moveEventCallback(e.clientX); <ide> <del> // NOTE: this fixes a problem where the cursor becomes an ibeam. <del> e.preventDefault(); <del> e.stopPropagation(); <add> // NOTE: this fixes a problem where the cursor becomes an ibeam. <add> e.preventDefault(); <add> e.stopPropagation(); <add> } <ide> }.bind(this); <ide> <ide> mouseUp = function() { <del> this._moveEventCallback = null; <del> document.body.removeChild(shielding); <del> <add> if (this._moveEventCallback !== null) { <add> this._moveEventCallback = null; <add> document.body.removeChild(shielding); <add> } <ide> window.removeEventListener('mousemove', mouseMove); <ide> window.removeEventListener('mouseup', mouseUp); <ide> }.bind(this);
Java
apache-2.0
39e80e9159672d826070ec6be1964080fe4ec3c3
0
vaskaloidis/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/ISAAC,DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui,vaskaloidis/va-isaac-gui,Apelon-VA/ISAAC,Apelon-VA/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/ISAAC
/** * Copyright Notice * * This is a work of the U.S. Government and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * 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 gov.va.isaac.gui.dialog; import gov.va.isaac.AppContext; import gov.va.isaac.gui.util.FxUtils; import gov.va.isaac.gui.util.GridPaneBuilder; import gov.va.isaac.model.InformationModelType; import gov.va.isaac.models.InformationModel; import gov.va.isaac.models.cem.CEMInformationModel; import gov.va.isaac.models.cem.exporter.CEMExporter; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.UUID; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.concurrent.Task; import javafx.scene.Cursor; import javafx.scene.control.Label; import javafx.scene.control.Separator; import javafx.scene.control.TextArea; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * A dialog for displaying an information model details. * * @author ocarlsen */ public class InformationModelDetailsPane extends GridPane { private static final Logger LOG = LoggerFactory.getLogger(InformationModelDetailsPane.class); private final Label modelNameLabel = new Label(); private final TextArea modelXmlTextArea = new TextArea(); public InformationModelDetailsPane() { super(); // GUI placeholders. GridPaneBuilder builder = new GridPaneBuilder(this); builder.addRow("Information Model: ", modelNameLabel); builder.addRow(new Separator()); builder.addRow(modelXmlTextArea); modelXmlTextArea.setEditable(false); setConstraints(); // Set minimum dimensions. setMinHeight(200); setMinWidth(600); } public void displayModel(InformationModel informationModel) { Preconditions.checkNotNull(informationModel); // Make sure in application thread. FxUtils.checkFxUserThread(); if (informationModel.getType() == InformationModelType.CEM) { displayCEM((CEMInformationModel) informationModel); } else { throw new UnsupportedOperationException(informationModel.getType() + " display not yet supported in ISAAC."); } } private void displayCEM(final CEMInformationModel cemModel) { // Do work in background. Task<String> task = new Task<String>() { @Override protected String call() throws Exception { // Do work. OutputStream out = new ByteArrayOutputStream(); CEMExporter exporter = new CEMExporter(out); UUID conceptUUID = cemModel.getConceptUUID(); exporter.exportModel(conceptUUID ); return out.toString(); } @Override protected void succeeded() { // Update UI. modelNameLabel.setText(cemModel.getName()); String modelXML = this.getValue(); modelXmlTextArea.setText(modelXML); } @Override protected void failed() { // Show dialog. Throwable ex = getException(); String title = ex.getClass().getName(); String msg = String.format("Unexpected error displaying CEM model \"%s\"", cemModel.getName()); LOG.error(msg, ex); AppContext.getCommonDialogs().showErrorDialog(title, msg, ex.getMessage()); } }; // Bind cursor to task state. ObjectBinding<Cursor> cursorBinding = Bindings.when(task.runningProperty()).then(Cursor.WAIT).otherwise(Cursor.DEFAULT); this.getScene().cursorProperty().bind(cursorBinding); Thread t = new Thread(task, "Display_" + cemModel.getName()); t.setDaemon(true); t.start(); } private void setConstraints() { // Column 1 has empty constraints. this.getColumnConstraints().add(new ColumnConstraints()); // Column 2 should grow to fill space. ColumnConstraints column2 = new ColumnConstraints(); column2.setHgrow(Priority.ALWAYS); this.getColumnConstraints().add(column2); // Rows 1-2 have empty constraints. this.getRowConstraints().add(new RowConstraints()); this.getRowConstraints().add(new RowConstraints()); // Row 3 should grow to fill space. RowConstraints row5 = new RowConstraints(); row5.setVgrow(Priority.ALWAYS); this.getRowConstraints().add(row5); } }
import-export/src/main/java/gov/va/isaac/gui/dialog/InformationModelDetailsPane.java
/** * Copyright Notice * * This is a work of the U.S. Government and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * 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 gov.va.isaac.gui.dialog; import gov.va.isaac.AppContext; import gov.va.isaac.gui.util.FxUtils; import gov.va.isaac.gui.util.GridPaneBuilder; import gov.va.isaac.model.InformationModelType; import gov.va.isaac.models.InformationModel; import gov.va.isaac.models.cem.CEMInformationModel; import gov.va.isaac.models.cem.exporter.CEMExporter; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.UUID; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.concurrent.Task; import javafx.scene.Cursor; import javafx.scene.control.Label; import javafx.scene.control.Separator; import javafx.scene.control.TextArea; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * A dialog for displaying an information model details. * * @author ocarlsen */ public class InformationModelDetailsPane extends GridPane { private static final Logger LOG = LoggerFactory.getLogger(InformationModelDetailsPane.class); private final Label modelNameLabel = new Label(); private final TextArea modelXmlTextArea = new TextArea(); public InformationModelDetailsPane() { super(); // GUI placeholders. GridPaneBuilder builder = new GridPaneBuilder(this); builder.addRow("Information Model: ", modelNameLabel); builder.addRow(new Separator()); builder.addRow(modelXmlTextArea); setConstraints(); // Set minimum dimensions. setMinHeight(200); setMinWidth(600); } public void displayModel(InformationModel informationModel) { Preconditions.checkNotNull(informationModel); // Make sure in application thread. FxUtils.checkFxUserThread(); if (informationModel.getType() == InformationModelType.CEM) { displayCEM((CEMInformationModel) informationModel); } else { throw new UnsupportedOperationException(informationModel.getType() + " display not yet supported in ISAAC."); } } private void displayCEM(final CEMInformationModel cemModel) { // Do work in background. Task<String> task = new Task<String>() { @Override protected String call() throws Exception { // Do work. OutputStream out = new ByteArrayOutputStream(); CEMExporter exporter = new CEMExporter(out); UUID conceptUUID = cemModel.getConceptUUID(); exporter.exportModel(conceptUUID ); return out.toString(); } @Override protected void succeeded() { // Update UI. modelNameLabel.setText(cemModel.getName()); String modelXML = this.getValue(); modelXmlTextArea.setText(modelXML); } @Override protected void failed() { // Show dialog. Throwable ex = getException(); String title = ex.getClass().getName(); String msg = String.format("Unexpected error displaying CEM model \"%s\"", cemModel.getName()); LOG.error(msg, ex); AppContext.getCommonDialogs().showErrorDialog(title, msg, ex.getMessage()); } }; // Bind cursor to task state. ObjectBinding<Cursor> cursorBinding = Bindings.when(task.runningProperty()).then(Cursor.WAIT).otherwise(Cursor.DEFAULT); this.getScene().cursorProperty().bind(cursorBinding); Thread t = new Thread(task, "Display_" + cemModel.getName()); t.setDaemon(true); t.start(); } private void setConstraints() { // Column 1 has empty constraints. this.getColumnConstraints().add(new ColumnConstraints()); // Column 2 should grow to fill space. ColumnConstraints column2 = new ColumnConstraints(); column2.setHgrow(Priority.ALWAYS); this.getColumnConstraints().add(column2); // Rows 1-2 have empty constraints. this.getRowConstraints().add(new RowConstraints()); this.getRowConstraints().add(new RowConstraints()); // Row 3 should grow to fill space. RowConstraints row5 = new RowConstraints(); row5.setVgrow(Priority.ALWAYS); this.getRowConstraints().add(row5); } }
Making text area read-only.
import-export/src/main/java/gov/va/isaac/gui/dialog/InformationModelDetailsPane.java
Making text area read-only.
<ide><path>mport-export/src/main/java/gov/va/isaac/gui/dialog/InformationModelDetailsPane.java <ide> builder.addRow("Information Model: ", modelNameLabel); <ide> builder.addRow(new Separator()); <ide> builder.addRow(modelXmlTextArea); <add> <add> modelXmlTextArea.setEditable(false); <ide> <ide> setConstraints(); <ide>
Java
apache-2.0
9b44549f911fa4cdb53ba457c14b892e348c0d90
0
spefley/appinventor-sources,warren922/appinventor-sources,ewpatton/appinventor-sources,afmckinney/appinventor-sources,bxie/appinventor-sources,jsheldonmit/appinventor-sources,mit-dig/punya,gitars/appinventor-sources,tvomf/appinventor-mapps,ZachLamb/appinventor-sources,halatmit/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,thequixotic/appinventor-sources,nmcalabroso/appinventor-sources,joshaham/latest_app_inventor,nickboucart/appinventor-sources,kkashi01/appinventor-sources,doburaimo/appinventor-sources,nickboucart/appinventor-sources,mit-dig/punya,KeithGalli/appinventor-sources,fturbak/appinventor-sources,gitars/appinventor-sources,toropeza/appinventor-sources,ewpatton/appinventor-sources,warren922/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,bxie/appinventor-sources,DRavnaas/appinventor-clone,jsheldonmit/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,DRavnaas/appinventor-clone,kannan-usf/AppInventorJavaBridge,kidebit/https-github.com-wicedfast-appinventor-sources,joshaham/latest_app_inventor,wadleo/appinventor-sources,mark-friedman/web-appinventor,ajcolter/appinventor-sources,aouskaroui/appinventor-sources,josmas/app-inventor,Edeleon4/punya,gitars/appinventor-sources,thequixotic/appinventor-sources,William-Byrne/appinventor-sources,KeithGalli/appinventor-sources,tiffanyle/appinventor-sources,weihuali0509/web-appinventor,spefley/appinventor-sources,sujianping/appinventor-sources,JalexChang/appinventor-sources,wadleo/appinventor-sources,dengxinyue0420/appinventor-sources,barreeeiroo/appinventor-sources,themadrobot/appinventor-sources,egiurleo/appinventor-sources,ewpatton/appinventor-sources,ram8647/appinventor-sources,mit-dig/punya,jisqyv/appinventor-sources,William-Byrne/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,wicedfast/appinventor-sources,weihuali0509/web-appinventor,kpjs4s/AppInventorJavaBridgeCodeGen,CoderDojoLX/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,CoderDojoLX/appinventor-sources,William-Byrne/appinventor-sources,bitsecure/appinventor1-sources,afmckinney/appinventor-sources,wadleo/appinventor-sources,sujianping/appinventor-sources,warren922/appinventor-sources,wadleo/appinventor-sources,wicedfast/appinventor-sources,wicedfast/appinventor-sources,wanddy/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,ewpatton/appinventor-sources,youprofit/appinventor-sources,mit-dig/punya,weihuali0509/appinventor-sources,kkashi01/appinventor-sources,emeryotopalik/appinventor-sources,mintingle/appinventor-sources,ram8647/appinventor-sources,thequixotic/appinventor-sources,awoodworth/appinventor-sources,fturbak/appinventor-sources,tatuzaumm/app-inventor2-custom,puravidaapps/appinventor-sources,halatmit/appinventor-sources,gitars/appinventor-sources,fmntf/appinventor-sources,dengxinyue0420/appinventor-sources,KeithGalli/appinventor-sources,Momoumar/appinventor-sources,josmas/app-inventor,bitsecure/appinventor1-sources,ajcolter/appinventor-sources,bitsecure/appinventor1-sources,fturbak/appinventor-sources,hasi96/appinventor-sources,toropeza/appinventor-sources,thilankam/appinventor-sources,E-Hon/appinventor-sources,JalexChang/appinventor-sources,ZachLamb/appinventor-sources,tvomf/appinventor-mapps,thilankam/appinventor-sources,fturbak/appinventor-sources,jithinbp/appinventor-sources,E-Hon/appinventor-sources,halatmit/appinventor-sources,barreeeiroo/appinventor-sources,Momoumar/appinventor-sources,puravidaapps/appinventor-sources,liyucun/appinventor-sources,farxinu/appinventor-sources,mintingle/appinventor-sources,awoodworth/appinventor-sources,hasi96/appinventor-sources,onyeka/AppInventor-WebApp,jsheldonmit/appinventor-sources,themadrobot/appinventor-sources,krishc90/APP-INVENTOR,kannan-usf/AppInventorJavaBridge,satgod/appinventor,krishc90/APP-INVENTOR,Mateopato/appinventor-sources,William-Byrne/appinventor-sources,ewpatton/appinventor-sources,GodUseVPN/appinventor-sources,E-Hon/appinventor-sources,frfranca/appinventor-sources,lizlooney/appinventor-sources,RachaelT/appinventor-sources,lizlooney/appinventor-sources,awoodworth/appinventor-sources,weihuali0509/appinventor-sources,mit-cml/appinventor-sources,bitsecure/appinventor1-sources,spefley/appinventor-sources,marksherman/appinventor-sources,JalexChang/appinventor-sources,William-Byrne/appinventor-sources,thilankam/appinventor-sources,Klomi/appinventor-sources,farxinu/appinventor-sources,weihuali0509/web-appinventor,spefley/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,mit-cml/appinventor-sources,egiurleo/appinventor-sources,aouskaroui/appinventor-sources,mit-dig/punya,krishc90/APP-INVENTOR,tvomf/appinventor-mapps,wanddy/appinventor-sources,bxie/appinventor-sources,thequixotic/appinventor-sources,CoderDojoLX/appinventor-sources,marksherman/appinventor-sources,jithinbp/appinventor-sources,jisqyv/appinventor-sources,jsheldonmit/appinventor-sources,onyeka/AppInventor-WebApp,CoderDojoLX/appinventor-sources,mark-friedman/web-appinventor,cs6510/CS6510-LiveEdit-Onyeka,tiffanyle/appinventor-sources,DRavnaas/appinventor-clone,mintingle/appinventor-sources,puravidaapps/appinventor-sources,ewpatton/appinventor-sources,farxinu/appinventor-sources,ram8647/appinventor-sources,kannan-usf/AppInventorJavaBridge,kpjs4s/AppInventorJavaBridgeCodeGen,joshaham/latest_app_inventor,cs6510/CS6510-LiveEdit-Onyeka,doburaimo/appinventor-sources,nickboucart/appinventor-sources,hasi96/appinventor-sources,Momoumar/appinventor-sources,barreeeiroo/appinventor-sources,satgod/appinventor,barreeeiroo/appinventor-sources,ram8647/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,mintingle/appinventor-sources,onyeka/AppInventor-WebApp,fturbak/appinventor-sources,Klomi/appinventor-sources,kannan-usf/AppInventorJavaBridge,RachaelT/appinventor-sources,aouskaroui/appinventor-sources,nickboucart/appinventor-sources,GodUseVPN/appinventor-sources,GodUseVPN/appinventor-sources,warren922/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,sujianping/appinventor-sources,weihuali0509/appinventor-sources,mark-friedman/web-appinventor,JalexChang/appinventor-sources,graceRyu/appinventor-sources,toropeza/appinventor-sources,wicedfast/appinventor-sources,mintingle/appinventor-sources,awoodworth/appinventor-sources,GodUseVPN/appinventor-sources,ajcolter/appinventor-sources,thequixotic/appinventor-sources,marksherman/appinventor-sources,toropeza/appinventor-sources,egiurleo/appinventor-sources,hasi96/appinventor-sources,themadrobot/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,marksherman/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,halatmit/appinventor-sources,graceRyu/appinventor-sources,marksherman/appinventor-sources,liyucun/appinventor-sources,Edeleon4/punya,FIRST-Tech-Challenge/appinventor-sources,themadrobot/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,fmntf/appinventor-sources,afmckinney/appinventor-sources,bxie/appinventor-sources,kannan-usf/AppInventorJavaBridge,bxie/appinventor-sources,mit-dig/punya,fmntf/appinventor-sources,dengxinyue0420/appinventor-sources,DRavnaas/appinventor-clone,Mateopato/appinventor-sources,josmas/app-inventor,Klomi/appinventor-sources,KeithGalli/appinventor-sources,tiffanyle/appinventor-sources,ajcolter/appinventor-sources,josmas/app-inventor,satgod/appinventor,anseo/friedgerAI24BLE,kkashi01/appinventor-sources,tatuzaumm/app-inventor2-custom,frfranca/appinventor-sources,barreeeiroo/appinventor-sources,satgod/appinventor,mit-cml/appinventor-sources,josmas/app-inventor,youprofit/appinventor-sources,josmas/app-inventor,Edeleon4/punya,toropeza/appinventor-sources,E-Hon/appinventor-sources,nmcalabroso/appinventor-sources,tvomf/appinventor-mapps,nmcalabroso/appinventor-sources,weihuali0509/web-appinventor,Mateopato/appinventor-sources,graceRyu/appinventor-sources,anseo/friedgerAI24BLE,weihuali0509/appinventor-sources,kkashi01/appinventor-sources,gitars/appinventor-sources,farxinu/appinventor-sources,spefley/appinventor-sources,lizlooney/appinventor-sources,kidebit/AudioBlurp,lizlooney/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,jsheldonmit/appinventor-sources,ZachLamb/appinventor-sources,sujianping/appinventor-sources,jithinbp/appinventor-sources,tvomf/appinventor-mapps,tatuzaumm/app-inventor2-custom,onyeka/AppInventor-WebApp,mintingle/appinventor-sources,mark-friedman/web-appinventor,tatuzaumm/app-inventor2-custom,wadleo/appinventor-sources,hasi96/appinventor-sources,Edeleon4/punya,GodUseVPN/appinventor-sources,wicedfast/appinventor-sources,mit-dig/punya,jisqyv/appinventor-sources,graceRyu/appinventor-sources,awoodworth/appinventor-sources,ajcolter/appinventor-sources,Mateopato/appinventor-sources,kidebit/AudioBlurp,farxinu/appinventor-sources,Edeleon4/punya,wanddy/appinventor-sources,afmckinney/appinventor-sources,wanddy/appinventor-sources,youprofit/appinventor-sources,jithinbp/appinventor-sources,doburaimo/appinventor-sources,mark-friedman/web-appinventor,joshaham/latest_app_inventor,E-Hon/appinventor-sources,Klomi/appinventor-sources,CoderDojoLX/appinventor-sources,mit-cml/appinventor-sources,graceRyu/appinventor-sources,Mateopato/appinventor-sources,warren922/appinventor-sources,doburaimo/appinventor-sources,thilankam/appinventor-sources,aouskaroui/appinventor-sources,nickboucart/appinventor-sources,Edeleon4/punya,Momoumar/appinventor-sources,kkashi01/appinventor-sources,jisqyv/appinventor-sources,nmcalabroso/appinventor-sources,afmckinney/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,krishc90/APP-INVENTOR,youprofit/appinventor-sources,sujianping/appinventor-sources,krishc90/APP-INVENTOR,nmcalabroso/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,joshaham/latest_app_inventor,youprofit/appinventor-sources,kkashi01/appinventor-sources,RachaelT/appinventor-sources,egiurleo/appinventor-sources,frfranca/appinventor-sources,Momoumar/appinventor-sources,emeryotopalik/appinventor-sources,aouskaroui/appinventor-sources,halatmit/appinventor-sources,KeithGalli/appinventor-sources,jisqyv/appinventor-sources,ZachLamb/appinventor-sources,jisqyv/appinventor-sources,anseo/friedgerAI24BLE,satgod/appinventor,emeryotopalik/appinventor-sources,frfranca/appinventor-sources,puravidaapps/appinventor-sources,jithinbp/appinventor-sources,fmntf/appinventor-sources,tiffanyle/appinventor-sources,bitsecure/appinventor1-sources,wanddy/appinventor-sources,anseo/friedgerAI24BLE,liyucun/appinventor-sources,liyucun/appinventor-sources,DRavnaas/appinventor-clone,puravidaapps/appinventor-sources,dengxinyue0420/appinventor-sources,weihuali0509/appinventor-sources,emeryotopalik/appinventor-sources,emeryotopalik/appinventor-sources,themadrobot/appinventor-sources,thilankam/appinventor-sources,weihuali0509/web-appinventor,doburaimo/appinventor-sources,tiffanyle/appinventor-sources,onyeka/AppInventor-WebApp,egiurleo/appinventor-sources,fmntf/appinventor-sources,RachaelT/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,RachaelT/appinventor-sources,kidebit/AudioBlurp,FIRST-Tech-Challenge/appinventor-sources,ZachLamb/appinventor-sources,mit-cml/appinventor-sources,ram8647/appinventor-sources,mit-cml/appinventor-sources,Klomi/appinventor-sources,liyucun/appinventor-sources,dengxinyue0420/appinventor-sources,tatuzaumm/app-inventor2-custom,JalexChang/appinventor-sources,kidebit/AudioBlurp,frfranca/appinventor-sources,halatmit/appinventor-sources,marksherman/appinventor-sources,lizlooney/appinventor-sources
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt package com.google.appinventor.client; import com.google.gwt.i18n.client.Messages; /** * I18n strings for {@link Ode}. * */ //@LocalizableResource.Generate(format = "com.google.gwt.i18n.rebind.format.PropertiesFormat") //@LocalizableResource.DefaultLocale("en") public interface OdeMessages extends Messages { // Used in multiple files @DefaultMessage("Cancel") @Description("Text on \"Cancel\" button.") String cancelButton(); @DefaultMessage("OK") @Description("Text on \"OK\" button.") String okButton(); @DefaultMessage("Dismiss") @Description("Text on \"Dismiss\" button.") String dismissButton(); @DefaultMessage("Old name:") @Description("Label next to the old name in a rename dialog") String oldNameLabel(); @DefaultMessage("New name:") @Description("Label next to the new name in a rename dialog") String newNameLabel(); @DefaultMessage("None") @Description("Caption for None entry") String noneCaption(); @DefaultMessage("Delete") @Description("Text on \"Delete\" button") String deleteButton(); @DefaultMessage("Delete Project") @Description("Text on \"Delete Project\" button") String deleteProjectButton(); @DefaultMessage("Show Warnings") @Description("Text on Toggle Warning Button") String showWarnings(); @DefaultMessage("Hide Warnings") @Description("Text on Toggle Warning Button") String hideWarnings(); @DefaultMessage("Upload File ...") @Description("Text on \"Add...\" button") String addButton(); @DefaultMessage("Name") @Description("Header for name column of project table") String projectNameHeader(); @DefaultMessage("Date Created") @Description("Header for date created column of project table.") String projectDateCreatedHeader(); @DefaultMessage("Date Modified") @Description("Header for date modified column of project table.") String projectDateModifiedHeader(); @DefaultMessage("Save") @Description("Label of the button for save") String saveButton(); @DefaultMessage("Save As") @Description("Label of the button for save as") String saveAsButton(); @DefaultMessage("Checkpoint ...") @Description("Label of the button for checkpoint") String checkpointButton(); @DefaultMessage("Add Screen ...") @Description("Label of the button for adding a new screen") String addFormButton(); @DefaultMessage("Remove Screen") @Description("Label of the button for removing a screen") String removeFormButton(); @DefaultMessage("Connect") @Description("Label of the button for selecting phone connection") String connectButton(); @DefaultMessage("Deleting this screen will completely remove the screen from your project. " + "All components and blocks associated with this screen will be deleted.\n" + "There is no undo.\nAre you sure you want to delete {0}?") @Description("Confirmation query for removing a screen") String reallyDeleteForm(String formName); @DefaultMessage("Open the Blocks Editor") @Description("Label of the button for opening the blocks editor") String openBlocksEditorButton(); @DefaultMessage("Screens ...") @Description("Label of the button for switching screens") String screensButton(); @DefaultMessage("Blocks") @Description("Label of the button for switching to the blocks editor") String switchToBlocksEditorButton(); @DefaultMessage("Designer") @Description("Label of the button for switching to the form editor") String switchToFormEditorButton(); @DefaultMessage("Packaging ...") @Description("Label of the button leading to build related cascade items, when building") String isBuildingButton(); @DefaultMessage("Opening the Blocks Editor... (click to cancel)") @Description("Label of the button for canceling the blocks editor launch") String cancelBlocksEditorButton(); @DefaultMessage("Blocks Editor is open") @Description("Label of the button for opening the blocks editor when the it is already open") String blocksEditorIsOpenButton(); // Switch Language Buttons (Internationalization) @DefaultMessage("Language") @Description("Label of the button for switching language") String switchLanguageButton(); // Not used anymore it is now dynamically created and translated at compile time depending on what //languages are translated and available. // @DefaultMessage("English") // @Description("Label of the button for switching language to English") // String switchLanguageEnglishButton(); // // @DefaultMessage("Chinese CN") // @Description("Label of the button for switching language to Chinese CN") // String switchLanguageChineseCNButton(); // // @DefaultMessage("German") // @Description("Label of the button for switching language to German") // String switchLanguageGermanButton(); // // @DefaultMessage("Vietnamese") // @Description("Label of the button for switching language to Vietnamese") // String switchLanguageVietnameseButton(); // Used in MotdFetcher.java @DefaultMessage("Failed to contact server to get the MOTD.") @Description("Message displayed when cannot get a MOTD from the server.") String getMotdFailed(); // Used in Ode.java // TODO(user): Replace with commented version once we're ready @DefaultMessage("MIT App Inventor 2") @Description("Title for App Inventor") String titleYoungAndroid(); @DefaultMessage("An internal error has occurred. Report a bug?") @Description("Confirmation for reporting a bug after an internal error") String internalErrorReportBug(); @DefaultMessage("An internal error has occurred.") @Description("Alert after an internal error") String internalError(); @DefaultMessage("An internal error has occurred. Go look in the Debugging view.") @Description("Alert after an internal error") String internalErrorSeeDebuggingView(); @DefaultMessage("An internal error has occurred. Click \"ok\" for more information.") @Description("Confirm alert after an internal error") String internalErrorClickOkDebuggingView(); @DefaultMessage("The server is temporarily unavailable. Please try again later!") @Description("Error message if the server becomes completely unavailable.") String serverUnavailable(); @DefaultMessage("No Project Chosen") @Description("Title for Error Dialog when connection is attempted without a project.") String noprojectDialogTitle(); @DefaultMessage("You must first create or select a project before connecting!") @Description("Error message for connection attempt without a project selected.") String noprojectDuringConnect(); // Used in RpcStatusPopup.java @DefaultMessage("Loading ...") @Description("Message that is shown to indicate that a loading RPC is going on") String defaultRpcMessage(); @DefaultMessage("Saving ...") @Description("Message that is shown to indicate that a saving RPC is going on") String savingRpcMessage(); @DefaultMessage("Copying ...") @Description("Message that is shown to indicate that a copying RPC is going on") String copyingRpcMessage(); @DefaultMessage("Deleting ...") @Description("Message that is shown to indicate that a deleting RPC is going on") String deletingRpcMessage(); @DefaultMessage("Packaging ...") @Description("Message shown during a building RPC (for Young Android, called 'packaging')") String packagingRpcMessage(); @DefaultMessage("Downloading to phone ...") @Description("Message shown while downloading application to the phone (during compilation)") String downloadingRpcMessage(); // Used in StatusPanel.java @DefaultMessage("Built: {0} Version: {1}") @Description("Label showing the ant build date and the git version") String gitBuildId(String date, String version); @DefaultMessage("Privacy") @Description("Label of the link for Privacy") String privacyLink(); @DefaultMessage("Terms") @Description("Label of the link for Terms") String termsLink(); @DefaultMessage("Privacy Policy and Terms of Use") @Description("Label of the link for Privacy and Terms of Use") String privacyTermsLink(); // Used in TopPanel.java //Project @DefaultMessage("Projects") @Description("Name of Projects tab") String projectsTabName(); @DefaultMessage("My projects") @Description("Name of My projects menuitem") String projectMenuItem(); @DefaultMessage("Start new project") @Description("Label of the menu item for creating a new project") String newProjectMenuItem(); @DefaultMessage("Import project (.aia) from my computer ...") @Description("Name of Import Project menuitem") String importProjectMenuItem(); @DefaultMessage("Delete project") @Description("Name of Delete project menuitem") String deleteProjectMenuItem(); @DefaultMessage("Save project") @Description("Name of Save menuitem") String saveMenuItem(); @DefaultMessage("Save project as ...") @Description("Name of Save as ... menuitem") String saveAsMenuItem(); @DefaultMessage("Checkpoint") @Description("Name of Checkpoint menuitem") String checkpointMenuItem(); @DefaultMessage("Import project (.aia) from a repository ...") @Description("Name of Import Template menuitem") String importTemplateButton(); @DefaultMessage("Export selected project (.aia) to my computer") @Description("Name of Export Project menuitem") String exportProjectMenuItem(); @DefaultMessage("Export all projects") @Description("Name of Export all Project menuitem") String exportAllProjectsMenuItem(); @DefaultMessage("Export keystore") @Description("Label of the button for export keystore") String downloadKeystoreMenuItem(); @DefaultMessage("Import keystore") @Description("Label of the button for import keystore") String uploadKeystoreMenuItem(); @DefaultMessage("Delete keystore") @Description("Label of the button for delete keystore") String deleteKeystoreMenuItem(); //Connect @DefaultMessage("Connect") @Description("Label of the button leading to Connect related cascade items") String connectTabName(); @DefaultMessage("AI Companion") @Description("Message providing details about starting the wireless connection.") String AICompanionMenuItem(); @DefaultMessage("Emulator") @Description("Message providing details about starting the emulator connection.") String emulatorMenuItem(); @DefaultMessage("USB") @Description("Message providing details about starting a USB connection.") String usbMenuItem(); @DefaultMessage("Reset Connection") @Description("Reset all connections.") String resetConnectionsMenuItem(); @DefaultMessage("Hard Reset") @Description("Hard Reset the Emulator.") String hardResetConnectionsMenuItem(); //Build @DefaultMessage("Build") @Description("Label of the button leading to build related cascade items") String buildTabName(); @DefaultMessage("App ( provide QR code for .apk )") @Description("Label of item for building a project and show barcode") String showBarcodeMenuItem(); @DefaultMessage("App ( save .apk to my computer )") @Description("Label of item for building a project and downloading") String downloadToComputerMenuItem(); @DefaultMessage("Generate YAIL") @Description("Label of the cascade item for generating YAIL for a project") String generateYailMenuItem(); //Help @DefaultMessage("Help") @Description("Label for the Help menu") String helpTabName(); @DefaultMessage("About") @Description("Label of the link for About") String aboutMenuItem(); @DefaultMessage("Library") @Description("Name of Library link") String libraryMenuItem(); @DefaultMessage("Get Started") @Description("Name of Getting Started link") String getStartedMenuItem(); @DefaultMessage("Tutorials") @Description("Name of Tutorials link") String tutorialsMenuItem(); @DefaultMessage("Troubleshooting") @Description("Name of Troubleshooting link") String troubleshootingMenuItem(); @DefaultMessage("Forums") @Description("Name of Forums link") String forumsMenuItem(); @DefaultMessage("Report an Issue") @Description("Link for Report an Issue form") String feedbackMenuItem(); //Admin @DefaultMessage("Admin") @Description("Label of the button leading to admin functionality") String adminTabName(); @DefaultMessage("Download User Source") @Description("Label of the button for admins to download a user's project source") String downloadUserSourceMenuItem(); @DefaultMessage("Switch To Debug Panel") @Description("Label of the button for admins to switch to the debug panel without an explicit error") String switchToDebugMenuItem(); //Tabs @DefaultMessage("My Projects") @Description("Name of My Projects tab") String myProjectsTabName(); @DefaultMessage("Guide") @Description("Name of Guide link") String guideTabName(); @DefaultMessage("Report an Issue") @Description("Link for Report an Issue form") String feedbackTabName(); @DefaultMessage("Gallery") @Description("Link for Gallery") String galleryTabName(); //User email dropdown @DefaultMessage("Sign out") @Description("Label of the link for signing out") String signOutLink(); // @DefaultMessage("Design") @Description("Name of Design tab") String tabNameDesign(); @DefaultMessage("(Debugging)") @Description("Name of Debugging tab") String tabNameDebugging(); @DefaultMessage("Please choose a project to open or create a new project.") @Description("Message shown when there is no current file editor to switch to") String chooseProject(); // Used in boxes/AssetListBox.java @DefaultMessage("Media") @Description("Caption for asset list box.") String assetListBoxCaption(); // Used in boxes/MessagesOutputBox.java @DefaultMessage("Messages") @Description("Caption for message output box.") String messagesOutputBoxCaption(); // Used in boxes/MotdBox.java @DefaultMessage("Welcome to App Inventor!") @Description("Initial caption for MOTD box.") String motdBoxCaption(); // Used in boxes/OdeLogBox.java @DefaultMessage("Developer Messages") @Description("Caption for ODE log box.") String odeLogBoxCaption(); // Used in boxes/PaletteBox.java @DefaultMessage("Palette") @Description("Caption for palette box.") String paletteBoxCaption(); // Used in boxes/ProjectListBox.java @DefaultMessage("Projects") @Description("Caption for project list box.") String projectListBoxCaption(); // Used in boxes/PropertiesBox.java @DefaultMessage("Properties") @Description("Caption for properties box.") String propertiesBoxCaption(); // Used in boxes/SourceStructureBox.java @DefaultMessage("Components") @Description("Caption for source structure box.") String sourceStructureBoxCaption(); // Used in boxes/BlockSelectorBox.java @DefaultMessage("Blocks") @Description("Caption for block selector box.") String blockSelectorBoxCaption(); @DefaultMessage("Built-in") @Description("Label on built-in-blocks branch of block selector tree") String builtinBlocksLabel(); @DefaultMessage("Control") @Description("Label on built-in-Control-blocks branch of block selector tree") String builtinControlLabel(); @DefaultMessage("Logic") @Description("Label on built-in-Logic-blocks branch of block selector tree") String builtinLogicLabel(); @DefaultMessage("Text") @Description("Label on built-in-Text-blocks branch of block selector tree") String builtinTextLabel(); @DefaultMessage("Lists") @Description("Label on built-in-Lists-blocks branch of block selector tree") String builtinListsLabel(); @DefaultMessage("Colors") @Description("Label on built-in-Colors-blocks branch of block selector tree") String builtinColorsLabel(); @DefaultMessage("Variables") @Description("Label on built-in-Variables-blocks branch of block selector tree") String builtinVariablesLabel(); @DefaultMessage("Procedures") @Description("Label on built-in-Procedures-blocks branch of block selector tree") String builtinProceduresLabel(); @DefaultMessage("Any component") @Description("Label on any-component branch of block selector tree") String anyComponentLabel(); @DefaultMessage("Any ") @Description("None") String textAnyComponentLabel(); // Used in boxes/ViewerBox.java @DefaultMessage("Viewer") @Description("Caption for a viewer box.") String viewerBoxCaption(); // Used in SaveAllEditorsCommand.java @DefaultMessage("Saved project at {0}") @Description("Message reported when project was saved successfully.") String savedProject(String saveTime); // Used in editor/EditorManager.java @DefaultMessage("Server error: could not save one or more files. Please try again later!") @Description("Error message reported when one or more file couldn't be saved to the server.") String saveErrorMultipleFiles(); @DefaultMessage("Error generating Yail for screen {0}: {1}. Please fix and try packaging again.") @Description("Error message reported when yail generation fails for a screen") String yailGenerationError(String formName, String description); // Used in editor/simple/SimpleNonVisibleComponentsPanel.java @DefaultMessage("Non-visible components") @Description("Header for the non-visible components in the designer.") String nonVisibleComponentsHeader(); // Used in editor/simple/SimpleVisibleComponentsPanel.java @DefaultMessage("Display hidden components in Viewer") @Description("Checkbox controlling whether to display invisible components in the designer.") String showHiddenComponentsCheckbox(); @DefaultMessage("Check to see Preview on Tablet size.") @Description("Checkbox (check) controlling whether to display a preview on Tablet size.") String previewTabletSize(); @DefaultMessage("Un-check to see Preview on Phone size.") @Description("Checkbox (un-check) controlling whether to display a preview on Phone size.") String previewPhoneSize(); // Used in editor/simple/components/MockComponent.java @DefaultMessage("Rename Component") @Description("Title for the rename component dialog") String renameTitle(); @DefaultMessage("Component names can contain only letters, numbers, and underscores and " + "must start with a letter") @Description("Error message when component name contains non-alphanumeric characters besides _ " + "or does not start with a letter") String malformedComponentNameError(); @DefaultMessage("Duplicate component name!") @Description("Error shown when a new component name would be the same as an existing one") String duplicateComponentNameError(); @DefaultMessage("Component instance names cannot be the same as a component type") @Description("Error shown when a new component name would be the same as a component type name") String sameAsComponentTypeNameError(); @DefaultMessage("Component name cannot be any of the following: CsvUtil, Double, Float, " + "Integer, JavaCollection, JavaIterator, KawaEnvironment, Long, Short, SimpleForm, String, " + "Pattern, YailList, YailNumberToString, YailRuntimeError") @Description("Error shown when a new component name is a variable name already used in the" + "Yail code") String badComponentNameError(); @DefaultMessage("Deleting this component will delete all blocks associated with it in the " + "Blocks Editor. Are you sure you want to delete?") @Description("Confirmation query for removing a component") String reallyDeleteComponent(); // Used in editor/simple/components/MockButtonBase.java, MockCheckBox.java, MockLabel.java, and // MockRadioButton.java @DefaultMessage("Text for {0}") @Description("Default value for Text property") String textPropertyValue(String componentName); // Used in editor/simple/components/MockButtonBase.java, MockHVLayoutBase.java @DefaultMessage("System error: Bad value - {0} - for Horizontal Alignment.") @Description("Default message for bad value for Horizontal Alignment") String badValueForHorizontalAlignment(String componentName); @DefaultMessage("System error: Bad value - {0} - for Vertical Alignment.") @Description("Default message for bad value for Vartical Alignment") String badValueForVerticalAlignment(String componentName); // Used in editor/simple/components/MockVisibleComponent.java @DefaultMessage("Width") @Description("Caption for the width property") String widthPropertyCaption(); @DefaultMessage("Height") @Description("Caption for the height property") String heightPropertyCaption(); // Used in editor/simple/components/MockTextBoxBase.java @DefaultMessage("Hint for {0}") @Description("Default value for Hint property") String hintPropertyValue(String componentName); // Used in editor/simple/palette/ComponentHelpWidget.java @DefaultMessage("More information") @Description("Label of the link to a component's reference docs") String moreInformation(); // Used in editor/youngandroid/YaFormEditor.java and YaBlocksEditor.java @DefaultMessage("Server error: could not load file. Please try again later!") @Description("Error message reported when a source file couldn't be loaded from the server.") String loadError(); @DefaultMessage("Server error: could not save file. Please try again later!") @Description("Error message reported when a source file couldn't be saved to the server.") String saveError(); @DefaultMessage("{0} blocks") @Description("Tab name for blocks editor") String blocksEditorTabName(String formName); // Used in editor/youngandroid/BlocklyPanel.java @DefaultMessage("The blocks area did not load properly. Changes to the blocks for screen {0} will not be saved.") @Description("Message indicating that blocks changes were not saved") String blocksNotSaved(String formName); @DefaultMessage("The blocks for screen {0} did not load properly. " + "You will not be able to edit using the blocks editor until the problem is corrected.") @Description("Message when blocks fail to load properly") String blocksLoadFailure(String formName); //Used in editor/youngandroid/properties/YoungAndroidAccelerometerSensitivityChoicePropertyEditor.java @DefaultMessage("weak") @Description("Text for accelerometer sensitivity choice 'weak'") String weakAccelerometerSensitivity(); @DefaultMessage("moderate") @Description("Text for accelerometer sensitivity choice 'moderate'") String moderateAccelerometerSensitivity(); @DefaultMessage("strong") @Description("Text for accelerometer sensitivity choice 'strong'") String strongAccelerometerSensitivity(); // Used in editor/youngandroid/properties/YoungAndroidAlignmentChoicePropertyEditor.java @DefaultMessage("left") @Description("Text for text alignment choice 'left'") String leftTextAlignment(); @DefaultMessage("center") @Description("Text for text alignment choice 'center'") String centerTextAlignment(); @DefaultMessage("right") @Description("Text for text alignment choice 'right'") String rightTextAlignment(); // Used in // editor/youngandroid/properties/YoungAndroidHorizontalAlignmentChoicePropertyEditor.java @DefaultMessage("Left") @Description("Text for horizontal alignment choice 'Left") String horizontalAlignmentChoiceLeft(); @DefaultMessage("Right") @Description("Text for horizontal alignemt choice 'Right'") String horizontalAlignmentChoiceRight(); @DefaultMessage("Center") @Description("Text for horizontal alignment choice 'Center'") String horizontalAlignmentChoiceCenter(); // Used in // editor/youngandroid/properties/YoungAndroidVerticalAlignmentChoicePropertyEditor.java @DefaultMessage("Top") @Description("Text for vertical alignment choice 'Top'") String verticalAlignmentChoiceTop(); @DefaultMessage("Center") @Description("Text for vertical alignment choice 'Center'") String verticalAlignmentChoiceCenter(); @DefaultMessage("Bottom") @Description("Text for vertical alignment choice 'Bottom'") String verticalAlignmentChoiceBottom(); // Used in editor/youngandroid/properties/YoungAndroidButtonShapeChoicePropertyEditor.java @DefaultMessage("default") @Description("Text for button shape choice 'default'") String defaultButtonShape(); @DefaultMessage("rounded") @Description("Text for button shape choice 'rounded'") String roundedButtonShape(); @DefaultMessage("rectangular") @Description("Text for button shape choice 'rectangular'") String rectButtonShape(); @DefaultMessage("oval") @Description("Text for button shape choice 'oval'") String ovalButtonShape(); // Used in editor/youngandroid/properties/YoungAndroidAssetSelectorPropertyEditor.java @DefaultMessage("You must select an asset!") @Description("Message displayed when OK button is clicked when there is no asset selected.") String noAssetSelected(); // Used in editor/youngandroid/properties/YoungAndroidComponentSelectorPropertyEditor.java @DefaultMessage("You must select a component!") @Description("Message displayed when OK button is clicked when there is no component selected.") String noComponentSelected(); // Used in editor/youngandroid/properties/YoungAndroidColorChoicePropertyEditor.java @DefaultMessage("None") @Description("Text for color choice 'None'") String noneColor(); @DefaultMessage("Black") @Description("Text for color choice 'Black'") String blackColor(); @DefaultMessage("Blue") @Description("Text for color choice 'Blue'") String blueColor(); @DefaultMessage("Cyan") @Description("Text for color choice 'Cyan'") String cyanColor(); @DefaultMessage("Default") @Description("Text for color choice 'Default'") String defaultColor(); @DefaultMessage("Dark Gray") @Description("Text for color choice 'Dark Gray'") String darkGrayColor(); @DefaultMessage("Gray") @Description("Text for color choice 'Gray'") String grayColor(); @DefaultMessage("Green") @Description("Text for color choice 'Green'") String greenColor(); @DefaultMessage("Light Gray") @Description("Text for color choice 'Light Gray'") String lightGrayColor(); @DefaultMessage("Magenta") @Description("Text for color choice 'Magenta'") String magentaColor(); @DefaultMessage("Orange") @Description("Text for color choice 'Orange'") String orangeColor(); @DefaultMessage("Pink") @Description("Text for color choice 'Pink'") String pinkColor(); @DefaultMessage("Red") @Description("Text for color choice 'Red'") String redColor(); @DefaultMessage("White") @Description("Text for color choice 'White'") String whiteColor(); @DefaultMessage("Yellow") @Description("Text for color choice 'Yellow'") String yellowColor(); // Used in editor/youngandroid/properties/YoungAndroidFontTypefaceChoicePropertyEditor.java @DefaultMessage("default") @Description("Text for font typeface choice 'default '") String defaultFontTypeface(); @DefaultMessage("sans serif") @Description("Text for font typeface choice 'sans serif '") String sansSerifFontTypeface(); @DefaultMessage("serif") @Description("Text for font typeface choice 'serif '") String serifFontTypeface(); @DefaultMessage("monospace") @Description("Text for font typeface choice 'monospace '") String monospaceFontTypeface(); // Used in editor/youngandroid/properties/YoungAndroidLengthPropertyEditor.java @DefaultMessage("Automatic") @Description("Caption and summary for Automatic choice") String automaticCaption(); @DefaultMessage("Fill parent") @Description("Caption and summary for Fill Parent choice") String fillParentCaption(); @DefaultMessage("DP") // DP - Density Independent Pixels @Description("Caption for DPs label") String dpsCaption(); @DefaultMessage("{0} DPs") @Description("Summary for custom length in DPs") String dpsSummary(String dps); @DefaultMessage("The value must be a number greater than or equal to 0") @Description("Error shown after validation of custom length field failed.") String nonnumericInputError(); // Used in editor/youngandroid/properties/YoungAndroidScreenAnimationChoicePropertyEditor.java @DefaultMessage("Default") @Description("Text for screen animation choice 'Default '") String defaultScreenAnimation(); @DefaultMessage("Fade") @Description("Text for screen animation choice 'Fade '") String fadeScreenAnimation(); @DefaultMessage("Zoom") @Description("Text for screen animation choice 'Zoom '") String zoomScreenAnimation(); @DefaultMessage("SlideHorizontal") @Description("Text for screen animation choice 'SlideHorizontal '") String slideHorizontalScreenAnimation(); @DefaultMessage("SlideVertical") @Description("Text for screen animation choice 'SlideVertical '") String slideVerticalScreenAnimation(); @DefaultMessage("None") @Description("Text for screen animation choice 'None '") String noneScreenAnimation(); // Used in editor/youngandroid/properties/YoungAndroidScreenOrientationChoicePropertyEditor.java @DefaultMessage("Unspecified") @Description("Text for screen orientation choice 'Unspecified '") String unspecifiedScreenOrientation(); @DefaultMessage("Portrait") @Description("Text for screen orientation choice 'Portrait '") String portraitScreenOrientation(); @DefaultMessage("Landscape") @Description("Text for screen orientation choice 'Landscape '") String landscapeScreenOrientation(); @DefaultMessage("Sensor") @Description("Text for screen orientation choice 'Sensor '") String sensorScreenOrientation(); @DefaultMessage("User") @Description("Text for screen orientation choice 'User '") String userScreenOrientation(); // Used in editor/youngandroid/properties/YoungAndroidToastLengthChoicePropertyEditor.java @DefaultMessage("Short") @Description("Show toast for a Toast_Short of time") String shortToastLength(); @DefaultMessage("Long") @Description("Show toast for a Toast_Long of time") String longToastLength(); // Used in explorer/SourceStructureExplorer.java @DefaultMessage("Rename") @Description("Label of the button for rename") String renameButton(); // Used in explorer/commands/AddFormCommand.java @DefaultMessage("Add") @Description("Text on 'Add' button to continue with screen creation.") String addScreenButton(); @DefaultMessage("Do Not Add") @Description("Text on 'Dont Add' button to dismiss screen creation.") String cancelScreenButton(); @DefaultMessage("New Screen") @Description("Title of new Screen dialog.") String newFormTitle(); @DefaultMessage("Screen name:") @Description("Label in front of name in new screen dialog.") String formNameLabel(); @DefaultMessage("WARNING: The number of screens in this app might exceed the limits of App Inventor. " + "Click <a target=\"_blank\" href=\"/reference/other/manyscreens.html\">here</a> for advice about " + "creating apps with many screens. " + "<p>Do you really want to add another screen?</p>") @Description("Label to indicate the application has too many screens.") String formCountErrorLabel(); @DefaultMessage("Screen names can contain only letters, numbers, and underscores and must " + "start with a letter") @Description("Error message when form name contains non-alphanumeric characters besides _") String malformedFormNameError(); @DefaultMessage("Duplicate Screen name!") @Description("Error shown when a new form name would be the same as an existing one") String duplicateFormNameError(); @DefaultMessage("Server error: could not add form. Please try again later!") @Description("Error message reported when adding a form failed on the server.") String addFormError(); // Used in explorer/commands/BuildCommand.java, and // explorer/commands/WaitForBuildResultCommand.java @DefaultMessage("Build of {0} requested at {1}.") @Description("Message shown in the build output panel when a build is requested.") String buildRequestedMessage(String projectName, String time); @DefaultMessage("Server error: could not build target. Please try again later!") @Description("Error message reported when building a target failed on the server because of a " + "network error.") String buildError(); @DefaultMessage("Build failed!") @Description("Error message reported when a build failed due to an error in the build pipeline.") String buildFailedError(); @DefaultMessage("The build server is currently busy. Please try again in a few minutes.") @Description("Error message reported when the build server is temporarily too busy to accept " + "a build request.") String buildServerBusyError(); @DefaultMessage("The build server is not compatible with this version of App Inventor.") @Description("Error message reported when the build server is running a different version of " + "the App Inventor code.") String buildServerDifferentVersion(); @DefaultMessage("Unable to generate code for {0}.") @Description("Message displayed when an error occurs while generating YAIL for a form.") String errorGeneratingYail(String formName); // Used in explorer/commands/CommandRegistory.java @DefaultMessage("Delete...") @Description("Label for the context menu command that deletes a file") String deleteFileCommand(); @DefaultMessage("Download to my computer") @Description("Label for the context menu command that downloads a file") String downloadFileCommand(); // Used in explorer/commands/CopyYoungAndroidProjectCommand.java @DefaultMessage("Checkpoint - {0}") @Description("Title of checkpoint dialog.") String checkpointTitle(String projectName); @DefaultMessage("Save As - {0}") @Description("Title of save as dialog.") String saveAsTitle(String projectName); @DefaultMessage("{0}_checkpoint{1}") @Description("Default project name in checkoint dialog") String defaultCheckpointProjectName(String projectName, String suffix); @DefaultMessage("Previous checkpoints:") @Description("Label for previous checkpoints table in checkpoint dialog.") String previousCheckpointsLabel(); @DefaultMessage("{0}_copy") @Description("Defaulf project name in save as dialog") String defaultSaveAsProjectName(String projectName); @DefaultMessage("Checkpoint name:") @Description("Label in front of new name in checkpoint dialog.") String checkpointNameLabel(); @DefaultMessage("Server error: could not copy project. Please try again later!") @Description("Error message reported when copying a project failed on the server.") String copyProjectError(); // Used in explorer/commands/DeleteFileCommand.java @DefaultMessage("Do you really want to delete this file? It will be removed from " + "the App Inventor server. Also, parts of your application may still refer to the deleted " + "file, and you will need to change these.") @Description("Confirmation message that will be shown before deleting a file") String reallyDeleteFile(); @DefaultMessage("Server error: could not delete the file. Please try again later!") @Description("Error message reported when deleting a file failed on the server.") String deleteFileError(); // Used in explorer/commands/EnsurePhoneConnectedCommand.java @DefaultMessage("The phone is not connected.") @Description("Error message displayed when the user wants to download a project to the phone, " + "but the phone is not connected.") String phoneNotConnected(); // Used in explorer/commands/ShowBarcodeCommand.java @DefaultMessage("Barcode link for {0}") @Description("Title of barcode dialog.") String barcodeTitle(String projectName); @DefaultMessage("Note: this barcode is only valid for 2 hours. See {0} the FAQ {1} for info " + "on how to share your app with others.") @Description("Warning in barcode dialog.") String barcodeWarning(String aTagStart, String aTagEnd); // Used in explorer/project/Project.java @DefaultMessage("Server error: could not load project. Please try again later!") @Description("Error message reported when a project could not be loaded from the server.") String projectLoadError(); // Used in explorer/project/ProjectManager.java @DefaultMessage("Server error: could not retrieve project information. Please try again later!") @Description("Error message reported when information about projects could not be retrieved " + "from the server.") String projectInformationRetrievalError(); // Used in explorer/youngandroid/Toolbar.java @DefaultMessage("It may take a little while for your projects to be downloaded. " + "Please be patient...") @Description("Warning that downloading projects will take a while") String downloadAllAlert(); @DefaultMessage("More Actions") @Description("Label of the button leading to more cascade items") String moreActionsButton(); @DefaultMessage("Download User Source") @Description("Title of the dialog box for downloading a user's project source") String downloadUserSourceDialogTitle(); @DefaultMessage("User id or email (case-sensitive):") @Description("Label for the user id input text box") String userIdLabel(); @DefaultMessage("Project id or name:") @Description("Label for the project id input text box") String projectIdLabel(); @DefaultMessage("Please specify both a user email address or id and a project name or id " + "for the project to be downloaded. Ids are numeric and may come from the system " + "logs or from browsing the Datastore. If you use an email address, it must match " + "exactly the stored email address in the Datastore. Similarly, project names must " + "match exactly. Both are case sensitive.") @Description("Error message reported when user id or project id is missing") String invalidUserIdOrProjectIdError(); @DefaultMessage("Please select a project to delete") @Description("Error message displayed when no project is selected") String noProjectSelectedForDelete(); @DefaultMessage("Are you really sure you want to delete this project: {0}") @Description("Confirmation message for selecting a single project and clicking delete") String confirmDeleteSingleProject(String projectName); @DefaultMessage("Are you really sure you want to delete these projects: {0}") @Description("Confirmation message for selecting multiple projects and clicking delete") String confirmDeleteManyProjects(String projectNames); @DefaultMessage("Server error: could not delete project. Please try again later!") @Description("Error message reported when deleting a project failed on the server.") String deleteProjectError(); @DefaultMessage("One project must be selected") @Description("Error message displayed when no or many projects are selected") String wrongNumberProjectsSelected(); @DefaultMessage("Server error: could not download your keystore file.") @Description("Error message displayed when a server error occurs during download keystore") String downloadKeystoreError(); @DefaultMessage("There is no keystore file to download.") @Description("Error message displayed when no keystore file exists") String noKeystoreToDownload(); @DefaultMessage("Server error: could not upload your keystore file.") @Description("Error message displayed when a server error occurs during upload keystore") String uploadKeystoreError(); @DefaultMessage("Do you want to overwrite your keystore file?\n\n" + "If you agree, your old keystore file will be completely removed from the App Inventor " + "server.\n\n" + "If you have published applications to the Google Play Store using the keystore you are " + "about to overwrite, you will lose the ability to update your applications.\n\n" + "Any projects that you package in the future will be signed using your new keystore file. " + "Changing the keystore affects the ability to reinstall previously installed apps. If you " + "are not sure that you want to do this, please read the documentation about keystores by " + "clicking above on \"Learn\", then \"Troubleshooting\", and then \"Keystores and Signing " + "of Applications\"\n\n" + "There is no undo for overwriting your keystore file.") @Description("Confirmation message shown when keystore is about to be overwritten.") String confirmOverwriteKeystore(); @DefaultMessage("Server error: could not delete your keystore file.") @Description("Error message reported when a server error occurs during delete keystore") String deleteKeystoreError(); @DefaultMessage("Do you really want to delete your keystore file?\n\n" + "If you agree, your old keystore file will be completely removed from the App Inventor " + "server. A new, but different, keystore file will be created automatically the next time " + "you package a project for the phone.\n\n" + "If you have published applications to the Google Play Store using the keystore you are " + "about to delete, you will lose the ability to update your applications.\n\n" + "Any projects that you package in the future will be signed using your new keystore file. " + "Changing the keystore affects the ability to reinstall previously installed apps. If you " + "are not sure that you want to do this, please read the documentation about keystores by " + "clicking above on \"Learn\", then \"Troubleshooting\", and then \"Keystores and Signing " + "of Applications\"\n\n" + "There is no undo for deleting your keystore file.") @Description("Confirmation message for delete keystore") String confirmDeleteKeystore(); // Used in output/OdeLog.java @DefaultMessage("Clear") @Description("Text on 'Clear' button") String clearButton(); // Used in settings/CommonSettings.java, settings/project/ProjectSettings.java, and // settings/user/UserSettings.java @DefaultMessage("Server error: could not load settings. Please try again later!") @Description("Error message reported when the settings couldn't be loaded from the server.") String settingsLoadError(); @DefaultMessage("Server error: could not save settings. Please try again later!") @Description("Error message reported when the settings couldn't be saved to the server.") String settingsSaveError(); // Used in widgets/boxes/Box.java @DefaultMessage("Done") @Description("Caption for button to finish the box resizing dialog.") String done(); @DefaultMessage("Close") @Description("Tool tip text for header icon for closing/removing a minimized box.") String hdrClose(); @DefaultMessage("Shrink") @Description("Tool tip text for header icon for minimizing the box.") String hdrMinimize(); @DefaultMessage("Settings") @Description("Tool tip text for header icon for context menu of box.") String hdrSettings(); @DefaultMessage("Shrink") @Description("Caption for context menu item for minimizing the box.") String cmMinimize(); @DefaultMessage("Expand") @Description("Caption for context menu item for restoring a minimized box.") String cmRestore(); @DefaultMessage("Resize...") @Description("Caption for context menu item for resizing the box.") String cmResize(); @DefaultMessage("Expand") @Description("Tool tip text for header icon for restoring a minimized box.") String hdrRestore(); // Used in widgets/properties/FloatPropertyEditor.java @DefaultMessage("{0} is not a legal number") @Description("Error shown after validation of float failed.") String notAFloat(String nonNumericText); // Used in widgets/properties/IntegerPropertyEditor.java @DefaultMessage("{0} is not a legal integer") @Description("Error shown after validation of integer failed.") String notAnInteger(String nonNumericText); // Used in widgets/properties/TextPropertyEditor.java @DefaultMessage("Malformed input!") @Description("Error shown after validation of input text failed.") String malformedInputError(); // Used in wizards/FileUploadWizard.java @DefaultMessage("Upload File ...") @Description("Caption for file upload wizard.") String fileUploadWizardCaption(); @DefaultMessage("File names can contain only unaccented letters, numbers, and the characters " + "\"-\", \"_\", \".\", \"!\", \"~\", \"*\", \"(\", and \")\"") @Description("Error message when file name contains characters that would require URL encoding.") String malformedFilename(); @DefaultMessage("File names must be between 1 and 100 characters.") @Description("Error message when filenames are 0 or 101+ characters long") String filenameBadSize(); @DefaultMessage("Uploading {0} to the App Inventor server") @Description("Message displayed when an asset is uploaded.") String fileUploadingMessage(String filename); @DefaultMessage("Server error: could not upload file. Please try again later!") @Description("Error message reported when a file couldn't be uploaded to the server.") String fileUploadError(); @DefaultMessage("Error: could not upload file because it is too large") @Description("Error message reported when a file couldn't be uploaded because of its size.") String fileTooLargeError(); @DefaultMessage("Please select a file to upload.") @Description("Error message reported when a file was not selected.") String noFileSelected(); @DefaultMessage("Request to save {1}" + "\n\nA file named {0} already exists in this project." + "\nDo you want to remove that old file?" + "\nThis will also remove any other files whose " + "names conflict with {1}.") @Description("Confirmation message shown when conflicting files are about to be deleted.") String confirmOverwrite(String newFile, String existingFile); // Used in wizards/KeystoreUploadWizard.java @DefaultMessage("Upload Keystore...") @Description("Caption for keystore upload wizard.") String keystoreUploadWizardCaption(); @DefaultMessage("Server error: could not upload keystore. Please try again later!") @Description("Error message reported when the keystore couldn't be uploaded to the server.") String keystoreUploadError(); @DefaultMessage("The selected file is not a keystore!") @Description("Error message reported when the file selected for upload is not a keystore.") String notKeystoreError(); // Used in wizards/NewProjectWizard.java @DefaultMessage("Server error: could not create project. Please try again later!") @Description("Error message reported when the project couldn't be created on the server.") String createProjectError(); // Used in wizards/TemplateUploadWizard.java @DefaultMessage("Create a Project from a Template") @Description("Caption for template upload wizard.") String templateUploadWizardCaption(); @DefaultMessage("Add a New Template Library Url") @Description("Caption for template dialog menu item.") String templateUploadNewUrlCaption(); @DefaultMessage("Input a Url...") @Description("Caption for input template url wizard.") String inputNewUrlCaption(); @DefaultMessage("Templates Url: ") @Description("Label for template url wizard.") String newUrlLabel(); // Used in wizards/ProjectUploadWizard.java @DefaultMessage("Import Project...") @Description("Caption for project upload wizard.") String projectUploadWizardCaption(); @DefaultMessage("Server error: could not upload project. Please try again later!") @Description("Error message reported when a project couldn't be uploaded to the server.") String projectUploadError(); @DefaultMessage("The selected project is not a project source file!\n" + "Project source files are aia files.") @Description("Error message reported when the file selected for upload is not a project archive.") String notProjectArchiveError(); // Used in wizards/Wizard.java @DefaultMessage("Back") @Description("Text on 'Back' button to go back to the previous page of the wizard.") String backButton(); @DefaultMessage("Next") @Description("Text on 'Next' button to proceed to the next page of the wizard.") String nextButton(); // Used in wizards/youngandroid/NewYoungAndroidProjectWizard.java @DefaultMessage("Create new App Inventor project") @Description("Caption for the wizard to create a new Young Android project") String newYoungAndroidProjectWizardCaption(); @DefaultMessage("Project name:") @Description("Label for the project name input text box") String projectNameLabel(); // Used in youngandroid/TextValidators.java @DefaultMessage("Project names must start with a letter and can contain only letters, " + "numbers, and underscores") @Description("Error message when project name does not start with a letter or contains a " + "character that is not a letter, number, or underscore.") String malformedProjectNameError(); @DefaultMessage("{0} already exists. You cannot create another project with the same name.") @Description("Error shown when a new project name would be the same as an existing one") String duplicateProjectNameError(String projectName); // Used in youngandroid/YoungAndroidFormUpgrader.java @DefaultMessage("This project was created with an older version of the App Inventor " + "system and was upgraded.\n{0}") @Description("Alert message displayed when a project is upgraded") String projectWasUpgraded(String details); @DefaultMessage("A problem occurred while loading this project. {0}") @Description("Alert message displayed when upgrade fails") String unexpectedProblem(String details); @DefaultMessage("This project was saved with a newer version of the App Inventor system. We " + "will attempt to load the project, but there may be compatibility issues.") @Description("Alert message displayed when project is newer than system") String newerVersionProject(); @DefaultMessage("This project was saved with an early pre-release version of the App Inventor " + "system. We will attempt to load the project, but there may be compatibility issues.") @Description("Alert message displayed when upgrading a project without version numbers") String veryOldProject(); @DefaultMessage("The Logger component named {0} was changed to a Notifier component.\n") @Description("Message providing details about a project upgrade involving a Logger component") String upgradeDetailLoggerReplacedWithNotifier(String name); @DefaultMessage("Unable to load project with {0} version {1} (maximum known version is {2}).") @Description("Exception message used when a project contains a newer version component than " + "the version known by the system") String newerVersionComponentException(String componentType, int srcCompVersion, int sysCompVersion); @DefaultMessage("No upgrade strategy exists for {0} from version {1} to {2}.") @Description("Exception message used when a component was not upgraded") String noUpgradeStrategyException(String componentType, int srcCompVersion, int sysCompVersion); // Used in client/editor/simple/components/MockHVarrangement.java @DefaultMessage("System error: bad alignment property editor for horizontal or vertical arrangement.") @Description("System error message for a bad alignment property editor") String badAlignmentPropertyEditorForArrangement(); // Used in // editor/youngandroid/properties/YoungAndroidTextReceivingPropertyEditor.java @DefaultMessage("Off") @Description("Text Messages are not received at any time.") String textReceivingChoiceOff(); @DefaultMessage("Foreground") @Description("Text Messages are received only when the App is in the foreground.") String textReceivingChoiceForeground(); @DefaultMessage("Always") @Description("Text messages are always received, and a notification is shown if the App is in the background.") String textReceivingChoiceAlways(); // This error message is displayed as HTML @DefaultMessage("App Inventor is unable to compile this project. " + "<br /> The compiler error output was <br /> {0}.") @Description("Compilation error, with error message.") String unableToCompile(String errorMesssage); // This error message is displayed as HTML @DefaultMessage("User Interface") @Description("") String UIComponentPallette(); @DefaultMessage("Layout") @Description("") String layoutComponentPallette(); @DefaultMessage("Media") @Description("") String mediaComponentPallette(); @DefaultMessage("Drawing and Animation") @Description("") String drawanimationComponentPallette(); @DefaultMessage("Sensors") @Description("") String sensorsComponentPallette(); @DefaultMessage("Social") @Description("") String socialComponentPallette(); @DefaultMessage("Storage") @Description("") String storageComponentPallette(); @DefaultMessage("Form") @Description("") String FormComponentPallette(); @DefaultMessage("Math") @Description("Label on built-in-Math-blocks branch of block selector tree") String builtinMathLabel(); @DefaultMessage("Connectivity") @Description("") String connectivityComponentPallette(); @DefaultMessage("LEGO\u00AE MINDSTORMS\u00AE") @Description("") String legoComponentPallette(); @DefaultMessage("Experimental") @Description("") String experimentalComponentPallette(); @DefaultMessage("For internal use only") @Description("") String internalUseComponentPallette(); @DefaultMessage("Uninitialized") @Description("") String uninitializedComponentPallette(); // UI Pallette @DefaultMessage("Button") @Description("") String buttonComponentPallette(); @DefaultMessage("Canvas") @Description("") String canvasComponentPallette(); @DefaultMessage("CheckBox") @Description("") String checkBoxComponentPallette(); @DefaultMessage("Clock") @Description("") String clockComponentPallette(); @DefaultMessage("DatePicker") @Description("") String datePickerComponentPallette(); @DefaultMessage("Image") @Description("") String imageComponentPallette(); @DefaultMessage("Label") @Description("") String labelComponentPallette(); @DefaultMessage("ListPicker") @Description("") String listPickerComponentPallette(); @DefaultMessage("ListView") @Description("") String listViewComponentPallette(); @DefaultMessage("PasswordTextBox") @Description("") String passwordTextBoxComponentPallette(); @DefaultMessage("Slider") @Description("") String sliderComponentPallette(); @DefaultMessage("Spinner") @Description("") String spinnerComponentPallette(); @DefaultMessage("TextBox") @Description("") String textBoxComponentPallette(); @DefaultMessage("TimePicker") @Description("") String timePickerComponentPallette(); @DefaultMessage("TinyDB") @Description("") String tinyDBComponentPallette(); // Media Pallette @DefaultMessage("Camcorder") @Description("") String camcorderComponentPallette(); @DefaultMessage("Camera") @Description("") String cameraComponentPallette(); @DefaultMessage("ImagePicker") @Description("") String imagePickerComponentPallette(); @DefaultMessage("Player") @Description("") String playerComponentPallette(); @DefaultMessage("Sound") @Description("") String soundComponentPallette(); @DefaultMessage("VideoPlayer") @Description("") String videoPlayerComponentPallette(); @DefaultMessage("YandexTranslate") @Description("") String yandexTranslateComponentPallette(); // Animation @DefaultMessage("Ball") @Description("") String ballComponentPallette(); @DefaultMessage("ImageSprite") @Description("") String imageSpriteComponentPallette(); // Social @DefaultMessage("ContactPicker") @Description("") String contactPickerComponentPallette(); @DefaultMessage("EmailPicker") @Description("") String emailPickerComponentPallette(); @DefaultMessage("PhoneCall") @Description("") String phoneCallComponentPallette(); @DefaultMessage("PhoneNumberPicker") @Description("") String phoneNumberPickerComponentPallette(); @DefaultMessage("Sharing") @Description("") String sharingComponentPallette(); @DefaultMessage("Texting") @Description("") String textingComponentPallette(); @DefaultMessage("Twitter") @Description("") String twitterComponentPallette(); // Sensor @DefaultMessage("AccelerometerSensor") @Description("") String accelerometerSensorComponentPallette(); @DefaultMessage("BarcodeScanner") @Description("") String barcodeScannerComponentPallette(); @DefaultMessage("LocationSensor") @Description("") String locationSensorComponentPallette(); @DefaultMessage("NearField") @Description("") String nearFieldComponentPallette(); @DefaultMessage("OrientationSensor") @Description("") String orientationSensorComponentPallette(); // Screen Arrangement @DefaultMessage("HorizontalArrangement") @Description("") String horizontalArrangementComponentPallette(); @DefaultMessage("TableArrangement") @Description("") String tableArrangementComponentPallette(); @DefaultMessage("VerticalArrangement") @Description("") String verticalArrangementComponentPallette(); // Lego Mindstorms @DefaultMessage("NxtColorSensor") @Description("") String nxtColorSensorComponentPallette(); @DefaultMessage("NxtDirectCommands") @Description("") String nxtDirectCommandsComponentPallette(); @DefaultMessage("NxtDrive") @Description("") String nxtDriveComponentPallette(); @DefaultMessage("NxtLightSensor") @Description("") String nxtLightSensorComponentPallette(); @DefaultMessage("NxtSoundSensor") @Description("") String nxtSoundSensorComponentPallette(); @DefaultMessage("NxtTouchSensor") @Description("") String nxtTouchSensorComponentPallette(); @DefaultMessage("NxtUltrasonicSensor") @Description("") String nxtUltrasonicSensorComponentPallette(); // Storage @DefaultMessage("ActivityStarter") @Description("") String activityStarterComponentPallette(); @DefaultMessage("BluetoothClient") @Description("") String bluetoothClientComponentPallette(); @DefaultMessage("BluetoothServer") @Description("") String bluetoothServerComponentPallette(); @DefaultMessage("Notifier") @Description("") String notifierComponentPallette(); @DefaultMessage("SpeechRecognizer") @Description("") String speechRecognizerComponentPallette(); @DefaultMessage("TextToSpeech") @Description("") String textToSpeechComponentPallette(); @DefaultMessage("TinyWebDB") @Description("") String tinyWebDBComponentPallette(); @DefaultMessage("Web") @Description("") String webComponentPallette(); // Connectivity @DefaultMessage("File") @Description("") String fileComponentPallette(); @DefaultMessage("FusiontablesControl") @Description("") String fusiontablesControlComponentPallette(); @DefaultMessage("GameClient") @Description("") String gameClientComponentPallette(); @DefaultMessage("SoundRecorder") @Description("") String soundRecorderComponentPallette(); @DefaultMessage("Voting") @Description("") String votingComponentPallette(); @DefaultMessage("WebViewer") @Description("") String webViewerComponentPallette(); // Component Properties @DefaultMessage("AboutScreen") @Description("") String AboutScreenProperties(); @DefaultMessage("AboveRangeEventEnabled") @Description("") String AboveRangeEventEnabledProperties(); @DefaultMessage("Action") @Description("") String ActionProperties(); @DefaultMessage("ActivityClass") @Description("") String ActivityClassProperties(); @DefaultMessage("ActivityPackage") @Description("") String ActivityPackageProperties(); @DefaultMessage("AlignHorizontal") @Description("") String AlignHorizontalProperties(); @DefaultMessage("AlignVertical") @Description("") String AlignVerticalProperties(); @DefaultMessage("AllowCookies") @Description("") String AllowCookiesProperties(); @DefaultMessage("ApiKey") @Description("") String ApiKeyProperties(); @DefaultMessage("BackgroundColor") @Description("") String BackgroundColorProperties(); @DefaultMessage("BackgroundImage") @Description("") String BackgroundImageProperties(); @DefaultMessage("BelowRangeEventEnabled") @Description("") String BelowRangeEventEnabledProperties(); @DefaultMessage("BluetoothClient") @Description("") String BluetoothClientProperties(); @DefaultMessage("BottomOfRange") @Description("") String BottomOfRangeProperties(); @DefaultMessage("CalibrateStrideLength") @Description("") String CalibrateStrideLengthProperties(); @DefaultMessage("CharacterEncoding") @Description("") String CharacterEncodingProperties(); @DefaultMessage("Checked") @Description("") String CheckedProperties(); @DefaultMessage("CloseScreenAnimation") @Description("") String CloseScreenAnimationProperties(); @DefaultMessage("ColorChangedEventEnabled") @Description("") String ColorChangedEventEnabledProperties(); @DefaultMessage("Columns") @Description("") String ColumnsProperties(); @DefaultMessage("ConsumerKey") @Description("") String ConsumerKeyProperties(); @DefaultMessage("ConsumerSecret") @Description("") String ConsumerSecretProperties(); @DefaultMessage("Country") @Description("") String CountryProperties(); @DefaultMessage("DataType") @Description("") String DataTypeProperties(); @DefaultMessage("DataUri") @Description("") String DataUriProperties(); @DefaultMessage("DelimiterByte") @Description("") String DelimiterByteProperties(); @DefaultMessage("DetectColor") @Description("") String DetectColorProperties(); @DefaultMessage("DistanceInterval") @Description("") String DistanceIntervalProperties(); @DefaultMessage("DriveMotors") @Description("") String DriveMotorsProperties(); @DefaultMessage("Enabled") @Description("") String EnabledProperties(); @DefaultMessage("ExtraKey") @Description("") String ExtraKeyProperties(); @DefaultMessage("ExtraValue") @Description("") String ExtraValueProperties(); @DefaultMessage("FollowLinks") @Description("") String FollowLinksProperties(); @DefaultMessage("FontBold") @Description("") String FontBoldProperties(); @DefaultMessage("FontItalic") @Description("") String FontItalicProperties(); @DefaultMessage("FontSize") @Description("") String FontSizeProperties(); @DefaultMessage("FontTypeface") @Description("") String FontTypefaceProperties(); @DefaultMessage("GameId") @Description("") String GameIdProperties(); @DefaultMessage("GenerateColor") @Description("") String GenerateColorProperties(); @DefaultMessage("GenerateLight") @Description("") String GenerateLightProperties(); @DefaultMessage("GoogleVoiceEnabled") @Description("") String GoogleVoiceEnabledProperties(); @DefaultMessage("Heading") @Description("") String HeadingProperties(); @DefaultMessage("HighByteFirst") @Description("") String HighByteFirstProperties(); @DefaultMessage("Hint") @Description("") String HintProperties(); @DefaultMessage("HomeUrl") @Description("") String HomeUrlProperties(); @DefaultMessage("Icon") @Description("") String IconProperties(); @DefaultMessage("Image") @Description("") String ImageProperties(); @DefaultMessage("Interval") @Description("") String IntervalProperties(); @DefaultMessage("IsLooping") @Description("") String IsLoopingProperties(); @DefaultMessage("KeyFile") @Description("") String KeyFileProperties(); @DefaultMessage("Language") @Description("") String LanguageProperties(); @DefaultMessage("LineWidth") @Description("") String LineWidthProperties(); @DefaultMessage("Message") @Description("") String MessageProperties(); @DefaultMessage("MinimumInterval") @Description("") String MinimumIntervalProperties(); @DefaultMessage("MultiLine") @Description("") String MultiLineProperties(); @DefaultMessage("NumbersOnly") @Description("") String NumbersOnlyProperties(); @DefaultMessage("OpenScreenAnimation") @Description("") String OpenScreenAnimationProperties(); @DefaultMessage("PaintColor") @Description("") String PaintColorProperties(); @DefaultMessage("PhoneNumber") @Description("") String PhoneNumberProperties(); @DefaultMessage("PhoneNumberList") @Description("") String PhoneNumberListProperties(); @DefaultMessage("Picture") @Description("") String PictureProperties(); @DefaultMessage("PressedEventEnabled") @Description("") String PressedEventEnabledProperties(); @DefaultMessage("PromptforPermission") @Description("") String PromptforPermissionProperties(); @DefaultMessage("Query") @Description("") String QueryProperties(); @DefaultMessage("Radius") @Description("") String RadiusProperties(); @DefaultMessage("ReadMode") @Description("") String ReadModeProperties(); @DefaultMessage("ReceivingEnabled") @Description("") String ReceivingEnabledProperties(); @DefaultMessage("ReleasedEventEnabled") @Description("") String ReleasedEventEnabledProperties(); @DefaultMessage("ResponseFileName") @Description("") String ResponseFileNameProperties(); @DefaultMessage("ResultName") @Description("") String ResultNameProperties(); @DefaultMessage("Rows") @Description("") String RowsProperties(); @DefaultMessage("SaveResponse") @Description("") String SaveResponseProperties(); @DefaultMessage("ScalePictureToFit") @Description("") String ScalePictureToFitProperties(); @DefaultMessage("SensorPort") @Description("") String SensorPortProperties(); @DefaultMessage("ScreenOrientation") @Description("") String ScreenOrientationProperties(); @DefaultMessage("Secure") @Description("") String SecureProperties(); @DefaultMessage("ServiceAccountEmail") @Description("") String ServiceAccountEmailProperties(); @DefaultMessage("ServiceURL") @Description("") String ServiceURLProperties(); @DefaultMessage("Scrollable") @Description("") String ScrollableProperties(); @DefaultMessage("Shape") @Description("") String ShapeProperties(); @DefaultMessage("ShowFeedback") @Description("") String ShowFeedbackProperties(); @DefaultMessage("show tables") @Description("") String ShowTablesProperties(); @DefaultMessage("Source") @Description("") String SourceProperties(); @DefaultMessage("Speed") @Description("") String SpeedProperties(); @DefaultMessage("StopBeforeDisconnect") @Description("") String StopBeforeDisconnectProperties(); @DefaultMessage("StopDetectionTimeout") @Description("") String StopDetectionTimeoutProperties(); @DefaultMessage("StrideLength") @Description("") String StrideLengthProperties(); @DefaultMessage("Text") @Description("") String TextProperties(); @DefaultMessage("TextAlignment") @Description("") String TextAlignmentProperties(); @DefaultMessage("TextColor") @Description("") String TextColorProperties(); @DefaultMessage("TimerAlwaysFires") @Description("") String TimerAlwaysFiresProperties(); @DefaultMessage("TimerEnabled") @Description("") String TimerEnabledProperties(); @DefaultMessage("TimerInterval") @Description("") String TimerIntervalProperties(); @DefaultMessage("Title") @Description("") String TitleProperties(); @DefaultMessage("TopOfRange") @Description("") String TopOfRangeProperties(); @DefaultMessage("Url") @Description("") String UrlProperties(); @DefaultMessage("UseFront") @Description("") String UseFrontProperties(); @DefaultMessage("UseGPS") @Description("") String UseGPSProperties(); @DefaultMessage("UseServiceAuthentication") @Description("") String UseServiceAuthenticationProperties(); @DefaultMessage("UsesLocationVisible") @Description("") String UsesLocationVisibleProperties(); @DefaultMessage("VersionCode") @Description("") String VersionCodeProperties(); @DefaultMessage("VersionName") @Description("") String VersionNameProperties(); @DefaultMessage("Visible") @Description("") String VisibleProperties(); @DefaultMessage("Volume") @Description("") String VolumeProperties(); @DefaultMessage("WheelDiameter") @Description("") String WheelDiameterProperties(); @DefaultMessage("WithinRangeEventEnabled") @Description("") String WithinRangeEventEnabledProperties(); @DefaultMessage("X") @Description("") String XProperties(); @DefaultMessage("Y") @Description("") String YProperties(); @DefaultMessage("Z") @Description("") String ZProperties(); @DefaultMessage("showing") @Description("") String VisibilityShowingProperties(); @DefaultMessage("hidden") @Description("") String VisibilityHiddenProperties(); @DefaultMessage("ElementsFromString") @Description("") String ElementsFromStringProperties(); @DefaultMessage("Rotates") @Description("") String RotatesProperties(); @DefaultMessage("Selection") @Description("") String SelectionProperties(); @DefaultMessage("TimeInterval") @Description("") String TimeIntervalProperties(); @DefaultMessage("UsesLocation") @Description("") String UsesLocationProperties(); @DefaultMessage("ShowFilterBar") @Description("") String ShowFilterBarProperties(); @DefaultMessage("NotifierLength") @Description("") String NotifierLengthProperties(); @DefaultMessage("Loop") @Description("") String LoopProperties(); @DefaultMessage("Pitch") @Description("") String PitchProperties(); @DefaultMessage("SpeechRate") @Description("") String SpeechRateProperties(); @DefaultMessage("Sensitivity") @Description("") String SensitivityProperties(); @DefaultMessage("TwitPic_API_Key") @Description("") String TwitPic_API_KeyProperties(); @DefaultMessage("Prompt") @Description("") String PromptProperties(); @DefaultMessage("ColorLeft") @Description("") String ColorLeftProperties(); @DefaultMessage("ColorRight") @Description("") String ColorRightProperties(); @DefaultMessage("MaxValue") @Description("") String MaxValueProperties(); @DefaultMessage("MinValue") @Description("") String MinValueProperties(); @DefaultMessage("ThumbPosition") @Description("") String ThumbPositionProperties(); @DefaultMessage("Day") @Description("") String DayProperties(); @DefaultMessage("Month") @Description("") String MonthProperties(); @DefaultMessage("MonthInText") @Description("") String MonthInTextProperties(); @DefaultMessage("Year") @Description("") String YearProperties(); @DefaultMessage("LastMessage") @Description("") String LastMessageProperties(); @DefaultMessage("TextToWrite") @Description("") String TextToWriteProperties(); @DefaultMessage("WriteType") @Description("") String WriteTypeProperties(); @DefaultMessage("ElapsedTime") @Description("") String ElapsedTimeProperties(); @DefaultMessage("Moving") @Description("") String MovingProperties(); @DefaultMessage("Hour") @Description("") String HourProperties(); @DefaultMessage("Minute") @Description("") String MinuteProperties(); @DefaultMessage("Distance") @Description("") String DistanceProperties(); @DefaultMessage("DirectMessages") @Description("") String DirectMessagesProperties(); @DefaultMessage("ContactName") @Description("") String ContactNameProperties(); @DefaultMessage("CurrentAddress") @Description("") String CurrentAddressProperties(); @DefaultMessage("CurrentPageTitle") @Description("") String CurrentPageTitleProperties(); @DefaultMessage("CurrentUrl") @Description("") String CurrentUrlProperties(); @DefaultMessage("Accuracy") @Description("") String AccuracyProperties(); @DefaultMessage("AddressesAndNames") @Description("") String AddressesAndNamesProperties(); @DefaultMessage("Altitude") @Description("") String AltitudeProperties(); @DefaultMessage("Angle") @Description("") String AngleProperties(); @DefaultMessage("Animation") @Description("") String AnimationProperties(); @DefaultMessage("Available") @Description("") String AvailableProperties(); @DefaultMessage("AvailableProviders") @Description("") String AvailableProvidersProperties(); @DefaultMessage("Azimuth") @Description("") String AzimuthProperties(); @DefaultMessage("BallotOptions") @Description("") String BallotOptionsProperties(); @DefaultMessage("BallotQuestion") @Description("") String BallotQuestionProperties(); @DefaultMessage("EmailAddress") @Description("") String EmailAddressProperties(); @DefaultMessage("EmailAddressList") @Description("") String EmailAddressListProperties(); @DefaultMessage("Elements") @Description("") String ElementsProperties(); @DefaultMessage("Followers") @Description("") String FollowersProperties(); @DefaultMessage("FriendTimeline") @Description("") String FriendTimelineProperties(); @DefaultMessage("FullScreen") @Description("") String FullScreenProperties(); @DefaultMessage("HasAccuracy") @Description("") String HasAccuracyProperties(); @DefaultMessage("HasAltitude") @Description("") String HasAltitudeProperties(); @DefaultMessage("HasLongitudeLatitude") @Description("") String HasLongitudeLatitudeProperties(); @DefaultMessage("Height") @Description("") String HeightProperties(); @DefaultMessage("InstanceId") @Description("") String InstanceIdProperties(); @DefaultMessage("InvitedInstances") @Description("") String InvitedInstancesProperties(); @DefaultMessage("IsAccepting") @Description("") String IsAcceptingProperties(); @DefaultMessage("IsConnected") @Description("") String IsConnectedProperties(); @DefaultMessage("IsPlaying") @Description("") String IsPlayingProperties(); @DefaultMessage("JoinedInstances") @Description("") String JoinedInstancesProperties(); @DefaultMessage("Latitude") @Description("") String LatitudeProperties(); @DefaultMessage("Leader") @Description("") String LeaderProperties(); @DefaultMessage("Longitude") @Description("") String LongitudeProperties(); @DefaultMessage("Magnitude") @Description("") String MagnitudeProperties(); @DefaultMessage("Mentions") @Description("") String MentionsProperties(); @DefaultMessage("ProviderLocked") @Description("") String ProviderLockedProperties(); @DefaultMessage("ProviderName") @Description("") String ProviderNameProperties(); @DefaultMessage("PublicInstances") @Description("") String PublicInstancesProperties(); @DefaultMessage("PlayOnlyInForeground") @Description("") String PlayOnlyInForegroundProperties(); @DefaultMessage("Players") @Description("") String PlayersProperties(); @DefaultMessage("RequestHeaders") @Description("") String RequestHeadersProperties(); @DefaultMessage("Result") @Description("") String ResultProperties(); @DefaultMessage("ResultType") @Description("") String ResultTypeProperties(); @DefaultMessage("ResultUri") @Description("") String ResultUriProperties(); @DefaultMessage("Roll") @Description("") String RollProperties(); @DefaultMessage("SearchResults") @Description("") String SearchResultsProperties(); @DefaultMessage("ServiceUrl") @Description("") String ServiceUrlProperties(); @DefaultMessage("SelectionIndex") @Description("") String SelectionIndexProperties(); @DefaultMessage("UserChoice") @Description("") String UserChoiceProperties(); @DefaultMessage("UserEmailAddress") @Description("") String UserEmailAddressProperties(); @DefaultMessage("UserId") @Description("") String UserIdProperties(); @DefaultMessage("Username") @Description("") String UsernameProperties(); @DefaultMessage("XAccel") @Description("") String XAccelProperties(); @DefaultMessage("YAccel") @Description("") String YAccelProperties(); @DefaultMessage("ZAccel") @Description("") String ZAccelProperties(); @DefaultMessage("Width") @Description("") String WidthProperties(); @DefaultMessage("WebViewString") @Description("") String WebViewStringProperties(); //Params @DefaultMessage("xAccel") @Description("") String xAccelParams(); @DefaultMessage("yAccel") @Description("") String yAccelParams(); @DefaultMessage("zAccel") @Description("") String zAccelParams(); @DefaultMessage("result") @Description("") String resultParams(); @DefaultMessage("other") @Description("") String otherParams(); @DefaultMessage("component") @Description("") String componentParams(); @DefaultMessage("startX") @Description("") String startXParams(); @DefaultMessage("startY") @Description("") String startYParams(); @DefaultMessage("prevX") @Description("") String prevXParams(); @DefaultMessage("prevY") @Description("") String prevYParams(); @DefaultMessage("currentX") @Description("") String currentXParams(); @DefaultMessage("currentY") @Description("") String currentYParams(); @DefaultMessage("edge") @Description("") String edgeParams(); @DefaultMessage("speed") @Description("") String speedParams(); @DefaultMessage("heading") @Description("") String headingParams(); @DefaultMessage("xvel") @Description("") String xvelParams(); @DefaultMessage("yvel") @Description("") String yvelParams(); @DefaultMessage("target") @Description("") String targetParams(); @DefaultMessage("address") @Description("") String addressParams(); @DefaultMessage("uuid") @Description("") String uuidParams(); @DefaultMessage("numberOfBytes") @Description("") String numberOfBytesParams(); @DefaultMessage("number") @Description("") String numberParams(); @DefaultMessage("list") @Description("") String listParams(); @DefaultMessage("text") @Description("") String textParams(); @DefaultMessage("clip") @Description("") String clipParams(); @DefaultMessage("image") @Description("") String imageParams(); @DefaultMessage("draggedSprite") @Description("") String draggedSpriteParams(); @DefaultMessage("flungSprite") @Description("") String flungSpriteParams(); @DefaultMessage("touchedSprite") @Description("") String touchedSpriteParams(); @DefaultMessage("x") @Description("") String xParams(); @DefaultMessage("y") @Description("") String yParams(); @DefaultMessage("r") @Description("") String rParams(); @DefaultMessage("x1") @Description("") String x1Params(); @DefaultMessage("x2") @Description("") String x2Params(); @DefaultMessage("y1") @Description("") String y1Params(); @DefaultMessage("y2") @Description("") String y2Params(); @DefaultMessage("angle") @Description("") String angleParams(); @DefaultMessage("fileName") @Description("") String fileNameParams(); @DefaultMessage("color") @Description("") String colorParams(); @DefaultMessage("instant") @Description("") String instantParams(); @DefaultMessage("days") @Description("") String daysParams(); @DefaultMessage("hours") @Description("") String hoursParams(); @DefaultMessage("minutes") @Description("") String minutesParams(); @DefaultMessage("months") @Description("") String monthsParams(); @DefaultMessage("seconds") @Description("") String secondsParams(); @DefaultMessage("weeks") @Description("") String weeksParams(); @DefaultMessage("years") @Description("") String yearsParams(); @DefaultMessage("InstantInTime") @Description("") String InstantInTimeParams(); @DefaultMessage("from") @Description("") String fromParams(); @DefaultMessage("millis") @Description("") String millisParams(); @DefaultMessage("functionName") @Description("") String functionNameParams(); @DefaultMessage("errorNumber") @Description("") String errorNumberParams(); @DefaultMessage("message") @Description("") String messageParams(); @DefaultMessage("otherScreenName") @Description("") String otherScreenNameParams(); @DefaultMessage("animType") @Description("") String animTypeParams(); @DefaultMessage("sender") @Description("") String senderParams(); @DefaultMessage("contents") @Description("") String contentsParams(); @DefaultMessage("instanceId") @Description("") String instanceIdParams(); @DefaultMessage("playerId") @Description("") String playerIdParams(); @DefaultMessage("command") @Description("") String commandParams(); @DefaultMessage("arguments") @Description("") String argumentsParams(); @DefaultMessage("response") @Description("") String responseParams(); @DefaultMessage("emailAddress") @Description("") String emailAddressParams(); @DefaultMessage("type") @Description("") String typeParams(); @DefaultMessage("count") @Description("") String countParams(); @DefaultMessage("makePublic") @Description("") String makePublicParams(); @DefaultMessage("recipients") @Description("") String recipientsParams(); @DefaultMessage("playerEmail") @Description("") String playerEmailParams(); @DefaultMessage("latitude") @Description("") String latitudeParams(); @DefaultMessage("longitude") @Description("") String longitudeParams(); @DefaultMessage("altitude") @Description("") String altitudeParams(); @DefaultMessage("provider") @Description("") String providerParams(); @DefaultMessage("status") @Description("") String statusParams(); @DefaultMessage("locationName") @Description("") String locationNameParams(); @DefaultMessage("choice") @Description("") String choiceParams(); @DefaultMessage("notice") @Description("") String noticeParams(); @DefaultMessage("title") @Description("") String titleParams(); @DefaultMessage("buttonText") @Description("") String buttonTextParams(); @DefaultMessage("cancelable") @Description("") String cancelableParams(); @DefaultMessage("button1Text") @Description("") String button1TextParams(); @DefaultMessage("button2Text") @Description("") String button2TextParams(); @DefaultMessage("source") @Description("") String sourceParams(); @DefaultMessage("destination") @Description("") String destinationParams(); @DefaultMessage("sensorPortLetter") @Description("") String sensorPortLetterParams(); @DefaultMessage("rxDataLength") @Description("") String rxDataLengthParams(); @DefaultMessage("wildcard") @Description("") String wildcardParams(); @DefaultMessage("motorPortLetter") @Description("") String motorPortLetterParams(); @DefaultMessage("mailbox") @Description("") String mailboxParams(); @DefaultMessage("durationMs") @Description("") String durationMsParams(); @DefaultMessage("relative") @Description("") String relativeParams(); @DefaultMessage("sensorType") @Description("") String sensorTypeParams(); @DefaultMessage("sensorMode") @Description("") String sensorModeParams(); @DefaultMessage("power") @Description("") String powerParams(); @DefaultMessage("mode") @Description("") String modeParams(); @DefaultMessage("regulationMode") @Description("") String regulationModeParams(); @DefaultMessage("turnRatio") @Description("") String turnRatioParams(); @DefaultMessage("runState") @Description("") String runStateParams(); @DefaultMessage("tachoLimit") @Description("") String tachoLimitParams(); @DefaultMessage("programName") @Description("") String programNameParams(); @DefaultMessage("distance") @Description("") String distanceParams(); @DefaultMessage("azimuth") @Description("") String azimuthParams(); @DefaultMessage("pitch") @Description("") String pitchParams(); @DefaultMessage("roll") @Description("") String rollParams(); @DefaultMessage("simpleSteps") @Description("") String simpleStepsParams(); @DefaultMessage("walkSteps") @Description("") String walkStepsParams(); @DefaultMessage("seed") @Description("") String seedParams(); @DefaultMessage("millisecs") @Description("") String millisecsParams(); @DefaultMessage("sound") @Description("") String soundParams(); @DefaultMessage("messageText") @Description("") String messageTextParams(); @DefaultMessage("tag") @Description("") String tagParams(); @DefaultMessage("valueToStore") @Description("") String valueToStoreParams(); @DefaultMessage("tagFromWebDB") @Description("") String tagFromWebDBParams(); @DefaultMessage("valueFromWebDB") @Description("") String valueFromWebDBParams(); @DefaultMessage("followers2") @Description("") String followers2Params(); @DefaultMessage("timeline") @Description("") String timelineParams(); @DefaultMessage("mentions") @Description("") String mentionsParams(); @DefaultMessage("searchResults") @Description("") String searchResultsParams(); @DefaultMessage("user") @Description("") String userParams(); @DefaultMessage("url") @Description("") String urlParams(); @DefaultMessage("responseCode") @Description("") String responseCodeParams(); @DefaultMessage("responseType") @Description("") String responseTypeParams(); @DefaultMessage("responseContent") @Description("") String responseContentParams(); @DefaultMessage("htmlText") @Description("") String htmlTextParams(); @DefaultMessage("jsonText") @Description("") String jsonTextParams(); @DefaultMessage("path") @Description("") String pathParams(); @DefaultMessage("encoding") @Description("") String encodingParams(); @DefaultMessage("name") @Description("") String nameParams(); @DefaultMessage("serviceName") @Description("") String serviceNameParams(); @DefaultMessage("milliseconds") @Description("") String millisecondsParams(); @DefaultMessage("messages") @Description("") String messagesParams(); @DefaultMessage("start") @Description("") String startParams(); @DefaultMessage("end") @Description("") String endParams(); @DefaultMessage("frequencyHz") @Description("") String frequencyHzParams(); @DefaultMessage("secure") @Description("") String secureParams(); @DefaultMessage("file") @Description("") String fileParams(); @DefaultMessage("thumbPosition") @Description("") String thumbPositionParams(); @DefaultMessage("selection") @Description("") String selectionParams(); @DefaultMessage("valueIfTagNotThere") @Description("") String valueIfTagNotThereParams(); @DefaultMessage("query") @Description("") String queryParams(); @DefaultMessage("ImagePath") @Description("") String ImagePathParams(); @DefaultMessage("ms") @Description("") String msParams(); @DefaultMessage("translation") @Description("") String translationParams(); @DefaultMessage("languageToTranslateTo") @Description("") String languageToTranslateToParams(); @DefaultMessage("textToTranslate") @Description("") String textToTranslateParams(); //Events @DefaultMessage("AccelerationChanged") @Description("") String AccelerationChangedEvents(); @DefaultMessage("AfterActivity") @Description("") String AfterActivityEvents(); @DefaultMessage("CollidedWith") @Description("") String CollidedWithEvents(); @DefaultMessage("Dragged") @Description("") String DraggedEvents(); @DefaultMessage("EdgeReached") @Description("") String EdgeReachedEvents(); @DefaultMessage("Flung") @Description("") String FlungEvents(); @DefaultMessage("NoLongerCollidingWith") @Description("") String NoLongerCollidingWithEvents(); @DefaultMessage("TouchDown") @Description("") String TouchDownEvents(); @DefaultMessage("TouchUp") @Description("") String TouchUpEvents(); @DefaultMessage("Touched") @Description("") String TouchedEvents(); @DefaultMessage("AfterScan") @Description("") String AfterScanEvents(); @DefaultMessage("ConnectionAccepted") @Description("") String ConnectionAcceptedEvents(); @DefaultMessage("Click") @Description("") String ClickEvents(); @DefaultMessage("GotFocus") @Description("") String GotFocusEvents(); @DefaultMessage("LongClick") @Description("") String LongClickEvents(); @DefaultMessage("LostFocus") @Description("") String LostFocusEvents(); @DefaultMessage("AfterRecording") @Description("") String AfterRecordingEvents(); @DefaultMessage("AfterPicture") @Description("") String AfterPictureEvents(); @DefaultMessage("Changed") @Description("") String ChangedEvents(); @DefaultMessage("Timer") @Description("") String TimerEvents(); @DefaultMessage("AfterPicking") @Description("") String AfterPickingEvents(); @DefaultMessage("BeforePicking") @Description("") String BeforePickingEvents(); @DefaultMessage("BackPressed") @Description("") String BackPressedEvents(); @DefaultMessage("ErrorOccurred") @Description("") String ErrorOccurredEvents(); @DefaultMessage("Initialize") @Description("") String InitializeEvents(); @DefaultMessage("OtherScreenClosed") @Description("") String OtherScreenClosedEvents(); @DefaultMessage("ScreenOrientationChanged") @Description("") String ScreenOrientationChangedEvents(); @DefaultMessage("GotResult") @Description("") String GotResultEvents(); @DefaultMessage("FunctionCompleted") @Description("") String FunctionCompletedEvents(); @DefaultMessage("GotMessage") @Description("") String GotMessageEvents(); @DefaultMessage("Info") @Description("") String InfoEvents(); @DefaultMessage("InstanceIdChanged") @Description("") String InstanceIdChangedEvents(); @DefaultMessage("Invited") @Description("") String InvitedEvents(); @DefaultMessage("NewInstanceMade") @Description("") String NewInstanceMadeEvents(); @DefaultMessage("NewLeader") @Description("") String NewLeaderEvents(); @DefaultMessage("PlayerJoined") @Description("") String PlayerJoinedEvents(); @DefaultMessage("PlayerLeft") @Description("") String PlayerLeftEvents(); @DefaultMessage("ServerCommandFailure") @Description("") String ServerCommandFailureEvents(); @DefaultMessage("ServerCommandSuccess") @Description("") String ServerCommandSuccessEvents(); @DefaultMessage("UserEmailAddressSet") @Description("") String UserEmailAddressSetEvents(); @DefaultMessage("WebServiceError") @Description("") String WebServiceErrorEvents(); @DefaultMessage("LocationChanged") @Description("") String LocationChangedEvents(); @DefaultMessage("StatusChanged") @Description("") String StatusChangedEvents(); @DefaultMessage("AfterChoosing") @Description("") String AfterChoosingEvents(); @DefaultMessage("AfterTextInput") @Description("") String AfterTextInputEvents(); @DefaultMessage("AboveRange") @Description("") String AboveRangeEvents(); @DefaultMessage("BelowRange") @Description("") String BelowRangeEvents(); @DefaultMessage("ColorChanged") @Description("") String ColorChangedEvents(); @DefaultMessage("WithinRange") @Description("") String WithinRangeEvents(); @DefaultMessage("Pressed") @Description("") String PressedEvents(); @DefaultMessage("Released") @Description("") String ReleasedEvents(); @DefaultMessage("OrientationChanged") @Description("") String OrientationChangedEvents(); @DefaultMessage("CalibrationFailed") @Description("") String CalibrationFailedEvents(); @DefaultMessage("GPSAvailable") @Description("") String GPSAvailableEvents(); @DefaultMessage("GPSLost") @Description("") String GPSLostEvents(); @DefaultMessage("SimpleStep") @Description("") String SimpleStepEvents(); @DefaultMessage("StartedMoving") @Description("") String StartedMovingEvents(); @DefaultMessage("StoppedMoving") @Description("") String StoppedMovingEvents(); @DefaultMessage("WalkStep") @Description("") String WalkStepEvents(); @DefaultMessage("Completed") @Description("") String CompletedEvents(); @DefaultMessage("AfterSoundRecorded") @Description("") String AfterSoundRecordedEvents(); @DefaultMessage("StartedRecording") @Description("") String StartedRecordingEvents(); @DefaultMessage("StoppedRecording") @Description("") String StoppedRecordingEvents(); @DefaultMessage("AfterGettingText") @Description("") String AfterGettingTextEvents(); @DefaultMessage("BeforeGettingText") @Description("") String BeforeGettingTextEvents(); @DefaultMessage("AfterSpeaking") @Description("") String AfterSpeakingEvents(); @DefaultMessage("BeforeSpeaking") @Description("") String BeforeSpeakingEvents(); @DefaultMessage("MessageReceived") @Description("") String MessageReceivedEvents(); @DefaultMessage("SendMessage") @Description("") String SendMessageEvents(); @DefaultMessage("GotValue") @Description("") String GotValueEvents(); @DefaultMessage("ValueStored") @Description("") String ValueStoredEvents(); @DefaultMessage("DirectMessagesReceived") @Description("") String DirectMessagesReceivedEvents(); @DefaultMessage("FollowersReceived") @Description("") String FollowersReceivedEvents(); @DefaultMessage("FriendTimelineReceived") @Description("") String FriendTimelineReceivedEvents(); @DefaultMessage("IsAuthorized") @Description("") String IsAuthorizedEvents(); @DefaultMessage("MentionsReceived") @Description("") String MentionsReceivedEvents(); @DefaultMessage("SearchSuccessful") @Description("") String SearchSuccessfulEvents(); @DefaultMessage("GotBallot") @Description("") String GotBallotEvents(); @DefaultMessage("GotBallotConfirmation") @Description("") String GotBallotConfirmationEvents(); @DefaultMessage("NoOpenPoll") @Description("") String NoOpenPollEvents(); @DefaultMessage("GotFile") @Description("") String GotFileEvents(); @DefaultMessage("GotText") @Description("") String GotTextEvents(); @DefaultMessage("AfterDateSet") @Description("") String AfterDateSetEvents(); @DefaultMessage("TagRead") @Description("") String TagReadEvents(); @DefaultMessage("TagWritten") @Description("") String TagWrittenEvents(); @DefaultMessage("PositionChanged") @Description("") String PositionChangedEvents(); @DefaultMessage("AfterSelecting") @Description("") String AfterSelectingEvents(); @DefaultMessage("AfterTimeSet") @Description("") String AfterTimeSetEvents(); @DefaultMessage("GotTranslation") @Description("") String GotTranslationEvents(); @DefaultMessage("Shaking") @Description("") String ShakingEvents(); //Methods @DefaultMessage("ResolveActivity") @Description("") String ResolveActivityMethods(); @DefaultMessage("StartActivity") @Description("") String StartActivityMethods(); @DefaultMessage("Connect") @Description("") String ConnectMethods(); @DefaultMessage("ConnectWithUUID") @Description("") String ConnectWithUUIDMethods(); @DefaultMessage("Disconnect") @Description("") String DisconnectMethods(); @DefaultMessage("IsDevicePaired") @Description("") String IsDevicePairedMethods(); @DefaultMessage("ReceiveSigned1ByteNumber") @Description("") String ReceiveSigned1ByteNumberMethods(); @DefaultMessage("ReceiveSigned2ByteNumber") @Description("") String ReceiveSigned2ByteNumberMethods(); @DefaultMessage("ReceiveSigned4ByteNumber") @Description("") String ReceiveSigned4ByteNumberMethods(); @DefaultMessage("ReceiveSignedBytes") @Description("") String ReceiveSignedBytesMethods(); @DefaultMessage("ReceiveText") @Description("") String ReceiveTextMethods(); @DefaultMessage("ReceiveUnsigned1ByteNumber") @Description("") String ReceiveUnsigned1ByteNumberMethods(); @DefaultMessage("ReceiveUnsigned2ByteNumber") @Description("") String ReceiveUnsigned2ByteNumberMethods(); @DefaultMessage("ReceiveUnsigned4ByteNumber") @Description("") String ReceiveUnsigned4ByteNumberMethods(); @DefaultMessage("ReceiveUnsignedBytes") @Description("") String ReceiveUnsignedBytesMethods(); @DefaultMessage("Send1ByteNumber") @Description("") String Send1ByteNumberMethods(); @DefaultMessage("Send2ByteNumber") @Description("") String Send2ByteNumberMethods(); @DefaultMessage("Send4ByteNumber") @Description("") String Send4ByteNumberMethods(); @DefaultMessage("SendBytes") @Description("") String SendBytesMethods(); @DefaultMessage("SendText") @Description("") String SendTextMethods(); @DefaultMessage("AcceptConnection") @Description("") String AcceptConnectionMethods(); @DefaultMessage("AcceptConnectionWithUUID") @Description("") String AcceptConnectionWithUUIDMethods(); @DefaultMessage("BytesAvailableToReceive") @Description("") String BytesAvailableToReceiveMethods(); @DefaultMessage("StopAccepting") @Description("") String StopAcceptingMethods(); @DefaultMessage("RecordVideo") @Description("") String RecordVideoMethods(); @DefaultMessage("TakePicture") @Description("") String TakePictureMethods(); @DefaultMessage("Clear") @Description("") String ClearMethods(); @DefaultMessage("DrawCircle") @Description("") String DrawCircleMethods(); @DefaultMessage("DrawLine") @Description("") String DrawLineMethods(); @DefaultMessage("DrawPoint") @Description("") String DrawPointMethods(); @DefaultMessage("DrawText") @Description("") String DrawTextMethods(); @DefaultMessage("DrawTextAtAngle") @Description("") String DrawTextAtAngleMethods(); @DefaultMessage("GetBackgroundPixelColor") @Description("") String GetBackgroundPixelColorMethods(); @DefaultMessage("GetPixelColor") @Description("") String GetPixelColorMethods(); @DefaultMessage("Save") @Description("") String SaveMethods(); @DefaultMessage("SaveAs") @Description("") String SaveAsMethods(); @DefaultMessage("SetBackgroundPixelColor") @Description("") String SetBackgroundPixelColorMethods(); @DefaultMessage("AddDays") @Description("") String AddDaysMethods(); @DefaultMessage("AddHours") @Description("") String AddHoursMethods(); @DefaultMessage("AddMinutes") @Description("") String AddMinutesMethods(); @DefaultMessage("AddMonths") @Description("") String AddMonthsMethods(); @DefaultMessage("AddSeconds") @Description("") String AddSecondsMethods(); @DefaultMessage("AddWeeks") @Description("") String AddWeeksMethods(); @DefaultMessage("AddYears") @Description("") String AddYearsMethods(); @DefaultMessage("DayOfMonth") @Description("") String DayOfMonthMethods(); @DefaultMessage("Duration") @Description("") String DurationMethods(); @DefaultMessage("FormatDate") @Description("") String FormatDateMethods(); @DefaultMessage("FormatDateTime") @Description("") String FormatDateTimeMethods(); @DefaultMessage("FormatTime") @Description("") String FormatTimeMethods(); @DefaultMessage("GetMillis") @Description("") String GetMillisMethods(); @DefaultMessage("Hour") @Description("") String HourMethods(); @DefaultMessage("MakeInstant") @Description("") String MakeInstantMethods(); @DefaultMessage("MakeInstantFromMillis") @Description("") String MakeInstantFromMillisMethods(); @DefaultMessage("Minute") @Description("") String MinuteMethods(); @DefaultMessage("Month") @Description("") String MonthMethods(); @DefaultMessage("MonthName") @Description("") String MonthNameMethods(); @DefaultMessage("Now") @Description("") String NowMethods(); @DefaultMessage("Second") @Description("") String SecondMethods(); @DefaultMessage("SystemTime") @Description("") String SystemTimeMethods(); @DefaultMessage("Weekday") @Description("") String WeekdayMethods(); @DefaultMessage("WeekdayName") @Description("") String WeekdayNameMethods(); @DefaultMessage("Year") @Description("") String YearMethods(); @DefaultMessage("Open") @Description("") String OpenMethods(); @DefaultMessage("CloseScreenAnimation") @Description("") String CloseScreenAnimationMethods(); @DefaultMessage("OpenScreenAnimation") @Description("") String OpenScreenAnimationMethods(); @DefaultMessage("DoQuery") @Description("") String DoQueryMethods(); @DefaultMessage("ForgetLogin") @Description("") String ForgetLoginMethods(); @DefaultMessage("SendQuery") @Description("") String SendQueryMethods(); @DefaultMessage("GetInstanceLists") @Description("") String GetInstanceListsMethods(); @DefaultMessage("GetMessages") @Description("") String GetMessagesMethods(); @DefaultMessage("Invite") @Description("") String InviteMethods(); @DefaultMessage("LeaveInstance") @Description("") String LeaveInstanceMethods(); @DefaultMessage("MakeNewInstance") @Description("") String MakeNewInstanceMethods(); @DefaultMessage("ServerCommand") @Description("") String ServerCommandMethods(); @DefaultMessage("SetInstance") @Description("") String SetInstanceMethods(); @DefaultMessage("SetLeader") @Description("") String SetLeaderMethods(); @DefaultMessage("Bounce") @Description("") String BounceMethods(); @DefaultMessage("CollidingWith") @Description("") String CollidingWithMethods(); @DefaultMessage("MoveIntoBounds") @Description("") String MoveIntoBoundsMethods(); @DefaultMessage("MoveTo") @Description("") String MoveToMethods(); @DefaultMessage("PointInDirection") @Description("") String PointInDirectionMethods(); @DefaultMessage("PointTowards") @Description("") String PointTowardsMethods(); @DefaultMessage("LatitudeFromAddress") @Description("") String LatitudeFromAddressMethods(); @DefaultMessage("LongitudeFromAddress") @Description("") String LongitudeFromAddressMethods(); @DefaultMessage("LogError") @Description("") String LogErrorMethods(); @DefaultMessage("LogInfo") @Description("") String LogInfoMethods(); @DefaultMessage("LogWarning") @Description("") String LogWarningMethods(); @DefaultMessage("ShowAlert") @Description("") String ShowAlertMethods(); @DefaultMessage("ShowChooseDialog") @Description("") String ShowChooseDialogMethods(); @DefaultMessage("ShowMessageDialog") @Description("") String ShowMessageDialogMethods(); @DefaultMessage("ShowTextDialog") @Description("") String ShowTextDialogMethods(); @DefaultMessage("GetColor") @Description("") String GetColorMethods(); @DefaultMessage("GetLightLevel") @Description("") String GetLightLevelMethods(); @DefaultMessage("DeleteFile") @Description("") String DeleteFileMethods(); @DefaultMessage("DownloadFile") @Description("") String DownloadFileMethods(); @DefaultMessage("GetBatteryLevel") @Description("") String GetBatteryLevelMethods(); @DefaultMessage("GetBrickName") @Description("") String GetBrickNameMethods(); @DefaultMessage("GetCurrentProgramName") @Description("") String GetCurrentProgramNameMethods(); @DefaultMessage("GetFirmwareVersion") @Description("") String GetFirmwareVersionMethods(); @DefaultMessage("GetInputValues") @Description("") String GetInputValuesMethods(); @DefaultMessage("GetOutputState") @Description("") String GetOutputStateMethods(); @DefaultMessage("KeepAlive") @Description("") String KeepAliveMethods(); @DefaultMessage("ListFiles") @Description("") String ListFilesMethods(); @DefaultMessage("LsGetStatus") @Description("") String LsGetStatusMethods(); @DefaultMessage("LsRead") @Description("") String LsReadMethods(); @DefaultMessage("MessageRead") @Description("") String MessageReadMethods(); @DefaultMessage("MessageWrite") @Description("") String MessageWriteMethods(); @DefaultMessage("PlaySoundFile") @Description("") String PlaySoundFileMethods(); @DefaultMessage("PlayTone") @Description("") String PlayToneMethods(); @DefaultMessage("ResetInputScaledValue") @Description("") String ResetInputScaledValueMethods(); @DefaultMessage("ResetMotorPosition") @Description("") String ResetMotorPositionMethods(); @DefaultMessage("SetBrickName") @Description("") String SetBrickNameMethods(); @DefaultMessage("SetInputMode") @Description("") String SetInputModeMethods(); @DefaultMessage("SetOutputState") @Description("") String SetOutputStateMethods(); @DefaultMessage("StartProgram") @Description("") String StartProgramMethods(); @DefaultMessage("StopProgram") @Description("") String StopProgramMethods(); @DefaultMessage("StopSoundPlayback") @Description("") String StopSoundPlaybackMethods(); @DefaultMessage("LsWrite") @Description("") String LsWriteMethods(); @DefaultMessage("MoveBackward") @Description("") String MoveBackwardMethods(); @DefaultMessage("MoveBackwardIndefinitely") @Description("") String MoveBackwardIndefinitelyMethods(); @DefaultMessage("MoveForward") @Description("") String MoveForwardMethods(); @DefaultMessage("MoveForwardIndefinitely") @Description("") String MoveForwardIndefinitelyMethods(); @DefaultMessage("Stop") @Description("") String StopMethods(); @DefaultMessage("TurnClockwiseIndefinitely") @Description("") String TurnClockwiseIndefinitelyMethods(); @DefaultMessage("TurnCounterClockwiseIndefinitely") @Description("") String TurnCounterClockwiseIndefinitelyMethods(); @DefaultMessage("GetSoundLevel") @Description("") String GetSoundLevelMethods(); @DefaultMessage("IsPressed") @Description("") String IsPressedMethods(); @DefaultMessage("GetDistance") @Description("") String GetDistanceMethods(); @DefaultMessage("Pause") @Description("") String PauseMethods(); @DefaultMessage("Reset") @Description("") String ResetMethods(); @DefaultMessage("Resume") @Description("") String ResumeMethods(); @DefaultMessage("Start") @Description("") String StartMethods(); @DefaultMessage("MakePhoneCall") @Description("") String MakePhoneCallMethods(); @DefaultMessage("GetWifiIpAddress") @Description("") String GetWifiIpAddressMethods(); @DefaultMessage("isConnected") @Description("") String isConnectedMethods(); @DefaultMessage("setHmacSeedReturnCode") @Description("") String setHmacSeedReturnCodeMethods(); @DefaultMessage("startHTTPD") @Description("") String startHTTPDMethods(); @DefaultMessage("Vibrate") @Description("") String VibrateMethods(); @DefaultMessage("GetText") @Description("") String GetTextMethods(); @DefaultMessage("HideKeyboard") @Description("") String HideKeyboardMethods(); @DefaultMessage("Speak") @Description("") String SpeakMethods(); @DefaultMessage("SendMessage") @Description("") String SendMessageMethods(); @DefaultMessage("GetValue") @Description("") String GetValueMethods(); @DefaultMessage("StoreValue") @Description("") String StoreValueMethods(); @DefaultMessage("Authorize") @Description("") String AuthorizeMethods(); @DefaultMessage("CheckAuthorized") @Description("") String CheckAuthorizedMethods(); @DefaultMessage("DeAuthorize") @Description("") String DeAuthorizeMethods(); @DefaultMessage("DirectMessage") @Description("") String DirectMessageMethods(); @DefaultMessage("Follow") @Description("") String FollowMethods(); @DefaultMessage("RequestDirectMessages") @Description("") String RequestDirectMessagesMethods(); @DefaultMessage("RequestFollowers") @Description("") String RequestFollowersMethods(); @DefaultMessage("RequestFriendTimeline") @Description("") String RequestFriendTimelineMethods(); @DefaultMessage("RequestMentions") @Description("") String RequestMentionsMethods(); @DefaultMessage("SearchTwitter") @Description("") String SearchTwitterMethods(); @DefaultMessage("SetStatus") @Description("") String SetStatusMethods(); @DefaultMessage("StopFollowing") @Description("") String StopFollowingMethods(); @DefaultMessage("GetDuration") @Description("") String GetDurationMethods(); @DefaultMessage("SeekTo") @Description("") String SeekToMethods(); @DefaultMessage("DoScan") @Description("") String DoScanMethods(); @DefaultMessage("RequestBallot") @Description("") String RequestBallotMethods(); @DefaultMessage("SendBallot") @Description("") String SendBallotMethods(); @DefaultMessage("BuildPostData") @Description("") String BuildPostDataMethods(); @DefaultMessage("ClearCookies") @Description("") String ClearCookiesMethods(); @DefaultMessage("Get") @Description("") String GetMethods(); @DefaultMessage("HtmlTextDecode") @Description("") String HtmlTextDecodeMethods(); @DefaultMessage("JsonTextDecode") @Description("") String JsonTextDecodeMethods(); @DefaultMessage("PostFile") @Description("") String PostFileMethods(); @DefaultMessage("PostText") @Description("") String PostTextMethods(); @DefaultMessage("PostTextWithEncoding") @Description("") String PostTextWithEncodingMethods(); @DefaultMessage("UriEncode") @Description("") String UriEncodeMethods(); @DefaultMessage("CanGoBack") @Description("") String CanGoBackMethods(); @DefaultMessage("CanGoForward") @Description("") String CanGoForwardMethods(); @DefaultMessage("ClearLocations") @Description("") String ClearLocationsMethods(); @DefaultMessage("GoBack") @Description("") String GoBackMethods(); @DefaultMessage("GoForward") @Description("") String GoForwardMethods(); @DefaultMessage("GoHome") @Description("") String GoHomeMethods(); @DefaultMessage("GoToUrl") @Description("") String GoToUrlMethods(); @DefaultMessage("AppendToFile") @Description("") String AppendToFileMethods(); @DefaultMessage("Delete") @Description("") String DeleteMethods(); @DefaultMessage("ReadFrom") @Description("") String ReadFromMethods(); @DefaultMessage("SaveFile") @Description("") String SaveFileMethods(); @DefaultMessage("doFault") @Description("") String doFaultMethods(); @DefaultMessage("getVersionName") @Description("") String getVersionNameMethods(); @DefaultMessage("installURL") @Description("") String installURLMethods(); @DefaultMessage("isDirect") @Description("") String isDirectMethods(); @DefaultMessage("setAssetsLoaded") @Description("") String setAssetsLoadedMethods(); @DefaultMessage("shutdown") @Description("") String shutdownMethods(); @DefaultMessage("ShareFile") @Description("") String ShareFileMethods(); @DefaultMessage("ShareFileWithMessage") @Description("") String ShareFileWithMessageMethods(); @DefaultMessage("ShareMessage") @Description("") String ShareMessageMethods(); @DefaultMessage("Play") @Description("") String PlayMethods(); @DefaultMessage("DisplayDropdown") @Description("") String DisplayDropdownMethods(); @DefaultMessage("ClearAll") @Description("") String ClearAllMethods(); @DefaultMessage("ClearTag") @Description("") String ClearTagMethods(); @DefaultMessage("GetTags") @Description("") String GetTagsMethods(); @DefaultMessage("Tweet") @Description("") String TweetMethods(); @DefaultMessage("TweetWithImage") @Description("") String TweetWithImageMethods(); @DefaultMessage("BuildRequestData") @Description("") String BuildRequestDataMethods(); @DefaultMessage("PutFile") @Description("") String PutFileMethods(); @DefaultMessage("PutText") @Description("") String PutTextMethods(); @DefaultMessage("PutTextWithEncoding") @Description("") String PutTextWithEncodingMethods(); @DefaultMessage("RequestTranslation") @Description("") String RequestTranslationMethods(); //Mock Components @DefaultMessage("add items...") @Description("") String MockSpinnerAddItems(); //help strings @DefaultMessage("Non-visible component that can detect shaking and measure acceleration approximately in three dimensions using SI units (m/s<sup>2</sup>). The components are: <ul>\n<li> <strong>xAccel</strong>: 0 when the phone is at rest on a flat surface, positive when the phone is tilted to the right (i.e., its left side is raised), and negative when the phone is tilted to the left (i.e., its right size is raised).</li>\n <li> <strong>yAccel</strong>: 0 when the phone is at rest on a flat surface, positive when its bottom is raised, and negative when its top is raised. </li>\n <li> <strong>zAccel</strong>: Equal to -9.8 (earth\"s gravity in meters per second per second when the device is at rest parallel to the ground with the display facing up, 0 when perpindicular to the ground, and +9.8 when facing down. The value can also be affected by accelerating it with or against gravity. </li></ul>") @Description("") String AccelerometerSensorHelpStringComponentPallette(); @DefaultMessage("A component that can launch an activity using the <code>StartActivity</code> method.<p>Activities that can be launched include: <ul> \n<li> starting other App Inventor for Android apps </li> \n<li> starting the camera application </li> \n<li> performing web search </li> \n<li> opening a browser to a specified web page</li> \n<li> opening the map application to a specified location</li></ul> \nYou can also launch activities that return text data. See the documentation on using the Activity Starter for examples.</p>") @Description("") String ActivityStarterHelpStringComponentPallette(); @DefaultMessage("<p>A round \"sprite\" that can be placed on a <code>Canvas</code>, where it can react to touches and drags, interact with other sprites (<code>ImageSprite</code>s and other <code>Ball</code>s) and the edge of the Canvas, and move according to its property values.</p><p>For example, to have a <code>Ball</code> move 4 pixels toward the top of a <code>Canvas</code> every 500 milliseconds (half second), you would set the <code>Speed</code> property to 4 [pixels], the <code>Interval</code> property to 500 [milliseconds], the <code>Heading</code> property to 90 [degrees], and the <code>Enabled</code> property to <code>True</code>. These and its other properties can be changed at any time.</p><p>The difference between a Ball and an <code>ImageSprite</code> is that the latter can get its appearance from an image file, while a Ball\"s appearance can only be changed by varying its <code>PaintColor</code> and <code>Radius</code> properties.</p>") @Description("") String BallHelpStringComponentPallette(); @DefaultMessage("Component for using the Barcode Scanner to read a barcode") @Description("") String BarcodeScannerHelpStringComponentPallette(); @DefaultMessage("Bluetooth client component") @Description("") String BluetoothClientHelpStringComponentPallette(); @DefaultMessage("Bluetooth server component") @Description("") String BluetoothServerHelpStringComponentPallette(); @DefaultMessage("Button with the ability to detect clicks. Many aspects of its appearance can be changed, as well as whether it is clickable (<code>Enabled</code>), can be changed in the Designer or in the Blocks Editor.") @Description("") String ButtonHelpStringComponentPallette(); @DefaultMessage("A component to record a video using the device\"s camcorder.After the video is recorded, the name of the file on the phone containing the clip is available as an argument to the AfterRecording event. The file name can be used, for example, to set the source property of a VideoPlayer component.") @Description("") String CamcorderHelpStringComponentPallette(); @DefaultMessage("A component to take a picture using the device\"s camera. After the picture is taken, the name of the file on the phone containing the picture is available as an argument to the AfterPicture event. The file name can be used, for example, to set the Picture property of an Image component.") @Description("") String CameraHelpStringComponentPallette(); @DefaultMessage("<p>A two-dimensional touch-sensitive rectangular panel on which drawing can be done and sprites can be moved.</p> <p>The <code>BackgroundColor</code>, <code>PaintColor</code>, <code>BackgroundImage</code>, <code>Width</code>, and <code>Height</code> of the Canvas can be set in either the Designer or in the Blocks Editor. The <code>Width</code> and <code>Height</code> are measured in pixels and must be positive.</p><p>Any location on the Canvas can be specified as a pair of (X, Y) values, where <ul> <li>X is the number of pixels away from the left edge of the Canvas</li><li>Y is the number of pixels away from the top edge of the Canvas</li></ul>.</p> <p>There are events to tell when and where a Canvas has been touched or a <code>Sprite</code> (<code>ImageSprite</code> or <code>Ball</code>) has been dragged. There are also methods for drawing points, lines, and circles.</p>") @Description("") String CanvasHelpStringComponentPallette(); @DefaultMessage("Checkbox that raises an event when the user clicks on it. There are many properties affecting its appearance that can be set in the Designer or Blocks Editor.") @Description("") String CheckBoxHelpStringComponentPallette(); @DefaultMessage("Non-visible component that provides the phone\"s clock, a timer, and time calculations.") @Description("") String ClockHelpStringComponentPallette(); @DefaultMessage("A button that, when clicked on, displays a list of the contacts to choose among. After the user has made a selection, the following properties will be set to information about the chosen contact: <ul>\n<li> <code>ContactName</code>: the contact\"s name </li>\n <li> <code>EmailAddress</code>: the contact\"s primary email address </li>\n <li> <code>Picture</code>: the name of the file containing the contact\"s image, which can be used as a <code>Picture</code> property value for the <code>Image</code> or <code>ImageSprite</code> component.</li></ul>\n</p><p>Other properties affect the appearance of the button (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be clicked on (<code>Enabled</code>).\n</p><p>Picking is not supported on all phones. If it fails, this component will show a notification. The error behavior can be overridden with the Screen.ErrorOccurred event handler.") @Description("") String ContactPickerHelpStringComponentPallette(); @DefaultMessage("<p>A button that, when clicked on, launches a popup dialog to allow the user to select a date.</p>") @Description("") String DatePickerHelpStringComponentPallette(); @DefaultMessage("An EmailPicker is a kind of text box. If the user begins entering the name or email address of a contact, the phone will show a dropdown menu of choices that complete the entry. If there are many contacts, the dropdown can take several seconds to appear, and can show intermediate results while the matches are being computed. <p>The initial contents of the text box and the contents< after user entry is in the <code>Text</code> property. If the <code>Text</code> property is initially empty, the contents of the <code>Hint</code> property will be faintly shown in the text box as a hint to the user.</p>\n <p>Other properties affect the appearance of the text box (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be used (<code>Enabled</code>).</p>\n<p>Text boxes like this are usually used with <code>Button</code> components, with the user clicking on the button when text entry is complete.") @Description("") String EmailPickerHelpStringComponentPallette(); @DefaultMessage("Non-visible component for storing and retrieving files. Use this component to write or read files on your device. The default behaviour is to write files to the private data directory associated with your App. The Companion is special cased to write files to /sdcard/AppInventor/data to facilitate debugging. If the file path starts with a slash (/), then the file is created relative to /sdcard. For example writing a file to /myFile.txt will write the file in /sdcard/myFile.txt.") @Description("") String FileHelpStringComponentPallette(); @DefaultMessage("Top-level component containing all other components in the program") @Description("") String FormHelpStringComponentPallette(); @DefaultMessage("<p>A non-visible component that communicates with Google Fusion Tables. Fusion Tables let you store, share, query and visualize data tables; this component lets you query, create, and modify these tables.</p> <p>This component uses the <a href=\"https://developers.google.com/fusiontables/docs/v1/getting_started\" target=\"_blank\">Fusion Tables API V1.0</a>. <p>Applications using Fusion Tables must authentication to Google\"s servers. There are two ways this can be done. The first way uses an API Key which you the developer obtain (see below). With this approach end-users must also login to access a Fusion Table. The second approach is to use a Service Account. With this approach you create credentials and a special \"Service Account Email Address\" which you obtain from the <a href=\"https://code.google.com/apis/console/\" target=\"_blank\">Google APIs Console</a>. You then tell the Fusion Table Control the name of the Service Account Email address and upload the secret key as an asset to your application and set the KeyFile property to point at this file. Finally you check the \"UseServiceAuthentication\" checkbox in the designer. When using a Service Account, end-users do not need to login to use Fusion Tables, your service account authenticates all access.</p> <p>To get an API key, follow these instructions.</p> <ol> <li>Go to your <a href=\"https://code.google.com/apis/console/\" target=\"_blank\">Google APIs Console</a> and login if necessary.</li> <li>Select the <i>Services</i> item from the menu on the left.</li> <li>Choose the <i>Fusiontables</i> service from the list provided and turn it on.</li> <li>Go back to the main menu and select the <i>API Access</i> item. </li> </ol> <p>Your API Key will be near the bottom of that pane in the section called \"Simple API Access\". You will have to provide that key as the value for the <i>ApiKey</i> property in your Fusiontables app.</p> <p>Once you have an API key, set the value of the <i>Query</i> property to a valid Fusiontables SQL query and call <i>SendQuery</i> to execute the query. App Inventor will send the query to the Fusion Tables server and the <i>GotResult</i> block will fire when a result is returned from the server. Query results will be returned in CSV format, and can be converted to list format using the \"list from csv table\" or \"list from csv row\" blocks.</p> <p>Note that you do not need to worry about UTF-encoding the query. But you do need to make sure the query follows the syntax described in <a href=\"https://developers.google.com/fusiontables/docs/v1/getting_started\" target=\"_blank\">the reference manual</a>, which means that things like capitalization for names of columns matters, and that single quotes must be used around column names if there are spaces in them.</p>") @Description("") String FusiontablesControlHelpStringComponentPallette(); @DefaultMessage("Provides a way for applications to communicate with online game servers") @Description("") String GameClientHelpStringComponentPallette(); @DefaultMessage("<p>A formatting element in which to place components that should be displayed from left to right. If you wish to have components displayed one over another, use <code>VerticalArrangement</code> instead.</p>") @Description("") String HorizontalArrangementHelpStringComponentPallette(); @DefaultMessage("Component for displaying images. The picture to display, and other aspects of the Image\"s appearance, can be specified in the Designer or in the Blocks Editor.") @Description("") String ImageHelpStringComponentPallette(); @DefaultMessage("A special-purpose button. When the user taps an image picker, the device\"s image gallery appears, and the user can choose an image. After an image is picked, it is saved on the SD card and the <code>ImageFile</code> property will be the name of the file where the image is stored. In order to not fill up storage, a maximum of 10 images will be stored. Picking more images will delete previous images, in order from oldest to newest.") @Description("") String ImagePickerHelpStringComponentPallette(); @DefaultMessage("<p>A \"sprite\" that can be placed on a <code>Canvas</code>, where it can react to touches and drags, interact with other sprites (<code>Ball</code>s and other <code>ImageSprite</code>s) and the edge of the Canvas, and move according to its property values. Its appearance is that of the image specified in its <code>Picture</code> property (unless its <code>Visible</code> property is <code>False</code>.</p> <p>To have an <code>ImageSprite</code> move 10 pixels to the left every 1000 milliseconds (one second), for example, you would set the <code>Speed</code> property to 10 [pixels], the <code>Interval</code> property to 1000 [milliseconds], the <code>Heading</code> property to 180 [degrees], and the <code>Enabled</code> property to <code>True</code>. A sprite whose <code>Rotates</code> property is <code>True</code> will rotate its image as the sprite\"s <code>Heading</code> changes. Checking for collisions with a rotated sprite currently checks the sprite\"s unrotated position so that collision checking will be inaccurate for tall narrow or short wide sprites that are rotated. Any of the sprite properties can be changed at any time under program control.</p> ") @Description("") String ImageSpriteHelpStringComponentPallette(); @DefaultMessage("A Label displays a piece of text, which is specified through the <code>Text</code> property. Other properties, all of which can be set in the Designer or Blocks Editor, control the appearance and placement of the text.") @Description("") String LabelHelpStringComponentPallette(); @DefaultMessage("<p>A button that, when clicked on, displays a list of texts for the user to choose among. The texts can be specified through the Designer or Blocks Editor by setting the <code>ElementsFromString</code> property to their string-separated concatenation (for example, <em>choice 1, choice 2, choice 3</em>) or by setting the <code>Elements</code> property to a List in the Blocks editor.</p><p>Setting property ShowFilterBar to true, will make the list searchable. Other properties affect the appearance of the button (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be clicked on (<code>Enabled</code>).</p>") @Description("") String ListPickerHelpStringComponentPallette(); @DefaultMessage("<p>This is a visible component that allows to place a list of text elements in your Screen to display. <br> The list can be set using the ElementsFromString property or using the Elements block in the blocks editor. <br> Warning: This component will not work correctly on Screens that are scrollable.</p>") @Description("") String ListViewHelpStringComponentPallette(); @DefaultMessage("Non-visible component providing location information, including longitude, latitude, altitude (if supported by the device), and address. This can also perform \"geocoding\", converting a given address (not necessarily the current one) to a latitude (with the <code>LatitudeFromAddress</code> method) and a longitude (with the <code>LongitudeFromAddress</code> method).</p>\n<p>In order to function, the component must have its <code>Enabled</code> property set to True, and the device must have location sensing enabled through wireless networks or GPS satellites (if outdoors).</p>\nLocation information might not be immediately available when an app starts. You\"ll have to wait a short time for a location provider to be found and used, or wait for the OnLocationChanged event") @Description("") String LocationSensorHelpStringComponentPallette(); @DefaultMessage("<p>Non-visible component to provide NFC capabilities. For now this component supports the reading and writing of text tags only (if supported by the device)</p><p>In order to read and write text tags, the component must have its <code>ReadMode</code> property set to True or False respectively.</p>") @Description("") String NearFieldHelpStringComponentPallette(); @DefaultMessage("The Notifier component displays alert dialogs, messages, and temporary alerts, and creates Android log entries through the following methods: <ul><li> ShowMessageDialog: displays a message which the user must dismiss by pressing a button.</li><li> ShowChooseDialog: displays a message two buttons to let the user choose one of two responses, for example, yes or no, after which the AfterChoosing event is raised.</li><li> ShowTextDialog: lets the user enter text in response to the message, after which the AfterTextInput event is raised. <li> ShowAlert: displays a temporary alert that goes away by itself after a short time.</li><li> LogError: logs an error message to the Android log. </li><li> LogInfo: logs an info message to the Android log.</li><li> LogWarning: logs a warning message to the Android log.</li><li>The messages in the dialogs (but not the alert) can be formatted using the following HTML tags:&lt;b&gt;, &lt;big&gt;, &lt;blockquote&gt;, &lt;br&gt;, &lt;cite&gt;, &lt;dfn&gt;, &lt;div&gt;, &lt;em&gt;, &lt;small&gt;, &lt;strong&gt;, &lt;sub&gt;, &lt;sup&gt;, &lt;tt&gt;. &lt;u&gt;</li><li>You can also use the font tag to specify color, for example, &lt;font color=\"blue\"&gt;. Some of the available color names are aqua, black, blue, fuchsia, green, grey, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow</li></ul>") @Description("") String NotifierHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a color sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtColorSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a low-level interface to a LEGO MINDSTORMS NXT robot, with functions to send NXT Direct Commands.") @Description("") String NxtDirectCommandsHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a LEGO MINDSTORMS NXT robot, with functions that can move and turn the robot.") @Description("") String NxtDriveHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a light sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtLightSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a sound sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtSoundSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a touch sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtTouchSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to an ultrasonic sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtUltrasonicSensorHelpStringComponentPallette(); @DefaultMessage("<p>Non-visible component providing information about the device\"s physical orientation in three dimensions: <ul> <li> <strong>Roll</strong>: 0 degrees when the device is level, increases to 90 degrees as the device is tilted up on its left side, and decreases to -90 degrees when the device is tilted up on its right side. </li> <li> <strong>Pitch</strong>: 0 degrees when the device is level, up to 90 degrees as the device is tilted so its top is pointing down, up to 180 degrees as it gets turned over. Similarly, as the device is tilted so its bottom points down, pitch decreases to -90 degrees, then further decreases to -180 degrees as it gets turned all the way over.</li> <li> <strong>Azimuth</strong>: 0 degrees when the top of the device is pointing north, 90 degrees when it is pointing east, 180 degrees when it is pointing south, 270 degrees when it is pointing west, etc.</li></ul> These measurements assume that the device itself is not moving.</p>") @Description("") String OrientationSensorHelpStringComponentPallette(); @DefaultMessage("<p>A box for entering passwords. This is the same as the ordinary <code>TextBox</code> component except this does not display the characters typed by the user.</p><p>The value of the text in the box can be found or set through the <code>Text</code> property. If blank, the <code>Hint</code> property, which appears as faint text in the box, can provide the user with guidance as to what to type.</p> <p>Text boxes are usually used with the <code>Button</code> component, with the user clicking on the button when text entry is complete.</p>") @Description("") String PasswordTextBoxHelpStringComponentPallette(); @DefaultMessage("Component that can count steps.") @Description("") String PedometerHelpStringComponentPallette(); @DefaultMessage("<p>A non-visible component that makes a phone call to the number specified in the <code>PhoneNumber</code> property, which can be set either in the Designer or Blocks Editor. The component has a <code>MakePhoneCall</code> method, enabling the program to launch a phone call.</p><p>Often, this component is used with the <code>ContactPicker</code> component, which lets the user select a contact from the ones stored on the phone and sets the <code>PhoneNumber</code> property to the contact\"s phone number.</p><p>To directly specify the phone number (e.g., 650-555-1212), set the <code>PhoneNumber</code> property to a Text with the specified digits (e.g., \"6505551212\"). Dashes, dots, and parentheses may be included (e.g., \"(650)-555-1212\") but will be ignored; spaces may not be included.</p>") @Description("") String PhoneCallHelpStringComponentPallette(); @DefaultMessage("A button that, when clicked on, displays a list of the contacts\" phone numbers to choose among. After the user has made a selection, the following properties will be set to information about the chosen contact: <ul>\n<li> <code>ContactName</code>: the contact\"s name </li>\n <li> <code>PhoneNumber</code>: the contact\"s phone number </li>\n <li> <code>EmailAddress</code>: the contact\"s email address </li> <li> <code>Picture</code>: the name of the file containing the contact\"s image, which can be used as a <code>Picture</code> property value for the <code>Image</code> or <code>ImageSprite</code> component.</li></ul>\n</p><p>Other properties affect the appearance of the button (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be clicked on (<code>Enabled</code>).</p>\n<p>Picking is not supported on all phones. If it fails, this component will show a notification. This default error behavior can be overridden with the Screen.ErrorOccurred event handler.") @Description("") String PhoneNumberPickerHelpStringComponentPallette(); @DefaultMessage("Component that returns information about the phone.") @Description("") String PhoneStatusHelpStringComponentPallette(); @DefaultMessage("Multimedia component that plays audio and controls phone vibration. The name of a multimedia field is specified in the <code>Source</code> property, which can be set in the Designer or in the Blocks Editor. The length of time for a vibration is specified in the Blocks Editor in milliseconds (thousandths of a second).\n<p>For supported audio formats, see <a href=\"http://developer.android.com/guide/appendix/media-formats.html\" target=\"_blank\">Android Supported Media Formats</a>.</p>\n<p>This component is best for long sound files, such as songs, while the <code>Sound</code> component is more efficient for short files, such as sound effects.</p>") @Description("") String PlayerHelpStringComponentPallette(); @DefaultMessage("Sharing is a non-visible component that enables sharing files and/or messages between your app and other apps installed on a device. The component will display a list of the installed apps that can handle the information provided, and will allow the user to choose one to share the content with, for instance a mail app, a social network app, a texting app, and so on.<br>The file path can be taken directly from other components such as the Camera or the ImagePicker, but can also be specified directly to read from storage. Be aware that different devices treat storage differently, so a few things to try if, for instance, you have a file called arrow.gif in the folder <code>Appinventor/assets</code>, would be: <ul><li><code>\"file:///sdcard/Appinventor/assets/arrow.gif\"</code></li> or <li><code>\"/storage/Appinventor/assets/arrow.gif\"</code></li></ul>") @Description("") String SharingHelpStringComponentPallette(); @DefaultMessage("A Slider is a progress bar that adds a draggable thumb. You can touch the thumb and drag left or right to set the slider thumb position. As the Slider thumb is dragged, it will trigger the PositionChanged event, reporting the position of the Slider thumb. The reported position of the Slider thumb can be used to dynamically update another component attribute, such as the font size of a TextBox or the radius of a Ball.") @Description("") String SliderHelpStringComponentPallette(); @DefaultMessage("<p>A multimedia component that plays sound files and optionally vibrates for the number of milliseconds (thousandths of a second) specified in the Blocks Editor. The name of the sound file to play can be specified either in the Designer or in the Blocks Editor.</p> <p>For supported sound file formats, see <a href=\"http://developer.android.com/guide/appendix/media-formats.html\" target=\"_blank\">Android Supported Media Formats</a>.</p><p>This <code>Sound</code> component is best for short sound files, such as sound effects, while the <code>Player</code> component is more efficient for longer sounds, such as songs.</p>") @Description("") String SoundHelpStringComponentPallette(); @DefaultMessage("<p>Multimedia component that records audio.</p>") @Description("") String SoundRecorderHelpStringComponentPallette(); @DefaultMessage("Component for using Voice Recognition to convert from speech to text") @Description("") String SpeechRecognizerHelpStringComponentPallette(); @DefaultMessage("<p>A spinner component that displays a pop-up with a list of elements. These elements can be set in the Designer or Blocks Editor by setting the<code>ElementsFromString</code> property to a string-separated concatenation (for example, <em>choice 1, choice 2, choice 3</em>) or by setting the <code>Elements</code> property to a List in the Blocks editor.</p>") @Description("") String SpinnerHelpStringComponentPallette(); @DefaultMessage("<p>A formatting element in which to place components that should be displayed in tabular form.</p>") @Description("") String TableArrangementHelpStringComponentPallette(); @DefaultMessage("<p>A box for the user to enter text. The initial or user-entered text value is in the <code>Text</code> property. If blank, the <code>Hint</code> property, which appears as faint text in the box, can provide the user with guidance as to what to type.</p><p>The <code>MultiLine</code> property determines if the text can havemore than one line. For a single line text box, the keyboard will closeautomatically when the user presses the Done key. To close the keyboard for multiline text boxes, the app should use the HideKeyboard method or rely on the user to press the Back key.</p><p>The <code> NumbersOnly</code> property restricts the keyboard to acceptnumeric input only.</p><p>Other properties affect the appearance of the text box (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be used (<code>Enabled</code>).</p><p>Text boxes are usually used with the <code>Button</code> component, with the user clicking on the button when text entry is complete.</p><p>If the text entered by the user should not be displayed, use <code>PasswordTextBox</code> instead.</p>") @Description("") String TextBoxHelpStringComponentPallette(); @DefaultMessage("Component for using TextToSpeech to speak a message") @Description("") String TextToSpeechHelpStringComponentPallette(); @DefaultMessage("<p>A component that will, when the <code>SendMessage</code> method is called, send the text message specified in the <code>Message</code> property to the phone number specified in the <code>PhoneNumber</code> property.</p> <p>If the <code>ReceivingEnabled</code> property is set to 1 messages will <b>not</b> be received. If <code>ReceivingEnabled</code> is set to 2 messages will be received only when the application is running. Finally if <code>ReceivingEnabled</code> is set to 3, messages will be received when the application is running <b>and</b> when the application is not running they will be queued and a notification displayed to the user.</p> <p>When a message arrives, the <code>MessageReceived</code> event is raised and provides the sending number and message.</p> <p> An app that includes this component will receive messages even when it is in the background (i.e. when it\"s not visible on the screen) and, moreso, even if the app is not running, so long as it\"s installed on the phone. If the phone receives a text message when the app is not in the foreground, the phone will show a notification in the notification bar. Selecting the notification will bring up the app. As an app developer, you\"ll probably want to give your users the ability to control ReceivingEnabled so that they can make the phone ignore text messages.</p> <p>If the GoogleVoiceEnabled property is true, messages can be sent over Wifi using Google Voice. This option requires that the user have a Google Voice account and that the mobile Voice app is installed on the phone. The Google Voice option works only on phones that support Android 2.0 (Eclair) or higher.</p> <p>To specify the phone number (e.g., 650-555-1212), set the <code>PhoneNumber</code> property to a Text string with the specified digits (e.g., 6505551212). Dashes, dots, and parentheses may be included (e.g., (650)-555-1212) but will be ignored; spaces may not be included.</p> <p>Another way for an app to specify a phone number would be to include a <code>PhoneNumberPicker</code> component, which lets the users select a phone numbers from the ones stored in the the phone\"s contacts.</p>") @Description("") String TextingHelpStringComponentPallette(); @DefaultMessage("<p>A button that, when clicked on, launches a popup dialog to allow the user to select a time.</p>") @Description("") String TimePickerHelpStringComponentPallette(); @DefaultMessage("TinyDB is a non-visible component that stores data for an app. <p> Apps created with App Inventor are initialized each time they run: If an app sets the value of a variable and the user then quits the app, the value of that variable will not be remembered the next time the app is run. In contrast, TinyDB is a <em> persistent </em> data store for the app, that is, the data stored there will be available each time the app is run. An example might be a game that saves the high score and retrieves it each time the game is played. </<p> <p> Data items are strings stored under <em>tags</em> . To store a data item, you specify the tag it should be stored under. Subsequently, you can retrieve the data that was stored under a given tag. </p><p> There is only one data store per app. Even if you have multiple TinyDB components, they will use the same data store. To get the effect of separate stores, use different keys. Also each app has its own data store. You cannot use TinyDB to pass data between two different apps on the phone, although you <em>can</em> use TinyDb to shares data between the different screens of a multi-screen app. </p> <p>When you are developing apps using the AI Companion, all the apps using that companion will share the same TinyDb. That sharing will disappear once the apps are packaged. But, during development, you should be careful to clear the TinyDb each time you start working on a new app.</p>") @Description("") String TinyDBHelpStringComponentPallette(); @DefaultMessage("Non-visible component that communicates with a Web service to store and retrieve information.") @Description("") String TinyWebDBHelpStringComponentPallette(); @DefaultMessage("A non-visible component that enables communication with <a href=\"http://www.twitter.com\" target=\"_blank\">Twitter</a>. Once a user has logged into their Twitter account (and the authorization has been confirmed successful by the <code>IsAuthorized</code> event), many more operations are available:<ul><li> Searching Twitter for tweets or labels (<code>SearchTwitter</code>)</li>\n<li> Sending a Tweet (<code>Tweet</code>) </li>\n<li> Sending a Tweet with an Image (<code>TweetWithImage</code>) </li>\n<li> Directing a message to a specific user (<code>DirectMessage</code>)</li>\n <li> Receiving the most recent messages directed to the logged-in user (<code>RequestDirectMessages</code>)</li>\n <li> Following a specific user (<code>Follow</code>)</li>\n<li> Ceasing to follow a specific user (<code>StopFollowing</code>)</li>\n<li> Getting a list of users following the logged-in user (<code>RequestFollowers</code>)</li>\n <li> Getting the most recent messages of users followed by the logged-in user (<code>RequestFriendTimeline</code>)</li>\n <li> Getting the most recent mentions of the logged-in user (<code>RequestMentions</code>)</li></ul></p>\n <p>You must obtain a Comsumer Key and Consumer Secret for Twitter authorization specific to your app from http://twitter.com/oauth_clients/new") @Description("") String TwitterHelpStringComponentPallette(); @DefaultMessage("<p>A formatting element in which to place components that should be displayed one below another. (The first child component is stored on top, the second beneath it, etc.) If you wish to have components displayed next to one another, use <code>HorizontalArrangement</code> instead.</p>") @Description("") String VerticalArrangementHelpStringComponentPallette(); @DefaultMessage("A multimedia component capable of playing videos. When the application is run, the VideoPlayer will be displayed as a rectangle on-screen. If the user touches the rectangle, controls will appear to play/pause, skip ahead, and skip backward within the video. The application can also control behavior by calling the <code>Start</code>, <code>Pause</code>, and <code>SeekTo</code> methods. <p>Video files should be in Windows Media Video (.wmv) format, 3GPP (.3gp), or MPEG-4 (.mp4). For more details about legal formats, see <a href=\"http://developer.android.com/guide/appendix/media-formats.html\" target=\"_blank\">Android Supported Media Formats</a>.</p><p>App Inventor for Android only permits video files under 1 MB and limits the total size of an application to 5 MB, not all of which is available for media (video, audio, and sound) files. If your media files are too large, you may get errors when packaging or installing your application, in which case you should reduce the number of media files or their sizes. Most video editing software, such as Windows Movie Maker and Apple iMovie, can help you decrease the size of videos by shortening them or re-encoding the video into a more compact format.</p><p>You can also set the media source to a URL that points to a streaming video, but the URL must point to the video file itself, not to a program that plays the video.") @Description("") String VideoPlayerHelpStringComponentPallette(); @DefaultMessage("<p>The Voting component enables users to vote on a question by communicating with a Web service to retrieve a ballot and later sending back users\" votes.</p>") @Description("") String VotingHelpStringComponentPallette(); @DefaultMessage("Non-visible component that provides functions for HTTP GET, POST, PUT, and DELETE requests.") @Description("") String WebHelpStringComponentPallette(); @DefaultMessage("Component for viewing Web pages. The Home URL can be specified in the Designer or in the Blocks Editor. The view can be set to follow links when they are tapped, and users can fill in Web forms. Warning: This is not a full browser. For example, pressing the phone\"s hardware Back key will exit the app, rather than move back in the browser history.<p />You can use the WebViewer.WebViewString property to communicate between your app and Javascript code running in the Webviewer page. In the app, you get and set WebViewString. In the WebViewer, you include Javascript that references the window.AppInventor object, using the methoods </em getWebViewString()</em> and <em>setWebViewString(text)</em>. <p />For example, if the WebViewer opens to a page that contains the Javascript command <br /> <em>document.write(\"The answer is\" + window.AppInventor.getWebViewString());</em> <br />and if you set WebView.WebVewString to \"hello\", then the web page will show </br ><em>The answer is hello</em>. <br />And if the Web page contains Javascript that executes the command <br /><em>windowAppInventor.setWebViewString(\"hello from Javascript\")</em>, <br />then the value of the WebViewString property will be <br /><em>hello from Javascript</em>. ") @Description("") String WebViewerHelpStringComponentPallette(); @DefaultMessage("Use this component to translate words and sentences between different languages. This component needs Internet access, as it will request translations to the Yandex.Translate service. Specify the source and target language in the form source-target using two letter language codes. So\"en-es\" will translate from English to Spanish while \"es-ru\" will translate from Spanish to Russian. If you leave out the source language, the service will attempt to detect the source language. So providing just \"es\" will attempt to detect the source language and translate it to Spanish.<p /> This component is powered by the Yandex translation service. See http://api.yandex.com/translate/ for more information, including the list of available languages and the meanings of the language codes and status codes. <p />Note: Translation happens asynchronously in the background. When the translation is complete, the \"GotTranslation\" event is triggered.") @Description("") String YandexTranslateHelpStringComponentPallette(); //Ode.java messages @DefaultMessage("Welcome to App Inventor 2!") @Description("") String createNoProjectsDialogText(); @DefaultMessage("<p>You don\"t have any projects in App Inventor 2 yet. " + "To learn how to use App Inventor, click the \"Guide\" " + "link at the upper right of the window; or to start your first project, " + "click the \"New\" button at the upper left of the window.</p>\n<p>" + "<strong>Where did my projects go?</strong> " + "If you had projects but now they\"re missing, " + "you are probably looking for App Inventor version 1. " + "It\"s still available here: " + "<a href=\"http://beta.appinventor.mit.edu\" target=\"_blank\">beta.appinventor.mit.edu</a></p>\n") @Description("") String createNoProjectsDialogMessage1(); @DefaultMessage("Happy Inventing!") @Description("") String createNoprojectsDialogMessage2(); @DefaultMessage("Welcome to App Inventor!") @Description("") String createWelcomeDialogText(); @DefaultMessage("<h2>This is the Splash Screen. Make this an iframe to your splash screen.</h2>") @Description("") String createWelcomeDialogMessage(); @DefaultMessage("Continue") @Description("") String createWelcomeDialogButton(); @DefaultMessage("<h2>Please fill out a short voluntary survey so that we can learn more about our users and improve MIT App Inventor.</h2>") @Description("") String showSurveySplashMessage(); @DefaultMessage("Take Survey Now") @Description("") String showSurveySplashButtonNow(); @DefaultMessage("Take Survey Later") @Description("") String showSurveySplashButtonLater(); @DefaultMessage("Never Take Survey") @Description("") String showSurveySplashButtonNever(); @DefaultMessage("This Session Is Out of Date") @Description("") String invalidSessionDialogText(); @DefaultMessage("<p><font color=red>Warning:</font> This session is out of date.</p>" + "<p>This App Inventor account has been opened from another location. " + "Using a single account from more than one location at the same time " + "can damage your projects.</p>" + "<p>Choose one of the buttons below to:" + "<ul>" + "<li>End this session here.</li>" + "<li>Make this the current session and make the other sessions out of date.</li>" + "<li>Continue with both sessions.</li>" + "</ul>" + "</p>") @Description("") String invalidSessionDialogMessage(); @DefaultMessage("End This Session") @Description("") String invalidSessionDialogButtonEnd(); @DefaultMessage("Make this the current session") @Description("") String invalidSessionDialogButtonCurrent(); @DefaultMessage("Continue with Both Sessions") @Description("") String invalidSessionDialogButtonContinue(); @DefaultMessage("Do you want to continue with multiple sessions?") @Description("") String bashWarningDialogText(); @DefaultMessage("<p><font color=red>WARNING:</font> A second App " + "Inventor session has been opened for this account. You may choose to " + "continue with both sessions, but working with App Inventor from more " + "than one session simultaneously can cause blocks to be lost in ways " + "that cannot be recovered from the App Inventor server.</p><p>" + "We recommend that people not open multiple sessions on the same " + "account. But if you do need to work in this way, then you should " + "regularly export your project to your local computer, so you will " + "have a backup copy independent of the App Inventor server. Use " + "\"Export\" from the Projects menu to export the project.</p>") @Description("") String bashWarningDialogMessage(); @DefaultMessage("Continue with Multiple Sessions") @Description("") String bashWarningDialogButtonContinue(); @DefaultMessage("Do not use multiple Sessions") @Description("") String bashWarningDialogButtonNo(); @DefaultMessage("Your Session is Finished") @Description("") String finalDialogText(); @DefaultMessage("<p><b>Your Session is now ended, you may close this window</b></p>") @Description("") String finalDialogMessage(); @DefaultMessage("Project Read Error") @Description("") String corruptionDialogText(); @DefaultMessage("<p><b>We detected errors while reading in your project</b></p>" + "<p>To protect your project from damage, we have ended this session. You may close this " + "window.</p>") @Description("") String corruptionDialogMessage(); @DefaultMessage("Blocks Workspace is Empty") @Description("") String blocksTruncatedDialogText(); @DefaultMessage("<p>It appears that <b>" + "%1" + "</b> has had all blocks removed. Either you removed them intentionally, or this is " + "the result of a bug in our system.</p><p>" + "<ul><li>Select \"OK, save the empty screen\" to continue to save the empty screen</li>" + "<li>Select \"No, Don\"t Save\" below to restore the previously saved version</li></ul></p>") @Description("") String blocksTruncatedDialogMessage(); @DefaultMessage("OK, save the empty screen") @Description("") String blocksTruncatedDialogButtonSave(); @DefaultMessage("No, Don\"t Save") @Description("") String blocksTruncatedDialogButtonNoSave(); @DefaultMessage("Please wait " + "%1" + " seconds...") @Description("") String blocksTruncatedDialogButtonHTML(); @DefaultMessage("InsertRow") @Description("") String InsertRowMethods(); @DefaultMessage("GetRows") @Description("") String GetRowsMethods(); @DefaultMessage("GetRowsWithConditions") @Description("") String GetRowsWithConditionsMethods(); @DefaultMessage("简体中文") @Description("") String SwitchToSimplifiedChinese(); @DefaultMessage("繁体中文") @Description("") String SwitchToTraditionalChinese(); @DefaultMessage("Progress Bar") @Description("") String ProgressBarFor(); }
appinventor/appengine/src/com/google/appinventor/client/OdeMessages.java
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt package com.google.appinventor.client; import com.google.gwt.i18n.client.Messages; /** * I18n strings for {@link Ode}. * */ //@LocalizableResource.Generate(format = "com.google.gwt.i18n.rebind.format.PropertiesFormat") //@LocalizableResource.DefaultLocale("en") public interface OdeMessages extends Messages { // Used in multiple files @DefaultMessage("Cancel") @Description("Text on \"Cancel\" button.") String cancelButton(); @DefaultMessage("OK") @Description("Text on \"OK\" button.") String okButton(); @DefaultMessage("Dismiss") @Description("Text on \"Dismiss\" button.") String dismissButton(); @DefaultMessage("Old name:") @Description("Label next to the old name in a rename dialog") String oldNameLabel(); @DefaultMessage("New name:") @Description("Label next to the new name in a rename dialog") String newNameLabel(); @DefaultMessage("None") @Description("Caption for None entry") String noneCaption(); @DefaultMessage("Delete") @Description("Text on \"Delete\" button") String deleteButton(); @DefaultMessage("Delete Project") @Description("Text on \"Delete Project\" button") String deleteProjectButton(); @DefaultMessage("Show Warnings") @Description("Text on Toggle Warning Button") String showWarnings(); @DefaultMessage("Hide Warnings") @Description("Text on Toggle Warning Button") String hideWarnings(); @DefaultMessage("Upload File ...") @Description("Text on \"Add...\" button") String addButton(); @DefaultMessage("Name") @Description("Header for name column of project table") String projectNameHeader(); @DefaultMessage("Date Created") @Description("Header for date created column of project table.") String projectDateCreatedHeader(); @DefaultMessage("Date Modified") @Description("Header for date modified column of project table.") String projectDateModifiedHeader(); @DefaultMessage("Save") @Description("Label of the button for save") String saveButton(); @DefaultMessage("Save As") @Description("Label of the button for save as") String saveAsButton(); @DefaultMessage("Checkpoint ...") @Description("Label of the button for checkpoint") String checkpointButton(); @DefaultMessage("Add Screen ...") @Description("Label of the button for adding a new screen") String addFormButton(); @DefaultMessage("Remove Screen") @Description("Label of the button for removing a screen") String removeFormButton(); @DefaultMessage("Connect") @Description("Label of the button for selecting phone connection") String connectButton(); @DefaultMessage("Deleting this screen will completely remove the screen from your project. " + "All components and blocks associated with this screen will be deleted.\n" + "There is no undo.\nAre you sure you want to delete {0}?") @Description("Confirmation query for removing a screen") String reallyDeleteForm(String formName); @DefaultMessage("Open the Blocks Editor") @Description("Label of the button for opening the blocks editor") String openBlocksEditorButton(); @DefaultMessage("Screens ...") @Description("Label of the button for switching screens") String screensButton(); @DefaultMessage("Blocks") @Description("Label of the button for switching to the blocks editor") String switchToBlocksEditorButton(); @DefaultMessage("Designer") @Description("Label of the button for switching to the form editor") String switchToFormEditorButton(); @DefaultMessage("Packaging ...") @Description("Label of the button leading to build related cascade items, when building") String isBuildingButton(); @DefaultMessage("Opening the Blocks Editor... (click to cancel)") @Description("Label of the button for canceling the blocks editor launch") String cancelBlocksEditorButton(); @DefaultMessage("Blocks Editor is open") @Description("Label of the button for opening the blocks editor when the it is already open") String blocksEditorIsOpenButton(); // Switch Language Buttons (Internationalization) @DefaultMessage("Language") @Description("Label of the button for switching language") String switchLanguageButton(); // Not used anymore it is now dynamically created and translated at compile time depending on what //languages are translated and available. // @DefaultMessage("English") // @Description("Label of the button for switching language to English") // String switchLanguageEnglishButton(); // // @DefaultMessage("Chinese CN") // @Description("Label of the button for switching language to Chinese CN") // String switchLanguageChineseCNButton(); // // @DefaultMessage("German") // @Description("Label of the button for switching language to German") // String switchLanguageGermanButton(); // // @DefaultMessage("Vietnamese") // @Description("Label of the button for switching language to Vietnamese") // String switchLanguageVietnameseButton(); // Used in MotdFetcher.java @DefaultMessage("Failed to contact server to get the MOTD.") @Description("Message displayed when cannot get a MOTD from the server.") String getMotdFailed(); // Used in Ode.java // TODO(user): Replace with commented version once we're ready @DefaultMessage("MIT App Inventor 2") @Description("Title for App Inventor") String titleYoungAndroid(); @DefaultMessage("An internal error has occurred. Report a bug?") @Description("Confirmation for reporting a bug after an internal error") String internalErrorReportBug(); @DefaultMessage("An internal error has occurred.") @Description("Alert after an internal error") String internalError(); @DefaultMessage("An internal error has occurred. Go look in the Debugging view.") @Description("Alert after an internal error") String internalErrorSeeDebuggingView(); @DefaultMessage("An internal error has occurred. Click \"ok\" for more information.") @Description("Confirm alert after an internal error") String internalErrorClickOkDebuggingView(); @DefaultMessage("The server is temporarily unavailable. Please try again later!") @Description("Error message if the server becomes completely unavailable.") String serverUnavailable(); @DefaultMessage("No Project Chosen") @Description("Title for Error Dialog when connection is attempted without a project.") String noprojectDialogTitle(); @DefaultMessage("You must first create or select a project before connecting!") @Description("Error message for connection attempt without a project selected.") String noprojectDuringConnect(); // Used in RpcStatusPopup.java @DefaultMessage("Loading ...") @Description("Message that is shown to indicate that a loading RPC is going on") String defaultRpcMessage(); @DefaultMessage("Saving ...") @Description("Message that is shown to indicate that a saving RPC is going on") String savingRpcMessage(); @DefaultMessage("Copying ...") @Description("Message that is shown to indicate that a copying RPC is going on") String copyingRpcMessage(); @DefaultMessage("Deleting ...") @Description("Message that is shown to indicate that a deleting RPC is going on") String deletingRpcMessage(); @DefaultMessage("Packaging ...") @Description("Message shown during a building RPC (for Young Android, called 'packaging')") String packagingRpcMessage(); @DefaultMessage("Downloading to phone ...") @Description("Message shown while downloading application to the phone (during compilation)") String downloadingRpcMessage(); // Used in StatusPanel.java @DefaultMessage("Built: {0} Version: {1}") @Description("Label showing the ant build date and the git version") String gitBuildId(String date, String version); @DefaultMessage("Privacy") @Description("Label of the link for Privacy") String privacyLink(); @DefaultMessage("Terms") @Description("Label of the link for Terms") String termsLink(); @DefaultMessage("Privacy Policy and Terms of Use") @Description("Label of the link for Privacy and Terms of Use") String privacyTermsLink(); // Used in TopPanel.java //Project @DefaultMessage("Projects") @Description("Name of Projects tab") String projectsTabName(); @DefaultMessage("My projects") @Description("Name of My projects menuitem") String projectMenuItem(); @DefaultMessage("Start new project") @Description("Label of the menu item for creating a new project") String newProjectMenuItem(); @DefaultMessage("Import project (.aia) from my computer ...") @Description("Name of Import Project menuitem") String importProjectMenuItem(); @DefaultMessage("Delete project") @Description("Name of Delete project menuitem") String deleteProjectMenuItem(); @DefaultMessage("Save project") @Description("Name of Save menuitem") String saveMenuItem(); @DefaultMessage("Save project as ...") @Description("Name of Save as ... menuitem") String saveAsMenuItem(); @DefaultMessage("Checkpoint") @Description("Name of Checkpoint menuitem") String checkpointMenuItem(); @DefaultMessage("Import project (.aia) from a repository ...") @Description("Name of Import Template menuitem") String importTemplateButton(); @DefaultMessage("Export selected project (.aia) to my computer") @Description("Name of Export Project menuitem") String exportProjectMenuItem(); @DefaultMessage("Export all projects") @Description("Name of Export all Project menuitem") String exportAllProjectsMenuItem(); @DefaultMessage("Export keystore") @Description("Label of the button for export keystore") String downloadKeystoreMenuItem(); @DefaultMessage("Import keystore") @Description("Label of the button for import keystore") String uploadKeystoreMenuItem(); @DefaultMessage("Delete keystore") @Description("Label of the button for delete keystore") String deleteKeystoreMenuItem(); //Connect @DefaultMessage("Connect") @Description("Label of the button leading to Connect related cascade items") String connectTabName(); @DefaultMessage("AI Companion") @Description("Message providing details about starting the wireless connection.") String AICompanionMenuItem(); @DefaultMessage("Emulator") @Description("Message providing details about starting the emulator connection.") String emulatorMenuItem(); @DefaultMessage("USB") @Description("Message providing details about starting a USB connection.") String usbMenuItem(); @DefaultMessage("Reset Connection") @Description("Reset all connections.") String resetConnectionsMenuItem(); @DefaultMessage("Hard Reset") @Description("Hard Reset the Emulator.") String hardResetConnectionsMenuItem(); //Build @DefaultMessage("Build") @Description("Label of the button leading to build related cascade items") String buildTabName(); @DefaultMessage("App ( provide QR code for .apk )") @Description("Label of item for building a project and show barcode") String showBarcodeMenuItem(); @DefaultMessage("App ( save .apk to my computer )") @Description("Label of item for building a project and downloading") String downloadToComputerMenuItem(); @DefaultMessage("Generate YAIL") @Description("Label of the cascade item for generating YAIL for a project") String generateYailMenuItem(); //Help @DefaultMessage("Help") @Description("Label for the Help menu") String helpTabName(); @DefaultMessage("About") @Description("Label of the link for About") String aboutMenuItem(); @DefaultMessage("Library") @Description("Name of Library link") String libraryMenuItem(); @DefaultMessage("Get Started") @Description("Name of Getting Started link") String getStartedMenuItem(); @DefaultMessage("Tutorials") @Description("Name of Tutorials link") String tutorialsMenuItem(); @DefaultMessage("Troubleshooting") @Description("Name of Troubleshooting link") String troubleshootingMenuItem(); @DefaultMessage("Forums") @Description("Name of Forums link") String forumsMenuItem(); @DefaultMessage("Report an Issue") @Description("Link for Report an Issue form") String feedbackMenuItem(); //Admin @DefaultMessage("Admin") @Description("Label of the button leading to admin functionality") String adminTabName(); @DefaultMessage("Download User Source") @Description("Label of the button for admins to download a user's project source") String downloadUserSourceMenuItem(); @DefaultMessage("Switch To Debug Panel") @Description("Label of the button for admins to switch to the debug panel without an explicit error") String switchToDebugMenuItem(); //Tabs @DefaultMessage("My Projects") @Description("Name of My Projects tab") String myProjectsTabName(); @DefaultMessage("Guide") @Description("Name of Guide link") String guideTabName(); @DefaultMessage("Report an Issue") @Description("Link for Report an Issue form") String feedbackTabName(); @DefaultMessage("Gallery") @Description("Link for Gallery") String galleryTabName(); //User email dropdown @DefaultMessage("Sign out") @Description("Label of the link for signing out") String signOutLink(); // @DefaultMessage("Design") @Description("Name of Design tab") String tabNameDesign(); @DefaultMessage("(Debugging)") @Description("Name of Debugging tab") String tabNameDebugging(); @DefaultMessage("Please choose a project to open or create a new project.") @Description("Message shown when there is no current file editor to switch to") String chooseProject(); // Used in boxes/AssetListBox.java @DefaultMessage("Media") @Description("Caption for asset list box.") String assetListBoxCaption(); // Used in boxes/MessagesOutputBox.java @DefaultMessage("Messages") @Description("Caption for message output box.") String messagesOutputBoxCaption(); // Used in boxes/MotdBox.java @DefaultMessage("Welcome to App Inventor!") @Description("Initial caption for MOTD box.") String motdBoxCaption(); // Used in boxes/OdeLogBox.java @DefaultMessage("Developer Messages") @Description("Caption for ODE log box.") String odeLogBoxCaption(); // Used in boxes/PaletteBox.java @DefaultMessage("Palette") @Description("Caption for palette box.") String paletteBoxCaption(); // Used in boxes/ProjectListBox.java @DefaultMessage("Projects") @Description("Caption for project list box.") String projectListBoxCaption(); // Used in boxes/PropertiesBox.java @DefaultMessage("Properties") @Description("Caption for properties box.") String propertiesBoxCaption(); // Used in boxes/SourceStructureBox.java @DefaultMessage("Components") @Description("Caption for source structure box.") String sourceStructureBoxCaption(); // Used in boxes/BlockSelectorBox.java @DefaultMessage("Blocks") @Description("Caption for block selector box.") String blockSelectorBoxCaption(); @DefaultMessage("Built-in") @Description("Label on built-in-blocks branch of block selector tree") String builtinBlocksLabel(); @DefaultMessage("Control") @Description("Label on built-in-Control-blocks branch of block selector tree") String builtinControlLabel(); @DefaultMessage("Logic") @Description("Label on built-in-Logic-blocks branch of block selector tree") String builtinLogicLabel(); @DefaultMessage("Text") @Description("Label on built-in-Text-blocks branch of block selector tree") String builtinTextLabel(); @DefaultMessage("Lists") @Description("Label on built-in-Lists-blocks branch of block selector tree") String builtinListsLabel(); @DefaultMessage("Colors") @Description("Label on built-in-Colors-blocks branch of block selector tree") String builtinColorsLabel(); @DefaultMessage("Variables") @Description("Label on built-in-Variables-blocks branch of block selector tree") String builtinVariablesLabel(); @DefaultMessage("Procedures") @Description("Label on built-in-Procedures-blocks branch of block selector tree") String builtinProceduresLabel(); @DefaultMessage("Any component") @Description("Label on any-component branch of block selector tree") String anyComponentLabel(); @DefaultMessage("Any ") @Description("None") String textAnyComponentLabel(); // Used in boxes/ViewerBox.java @DefaultMessage("Viewer") @Description("Caption for a viewer box.") String viewerBoxCaption(); // Used in SaveAllEditorsCommand.java @DefaultMessage("Saved project at {0}") @Description("Message reported when project was saved successfully.") String savedProject(String saveTime); // Used in editor/EditorManager.java @DefaultMessage("Server error: could not save one or more files. Please try again later!") @Description("Error message reported when one or more file couldn't be saved to the server.") String saveErrorMultipleFiles(); @DefaultMessage("Error generating Yail for screen {0}: {1}. Please fix and try packaging again.") @Description("Error message reported when yail generation fails for a screen") String yailGenerationError(String formName, String description); // Used in editor/simple/SimpleNonVisibleComponentsPanel.java @DefaultMessage("Non-visible components") @Description("Header for the non-visible components in the designer.") String nonVisibleComponentsHeader(); // Used in editor/simple/SimpleVisibleComponentsPanel.java @DefaultMessage("Display hidden components in Viewer") @Description("Checkbox controlling whether to display invisible components in the designer.") String showHiddenComponentsCheckbox(); @DefaultMessage("Check to see Preview on Tablet size.") @Description("Checkbox (check) controlling whether to display a preview on Tablet size.") String previewTabletSize(); @DefaultMessage("Un-check to see Preview on Phone size.") @Description("Checkbox (un-check) controlling whether to display a preview on Phone size.") String previewPhoneSize(); // Used in editor/simple/components/MockComponent.java @DefaultMessage("Rename Component") @Description("Title for the rename component dialog") String renameTitle(); @DefaultMessage("Component names can contain only letters, numbers, and underscores and " + "must start with a letter") @Description("Error message when component name contains non-alphanumeric characters besides _ " + "or does not start with a letter") String malformedComponentNameError(); @DefaultMessage("Duplicate component name!") @Description("Error shown when a new component name would be the same as an existing one") String duplicateComponentNameError(); @DefaultMessage("Component instance names cannot be the same as a component type") @Description("Error shown when a new component name would be the same as a component type name") String sameAsComponentTypeNameError(); @DefaultMessage("Component name cannot be any of the following: CsvUtil, Double, Float, " + "Integer, JavaCollection, JavaIterator, KawaEnvironment, Long, Short, SimpleForm, String, " + "Pattern, YailList, YailNumberToString, YailRuntimeError") @Description("Error shown when a new component name is a variable name already used in the" + "Yail code") String badComponentNameError(); @DefaultMessage("Deleting this component will delete all blocks associated with it in the " + "Blocks Editor. Are you sure you want to delete?") @Description("Confirmation query for removing a component") String reallyDeleteComponent(); // Used in editor/simple/components/MockButtonBase.java, MockCheckBox.java, MockLabel.java, and // MockRadioButton.java @DefaultMessage("Text for {0}") @Description("Default value for Text property") String textPropertyValue(String componentName); // Used in editor/simple/components/MockButtonBase.java, MockHVLayoutBase.java @DefaultMessage("System error: Bad value - {0} - for Horizontal Alignment.") @Description("Default message for bad value for Horizontal Alignment") String badValueForHorizontalAlignment(String componentName); @DefaultMessage("System error: Bad value - {0} - for Vertical Alignment.") @Description("Default message for bad value for Vartical Alignment") String badValueForVerticalAlignment(String componentName); // Used in editor/simple/components/MockVisibleComponent.java @DefaultMessage("Width") @Description("Caption for the width property") String widthPropertyCaption(); @DefaultMessage("Height") @Description("Caption for the height property") String heightPropertyCaption(); // Used in editor/simple/components/MockTextBoxBase.java @DefaultMessage("Hint for {0}") @Description("Default value for Hint property") String hintPropertyValue(String componentName); // Used in editor/simple/palette/ComponentHelpWidget.java @DefaultMessage("More information") @Description("Label of the link to a component's reference docs") String moreInformation(); // Used in editor/youngandroid/YaFormEditor.java and YaBlocksEditor.java @DefaultMessage("Server error: could not load file. Please try again later!") @Description("Error message reported when a source file couldn't be loaded from the server.") String loadError(); @DefaultMessage("Server error: could not save file. Please try again later!") @Description("Error message reported when a source file couldn't be saved to the server.") String saveError(); @DefaultMessage("{0} blocks") @Description("Tab name for blocks editor") String blocksEditorTabName(String formName); // Used in editor/youngandroid/BlocklyPanel.java @DefaultMessage("The blocks area did not load properly. Changes to the blocks for screen {0} will not be saved.") @Description("Message indicating that blocks changes were not saved") String blocksNotSaved(String formName); @DefaultMessage("The blocks for screen {0} did not load properly. " + "You will not be able to edit using the blocks editor until the problem is corrected.") @Description("Message when blocks fail to load properly") String blocksLoadFailure(String formName); //Used in editor/youngandroid/properties/YoungAndroidAccelerometerSensitivityChoicePropertyEditor.java @DefaultMessage("weak") @Description("Text for accelerometer sensitivity choice 'weak'") String weakAccelerometerSensitivity(); @DefaultMessage("moderate") @Description("Text for accelerometer sensitivity choice 'moderate'") String moderateAccelerometerSensitivity(); @DefaultMessage("strong") @Description("Text for accelerometer sensitivity choice 'strong'") String strongAccelerometerSensitivity(); // Used in editor/youngandroid/properties/YoungAndroidAlignmentChoicePropertyEditor.java @DefaultMessage("left") @Description("Text for text alignment choice 'left'") String leftTextAlignment(); @DefaultMessage("center") @Description("Text for text alignment choice 'center'") String centerTextAlignment(); @DefaultMessage("right") @Description("Text for text alignment choice 'right'") String rightTextAlignment(); // Used in // editor/youngandroid/properties/YoungAndroidHorizontalAlignmentChoicePropertyEditor.java @DefaultMessage("Left") @Description("Text for horizontal alignment choice 'Left") String horizontalAlignmentChoiceLeft(); @DefaultMessage("Right") @Description("Text for horizontal alignemt choice 'Right'") String horizontalAlignmentChoiceRight(); @DefaultMessage("Center") @Description("Text for horizontal alignment choice 'Center'") String horizontalAlignmentChoiceCenter(); // Used in // editor/youngandroid/properties/YoungAndroidVerticalAlignmentChoicePropertyEditor.java @DefaultMessage("Top") @Description("Text for vertical alignment choice 'Top'") String verticalAlignmentChoiceTop(); @DefaultMessage("Center") @Description("Text for vertical alignment choice 'Center'") String verticalAlignmentChoiceCenter(); @DefaultMessage("Bottom") @Description("Text for vertical alignment choice 'Bottom'") String verticalAlignmentChoiceBottom(); // Used in editor/youngandroid/properties/YoungAndroidButtonShapeChoicePropertyEditor.java @DefaultMessage("default") @Description("Text for button shape choice 'default'") String defaultButtonShape(); @DefaultMessage("rounded") @Description("Text for button shape choice 'rounded'") String roundedButtonShape(); @DefaultMessage("rectangular") @Description("Text for button shape choice 'rectangular'") String rectButtonShape(); @DefaultMessage("oval") @Description("Text for button shape choice 'oval'") String ovalButtonShape(); // Used in editor/youngandroid/properties/YoungAndroidAssetSelectorPropertyEditor.java @DefaultMessage("You must select an asset!") @Description("Message displayed when OK button is clicked when there is no asset selected.") String noAssetSelected(); // Used in editor/youngandroid/properties/YoungAndroidComponentSelectorPropertyEditor.java @DefaultMessage("You must select a component!") @Description("Message displayed when OK button is clicked when there is no component selected.") String noComponentSelected(); // Used in editor/youngandroid/properties/YoungAndroidColorChoicePropertyEditor.java @DefaultMessage("None") @Description("Text for color choice 'None'") String noneColor(); @DefaultMessage("Black") @Description("Text for color choice 'Black'") String blackColor(); @DefaultMessage("Blue") @Description("Text for color choice 'Blue'") String blueColor(); @DefaultMessage("Cyan") @Description("Text for color choice 'Cyan'") String cyanColor(); @DefaultMessage("Default") @Description("Text for color choice 'Default'") String defaultColor(); @DefaultMessage("Dark Gray") @Description("Text for color choice 'Dark Gray'") String darkGrayColor(); @DefaultMessage("Gray") @Description("Text for color choice 'Gray'") String grayColor(); @DefaultMessage("Green") @Description("Text for color choice 'Green'") String greenColor(); @DefaultMessage("Light Gray") @Description("Text for color choice 'Light Gray'") String lightGrayColor(); @DefaultMessage("Magenta") @Description("Text for color choice 'Magenta'") String magentaColor(); @DefaultMessage("Orange") @Description("Text for color choice 'Orange'") String orangeColor(); @DefaultMessage("Pink") @Description("Text for color choice 'Pink'") String pinkColor(); @DefaultMessage("Red") @Description("Text for color choice 'Red'") String redColor(); @DefaultMessage("White") @Description("Text for color choice 'White'") String whiteColor(); @DefaultMessage("Yellow") @Description("Text for color choice 'Yellow'") String yellowColor(); // Used in editor/youngandroid/properties/YoungAndroidFontTypefaceChoicePropertyEditor.java @DefaultMessage("default") @Description("Text for font typeface choice 'default '") String defaultFontTypeface(); @DefaultMessage("sans serif") @Description("Text for font typeface choice 'sans serif '") String sansSerifFontTypeface(); @DefaultMessage("serif") @Description("Text for font typeface choice 'serif '") String serifFontTypeface(); @DefaultMessage("monospace") @Description("Text for font typeface choice 'monospace '") String monospaceFontTypeface(); // Used in editor/youngandroid/properties/YoungAndroidLengthPropertyEditor.java @DefaultMessage("Automatic") @Description("Caption and summary for Automatic choice") String automaticCaption(); @DefaultMessage("Fill parent") @Description("Caption and summary for Fill Parent choice") String fillParentCaption(); @DefaultMessage("DP") // DP - Density Independent Pixels @Description("Caption for DPs label") String dpsCaption(); @DefaultMessage("{0} DPs") @Description("Summary for custom length in DPs") String dpsSummary(String dps); @DefaultMessage("The value must be a number greater than or equal to 0") @Description("Error shown after validation of custom length field failed.") String nonnumericInputError(); // Used in editor/youngandroid/properties/YoungAndroidScreenAnimationChoicePropertyEditor.java @DefaultMessage("Default") @Description("Text for screen animation choice 'Default '") String defaultScreenAnimation(); @DefaultMessage("Fade") @Description("Text for screen animation choice 'Fade '") String fadeScreenAnimation(); @DefaultMessage("Zoom") @Description("Text for screen animation choice 'Zoom '") String zoomScreenAnimation(); @DefaultMessage("SlideHorizontal") @Description("Text for screen animation choice 'SlideHorizontal '") String slideHorizontalScreenAnimation(); @DefaultMessage("SlideVertical") @Description("Text for screen animation choice 'SlideVertical '") String slideVerticalScreenAnimation(); @DefaultMessage("None") @Description("Text for screen animation choice 'None '") String noneScreenAnimation(); // Used in editor/youngandroid/properties/YoungAndroidScreenOrientationChoicePropertyEditor.java @DefaultMessage("Unspecified") @Description("Text for screen orientation choice 'Unspecified '") String unspecifiedScreenOrientation(); @DefaultMessage("Portrait") @Description("Text for screen orientation choice 'Portrait '") String portraitScreenOrientation(); @DefaultMessage("Landscape") @Description("Text for screen orientation choice 'Landscape '") String landscapeScreenOrientation(); @DefaultMessage("Sensor") @Description("Text for screen orientation choice 'Sensor '") String sensorScreenOrientation(); @DefaultMessage("User") @Description("Text for screen orientation choice 'User '") String userScreenOrientation(); // Used in editor/youngandroid/properties/YoungAndroidToastLengthChoicePropertyEditor.java @DefaultMessage("Short") @Description("Show toast for a Toast_Short of time") String shortToastLength(); @DefaultMessage("Long") @Description("Show toast for a Toast_Long of time") String longToastLength(); // Used in explorer/SourceStructureExplorer.java @DefaultMessage("Rename") @Description("Label of the button for rename") String renameButton(); // Used in explorer/commands/AddFormCommand.java @DefaultMessage("Add") @Description("Text on 'Add' button to continue with screen creation.") String addScreenButton(); @DefaultMessage("Do Not Add") @Description("Text on 'Dont Add' button to dismiss screen creation.") String cancelScreenButton(); @DefaultMessage("New Screen") @Description("Title of new Screen dialog.") String newFormTitle(); @DefaultMessage("Screen name:") @Description("Label in front of name in new screen dialog.") String formNameLabel(); @DefaultMessage("WARNING: The number of screens in this app might exceed the limits of App Inventor. " + "Click <a target=\"_blank\" href=\"/reference/other/manyscreens.html\">here</a> for advice about " + "creating apps with many screens. " + "<p>Do you really want to add another screen?</p>") @Description("Label to indicate the application has too many screens.") String formCountErrorLabel(); @DefaultMessage("Screen names can contain only letters, numbers, and underscores and must " + "start with a letter") @Description("Error message when form name contains non-alphanumeric characters besides _") String malformedFormNameError(); @DefaultMessage("Duplicate Screen name!") @Description("Error shown when a new form name would be the same as an existing one") String duplicateFormNameError(); @DefaultMessage("Server error: could not add form. Please try again later!") @Description("Error message reported when adding a form failed on the server.") String addFormError(); // Used in explorer/commands/BuildCommand.java, and // explorer/commands/WaitForBuildResultCommand.java @DefaultMessage("Build of {0} requested at {1}.") @Description("Message shown in the build output panel when a build is requested.") String buildRequestedMessage(String projectName, String time); @DefaultMessage("Server error: could not build target. Please try again later!") @Description("Error message reported when building a target failed on the server because of a " + "network error.") String buildError(); @DefaultMessage("Build failed!") @Description("Error message reported when a build failed due to an error in the build pipeline.") String buildFailedError(); @DefaultMessage("The build server is currently busy. Please try again in a few minutes.") @Description("Error message reported when the build server is temporarily too busy to accept " + "a build request.") String buildServerBusyError(); @DefaultMessage("The build server is not compatible with this version of App Inventor.") @Description("Error message reported when the build server is running a different version of " + "the App Inventor code.") String buildServerDifferentVersion(); @DefaultMessage("Unable to generate code for {0}.") @Description("Message displayed when an error occurs while generating YAIL for a form.") String errorGeneratingYail(String formName); // Used in explorer/commands/CommandRegistory.java @DefaultMessage("Delete...") @Description("Label for the context menu command that deletes a file") String deleteFileCommand(); @DefaultMessage("Download to my computer") @Description("Label for the context menu command that downloads a file") String downloadFileCommand(); // Used in explorer/commands/CopyYoungAndroidProjectCommand.java @DefaultMessage("Checkpoint - {0}") @Description("Title of checkpoint dialog.") String checkpointTitle(String projectName); @DefaultMessage("Save As - {0}") @Description("Title of save as dialog.") String saveAsTitle(String projectName); @DefaultMessage("{0}_checkpoint{1}") @Description("Default project name in checkoint dialog") String defaultCheckpointProjectName(String projectName, String suffix); @DefaultMessage("Previous checkpoints:") @Description("Label for previous checkpoints table in checkpoint dialog.") String previousCheckpointsLabel(); @DefaultMessage("{0}_copy") @Description("Defaulf project name in save as dialog") String defaultSaveAsProjectName(String projectName); @DefaultMessage("Checkpoint name:") @Description("Label in front of new name in checkpoint dialog.") String checkpointNameLabel(); @DefaultMessage("Server error: could not copy project. Please try again later!") @Description("Error message reported when copying a project failed on the server.") String copyProjectError(); // Used in explorer/commands/DeleteFileCommand.java @DefaultMessage("Do you really want to delete this file? It will be removed from " + "the App Inventor server. Also, parts of your application may still refer to the deleted " + "file, and you will need to change these.") @Description("Confirmation message that will be shown before deleting a file") String reallyDeleteFile(); @DefaultMessage("Server error: could not delete the file. Please try again later!") @Description("Error message reported when deleting a file failed on the server.") String deleteFileError(); // Used in explorer/commands/EnsurePhoneConnectedCommand.java @DefaultMessage("The phone is not connected.") @Description("Error message displayed when the user wants to download a project to the phone, " + "but the phone is not connected.") String phoneNotConnected(); // Used in explorer/commands/ShowBarcodeCommand.java @DefaultMessage("Barcode link for {0}") @Description("Title of barcode dialog.") String barcodeTitle(String projectName); @DefaultMessage("Note: this barcode is only valid for 2 hours. See {0} the FAQ {1} for info " + "on how to share your app with others.") @Description("Warning in barcode dialog.") String barcodeWarning(String aTagStart, String aTagEnd); // Used in explorer/project/Project.java @DefaultMessage("Server error: could not load project. Please try again later!") @Description("Error message reported when a project could not be loaded from the server.") String projectLoadError(); // Used in explorer/project/ProjectManager.java @DefaultMessage("Server error: could not retrieve project information. Please try again later!") @Description("Error message reported when information about projects could not be retrieved " + "from the server.") String projectInformationRetrievalError(); // Used in explorer/youngandroid/Toolbar.java @DefaultMessage("It may take a little while for your projects to be downloaded. " + "Please be patient...") @Description("Warning that downloading projects will take a while") String downloadAllAlert(); @DefaultMessage("More Actions") @Description("Label of the button leading to more cascade items") String moreActionsButton(); @DefaultMessage("Download User Source") @Description("Title of the dialog box for downloading a user's project source") String downloadUserSourceDialogTitle(); @DefaultMessage("User id or email (case-sensitive):") @Description("Label for the user id input text box") String userIdLabel(); @DefaultMessage("Project id or name:") @Description("Label for the project id input text box") String projectIdLabel(); @DefaultMessage("Please specify both a user email address or id and a project name or id " + "for the project to be downloaded. Ids are numeric and may come from the system " + "logs or from browsing the Datastore. If you use an email address, it must match " + "exactly the stored email address in the Datastore. Similarly, project names must " + "match exactly. Both are case sensitive.") @Description("Error message reported when user id or project id is missing") String invalidUserIdOrProjectIdError(); @DefaultMessage("Please select a project to delete") @Description("Error message displayed when no project is selected") String noProjectSelectedForDelete(); @DefaultMessage("Are you really sure you want to delete this project: {0}") @Description("Confirmation message for selecting a single project and clicking delete") String confirmDeleteSingleProject(String projectName); @DefaultMessage("Are you really sure you want to delete these projects: {0}") @Description("Confirmation message for selecting multiple projects and clicking delete") String confirmDeleteManyProjects(String projectNames); @DefaultMessage("Server error: could not delete project. Please try again later!") @Description("Error message reported when deleting a project failed on the server.") String deleteProjectError(); @DefaultMessage("One project must be selected") @Description("Error message displayed when no or many projects are selected") String wrongNumberProjectsSelected(); @DefaultMessage("Server error: could not download your keystore file.") @Description("Error message displayed when a server error occurs during download keystore") String downloadKeystoreError(); @DefaultMessage("There is no keystore file to download.") @Description("Error message displayed when no keystore file exists") String noKeystoreToDownload(); @DefaultMessage("Server error: could not upload your keystore file.") @Description("Error message displayed when a server error occurs during upload keystore") String uploadKeystoreError(); @DefaultMessage("Do you want to overwrite your keystore file?\n\n" + "If you agree, your old keystore file will be completely removed from the App Inventor " + "server.\n\n" + "If you have published applications to the Google Play Store using the keystore you are " + "about to overwrite, you will lose the ability to update your applications.\n\n" + "Any projects that you package in the future will be signed using your new keystore file. " + "Changing the keystore affects the ability to reinstall previously installed apps. If you " + "are not sure that you want to do this, please read the documentation about keystores by " + "clicking above on \"Learn\", then \"Troubleshooting\", and then \"Keystores and Signing " + "of Applications\"\n\n" + "There is no undo for overwriting your keystore file.") @Description("Confirmation message shown when keystore is about to be overwritten.") String confirmOverwriteKeystore(); @DefaultMessage("Server error: could not delete your keystore file.") @Description("Error message reported when a server error occurs during delete keystore") String deleteKeystoreError(); @DefaultMessage("Do you really want to delete your keystore file?\n\n" + "If you agree, your old keystore file will be completely removed from the App Inventor " + "server. A new, but different, keystore file will be created automatically the next time " + "you package a project for the phone.\n\n" + "If you have published applications to the Google Play Store using the keystore you are " + "about to delete, you will lose the ability to update your applications.\n\n" + "Any projects that you package in the future will be signed using your new keystore file. " + "Changing the keystore affects the ability to reinstall previously installed apps. If you " + "are not sure that you want to do this, please read the documentation about keystores by " + "clicking above on \"Learn\", then \"Troubleshooting\", and then \"Keystores and Signing " + "of Applications\"\n\n" + "There is no undo for deleting your keystore file.") @Description("Confirmation message for delete keystore") String confirmDeleteKeystore(); // Used in output/OdeLog.java @DefaultMessage("Clear") @Description("Text on 'Clear' button") String clearButton(); // Used in settings/CommonSettings.java, settings/project/ProjectSettings.java, and // settings/user/UserSettings.java @DefaultMessage("Server error: could not load settings. Please try again later!") @Description("Error message reported when the settings couldn't be loaded from the server.") String settingsLoadError(); @DefaultMessage("Server error: could not save settings. Please try again later!") @Description("Error message reported when the settings couldn't be saved to the server.") String settingsSaveError(); // Used in widgets/boxes/Box.java @DefaultMessage("Done") @Description("Caption for button to finish the box resizing dialog.") String done(); @DefaultMessage("Close") @Description("Tool tip text for header icon for closing/removing a minimized box.") String hdrClose(); @DefaultMessage("Shrink") @Description("Tool tip text for header icon for minimizing the box.") String hdrMinimize(); @DefaultMessage("Settings") @Description("Tool tip text for header icon for context menu of box.") String hdrSettings(); @DefaultMessage("Shrink") @Description("Caption for context menu item for minimizing the box.") String cmMinimize(); @DefaultMessage("Expand") @Description("Caption for context menu item for restoring a minimized box.") String cmRestore(); @DefaultMessage("Resize...") @Description("Caption for context menu item for resizing the box.") String cmResize(); @DefaultMessage("Expand") @Description("Tool tip text for header icon for restoring a minimized box.") String hdrRestore(); // Used in widgets/properties/FloatPropertyEditor.java @DefaultMessage("{0} is not a legal number") @Description("Error shown after validation of float failed.") String notAFloat(String nonNumericText); // Used in widgets/properties/IntegerPropertyEditor.java @DefaultMessage("{0} is not a legal integer") @Description("Error shown after validation of integer failed.") String notAnInteger(String nonNumericText); // Used in widgets/properties/TextPropertyEditor.java @DefaultMessage("Malformed input!") @Description("Error shown after validation of input text failed.") String malformedInputError(); // Used in wizards/FileUploadWizard.java @DefaultMessage("Upload File ...") @Description("Caption for file upload wizard.") String fileUploadWizardCaption(); @DefaultMessage("File names can contain only unaccented letters, numbers, and the characters " + "\"-\", \"_\", \".\", \"!\", \"~\", \"*\", \"(\", and \")\"") @Description("Error message when file name contains characters that would require URL encoding.") String malformedFilename(); @DefaultMessage("File names must be between 1 and 100 characters.") @Description("Error message when filenames are 0 or 101+ characters long") String filenameBadSize(); @DefaultMessage("Uploading {0} to the App Inventor server") @Description("Message displayed when an asset is uploaded.") String fileUploadingMessage(String filename); @DefaultMessage("Server error: could not upload file. Please try again later!") @Description("Error message reported when a file couldn't be uploaded to the server.") String fileUploadError(); @DefaultMessage("Error: could not upload file because it is too large") @Description("Error message reported when a file couldn't be uploaded because of its size.") String fileTooLargeError(); @DefaultMessage("Please select a file to upload.") @Description("Error message reported when a file was not selected.") String noFileSelected(); @DefaultMessage("Request to save {1}" + "\n\nA file named {0} already exists in this project." + "\nDo you want to remove that old file?" + "\nThis will also remove any other files whose " + "names conflict with {1}.") @Description("Confirmation message shown when conflicting files are about to be deleted.") String confirmOverwrite(String newFile, String existingFile); // Used in wizards/KeystoreUploadWizard.java @DefaultMessage("Upload Keystore...") @Description("Caption for keystore upload wizard.") String keystoreUploadWizardCaption(); @DefaultMessage("Server error: could not upload keystore. Please try again later!") @Description("Error message reported when the keystore couldn't be uploaded to the server.") String keystoreUploadError(); @DefaultMessage("The selected file is not a keystore!") @Description("Error message reported when the file selected for upload is not a keystore.") String notKeystoreError(); // Used in wizards/NewProjectWizard.java @DefaultMessage("Server error: could not create project. Please try again later!") @Description("Error message reported when the project couldn't be created on the server.") String createProjectError(); // Used in wizards/TemplateUploadWizard.java @DefaultMessage("Create a Project from a Template") @Description("Caption for template upload wizard.") String templateUploadWizardCaption(); @DefaultMessage("Add a New Template Library Url") @Description("Caption for template dialog menu item.") String templateUploadNewUrlCaption(); @DefaultMessage("Input a Url...") @Description("Caption for input template url wizard.") String inputNewUrlCaption(); @DefaultMessage("Templates Url: ") @Description("Label for template url wizard.") String newUrlLabel(); // Used in wizards/ProjectUploadWizard.java @DefaultMessage("Import Project...") @Description("Caption for project upload wizard.") String projectUploadWizardCaption(); @DefaultMessage("Server error: could not upload project. Please try again later!") @Description("Error message reported when a project couldn't be uploaded to the server.") String projectUploadError(); @DefaultMessage("The selected project is not a project source file!\n" + "Project source files are aia files.") @Description("Error message reported when the file selected for upload is not a project archive.") String notProjectArchiveError(); // Used in wizards/Wizard.java @DefaultMessage("Back") @Description("Text on 'Back' button to go back to the previous page of the wizard.") String backButton(); @DefaultMessage("Next") @Description("Text on 'Next' button to proceed to the next page of the wizard.") String nextButton(); // Used in wizards/youngandroid/NewYoungAndroidProjectWizard.java @DefaultMessage("Create new App Inventor project") @Description("Caption for the wizard to create a new Young Android project") String newYoungAndroidProjectWizardCaption(); @DefaultMessage("Project name:") @Description("Label for the project name input text box") String projectNameLabel(); // Used in youngandroid/TextValidators.java @DefaultMessage("Project names must start with a letter and can contain only letters, " + "numbers, and underscores") @Description("Error message when project name does not start with a letter or contains a " + "character that is not a letter, number, or underscore.") String malformedProjectNameError(); @DefaultMessage("{0} already exists. You cannot create another project with the same name.") @Description("Error shown when a new project name would be the same as an existing one") String duplicateProjectNameError(String projectName); // Used in youngandroid/YoungAndroidFormUpgrader.java @DefaultMessage("This project was created with an older version of the App Inventor " + "system and was upgraded.\n{0}") @Description("Alert message displayed when a project is upgraded") String projectWasUpgraded(String details); @DefaultMessage("A problem occurred while loading this project. {0}") @Description("Alert message displayed when upgrade fails") String unexpectedProblem(String details); @DefaultMessage("This project was saved with a newer version of the App Inventor system. We " + "will attempt to load the project, but there may be compatibility issues.") @Description("Alert message displayed when project is newer than system") String newerVersionProject(); @DefaultMessage("This project was saved with an early pre-release version of the App Inventor " + "system. We will attempt to load the project, but there may be compatibility issues.") @Description("Alert message displayed when upgrading a project without version numbers") String veryOldProject(); @DefaultMessage("The Logger component named {0} was changed to a Notifier component.\n") @Description("Message providing details about a project upgrade involving a Logger component") String upgradeDetailLoggerReplacedWithNotifier(String name); @DefaultMessage("Unable to load project with {0} version {1} (maximum known version is {2}).") @Description("Exception message used when a project contains a newer version component than " + "the version known by the system") String newerVersionComponentException(String componentType, int srcCompVersion, int sysCompVersion); @DefaultMessage("No upgrade strategy exists for {0} from version {1} to {2}.") @Description("Exception message used when a component was not upgraded") String noUpgradeStrategyException(String componentType, int srcCompVersion, int sysCompVersion); // Used in client/editor/simple/components/MockHVarrangement.java @DefaultMessage("System error: bad alignment property editor for horizontal or vertical arrangement.") @Description("System error message for a bad alignment property editor") String badAlignmentPropertyEditorForArrangement(); // Used in // editor/youngandroid/properties/YoungAndroidTextReceivingPropertyEditor.java @DefaultMessage("Off") @Description("Text Messages are not received at any time.") String textReceivingChoiceOff(); @DefaultMessage("Foreground") @Description("Text Messages are received only when the App is in the foreground.") String textReceivingChoiceForeground(); @DefaultMessage("Always") @Description("Text messages are always received, and a notification is shown if the App is in the background.") String textReceivingChoiceAlways(); // This error message is displayed as HTML @DefaultMessage("App Inventor is unable to compile this project. " + "<br /> The compiler error output was <br /> {0}.") @Description("Compilation error, with error message.") String unableToCompile(String errorMesssage); // This error message is displayed as HTML @DefaultMessage("User Interface") @Description("") String UIComponentPallette(); @DefaultMessage("Layout") @Description("") String layoutComponentPallette(); @DefaultMessage("Media") @Description("") String mediaComponentPallette(); @DefaultMessage("Drawing and Animation") @Description("") String drawanimationComponentPallette(); @DefaultMessage("Sensors") @Description("") String sensorsComponentPallette(); @DefaultMessage("Social") @Description("") String socialComponentPallette(); @DefaultMessage("Storage") @Description("") String storageComponentPallette(); @DefaultMessage("Form") @Description("") String FormComponentPallette(); @DefaultMessage("Math") @Description("Label on built-in-Math-blocks branch of block selector tree") String builtinMathLabel(); @DefaultMessage("Connectivity") @Description("") String connectivityComponentPallette(); @DefaultMessage("LEGO\u00AE MINDSTORMS\u00AE") @Description("") String legoComponentPallette(); @DefaultMessage("Experimental") @Description("") String experimentalComponentPallette(); @DefaultMessage("For internal use only") @Description("") String internalUseComponentPallette(); @DefaultMessage("Uninitialized") @Description("") String uninitializedComponentPallette(); // UI Pallette @DefaultMessage("Button") @Description("") String buttonComponentPallette(); @DefaultMessage("Canvas") @Description("") String canvasComponentPallette(); @DefaultMessage("CheckBox") @Description("") String checkBoxComponentPallette(); @DefaultMessage("Clock") @Description("") String clockComponentPallette(); @DefaultMessage("DatePicker") @Description("") String datePickerComponentPallette(); @DefaultMessage("Image") @Description("") String imageComponentPallette(); @DefaultMessage("Label") @Description("") String labelComponentPallette(); @DefaultMessage("ListPicker") @Description("") String listPickerComponentPallette(); @DefaultMessage("ListView") @Description("") String listViewComponentPallette(); @DefaultMessage("PasswordTextBox") @Description("") String passwordTextBoxComponentPallette(); @DefaultMessage("Slider") @Description("") String sliderComponentPallette(); @DefaultMessage("Spinner") @Description("") String spinnerComponentPallette(); @DefaultMessage("TextBox") @Description("") String textBoxComponentPallette(); @DefaultMessage("timePicker") @Description("") String timePickerComponentPallette(); @DefaultMessage("TinyDB") @Description("") String tinyDBComponentPallette(); // Media Pallette @DefaultMessage("Camcorder") @Description("") String camcorderComponentPallette(); @DefaultMessage("Camera") @Description("") String cameraComponentPallette(); @DefaultMessage("ImagePicker") @Description("") String imagePickerComponentPallette(); @DefaultMessage("Player") @Description("") String playerComponentPallette(); @DefaultMessage("Sound") @Description("") String soundComponentPallette(); @DefaultMessage("VideoPlayer") @Description("") String videoPlayerComponentPallette(); @DefaultMessage("YandexTranslate") @Description("") String yandexTranslateComponentPallette(); // Animation @DefaultMessage("Ball") @Description("") String ballComponentPallette(); @DefaultMessage("ImageSprite") @Description("") String imageSpriteComponentPallette(); // Social @DefaultMessage("ContactPicker") @Description("") String contactPickerComponentPallette(); @DefaultMessage("EmailPicker") @Description("") String emailPickerComponentPallette(); @DefaultMessage("PhoneCall") @Description("") String phoneCallComponentPallette(); @DefaultMessage("PhoneNumberPicker") @Description("") String phoneNumberPickerComponentPallette(); @DefaultMessage("Sharing") @Description("") String sharingComponentPallette(); @DefaultMessage("Texting") @Description("") String textingComponentPallette(); @DefaultMessage("Twitter") @Description("") String twitterComponentPallette(); // Sensor @DefaultMessage("AccelerometerSensor") @Description("") String accelerometerSensorComponentPallette(); @DefaultMessage("BarcodeScanner") @Description("") String barcodeScannerComponentPallette(); @DefaultMessage("LocationSensor") @Description("") String locationSensorComponentPallette(); @DefaultMessage("NearField") @Description("") String nearFieldComponentPallette(); @DefaultMessage("OrientationSensor") @Description("") String orientationSensorComponentPallette(); // Screen Arrangement @DefaultMessage("HorizontalArrangement") @Description("") String horizontalArrangementComponentPallette(); @DefaultMessage("TableArrangement") @Description("") String tableArrangementComponentPallette(); @DefaultMessage("VerticalArrangement") @Description("") String verticalArrangementComponentPallette(); // Lego Mindstorms @DefaultMessage("NxtColorSensor") @Description("") String nxtColorSensorComponentPallette(); @DefaultMessage("NxtDirectCommands") @Description("") String nxtDirectCommandsComponentPallette(); @DefaultMessage("NxtDrive") @Description("") String nxtDriveComponentPallette(); @DefaultMessage("NxtLightSensor") @Description("") String nxtLightSensorComponentPallette(); @DefaultMessage("NxtSoundSensor") @Description("") String nxtSoundSensorComponentPallette(); @DefaultMessage("NxtTouchSensor") @Description("") String nxtTouchSensorComponentPallette(); @DefaultMessage("NxtUltrasonicSensor") @Description("") String nxtUltrasonicSensorComponentPallette(); // Storage @DefaultMessage("ActivityStarter") @Description("") String activityStarterComponentPallette(); @DefaultMessage("BluetoothClient") @Description("") String bluetoothClientComponentPallette(); @DefaultMessage("BluetoothServer") @Description("") String bluetoothServerComponentPallette(); @DefaultMessage("Notifier") @Description("") String notifierComponentPallette(); @DefaultMessage("SpeechRecognizer") @Description("") String speechRecognizerComponentPallette(); @DefaultMessage("TextToSpeech") @Description("") String textToSpeechComponentPallette(); @DefaultMessage("TinyWebDB") @Description("") String tinyWebDBComponentPallette(); @DefaultMessage("Web") @Description("") String webComponentPallette(); // Connectivity @DefaultMessage("File") @Description("") String fileComponentPallette(); @DefaultMessage("FusiontablesControl") @Description("") String fusiontablesControlComponentPallette(); @DefaultMessage("GameClient") @Description("") String gameClientComponentPallette(); @DefaultMessage("SoundRecorder") @Description("") String soundRecorderComponentPallette(); @DefaultMessage("Voting") @Description("") String votingComponentPallette(); @DefaultMessage("WebViewer") @Description("") String webViewerComponentPallette(); // Component Properties @DefaultMessage("AboutScreen") @Description("") String AboutScreenProperties(); @DefaultMessage("AboveRangeEventEnabled") @Description("") String AboveRangeEventEnabledProperties(); @DefaultMessage("Action") @Description("") String ActionProperties(); @DefaultMessage("ActivityClass") @Description("") String ActivityClassProperties(); @DefaultMessage("ActivityPackage") @Description("") String ActivityPackageProperties(); @DefaultMessage("AlignHorizontal") @Description("") String AlignHorizontalProperties(); @DefaultMessage("AlignVertical") @Description("") String AlignVerticalProperties(); @DefaultMessage("AllowCookies") @Description("") String AllowCookiesProperties(); @DefaultMessage("ApiKey") @Description("") String ApiKeyProperties(); @DefaultMessage("BackgroundColor") @Description("") String BackgroundColorProperties(); @DefaultMessage("BackgroundImage") @Description("") String BackgroundImageProperties(); @DefaultMessage("BelowRangeEventEnabled") @Description("") String BelowRangeEventEnabledProperties(); @DefaultMessage("BluetoothClient") @Description("") String BluetoothClientProperties(); @DefaultMessage("BottomOfRange") @Description("") String BottomOfRangeProperties(); @DefaultMessage("CalibrateStrideLength") @Description("") String CalibrateStrideLengthProperties(); @DefaultMessage("CharacterEncoding") @Description("") String CharacterEncodingProperties(); @DefaultMessage("Checked") @Description("") String CheckedProperties(); @DefaultMessage("CloseScreenAnimation") @Description("") String CloseScreenAnimationProperties(); @DefaultMessage("ColorChangedEventEnabled") @Description("") String ColorChangedEventEnabledProperties(); @DefaultMessage("Columns") @Description("") String ColumnsProperties(); @DefaultMessage("ConsumerKey") @Description("") String ConsumerKeyProperties(); @DefaultMessage("ConsumerSecret") @Description("") String ConsumerSecretProperties(); @DefaultMessage("Country") @Description("") String CountryProperties(); @DefaultMessage("DataType") @Description("") String DataTypeProperties(); @DefaultMessage("DataUri") @Description("") String DataUriProperties(); @DefaultMessage("DelimiterByte") @Description("") String DelimiterByteProperties(); @DefaultMessage("DetectColor") @Description("") String DetectColorProperties(); @DefaultMessage("DistanceInterval") @Description("") String DistanceIntervalProperties(); @DefaultMessage("DriveMotors") @Description("") String DriveMotorsProperties(); @DefaultMessage("Enabled") @Description("") String EnabledProperties(); @DefaultMessage("ExtraKey") @Description("") String ExtraKeyProperties(); @DefaultMessage("ExtraValue") @Description("") String ExtraValueProperties(); @DefaultMessage("FollowLinks") @Description("") String FollowLinksProperties(); @DefaultMessage("FontBold") @Description("") String FontBoldProperties(); @DefaultMessage("FontItalic") @Description("") String FontItalicProperties(); @DefaultMessage("FontSize") @Description("") String FontSizeProperties(); @DefaultMessage("FontTypeface") @Description("") String FontTypefaceProperties(); @DefaultMessage("GameId") @Description("") String GameIdProperties(); @DefaultMessage("GenerateColor") @Description("") String GenerateColorProperties(); @DefaultMessage("GenerateLight") @Description("") String GenerateLightProperties(); @DefaultMessage("GoogleVoiceEnabled") @Description("") String GoogleVoiceEnabledProperties(); @DefaultMessage("Heading") @Description("") String HeadingProperties(); @DefaultMessage("HighByteFirst") @Description("") String HighByteFirstProperties(); @DefaultMessage("Hint") @Description("") String HintProperties(); @DefaultMessage("HomeUrl") @Description("") String HomeUrlProperties(); @DefaultMessage("Icon") @Description("") String IconProperties(); @DefaultMessage("Image") @Description("") String ImageProperties(); @DefaultMessage("Interval") @Description("") String IntervalProperties(); @DefaultMessage("IsLooping") @Description("") String IsLoopingProperties(); @DefaultMessage("KeyFile") @Description("") String KeyFileProperties(); @DefaultMessage("Language") @Description("") String LanguageProperties(); @DefaultMessage("LineWidth") @Description("") String LineWidthProperties(); @DefaultMessage("Message") @Description("") String MessageProperties(); @DefaultMessage("MinimumInterval") @Description("") String MinimumIntervalProperties(); @DefaultMessage("MultiLine") @Description("") String MultiLineProperties(); @DefaultMessage("NumbersOnly") @Description("") String NumbersOnlyProperties(); @DefaultMessage("OpenScreenAnimation") @Description("") String OpenScreenAnimationProperties(); @DefaultMessage("PaintColor") @Description("") String PaintColorProperties(); @DefaultMessage("PhoneNumber") @Description("") String PhoneNumberProperties(); @DefaultMessage("PhoneNumberList") @Description("") String PhoneNumberListProperties(); @DefaultMessage("Picture") @Description("") String PictureProperties(); @DefaultMessage("PressedEventEnabled") @Description("") String PressedEventEnabledProperties(); @DefaultMessage("PromptforPermission") @Description("") String PromptforPermissionProperties(); @DefaultMessage("Query") @Description("") String QueryProperties(); @DefaultMessage("Radius") @Description("") String RadiusProperties(); @DefaultMessage("ReadMode") @Description("") String ReadModeProperties(); @DefaultMessage("ReceivingEnabled") @Description("") String ReceivingEnabledProperties(); @DefaultMessage("ReleasedEventEnabled") @Description("") String ReleasedEventEnabledProperties(); @DefaultMessage("ResponseFileName") @Description("") String ResponseFileNameProperties(); @DefaultMessage("ResultName") @Description("") String ResultNameProperties(); @DefaultMessage("Rows") @Description("") String RowsProperties(); @DefaultMessage("SaveResponse") @Description("") String SaveResponseProperties(); @DefaultMessage("ScalePictureToFit") @Description("") String ScalePictureToFitProperties(); @DefaultMessage("SensorPort") @Description("") String SensorPortProperties(); @DefaultMessage("ScreenOrientation") @Description("") String ScreenOrientationProperties(); @DefaultMessage("Secure") @Description("") String SecureProperties(); @DefaultMessage("ServiceAccountEmail") @Description("") String ServiceAccountEmailProperties(); @DefaultMessage("ServiceURL") @Description("") String ServiceURLProperties(); @DefaultMessage("Scrollable") @Description("") String ScrollableProperties(); @DefaultMessage("Shape") @Description("") String ShapeProperties(); @DefaultMessage("ShowFeedback") @Description("") String ShowFeedbackProperties(); @DefaultMessage("show tables") @Description("") String ShowTablesProperties(); @DefaultMessage("Source") @Description("") String SourceProperties(); @DefaultMessage("Speed") @Description("") String SpeedProperties(); @DefaultMessage("StopBeforeDisconnect") @Description("") String StopBeforeDisconnectProperties(); @DefaultMessage("StopDetectionTimeout") @Description("") String StopDetectionTimeoutProperties(); @DefaultMessage("StrideLength") @Description("") String StrideLengthProperties(); @DefaultMessage("Text") @Description("") String TextProperties(); @DefaultMessage("TextAlignment") @Description("") String TextAlignmentProperties(); @DefaultMessage("TextColor") @Description("") String TextColorProperties(); @DefaultMessage("TimerAlwaysFires") @Description("") String TimerAlwaysFiresProperties(); @DefaultMessage("TimerEnabled") @Description("") String TimerEnabledProperties(); @DefaultMessage("TimerInterval") @Description("") String TimerIntervalProperties(); @DefaultMessage("Title") @Description("") String TitleProperties(); @DefaultMessage("TopOfRange") @Description("") String TopOfRangeProperties(); @DefaultMessage("Url") @Description("") String UrlProperties(); @DefaultMessage("UseFront") @Description("") String UseFrontProperties(); @DefaultMessage("UseGPS") @Description("") String UseGPSProperties(); @DefaultMessage("UseServiceAuthentication") @Description("") String UseServiceAuthenticationProperties(); @DefaultMessage("UsesLocationVisible") @Description("") String UsesLocationVisibleProperties(); @DefaultMessage("VersionCode") @Description("") String VersionCodeProperties(); @DefaultMessage("VersionName") @Description("") String VersionNameProperties(); @DefaultMessage("Visible") @Description("") String VisibleProperties(); @DefaultMessage("Volume") @Description("") String VolumeProperties(); @DefaultMessage("WheelDiameter") @Description("") String WheelDiameterProperties(); @DefaultMessage("WithinRangeEventEnabled") @Description("") String WithinRangeEventEnabledProperties(); @DefaultMessage("X") @Description("") String XProperties(); @DefaultMessage("Y") @Description("") String YProperties(); @DefaultMessage("Z") @Description("") String ZProperties(); @DefaultMessage("showing") @Description("") String VisibilityShowingProperties(); @DefaultMessage("hidden") @Description("") String VisibilityHiddenProperties(); @DefaultMessage("ElementsFromString") @Description("") String ElementsFromStringProperties(); @DefaultMessage("Rotates") @Description("") String RotatesProperties(); @DefaultMessage("Selection") @Description("") String SelectionProperties(); @DefaultMessage("TimeInterval") @Description("") String TimeIntervalProperties(); @DefaultMessage("UsesLocation") @Description("") String UsesLocationProperties(); @DefaultMessage("ShowFilterBar") @Description("") String ShowFilterBarProperties(); @DefaultMessage("NotifierLength") @Description("") String NotifierLengthProperties(); @DefaultMessage("Loop") @Description("") String LoopProperties(); @DefaultMessage("Pitch") @Description("") String PitchProperties(); @DefaultMessage("SpeechRate") @Description("") String SpeechRateProperties(); @DefaultMessage("Sensitivity") @Description("") String SensitivityProperties(); @DefaultMessage("TwitPic_API_Key") @Description("") String TwitPic_API_KeyProperties(); @DefaultMessage("Prompt") @Description("") String PromptProperties(); @DefaultMessage("ColorLeft") @Description("") String ColorLeftProperties(); @DefaultMessage("ColorRight") @Description("") String ColorRightProperties(); @DefaultMessage("MaxValue") @Description("") String MaxValueProperties(); @DefaultMessage("MinValue") @Description("") String MinValueProperties(); @DefaultMessage("ThumbPosition") @Description("") String ThumbPositionProperties(); @DefaultMessage("Day") @Description("") String DayProperties(); @DefaultMessage("Month") @Description("") String MonthProperties(); @DefaultMessage("MonthInText") @Description("") String MonthInTextProperties(); @DefaultMessage("Year") @Description("") String YearProperties(); @DefaultMessage("LastMessage") @Description("") String LastMessageProperties(); @DefaultMessage("TextToWrite") @Description("") String TextToWriteProperties(); @DefaultMessage("WriteType") @Description("") String WriteTypeProperties(); @DefaultMessage("ElapsedTime") @Description("") String ElapsedTimeProperties(); @DefaultMessage("Moving") @Description("") String MovingProperties(); @DefaultMessage("Hour") @Description("") String HourProperties(); @DefaultMessage("Minute") @Description("") String MinuteProperties(); @DefaultMessage("Distance") @Description("") String DistanceProperties(); @DefaultMessage("DirectMessages") @Description("") String DirectMessagesProperties(); @DefaultMessage("ContactName") @Description("") String ContactNameProperties(); @DefaultMessage("CurrentAddress") @Description("") String CurrentAddressProperties(); @DefaultMessage("CurrentPageTitle") @Description("") String CurrentPageTitleProperties(); @DefaultMessage("CurrentUrl") @Description("") String CurrentUrlProperties(); @DefaultMessage("Accuracy") @Description("") String AccuracyProperties(); @DefaultMessage("AddressesAndNames") @Description("") String AddressesAndNamesProperties(); @DefaultMessage("Altitude") @Description("") String AltitudeProperties(); @DefaultMessage("Angle") @Description("") String AngleProperties(); @DefaultMessage("Animation") @Description("") String AnimationProperties(); @DefaultMessage("Available") @Description("") String AvailableProperties(); @DefaultMessage("AvailableProviders") @Description("") String AvailableProvidersProperties(); @DefaultMessage("Azimuth") @Description("") String AzimuthProperties(); @DefaultMessage("BallotOptions") @Description("") String BallotOptionsProperties(); @DefaultMessage("BallotQuestion") @Description("") String BallotQuestionProperties(); @DefaultMessage("EmailAddress") @Description("") String EmailAddressProperties(); @DefaultMessage("EmailAddressList") @Description("") String EmailAddressListProperties(); @DefaultMessage("Elements") @Description("") String ElementsProperties(); @DefaultMessage("Followers") @Description("") String FollowersProperties(); @DefaultMessage("FriendTimeline") @Description("") String FriendTimelineProperties(); @DefaultMessage("FullScreen") @Description("") String FullScreenProperties(); @DefaultMessage("HasAccuracy") @Description("") String HasAccuracyProperties(); @DefaultMessage("HasAltitude") @Description("") String HasAltitudeProperties(); @DefaultMessage("HasLongitudeLatitude") @Description("") String HasLongitudeLatitudeProperties(); @DefaultMessage("Height") @Description("") String HeightProperties(); @DefaultMessage("InstanceId") @Description("") String InstanceIdProperties(); @DefaultMessage("InvitedInstances") @Description("") String InvitedInstancesProperties(); @DefaultMessage("IsAccepting") @Description("") String IsAcceptingProperties(); @DefaultMessage("IsConnected") @Description("") String IsConnectedProperties(); @DefaultMessage("IsPlaying") @Description("") String IsPlayingProperties(); @DefaultMessage("JoinedInstances") @Description("") String JoinedInstancesProperties(); @DefaultMessage("Latitude") @Description("") String LatitudeProperties(); @DefaultMessage("Leader") @Description("") String LeaderProperties(); @DefaultMessage("Longitude") @Description("") String LongitudeProperties(); @DefaultMessage("Magnitude") @Description("") String MagnitudeProperties(); @DefaultMessage("Mentions") @Description("") String MentionsProperties(); @DefaultMessage("ProviderLocked") @Description("") String ProviderLockedProperties(); @DefaultMessage("ProviderName") @Description("") String ProviderNameProperties(); @DefaultMessage("PublicInstances") @Description("") String PublicInstancesProperties(); @DefaultMessage("PlayOnlyInForeground") @Description("") String PlayOnlyInForegroundProperties(); @DefaultMessage("Players") @Description("") String PlayersProperties(); @DefaultMessage("RequestHeaders") @Description("") String RequestHeadersProperties(); @DefaultMessage("Result") @Description("") String ResultProperties(); @DefaultMessage("ResultType") @Description("") String ResultTypeProperties(); @DefaultMessage("ResultUri") @Description("") String ResultUriProperties(); @DefaultMessage("Roll") @Description("") String RollProperties(); @DefaultMessage("SearchResults") @Description("") String SearchResultsProperties(); @DefaultMessage("ServiceUrl") @Description("") String ServiceUrlProperties(); @DefaultMessage("SelectionIndex") @Description("") String SelectionIndexProperties(); @DefaultMessage("UserChoice") @Description("") String UserChoiceProperties(); @DefaultMessage("UserEmailAddress") @Description("") String UserEmailAddressProperties(); @DefaultMessage("UserId") @Description("") String UserIdProperties(); @DefaultMessage("Username") @Description("") String UsernameProperties(); @DefaultMessage("XAccel") @Description("") String XAccelProperties(); @DefaultMessage("YAccel") @Description("") String YAccelProperties(); @DefaultMessage("ZAccel") @Description("") String ZAccelProperties(); @DefaultMessage("Width") @Description("") String WidthProperties(); @DefaultMessage("WebViewString") @Description("") String WebViewStringProperties(); //Params @DefaultMessage("xAccel") @Description("") String xAccelParams(); @DefaultMessage("yAccel") @Description("") String yAccelParams(); @DefaultMessage("zAccel") @Description("") String zAccelParams(); @DefaultMessage("result") @Description("") String resultParams(); @DefaultMessage("other") @Description("") String otherParams(); @DefaultMessage("component") @Description("") String componentParams(); @DefaultMessage("startX") @Description("") String startXParams(); @DefaultMessage("startY") @Description("") String startYParams(); @DefaultMessage("prevX") @Description("") String prevXParams(); @DefaultMessage("prevY") @Description("") String prevYParams(); @DefaultMessage("currentX") @Description("") String currentXParams(); @DefaultMessage("currentY") @Description("") String currentYParams(); @DefaultMessage("edge") @Description("") String edgeParams(); @DefaultMessage("speed") @Description("") String speedParams(); @DefaultMessage("heading") @Description("") String headingParams(); @DefaultMessage("xvel") @Description("") String xvelParams(); @DefaultMessage("yvel") @Description("") String yvelParams(); @DefaultMessage("target") @Description("") String targetParams(); @DefaultMessage("address") @Description("") String addressParams(); @DefaultMessage("uuid") @Description("") String uuidParams(); @DefaultMessage("numberOfBytes") @Description("") String numberOfBytesParams(); @DefaultMessage("number") @Description("") String numberParams(); @DefaultMessage("list") @Description("") String listParams(); @DefaultMessage("text") @Description("") String textParams(); @DefaultMessage("clip") @Description("") String clipParams(); @DefaultMessage("image") @Description("") String imageParams(); @DefaultMessage("draggedSprite") @Description("") String draggedSpriteParams(); @DefaultMessage("flungSprite") @Description("") String flungSpriteParams(); @DefaultMessage("touchedSprite") @Description("") String touchedSpriteParams(); @DefaultMessage("x") @Description("") String xParams(); @DefaultMessage("y") @Description("") String yParams(); @DefaultMessage("r") @Description("") String rParams(); @DefaultMessage("x1") @Description("") String x1Params(); @DefaultMessage("x2") @Description("") String x2Params(); @DefaultMessage("y1") @Description("") String y1Params(); @DefaultMessage("y2") @Description("") String y2Params(); @DefaultMessage("angle") @Description("") String angleParams(); @DefaultMessage("fileName") @Description("") String fileNameParams(); @DefaultMessage("color") @Description("") String colorParams(); @DefaultMessage("instant") @Description("") String instantParams(); @DefaultMessage("days") @Description("") String daysParams(); @DefaultMessage("hours") @Description("") String hoursParams(); @DefaultMessage("minutes") @Description("") String minutesParams(); @DefaultMessage("months") @Description("") String monthsParams(); @DefaultMessage("seconds") @Description("") String secondsParams(); @DefaultMessage("weeks") @Description("") String weeksParams(); @DefaultMessage("years") @Description("") String yearsParams(); @DefaultMessage("InstantInTime") @Description("") String InstantInTimeParams(); @DefaultMessage("from") @Description("") String fromParams(); @DefaultMessage("millis") @Description("") String millisParams(); @DefaultMessage("functionName") @Description("") String functionNameParams(); @DefaultMessage("errorNumber") @Description("") String errorNumberParams(); @DefaultMessage("message") @Description("") String messageParams(); @DefaultMessage("otherScreenName") @Description("") String otherScreenNameParams(); @DefaultMessage("animType") @Description("") String animTypeParams(); @DefaultMessage("sender") @Description("") String senderParams(); @DefaultMessage("contents") @Description("") String contentsParams(); @DefaultMessage("instanceId") @Description("") String instanceIdParams(); @DefaultMessage("playerId") @Description("") String playerIdParams(); @DefaultMessage("command") @Description("") String commandParams(); @DefaultMessage("arguments") @Description("") String argumentsParams(); @DefaultMessage("response") @Description("") String responseParams(); @DefaultMessage("emailAddress") @Description("") String emailAddressParams(); @DefaultMessage("type") @Description("") String typeParams(); @DefaultMessage("count") @Description("") String countParams(); @DefaultMessage("makePublic") @Description("") String makePublicParams(); @DefaultMessage("recipients") @Description("") String recipientsParams(); @DefaultMessage("playerEmail") @Description("") String playerEmailParams(); @DefaultMessage("latitude") @Description("") String latitudeParams(); @DefaultMessage("longitude") @Description("") String longitudeParams(); @DefaultMessage("altitude") @Description("") String altitudeParams(); @DefaultMessage("provider") @Description("") String providerParams(); @DefaultMessage("status") @Description("") String statusParams(); @DefaultMessage("locationName") @Description("") String locationNameParams(); @DefaultMessage("choice") @Description("") String choiceParams(); @DefaultMessage("notice") @Description("") String noticeParams(); @DefaultMessage("title") @Description("") String titleParams(); @DefaultMessage("buttonText") @Description("") String buttonTextParams(); @DefaultMessage("cancelable") @Description("") String cancelableParams(); @DefaultMessage("button1Text") @Description("") String button1TextParams(); @DefaultMessage("button2Text") @Description("") String button2TextParams(); @DefaultMessage("source") @Description("") String sourceParams(); @DefaultMessage("destination") @Description("") String destinationParams(); @DefaultMessage("sensorPortLetter") @Description("") String sensorPortLetterParams(); @DefaultMessage("rxDataLength") @Description("") String rxDataLengthParams(); @DefaultMessage("wildcard") @Description("") String wildcardParams(); @DefaultMessage("motorPortLetter") @Description("") String motorPortLetterParams(); @DefaultMessage("mailbox") @Description("") String mailboxParams(); @DefaultMessage("durationMs") @Description("") String durationMsParams(); @DefaultMessage("relative") @Description("") String relativeParams(); @DefaultMessage("sensorType") @Description("") String sensorTypeParams(); @DefaultMessage("sensorMode") @Description("") String sensorModeParams(); @DefaultMessage("power") @Description("") String powerParams(); @DefaultMessage("mode") @Description("") String modeParams(); @DefaultMessage("regulationMode") @Description("") String regulationModeParams(); @DefaultMessage("turnRatio") @Description("") String turnRatioParams(); @DefaultMessage("runState") @Description("") String runStateParams(); @DefaultMessage("tachoLimit") @Description("") String tachoLimitParams(); @DefaultMessage("programName") @Description("") String programNameParams(); @DefaultMessage("distance") @Description("") String distanceParams(); @DefaultMessage("azimuth") @Description("") String azimuthParams(); @DefaultMessage("pitch") @Description("") String pitchParams(); @DefaultMessage("roll") @Description("") String rollParams(); @DefaultMessage("simpleSteps") @Description("") String simpleStepsParams(); @DefaultMessage("walkSteps") @Description("") String walkStepsParams(); @DefaultMessage("seed") @Description("") String seedParams(); @DefaultMessage("millisecs") @Description("") String millisecsParams(); @DefaultMessage("sound") @Description("") String soundParams(); @DefaultMessage("messageText") @Description("") String messageTextParams(); @DefaultMessage("tag") @Description("") String tagParams(); @DefaultMessage("valueToStore") @Description("") String valueToStoreParams(); @DefaultMessage("tagFromWebDB") @Description("") String tagFromWebDBParams(); @DefaultMessage("valueFromWebDB") @Description("") String valueFromWebDBParams(); @DefaultMessage("followers2") @Description("") String followers2Params(); @DefaultMessage("timeline") @Description("") String timelineParams(); @DefaultMessage("mentions") @Description("") String mentionsParams(); @DefaultMessage("searchResults") @Description("") String searchResultsParams(); @DefaultMessage("user") @Description("") String userParams(); @DefaultMessage("url") @Description("") String urlParams(); @DefaultMessage("responseCode") @Description("") String responseCodeParams(); @DefaultMessage("responseType") @Description("") String responseTypeParams(); @DefaultMessage("responseContent") @Description("") String responseContentParams(); @DefaultMessage("htmlText") @Description("") String htmlTextParams(); @DefaultMessage("jsonText") @Description("") String jsonTextParams(); @DefaultMessage("path") @Description("") String pathParams(); @DefaultMessage("encoding") @Description("") String encodingParams(); @DefaultMessage("name") @Description("") String nameParams(); @DefaultMessage("serviceName") @Description("") String serviceNameParams(); @DefaultMessage("milliseconds") @Description("") String millisecondsParams(); @DefaultMessage("messages") @Description("") String messagesParams(); @DefaultMessage("start") @Description("") String startParams(); @DefaultMessage("end") @Description("") String endParams(); @DefaultMessage("frequencyHz") @Description("") String frequencyHzParams(); @DefaultMessage("secure") @Description("") String secureParams(); @DefaultMessage("file") @Description("") String fileParams(); @DefaultMessage("thumbPosition") @Description("") String thumbPositionParams(); @DefaultMessage("selection") @Description("") String selectionParams(); @DefaultMessage("valueIfTagNotThere") @Description("") String valueIfTagNotThereParams(); @DefaultMessage("query") @Description("") String queryParams(); @DefaultMessage("ImagePath") @Description("") String ImagePathParams(); @DefaultMessage("ms") @Description("") String msParams(); @DefaultMessage("translation") @Description("") String translationParams(); @DefaultMessage("languageToTranslateTo") @Description("") String languageToTranslateToParams(); @DefaultMessage("textToTranslate") @Description("") String textToTranslateParams(); //Events @DefaultMessage("AccelerationChanged") @Description("") String AccelerationChangedEvents(); @DefaultMessage("AfterActivity") @Description("") String AfterActivityEvents(); @DefaultMessage("CollidedWith") @Description("") String CollidedWithEvents(); @DefaultMessage("Dragged") @Description("") String DraggedEvents(); @DefaultMessage("EdgeReached") @Description("") String EdgeReachedEvents(); @DefaultMessage("Flung") @Description("") String FlungEvents(); @DefaultMessage("NoLongerCollidingWith") @Description("") String NoLongerCollidingWithEvents(); @DefaultMessage("TouchDown") @Description("") String TouchDownEvents(); @DefaultMessage("TouchUp") @Description("") String TouchUpEvents(); @DefaultMessage("Touched") @Description("") String TouchedEvents(); @DefaultMessage("AfterScan") @Description("") String AfterScanEvents(); @DefaultMessage("ConnectionAccepted") @Description("") String ConnectionAcceptedEvents(); @DefaultMessage("Click") @Description("") String ClickEvents(); @DefaultMessage("GotFocus") @Description("") String GotFocusEvents(); @DefaultMessage("LongClick") @Description("") String LongClickEvents(); @DefaultMessage("LostFocus") @Description("") String LostFocusEvents(); @DefaultMessage("AfterRecording") @Description("") String AfterRecordingEvents(); @DefaultMessage("AfterPicture") @Description("") String AfterPictureEvents(); @DefaultMessage("Changed") @Description("") String ChangedEvents(); @DefaultMessage("Timer") @Description("") String TimerEvents(); @DefaultMessage("AfterPicking") @Description("") String AfterPickingEvents(); @DefaultMessage("BeforePicking") @Description("") String BeforePickingEvents(); @DefaultMessage("BackPressed") @Description("") String BackPressedEvents(); @DefaultMessage("ErrorOccurred") @Description("") String ErrorOccurredEvents(); @DefaultMessage("Initialize") @Description("") String InitializeEvents(); @DefaultMessage("OtherScreenClosed") @Description("") String OtherScreenClosedEvents(); @DefaultMessage("ScreenOrientationChanged") @Description("") String ScreenOrientationChangedEvents(); @DefaultMessage("GotResult") @Description("") String GotResultEvents(); @DefaultMessage("FunctionCompleted") @Description("") String FunctionCompletedEvents(); @DefaultMessage("GotMessage") @Description("") String GotMessageEvents(); @DefaultMessage("Info") @Description("") String InfoEvents(); @DefaultMessage("InstanceIdChanged") @Description("") String InstanceIdChangedEvents(); @DefaultMessage("Invited") @Description("") String InvitedEvents(); @DefaultMessage("NewInstanceMade") @Description("") String NewInstanceMadeEvents(); @DefaultMessage("NewLeader") @Description("") String NewLeaderEvents(); @DefaultMessage("PlayerJoined") @Description("") String PlayerJoinedEvents(); @DefaultMessage("PlayerLeft") @Description("") String PlayerLeftEvents(); @DefaultMessage("ServerCommandFailure") @Description("") String ServerCommandFailureEvents(); @DefaultMessage("ServerCommandSuccess") @Description("") String ServerCommandSuccessEvents(); @DefaultMessage("UserEmailAddressSet") @Description("") String UserEmailAddressSetEvents(); @DefaultMessage("WebServiceError") @Description("") String WebServiceErrorEvents(); @DefaultMessage("LocationChanged") @Description("") String LocationChangedEvents(); @DefaultMessage("StatusChanged") @Description("") String StatusChangedEvents(); @DefaultMessage("AfterChoosing") @Description("") String AfterChoosingEvents(); @DefaultMessage("AfterTextInput") @Description("") String AfterTextInputEvents(); @DefaultMessage("AboveRange") @Description("") String AboveRangeEvents(); @DefaultMessage("BelowRange") @Description("") String BelowRangeEvents(); @DefaultMessage("ColorChanged") @Description("") String ColorChangedEvents(); @DefaultMessage("WithinRange") @Description("") String WithinRangeEvents(); @DefaultMessage("Pressed") @Description("") String PressedEvents(); @DefaultMessage("Released") @Description("") String ReleasedEvents(); @DefaultMessage("OrientationChanged") @Description("") String OrientationChangedEvents(); @DefaultMessage("CalibrationFailed") @Description("") String CalibrationFailedEvents(); @DefaultMessage("GPSAvailable") @Description("") String GPSAvailableEvents(); @DefaultMessage("GPSLost") @Description("") String GPSLostEvents(); @DefaultMessage("SimpleStep") @Description("") String SimpleStepEvents(); @DefaultMessage("StartedMoving") @Description("") String StartedMovingEvents(); @DefaultMessage("StoppedMoving") @Description("") String StoppedMovingEvents(); @DefaultMessage("WalkStep") @Description("") String WalkStepEvents(); @DefaultMessage("Completed") @Description("") String CompletedEvents(); @DefaultMessage("AfterSoundRecorded") @Description("") String AfterSoundRecordedEvents(); @DefaultMessage("StartedRecording") @Description("") String StartedRecordingEvents(); @DefaultMessage("StoppedRecording") @Description("") String StoppedRecordingEvents(); @DefaultMessage("AfterGettingText") @Description("") String AfterGettingTextEvents(); @DefaultMessage("BeforeGettingText") @Description("") String BeforeGettingTextEvents(); @DefaultMessage("AfterSpeaking") @Description("") String AfterSpeakingEvents(); @DefaultMessage("BeforeSpeaking") @Description("") String BeforeSpeakingEvents(); @DefaultMessage("MessageReceived") @Description("") String MessageReceivedEvents(); @DefaultMessage("SendMessage") @Description("") String SendMessageEvents(); @DefaultMessage("GotValue") @Description("") String GotValueEvents(); @DefaultMessage("ValueStored") @Description("") String ValueStoredEvents(); @DefaultMessage("DirectMessagesReceived") @Description("") String DirectMessagesReceivedEvents(); @DefaultMessage("FollowersReceived") @Description("") String FollowersReceivedEvents(); @DefaultMessage("FriendTimelineReceived") @Description("") String FriendTimelineReceivedEvents(); @DefaultMessage("IsAuthorized") @Description("") String IsAuthorizedEvents(); @DefaultMessage("MentionsReceived") @Description("") String MentionsReceivedEvents(); @DefaultMessage("SearchSuccessful") @Description("") String SearchSuccessfulEvents(); @DefaultMessage("GotBallot") @Description("") String GotBallotEvents(); @DefaultMessage("GotBallotConfirmation") @Description("") String GotBallotConfirmationEvents(); @DefaultMessage("NoOpenPoll") @Description("") String NoOpenPollEvents(); @DefaultMessage("GotFile") @Description("") String GotFileEvents(); @DefaultMessage("GotText") @Description("") String GotTextEvents(); @DefaultMessage("AfterDateSet") @Description("") String AfterDateSetEvents(); @DefaultMessage("TagRead") @Description("") String TagReadEvents(); @DefaultMessage("TagWritten") @Description("") String TagWrittenEvents(); @DefaultMessage("PositionChanged") @Description("") String PositionChangedEvents(); @DefaultMessage("AfterSelecting") @Description("") String AfterSelectingEvents(); @DefaultMessage("AfterTimeSet") @Description("") String AfterTimeSetEvents(); @DefaultMessage("GotTranslation") @Description("") String GotTranslationEvents(); @DefaultMessage("Shaking") @Description("") String ShakingEvents(); //Methods @DefaultMessage("ResolveActivity") @Description("") String ResolveActivityMethods(); @DefaultMessage("StartActivity") @Description("") String StartActivityMethods(); @DefaultMessage("Connect") @Description("") String ConnectMethods(); @DefaultMessage("ConnectWithUUID") @Description("") String ConnectWithUUIDMethods(); @DefaultMessage("Disconnect") @Description("") String DisconnectMethods(); @DefaultMessage("IsDevicePaired") @Description("") String IsDevicePairedMethods(); @DefaultMessage("ReceiveSigned1ByteNumber") @Description("") String ReceiveSigned1ByteNumberMethods(); @DefaultMessage("ReceiveSigned2ByteNumber") @Description("") String ReceiveSigned2ByteNumberMethods(); @DefaultMessage("ReceiveSigned4ByteNumber") @Description("") String ReceiveSigned4ByteNumberMethods(); @DefaultMessage("ReceiveSignedBytes") @Description("") String ReceiveSignedBytesMethods(); @DefaultMessage("ReceiveText") @Description("") String ReceiveTextMethods(); @DefaultMessage("ReceiveUnsigned1ByteNumber") @Description("") String ReceiveUnsigned1ByteNumberMethods(); @DefaultMessage("ReceiveUnsigned2ByteNumber") @Description("") String ReceiveUnsigned2ByteNumberMethods(); @DefaultMessage("ReceiveUnsigned4ByteNumber") @Description("") String ReceiveUnsigned4ByteNumberMethods(); @DefaultMessage("ReceiveUnsignedBytes") @Description("") String ReceiveUnsignedBytesMethods(); @DefaultMessage("Send1ByteNumber") @Description("") String Send1ByteNumberMethods(); @DefaultMessage("Send2ByteNumber") @Description("") String Send2ByteNumberMethods(); @DefaultMessage("Send4ByteNumber") @Description("") String Send4ByteNumberMethods(); @DefaultMessage("SendBytes") @Description("") String SendBytesMethods(); @DefaultMessage("SendText") @Description("") String SendTextMethods(); @DefaultMessage("AcceptConnection") @Description("") String AcceptConnectionMethods(); @DefaultMessage("AcceptConnectionWithUUID") @Description("") String AcceptConnectionWithUUIDMethods(); @DefaultMessage("BytesAvailableToReceive") @Description("") String BytesAvailableToReceiveMethods(); @DefaultMessage("StopAccepting") @Description("") String StopAcceptingMethods(); @DefaultMessage("RecordVideo") @Description("") String RecordVideoMethods(); @DefaultMessage("TakePicture") @Description("") String TakePictureMethods(); @DefaultMessage("Clear") @Description("") String ClearMethods(); @DefaultMessage("DrawCircle") @Description("") String DrawCircleMethods(); @DefaultMessage("DrawLine") @Description("") String DrawLineMethods(); @DefaultMessage("DrawPoint") @Description("") String DrawPointMethods(); @DefaultMessage("DrawText") @Description("") String DrawTextMethods(); @DefaultMessage("DrawTextAtAngle") @Description("") String DrawTextAtAngleMethods(); @DefaultMessage("GetBackgroundPixelColor") @Description("") String GetBackgroundPixelColorMethods(); @DefaultMessage("GetPixelColor") @Description("") String GetPixelColorMethods(); @DefaultMessage("Save") @Description("") String SaveMethods(); @DefaultMessage("SaveAs") @Description("") String SaveAsMethods(); @DefaultMessage("SetBackgroundPixelColor") @Description("") String SetBackgroundPixelColorMethods(); @DefaultMessage("AddDays") @Description("") String AddDaysMethods(); @DefaultMessage("AddHours") @Description("") String AddHoursMethods(); @DefaultMessage("AddMinutes") @Description("") String AddMinutesMethods(); @DefaultMessage("AddMonths") @Description("") String AddMonthsMethods(); @DefaultMessage("AddSeconds") @Description("") String AddSecondsMethods(); @DefaultMessage("AddWeeks") @Description("") String AddWeeksMethods(); @DefaultMessage("AddYears") @Description("") String AddYearsMethods(); @DefaultMessage("DayOfMonth") @Description("") String DayOfMonthMethods(); @DefaultMessage("Duration") @Description("") String DurationMethods(); @DefaultMessage("FormatDate") @Description("") String FormatDateMethods(); @DefaultMessage("FormatDateTime") @Description("") String FormatDateTimeMethods(); @DefaultMessage("FormatTime") @Description("") String FormatTimeMethods(); @DefaultMessage("GetMillis") @Description("") String GetMillisMethods(); @DefaultMessage("Hour") @Description("") String HourMethods(); @DefaultMessage("MakeInstant") @Description("") String MakeInstantMethods(); @DefaultMessage("MakeInstantFromMillis") @Description("") String MakeInstantFromMillisMethods(); @DefaultMessage("Minute") @Description("") String MinuteMethods(); @DefaultMessage("Month") @Description("") String MonthMethods(); @DefaultMessage("MonthName") @Description("") String MonthNameMethods(); @DefaultMessage("Now") @Description("") String NowMethods(); @DefaultMessage("Second") @Description("") String SecondMethods(); @DefaultMessage("SystemTime") @Description("") String SystemTimeMethods(); @DefaultMessage("Weekday") @Description("") String WeekdayMethods(); @DefaultMessage("WeekdayName") @Description("") String WeekdayNameMethods(); @DefaultMessage("Year") @Description("") String YearMethods(); @DefaultMessage("Open") @Description("") String OpenMethods(); @DefaultMessage("CloseScreenAnimation") @Description("") String CloseScreenAnimationMethods(); @DefaultMessage("OpenScreenAnimation") @Description("") String OpenScreenAnimationMethods(); @DefaultMessage("DoQuery") @Description("") String DoQueryMethods(); @DefaultMessage("ForgetLogin") @Description("") String ForgetLoginMethods(); @DefaultMessage("SendQuery") @Description("") String SendQueryMethods(); @DefaultMessage("GetInstanceLists") @Description("") String GetInstanceListsMethods(); @DefaultMessage("GetMessages") @Description("") String GetMessagesMethods(); @DefaultMessage("Invite") @Description("") String InviteMethods(); @DefaultMessage("LeaveInstance") @Description("") String LeaveInstanceMethods(); @DefaultMessage("MakeNewInstance") @Description("") String MakeNewInstanceMethods(); @DefaultMessage("ServerCommand") @Description("") String ServerCommandMethods(); @DefaultMessage("SetInstance") @Description("") String SetInstanceMethods(); @DefaultMessage("SetLeader") @Description("") String SetLeaderMethods(); @DefaultMessage("Bounce") @Description("") String BounceMethods(); @DefaultMessage("CollidingWith") @Description("") String CollidingWithMethods(); @DefaultMessage("MoveIntoBounds") @Description("") String MoveIntoBoundsMethods(); @DefaultMessage("MoveTo") @Description("") String MoveToMethods(); @DefaultMessage("PointInDirection") @Description("") String PointInDirectionMethods(); @DefaultMessage("PointTowards") @Description("") String PointTowardsMethods(); @DefaultMessage("LatitudeFromAddress") @Description("") String LatitudeFromAddressMethods(); @DefaultMessage("LongitudeFromAddress") @Description("") String LongitudeFromAddressMethods(); @DefaultMessage("LogError") @Description("") String LogErrorMethods(); @DefaultMessage("LogInfo") @Description("") String LogInfoMethods(); @DefaultMessage("LogWarning") @Description("") String LogWarningMethods(); @DefaultMessage("ShowAlert") @Description("") String ShowAlertMethods(); @DefaultMessage("ShowChooseDialog") @Description("") String ShowChooseDialogMethods(); @DefaultMessage("ShowMessageDialog") @Description("") String ShowMessageDialogMethods(); @DefaultMessage("ShowTextDialog") @Description("") String ShowTextDialogMethods(); @DefaultMessage("GetColor") @Description("") String GetColorMethods(); @DefaultMessage("GetLightLevel") @Description("") String GetLightLevelMethods(); @DefaultMessage("DeleteFile") @Description("") String DeleteFileMethods(); @DefaultMessage("DownloadFile") @Description("") String DownloadFileMethods(); @DefaultMessage("GetBatteryLevel") @Description("") String GetBatteryLevelMethods(); @DefaultMessage("GetBrickName") @Description("") String GetBrickNameMethods(); @DefaultMessage("GetCurrentProgramName") @Description("") String GetCurrentProgramNameMethods(); @DefaultMessage("GetFirmwareVersion") @Description("") String GetFirmwareVersionMethods(); @DefaultMessage("GetInputValues") @Description("") String GetInputValuesMethods(); @DefaultMessage("GetOutputState") @Description("") String GetOutputStateMethods(); @DefaultMessage("KeepAlive") @Description("") String KeepAliveMethods(); @DefaultMessage("ListFiles") @Description("") String ListFilesMethods(); @DefaultMessage("LsGetStatus") @Description("") String LsGetStatusMethods(); @DefaultMessage("LsRead") @Description("") String LsReadMethods(); @DefaultMessage("MessageRead") @Description("") String MessageReadMethods(); @DefaultMessage("MessageWrite") @Description("") String MessageWriteMethods(); @DefaultMessage("PlaySoundFile") @Description("") String PlaySoundFileMethods(); @DefaultMessage("PlayTone") @Description("") String PlayToneMethods(); @DefaultMessage("ResetInputScaledValue") @Description("") String ResetInputScaledValueMethods(); @DefaultMessage("ResetMotorPosition") @Description("") String ResetMotorPositionMethods(); @DefaultMessage("SetBrickName") @Description("") String SetBrickNameMethods(); @DefaultMessage("SetInputMode") @Description("") String SetInputModeMethods(); @DefaultMessage("SetOutputState") @Description("") String SetOutputStateMethods(); @DefaultMessage("StartProgram") @Description("") String StartProgramMethods(); @DefaultMessage("StopProgram") @Description("") String StopProgramMethods(); @DefaultMessage("StopSoundPlayback") @Description("") String StopSoundPlaybackMethods(); @DefaultMessage("LsWrite") @Description("") String LsWriteMethods(); @DefaultMessage("MoveBackward") @Description("") String MoveBackwardMethods(); @DefaultMessage("MoveBackwardIndefinitely") @Description("") String MoveBackwardIndefinitelyMethods(); @DefaultMessage("MoveForward") @Description("") String MoveForwardMethods(); @DefaultMessage("MoveForwardIndefinitely") @Description("") String MoveForwardIndefinitelyMethods(); @DefaultMessage("Stop") @Description("") String StopMethods(); @DefaultMessage("TurnClockwiseIndefinitely") @Description("") String TurnClockwiseIndefinitelyMethods(); @DefaultMessage("TurnCounterClockwiseIndefinitely") @Description("") String TurnCounterClockwiseIndefinitelyMethods(); @DefaultMessage("GetSoundLevel") @Description("") String GetSoundLevelMethods(); @DefaultMessage("IsPressed") @Description("") String IsPressedMethods(); @DefaultMessage("GetDistance") @Description("") String GetDistanceMethods(); @DefaultMessage("Pause") @Description("") String PauseMethods(); @DefaultMessage("Reset") @Description("") String ResetMethods(); @DefaultMessage("Resume") @Description("") String ResumeMethods(); @DefaultMessage("Start") @Description("") String StartMethods(); @DefaultMessage("MakePhoneCall") @Description("") String MakePhoneCallMethods(); @DefaultMessage("GetWifiIpAddress") @Description("") String GetWifiIpAddressMethods(); @DefaultMessage("isConnected") @Description("") String isConnectedMethods(); @DefaultMessage("setHmacSeedReturnCode") @Description("") String setHmacSeedReturnCodeMethods(); @DefaultMessage("startHTTPD") @Description("") String startHTTPDMethods(); @DefaultMessage("Vibrate") @Description("") String VibrateMethods(); @DefaultMessage("GetText") @Description("") String GetTextMethods(); @DefaultMessage("HideKeyboard") @Description("") String HideKeyboardMethods(); @DefaultMessage("Speak") @Description("") String SpeakMethods(); @DefaultMessage("SendMessage") @Description("") String SendMessageMethods(); @DefaultMessage("GetValue") @Description("") String GetValueMethods(); @DefaultMessage("StoreValue") @Description("") String StoreValueMethods(); @DefaultMessage("Authorize") @Description("") String AuthorizeMethods(); @DefaultMessage("CheckAuthorized") @Description("") String CheckAuthorizedMethods(); @DefaultMessage("DeAuthorize") @Description("") String DeAuthorizeMethods(); @DefaultMessage("DirectMessage") @Description("") String DirectMessageMethods(); @DefaultMessage("Follow") @Description("") String FollowMethods(); @DefaultMessage("RequestDirectMessages") @Description("") String RequestDirectMessagesMethods(); @DefaultMessage("RequestFollowers") @Description("") String RequestFollowersMethods(); @DefaultMessage("RequestFriendTimeline") @Description("") String RequestFriendTimelineMethods(); @DefaultMessage("RequestMentions") @Description("") String RequestMentionsMethods(); @DefaultMessage("SearchTwitter") @Description("") String SearchTwitterMethods(); @DefaultMessage("SetStatus") @Description("") String SetStatusMethods(); @DefaultMessage("StopFollowing") @Description("") String StopFollowingMethods(); @DefaultMessage("GetDuration") @Description("") String GetDurationMethods(); @DefaultMessage("SeekTo") @Description("") String SeekToMethods(); @DefaultMessage("DoScan") @Description("") String DoScanMethods(); @DefaultMessage("RequestBallot") @Description("") String RequestBallotMethods(); @DefaultMessage("SendBallot") @Description("") String SendBallotMethods(); @DefaultMessage("BuildPostData") @Description("") String BuildPostDataMethods(); @DefaultMessage("ClearCookies") @Description("") String ClearCookiesMethods(); @DefaultMessage("Get") @Description("") String GetMethods(); @DefaultMessage("HtmlTextDecode") @Description("") String HtmlTextDecodeMethods(); @DefaultMessage("JsonTextDecode") @Description("") String JsonTextDecodeMethods(); @DefaultMessage("PostFile") @Description("") String PostFileMethods(); @DefaultMessage("PostText") @Description("") String PostTextMethods(); @DefaultMessage("PostTextWithEncoding") @Description("") String PostTextWithEncodingMethods(); @DefaultMessage("UriEncode") @Description("") String UriEncodeMethods(); @DefaultMessage("CanGoBack") @Description("") String CanGoBackMethods(); @DefaultMessage("CanGoForward") @Description("") String CanGoForwardMethods(); @DefaultMessage("ClearLocations") @Description("") String ClearLocationsMethods(); @DefaultMessage("GoBack") @Description("") String GoBackMethods(); @DefaultMessage("GoForward") @Description("") String GoForwardMethods(); @DefaultMessage("GoHome") @Description("") String GoHomeMethods(); @DefaultMessage("GoToUrl") @Description("") String GoToUrlMethods(); @DefaultMessage("AppendToFile") @Description("") String AppendToFileMethods(); @DefaultMessage("Delete") @Description("") String DeleteMethods(); @DefaultMessage("ReadFrom") @Description("") String ReadFromMethods(); @DefaultMessage("SaveFile") @Description("") String SaveFileMethods(); @DefaultMessage("doFault") @Description("") String doFaultMethods(); @DefaultMessage("getVersionName") @Description("") String getVersionNameMethods(); @DefaultMessage("installURL") @Description("") String installURLMethods(); @DefaultMessage("isDirect") @Description("") String isDirectMethods(); @DefaultMessage("setAssetsLoaded") @Description("") String setAssetsLoadedMethods(); @DefaultMessage("shutdown") @Description("") String shutdownMethods(); @DefaultMessage("ShareFile") @Description("") String ShareFileMethods(); @DefaultMessage("ShareFileWithMessage") @Description("") String ShareFileWithMessageMethods(); @DefaultMessage("ShareMessage") @Description("") String ShareMessageMethods(); @DefaultMessage("Play") @Description("") String PlayMethods(); @DefaultMessage("DisplayDropdown") @Description("") String DisplayDropdownMethods(); @DefaultMessage("ClearAll") @Description("") String ClearAllMethods(); @DefaultMessage("ClearTag") @Description("") String ClearTagMethods(); @DefaultMessage("GetTags") @Description("") String GetTagsMethods(); @DefaultMessage("Tweet") @Description("") String TweetMethods(); @DefaultMessage("TweetWithImage") @Description("") String TweetWithImageMethods(); @DefaultMessage("BuildRequestData") @Description("") String BuildRequestDataMethods(); @DefaultMessage("PutFile") @Description("") String PutFileMethods(); @DefaultMessage("PutText") @Description("") String PutTextMethods(); @DefaultMessage("PutTextWithEncoding") @Description("") String PutTextWithEncodingMethods(); @DefaultMessage("RequestTranslation") @Description("") String RequestTranslationMethods(); //Mock Components @DefaultMessage("add items...") @Description("") String MockSpinnerAddItems(); //help strings @DefaultMessage("Non-visible component that can detect shaking and measure acceleration approximately in three dimensions using SI units (m/s<sup>2</sup>). The components are: <ul>\n<li> <strong>xAccel</strong>: 0 when the phone is at rest on a flat surface, positive when the phone is tilted to the right (i.e., its left side is raised), and negative when the phone is tilted to the left (i.e., its right size is raised).</li>\n <li> <strong>yAccel</strong>: 0 when the phone is at rest on a flat surface, positive when its bottom is raised, and negative when its top is raised. </li>\n <li> <strong>zAccel</strong>: Equal to -9.8 (earth\"s gravity in meters per second per second when the device is at rest parallel to the ground with the display facing up, 0 when perpindicular to the ground, and +9.8 when facing down. The value can also be affected by accelerating it with or against gravity. </li></ul>") @Description("") String AccelerometerSensorHelpStringComponentPallette(); @DefaultMessage("A component that can launch an activity using the <code>StartActivity</code> method.<p>Activities that can be launched include: <ul> \n<li> starting other App Inventor for Android apps </li> \n<li> starting the camera application </li> \n<li> performing web search </li> \n<li> opening a browser to a specified web page</li> \n<li> opening the map application to a specified location</li></ul> \nYou can also launch activities that return text data. See the documentation on using the Activity Starter for examples.</p>") @Description("") String ActivityStarterHelpStringComponentPallette(); @DefaultMessage("<p>A round \"sprite\" that can be placed on a <code>Canvas</code>, where it can react to touches and drags, interact with other sprites (<code>ImageSprite</code>s and other <code>Ball</code>s) and the edge of the Canvas, and move according to its property values.</p><p>For example, to have a <code>Ball</code> move 4 pixels toward the top of a <code>Canvas</code> every 500 milliseconds (half second), you would set the <code>Speed</code> property to 4 [pixels], the <code>Interval</code> property to 500 [milliseconds], the <code>Heading</code> property to 90 [degrees], and the <code>Enabled</code> property to <code>True</code>. These and its other properties can be changed at any time.</p><p>The difference between a Ball and an <code>ImageSprite</code> is that the latter can get its appearance from an image file, while a Ball\"s appearance can only be changed by varying its <code>PaintColor</code> and <code>Radius</code> properties.</p>") @Description("") String BallHelpStringComponentPallette(); @DefaultMessage("Component for using the Barcode Scanner to read a barcode") @Description("") String BarcodeScannerHelpStringComponentPallette(); @DefaultMessage("Bluetooth client component") @Description("") String BluetoothClientHelpStringComponentPallette(); @DefaultMessage("Bluetooth server component") @Description("") String BluetoothServerHelpStringComponentPallette(); @DefaultMessage("Button with the ability to detect clicks. Many aspects of its appearance can be changed, as well as whether it is clickable (<code>Enabled</code>), can be changed in the Designer or in the Blocks Editor.") @Description("") String ButtonHelpStringComponentPallette(); @DefaultMessage("A component to record a video using the device\"s camcorder.After the video is recorded, the name of the file on the phone containing the clip is available as an argument to the AfterRecording event. The file name can be used, for example, to set the source property of a VideoPlayer component.") @Description("") String CamcorderHelpStringComponentPallette(); @DefaultMessage("A component to take a picture using the device\"s camera. After the picture is taken, the name of the file on the phone containing the picture is available as an argument to the AfterPicture event. The file name can be used, for example, to set the Picture property of an Image component.") @Description("") String CameraHelpStringComponentPallette(); @DefaultMessage("<p>A two-dimensional touch-sensitive rectangular panel on which drawing can be done and sprites can be moved.</p> <p>The <code>BackgroundColor</code>, <code>PaintColor</code>, <code>BackgroundImage</code>, <code>Width</code>, and <code>Height</code> of the Canvas can be set in either the Designer or in the Blocks Editor. The <code>Width</code> and <code>Height</code> are measured in pixels and must be positive.</p><p>Any location on the Canvas can be specified as a pair of (X, Y) values, where <ul> <li>X is the number of pixels away from the left edge of the Canvas</li><li>Y is the number of pixels away from the top edge of the Canvas</li></ul>.</p> <p>There are events to tell when and where a Canvas has been touched or a <code>Sprite</code> (<code>ImageSprite</code> or <code>Ball</code>) has been dragged. There are also methods for drawing points, lines, and circles.</p>") @Description("") String CanvasHelpStringComponentPallette(); @DefaultMessage("Checkbox that raises an event when the user clicks on it. There are many properties affecting its appearance that can be set in the Designer or Blocks Editor.") @Description("") String CheckBoxHelpStringComponentPallette(); @DefaultMessage("Non-visible component that provides the phone\"s clock, a timer, and time calculations.") @Description("") String ClockHelpStringComponentPallette(); @DefaultMessage("A button that, when clicked on, displays a list of the contacts to choose among. After the user has made a selection, the following properties will be set to information about the chosen contact: <ul>\n<li> <code>ContactName</code>: the contact\"s name </li>\n <li> <code>EmailAddress</code>: the contact\"s primary email address </li>\n <li> <code>Picture</code>: the name of the file containing the contact\"s image, which can be used as a <code>Picture</code> property value for the <code>Image</code> or <code>ImageSprite</code> component.</li></ul>\n</p><p>Other properties affect the appearance of the button (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be clicked on (<code>Enabled</code>).\n</p><p>Picking is not supported on all phones. If it fails, this component will show a notification. The error behavior can be overridden with the Screen.ErrorOccurred event handler.") @Description("") String ContactPickerHelpStringComponentPallette(); @DefaultMessage("<p>A button that, when clicked on, launches a popup dialog to allow the user to select a date.</p>") @Description("") String DatePickerHelpStringComponentPallette(); @DefaultMessage("An EmailPicker is a kind of text box. If the user begins entering the name or email address of a contact, the phone will show a dropdown menu of choices that complete the entry. If there are many contacts, the dropdown can take several seconds to appear, and can show intermediate results while the matches are being computed. <p>The initial contents of the text box and the contents< after user entry is in the <code>Text</code> property. If the <code>Text</code> property is initially empty, the contents of the <code>Hint</code> property will be faintly shown in the text box as a hint to the user.</p>\n <p>Other properties affect the appearance of the text box (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be used (<code>Enabled</code>).</p>\n<p>Text boxes like this are usually used with <code>Button</code> components, with the user clicking on the button when text entry is complete.") @Description("") String EmailPickerHelpStringComponentPallette(); @DefaultMessage("Non-visible component for storing and retrieving files. Use this component to write or read files on your device. The default behaviour is to write files to the private data directory associated with your App. The Companion is special cased to write files to /sdcard/AppInventor/data to facilitate debugging. If the file path starts with a slash (/), then the file is created relative to /sdcard. For example writing a file to /myFile.txt will write the file in /sdcard/myFile.txt.") @Description("") String FileHelpStringComponentPallette(); @DefaultMessage("Top-level component containing all other components in the program") @Description("") String FormHelpStringComponentPallette(); @DefaultMessage("<p>A non-visible component that communicates with Google Fusion Tables. Fusion Tables let you store, share, query and visualize data tables; this component lets you query, create, and modify these tables.</p> <p>This component uses the <a href=\"https://developers.google.com/fusiontables/docs/v1/getting_started\" target=\"_blank\">Fusion Tables API V1.0</a>. <p>Applications using Fusion Tables must authentication to Google\"s servers. There are two ways this can be done. The first way uses an API Key which you the developer obtain (see below). With this approach end-users must also login to access a Fusion Table. The second approach is to use a Service Account. With this approach you create credentials and a special \"Service Account Email Address\" which you obtain from the <a href=\"https://code.google.com/apis/console/\" target=\"_blank\">Google APIs Console</a>. You then tell the Fusion Table Control the name of the Service Account Email address and upload the secret key as an asset to your application and set the KeyFile property to point at this file. Finally you check the \"UseServiceAuthentication\" checkbox in the designer. When using a Service Account, end-users do not need to login to use Fusion Tables, your service account authenticates all access.</p> <p>To get an API key, follow these instructions.</p> <ol> <li>Go to your <a href=\"https://code.google.com/apis/console/\" target=\"_blank\">Google APIs Console</a> and login if necessary.</li> <li>Select the <i>Services</i> item from the menu on the left.</li> <li>Choose the <i>Fusiontables</i> service from the list provided and turn it on.</li> <li>Go back to the main menu and select the <i>API Access</i> item. </li> </ol> <p>Your API Key will be near the bottom of that pane in the section called \"Simple API Access\". You will have to provide that key as the value for the <i>ApiKey</i> property in your Fusiontables app.</p> <p>Once you have an API key, set the value of the <i>Query</i> property to a valid Fusiontables SQL query and call <i>SendQuery</i> to execute the query. App Inventor will send the query to the Fusion Tables server and the <i>GotResult</i> block will fire when a result is returned from the server. Query results will be returned in CSV format, and can be converted to list format using the \"list from csv table\" or \"list from csv row\" blocks.</p> <p>Note that you do not need to worry about UTF-encoding the query. But you do need to make sure the query follows the syntax described in <a href=\"https://developers.google.com/fusiontables/docs/v1/getting_started\" target=\"_blank\">the reference manual</a>, which means that things like capitalization for names of columns matters, and that single quotes must be used around column names if there are spaces in them.</p>") @Description("") String FusiontablesControlHelpStringComponentPallette(); @DefaultMessage("Provides a way for applications to communicate with online game servers") @Description("") String GameClientHelpStringComponentPallette(); @DefaultMessage("<p>A formatting element in which to place components that should be displayed from left to right. If you wish to have components displayed one over another, use <code>VerticalArrangement</code> instead.</p>") @Description("") String HorizontalArrangementHelpStringComponentPallette(); @DefaultMessage("Component for displaying images. The picture to display, and other aspects of the Image\"s appearance, can be specified in the Designer or in the Blocks Editor.") @Description("") String ImageHelpStringComponentPallette(); @DefaultMessage("A special-purpose button. When the user taps an image picker, the device\"s image gallery appears, and the user can choose an image. After an image is picked, it is saved on the SD card and the <code>ImageFile</code> property will be the name of the file where the image is stored. In order to not fill up storage, a maximum of 10 images will be stored. Picking more images will delete previous images, in order from oldest to newest.") @Description("") String ImagePickerHelpStringComponentPallette(); @DefaultMessage("<p>A \"sprite\" that can be placed on a <code>Canvas</code>, where it can react to touches and drags, interact with other sprites (<code>Ball</code>s and other <code>ImageSprite</code>s) and the edge of the Canvas, and move according to its property values. Its appearance is that of the image specified in its <code>Picture</code> property (unless its <code>Visible</code> property is <code>False</code>.</p> <p>To have an <code>ImageSprite</code> move 10 pixels to the left every 1000 milliseconds (one second), for example, you would set the <code>Speed</code> property to 10 [pixels], the <code>Interval</code> property to 1000 [milliseconds], the <code>Heading</code> property to 180 [degrees], and the <code>Enabled</code> property to <code>True</code>. A sprite whose <code>Rotates</code> property is <code>True</code> will rotate its image as the sprite\"s <code>Heading</code> changes. Checking for collisions with a rotated sprite currently checks the sprite\"s unrotated position so that collision checking will be inaccurate for tall narrow or short wide sprites that are rotated. Any of the sprite properties can be changed at any time under program control.</p> ") @Description("") String ImageSpriteHelpStringComponentPallette(); @DefaultMessage("A Label displays a piece of text, which is specified through the <code>Text</code> property. Other properties, all of which can be set in the Designer or Blocks Editor, control the appearance and placement of the text.") @Description("") String LabelHelpStringComponentPallette(); @DefaultMessage("<p>A button that, when clicked on, displays a list of texts for the user to choose among. The texts can be specified through the Designer or Blocks Editor by setting the <code>ElementsFromString</code> property to their string-separated concatenation (for example, <em>choice 1, choice 2, choice 3</em>) or by setting the <code>Elements</code> property to a List in the Blocks editor.</p><p>Setting property ShowFilterBar to true, will make the list searchable. Other properties affect the appearance of the button (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be clicked on (<code>Enabled</code>).</p>") @Description("") String ListPickerHelpStringComponentPallette(); @DefaultMessage("<p>This is a visible component that allows to place a list of text elements in your Screen to display. <br> The list can be set using the ElementsFromString property or using the Elements block in the blocks editor. <br> Warning: This component will not work correctly on Screens that are scrollable.</p>") @Description("") String ListViewHelpStringComponentPallette(); @DefaultMessage("Non-visible component providing location information, including longitude, latitude, altitude (if supported by the device), and address. This can also perform \"geocoding\", converting a given address (not necessarily the current one) to a latitude (with the <code>LatitudeFromAddress</code> method) and a longitude (with the <code>LongitudeFromAddress</code> method).</p>\n<p>In order to function, the component must have its <code>Enabled</code> property set to True, and the device must have location sensing enabled through wireless networks or GPS satellites (if outdoors).</p>\nLocation information might not be immediately available when an app starts. You\"ll have to wait a short time for a location provider to be found and used, or wait for the OnLocationChanged event") @Description("") String LocationSensorHelpStringComponentPallette(); @DefaultMessage("<p>Non-visible component to provide NFC capabilities. For now this component supports the reading and writing of text tags only (if supported by the device)</p><p>In order to read and write text tags, the component must have its <code>ReadMode</code> property set to True or False respectively.</p>") @Description("") String NearFieldHelpStringComponentPallette(); @DefaultMessage("The Notifier component displays alert dialogs, messages, and temporary alerts, and creates Android log entries through the following methods: <ul><li> ShowMessageDialog: displays a message which the user must dismiss by pressing a button.</li><li> ShowChooseDialog: displays a message two buttons to let the user choose one of two responses, for example, yes or no, after which the AfterChoosing event is raised.</li><li> ShowTextDialog: lets the user enter text in response to the message, after which the AfterTextInput event is raised. <li> ShowAlert: displays a temporary alert that goes away by itself after a short time.</li><li> LogError: logs an error message to the Android log. </li><li> LogInfo: logs an info message to the Android log.</li><li> LogWarning: logs a warning message to the Android log.</li><li>The messages in the dialogs (but not the alert) can be formatted using the following HTML tags:&lt;b&gt;, &lt;big&gt;, &lt;blockquote&gt;, &lt;br&gt;, &lt;cite&gt;, &lt;dfn&gt;, &lt;div&gt;, &lt;em&gt;, &lt;small&gt;, &lt;strong&gt;, &lt;sub&gt;, &lt;sup&gt;, &lt;tt&gt;. &lt;u&gt;</li><li>You can also use the font tag to specify color, for example, &lt;font color=\"blue\"&gt;. Some of the available color names are aqua, black, blue, fuchsia, green, grey, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow</li></ul>") @Description("") String NotifierHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a color sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtColorSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a low-level interface to a LEGO MINDSTORMS NXT robot, with functions to send NXT Direct Commands.") @Description("") String NxtDirectCommandsHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a LEGO MINDSTORMS NXT robot, with functions that can move and turn the robot.") @Description("") String NxtDriveHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a light sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtLightSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a sound sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtSoundSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to a touch sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtTouchSensorHelpStringComponentPallette(); @DefaultMessage("A component that provides a high-level interface to an ultrasonic sensor on a LEGO MINDSTORMS NXT robot.") @Description("") String NxtUltrasonicSensorHelpStringComponentPallette(); @DefaultMessage("<p>Non-visible component providing information about the device\"s physical orientation in three dimensions: <ul> <li> <strong>Roll</strong>: 0 degrees when the device is level, increases to 90 degrees as the device is tilted up on its left side, and decreases to -90 degrees when the device is tilted up on its right side. </li> <li> <strong>Pitch</strong>: 0 degrees when the device is level, up to 90 degrees as the device is tilted so its top is pointing down, up to 180 degrees as it gets turned over. Similarly, as the device is tilted so its bottom points down, pitch decreases to -90 degrees, then further decreases to -180 degrees as it gets turned all the way over.</li> <li> <strong>Azimuth</strong>: 0 degrees when the top of the device is pointing north, 90 degrees when it is pointing east, 180 degrees when it is pointing south, 270 degrees when it is pointing west, etc.</li></ul> These measurements assume that the device itself is not moving.</p>") @Description("") String OrientationSensorHelpStringComponentPallette(); @DefaultMessage("<p>A box for entering passwords. This is the same as the ordinary <code>TextBox</code> component except this does not display the characters typed by the user.</p><p>The value of the text in the box can be found or set through the <code>Text</code> property. If blank, the <code>Hint</code> property, which appears as faint text in the box, can provide the user with guidance as to what to type.</p> <p>Text boxes are usually used with the <code>Button</code> component, with the user clicking on the button when text entry is complete.</p>") @Description("") String PasswordTextBoxHelpStringComponentPallette(); @DefaultMessage("Component that can count steps.") @Description("") String PedometerHelpStringComponentPallette(); @DefaultMessage("<p>A non-visible component that makes a phone call to the number specified in the <code>PhoneNumber</code> property, which can be set either in the Designer or Blocks Editor. The component has a <code>MakePhoneCall</code> method, enabling the program to launch a phone call.</p><p>Often, this component is used with the <code>ContactPicker</code> component, which lets the user select a contact from the ones stored on the phone and sets the <code>PhoneNumber</code> property to the contact\"s phone number.</p><p>To directly specify the phone number (e.g., 650-555-1212), set the <code>PhoneNumber</code> property to a Text with the specified digits (e.g., \"6505551212\"). Dashes, dots, and parentheses may be included (e.g., \"(650)-555-1212\") but will be ignored; spaces may not be included.</p>") @Description("") String PhoneCallHelpStringComponentPallette(); @DefaultMessage("A button that, when clicked on, displays a list of the contacts\" phone numbers to choose among. After the user has made a selection, the following properties will be set to information about the chosen contact: <ul>\n<li> <code>ContactName</code>: the contact\"s name </li>\n <li> <code>PhoneNumber</code>: the contact\"s phone number </li>\n <li> <code>EmailAddress</code>: the contact\"s email address </li> <li> <code>Picture</code>: the name of the file containing the contact\"s image, which can be used as a <code>Picture</code> property value for the <code>Image</code> or <code>ImageSprite</code> component.</li></ul>\n</p><p>Other properties affect the appearance of the button (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be clicked on (<code>Enabled</code>).</p>\n<p>Picking is not supported on all phones. If it fails, this component will show a notification. This default error behavior can be overridden with the Screen.ErrorOccurred event handler.") @Description("") String PhoneNumberPickerHelpStringComponentPallette(); @DefaultMessage("Component that returns information about the phone.") @Description("") String PhoneStatusHelpStringComponentPallette(); @DefaultMessage("Multimedia component that plays audio and controls phone vibration. The name of a multimedia field is specified in the <code>Source</code> property, which can be set in the Designer or in the Blocks Editor. The length of time for a vibration is specified in the Blocks Editor in milliseconds (thousandths of a second).\n<p>For supported audio formats, see <a href=\"http://developer.android.com/guide/appendix/media-formats.html\" target=\"_blank\">Android Supported Media Formats</a>.</p>\n<p>This component is best for long sound files, such as songs, while the <code>Sound</code> component is more efficient for short files, such as sound effects.</p>") @Description("") String PlayerHelpStringComponentPallette(); @DefaultMessage("Sharing is a non-visible component that enables sharing files and/or messages between your app and other apps installed on a device. The component will display a list of the installed apps that can handle the information provided, and will allow the user to choose one to share the content with, for instance a mail app, a social network app, a texting app, and so on.<br>The file path can be taken directly from other components such as the Camera or the ImagePicker, but can also be specified directly to read from storage. Be aware that different devices treat storage differently, so a few things to try if, for instance, you have a file called arrow.gif in the folder <code>Appinventor/assets</code>, would be: <ul><li><code>\"file:///sdcard/Appinventor/assets/arrow.gif\"</code></li> or <li><code>\"/storage/Appinventor/assets/arrow.gif\"</code></li></ul>") @Description("") String SharingHelpStringComponentPallette(); @DefaultMessage("A Slider is a progress bar that adds a draggable thumb. You can touch the thumb and drag left or right to set the slider thumb position. As the Slider thumb is dragged, it will trigger the PositionChanged event, reporting the position of the Slider thumb. The reported position of the Slider thumb can be used to dynamically update another component attribute, such as the font size of a TextBox or the radius of a Ball.") @Description("") String SliderHelpStringComponentPallette(); @DefaultMessage("<p>A multimedia component that plays sound files and optionally vibrates for the number of milliseconds (thousandths of a second) specified in the Blocks Editor. The name of the sound file to play can be specified either in the Designer or in the Blocks Editor.</p> <p>For supported sound file formats, see <a href=\"http://developer.android.com/guide/appendix/media-formats.html\" target=\"_blank\">Android Supported Media Formats</a>.</p><p>This <code>Sound</code> component is best for short sound files, such as sound effects, while the <code>Player</code> component is more efficient for longer sounds, such as songs.</p>") @Description("") String SoundHelpStringComponentPallette(); @DefaultMessage("<p>Multimedia component that records audio.</p>") @Description("") String SoundRecorderHelpStringComponentPallette(); @DefaultMessage("Component for using Voice Recognition to convert from speech to text") @Description("") String SpeechRecognizerHelpStringComponentPallette(); @DefaultMessage("<p>A spinner component that displays a pop-up with a list of elements. These elements can be set in the Designer or Blocks Editor by setting the<code>ElementsFromString</code> property to a string-separated concatenation (for example, <em>choice 1, choice 2, choice 3</em>) or by setting the <code>Elements</code> property to a List in the Blocks editor.</p>") @Description("") String SpinnerHelpStringComponentPallette(); @DefaultMessage("<p>A formatting element in which to place components that should be displayed in tabular form.</p>") @Description("") String TableArrangementHelpStringComponentPallette(); @DefaultMessage("<p>A box for the user to enter text. The initial or user-entered text value is in the <code>Text</code> property. If blank, the <code>Hint</code> property, which appears as faint text in the box, can provide the user with guidance as to what to type.</p><p>The <code>MultiLine</code> property determines if the text can havemore than one line. For a single line text box, the keyboard will closeautomatically when the user presses the Done key. To close the keyboard for multiline text boxes, the app should use the HideKeyboard method or rely on the user to press the Back key.</p><p>The <code> NumbersOnly</code> property restricts the keyboard to acceptnumeric input only.</p><p>Other properties affect the appearance of the text box (<code>TextAlignment</code>, <code>BackgroundColor</code>, etc.) and whether it can be used (<code>Enabled</code>).</p><p>Text boxes are usually used with the <code>Button</code> component, with the user clicking on the button when text entry is complete.</p><p>If the text entered by the user should not be displayed, use <code>PasswordTextBox</code> instead.</p>") @Description("") String TextBoxHelpStringComponentPallette(); @DefaultMessage("Component for using TextToSpeech to speak a message") @Description("") String TextToSpeechHelpStringComponentPallette(); @DefaultMessage("<p>A component that will, when the <code>SendMessage</code> method is called, send the text message specified in the <code>Message</code> property to the phone number specified in the <code>PhoneNumber</code> property.</p> <p>If the <code>ReceivingEnabled</code> property is set to 1 messages will <b>not</b> be received. If <code>ReceivingEnabled</code> is set to 2 messages will be received only when the application is running. Finally if <code>ReceivingEnabled</code> is set to 3, messages will be received when the application is running <b>and</b> when the application is not running they will be queued and a notification displayed to the user.</p> <p>When a message arrives, the <code>MessageReceived</code> event is raised and provides the sending number and message.</p> <p> An app that includes this component will receive messages even when it is in the background (i.e. when it\"s not visible on the screen) and, moreso, even if the app is not running, so long as it\"s installed on the phone. If the phone receives a text message when the app is not in the foreground, the phone will show a notification in the notification bar. Selecting the notification will bring up the app. As an app developer, you\"ll probably want to give your users the ability to control ReceivingEnabled so that they can make the phone ignore text messages.</p> <p>If the GoogleVoiceEnabled property is true, messages can be sent over Wifi using Google Voice. This option requires that the user have a Google Voice account and that the mobile Voice app is installed on the phone. The Google Voice option works only on phones that support Android 2.0 (Eclair) or higher.</p> <p>To specify the phone number (e.g., 650-555-1212), set the <code>PhoneNumber</code> property to a Text string with the specified digits (e.g., 6505551212). Dashes, dots, and parentheses may be included (e.g., (650)-555-1212) but will be ignored; spaces may not be included.</p> <p>Another way for an app to specify a phone number would be to include a <code>PhoneNumberPicker</code> component, which lets the users select a phone numbers from the ones stored in the the phone\"s contacts.</p>") @Description("") String TextingHelpStringComponentPallette(); @DefaultMessage("<p>A button that, when clicked on, launches a popup dialog to allow the user to select a time.</p>") @Description("") String TimePickerHelpStringComponentPallette(); @DefaultMessage("TinyDB is a non-visible component that stores data for an app. <p> Apps created with App Inventor are initialized each time they run: If an app sets the value of a variable and the user then quits the app, the value of that variable will not be remembered the next time the app is run. In contrast, TinyDB is a <em> persistent </em> data store for the app, that is, the data stored there will be available each time the app is run. An example might be a game that saves the high score and retrieves it each time the game is played. </<p> <p> Data items are strings stored under <em>tags</em> . To store a data item, you specify the tag it should be stored under. Subsequently, you can retrieve the data that was stored under a given tag. </p><p> There is only one data store per app. Even if you have multiple TinyDB components, they will use the same data store. To get the effect of separate stores, use different keys. Also each app has its own data store. You cannot use TinyDB to pass data between two different apps on the phone, although you <em>can</em> use TinyDb to shares data between the different screens of a multi-screen app. </p> <p>When you are developing apps using the AI Companion, all the apps using that companion will share the same TinyDb. That sharing will disappear once the apps are packaged. But, during development, you should be careful to clear the TinyDb each time you start working on a new app.</p>") @Description("") String TinyDBHelpStringComponentPallette(); @DefaultMessage("Non-visible component that communicates with a Web service to store and retrieve information.") @Description("") String TinyWebDBHelpStringComponentPallette(); @DefaultMessage("A non-visible component that enables communication with <a href=\"http://www.twitter.com\" target=\"_blank\">Twitter</a>. Once a user has logged into their Twitter account (and the authorization has been confirmed successful by the <code>IsAuthorized</code> event), many more operations are available:<ul><li> Searching Twitter for tweets or labels (<code>SearchTwitter</code>)</li>\n<li> Sending a Tweet (<code>Tweet</code>) </li>\n<li> Sending a Tweet with an Image (<code>TweetWithImage</code>) </li>\n<li> Directing a message to a specific user (<code>DirectMessage</code>)</li>\n <li> Receiving the most recent messages directed to the logged-in user (<code>RequestDirectMessages</code>)</li>\n <li> Following a specific user (<code>Follow</code>)</li>\n<li> Ceasing to follow a specific user (<code>StopFollowing</code>)</li>\n<li> Getting a list of users following the logged-in user (<code>RequestFollowers</code>)</li>\n <li> Getting the most recent messages of users followed by the logged-in user (<code>RequestFriendTimeline</code>)</li>\n <li> Getting the most recent mentions of the logged-in user (<code>RequestMentions</code>)</li></ul></p>\n <p>You must obtain a Comsumer Key and Consumer Secret for Twitter authorization specific to your app from http://twitter.com/oauth_clients/new") @Description("") String TwitterHelpStringComponentPallette(); @DefaultMessage("<p>A formatting element in which to place components that should be displayed one below another. (The first child component is stored on top, the second beneath it, etc.) If you wish to have components displayed next to one another, use <code>HorizontalArrangement</code> instead.</p>") @Description("") String VerticalArrangementHelpStringComponentPallette(); @DefaultMessage("A multimedia component capable of playing videos. When the application is run, the VideoPlayer will be displayed as a rectangle on-screen. If the user touches the rectangle, controls will appear to play/pause, skip ahead, and skip backward within the video. The application can also control behavior by calling the <code>Start</code>, <code>Pause</code>, and <code>SeekTo</code> methods. <p>Video files should be in Windows Media Video (.wmv) format, 3GPP (.3gp), or MPEG-4 (.mp4). For more details about legal formats, see <a href=\"http://developer.android.com/guide/appendix/media-formats.html\" target=\"_blank\">Android Supported Media Formats</a>.</p><p>App Inventor for Android only permits video files under 1 MB and limits the total size of an application to 5 MB, not all of which is available for media (video, audio, and sound) files. If your media files are too large, you may get errors when packaging or installing your application, in which case you should reduce the number of media files or their sizes. Most video editing software, such as Windows Movie Maker and Apple iMovie, can help you decrease the size of videos by shortening them or re-encoding the video into a more compact format.</p><p>You can also set the media source to a URL that points to a streaming video, but the URL must point to the video file itself, not to a program that plays the video.") @Description("") String VideoPlayerHelpStringComponentPallette(); @DefaultMessage("<p>The Voting component enables users to vote on a question by communicating with a Web service to retrieve a ballot and later sending back users\" votes.</p>") @Description("") String VotingHelpStringComponentPallette(); @DefaultMessage("Non-visible component that provides functions for HTTP GET, POST, PUT, and DELETE requests.") @Description("") String WebHelpStringComponentPallette(); @DefaultMessage("Component for viewing Web pages. The Home URL can be specified in the Designer or in the Blocks Editor. The view can be set to follow links when they are tapped, and users can fill in Web forms. Warning: This is not a full browser. For example, pressing the phone\"s hardware Back key will exit the app, rather than move back in the browser history.<p />You can use the WebViewer.WebViewString property to communicate between your app and Javascript code running in the Webviewer page. In the app, you get and set WebViewString. In the WebViewer, you include Javascript that references the window.AppInventor object, using the methoods </em getWebViewString()</em> and <em>setWebViewString(text)</em>. <p />For example, if the WebViewer opens to a page that contains the Javascript command <br /> <em>document.write(\"The answer is\" + window.AppInventor.getWebViewString());</em> <br />and if you set WebView.WebVewString to \"hello\", then the web page will show </br ><em>The answer is hello</em>. <br />And if the Web page contains Javascript that executes the command <br /><em>windowAppInventor.setWebViewString(\"hello from Javascript\")</em>, <br />then the value of the WebViewString property will be <br /><em>hello from Javascript</em>. ") @Description("") String WebViewerHelpStringComponentPallette(); @DefaultMessage("Use this component to translate words and sentences between different languages. This component needs Internet access, as it will request translations to the Yandex.Translate service. Specify the source and target language in the form source-target using two letter language codes. So\"en-es\" will translate from English to Spanish while \"es-ru\" will translate from Spanish to Russian. If you leave out the source language, the service will attempt to detect the source language. So providing just \"es\" will attempt to detect the source language and translate it to Spanish.<p /> This component is powered by the Yandex translation service. See http://api.yandex.com/translate/ for more information, including the list of available languages and the meanings of the language codes and status codes. <p />Note: Translation happens asynchronously in the background. When the translation is complete, the \"GotTranslation\" event is triggered.") @Description("") String YandexTranslateHelpStringComponentPallette(); //Ode.java messages @DefaultMessage("Welcome to App Inventor 2!") @Description("") String createNoProjectsDialogText(); @DefaultMessage("<p>You don\"t have any projects in App Inventor 2 yet. " + "To learn how to use App Inventor, click the \"Guide\" " + "link at the upper right of the window; or to start your first project, " + "click the \"New\" button at the upper left of the window.</p>\n<p>" + "<strong>Where did my projects go?</strong> " + "If you had projects but now they\"re missing, " + "you are probably looking for App Inventor version 1. " + "It\"s still available here: " + "<a href=\"http://beta.appinventor.mit.edu\" target=\"_blank\">beta.appinventor.mit.edu</a></p>\n") @Description("") String createNoProjectsDialogMessage1(); @DefaultMessage("Happy Inventing!") @Description("") String createNoprojectsDialogMessage2(); @DefaultMessage("Welcome to App Inventor!") @Description("") String createWelcomeDialogText(); @DefaultMessage("<h2>This is the Splash Screen. Make this an iframe to your splash screen.</h2>") @Description("") String createWelcomeDialogMessage(); @DefaultMessage("Continue") @Description("") String createWelcomeDialogButton(); @DefaultMessage("<h2>Please fill out a short voluntary survey so that we can learn more about our users and improve MIT App Inventor.</h2>") @Description("") String showSurveySplashMessage(); @DefaultMessage("Take Survey Now") @Description("") String showSurveySplashButtonNow(); @DefaultMessage("Take Survey Later") @Description("") String showSurveySplashButtonLater(); @DefaultMessage("Never Take Survey") @Description("") String showSurveySplashButtonNever(); @DefaultMessage("This Session Is Out of Date") @Description("") String invalidSessionDialogText(); @DefaultMessage("<p><font color=red>Warning:</font> This session is out of date.</p>" + "<p>This App Inventor account has been opened from another location. " + "Using a single account from more than one location at the same time " + "can damage your projects.</p>" + "<p>Choose one of the buttons below to:" + "<ul>" + "<li>End this session here.</li>" + "<li>Make this the current session and make the other sessions out of date.</li>" + "<li>Continue with both sessions.</li>" + "</ul>" + "</p>") @Description("") String invalidSessionDialogMessage(); @DefaultMessage("End This Session") @Description("") String invalidSessionDialogButtonEnd(); @DefaultMessage("Make this the current session") @Description("") String invalidSessionDialogButtonCurrent(); @DefaultMessage("Continue with Both Sessions") @Description("") String invalidSessionDialogButtonContinue(); @DefaultMessage("Do you want to continue with multiple sessions?") @Description("") String bashWarningDialogText(); @DefaultMessage("<p><font color=red>WARNING:</font> A second App " + "Inventor session has been opened for this account. You may choose to " + "continue with both sessions, but working with App Inventor from more " + "than one session simultaneously can cause blocks to be lost in ways " + "that cannot be recovered from the App Inventor server.</p><p>" + "We recommend that people not open multiple sessions on the same " + "account. But if you do need to work in this way, then you should " + "regularly export your project to your local computer, so you will " + "have a backup copy independent of the App Inventor server. Use " + "\"Export\" from the Projects menu to export the project.</p>") @Description("") String bashWarningDialogMessage(); @DefaultMessage("Continue with Multiple Sessions") @Description("") String bashWarningDialogButtonContinue(); @DefaultMessage("Do not use multiple Sessions") @Description("") String bashWarningDialogButtonNo(); @DefaultMessage("Your Session is Finished") @Description("") String finalDialogText(); @DefaultMessage("<p><b>Your Session is now ended, you may close this window</b></p>") @Description("") String finalDialogMessage(); @DefaultMessage("Project Read Error") @Description("") String corruptionDialogText(); @DefaultMessage("<p><b>We detected errors while reading in your project</b></p>" + "<p>To protect your project from damage, we have ended this session. You may close this " + "window.</p>") @Description("") String corruptionDialogMessage(); @DefaultMessage("Blocks Workspace is Empty") @Description("") String blocksTruncatedDialogText(); @DefaultMessage("<p>It appears that <b>" + "%1" + "</b> has had all blocks removed. Either you removed them intentionally, or this is " + "the result of a bug in our system.</p><p>" + "<ul><li>Select \"OK, save the empty screen\" to continue to save the empty screen</li>" + "<li>Select \"No, Don\"t Save\" below to restore the previously saved version</li></ul></p>") @Description("") String blocksTruncatedDialogMessage(); @DefaultMessage("OK, save the empty screen") @Description("") String blocksTruncatedDialogButtonSave(); @DefaultMessage("No, Don\"t Save") @Description("") String blocksTruncatedDialogButtonNoSave(); @DefaultMessage("Please wait " + "%1" + " seconds...") @Description("") String blocksTruncatedDialogButtonHTML(); @DefaultMessage("InsertRow") @Description("") String InsertRowMethods(); @DefaultMessage("GetRows") @Description("") String GetRowsMethods(); @DefaultMessage("GetRowsWithConditions") @Description("") String GetRowsWithConditionsMethods(); @DefaultMessage("简体中文") @Description("") String SwitchToSimplifiedChinese(); @DefaultMessage("繁体中文") @Description("") String SwitchToTraditionalChinese(); @DefaultMessage("Progress Bar") @Description("") String ProgressBarFor(); }
Upper Case the English name of TimePicker Have the TimePicker show up as TimePicker in the Designer Palette instead of timePicker (starting with a lower case T). Change-Id: Ic16a0acbcb56bee7995d38e5d476bab9d6d26670
appinventor/appengine/src/com/google/appinventor/client/OdeMessages.java
Upper Case the English name of TimePicker
<ide><path>ppinventor/appengine/src/com/google/appinventor/client/OdeMessages.java <ide> @Description("") <ide> String textBoxComponentPallette(); <ide> <del> @DefaultMessage("timePicker") <add> @DefaultMessage("TimePicker") <ide> @Description("") <ide> String timePickerComponentPallette(); <ide>
JavaScript
mit
b688daaf237693f35d10b27380304d76e2f44a1f
0
ChillyFlashER/OpenInput
const { description } = require('../../package') module.exports = { base: 'Mallos.Input', /** * Ref:https://v1.vuepress.vuejs.org/config/#title */ title: 'Mallos.Input Docs', /** * Ref:https://v1.vuepress.vuejs.org/config/#description */ description: description, /** * Extra tags to be injected to the page HTML `<head>` * * ref:https://v1.vuepress.vuejs.org/config/#head */ head: [ ['meta', { name: 'theme-color', content: '#3eaf7c' }], ['meta', { name: 'apple-mobile-web-app-capable', content: 'yes' }], ['meta', { name: 'apple-mobile-web-app-status-bar-style', content: 'black' }] ], /** * Theme configuration, here is the default theme configuration for VuePress. * * ref:https://v1.vuepress.vuejs.org/theme/default-theme-config.html */ themeConfig: { repo: 'https://github.com/Mallos/Mallos.Input', editLinks: false, docsDir: '', editLinkText: '', lastUpdated: false, nav: [ { text: 'Guide', link: '/guide/', } ], sidebar: { '/guide/': [ { title: 'Guide', collapsable: false, children: [ '', 'feature', 'getting-started', ] }, { title: 'Features', collapsable: false, children: [ 'features/events', 'features/input-system', 'features/combo-tracker', 'features/layout', ] }, { title: 'Platforms', collapsable: false, children: [ 'platforms/blazor', 'platforms/veldrid', ] } ], } }, /** * Apply plugins,ref:https://v1.vuepress.vuejs.org/zh/plugin/ */ plugins: [ '@vuepress/plugin-back-to-top', '@vuepress/plugin-medium-zoom', ] }
docs/.vuepress/config.js
const { description } = require('../../package') module.exports = { /** * Ref:https://v1.vuepress.vuejs.org/config/#title */ title: 'Mallos.Input Docs', /** * Ref:https://v1.vuepress.vuejs.org/config/#description */ description: description, /** * Extra tags to be injected to the page HTML `<head>` * * ref:https://v1.vuepress.vuejs.org/config/#head */ head: [ ['meta', { name: 'theme-color', content: '#3eaf7c' }], ['meta', { name: 'apple-mobile-web-app-capable', content: 'yes' }], ['meta', { name: 'apple-mobile-web-app-status-bar-style', content: 'black' }] ], /** * Theme configuration, here is the default theme configuration for VuePress. * * ref:https://v1.vuepress.vuejs.org/theme/default-theme-config.html */ themeConfig: { repo: 'https://github.com/Mallos/Mallos.Input', editLinks: false, docsDir: '', editLinkText: '', lastUpdated: false, nav: [ { text: 'Guide', link: '/guide/', } ], sidebar: { '/guide/': [ { title: 'Guide', collapsable: false, children: [ '', 'feature', 'getting-started', ] }, { title: 'Features', collapsable: false, children: [ 'features/events', 'features/input-system', 'features/combo-tracker', 'features/layout', ] }, { title: 'Platforms', collapsable: false, children: [ 'platforms/blazor', 'platforms/veldrid', ] } ], } }, /** * Apply plugins,ref:https://v1.vuepress.vuejs.org/zh/plugin/ */ plugins: [ '@vuepress/plugin-back-to-top', '@vuepress/plugin-medium-zoom', ] }
docs: update base url path
docs/.vuepress/config.js
docs: update base url path
<ide><path>ocs/.vuepress/config.js <ide> const { description } = require('../../package') <ide> <ide> module.exports = { <add> base: 'Mallos.Input', <add> <ide> /** <ide> * Ref:https://v1.vuepress.vuejs.org/config/#title <ide> */
Java
apache-2.0
0bddababba1a9127834a073c543a9ff13dd24e24
0
reactor/reactive-streams-commons,reactor/reactive-streams-commons
package rsc.publisher; import java.util.Objects; import org.reactivestreams.Subscriber; import rsc.flow.Cancellation; import rsc.scheduler.Scheduler; /** * Publisher indicating a scalar/empty source that subscribes on the specified scheduler. * * @param <T> */ final class PublisherSubscribeOnValue<T> extends Px<T> { final T value; final Scheduler scheduler; public PublisherSubscribeOnValue(T value, Scheduler scheduler) { this.value = value; this.scheduler = Objects.requireNonNull(scheduler, "scheduler"); } @Override public void subscribe(Subscriber<? super T> s) { T v = value; if (v == null) { PublisherSubscribeOn.ScheduledEmpty parent = new PublisherSubscribeOn.ScheduledEmpty(s); s.onSubscribe(parent); Cancellation f = scheduler.schedule(parent); parent.setFuture(f); } else { s.onSubscribe(new PublisherSubscribeOn.ScheduledScalar<>(s, v, scheduler)); } } }
src/main/java/rsc/publisher/PublisherSubscribeOnValue.java
package rsc.publisher; import java.util.Objects; import org.reactivestreams.Subscriber; import rsc.flow.Cancellation; import rsc.scheduler.Scheduler; import rsc.util.EmptySubscription; import rsc.util.ExceptionHelper; /** * Publisher indicating a scalar/empty source that subscribes on the specified scheduler. * * @param <T> */ final class PublisherSubscribeOnValue<T> extends Px<T> { final T value; final Scheduler scheduler; public PublisherSubscribeOnValue(T value, Scheduler scheduler) { this.value = value; this.scheduler = Objects.requireNonNull(scheduler, "scheduler"); } @Override public void subscribe(Subscriber<? super T> s) { Scheduler.Worker worker; try { worker = scheduler.createWorker(); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); EmptySubscription.error(s, e); return; } if (worker == null) { EmptySubscription.error(s, new NullPointerException("The scheduler returned a null Function")); return; } T v = value; if (v == null) { PublisherSubscribeOn.ScheduledEmpty parent = new PublisherSubscribeOn.ScheduledEmpty(s); s.onSubscribe(parent); Cancellation f = scheduler.schedule(parent); parent.setFuture(f); } else { s.onSubscribe(new PublisherSubscribeOn.ScheduledScalar<>(s, v, scheduler)); } } }
Remove unused worker (and thus a worker leak)
src/main/java/rsc/publisher/PublisherSubscribeOnValue.java
Remove unused worker (and thus a worker leak)
<ide><path>rc/main/java/rsc/publisher/PublisherSubscribeOnValue.java <ide> <ide> import rsc.flow.Cancellation; <ide> import rsc.scheduler.Scheduler; <del>import rsc.util.EmptySubscription; <del>import rsc.util.ExceptionHelper; <ide> <ide> /** <ide> * Publisher indicating a scalar/empty source that subscribes on the specified scheduler. <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T> s) { <del> Scheduler.Worker worker; <del> <del> try { <del> worker = scheduler.createWorker(); <del> } catch (Throwable e) { <del> ExceptionHelper.throwIfFatal(e); <del> EmptySubscription.error(s, e); <del> return; <del> } <del> <del> if (worker == null) { <del> EmptySubscription.error(s, new NullPointerException("The scheduler returned a null Function")); <del> return; <del> } <del> <ide> T v = value; <ide> if (v == null) { <ide> PublisherSubscribeOn.ScheduledEmpty parent = new PublisherSubscribeOn.ScheduledEmpty(s);
Java
apache-2.0
d0bf7d2b11288a09ca8ce5faffbca7c965eb494f
0
amir-zeldes/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,zangsir/ANNIS,zangsir/ANNIS,zangsir/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.querybuilder; import annis.gui.querybuilder.NodeWindow.SimpleNewItemHandler; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.server.ThemeResource; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.*; import com.vaadin.ui.themes.ChameleonTheme; /** * * @author thomas */ public class EdgeWindow extends Panel implements Button.ClickListener { private TigerQueryBuilderCanvas parent; private ComboBox cbOperator; private Button btClose; private NodeWindow source; private NodeWindow target; private TextField txtOperator; private final static String CUSTOM = "custom"; public EdgeWindow(final TigerQueryBuilderCanvas parent, NodeWindow source, NodeWindow target) { this.parent = parent; this.source = source; this.target = target; setSizeFull(); // HACK: use our own border since the one from chameleon does not really work addStyleName(ChameleonTheme.PANEL_BORDERLESS); addStyleName("border-layout"); addStyleName("solid-white-background"); VerticalLayout vLayout = new VerticalLayout(); setContent(vLayout); vLayout.setMargin(false); HorizontalLayout toolbar = new HorizontalLayout(); toolbar.addStyleName("toolbar"); toolbar.setWidth("100%"); toolbar.setHeight("-1px"); vLayout.addComponent(toolbar); Label lblTitle = new Label("AQL Operator"); lblTitle.setWidth("100%"); toolbar.addComponent(lblTitle); toolbar.setComponentAlignment(lblTitle, Alignment.MIDDLE_LEFT); btClose = new Button(); btClose.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btClose.addStyleName(ChameleonTheme.BUTTON_SMALL); btClose.setIcon(new ThemeResource("tango-icons/16x16/process-stop.png")); btClose.addListener((Button.ClickListener) this); toolbar.addComponent(btClose); toolbar.setComponentAlignment(btClose, Alignment.MIDDLE_RIGHT); cbOperator = new ComboBox(); cbOperator.setNewItemsAllowed(false); cbOperator.setTextInputAllowed(false); cbOperator.setNullSelectionAllowed(true); cbOperator.addItem(CUSTOM); cbOperator.setItemCaption(CUSTOM, "custom"); cbOperator.setNullSelectionItemId(CUSTOM); cbOperator.setNewItemHandler(new SimpleNewItemHandler(cbOperator)); cbOperator.setImmediate(true); vLayout.addComponent(cbOperator); for(AQLOperator o : AQLOperator.values()) { cbOperator.addItem(o); cbOperator.setItemCaption(o, o.getDescription() + " (" + o.getOp() + ")"); } cbOperator.setValue(AQLOperator.DIRECT_PRECEDENCE); cbOperator.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { Object val = event.getProperty().getValue(); if(val instanceof AQLOperator) { txtOperator.setValue(((AQLOperator) val).getOp()); } } }); cbOperator.setWidth("100%"); cbOperator.setHeight("20px"); txtOperator = new TextField(); txtOperator.setValue("."); txtOperator.setInputPrompt("select operator definition"); txtOperator.setSizeFull(); txtOperator.addValueChangeListener(new OperatorValueChangeListener(parent)); txtOperator.setImmediate(true); vLayout.addComponent(txtOperator); vLayout.setExpandRatio(cbOperator, 1.0f); } @Override public void buttonClick(ClickEvent event) { if(event.getButton() == btClose) { parent.deleteEdge(this); } } public NodeWindow getSource() { return source; } public NodeWindow getTarget() { return target; } private AQLOperator findAQLOperatorForText(String txt) { for(AQLOperator op : AQLOperator.values()) { if(op.getOp().equals(txt)) { return op; } } return null; } public String getOperator() { String val = txtOperator.getValue(); if(val == null || val.isEmpty()) { return "SET_OPERATOR"; } else { return val; } } private class OperatorValueChangeListener implements ValueChangeListener { private final TigerQueryBuilderCanvas parent; public OperatorValueChangeListener(TigerQueryBuilderCanvas parent) { this.parent = parent; } @Override public void valueChange(ValueChangeEvent event) { Object oldVal = cbOperator.getValue(); if(CUSTOM.equals(oldVal)) { oldVal = null; } AQLOperator newVal = findAQLOperatorForText((String) event.getProperty().getValue()); if(oldVal != newVal) { cbOperator.setValue(newVal); } if(parent != null) { parent.updateQuery(); } } } }
annis-gui/src/main/java/annis/gui/querybuilder/EdgeWindow.java
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.querybuilder; import annis.gui.querybuilder.NodeWindow.SimpleNewItemHandler; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.server.ThemeResource; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.*; import com.vaadin.ui.themes.ChameleonTheme; /** * * @author thomas */ public class EdgeWindow extends Panel implements Button.ClickListener { private TigerQueryBuilderCanvas parent; private ComboBox cbOperator; private Button btClose; private NodeWindow source; private NodeWindow target; private TextField txtOperator; private final static String CUSTOM = "custom"; public EdgeWindow(final TigerQueryBuilderCanvas parent, NodeWindow source, NodeWindow target) { this.parent = parent; this.source = source; this.target = target; setSizeFull(); // HACK: use our own border since the one from chameleon does not really work addStyleName(ChameleonTheme.PANEL_BORDERLESS); addStyleName("border-layout"); addStyleName("solid-white-background"); VerticalLayout vLayout = new VerticalLayout(); setContent(vLayout); vLayout.setMargin(false); HorizontalLayout toolbar = new HorizontalLayout(); toolbar.addStyleName("toolbar"); toolbar.setWidth("100%"); toolbar.setHeight("-1px"); vLayout.addComponent(toolbar); Label lblTitle = new Label("AQL Operator"); lblTitle.setWidth("100%"); toolbar.addComponent(lblTitle); toolbar.setComponentAlignment(lblTitle, Alignment.MIDDLE_LEFT); btClose = new Button(); btClose.addStyleName(ChameleonTheme.BUTTON_ICON_ONLY); btClose.addStyleName(ChameleonTheme.BUTTON_SMALL); btClose.setIcon(new ThemeResource("tango-icons/16x16/process-stop.png")); btClose.addListener((Button.ClickListener) this); toolbar.addComponent(btClose); toolbar.setComponentAlignment(btClose, Alignment.MIDDLE_RIGHT); cbOperator = new ComboBox(); cbOperator.setNewItemsAllowed(false); cbOperator.setNullSelectionAllowed(true); cbOperator.addItem(CUSTOM); cbOperator.setItemCaption(CUSTOM, "custom"); cbOperator.setNullSelectionItemId(CUSTOM); cbOperator.setNewItemHandler(new SimpleNewItemHandler(cbOperator)); cbOperator.setImmediate(true); cbOperator.setValue(null); vLayout.addComponent(cbOperator); for(AQLOperator o : AQLOperator.values()) { cbOperator.addItem(o); cbOperator.setItemCaption(o, o.getDescription() + " (" + o.getOp() + ")"); } cbOperator.setValue(null); cbOperator.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { Object val = event.getProperty().getValue(); if(val instanceof AQLOperator) { txtOperator.setValue(((AQLOperator) val).getOp()); } } }); cbOperator.setWidth("100%"); cbOperator.setHeight("20px"); txtOperator = new TextField(); txtOperator.setInputPrompt("select operator definition"); txtOperator.setSizeFull(); txtOperator.addValueChangeListener(new OperatorValueChangeListener(parent)); txtOperator.setImmediate(true); vLayout.addComponent(txtOperator); vLayout.setExpandRatio(cbOperator, 1.0f); } @Override public void buttonClick(ClickEvent event) { if(event.getButton() == btClose) { parent.deleteEdge(this); } } public NodeWindow getSource() { return source; } public NodeWindow getTarget() { return target; } private AQLOperator findAQLOperatorForText(String txt) { for(AQLOperator op : AQLOperator.values()) { if(op.getOp().equals(txt)) { return op; } } return null; } public String getOperator() { String val = txtOperator.getValue(); if(val == null || val.isEmpty()) { return "SET_OPERATOR"; } else { return val; } } private class OperatorValueChangeListener implements ValueChangeListener { private final TigerQueryBuilderCanvas parent; public OperatorValueChangeListener(TigerQueryBuilderCanvas parent) { this.parent = parent; } @Override public void valueChange(ValueChangeEvent event) { Object oldVal = cbOperator.getValue(); if(CUSTOM.equals(oldVal)) { oldVal = null; } AQLOperator newVal = findAQLOperatorForText((String) event.getProperty().getValue()); if(oldVal != newVal) { cbOperator.setValue(newVal); } if(parent != null) { parent.updateQuery(); } } } }
fix #280 The default operator for edges should be '.', not 'custom' The description area (where custom appears) should be uneditable and greyed out, so as not to look like a text box (right now it's very tempting to type an operator there).
annis-gui/src/main/java/annis/gui/querybuilder/EdgeWindow.java
fix #280
<ide><path>nnis-gui/src/main/java/annis/gui/querybuilder/EdgeWindow.java <ide> <ide> cbOperator = new ComboBox(); <ide> cbOperator.setNewItemsAllowed(false); <add> cbOperator.setTextInputAllowed(false); <ide> cbOperator.setNullSelectionAllowed(true); <ide> cbOperator.addItem(CUSTOM); <ide> cbOperator.setItemCaption(CUSTOM, "custom"); <ide> cbOperator.setNullSelectionItemId(CUSTOM); <ide> cbOperator.setNewItemHandler(new SimpleNewItemHandler(cbOperator)); <ide> cbOperator.setImmediate(true); <del> cbOperator.setValue(null); <ide> vLayout.addComponent(cbOperator); <ide> for(AQLOperator o : AQLOperator.values()) <ide> { <ide> cbOperator.addItem(o); <ide> cbOperator.setItemCaption(o, o.getDescription() + " (" + o.getOp() + ")"); <ide> } <del> cbOperator.setValue(null); <add> cbOperator.setValue(AQLOperator.DIRECT_PRECEDENCE); <ide> cbOperator.addValueChangeListener(new ValueChangeListener() <ide> { <ide> @Override <ide> cbOperator.setHeight("20px"); <ide> <ide> txtOperator = new TextField(); <add> txtOperator.setValue("."); <ide> txtOperator.setInputPrompt("select operator definition"); <ide> txtOperator.setSizeFull(); <ide> txtOperator.addValueChangeListener(new OperatorValueChangeListener(parent));
JavaScript
mit
0c030ba8f16b562e941bd36f91a0df9d45baa09b
0
jcopi/Selector_Library
if (!Object.assign) { Object.assign = function (target) { for (var i = 1; i < arguments.length; ++i) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty(arguments[i], key)) { target[key] = arguments[i][key]; } } } return target; } } function $ (selector, parent) { if (window === this) return new $(selector, parent); return $.css(selector, parent); } class Selector { constructor (elements, parent) { if (window === this) return new Selector(elements); this.elements = elements; this.first = [...elements][0]; this.parent = parent; } get length () { return this.elements.size; } map (fn) { let elements = []; for (let el of this.elements) { elements.push(fn(el)); } return elements; } filter (fn) { let elements = new Set(); for (let el of this.elements) { fn(el) && elements.add(el); } return new Selector(elements, this.parent); } forEach (fn) { this.elements.forEach(fn); return this; } reduce (fn, init) { for (let el of this.elements) { init = fn(init, el); } return init; } concat (sels) { if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); for (let el of sels.elements) { this.elements.add(el); } return this; } append (sel) { sel.elements.forEach((el) => { this.first.appendChild(sel); }); return this; } prepend (sel) { sel.elements.forEach(function (el) { this.first.insertBefore(el, this.first.childNodes[0]); }); return this; } insert (sel, child) { sel.elements.forEach(function (el) { this.first.insertBefore(el, child); }); return this; } appendTo (sel) { this.elements.forEach(function (el) { sel.first.appendChild(el); }); return this; } prependTo (sel) { this.elements.forEach(function (el) { sel.first.insertBefore(el, sel.first.childNodes[0]); }); return this; } insertInto (sel, child) { this.elements.forEach(function (el) { sel.first.insertBefore(el, child); }); return this; } remove () { this.elements.forEach(function (el) { el.parentNode.removeChild(el); }); return this; } event (name, callbackFn) { if (name.startsWith("on")) name = name.substring(2); this.elements.forEach(function (v) { v.addEventListener(name, callbackFn); }); return this; } trigger (str, args) { if (str.startsWith("on")) str = str.substring(2); if (!args) args = {}; switch (true) { case (str.startsWith("key") == 0): /* if the event begins with 'key', dispatch a KeyboardEvent */ this.elements.forEach(function (v) { args.relatedTarget = v; var ev = new KeyboardEvent(str, opts); v.dispatchEvent(ev); }); break; /* All other event will be dispatched as MouseEvents Some events require a specific button index */ case (str == "click" || str == "mouseup" || str == "mousedown"): this.elements.forEach(function (v) { args.button = 0; args.relatedTarget = v; var ev = new MouseEvent(str, args); v.dispatchEvent(ev); }); break; case (str == "contextmenu"): this.elements.forEach(function (v) { args.button = 2; args.relatedTarget = v; var ev = new MouseEvent(str, args); v.dispatchEvent(ev); }); break; default: this.elements.forEach(function (v) { args.relatedTarget = v; var ev = new MouseEvent(str, args); v.dispatchEvent(ev); }); break; } return this; } styles (styleObj) { this.elements.forEach(function (v) { Object.assign(v.style, styleObj); }); return this; } and (sel) { // Create a list of elements in both this and sel if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { if (sel.elements.has(el)) { elements.add(el); } } return new Selector(elements, this.parent); } or (sel) { // Create a list of elements in either this or sel if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { elements.add(el); } for (let el of sel.elements) { elements.add(el); } return new Selector(elements, this.parent); } xor (sel) { // Create a set of elements in either this or sel, but not both if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { if (!sel.elements.has(el)) { elements.add(el); } } for (let el of sel.elements) { if (!this.elements.has(el)) { elements.add(el); } } return new Selector(elements, this.parent); } not (sel) { // Create a set of elements not in 'sel' if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { if (!sel.elements.has(el)) { elements.add(el); } } return new Selector(elements, this.parent); } } $.id = function (id, parent) { // Ensure inputs are of the correct type if (!(parent && "getElementById" in parent)) parent = document; if (id.startsWith("#")) id = id.substring(1); let element = new Set(parent.getElementById(id)); return new Selector(element, parent); } $.css = function (selector, parent) { if (!(parent && "querySelectorAll" in parent)) parent = document; let elements = new Set(parent.querySelectorAll(selector)); return new Selector(elements, parent); }; $.tag = function (tname, parent) { if (!(parent && "getElementsByTagName" in parent)) parent = document; let elements = new Set(parent.getElementsByClassName(tname)); return new Selector(elements, parent); }; $.name = function (name, parent) { if (!(parent && "getElementsByName" in parent)) parent = document; let elements = new Set(parent.getElementsByName(name)); return new Selector(elements, parent); }; $.class = function (cname, parent) { if (!(parent && "getElementsByClassName" in parent)) parent = document; if (cname.startsWith(".")) cname = cname.substring(1); let elements = new Set(parent.getElementsByClassName(cname)); return new Selector(elements, parent); }; $.element = function (el, parent) { if (!parent) parent = document; let elements = new Set([el]); return new Selector(elements, parent); } $.list = function (els, parent) { if (!parent) parent = document; let elements = new Set(els); return new Selector(elements, parent); } $.compile = function (selector) { // O(n) if (!selector.startsWith('<') || !selector.endsWith('>')) { console.error("Invalid element creation string."); } // Create an element based on the creation string let master = null; // Prepare string for processing selector = selector.substring(1, selector.length - 1); selector += '\0'; // list of key characters to influence processing let chkArray = ['.','#','$','[',']','\0']; for (let i = 0, state = 0, ptr = 0, esc = false, strStart = -1, tmp = ""; i < selector.length; ++i) { if (esc) { tmp += selector[i]; esc = false; continue; } else if (selector[i] == "\\") { esc = true; continue; } else if (strStart >= 0) { if (selector[i] == selector[strStart]) { tmp += selector.slice(strStart + 1, i); strStart = -1; } continue; } else if (selector[i] == "'" || selector == '"') { strStart = i; continue; } let chk = chkArray.indexOf(selector[i]); if (chk >= 0) { switch (state) { case 0: master = document.createElement(tmp); break; case 1: master.classList.add(tmp); break; case 2: master.id = tmp; break; case 3: master.name = tmp; break; case 4: if (chk !== 4) continue; let vals = tmp.split('=', 2); master.setAttribute(vals[0], vals[1]); break; } state = chk + 1; tmp = ""; } else { tmp += selector[i]; } } return function (master) { let el = master.cloneNode(true); let elements = new Set([el]); return new Selector(elements, document); } }; $.build = function (str) { return $.compile(str)(); }; $.utils = { array: { backSwap: function (arr, i) { var tmp = arr[i]; arr[i] = arr[arr.length - 1]; arr[arr.length - 1] = tmp; }, unorderedRemove: function (arr, i) { arr[i] = arr[arr.length - 1]; arr.pop(); }, removeDuplicates: function (arr) { for (var i = 0; i < arr.length; ++i) { for (var j = i + 1; j < arr.length; ++j) { if (arr[i] === arr[j]) { $.utils.array.unorderedRemove(arr, i--); break; } } } } } }
selector.js
if (!Object.assign) { Object.assign = function (target) { for (var i = 1; i < arguments.length; ++i) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty(arguments[i], key)) { target[key] = arguments[i][key]; } } } return target; } } function $ (selector, parent) { if (window === this) return new $(selector, parent); return $.css(selector, parent); } function Selector (elements, parent) { if (window === this) return new Selector(elements); this.elements = elements; this.first = [...elements][0]; this.parent = parent; } $.id = function (id, parent) { // Ensure inputs are of the correct type if (!(parent && "getElementById" in parent)) parent = document; if (id.startsWith("#")) id = id.substring(1); let element = new Set(parent.getElementById(id)); return new Selector(element, parent); } $.css = function (selector, parent) { if (!(parent && "querySelectorAll" in parent)) parent = document; let elements = new Set(parent.querySelectorAll(selector)); return new Selector(elements, parent); }; $.tag = function (tname, parent) { if (!(parent && "getElementsByTagName" in parent)) parent = document; let elements = new Set(parent.getElementsByClassName(tname)); return new Selector(elements, parent); }; $.name = function (name, parent) { if (!(parent && "getElementsByName" in parent)) parent = document; let elements = new Set(parent.getElementsByName(name)); return new Selector(elements, parent); }; $.class = function (cname, parent) { if (!(parent && "getElementsByClassName" in parent)) parent = document; if (cname.startsWith(".")) cname = cname.substring(1); let elements = new Set(parent.getElementsByClassName(cname)); return new Selector(elements, parent); }; $.element = function (el, parent) { if (!parent) parent = document; let elements = new Set([el]); return new Selector(elements, parent); } $.list = function (els, parent) { if (!parent) parent = document; let elements = new Set(els); return new Selector(elements, parent); } $.compile = function (selector) { // O(n) if (!selector.startsWith('<') || !selector.endsWith('>')) { console.error("Invalid element creation string."); } // Create an element based on the creation string let master = null; // Prepare string for processing selector = selector.substring(1, selector.length - 1); selector += '\0'; // list of key characters to influence processing let chkArray = ['.','#','$','[',']','\0']; for (let i = 0, state = 0, ptr = 0, esc = false, strStart = -1, tmp = ""; i < selector.length; ++i) { if (esc) { tmp += selector[i]; esc = false; continue; } else if (selector[i] == "\\") { esc = true; continue; } else if (strStart >= 0) { if (selector[i] == selector[strStart]) { tmp += selector.slice(strStart + 1, i); strStart = -1; } continue; } else if (selector[i] == "'" || selector == '"') { strStart = i; continue; } let chk = chkArray.indexOf(selector[i]); if (chk >= 0) { switch (state) { case 0: master = document.createElement(tmp); break; case 1: master.classList.add(tmp); break; case 2: master.id = tmp; break; case 3: master.name = tmp; break; case 4: if (chk !== 4) continue; let vals = tmp.split('=', 2); master.setAttribute(vals[0], vals[1]); break; } state = chk + 1; tmp = ""; } else { tmp += selector[i]; } } return function (master) { let el = master.cloneNode(true); let elements = new Set([el]); return new Selector(elements, document); } }; $.build = function (str) { return $.compile(str)(); }; $.utils = { array: { backSwap: function (arr, i) { var tmp = arr[i]; arr[i] = arr[arr.length - 1]; arr[arr.length - 1] = tmp; }, unorderedRemove: function (arr, i) { arr[i] = arr[arr.length - 1]; arr.pop(); }, removeDuplicates: function (arr) { for (var i = 0; i < arr.length; ++i) { for (var j = i + 1; j < arr.length; ++j) { if (arr[i] === arr[j]) { $.utils.array.unorderedRemove(arr, i--); break; } } } } } } Selector.prototype = { constructor: Selector, map: function (fn) { let elements = []; for (let el of this.elements) { elements.push(fn(el)); } return elements; }, filter: function (fn) { let elements = new Set(); for (let el of this.elements) { fn(el) && elements.add(el); } return new Selector(elements, this.parent); }, forEach: function (fn) { this.elements.forEach(fn); return this; }, reduce: function (fn, init) { for (let el of this.elements) { init = fn(init, el); } return init; }, concat: function (sels) { if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); for (let el of sels.elements) { this.elements.add(el); } return this; }, append: function (sel) { sel.elements.forEach((el) => { this.first.appendChild(sel); }); return this; }, prepend: function (sel) { sel.elements.forEach(function (el) { this.first.insertBefore(el, this.first.childNodes[0]); }); return this; }, insert: function (sel, child) { sel.elements.forEach(function (el) { this.first.insertBefore(el, child); }); return this; }, appendTo: function (sel) { this.elements.forEach(function (el) { sel.first.appendChild(el); }); return this; }, prependTo: function (sel) { this.elements.forEach(function (el) { sel.first.insertBefore(el, sel.first.childNodes[0]); }); return this; }, insertInto: function (sel, child) { this.elements.forEach(function (el) { sel.first.insertBefore(el, child); }); return this; }, remove: function () { this.elements.forEach(function (el) { el.parentNode.removeChild(el); }); return this; }, event: function (name, callbackFn) { if (name.startsWith("on")) name = name.substring(2); this.elements.forEach(function (v) { v.addEventListener(name, callbackFn); }); return this; }, trigger: function (str, args) { if (str.startsWith("on")) str = str.substring(2); if (!args) args = {}; switch (true) { case (str.startsWith("key") == 0): /* if the event begins with 'key', dispatch a KeyboardEvent */ this.elements.forEach(function (v) { args.relatedTarget = v; var ev = new KeyboardEvent(str, opts); v.dispatchEvent(ev); }); break; /* All other event will be dispatched as MouseEvents Some events require a specific button index */ case (str == "click" || str == "mouseup" || str == "mousedown"): this.elements.forEach(function (v) { args.button = 0; args.relatedTarget = v; var ev = new MouseEvent(str, args); v.dispatchEvent(ev); }); break; case (str == "contextmenu"): this.elements.forEach(function (v) { args.button = 2; args.relatedTarget = v; var ev = new MouseEvent(str, args); v.dispatchEvent(ev); }); break; default: this.elements.forEach(function (v) { args.relatedTarget = v; var ev = new MouseEvent(str, args); v.dispatchEvent(ev); }); break; } return this; }, styles: function (styleObj) { this.elements.forEach(function (v) { Object.assign(v.style, styleObj); }); return this; }, and: function (sel) { // Create a list of elements in both this and sel if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { if (sel.elements.has(el)) { elements.add(el); } } return new Selector(elements, this.parent); }, or: function (sel) { // Create a list of elements in either this or sel if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { elements.add(el); } for (let el of sel.elements) { elements.add(el); } return new Selector(elements, this.parent); }, xor: function (sel) { // Create a set of elements in either this or sel, but not both if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { if (!sel.elements.has(el)) { elements.add(el); } } for (let el of sel.elements) { if (!this.elements.has(el)) { elements.add(el); } } return new Selector(elements, this.parent); }, not: function (sel) { // Create a set of elements not in 'sel' if (!(sel instanceof Selector)) return console.error("Argument not instance of Selector ($)."); let elements = new Set(); for (let el of this.elements) { if (!sel.elements.has(el)) { elements.add(el); } } return new Selector(elements, this.parent); } }
Changed Selector to es6 class
selector.js
Changed Selector to es6 class
<ide><path>elector.js <ide> return $.css(selector, parent); <ide> } <ide> <del>function Selector (elements, parent) { <del> if (window === this) <del> return new Selector(elements); <del> <del> this.elements = elements; <del> this.first = [...elements][0]; <del> this.parent = parent; <del>} <del> <del>$.id = function (id, parent) { <del> // Ensure inputs are of the correct type <del> if (!(parent && "getElementById" in parent)) parent = document; <del> if (id.startsWith("#")) id = id.substring(1); <del> <del> let element = new Set(parent.getElementById(id)); <del> return new Selector(element, parent); <del>} <del> <del>$.css = function (selector, parent) { <del> if (!(parent && "querySelectorAll" in parent)) parent = document; <del> <del> let elements = new Set(parent.querySelectorAll(selector)); <del> return new Selector(elements, parent); <del>}; <del> <del>$.tag = function (tname, parent) { <del> if (!(parent && "getElementsByTagName" in parent)) parent = document; <del> <del> let elements = new Set(parent.getElementsByClassName(tname)); <del> return new Selector(elements, parent); <del>}; <del> <del>$.name = function (name, parent) { <del> if (!(parent && "getElementsByName" in parent)) parent = document; <del> <del> let elements = new Set(parent.getElementsByName(name)); <del> return new Selector(elements, parent); <del>}; <del> <del>$.class = function (cname, parent) { <del> if (!(parent && "getElementsByClassName" in parent)) parent = document; <del> if (cname.startsWith(".")) cname = cname.substring(1); <del> <del> let elements = new Set(parent.getElementsByClassName(cname)); <del> return new Selector(elements, parent); <del>}; <del> <del>$.element = function (el, parent) { <del> if (!parent) parent = document; <del> <del> let elements = new Set([el]); <del> return new Selector(elements, parent); <del>} <del> <del>$.list = function (els, parent) { <del> if (!parent) parent = document; <del> <del> let elements = new Set(els); <del> return new Selector(elements, parent); <del>} <del> <del>$.compile = function (selector) { <del> // O(n) <del> if (!selector.startsWith('<') || !selector.endsWith('>')) { <del> console.error("Invalid element creation string."); <del> } <del> // Create an element based on the creation string <del> let master = null; <del> // Prepare string for processing <del> selector = selector.substring(1, selector.length - 1); <del> selector += '\0'; <del> // list of key characters to influence processing <del> let chkArray = ['.','#','$','[',']','\0']; <del> for (let i = 0, state = 0, ptr = 0, esc = false, strStart = -1, tmp = ""; i < selector.length; ++i) { <del> if (esc) { <del> tmp += selector[i]; <del> esc = false; <del> continue; <del> } else if (selector[i] == "\\") { <del> esc = true; <del> continue; <del> } else if (strStart >= 0) { <del> if (selector[i] == selector[strStart]) { <del> tmp += selector.slice(strStart + 1, i); <del> strStart = -1; <del> } <del> continue; <del> } else if (selector[i] == "'" || selector == '"') { <del> strStart = i; <del> continue; <del> } <del> <del> let chk = chkArray.indexOf(selector[i]); <del> if (chk >= 0) { <del> switch (state) { <del> case 0: <del> master = document.createElement(tmp); <del> break; <del> case 1: <del> master.classList.add(tmp); <del> break; <del> case 2: <del> master.id = tmp; <del> break; <del> case 3: <del> master.name = tmp; <del> break; <del> case 4: <del> if (chk !== 4) <del> continue; <del> <del> let vals = tmp.split('=', 2); <del> master.setAttribute(vals[0], vals[1]); <del> break; <del> } <del> <del> state = chk + 1; <del> tmp = ""; <del> } else { <del> tmp += selector[i]; <del> } <del> } <del> <del> return function (master) { <del> let el = master.cloneNode(true); <del> let elements = new Set([el]); <del> return new Selector(elements, document); <del> } <del>}; <del>$.build = function (str) { <del> return $.compile(str)(); <del>}; <del> <del>$.utils = { <del> array: { <del> backSwap: function (arr, i) { <del> var tmp = arr[i]; <del> arr[i] = arr[arr.length - 1]; <del> arr[arr.length - 1] = tmp; <del> }, <del> unorderedRemove: function (arr, i) { <del> arr[i] = arr[arr.length - 1]; <del> arr.pop(); <del> }, <del> removeDuplicates: function (arr) { <del> for (var i = 0; i < arr.length; ++i) { <del> for (var j = i + 1; j < arr.length; ++j) { <del> if (arr[i] === arr[j]) { <del> $.utils.array.unorderedRemove(arr, i--); <del> break; <del> } <del> } <del> } <del> } <del> } <del>} <del> <del>Selector.prototype = { <del> constructor: Selector, <del> map: function (fn) { <add>class Selector { <add> constructor (elements, parent) { <add> if (window === this) <add> return new Selector(elements); <add> <add> this.elements = elements; <add> this.first = [...elements][0]; <add> this.parent = parent; <add> } <add> <add> get length () { <add> return this.elements.size; <add> } <add> <add> map (fn) { <ide> let elements = []; <ide> for (let el of this.elements) { <ide> elements.push(fn(el)); <ide> } <ide> <ide> return elements; <del> }, <del> filter: function (fn) { <add> } <add> <add> filter (fn) { <ide> let elements = new Set(); <ide> for (let el of this.elements) { <ide> fn(el) && elements.add(el); <ide> } <ide> <ide> return new Selector(elements, this.parent); <del> }, <del> forEach: function (fn) { <add> } <add> <add> forEach (fn) { <ide> this.elements.forEach(fn); <ide> return this; <del> }, <del> reduce: function (fn, init) { <add> } <add> <add> reduce (fn, init) { <ide> for (let el of this.elements) { <ide> init = fn(init, el); <ide> } <ide> <ide> return init; <del> }, <del> concat: function (sels) { <add> } <add> <add> concat (sels) { <ide> if (!(sel instanceof Selector)) <ide> return console.error("Argument not instance of Selector ($)."); <ide> <ide> this.elements.add(el); <ide> } <ide> return this; <del> }, <del> <del> append: function (sel) { <add> } <add> <add> append (sel) { <ide> sel.elements.forEach((el) => { <ide> this.first.appendChild(sel); <ide> }); <ide> return this; <del> }, <del> prepend: function (sel) { <add> } <add> <add> prepend (sel) { <ide> sel.elements.forEach(function (el) { <ide> this.first.insertBefore(el, this.first.childNodes[0]); <ide> }); <ide> return this; <del> }, <del> insert: function (sel, child) { <add> } <add> <add> insert (sel, child) { <ide> sel.elements.forEach(function (el) { <ide> this.first.insertBefore(el, child); <ide> }); <ide> return this; <del> }, <del> appendTo: function (sel) { <add> } <add> <add> appendTo (sel) { <ide> this.elements.forEach(function (el) { <ide> sel.first.appendChild(el); <ide> }); <ide> return this; <del> }, <del> prependTo: function (sel) { <add> } <add> <add> prependTo (sel) { <ide> this.elements.forEach(function (el) { <ide> sel.first.insertBefore(el, sel.first.childNodes[0]); <ide> }); <ide> return this; <del> }, <del> insertInto: function (sel, child) { <add> } <add> <add> insertInto (sel, child) { <ide> this.elements.forEach(function (el) { <ide> sel.first.insertBefore(el, child); <ide> }); <ide> return this; <del> }, <del> remove: function () { <add> } <add> <add> remove () { <ide> this.elements.forEach(function (el) { <ide> el.parentNode.removeChild(el); <ide> }); <ide> return this; <del> }, <del> <del> event: function (name, callbackFn) { <add> } <add> <add> event (name, callbackFn) { <ide> if (name.startsWith("on")) name = name.substring(2); <ide> <ide> this.elements.forEach(function (v) { <ide> v.addEventListener(name, callbackFn); <ide> }); <ide> return this; <del> }, <del> <del> trigger: function (str, args) { <add> } <add> <add> trigger (str, args) { <ide> if (str.startsWith("on")) str = str.substring(2); <ide> if (!args) args = {}; <ide> <ide> } <ide> <ide> return this; <del> }, <del> styles: function (styleObj) { <add> } <add> <add> styles (styleObj) { <ide> this.elements.forEach(function (v) { <ide> Object.assign(v.style, styleObj); <ide> }); <ide> <ide> return this; <del> }, <del> <del> and: function (sel) { <add> } <add> <add> and (sel) { <ide> // Create a list of elements in both this and sel <ide> if (!(sel instanceof Selector)) <ide> return console.error("Argument not instance of Selector ($)."); <ide> } <ide> } <ide> return new Selector(elements, this.parent); <del> }, <del> or: function (sel) { <add> } <add> <add> or (sel) { <ide> // Create a list of elements in either this or sel <ide> if (!(sel instanceof Selector)) <ide> return console.error("Argument not instance of Selector ($)."); <ide> } <ide> <ide> return new Selector(elements, this.parent); <del> }, <del> xor: function (sel) { <add> } <add> <add> xor (sel) { <ide> // Create a set of elements in either this or sel, but not both <ide> if (!(sel instanceof Selector)) <ide> return console.error("Argument not instance of Selector ($)."); <ide> } <ide> <ide> return new Selector(elements, this.parent); <del> }, <del> not: function (sel) { <add> } <add> <add> not (sel) { <ide> // Create a set of elements not in 'sel' <ide> if (!(sel instanceof Selector)) <ide> return console.error("Argument not instance of Selector ($)."); <ide> return new Selector(elements, this.parent); <ide> } <ide> } <add> <add>$.id = function (id, parent) { <add> // Ensure inputs are of the correct type <add> if (!(parent && "getElementById" in parent)) parent = document; <add> if (id.startsWith("#")) id = id.substring(1); <add> <add> let element = new Set(parent.getElementById(id)); <add> return new Selector(element, parent); <add>} <add> <add>$.css = function (selector, parent) { <add> if (!(parent && "querySelectorAll" in parent)) parent = document; <add> <add> let elements = new Set(parent.querySelectorAll(selector)); <add> return new Selector(elements, parent); <add>}; <add> <add>$.tag = function (tname, parent) { <add> if (!(parent && "getElementsByTagName" in parent)) parent = document; <add> <add> let elements = new Set(parent.getElementsByClassName(tname)); <add> return new Selector(elements, parent); <add>}; <add> <add>$.name = function (name, parent) { <add> if (!(parent && "getElementsByName" in parent)) parent = document; <add> <add> let elements = new Set(parent.getElementsByName(name)); <add> return new Selector(elements, parent); <add>}; <add> <add>$.class = function (cname, parent) { <add> if (!(parent && "getElementsByClassName" in parent)) parent = document; <add> if (cname.startsWith(".")) cname = cname.substring(1); <add> <add> let elements = new Set(parent.getElementsByClassName(cname)); <add> return new Selector(elements, parent); <add>}; <add> <add>$.element = function (el, parent) { <add> if (!parent) parent = document; <add> <add> let elements = new Set([el]); <add> return new Selector(elements, parent); <add>} <add> <add>$.list = function (els, parent) { <add> if (!parent) parent = document; <add> <add> let elements = new Set(els); <add> return new Selector(elements, parent); <add>} <add> <add>$.compile = function (selector) { <add> // O(n) <add> if (!selector.startsWith('<') || !selector.endsWith('>')) { <add> console.error("Invalid element creation string."); <add> } <add> // Create an element based on the creation string <add> let master = null; <add> // Prepare string for processing <add> selector = selector.substring(1, selector.length - 1); <add> selector += '\0'; <add> // list of key characters to influence processing <add> let chkArray = ['.','#','$','[',']','\0']; <add> for (let i = 0, state = 0, ptr = 0, esc = false, strStart = -1, tmp = ""; i < selector.length; ++i) { <add> if (esc) { <add> tmp += selector[i]; <add> esc = false; <add> continue; <add> } else if (selector[i] == "\\") { <add> esc = true; <add> continue; <add> } else if (strStart >= 0) { <add> if (selector[i] == selector[strStart]) { <add> tmp += selector.slice(strStart + 1, i); <add> strStart = -1; <add> } <add> continue; <add> } else if (selector[i] == "'" || selector == '"') { <add> strStart = i; <add> continue; <add> } <add> <add> let chk = chkArray.indexOf(selector[i]); <add> if (chk >= 0) { <add> switch (state) { <add> case 0: <add> master = document.createElement(tmp); <add> break; <add> case 1: <add> master.classList.add(tmp); <add> break; <add> case 2: <add> master.id = tmp; <add> break; <add> case 3: <add> master.name = tmp; <add> break; <add> case 4: <add> if (chk !== 4) <add> continue; <add> <add> let vals = tmp.split('=', 2); <add> master.setAttribute(vals[0], vals[1]); <add> break; <add> } <add> <add> state = chk + 1; <add> tmp = ""; <add> } else { <add> tmp += selector[i]; <add> } <add> } <add> <add> return function (master) { <add> let el = master.cloneNode(true); <add> let elements = new Set([el]); <add> return new Selector(elements, document); <add> } <add>}; <add>$.build = function (str) { <add> return $.compile(str)(); <add>}; <add> <add>$.utils = { <add> array: { <add> backSwap: function (arr, i) { <add> var tmp = arr[i]; <add> arr[i] = arr[arr.length - 1]; <add> arr[arr.length - 1] = tmp; <add> }, <add> unorderedRemove: function (arr, i) { <add> arr[i] = arr[arr.length - 1]; <add> arr.pop(); <add> }, <add> removeDuplicates: function (arr) { <add> for (var i = 0; i < arr.length; ++i) { <add> for (var j = i + 1; j < arr.length; ++j) { <add> if (arr[i] === arr[j]) { <add> $.utils.array.unorderedRemove(arr, i--); <add> break; <add> } <add> } <add> } <add> } <add> } <add>} <add>
Java
bsd-2-clause
29eeab2f87188aeb95131fbb8c21b2ecbfbb8273
0
dragondgold/MultiWork
package com.multiwork.andres; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.protocolanalyzer.andres.LogicData; import com.protocolanalyzer.andres.LogicData.Protocol; import android.os.Bundle; import android.text.Html; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class LogicAnalizerListFragment extends SherlockFragment implements OnDataDecodedListener{ private static final boolean DEBUG = true; private static SherlockFragmentActivity mActivity; private static ActionBar mActionBar; private static TextView mRawData[] = new TextView[LogicAnalizerActivity.channelsNumber]; private static OnActionBarClickListener mActionBarListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(DEBUG) Log.i("mFragment2","onCreate()"); // Obtengo la Activity que contiene el Fragment mActivity = getSherlockActivity(); mActionBar = mActivity.getSupportActionBar(); // Obtengo el ActionBar mActionBar.setDisplayHomeAsUpEnabled(true); // El icono de la aplicacion funciona como boton HOME mActionBar.setTitle(getString(R.string.AnalyzerName)) ; // Nombre this.setHasOptionsMenu(true); // Obtengo el OnActionBarClickListener de la Activity try { mActionBarListener = (OnActionBarClickListener) mActivity; } catch (ClassCastException e) { throw new ClassCastException(mActivity.toString() + " must implement OnActionBarClickListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.logic_rawdata, container, false); mRawData[0] = (TextView) v.findViewById(R.id.tvRawDataLogic1); mRawData[0].setMovementMethod(new ScrollingMovementMethod()); mRawData[1] = (TextView) v.findViewById(R.id.tvRawDataLogic2); mRawData[1].setMovementMethod(new ScrollingMovementMethod()); mRawData[2] = (TextView) v.findViewById(R.id.tvRawDataLogic3); mRawData[2].setMovementMethod(new ScrollingMovementMethod()); mRawData[3] = (TextView) v.findViewById(R.id.tvRawDataLogic4); mRawData[3].setMovementMethod(new ScrollingMovementMethod()); mRawData[1].setPadding(40, 0, 0, 0); mRawData[2].setPadding(40, 0, 0, 0); mRawData[3].setPadding(40, 0, 0, 0); /** Hace que todos los toques en la pantalla sean para esta Fragment y no el que esta detras */ v.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); return v; } @Override public void onResume() { super.onResume(); if(DEBUG) Log.i("mFragment2","Resume"); } @Override public double onDataDecodedListener(LogicData[] mLogicData, int samplesCount) { if(DEBUG) Log.i("mFragment2","onDataDecodedListener() - " + mLogicData.length + " channels"); for(int n=0; n < mRawData.length; ++n) mRawData[n].setText(""); for(int n=0; n < mRawData.length; ++n){ if(mLogicData[n].getProtocol() != Protocol.CLOCK){ mRawData[n].append( Html.fromHtml("<u>Canal " + (n+1) + " - " + mLogicData[n].getProtocol().toString() + "</u><br/>") ); for(int i=0; i < mLogicData[n].getStringCount(); ++i){ // Con código HTML se puede aplicar propiedades de texto a ciertas partes unicamente // http://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview mRawData[n].append( Html.fromHtml("<b><font color=#ff0000>" + mLogicData[n].getString(i) + "</font></b>" + "\t --> " + String.format("%.2f", (mLogicData[n].getPositionAt(i)[0]*1000000)) + "uS<br/>") ); } } } return 0; } }
src/com/multiwork/andres/LogicAnalizerListFragment.java
package com.multiwork.andres; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.protocolanalyzer.andres.LogicData; import com.protocolanalyzer.andres.LogicData.Protocol; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class LogicAnalizerListFragment extends SherlockFragment implements OnDataDecodedListener{ private static final boolean DEBUG = true; private static SherlockFragmentActivity mActivity; private static ActionBar mActionBar; private static TextView mRawData[] = new TextView[LogicAnalizerActivity.channelsNumber]; private static OnActionBarClickListener mActionBarListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(DEBUG) Log.i("mFragment2","onCreate()"); // Obtengo la Activity que contiene el Fragment mActivity = getSherlockActivity(); mActionBar = mActivity.getSupportActionBar(); // Obtengo el ActionBar mActionBar.setDisplayHomeAsUpEnabled(true); // El icono de la aplicacion funciona como boton HOME mActionBar.setTitle(getString(R.string.AnalyzerName)) ; // Nombre this.setHasOptionsMenu(true); // Obtengo el OnActionBarClickListener de la Activity try { mActionBarListener = (OnActionBarClickListener) mActivity; } catch (ClassCastException e) { throw new ClassCastException(mActivity.toString() + " must implement OnActionBarClickListener"); } mActionBarListener.onActionBarClickListener(R.id.PlayPauseLogic); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.logic_rawdata, container, false); mRawData[0] = (TextView) v.findViewById(R.id.tvRawDataLogic1); mRawData[0].setMovementMethod(new ScrollingMovementMethod()); mRawData[1] = (TextView) v.findViewById(R.id.tvRawDataLogic2); mRawData[1].setMovementMethod(new ScrollingMovementMethod()); mRawData[2] = (TextView) v.findViewById(R.id.tvRawDataLogic3); mRawData[2].setMovementMethod(new ScrollingMovementMethod()); mRawData[3] = (TextView) v.findViewById(R.id.tvRawDataLogic4); mRawData[3].setMovementMethod(new ScrollingMovementMethod()); mRawData[1].setPadding(40, 0, 0, 0); mRawData[2].setPadding(40, 0, 0, 0); mRawData[3].setPadding(40, 0, 0, 0); /** Hace que todos los toques en la pantalla sean para esta Fragment y no el que esta detras */ v.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); return v; } @Override public void onResume() { super.onResume(); if(DEBUG) Log.i("mFragment2","Resume"); } @Override public double onDataDecodedListener(LogicData[] mLogicData, int samplesCount) { if(DEBUG) Log.i("mFragment2","onDataDecodedListener() - " + mLogicData.length + " channels"); for(int n=0; n < mRawData.length; ++n) mRawData[n].setText(""); for(int n=0; n < mRawData.length; ++n){ if(mLogicData[n].getProtocol() != Protocol.CLOCK){ mRawData[n].append("Canal " + n + " - " + mLogicData[n].getProtocol().toString() + "\n"); for(int i=0; i < mLogicData[n].getStringCount(); ++i){ mRawData[n].append(mLogicData[n].getString(i) + "\t --> " + String.format("%.2f", (mLogicData[n].getPositionAt(i)[0]*1000000)) + "uS\n"); } mRawData[n].append("\n"); } } return 0; } }
Resaltado del texto decodificado
src/com/multiwork/andres/LogicAnalizerListFragment.java
Resaltado del texto decodificado
<ide><path>rc/com/multiwork/andres/LogicAnalizerListFragment.java <ide> import com.protocolanalyzer.andres.LogicData.Protocol; <ide> <ide> import android.os.Bundle; <add>import android.text.Html; <ide> import android.text.method.ScrollingMovementMethod; <ide> import android.util.Log; <ide> import android.view.LayoutInflater; <ide> // Obtengo el OnActionBarClickListener de la Activity <ide> try { mActionBarListener = (OnActionBarClickListener) mActivity; } <ide> catch (ClassCastException e) { throw new ClassCastException(mActivity.toString() + " must implement OnActionBarClickListener"); } <del> <del> mActionBarListener.onActionBarClickListener(R.id.PlayPauseLogic); <ide> <ide> } <ide> <ide> if(DEBUG) Log.i("mFragment2","onDataDecodedListener() - " + mLogicData.length + " channels"); <ide> <ide> for(int n=0; n < mRawData.length; ++n) mRawData[n].setText(""); <del> <add> <ide> for(int n=0; n < mRawData.length; ++n){ <ide> if(mLogicData[n].getProtocol() != Protocol.CLOCK){ <del> mRawData[n].append("Canal " + n + " - " + mLogicData[n].getProtocol().toString() + "\n"); <add> mRawData[n].append( Html.fromHtml("<u>Canal " + (n+1) + " - " + mLogicData[n].getProtocol().toString() + "</u><br/>") ); <ide> for(int i=0; i < mLogicData[n].getStringCount(); ++i){ <del> mRawData[n].append(mLogicData[n].getString(i) + "\t --> " + <del> String.format("%.2f", (mLogicData[n].getPositionAt(i)[0]*1000000)) + "uS\n"); <add> // Con código HTML se puede aplicar propiedades de texto a ciertas partes unicamente <add> // http://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview <add> mRawData[n].append( Html.fromHtml("<b><font color=#ff0000>" + <add> mLogicData[n].getString(i) + "</font></b>" <add> + "\t --> " + String.format("%.2f", (mLogicData[n].getPositionAt(i)[0]*1000000)) <add> + "uS<br/>") ); <ide> } <del> mRawData[n].append("\n"); <ide> } <ide> } <del> <ide> return 0; <ide> } <ide>
Java
mit
e280dd8afb503a0fc1da4e5dba00734959302fa6
0
dvla/vdr-core
package uk.gov.dvla.domain.portal; import org.joda.time.DateTime; import uk.gov.dvla.domain.DomainConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.gov.dvla.domain.Message; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; public class PortalDTO { private static final Logger logger = LoggerFactory.getLogger(PortalDTO.class.getName()); private Driver driver; private List<Message> messages; public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } public Driver getDriver() { return driver; } public void setDriver(Driver driver) { this.driver = driver; } public static class Driver { private String currentDriverNumber; private BirthDetails birthDetails; private Name name; private Licence licence; private Integer gender; private Address address; private DriverStatus status; private List<DriverFlag> flags; private List<TestPass> testPasses; private List<Integer> restrictionKeys; private Date disqualifiedUntilDate; private DriverStatedFlags driverStatedFlags; private List<Disqualification> disqualifications; public String getCurrentDriverNumber() { return currentDriverNumber; } public void setCurrentDriverNumber(String currentDriverNumber) { this.currentDriverNumber = currentDriverNumber; } public BirthDetails getBirthDetails() { return birthDetails; } public void setBirthDetails(BirthDetails birthDetails) { this.birthDetails = birthDetails; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public Licence getLicence() { return this.licence; } public void setLicence(Licence licence) { this.licence = licence; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public DriverStatus getStatus() { return status; } public void setStatus(DriverStatus status) { this.status = status; } public void addDriverFlag(DriverFlag flag) { if (null == flags) { flags = new ArrayList<DriverFlag>(); } flags.add(flag); } public List<DriverFlag> getFlags() { return flags; } public void setFlags(List<DriverFlag> flags) { this.flags = flags; } public void addTestPass(TestPass testPass) { if (null == testPasses) { testPasses = new ArrayList<TestPass>(); } testPasses.add(testPass); } public List<TestPass> getTestPasses() { return testPasses; } public void setTestPasses(List<TestPass> testPasses) { this.testPasses = testPasses; } public TestPass getTestPassForEntitlement(uk.gov.dvla.domain.Entitlement ent) { ArrayList<TestPass> possibleTestPasses = new ArrayList<TestPass>(); if (testPasses == null) { return null; } for (TestPass testPass : testPasses) { if (testPass.getEntitlementType().equals(ent.getCode())) { possibleTestPasses.add(testPass); } } if (possibleTestPasses.size() == 0) { return null; } else { //Ensure the most recent is returned Collections.reverse(possibleTestPasses); return possibleTestPasses.get(0); } } public void addRestrictionKey(Integer key) { if (null == restrictionKeys) { restrictionKeys = new ArrayList<Integer>(); } restrictionKeys.add(key); } public List<Integer> getRestrictionKeys() { return restrictionKeys; } public void setRestrictionKeys(List<Integer> restrictionKeys) { this.restrictionKeys = restrictionKeys; } public Date getDisqualifiedUntilDate() { return disqualifiedUntilDate; } public void setDisqualifiedUntilDate(Date disqualifiedUntilDate) { this.disqualifiedUntilDate = disqualifiedUntilDate; } public DriverStatedFlags getDriverStatedFlags() { return driverStatedFlags; } public void setDriverStatedFlags(DriverStatedFlags driverStatedFlags) { this.driverStatedFlags = driverStatedFlags; } public List<Disqualification> getDisqualifications() { return disqualifications; } public void setDisqualifications(List<Disqualification> disqualifications) { this.disqualifications = disqualifications; } } public static class Name { private String title = null; private List<String> givenName = null; private String familyName = null; public void addGivenName(String gn) { if (null == givenName) { givenName = new ArrayList<String>(); } givenName.add(gn); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getGivenName() { return givenName; } public void setGivenName(List<String> givenName) { this.givenName = givenName; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } } public static class Address { private String buildingName; private String ddtfare; private String postTown; private String postCode; private String type; private List<String> uLine; private String uPostCode; public String getBuildingName() { return buildingName; } public void setBuildingName(String buildingName) { this.buildingName = buildingName; } public String getDdtfare() { return ddtfare; } public void setDdtfare(String ddtfare) { this.ddtfare = ddtfare; } public String getPostTown() { return postTown; } public void setPostTown(String postTown) { this.postTown = postTown; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<String> getuLine() { return uLine; } public void setuLine(List<String> uLine) { this.uLine = uLine; } public String getuPostCode() { return uPostCode; } public void setuPostCode(String uPostCode) { this.uPostCode = uPostCode; } } public static class BirthDetails { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } public static class Licence { private String currentIssueNum; private Date validFrom; private Date validTo; private int directiveStatus; private List<Entitlement> entitlements; private List<Endorsement> endorsements; private Date photoExpiryDate; public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } public Integer getDirectiveStatus() { return directiveStatus; } public void setDirectiveStatus(Integer directiveStatus) { this.directiveStatus = directiveStatus; } public List<Entitlement> getEntitlements() { return entitlements; } public void setEntitlements(List<Entitlement> entitlements) { this.entitlements = entitlements; } public List<Endorsement> getEndorsements() { return endorsements; } public void setEndorsements(List<Endorsement> endorsements) { this.endorsements = endorsements; } public Date getPhotoExpiryDate() { return photoExpiryDate; } public void setPhotoExpiryDate(Date photoExpiryDate) { this.photoExpiryDate = photoExpiryDate; } public String getCurrentIssueNum() { return currentIssueNum; } public void setCurrentIssueNum(String currentIssueNum) { this.currentIssueNum = currentIssueNum; } } public static class Entitlement { private String code; private Date validFrom; private Date validTo; private Boolean provisional; private Boolean priorTo; private List<EntitlementRestriction> restrictions; private Boolean vocational; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } public Boolean getProvisional() { return provisional; } public void setProvisional(Boolean provisional) { this.provisional = provisional; } public Boolean getPriorTo() { return priorTo; } public void setPriorTo(Boolean priorTo) { this.priorTo = priorTo; } public List<EntitlementRestriction> getRestrictions() { return restrictions; } public void setRestrictions(List<EntitlementRestriction> restrictions) { this.restrictions = restrictions; } public Boolean getVocational() { return vocational; } public void setVocational(Boolean vocational) { this.vocational = vocational; } } public static class Endorsement { private Integer id; private Boolean disqual; private String code; private String convictingCourt; private Date offence; private Date expires; private Date removed; private Date conviction; private Date sentencing; private String duration; private Double fine; private Integer noPoints; private OtherSentence otherSentence; public Boolean nonEndorseableOffence; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Boolean getDisqual() { return disqual; } public void setDisqual(Boolean disqual) { this.disqual = disqual; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getConvictingCourt() { return convictingCourt; } public void setConvictingCourt(String convictingCourt) { this.convictingCourt = convictingCourt; } public Date getOffence() { return offence; } public void setOffence(Date offence) { this.offence = offence; } public Date getExpires() { return expires; } public void setExpires(Date expires) { this.expires = expires; } public Date getRemoved() { return removed; } public void setRemoved(Date removed) { this.removed = removed; } public Date getConviction() { return conviction; } public void setConviction(Date conviction) { this.conviction = conviction; } public Date getSentencing() { return sentencing; } public void setSentencing(Date sentencing) { this.sentencing = sentencing; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public Double getFine() { return fine; } public void setFine(Double fine) { this.fine = fine; } public Integer getNoPoints() { return noPoints; } public void setNoPoints(Integer noPoints) { this.noPoints = noPoints; } public OtherSentence getOtherSentence() { return otherSentence; } public void setOtherSentence(uk.gov.dvla.domain.OtherSentence otherSentence) { OtherSentence DTOotherSentence = new OtherSentence(); DTOotherSentence.code = otherSentence.getCode(); DTOotherSentence.duration = otherSentence.getDuration(); this.otherSentence = DTOotherSentence; } public Boolean getNonEndorseableOffence() { return nonEndorseableOffence; } public void setNonEndorseableOffence(Boolean nonEndorseableOffence) { this.nonEndorseableOffence = nonEndorseableOffence; } } public static class OtherSentence { private String code; private String duration; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } } public static class EntitlementRestriction { private String code; private String categoryCode; private Date validTo; public EntitlementRestriction() { } public EntitlementRestriction(String code, String categoryCode, Date validTo) { if (code == null) { logger.debug("code must be specified"); throw new RuntimeException("code must be specified"); } this.validTo = validTo; this.code = code; this.categoryCode = categoryCode; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getCategoryCode() { return categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } } public static class TestPass { private String entitlementType; private String statusType; private Date testPassDate; private Date expiryDate; public String getEntitlementType() { return entitlementType; } public void setEntitlementType(String entitlementType) { this.entitlementType = entitlementType; } public String getStatusType() { return statusType; } public void setStatusType(String statusType) { this.statusType = statusType; } public Date getTestPassDate() { return testPassDate; } public void setTestPassDate(Date testPassDate) { this.testPassDate = testPassDate; } public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } public Date getExpiryDate() { return expiryDate; } } public static class DriverStatedFlags { private Boolean excessEndorsements; public Boolean getExcessEndorsements() { return excessEndorsements; } public void setExcessEndorsements(Boolean excessEndorsements) { this.excessEndorsements = excessEndorsements; } } public static class DriverStatus { private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } } public static class Disqualification { private Date disqFromDate; private Date disqToDate; private Integer endorsementID; private String type; public Date getDisqFromDate() { return disqFromDate; } public void setDisqFromDate(Date disqFromDate) { this.disqFromDate = disqFromDate; } public Date getDisqToDate() { return disqToDate; } public void setDisqToDate(Date disqToDate) { this.disqToDate = disqToDate; } public Integer getEndorsementID() { return endorsementID; } public void setEndorsementID(Integer endorsementID) { this.endorsementID = endorsementID; } public String getType() { return type; } public void setType(String type) { this.type = type; } } public static class DriverFlag { private String flag; private boolean manual; private boolean caseType; public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public boolean isManual() { return manual; } public void setManual(boolean manual) { this.manual = manual; } public boolean isCaseType() { return caseType; } public void setCaseType(boolean caseType) { this.caseType = caseType; } } }
domain/src/main/java/uk/gov/dvla/domain/portal/PortalDTO.java
package uk.gov.dvla.domain.portal; import org.joda.time.DateTime; import uk.gov.dvla.domain.DomainConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.gov.dvla.domain.Message; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; public class PortalDTO { private static final Logger logger = LoggerFactory.getLogger(PortalDTO.class.getName()); private Driver driver; private List<Message> messages; public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } public Driver getDriver() { return driver; } public void setDriver(Driver driver) { this.driver = driver; } public static class Driver { private String currentDriverNumber; private BirthDetails birthDetails; private Name name; private Licence licence; private Integer gender; private Address address; private DriverStatus status; private List<DriverFlag> flags; private List<TestPass> testPasses; private List<Integer> restrictionKeys; private Date disqualifiedUntilDate; private DriverStatedFlags driverStatedFlags; private List<Disqualification> disqualifications; public String getCurrentDriverNumber() { return currentDriverNumber; } public void setCurrentDriverNumber(String currentDriverNumber) { this.currentDriverNumber = currentDriverNumber; } public BirthDetails getBirthDetails() { return birthDetails; } public void setBirthDetails(BirthDetails birthDetails) { this.birthDetails = birthDetails; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public Licence getLicence() { return this.licence; } public void setLicence(Licence licence) { this.licence = licence; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public DriverStatus getStatus() { return status; } public void setStatus(DriverStatus status) { this.status = status; } public void addDriverFlag(DriverFlag flag) { if (null == flags) { flags = new ArrayList<DriverFlag>(); } flags.add(flag); } public List<DriverFlag> getFlags() { return flags; } public void setFlags(List<DriverFlag> flags) { this.flags = flags; } public void addTestPass(TestPass testPass) { if (null == testPasses) { testPasses = new ArrayList<TestPass>(); } testPasses.add(testPass); } public List<TestPass> getTestPasses() { return testPasses; } public void setTestPasses(List<TestPass> testPasses) { this.testPasses = testPasses; } public TestPass getTestPassForEntitlement(uk.gov.dvla.domain.Entitlement ent) { ArrayList<TestPass> possibleTestPasses = new ArrayList<TestPass>(); if (testPasses == null) { return null; } for (TestPass testPass : testPasses) { if (testPass.getEntitlementType().equals(ent.getCode())) { possibleTestPasses.add(testPass); } } if (possibleTestPasses.size() == 0) { return null; } else { //Ensure the most recent is returned Collections.reverse(possibleTestPasses); return possibleTestPasses.get(0); } } public void addRestrictionKey(Integer key) { if (null == restrictionKeys) { restrictionKeys = new ArrayList<Integer>(); } restrictionKeys.add(key); } public List<Integer> getRestrictionKeys() { return restrictionKeys; } public void setRestrictionKeys(List<Integer> restrictionKeys) { this.restrictionKeys = restrictionKeys; } public Date getDisqualifiedUntilDate() { return disqualifiedUntilDate; } public void setDisqualifiedUntilDate(Date disqualifiedUntilDate) { this.disqualifiedUntilDate = disqualifiedUntilDate; } public DriverStatedFlags getDriverStatedFlags() { return driverStatedFlags; } public void setDriverStatedFlags(DriverStatedFlags driverStatedFlags) { this.driverStatedFlags = driverStatedFlags; } public List<Disqualification> getDisqualifications() { return disqualifications; } public void setDisqualifications(List<Disqualification> disqualifications) { this.disqualifications = disqualifications; } } public static class Name { private String title = null; private List<String> givenName = null; private String familyName = null; public void addGivenName(String gn) { if (null == givenName) { givenName = new ArrayList<String>(); } givenName.add(gn); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getGivenName() { return givenName; } public void setGivenName(List<String> givenName) { this.givenName = givenName; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } } public static class Address { private String buildingName; private String ddtfare; private String postTown; private String postCode; private String type; private List<String> uLine; private String uPostCode; public String getBuildingName() { return buildingName; } public void setBuildingName(String buildingName) { this.buildingName = buildingName; } public String getDdtfare() { return ddtfare; } public void setDdtfare(String ddtfare) { this.ddtfare = ddtfare; } public String getPostTown() { return postTown; } public void setPostTown(String postTown) { this.postTown = postTown; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<String> getuLine() { return uLine; } public void setuLine(List<String> uLine) { this.uLine = uLine; } public String getuPostCode() { return uPostCode; } public void setuPostCode(String uPostCode) { this.uPostCode = uPostCode; } } public static class BirthDetails { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } public static class Licence { private String currentIssueNum; private Date validFrom; private Date validTo; private int directiveStatus; private List<Entitlement> entitlements; private List<Endorsement> endorsements; private Date photoExpiryDate; public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } public Integer getDirectiveStatus() { return directiveStatus; } public void setDirectiveStatus(Integer directiveStatus) { this.directiveStatus = directiveStatus; } public List<Entitlement> getEntitlements() { return entitlements; } public void setEntitlements(List<Entitlement> entitlements) { this.entitlements = entitlements; } public List<Endorsement> getEndorsements() { return endorsements; } public void setEndorsements(List<Endorsement> endorsements) { this.endorsements = endorsements; } public Date getPhotoExpiryDate() { return photoExpiryDate; } public void setPhotoExpiryDate(Date photoExpiryDate) { this.photoExpiryDate = photoExpiryDate; } public String getCurrentIssueNum() { return currentIssueNum; } public void setCurrentIssueNum(String currentIssueNum) { this.currentIssueNum = currentIssueNum; } } public static class Entitlement { private String code; private Date validFrom; private Date validTo; private Boolean provisional; private Boolean priorTo; private List<EntitlementRestriction> restrictions; private Boolean vocational; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } public Boolean getProvisional() { return provisional; } public void setProvisional(Boolean provisional) { this.provisional = provisional; } public Boolean getPriorTo() { return priorTo; } public void setPriorTo(Boolean priorTo) { this.priorTo = priorTo; } public List<EntitlementRestriction> getRestrictions() { return restrictions; } public void setRestrictions(List<EntitlementRestriction> restrictions) { this.restrictions = restrictions; } public Boolean getVocational() { return vocational; } public void setVocational(Boolean vocational) { this.vocational = vocational; } } public static class Endorsement { private Integer id; private Boolean disqual; private String code; private String convictingCourt; private Date offence; private Date expires; private Date removed; private Date conviction; private Date sentencing; private String duration; private Double fine; private Integer noPoints; private OtherSentence otherSentence; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Boolean getDisqual() { return disqual; } public void setDisqual(Boolean disqual) { this.disqual = disqual; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getConvictingCourt() { return convictingCourt; } public void setConvictingCourt(String convictingCourt) { this.convictingCourt = convictingCourt; } public Date getOffence() { return offence; } public void setOffence(Date offence) { this.offence = offence; } public Date getExpires() { return expires; } public void setExpires(Date expires) { this.expires = expires; } public Date getRemoved() { return removed; } public void setRemoved(Date removed) { this.removed = removed; } public Date getConviction() { return conviction; } public void setConviction(Date conviction) { this.conviction = conviction; } public Date getSentencing() { return sentencing; } public void setSentencing(Date sentencing) { this.sentencing = sentencing; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public Double getFine() { return fine; } public void setFine(Double fine) { this.fine = fine; } public Integer getNoPoints() { return noPoints; } public void setNoPoints(Integer noPoints) { this.noPoints = noPoints; } public OtherSentence getOtherSentence() { return otherSentence; } public void setOtherSentence(uk.gov.dvla.domain.OtherSentence otherSentence) { OtherSentence DTOotherSentence = new OtherSentence(); DTOotherSentence.code = otherSentence.getCode(); DTOotherSentence.duration = otherSentence.getDuration(); this.otherSentence = DTOotherSentence; } } public static class OtherSentence { private String code; private String duration; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } } public static class EntitlementRestriction { private String code; private String categoryCode; private Date validTo; public EntitlementRestriction() { } public EntitlementRestriction(String code, String categoryCode, Date validTo) { if (code == null) { logger.debug("code must be specified"); throw new RuntimeException("code must be specified"); } this.validTo = validTo; this.code = code; this.categoryCode = categoryCode; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getCategoryCode() { return categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } } public static class TestPass { private String entitlementType; private String statusType; private Date testPassDate; private Date expiryDate; public String getEntitlementType() { return entitlementType; } public void setEntitlementType(String entitlementType) { this.entitlementType = entitlementType; } public String getStatusType() { return statusType; } public void setStatusType(String statusType) { this.statusType = statusType; } public Date getTestPassDate() { return testPassDate; } public void setTestPassDate(Date testPassDate) { this.testPassDate = testPassDate; } public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } public Date getExpiryDate() { return expiryDate; } } public static class DriverStatedFlags { private Boolean excessEndorsements; public Boolean getExcessEndorsements() { return excessEndorsements; } public void setExcessEndorsements(Boolean excessEndorsements) { this.excessEndorsements = excessEndorsements; } } public static class DriverStatus { private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } } public static class Disqualification { private Date disqFromDate; private Date disqToDate; private Integer endorsementID; private String type; public Date getDisqFromDate() { return disqFromDate; } public void setDisqFromDate(Date disqFromDate) { this.disqFromDate = disqFromDate; } public Date getDisqToDate() { return disqToDate; } public void setDisqToDate(Date disqToDate) { this.disqToDate = disqToDate; } public Integer getEndorsementID() { return endorsementID; } public void setEndorsementID(Integer endorsementID) { this.endorsementID = endorsementID; } public String getType() { return type; } public void setType(String type) { this.type = type; } } public static class DriverFlag { private String flag; private boolean manual; private boolean caseType; public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public boolean isManual() { return manual; } public void setManual(boolean manual) { this.manual = manual; } public boolean isCaseType() { return caseType; } public void setCaseType(boolean caseType) { this.caseType = caseType; } } }
Set new NonEndorseableOffence flag on Portal DTO's Endorsement record
domain/src/main/java/uk/gov/dvla/domain/portal/PortalDTO.java
Set new NonEndorseableOffence flag on Portal DTO's Endorsement record
<ide><path>omain/src/main/java/uk/gov/dvla/domain/portal/PortalDTO.java <ide> private Double fine; <ide> private Integer noPoints; <ide> private OtherSentence otherSentence; <add> public Boolean nonEndorseableOffence; <ide> <ide> public Integer getId() { <ide> return id; <ide> this.otherSentence = DTOotherSentence; <ide> <ide> } <add> <add> public Boolean getNonEndorseableOffence() { <add> return nonEndorseableOffence; <add> } <add> <add> public void setNonEndorseableOffence(Boolean nonEndorseableOffence) { <add> this.nonEndorseableOffence = nonEndorseableOffence; <add> } <ide> } <ide> <ide> public static class OtherSentence {
JavaScript
mit
ebfe472bf9df42efa08c196a2fd2ada4a03bbad2
0
hazio/meteor-counter-cache
Package.describe({ name: 'hazio:counter-cache', summary: "Cache the counts of an associated collection", version: "0.0.3", git: "https://github.com/hazio/meteor-counter-cache.git" }); Package.onUse(function(api) { api.use([ '[email protected]', '[email protected]', '[email protected]', '[email protected]' ]); api.add_files('counter-cache.js', ['client', 'server']); api.export('CounterCache'); }); Package.onTest(function(api) { api.use(['tinytest', 'dburles:counter-cache']); api.add_files('counter-cache_tests.js', 'server'); });
package.js
Package.describe({ name: 'hazio:counter-cache', summary: "Cache the counts of an associated collection", version: "0.0.3", git: "https://github.com/hazio/meteor-counter-cache.git" }); Package.onUse(function(api) { api.use([ 'check', '[email protected]', '[email protected]', 'minimongo' ]); api.add_files('counter-cache.js', ['client', 'server']); api.export('CounterCache'); }); Package.onTest(function(api) { api.use(['tinytest', 'dburles:counter-cache']); api.add_files('counter-cache_tests.js', 'server'); });
package versions
package.js
package versions
<ide><path>ackage.js <ide> <ide> Package.onUse(function(api) { <ide> api.use([ <del> 'check', <add> '[email protected]', <ide> '[email protected]', <ide> '[email protected]', <del> 'minimongo' <add> '[email protected]' <ide> ]); <ide> api.add_files('counter-cache.js', ['client', 'server']); <ide> api.export('CounterCache');
Java
apache-2.0
139d95e6b0aebd7b18e18e0c91271569973fbc06
0
jruesga/rview,jruesga/rview,jruesga/rview
/* * Copyright (C) 2016 Jorge Ruesga * * 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.ruesga.rview.widget; import android.content.Context; import android.databinding.DataBindingUtil; import android.os.AsyncTask; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.content.ContextCompat; import android.support.v4.util.Pair; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.LayoutManager; import android.text.Spannable; import android.text.Spanned; import android.text.TextPaint; import android.text.style.BackgroundColorSpan; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import com.google.gson.reflect.TypeToken; import com.ruesga.rview.R; import com.ruesga.rview.annotations.ProguardIgnored; import com.ruesga.rview.databinding.DiffCommentItemBinding; import com.ruesga.rview.databinding.DiffSkipItemBinding; import com.ruesga.rview.databinding.DiffSourceItemBinding; import com.ruesga.rview.gerrit.model.CommentInfo; import com.ruesga.rview.gerrit.model.DiffContentInfo; import com.ruesga.rview.misc.SerializationManager; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; public class DiffView extends FrameLayout { private static final int SKIPPED_LINES = 10; public static final int SIDE_BY_SIDE_MODE = 0; public static final int UNIFIED_MODE = 1; private static final int SOURCE_VIEW_TYPE = 0; private static final int SKIP_VIEW_TYPE = 1; private static final int COMMENT_VIEW_TYPE = 2; @ProguardIgnored @SuppressWarnings({"UnusedParameters", "unused"}) public static class EventHandlers { private final DiffView mView; public EventHandlers(DiffView view) { mView = view; } public void onNewDraftPressed(View v) { if (mView.mCanEdit && mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onNewDraft( v, Boolean.parseBoolean(s[0]), Integer.valueOf(s[1])); } } public void onReplyPressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onReply(v, s[0], s[1], Integer.valueOf(s[2])); } } public void onDonePressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onDone(v, s[0], s[1], Integer.valueOf(s[2])); } } public void onEditPressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); String msg = (String) v.getTag(R.id.tag_key); mView.mOnCommentListener.onEditDraft( v, s[0], s[1], s[2], Integer.valueOf(s[3]), msg); } } public void onDeletePressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onDeleteDraft(v, s[0], s[1]); } } } public interface OnCommentListener { void onNewDraft(View v, boolean left, int line); void onReply(View v, String revisionId, String commentId, int line); void onDone(View v, String revisionId, String commentId, int line); void onEditDraft(View v, String revisionId, String draftId, String inReplyTo, int line, String msg); void onDeleteDraft(View v, String revisionId, String draftId); } private static class DiffSourceViewHolder extends RecyclerView.ViewHolder { private DiffSourceItemBinding mBinding; DiffSourceViewHolder(DiffSourceItemBinding binding) { super(binding.getRoot()); mBinding = binding; mBinding.executePendingBindings(); } } private static class DiffSkipViewHolder extends RecyclerView.ViewHolder { private DiffSkipItemBinding mBinding; DiffSkipViewHolder(DiffSkipItemBinding binding) { super(binding.getRoot()); mBinding = binding; mBinding.executePendingBindings(); } } private static class DiffCommentViewHolder extends RecyclerView.ViewHolder { private DiffCommentItemBinding mBinding; DiffCommentViewHolder(DiffCommentItemBinding binding) { super(binding.getRoot()); mBinding = binding; mBinding.executePendingBindings(); } } public static abstract class AbstractModel { } @ProguardIgnored public static class DiffInfoModel extends AbstractModel { public String lineNumberA; public String lineNumberB; public int colorA; public int colorB; CharSequence lineA; CharSequence lineB; } @ProguardIgnored public static class CommentModel extends AbstractModel { public CommentInfo commentA; public CommentInfo commentB; public boolean isDraft; } @ProguardIgnored public static class SkipLineModel extends AbstractModel { public String msg; } @ProguardIgnored public static class DiffViewMeasurement { public int width = -1; public int lineAWidth = -1; public int lineBWidth = -1; public int lineNumAWidth = -1; public int lineNumBWidth = -1; private void clear() { width = -1; lineAWidth = -1; lineBWidth = -1; lineNumAWidth = -1; lineNumBWidth = -1; } } private class DiffAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private LayoutInflater mLayoutInflater; private final List<AbstractModel> mModel = new ArrayList<>(); private final DiffViewMeasurement mDiffViewMeasurement = new DiffViewMeasurement(); private final int mMode; DiffAdapter(int mode) { mLayoutInflater = LayoutInflater.from(getContext()); mMode = mode; } void update(List<AbstractModel> diffs) { mModel.clear(); mModel.addAll(diffs); mDiffViewMeasurement.clear(); computeViewChildMeasuresIfNeeded(); notifyDataSetChanged(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == SOURCE_VIEW_TYPE) { return new DiffSourceViewHolder(DataBindingUtil.inflate( mLayoutInflater, R.layout.diff_source_item, parent, false)); } else if (viewType == SKIP_VIEW_TYPE) { return new DiffSkipViewHolder(DataBindingUtil.inflate( mLayoutInflater, R.layout.diff_skip_item, parent, false)); } else if (viewType == COMMENT_VIEW_TYPE) { return new DiffCommentViewHolder(DataBindingUtil.inflate( mLayoutInflater, R.layout.diff_comment_item, parent, false)); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder vh, int position) { AbstractModel model = mModel.get(position); if (vh instanceof DiffSourceViewHolder) { DiffSourceViewHolder holder = ((DiffSourceViewHolder) vh); DiffInfoModel diff = (DiffInfoModel) model; if (mMode == UNIFIED_MODE) { CharSequence text = diff.lineA != null ? diff.lineA : diff.lineB; holder.mBinding.diffA.setText(text, TextView.BufferType.NORMAL); } else { holder.mBinding.diffA.setText(diff.lineA, TextView.BufferType.NORMAL); holder.mBinding.diffB.setText(diff.lineB, TextView.BufferType.NORMAL); } holder.mBinding.setWrap(isWrapMode()); holder.mBinding.setMode(mMode); holder.mBinding.setModel(diff); holder.mBinding.setMeasurement(mDiffViewMeasurement); if (mCanEdit) { holder.mBinding.setHandlers(mEventHandlers); } } else if (vh instanceof DiffSkipViewHolder) { DiffSkipViewHolder holder = ((DiffSkipViewHolder) vh); SkipLineModel skip = (SkipLineModel) model; holder.mBinding.setWrap(isWrapMode()); holder.mBinding.setMode(mMode); holder.mBinding.setModel(skip); holder.mBinding.setMeasurement(mDiffViewMeasurement); } else if (vh instanceof DiffCommentViewHolder) { DiffCommentViewHolder holder = ((DiffCommentViewHolder) vh); CommentModel comment = (CommentModel) model; holder.mBinding.setCanEdit(mCanEdit); holder.mBinding.setWrap(isWrapMode()); holder.mBinding.setMode(mMode); holder.mBinding.setModel(comment); holder.mBinding.setMeasurement(mDiffViewMeasurement); holder.mBinding.setHandlers(mEventHandlers); if (comment.commentA != null) { holder.mBinding.actionsA.edit.setTag(R.id.tag_key, comment.commentA.message); } if (comment.commentB != null) { holder.mBinding.actionsB.edit.setTag(R.id.tag_key, comment.commentB.message); } } } @Override public int getItemViewType(int position) { AbstractModel model = mModel.get(position); if (model instanceof DiffInfoModel) { return SOURCE_VIEW_TYPE; } if (model instanceof SkipLineModel) { return SKIP_VIEW_TYPE; } return COMMENT_VIEW_TYPE; } @Override public int getItemCount() { return mModel.size(); } private void computeViewChildMeasuresIfNeeded() { boolean wrap = isWrapMode(); if (!mModel.isEmpty()) { int dp = (int) getResources().getDisplayMetrics().density; TextPaint paint = new TextPaint(); paint.setTextSize(12 * dp); int padding = 3 * dp; for (AbstractModel model : mModel) { if (model instanceof DiffInfoModel) { DiffInfoModel diff = (DiffInfoModel) model; if (wrap) { mDiffViewMeasurement.lineAWidth = MATCH_PARENT; mDiffViewMeasurement.lineBWidth = MATCH_PARENT; } else { if (mMode == UNIFIED_MODE) { // All lines are displayed in A CharSequence line = diff.lineA != null ? diff.lineA : diff.lineB; int width = (int) paint.measureText(String.valueOf(line)) + padding; mDiffViewMeasurement.lineAWidth = Math.max( mDiffViewMeasurement.lineAWidth, width); } else { // All lines are displayed in A if (diff.lineA != null) { String lineA = String.valueOf(diff.lineA); int width = (int) paint.measureText(lineA) + padding; mDiffViewMeasurement.lineAWidth = Math.max( mDiffViewMeasurement.lineAWidth, width); } if (diff.lineB != null) { String lineB = String.valueOf(diff.lineB); int width = (int) paint.measureText(lineB) + padding; mDiffViewMeasurement.lineBWidth = Math.max( mDiffViewMeasurement.lineBWidth, width); } } } if (diff.lineNumberA != null) { mDiffViewMeasurement.lineNumAWidth = Math.max( mDiffViewMeasurement.lineNumAWidth, (int) paint.measureText(String.valueOf(diff.lineNumberA))); } if (diff.lineNumberB != null) { mDiffViewMeasurement.lineNumBWidth = Math.max( mDiffViewMeasurement.lineNumBWidth, (int) paint.measureText(String.valueOf(diff.lineNumberB))); } } } // User same size for A y B number and apply a minimum mDiffViewMeasurement.lineNumAWidth = mDiffViewMeasurement.lineNumBWidth = Math.max(mDiffViewMeasurement.lineNumAWidth, mDiffViewMeasurement.lineNumBWidth); mDiffViewMeasurement.lineNumAWidth = mDiffViewMeasurement.lineNumBWidth = Math.max(mDiffViewMeasurement.lineNumAWidth, 20 * dp); // Adjust padding mDiffViewMeasurement.lineNumAWidth += (padding * 2); mDiffViewMeasurement.lineNumBWidth += (padding * 2); int diffIndicatorWidth = 16 * dp; mDiffViewMeasurement.width = mDiffViewMeasurement.lineNumAWidth + mDiffViewMeasurement.lineNumBWidth + mDiffViewMeasurement.lineAWidth + mDiffViewMeasurement.lineBWidth + diffIndicatorWidth + (dp * 2); if (mDiffViewMeasurement.width < getWidth()) { mDiffViewMeasurement.width = getWidth(); if (mMode == UNIFIED_MODE) { mDiffViewMeasurement.lineAWidth = getWidth() - mDiffViewMeasurement.lineNumAWidth - mDiffViewMeasurement.lineNumBWidth - diffIndicatorWidth - (dp * 2); } } } } } private class AsyncDiffProcessor extends AsyncTask<Void, Void, List<AbstractModel>> { private final int mMode; private final DiffContentInfo[] mDiffs; private final Pair<List<CommentInfo>, List<CommentInfo>> mComments; AsyncDiffProcessor(int mode, DiffContentInfo[] diffs, Pair<List<CommentInfo>, List<CommentInfo>> comments, Pair<List<CommentInfo>, List<CommentInfo>> drafts) { mMode = mode; mDiffs = diffs; mComments = comments; mDrafts = drafts; } @Override protected List<AbstractModel> doInBackground(Void... params) { return processDrafts(processComments(processDiffs())); } @Override protected void onPostExecute(List<AbstractModel> model) { if (!mLayoutManager.equals(mTmpLayoutManager)) { mDiffAdapter = new DiffAdapter(mDiffMode); if (mTmpLayoutManager != null) { mLayoutManager = mTmpLayoutManager; } mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mDiffAdapter); } mDiffAdapter.update(model); } private List<AbstractModel> processDiffs() { if (mMode == SIDE_BY_SIDE_MODE) { return processSideBySideDiffs(); } return processUnifiedDiffs(); } private List<AbstractModel> processSideBySideDiffs() { if (mDiffs == null) { return new ArrayList<>(); } int lineNumberA = 0; int lineNumberB = 0; final Spannable.Factory spannableFactory = Spannable.Factory.getInstance(); final int noColor = ContextCompat.getColor(getContext(), android.R.color.transparent); final int addedBgColor = ContextCompat.getColor( getContext(), R.color.diffAddedBackgroundColor); final int addedFgColor = ContextCompat.getColor( getContext(), R.color.diffAddedForegroundColor); final int deletedBgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedBackgroundColor); final int deletedFgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedForegroundColor); List<AbstractModel> model = new ArrayList<>(); int j = 0; for (DiffContentInfo diff : mDiffs) { if (diff.ab != null) { // Unchanged lines int count = diff.ab.length; int skipStartAt = -1, skippedLines = -1; boolean breakAfterSkip = false; if (j == 0 && diff.ab.length > SKIPPED_LINES) { skipStartAt = 0; skippedLines = count - SKIPPED_LINES - skipStartAt; } else if (j == (mDiffs.length - 1) && diff.ab.length > SKIPPED_LINES) { skipStartAt = SKIPPED_LINES; skippedLines = count - skipStartAt; breakAfterSkip = true; } else if (diff.ab.length > (SKIPPED_LINES * 2)) { skipStartAt = SKIPPED_LINES; skippedLines = count - SKIPPED_LINES - skipStartAt; } for (int i = 0; i < count; i++) { if (skipStartAt != -1 && skipStartAt == i) { lineNumberA += skippedLines; lineNumberB += skippedLines; i += skippedLines; SkipLineModel skip = new SkipLineModel(); skip.msg = getResources().getQuantityString( R.plurals.skipped_lines, skippedLines, skippedLines); model.add(skip); if (breakAfterSkip) { break; } } String line = diff.ab[i]; DiffInfoModel m = new DiffInfoModel(); m.lineNumberA = String.valueOf(++lineNumberA); m.lineNumberB = String.valueOf(++lineNumberB); m.lineA = line; m.lineB = line; m.colorA = noColor; m.colorB = noColor; model.add(m); } } else { int posA = 0; int posB = 0; int count = Math.max( diff.a == null ? 0 : diff.a.length, diff.b == null ? 0 : diff.b.length); for (int i = 0; i < count; i++) { DiffInfoModel m = new DiffInfoModel(); m.colorA = noColor; m.colorB = noColor; if (diff.a != null && i < diff.a.length) { String line = diff.a[i]; m.lineNumberA = String.valueOf(++lineNumberA); if (diff.editA != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editA) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = posA + line.length(); if ((s1 >= posA && s1 <= l) || (s2 >= posA && s2 <= l) || (s1 <= posA && s2 >= l)) { span.setSpan(new BackgroundColorSpan(deletedFgColor), Math.max(posA, s1) - posA, Math.min(l, s2) - posA, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineA = span; } else { m.lineA = line; } m.colorA = deletedBgColor; posA += line.length() + 1; } if (diff.b != null && i < diff.b.length) { String line = diff.b[i]; m.lineNumberB = String.valueOf(++lineNumberB); if (diff.editB != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editB) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = posB + line.length(); if ((s1 >= posB && s1 <= l) || (s2 >= posB && s2 <= l) || (s1 <= posB && s2 >= l)) { span.setSpan(new BackgroundColorSpan(addedFgColor), Math.max(posB, s1) - posB, Math.min(l, s2) - posB, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineB = span; } else { m.lineB = line; } m.colorB = addedBgColor; posB += line.length() + 1; } model.add(m); } } j++; } return model; } private List<AbstractModel> processUnifiedDiffs() { if (mDiffs == null) { return new ArrayList<>(); } int lineNumberA = 0; int lineNumberB = 0; final Spannable.Factory spannableFactory = Spannable.Factory.getInstance(); final int noColor = ContextCompat.getColor(getContext(), android.R.color.transparent); final int addedBgColor = ContextCompat.getColor( getContext(), R.color.diffAddedBackgroundColor); final int addedFgColor = ContextCompat.getColor( getContext(), R.color.diffAddedForegroundColor); final int deletedBgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedBackgroundColor); final int deletedFgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedForegroundColor); List<AbstractModel> model = new ArrayList<>(); int j = 0; for (DiffContentInfo diff : mDiffs) { if (diff.ab != null) { // Unchanged lines int count = diff.ab.length; int skipStartAt = -1, skippedLines = -1; boolean breakAfterSkip = false; if (j == 0 && diff.ab.length > SKIPPED_LINES) { skipStartAt = 0; skippedLines = count - SKIPPED_LINES - skipStartAt; } else if (j == (mDiffs.length - 1) && diff.ab.length > SKIPPED_LINES) { skipStartAt = SKIPPED_LINES; skippedLines = count - skipStartAt; breakAfterSkip = true; } else if (diff.ab.length > (SKIPPED_LINES * 2)) { skipStartAt = SKIPPED_LINES; skippedLines = count - SKIPPED_LINES - skipStartAt; } for (int i = 0; i < count; i++) { if (skipStartAt != -1 && skipStartAt == i) { lineNumberA += skippedLines; lineNumberB += skippedLines; i += skippedLines; SkipLineModel skip = new SkipLineModel(); skip.msg = getResources().getQuantityString( R.plurals.skipped_lines, skippedLines, skippedLines); model.add(skip); if (breakAfterSkip) { break; } } String line = diff.ab[i]; DiffInfoModel m = new DiffInfoModel(); m.lineNumberA = String.valueOf(++lineNumberA); m.lineNumberB = String.valueOf(++lineNumberB); m.lineA = line; m.lineB = line; m.colorA = noColor; m.colorB = noColor; model.add(m); } } else { if (diff.a != null) { int pos = 0; for (String line : diff.a) { DiffInfoModel m = new DiffInfoModel(); m.lineNumberA = String.valueOf(++lineNumberA); if (diff.editA != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editA) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = pos + line.length(); if ((s1 >= pos && s1 <= l) || (s2 >= pos && s2 <= l) || (s1 <= pos && s2 >= l)) { span.setSpan(new BackgroundColorSpan(deletedFgColor), Math.max(pos, s1) - pos, Math.min(l, s2) - pos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineA = span; } else { m.lineA = line; } m.colorA = deletedBgColor; m.colorB = noColor; model.add(m); pos += line.length() + 1; } } if (diff.b != null) { int pos = 0; for (String line : diff.b) { DiffInfoModel m = new DiffInfoModel(); m.lineNumberB = String.valueOf(++lineNumberB); if (diff.editB != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editB) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = pos + line.length(); if ((s1 >= pos && s1 <= l) || (s2 >= pos && s2 <= l) || (s1 <= pos && s2 >= l)) { span.setSpan(new BackgroundColorSpan(addedFgColor), Math.max(pos, s1) - pos, Math.min(l, s2) - pos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineB = span; } else { m.lineB = line; } m.colorA = addedBgColor; m.colorB = noColor; model.add(m); pos += line.length() + 1; } } } j++; } return model; } private List<AbstractModel> processComments(List<AbstractModel> model) { if (mComments != null) { // Comments on A if (mComments.second != null) { addCommentsToModel(model, mComments.first, true, false); } // Comments on B if (mComments.second != null) { addCommentsToModel(model, mComments.second, false, false); } } return model; } private List<AbstractModel> processDrafts(List<AbstractModel> model) { if (mDrafts != null) { // Comments on A if (mDrafts.second != null) { addCommentsToModel(model, mDrafts.first, true, true); } // Comments on B if (mDrafts.second != null) { addCommentsToModel(model, mDrafts.second, false, true); } } return model; } private void addCommentsToModel(List<AbstractModel> model, List<CommentInfo> comments, boolean isA, boolean isDraft) { if (comments == null) { return; } int count = comments.size(); for (int i = 0; i < count; i++) { CommentInfo comment = comments.get(i); int pos = findLineInModel(model, isA, comment.line); if (pos != -1) { if (mMode == UNIFIED_MODE) { CommentModel commentModel = new CommentModel(); commentModel.isDraft = isDraft; commentModel.commentA = comment; int nextPos = findNextPositionWithoutComment(model, pos); if (nextPos != -1) { model.add(nextPos, commentModel); } else { model.add(pos + 1, commentModel); } } else { int reusablePos = findReusableCommentView(model, pos, isA); if (reusablePos != -1) { CommentModel commentModel = (CommentModel) model.get(reusablePos); commentModel.isDraft = isDraft; if (isA) { commentModel.commentA = comment; } else { commentModel.commentB = comment; } } else { CommentModel commentModel = new CommentModel(); commentModel.isDraft = isDraft; if (isA) { commentModel.commentA = comment; } else { commentModel.commentB = comment; } int nextPos = findNextPositionWithoutComment(model, pos); if (nextPos != -1) { model.add(nextPos, commentModel); } else { model.add(pos + 1, commentModel); } } } } } } private int findLineInModel(List<AbstractModel> model, boolean isA, int line) { int count = model.size(); for (int i = 0; i < count; i++) { AbstractModel m = model.get(i); if (m instanceof DiffInfoModel) { DiffInfoModel diff = (DiffInfoModel) m; if (isA && diff.lineNumberA != null && Integer.valueOf(diff.lineNumberA) == line) { return i; } else if (!isA && diff.lineNumberB != null && Integer.valueOf(diff.lineNumberB) == line) { return i; } } } return -1; } private int findReusableCommentView(List<AbstractModel> model, int pos, boolean isA) { int count = model.size(); for (int i = pos + 1; i < count; i++) { AbstractModel m = model.get(i); if (!(m instanceof CommentModel)) { break; } CommentModel comment = (CommentModel) m; if ((isA && comment.commentA == null && comment.commentB != null) || (!isA && comment.commentB == null && comment.commentA != null)) { return i; } } return -1; } private int findNextPositionWithoutComment(List<AbstractModel> model, int pos) { int count = model.size(); for (int i = pos + 1; i < count; i++) { AbstractModel m = model.get(i); if (!(m instanceof CommentModel)) { return i; } } return -1; } } private final RecyclerView mRecyclerView; private DiffAdapter mDiffAdapter; private LayoutManager mLayoutManager; private LayoutManager mTmpLayoutManager; private boolean mHighlightTabs; private boolean mCanEdit; private int mDiffMode = UNIFIED_MODE; private DiffContentInfo[] mAllDiffs; private Pair<List<CommentInfo>, List<CommentInfo>> mComments; private Pair<List<CommentInfo>, List<CommentInfo>> mDrafts; private OnCommentListener mOnCommentListener; private EventHandlers mEventHandlers; private AsyncDiffProcessor mTask; public DiffView(Context context) { this(context, null); } public DiffView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DiffView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mEventHandlers = new EventHandlers(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( MATCH_PARENT, MATCH_PARENT); mRecyclerView = new RecyclerView(context); mLayoutManager = new LinearLayoutManager(context); mRecyclerView.setLayoutManager(mLayoutManager); mDiffAdapter = new DiffAdapter(mDiffMode); mRecyclerView.setAdapter(mDiffAdapter); mRecyclerView.setVerticalScrollBarEnabled(true); addView(mRecyclerView, params); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // Stops running things now if (mTask != null) { mTask.cancel(true); } } @Override protected Parcelable onSaveInstanceState() { SavedState savedState = new SavedState(super.onSaveInstanceState()); savedState.mHighlightTabs = mHighlightTabs; savedState.mCanEdit = mCanEdit; savedState.mDiffMode = mDiffMode; savedState.mAllDiffs = SerializationManager.getInstance().toJson(mAllDiffs); savedState.mComments = SerializationManager.getInstance().toJson(mComments); savedState.mDrafts = SerializationManager.getInstance().toJson(mDrafts); return savedState; } @Override protected void onRestoreInstanceState(Parcelable state) { //begin boilerplate code so parent classes can restore state if(!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mHighlightTabs = savedState.mHighlightTabs; mCanEdit = savedState.mCanEdit; mDiffMode = savedState.mDiffMode; Type type = new TypeToken<DiffContentInfo[]>(){}.getType(); mAllDiffs = SerializationManager.getInstance().fromJson(savedState.mAllDiffs, type); type = new TypeToken<Pair<List<CommentInfo>, List<CommentInfo>>>(){}.getType(); mComments = SerializationManager.getInstance().fromJson(savedState.mComments, type); mDrafts = SerializationManager.getInstance().fromJson(savedState.mDrafts, type); } public DiffView from(DiffContentInfo[] allDiffs) { mAllDiffs = allDiffs; return this; } public DiffView withComments(Pair<List<CommentInfo>, List<CommentInfo>> comments) { mComments = comments; return this; } public DiffView withDrafts(Pair<List<CommentInfo>, List<CommentInfo>> drafts) { mDrafts = drafts; return this; } public DiffView canEdit(boolean canEdit) { mCanEdit = canEdit; return this; } public DiffView highlightTabs(boolean highlightTabs) { mHighlightTabs = highlightTabs; return this; } public DiffView wrap(boolean wrap) { if (isWrapMode() != wrap) { mTmpLayoutManager = wrap ? new LinearLayoutManager(getContext()) : new UnwrappedLinearLayoutManager(getContext()); } else { mTmpLayoutManager = mLayoutManager; } return this; } public DiffView mode(int mode) { mDiffMode = mode; return this; } public DiffView listenOn(OnCommentListener cb) { mOnCommentListener = cb; return this; } public void update() { if (mTask != null) { mTask.cancel(true); } mTask = new AsyncDiffProcessor(mDiffMode, mAllDiffs, mComments, mDrafts); mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private boolean isWrapMode() { return mLayoutManager == null || !(mLayoutManager instanceof UnwrappedLinearLayoutManager); } static class SavedState extends BaseSavedState { boolean mHighlightTabs; boolean mCanEdit; int mDiffMode; String mAllDiffs; String mComments; String mDrafts; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); mHighlightTabs = in.readInt() == 1; mCanEdit = in.readInt() == 1; mDiffMode = in.readInt(); mAllDiffs = in.readString(); mComments = in.readString(); mDrafts = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mHighlightTabs ? 1 : 0); out.writeInt(mCanEdit ? 1 : 0); out.writeInt(mDiffMode); out.writeString(mAllDiffs); out.writeString(mComments); out.writeString(mDrafts); } //required field that makes Parcelables from a Parcel public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
app/src/main/java/com/ruesga/rview/widget/DiffView.java
/* * Copyright (C) 2016 Jorge Ruesga * * 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.ruesga.rview.widget; import android.content.Context; import android.databinding.DataBindingUtil; import android.os.AsyncTask; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.content.ContextCompat; import android.support.v4.util.Pair; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.LayoutManager; import android.text.Spannable; import android.text.Spanned; import android.text.TextPaint; import android.text.style.BackgroundColorSpan; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import com.google.gson.reflect.TypeToken; import com.ruesga.rview.R; import com.ruesga.rview.annotations.ProguardIgnored; import com.ruesga.rview.databinding.DiffCommentItemBinding; import com.ruesga.rview.databinding.DiffSkipItemBinding; import com.ruesga.rview.databinding.DiffSourceItemBinding; import com.ruesga.rview.gerrit.model.CommentInfo; import com.ruesga.rview.gerrit.model.DiffContentInfo; import com.ruesga.rview.misc.SerializationManager; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; public class DiffView extends FrameLayout { private static final int SKIPPED_LINES = 10; public static final int SIDE_BY_SIDE_MODE = 0; public static final int UNIFIED_MODE = 1; private static final int SOURCE_VIEW_TYPE = 0; private static final int SKIP_VIEW_TYPE = 1; private static final int COMMENT_VIEW_TYPE = 2; @ProguardIgnored @SuppressWarnings({"UnusedParameters", "unused"}) public static class EventHandlers { private final DiffView mView; public EventHandlers(DiffView view) { mView = view; } public void onNewDraftPressed(View v) { if (mView.mCanEdit && mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onNewDraft( v, Boolean.parseBoolean(s[0]), Integer.valueOf(s[1])); } } public void onReplyPressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onReply(v, s[0], s[1], Integer.valueOf(s[2])); } } public void onDonePressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onDone(v, s[0], s[1], Integer.valueOf(s[2])); } } public void onEditPressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); String msg = (String) v.getTag(R.id.tag_key); mView.mOnCommentListener.onEditDraft( v, s[0], s[1], s[2], Integer.valueOf(s[3]), msg); } } public void onDeletePressed(View v) { if (mView.mOnCommentListener != null) { String[] s = ((String) v.getTag()).split("/"); mView.mOnCommentListener.onDeleteDraft(v, s[0], s[1]); } } } public interface OnCommentListener { void onNewDraft(View v, boolean left, int line); void onReply(View v, String revisionId, String commentId, int line); void onDone(View v, String revisionId, String commentId, int line); void onEditDraft(View v, String revisionId, String draftId, String inReplyTo, int line, String msg); void onDeleteDraft(View v, String revisionId, String draftId); } private static class DiffSourceViewHolder extends RecyclerView.ViewHolder { private DiffSourceItemBinding mBinding; DiffSourceViewHolder(DiffSourceItemBinding binding) { super(binding.getRoot()); mBinding = binding; mBinding.executePendingBindings(); } } private static class DiffSkipViewHolder extends RecyclerView.ViewHolder { private DiffSkipItemBinding mBinding; DiffSkipViewHolder(DiffSkipItemBinding binding) { super(binding.getRoot()); mBinding = binding; mBinding.executePendingBindings(); } } private static class DiffCommentViewHolder extends RecyclerView.ViewHolder { private DiffCommentItemBinding mBinding; DiffCommentViewHolder(DiffCommentItemBinding binding) { super(binding.getRoot()); mBinding = binding; mBinding.executePendingBindings(); } } public static abstract class AbstractModel { } @ProguardIgnored public static class DiffInfoModel extends AbstractModel { public String lineNumberA; public String lineNumberB; public int colorA; public int colorB; CharSequence lineA; CharSequence lineB; } @ProguardIgnored public static class CommentModel extends AbstractModel { public CommentInfo commentA; public CommentInfo commentB; public boolean isDraft; } @ProguardIgnored public static class SkipLineModel extends AbstractModel { public String msg; } @ProguardIgnored public static class DiffViewMeasurement { public int width = -1; public int lineAWidth = -1; public int lineBWidth = -1; public int lineNumAWidth = -1; public int lineNumBWidth = -1; private void clear() { width = -1; lineAWidth = -1; lineBWidth = -1; lineNumAWidth = -1; lineNumBWidth = -1; } } private class DiffAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private LayoutInflater mLayoutInflater; private final List<AbstractModel> mModel = new ArrayList<>(); private final DiffViewMeasurement mDiffViewMeasurement = new DiffViewMeasurement(); private final int mMode; DiffAdapter(int mode) { mLayoutInflater = LayoutInflater.from(getContext()); mMode = mode; } void update(List<AbstractModel> diffs) { mModel.clear(); mModel.addAll(diffs); mDiffViewMeasurement.clear(); computeViewChildMeasuresIfNeeded(); notifyDataSetChanged(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == SOURCE_VIEW_TYPE) { return new DiffSourceViewHolder(DataBindingUtil.inflate( mLayoutInflater, R.layout.diff_source_item, parent, false)); } else if (viewType == SKIP_VIEW_TYPE) { return new DiffSkipViewHolder(DataBindingUtil.inflate( mLayoutInflater, R.layout.diff_skip_item, parent, false)); } else if (viewType == COMMENT_VIEW_TYPE) { return new DiffCommentViewHolder(DataBindingUtil.inflate( mLayoutInflater, R.layout.diff_comment_item, parent, false)); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder vh, int position) { AbstractModel model = mModel.get(position); if (vh instanceof DiffSourceViewHolder) { DiffSourceViewHolder holder = ((DiffSourceViewHolder) vh); DiffInfoModel diff = (DiffInfoModel) model; if (mMode == UNIFIED_MODE) { CharSequence text = diff.lineA != null ? diff.lineA : diff.lineB; holder.mBinding.diffA.setText(text, TextView.BufferType.NORMAL); } else { holder.mBinding.diffA.setText(diff.lineA, TextView.BufferType.NORMAL); holder.mBinding.diffB.setText(diff.lineB, TextView.BufferType.NORMAL); } holder.mBinding.setWrap(isWrapMode()); holder.mBinding.setMode(mMode); holder.mBinding.setModel(diff); holder.mBinding.setMeasurement(mDiffViewMeasurement); if (mCanEdit) { holder.mBinding.setHandlers(mEventHandlers); } } else if (vh instanceof DiffSkipViewHolder) { DiffSkipViewHolder holder = ((DiffSkipViewHolder) vh); SkipLineModel skip = (SkipLineModel) model; holder.mBinding.setWrap(isWrapMode()); holder.mBinding.setMode(mMode); holder.mBinding.setModel(skip); holder.mBinding.setMeasurement(mDiffViewMeasurement); } else if (vh instanceof DiffCommentViewHolder) { DiffCommentViewHolder holder = ((DiffCommentViewHolder) vh); CommentModel comment = (CommentModel) model; holder.mBinding.setCanEdit(mCanEdit); holder.mBinding.setWrap(isWrapMode()); holder.mBinding.setMode(mMode); holder.mBinding.setModel(comment); holder.mBinding.setMeasurement(mDiffViewMeasurement); holder.mBinding.setHandlers(mEventHandlers); if (comment.commentA != null) { holder.mBinding.actionsA.edit.setTag(R.id.tag_key, comment.commentA.message); } if (comment.commentB != null) { holder.mBinding.actionsB.edit.setTag(R.id.tag_key, comment.commentB.message); } } } @Override public int getItemViewType(int position) { AbstractModel model = mModel.get(position); if (model instanceof DiffInfoModel) { return SOURCE_VIEW_TYPE; } if (model instanceof SkipLineModel) { return SKIP_VIEW_TYPE; } return COMMENT_VIEW_TYPE; } @Override public int getItemCount() { return mModel.size(); } private void computeViewChildMeasuresIfNeeded() { boolean wrap = isWrapMode(); if (!mModel.isEmpty()) { int dp = (int) getResources().getDisplayMetrics().density; TextPaint paint = new TextPaint(); paint.setTextSize(12 * dp); int padding = 3 * dp; for (AbstractModel model : mModel) { if (model instanceof DiffInfoModel) { DiffInfoModel diff = (DiffInfoModel) model; if (wrap) { mDiffViewMeasurement.lineAWidth = MATCH_PARENT; mDiffViewMeasurement.lineBWidth = MATCH_PARENT; } else { if (mMode == UNIFIED_MODE) { // All lines are displayed in A CharSequence line = diff.lineA != null ? diff.lineA : diff.lineB; int width = (int) paint.measureText(String.valueOf(line)) + padding; mDiffViewMeasurement.lineAWidth = Math.max( mDiffViewMeasurement.lineAWidth, width); } else { // All lines are displayed in A if (diff.lineA != null) { String lineA = String.valueOf(diff.lineA); int width = (int) paint.measureText(lineA) + padding; mDiffViewMeasurement.lineAWidth = Math.max( mDiffViewMeasurement.lineAWidth, width); } if (diff.lineB != null) { String lineB = String.valueOf(diff.lineB); int width = (int) paint.measureText(lineB) + padding; mDiffViewMeasurement.lineBWidth = Math.max( mDiffViewMeasurement.lineBWidth, width); } } } if (diff.lineNumberA != null) { mDiffViewMeasurement.lineNumAWidth = Math.max( mDiffViewMeasurement.lineNumAWidth, (int) paint.measureText(String.valueOf(diff.lineNumberA))); } if (diff.lineNumberB != null) { mDiffViewMeasurement.lineNumBWidth = Math.max( mDiffViewMeasurement.lineNumBWidth, (int) paint.measureText(String.valueOf(diff.lineNumberB))); } } } // User same size for A y B number and apply a minimum mDiffViewMeasurement.lineNumAWidth = mDiffViewMeasurement.lineNumBWidth = Math.max(mDiffViewMeasurement.lineNumAWidth, mDiffViewMeasurement.lineNumBWidth); mDiffViewMeasurement.lineNumAWidth = mDiffViewMeasurement.lineNumBWidth = Math.max(mDiffViewMeasurement.lineNumAWidth, 20 * dp); // Adjust padding mDiffViewMeasurement.lineNumAWidth += (padding * 2); mDiffViewMeasurement.lineNumBWidth += (padding * 2); int diffIndicatorWidth = 16 * dp; mDiffViewMeasurement.width = mDiffViewMeasurement.lineNumAWidth + mDiffViewMeasurement.lineNumBWidth + mDiffViewMeasurement.lineAWidth + mDiffViewMeasurement.lineBWidth + diffIndicatorWidth + (dp * 2); if (mDiffViewMeasurement.width < getWidth()) { mDiffViewMeasurement.width = getWidth(); if (mMode == UNIFIED_MODE) { mDiffViewMeasurement.lineAWidth = getWidth() - mDiffViewMeasurement.lineNumAWidth - mDiffViewMeasurement.lineNumBWidth - diffIndicatorWidth - (dp * 2); } } } } } private class AsyncDiffProcessor extends AsyncTask<Void, Void, List<AbstractModel>> { private final int mMode; private final DiffContentInfo[] mDiffs; private final Pair<List<CommentInfo>, List<CommentInfo>> mComments; AsyncDiffProcessor(int mode, DiffContentInfo[] diffs, Pair<List<CommentInfo>, List<CommentInfo>> comments, Pair<List<CommentInfo>, List<CommentInfo>> drafts) { mMode = mode; mDiffs = diffs; mComments = comments; mDrafts = drafts; } @Override protected List<AbstractModel> doInBackground(Void... params) { return processDrafts(processComments(processDiffs())); } @Override protected void onPostExecute(List<AbstractModel> model) { mDiffAdapter = new DiffAdapter(mDiffMode); mLayoutManager = mTmpLayoutManager; mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mDiffAdapter); mDiffAdapter.update(model); } private List<AbstractModel> processDiffs() { if (mMode == SIDE_BY_SIDE_MODE) { return processSideBySideDiffs(); } return processUnifiedDiffs(); } private List<AbstractModel> processSideBySideDiffs() { if (mDiffs == null) { return new ArrayList<>(); } int lineNumberA = 0; int lineNumberB = 0; final Spannable.Factory spannableFactory = Spannable.Factory.getInstance(); final int noColor = ContextCompat.getColor(getContext(), android.R.color.transparent); final int addedBgColor = ContextCompat.getColor( getContext(), R.color.diffAddedBackgroundColor); final int addedFgColor = ContextCompat.getColor( getContext(), R.color.diffAddedForegroundColor); final int deletedBgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedBackgroundColor); final int deletedFgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedForegroundColor); List<AbstractModel> model = new ArrayList<>(); int j = 0; for (DiffContentInfo diff : mDiffs) { if (diff.ab != null) { // Unchanged lines int count = diff.ab.length; int skipStartAt = -1, skippedLines = -1; boolean breakAfterSkip = false; if (j == 0 && diff.ab.length > SKIPPED_LINES) { skipStartAt = 0; skippedLines = count - SKIPPED_LINES - skipStartAt; } else if (j == (mDiffs.length - 1) && diff.ab.length > SKIPPED_LINES) { skipStartAt = SKIPPED_LINES; skippedLines = count - skipStartAt; breakAfterSkip = true; } else if (diff.ab.length > (SKIPPED_LINES * 2)) { skipStartAt = SKIPPED_LINES; skippedLines = count - SKIPPED_LINES - skipStartAt; } for (int i = 0; i < count; i++) { if (skipStartAt != -1 && skipStartAt == i) { lineNumberA += skippedLines; lineNumberB += skippedLines; i += skippedLines; SkipLineModel skip = new SkipLineModel(); skip.msg = getResources().getQuantityString( R.plurals.skipped_lines, skippedLines, skippedLines); model.add(skip); if (breakAfterSkip) { break; } } String line = diff.ab[i]; DiffInfoModel m = new DiffInfoModel(); m.lineNumberA = String.valueOf(++lineNumberA); m.lineNumberB = String.valueOf(++lineNumberB); m.lineA = line; m.lineB = line; m.colorA = noColor; m.colorB = noColor; model.add(m); } } else { int posA = 0; int posB = 0; int count = Math.max( diff.a == null ? 0 : diff.a.length, diff.b == null ? 0 : diff.b.length); for (int i = 0; i < count; i++) { DiffInfoModel m = new DiffInfoModel(); m.colorA = noColor; m.colorB = noColor; if (diff.a != null && i < diff.a.length) { String line = diff.a[i]; m.lineNumberA = String.valueOf(++lineNumberA); if (diff.editA != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editA) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = posA + line.length(); if ((s1 >= posA && s1 <= l) || (s2 >= posA && s2 <= l) || (s1 <= posA && s2 >= l)) { span.setSpan(new BackgroundColorSpan(deletedFgColor), Math.max(posA, s1) - posA, Math.min(l, s2) - posA, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineA = span; } else { m.lineA = line; } m.colorA = deletedBgColor; posA += line.length() + 1; } if (diff.b != null && i < diff.b.length) { String line = diff.b[i]; m.lineNumberB = String.valueOf(++lineNumberB); if (diff.editB != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editB) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = posB + line.length(); if ((s1 >= posB && s1 <= l) || (s2 >= posB && s2 <= l) || (s1 <= posB && s2 >= l)) { span.setSpan(new BackgroundColorSpan(addedFgColor), Math.max(posB, s1) - posB, Math.min(l, s2) - posB, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineB = span; } else { m.lineB = line; } m.colorB = addedBgColor; posB += line.length() + 1; } model.add(m); } } j++; } return model; } private List<AbstractModel> processUnifiedDiffs() { if (mDiffs == null) { return new ArrayList<>(); } int lineNumberA = 0; int lineNumberB = 0; final Spannable.Factory spannableFactory = Spannable.Factory.getInstance(); final int noColor = ContextCompat.getColor(getContext(), android.R.color.transparent); final int addedBgColor = ContextCompat.getColor( getContext(), R.color.diffAddedBackgroundColor); final int addedFgColor = ContextCompat.getColor( getContext(), R.color.diffAddedForegroundColor); final int deletedBgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedBackgroundColor); final int deletedFgColor = ContextCompat.getColor( getContext(), R.color.diffDeletedForegroundColor); List<AbstractModel> model = new ArrayList<>(); int j = 0; for (DiffContentInfo diff : mDiffs) { if (diff.ab != null) { // Unchanged lines int count = diff.ab.length; int skipStartAt = -1, skippedLines = -1; boolean breakAfterSkip = false; if (j == 0 && diff.ab.length > SKIPPED_LINES) { skipStartAt = 0; skippedLines = count - SKIPPED_LINES - skipStartAt; } else if (j == (mDiffs.length - 1) && diff.ab.length > SKIPPED_LINES) { skipStartAt = SKIPPED_LINES; skippedLines = count - skipStartAt; breakAfterSkip = true; } else if (diff.ab.length > (SKIPPED_LINES * 2)) { skipStartAt = SKIPPED_LINES; skippedLines = count - SKIPPED_LINES - skipStartAt; } for (int i = 0; i < count; i++) { if (skipStartAt != -1 && skipStartAt == i) { lineNumberA += skippedLines; lineNumberB += skippedLines; i += skippedLines; SkipLineModel skip = new SkipLineModel(); skip.msg = getResources().getQuantityString( R.plurals.skipped_lines, skippedLines, skippedLines); model.add(skip); if (breakAfterSkip) { break; } } String line = diff.ab[i]; DiffInfoModel m = new DiffInfoModel(); m.lineNumberA = String.valueOf(++lineNumberA); m.lineNumberB = String.valueOf(++lineNumberB); m.lineA = line; m.lineB = line; m.colorA = noColor; m.colorB = noColor; model.add(m); } } else { if (diff.a != null) { int pos = 0; for (String line : diff.a) { DiffInfoModel m = new DiffInfoModel(); m.lineNumberA = String.valueOf(++lineNumberA); if (diff.editA != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editA) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = pos + line.length(); if ((s1 >= pos && s1 <= l) || (s2 >= pos && s2 <= l) || (s1 <= pos && s2 >= l)) { span.setSpan(new BackgroundColorSpan(deletedFgColor), Math.max(pos, s1) - pos, Math.min(l, s2) - pos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineA = span; } else { m.lineA = line; } m.colorA = deletedBgColor; m.colorB = noColor; model.add(m); pos += line.length() + 1; } } if (diff.b != null) { int pos = 0; for (String line : diff.b) { DiffInfoModel m = new DiffInfoModel(); m.lineNumberB = String.valueOf(++lineNumberB); if (diff.editB != null) { Spannable span = spannableFactory.newSpannable(line); int s2 = 0; for (ArrayList<Integer> intra : diff.editB) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = pos + line.length(); if ((s1 >= pos && s1 <= l) || (s2 >= pos && s2 <= l) || (s1 <= pos && s2 >= l)) { span.setSpan(new BackgroundColorSpan(addedFgColor), Math.max(pos, s1) - pos, Math.min(l, s2) - pos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } m.lineB = span; } else { m.lineB = line; } m.colorA = addedBgColor; m.colorB = noColor; model.add(m); pos += line.length() + 1; } } } j++; } return model; } private List<AbstractModel> processComments(List<AbstractModel> model) { if (mComments != null) { // Comments on A if (mComments.second != null) { addCommentsToModel(model, mComments.first, true, false); } // Comments on B if (mComments.second != null) { addCommentsToModel(model, mComments.second, false, false); } } return model; } private List<AbstractModel> processDrafts(List<AbstractModel> model) { if (mDrafts != null) { // Comments on A if (mDrafts.second != null) { addCommentsToModel(model, mDrafts.first, true, true); } // Comments on B if (mDrafts.second != null) { addCommentsToModel(model, mDrafts.second, false, true); } } return model; } private void addCommentsToModel(List<AbstractModel> model, List<CommentInfo> comments, boolean isA, boolean isDraft) { if (comments == null) { return; } int count = comments.size(); for (int i = 0; i < count; i++) { CommentInfo comment = comments.get(i); int pos = findLineInModel(model, isA, comment.line); if (pos != -1) { if (mMode == UNIFIED_MODE) { CommentModel commentModel = new CommentModel(); commentModel.isDraft = isDraft; commentModel.commentA = comment; int nextPos = findNextPositionWithoutComment(model, pos); if (nextPos != -1) { model.add(nextPos, commentModel); } else { model.add(pos + 1, commentModel); } } else { int reusablePos = findReusableCommentView(model, pos, isA); if (reusablePos != -1) { CommentModel commentModel = (CommentModel) model.get(reusablePos); commentModel.isDraft = isDraft; if (isA) { commentModel.commentA = comment; } else { commentModel.commentB = comment; } } else { CommentModel commentModel = new CommentModel(); commentModel.isDraft = isDraft; if (isA) { commentModel.commentA = comment; } else { commentModel.commentB = comment; } int nextPos = findNextPositionWithoutComment(model, pos); if (nextPos != -1) { model.add(nextPos, commentModel); } else { model.add(pos + 1, commentModel); } } } } } } private int findLineInModel(List<AbstractModel> model, boolean isA, int line) { int count = model.size(); for (int i = 0; i < count; i++) { AbstractModel m = model.get(i); if (m instanceof DiffInfoModel) { DiffInfoModel diff = (DiffInfoModel) m; if (isA && diff.lineNumberA != null && Integer.valueOf(diff.lineNumberA) == line) { return i; } else if (!isA && diff.lineNumberB != null && Integer.valueOf(diff.lineNumberB) == line) { return i; } } } return -1; } private int findReusableCommentView(List<AbstractModel> model, int pos, boolean isA) { int count = model.size(); for (int i = pos + 1; i < count; i++) { AbstractModel m = model.get(i); if (!(m instanceof CommentModel)) { break; } CommentModel comment = (CommentModel) m; if ((isA && comment.commentA == null && comment.commentB != null) || (!isA && comment.commentB == null && comment.commentA != null)) { return i; } } return -1; } private int findNextPositionWithoutComment(List<AbstractModel> model, int pos) { int count = model.size(); for (int i = pos + 1; i < count; i++) { AbstractModel m = model.get(i); if (!(m instanceof CommentModel)) { return i; } } return -1; } } private final RecyclerView mRecyclerView; private DiffAdapter mDiffAdapter; private LayoutManager mLayoutManager; private LayoutManager mTmpLayoutManager; private boolean mHighlightTabs; private boolean mCanEdit; private int mDiffMode = UNIFIED_MODE; private DiffContentInfo[] mAllDiffs; private Pair<List<CommentInfo>, List<CommentInfo>> mComments; private Pair<List<CommentInfo>, List<CommentInfo>> mDrafts; private OnCommentListener mOnCommentListener; private EventHandlers mEventHandlers; private AsyncDiffProcessor mTask; public DiffView(Context context) { this(context, null); } public DiffView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DiffView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mEventHandlers = new EventHandlers(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( MATCH_PARENT, MATCH_PARENT); mRecyclerView = new RecyclerView(context); mLayoutManager = new LinearLayoutManager(context); mRecyclerView.setLayoutManager(mLayoutManager); mDiffAdapter = new DiffAdapter(mDiffMode); mRecyclerView.setAdapter(mDiffAdapter); mRecyclerView.setVerticalScrollBarEnabled(true); addView(mRecyclerView, params); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); update(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // Stops running things now if (mTask != null) { mTask.cancel(true); } } @Override protected Parcelable onSaveInstanceState() { SavedState savedState = new SavedState(super.onSaveInstanceState()); savedState.mHighlightTabs = mHighlightTabs; savedState.mCanEdit = mCanEdit; savedState.mDiffMode = mDiffMode; savedState.mAllDiffs = SerializationManager.getInstance().toJson(mAllDiffs); savedState.mComments = SerializationManager.getInstance().toJson(mComments); savedState.mDrafts = SerializationManager.getInstance().toJson(mDrafts); return savedState; } @Override protected void onRestoreInstanceState(Parcelable state) { //begin boilerplate code so parent classes can restore state if(!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mHighlightTabs = savedState.mHighlightTabs; mCanEdit = savedState.mCanEdit; mDiffMode = savedState.mDiffMode; Type type = new TypeToken<DiffContentInfo[]>(){}.getType(); mAllDiffs = SerializationManager.getInstance().fromJson(savedState.mAllDiffs, type); type = new TypeToken<Pair<List<CommentInfo>, List<CommentInfo>>>(){}.getType(); mComments = SerializationManager.getInstance().fromJson(savedState.mComments, type); mDrafts = SerializationManager.getInstance().fromJson(savedState.mDrafts, type); } public DiffView from(DiffContentInfo[] allDiffs) { mAllDiffs = allDiffs; return this; } public DiffView withComments(Pair<List<CommentInfo>, List<CommentInfo>> comments) { mComments = comments; return this; } public DiffView withDrafts(Pair<List<CommentInfo>, List<CommentInfo>> drafts) { mDrafts = drafts; return this; } public DiffView canEdit(boolean canEdit) { mCanEdit = canEdit; return this; } public DiffView highlightTabs(boolean highlightTabs) { mHighlightTabs = highlightTabs; return this; } public DiffView wrap(boolean wrap) { mTmpLayoutManager = wrap ? new LinearLayoutManager(getContext()) : new UnwrappedLinearLayoutManager(getContext()); return this; } public DiffView mode(int mode) { mDiffMode = mode; return this; } public DiffView listenOn(OnCommentListener cb) { mOnCommentListener = cb; return this; } public void update() { if (mTask != null) { mTask.cancel(true); } mTask = new AsyncDiffProcessor(mDiffMode, mAllDiffs, mComments, mDrafts); mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private boolean isWrapMode() { return mLayoutManager == null || !(mLayoutManager instanceof UnwrappedLinearLayoutManager); } static class SavedState extends BaseSavedState { boolean mHighlightTabs; boolean mCanEdit; int mDiffMode; String mAllDiffs; String mComments; String mDrafts; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); mHighlightTabs = in.readInt() == 1; mCanEdit = in.readInt() == 1; mDiffMode = in.readInt(); mAllDiffs = in.readString(); mComments = in.readString(); mDrafts = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mHighlightTabs ? 1 : 0); out.writeInt(mCanEdit ? 1 : 0); out.writeInt(mDiffMode); out.writeString(mAllDiffs); out.writeString(mComments); out.writeString(mDrafts); } //required field that makes Parcelables from a Parcel public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
Improve diffview redrawing Signed-off-by: Jorge Ruesga <[email protected]>
app/src/main/java/com/ruesga/rview/widget/DiffView.java
Improve diffview redrawing
<ide><path>pp/src/main/java/com/ruesga/rview/widget/DiffView.java <ide> <ide> @Override <ide> protected void onPostExecute(List<AbstractModel> model) { <del> mDiffAdapter = new DiffAdapter(mDiffMode); <del> mLayoutManager = mTmpLayoutManager; <del> mRecyclerView.setLayoutManager(mLayoutManager); <del> mRecyclerView.setAdapter(mDiffAdapter); <add> if (!mLayoutManager.equals(mTmpLayoutManager)) { <add> mDiffAdapter = new DiffAdapter(mDiffMode); <add> if (mTmpLayoutManager != null) { <add> mLayoutManager = mTmpLayoutManager; <add> } <add> mRecyclerView.setLayoutManager(mLayoutManager); <add> mRecyclerView.setAdapter(mDiffAdapter); <add> } <ide> mDiffAdapter.update(model); <ide> } <ide> <ide> } <ide> <ide> @Override <del> protected void onAttachedToWindow() { <del> super.onAttachedToWindow(); <del> update(); <del> } <del> <del> @Override <ide> protected void onDetachedFromWindow() { <ide> super.onDetachedFromWindow(); <ide> <ide> } <ide> <ide> public DiffView wrap(boolean wrap) { <del> mTmpLayoutManager = wrap <del> ? new LinearLayoutManager(getContext()) <del> : new UnwrappedLinearLayoutManager(getContext()); <add> if (isWrapMode() != wrap) { <add> mTmpLayoutManager = wrap <add> ? new LinearLayoutManager(getContext()) <add> : new UnwrappedLinearLayoutManager(getContext()); <add> } else { <add> mTmpLayoutManager = mLayoutManager; <add> } <ide> return this; <ide> } <ide>
JavaScript
bsd-2-clause
e9710a238a9f480dabbb2f86f99fe36db0012423
0
opbeat/opbeat-node,opbeat/opbeat-node
'use strict' var shimmer = require('shimmer') var SERVER_FNS = ['on', 'addListener'] module.exports = function (http, agent) { agent.logger.trace('shimming http.Server.prototype functions:', SERVER_FNS) shimmer.massWrap(http.Server.prototype, SERVER_FNS, function (orig, name) { return function (event, listener) { if (event === 'request' && typeof listener === 'function') return orig.call(this, event, onRequest) else return orig.apply(this, arguments) function onRequest (req, res) { agent.logger.trace('intercepted call to http.Server.prototype.%s', name) var trans = agent.startTransaction(req.method + ' ' + req.url, 'web.http') trans.req = req res.once('finish', function () { var path // Get proper route name from Express 4.x if (req.route) { path = req.route.path || req.route.regexp && req.route.regexp.source } if (!path) { agent.logger.warn('[%s] could not extract route name from request', trans._uuid) path = 'unknown route' } trans._defaultName = req.method + ' ' + path trans.result = res.statusCode agent.logger.trace('[%s] ending transaction', trans._uuid) trans.end() }) listener.apply(this, arguments) } } }) agent.logger.trace('shimming http.request function') shimmer.wrap(http, 'request', function (orig, name) { return function () { var trace = agent.buildTrace() var uuid = trace ? trace.transaction._uuid : 'n/a' agent.logger.trace('[%s] intercepted call to http.request (transaction: %s)', uuid, trace ? 'exists' : 'missing') var req = orig.apply(this, arguments) if (!trace) return req if (req._headers.host === agent._apiHost) { agent.logger.trace('[%s] ignore http request to opbeat server', uuid) return req } else { agent.logger.trace('[%s] detected host:', uuid, req._headers.host) } var name = req.method + ' ' + req._headers.host trace.start(name, 'ext.http.http') req.on('response', onresponse) return req function onresponse (res) { agent.logger.trace('[%s] intercepted http.ClientRequest response event', uuid) res.on('end', function () { agent.logger.trace('[%s] intercepted http.IncomingMessage end event', uuid) trace.end() }) } } }) return http }
lib/instrumentation/modules/http.js
'use strict' var shimmer = require('shimmer') var SERVER_FNS = ['on', 'addListener'] module.exports = function (http, agent) { agent.logger.trace('shimming http.Server.prototype functions:', SERVER_FNS) shimmer.massWrap(http.Server.prototype, SERVER_FNS, function (orig, name) { return function (event, listener) { if (event === 'request' && typeof listener === 'function') return orig.call(this, event, onRequest) else return orig.apply(this, arguments) function onRequest (req, res) { agent.logger.trace('intercepted call to http.Server.prototype.%s', name) var trans = agent.startTransaction(req.method + ' ' + req.url, 'web.http') trans.req = req res.once('finish', function () { // Get proper route name from Express 4.x if (req.route) { var path = req.route.path || req.route.regexp && req.route.regexp.source if (!path) agent.logger.debug('no default route name found') else trans._defaultName = req.method + ' ' + path } trans.result = res.statusCode agent.logger.trace('[%s] ending transaction', trans._uuid) trans.end() }) listener.apply(this, arguments) } } }) agent.logger.trace('shimming http.request function') shimmer.wrap(http, 'request', function (orig, name) { return function () { var trace = agent.buildTrace() var uuid = trace ? trace.transaction._uuid : 'n/a' agent.logger.trace('[%s] intercepted call to http.request (transaction: %s)', uuid, trace ? 'exists' : 'missing') var req = orig.apply(this, arguments) if (!trace) return req if (req._headers.host === agent._apiHost) { agent.logger.trace('[%s] ignore http request to opbeat server', uuid) return req } else { agent.logger.trace('[%s] detected host:', uuid, req._headers.host) } var name = req.method + ' ' + req._headers.host trace.start(name, 'ext.http.http') req.on('response', onresponse) return req function onresponse (res) { agent.logger.trace('[%s] intercepted http.ClientRequest response event', uuid) res.on('end', function () { agent.logger.trace('[%s] intercepted http.IncomingMessage end event', uuid) trace.end() }) } } }) return http }
Group all transactions where the route could not be extracted
lib/instrumentation/modules/http.js
Group all transactions where the route could not be extracted
<ide><path>ib/instrumentation/modules/http.js <ide> trans.req = req <ide> <ide> res.once('finish', function () { <add> var path <add> <ide> // Get proper route name from Express 4.x <ide> if (req.route) { <del> var path = req.route.path || req.route.regexp && req.route.regexp.source <del> if (!path) agent.logger.debug('no default route name found') <del> else trans._defaultName = req.method + ' ' + path <add> path = req.route.path || req.route.regexp && req.route.regexp.source <ide> } <add> <add> if (!path) { <add> agent.logger.warn('[%s] could not extract route name from request', trans._uuid) <add> path = 'unknown route' <add> } <add> <add> trans._defaultName = req.method + ' ' + path <ide> <ide> trans.result = res.statusCode <ide> agent.logger.trace('[%s] ending transaction', trans._uuid)
JavaScript
mit
8a39e2becc2d6e25141cf95ceecaa09b08c99c89
0
cofacts/rumors-site,cofacts/rumors-site
import { useRef, useState, forwardRef, memo } from 'react'; import { useRouter } from 'next/router'; import DateRangeIcon from '@material-ui/icons/DateRange'; import { makeStyles } from '@material-ui/core/styles'; import { ButtonGroup, Button, Menu, MenuItem } from '@material-ui/core'; import { goToUrlQueryAndResetPagination } from 'lib/listPage'; import { c, t } from 'ttag'; const useStyles = makeStyles(theme => ({ root: { display: 'flex', alignItems: 'center', }, buttonGroup: { border: `1px solid ${theme.palette.secondary[100]}`, }, calendarButton: { background: theme.palette.common.white, padding: 5, minWidth: 0, '&:hover': { background: theme.palette.secondary[100], color: theme.palette.secondary[300], }, [theme.breakpoints.up('md')]: { padding: 7, }, }, calendarIcon: { fontSize: 14, color: theme.palette.secondary[300], [theme.breakpoints.up('md')]: { fontSize: 18, }, }, selectButton: { background: theme.palette.common.white, padding: '0px 8px', }, startDate: { background: theme.palette.common.white, marginLeft: '0 !important', border: `1px solid ${theme.palette.secondary[100]}`, borderTopRightRadius: 4, borderBottomRightRadius: 4, }, to: { padding: '0 11px', }, endDate: { background: theme.palette.common.white, border: `1px solid ${theme.palette.secondary[100]}`, borderRadius: 4, padding: '1.5px 0', minWidth: 100, [theme.breakpoints.up('md')]: { padding: '5.5px 0', }, }, })); export const options = [ { value: 'all', label: c('Time range dropdown').t`All` }, { value: 'now-1d/d', label: t`In 1 Day` }, { value: 'now-1w/d', label: t`In 1 Week` }, { value: 'now-1M/d', label: t`In 1 Month` }, { value: 'custom', label: c('Time range dropdown').t`Custom` }, ]; /** * @param {string?} start * @param {string?} end * @return {string} one of options' value */ function getSelectedValue(start, end) { if (start === undefined && end === undefined) return 'all'; if (end !== undefined) return 'custom'; const option = options.find(o => o.value === start); return option ? option.value : 'custom'; } /* material ui actually passes down some non-DOM props to children, and this cause some warning on runtime. but I want to use the ButtonGroup styles, so I use this hacky workaround. */ const Input = forwardRef(({ value, className, type, onChange }, ref) => ( <input ref={ref} value={value} className={className} type={type} onChange={onChange} /> )); Input.displayName = 'input'; /** * Controlled input of time range * * @param {string?} props.start - ISO date (YYYY-MM-DD) or relative date format supported by Elasticsearch. * @param {string?} props.end - ISO date (YYYY-MM-DD) or relative date format supported by Elasticsearch. * @param {(start: string, end: string) => void} onChange */ export function BaseTimeRange({ start, end, onChange = () => null }) { const [anchor, setAnchor] = useState(null); const anchorEl = useRef(null); const classes = useStyles(); const openMenu = () => setAnchor(anchorEl.current); const closeMenu = () => setAnchor(null); const select = option => () => { switch (option) { case 'all': onChange(undefined, undefined); break; case 'custom': onChange('', ''); break; default: onChange(option, undefined); } closeMenu(); }; const selectedValue = getSelectedValue(start, end); const isCustom = selectedValue === 'custom'; return ( <div className={classes.root}> <ButtonGroup classes={{ contained: classes.buttonGroup }}> <Button className={classes.calendarButton} onClick={openMenu}> <DateRangeIcon className={classes.calendarIcon} /> </Button> {isCustom ? ( <Input ref={anchorEl} value={start} className={classes.startDate} onChange={e => { onChange(e.target.value, end); }} type="date" /> ) : ( <Button className={classes.selectButton} ref={anchorEl} onClick={openMenu} > {options.find(option => option.value === selectedValue).label} </Button> )} </ButtonGroup> {isCustom && ( <> <span className={classes.to}>{t`to`}</span> <input value={end} className={classes.endDate} onChange={e => { onChange(start, e.target.value); }} type="date" /> </> )} <Menu anchorEl={anchor} keepMounted open={Boolean(anchor)} onClose={closeMenu} > {options.map(option => ( <MenuItem key={option.value} onClick={select(option.value)} data-ga={`MenuItem(${option.value})`} > {option.label} </MenuItem> ))} </Menu> </div> ); } /** * Time range control connnected to URL "start", "end" param */ function TimeRange() { const { query } = useRouter(); return ( <BaseTimeRange start={query.start} end={query.end} onChange={(start, end) => { goToUrlQueryAndResetPagination({ ...query, start, end, }); }} /> ); } export default memo(TimeRange);
components/ListPage/TimeRange.js
import { useRef, useState, forwardRef, memo } from 'react'; import { useRouter } from 'next/router'; import DateRangeIcon from '@material-ui/icons/DateRange'; import { makeStyles } from '@material-ui/core/styles'; import { ButtonGroup, Button, Menu, MenuItem } from '@material-ui/core'; import { goToUrlQueryAndResetPagination } from 'lib/listPage'; import { c, t } from 'ttag'; const useStyles = makeStyles(theme => ({ root: { display: 'flex', alignItems: 'center', }, buttonGroup: { border: `1px solid ${theme.palette.secondary[100]}`, }, calendarButton: { background: theme.palette.common.white, padding: 5, minWidth: 0, '&:hover': { background: theme.palette.secondary[100], color: theme.palette.secondary[300], }, [theme.breakpoints.up('md')]: { padding: 7, }, }, calendarIcon: { fontSize: 14, color: theme.palette.secondary[300], [theme.breakpoints.up('md')]: { fontSize: 18, }, }, selectButton: { background: theme.palette.common.white, padding: '0px 8px', }, startDate: { background: theme.palette.common.white, marginLeft: '0 !important', border: `1px solid ${theme.palette.secondary[100]}`, borderTopRightRadius: 4, borderBottomRightRadius: 4, }, to: { padding: '0 11px', }, endDate: { background: theme.palette.common.white, border: `1px solid ${theme.palette.secondary[100]}`, borderRadius: 4, padding: '1.5px 0', minWidth: 100, [theme.breakpoints.up('md')]: { padding: '5.5px 0', }, }, })); export const options = [ { value: 'all', label: c('Time range dropdown').t`All` }, { value: 'now-1d/d', label: t`In 1 Day` }, { value: 'now-1w/d', label: t`In 1 Week` }, { value: 'now-1m/d', label: t`In 1 Month` }, { value: 'custom', label: c('Time range dropdown').t`Custom` }, ]; /** * @param {string?} start * @param {string?} end * @return {string} one of options' value */ function getSelectedValue(start, end) { if (start === undefined && end === undefined) return 'all'; if (end !== undefined) return 'custom'; const option = options.find(o => o.value === start); return option ? option.value : 'custom'; } /* material ui actually passes down some non-DOM props to children, and this cause some warning on runtime. but I want to use the ButtonGroup styles, so I use this hacky workaround. */ const Input = forwardRef(({ value, className, type, onChange }, ref) => ( <input ref={ref} value={value} className={className} type={type} onChange={onChange} /> )); Input.displayName = 'input'; /** * Controlled input of time range * * @param {string?} props.start - ISO date (YYYY-MM-DD) or relative date format supported by Elasticsearch. * @param {string?} props.end - ISO date (YYYY-MM-DD) or relative date format supported by Elasticsearch. * @param {(start: string, end: string) => void} onChange */ export function BaseTimeRange({ start, end, onChange = () => null }) { const [anchor, setAnchor] = useState(null); const anchorEl = useRef(null); const classes = useStyles(); const openMenu = () => setAnchor(anchorEl.current); const closeMenu = () => setAnchor(null); const select = option => () => { switch (option) { case 'all': onChange(undefined, undefined); break; case 'custom': onChange('', ''); break; default: onChange(option, undefined); } closeMenu(); }; const selectedValue = getSelectedValue(start, end); const isCustom = selectedValue === 'custom'; return ( <div className={classes.root}> <ButtonGroup classes={{ contained: classes.buttonGroup }}> <Button className={classes.calendarButton} onClick={openMenu}> <DateRangeIcon className={classes.calendarIcon} /> </Button> {isCustom ? ( <Input ref={anchorEl} value={start} className={classes.startDate} onChange={e => { onChange(e.target.value, end); }} type="date" /> ) : ( <Button className={classes.selectButton} ref={anchorEl} onClick={openMenu} > {options.find(option => option.value === selectedValue).label} </Button> )} </ButtonGroup> {isCustom && ( <> <span className={classes.to}>{t`to`}</span> <input value={end} className={classes.endDate} onChange={e => { onChange(start, e.target.value); }} type="date" /> </> )} <Menu anchorEl={anchor} keepMounted open={Boolean(anchor)} onClose={closeMenu} > {options.map(option => ( <MenuItem key={option.value} onClick={select(option.value)} data-ga={`MenuItem(${option.value})`} > {option.label} </MenuItem> ))} </Menu> </div> ); } /** * Time range control connnected to URL "start", "end" param */ function TimeRange() { const { query } = useRouter(); return ( <BaseTimeRange start={query.start} end={query.end} onChange={(start, end) => { goToUrlQueryAndResetPagination({ ...query, start, end, }); }} /> ); } export default memo(TimeRange);
Fix TimeRange "In 1 Month" option Ref: https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math
components/ListPage/TimeRange.js
Fix TimeRange "In 1 Month" option Ref: https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math
<ide><path>omponents/ListPage/TimeRange.js <ide> { value: 'all', label: c('Time range dropdown').t`All` }, <ide> { value: 'now-1d/d', label: t`In 1 Day` }, <ide> { value: 'now-1w/d', label: t`In 1 Week` }, <del> { value: 'now-1m/d', label: t`In 1 Month` }, <add> { value: 'now-1M/d', label: t`In 1 Month` }, <ide> { value: 'custom', label: c('Time range dropdown').t`Custom` }, <ide> ]; <ide>
JavaScript
mit
434213a0b3722f097c49869ae5476a2a70b871ca
0
motorcyclejs/motorcyclejs,motorcyclejs/motorcyclejs,motorcyclejs/motorcyclejs
import Stream from 'most/lib/Stream' import MulticastSource from 'most/lib/source/MulticastSource' import forEach from 'fast.js/array/forEach' const tryEvent = (t, x, sink) => { try { sink.event(t, x) } catch (e) { sink.error(t, e) } } const EventAdapter = function EventAdapter(// eslint-disable-line init, event, source, useCapture, sink, scheduler ) { this.event = event this.source = source this.useCapture = useCapture const addEvent = ev => { tryEvent(scheduler.now(), ev, sink) } this._dispose = init( source, event, addEvent, useCapture ) } EventAdapter.prototype.dispose = function dispose() { return this._dispose(this.event, this.source) } const initEventTarget = (source, event, addEvent, useCapture) => { // eslint-disable-line forEach( source, s => s.addEventListener(event, addEvent, useCapture) ) const dispose = (_event, target) => { forEach( target, t => t.removeEventListener(_event, addEvent, useCapture) ) } return dispose } function EventTargetSource(event, source, useCapture) { this.event = event this.source = source this.useCapture = useCapture } EventTargetSource.prototype.run = function run(sink, scheduler) { return new EventAdapter( initEventTarget, this.event, this.source, this.useCapture, sink, scheduler ) } const fromEvent = (event, source, useCapture = false) => { // is not a NodeList if (!source.length) { throw new Error( `source must be a NodeList or an Array of DOM Nodes` ) } let s if (source[0].addEventListener && source[0].removeEventListener) { s = new MulticastSource( new EventTargetSource(event, source, useCapture) ) } else { throw new Error( `source must support addEventListener/removeEventListener` ) } return new Stream(s) } export default fromEvent
dom/src/fromEvent.js
import Stream from 'most/lib/Stream' import MulticastSource from 'most/lib/source/MulticastSource' import forEach from 'fast.js/array/forEach' const tryEvent = (t, x, sink) => { try { sink.event(t, x) } catch(e) { sink.error(t, e) } } const EventAdapter = function EventAdapter(// eslint-disable-line init, event, source, useCapture, sink, scheduler ) { this.event = event this.source = source this.useCapture = useCapture const addEvent = ev => { tryEvent(scheduler.now(), ev, sink) } this._dispose = init( source, event, addEvent, useCapture ) } EventAdapter.prototype.dispose = function dispose() { return this._dispose(this.event, this.source) } const initEventTarget = (source, event, addEvent, useCapture) => { // eslint-disable-line forEach( source, s => s.addEventListener(event, addEvent, useCapture) ) const dispose = (_event, target) => { forEach( target, t => t.removeEventListener(_event, addEvent, useCapture) ) } return dispose } function EventTargetSource(event, source, useCapture) { this.event = event this.source = source this.useCapture = useCapture } EventTargetSource.prototype.run = function run(sink, scheduler) { return new EventAdapter( initEventTarget, this.event, this.source, this.useCapture, sink, scheduler ) } const fromEvent = (event, source, useCapture = false) => { // is not a NodeList if (!source.length) { throw new Error( `source must be a NodeList or an Array of DOM Nodes` ) } let s if (source[0].addEventListener && source[0].removeEventListener) { s = new MulticastSource( new EventTargetSource(event, source, useCapture) ) } else { throw new Error( `source must support addEventListener/removeEventListener` ) } return new Stream(s) } export default fromEvent
style(fromEvent): fix spacing after catch Fix eslint error
dom/src/fromEvent.js
style(fromEvent): fix spacing after catch
<ide><path>om/src/fromEvent.js <ide> (t, x, sink) => { <ide> try { <ide> sink.event(t, x) <del> } catch(e) { <add> } catch (e) { <ide> sink.error(t, e) <ide> } <ide> }
Java
bsd-3-clause
c755f4b211c268ac286100c2ff75cee1cc7644b5
0
ibr-cm/avrora,ibr-cm/avrora,ibr-cm/avrora
/** * Copyright (c) 2013-2014, TU Braunschweig * 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 University of California, Los Angeles 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 avrora.sim.platform; import avrora.core.Program; import avrora.sim.Simulation; import avrora.sim.Simulator; import avrora.sim.clock.ClockDomain; import avrora.sim.mcu.ATMega1284p; import avrora.sim.mcu.AtmelMicrocontroller; import avrora.sim.mcu.Microcontroller; import avrora.sim.mcu.SPI; import avrora.sim.mcu.SPIDevice; import avrora.sim.mcu.TWI; import avrora.sim.platform.devices.ADXL345; import avrora.sim.platform.devices.AT45DB; import avrora.sim.platform.devices.BMP085; import avrora.sim.platform.devices.Button; import avrora.sim.platform.devices.L3G4200D; import avrora.sim.radio.AT86RF231Radio; import avrora.sim.radio.ATmega128RFA1Radio; import avrora.sim.util.LCX138; import cck.text.Terminal; /** * The <code>Inga</code> class is an implementation of the <code>Platform</code> * interface that represents * both a specific microcontroller and the devices connected to it. This * implements the Inga * configuration, an ATMega1284p with SPI connection to an AT86RF230 radio, and * some other peripherals. * * @author Ben L. Titzer * @author Daniel Lee * @author David Kopf * @author S. Willenborg */ public class Inga extends Platform { protected static final int MAIN_HZ = 8000000; protected static final Simulation mysim = null; public static class Factory implements PlatformFactory { /** * The <code>newPlatform()</code> method is a factory method used to create new instances of the * <code>Raven</code> class. * @param id the integer ID of the node * @param sim the simulation * @param p the program to load onto the node @return a new instance of the <code>Mica2</code> platform * @return new Inga platform */ @Override public Platform newPlatform(int id, Simulation sim, Program p) { ClockDomain cd = new ClockDomain(MAIN_HZ); cd.newClock("external", 32768); return new Inga(new ATMega1284p(id, sim, cd, p)); } } protected final Simulator sim; protected ATmega128RFA1Radio radio; protected LED.LEDGroup ledGroup; private Inga(Microcontroller m) { super(m); sim = m.getSimulator(); addDevices(); } /** * The <code>addDevices()</code> method is used to add * the external (off-chip) devices to the platform. */ private void addDevices() { LED green = new LED(sim, Terminal.COLOR_GREEN, "Green"); LED orange = new LED(sim, Terminal.COLOR_YELLOW, "Orange"); ledGroup = new LED.LEDGroup(sim, new LED[]{green, orange}); addDevice("leds", ledGroup); //AtmelMicrocontroller amcu = (AtmelMicrocontroller)mcu; mcu.getPin("PD5").connectOutput(green); mcu.getPin("PD7").connectOutput(orange); // install the new AT86RF230 radio. Actually an AT86RF231. AT86RF231Radio radio = new AT86RF231Radio(mcu, MAIN_HZ * 2); // mcu.getPin("PB7").connectOutput(radio.SCLK_pin); mcu.getPin(3).connectOutput(radio.SCLK_pin); //PB7 mcu.getPin(1).connectOutput(radio.MOSI_pin); //PB5 mcu.getPin(2).connectInput(radio.MISO_pin); //PB6 mcu.getPin(41).connectOutput(radio.RSTN_pin); //PB1 mcu.getPin(43).connectOutput(radio.SLPTR_pin);//PB3 mcu.getPin(44).connectOutput(radio.CS_pin); //PB4 SPI spi = (SPI) ((AtmelMicrocontroller) mcu).getDevice("spi"); SPIDevice spi2 = (SPIDevice) ((AtmelMicrocontroller) mcu).getDevice("usart1"); spi.connect(radio.spiInterface); addDevice("radio", radio); radio.RF231_interrupt = mcu.getProperties().getInterrupt("TIMER1 CAPT"); TWI twi = (TWI) ((AtmelMicrocontroller) mcu).getDevice("twi"); BMP085 pressure = new BMP085(); twi.connect(pressure); addDevice("bmp085", pressure); L3G4200D gyroscope = new L3G4200D(); twi.connect(gyroscope); addDevice("l3g4200d", gyroscope); LCX138 decoder = new LCX138(); mcu.getPin(32).connectOutput(decoder.A0); mcu.getPin(31).connectOutput(decoder.A1); mcu.getPin(30).connectOutput(decoder.A2); decoder.E1.write(false); decoder.E2.write(false); decoder.E3.write(true); addDevice("lcx138", decoder); AT45DB flash = new AT45DB(); flash.connectCS(decoder.O1); spi2.connect(flash); addDevice("at45db", flash); ADXL345 accelerometer = new ADXL345(sim); accelerometer.connectCS(decoder.O2); spi2.connect(accelerometer); addDevice("adxl345", accelerometer); Button button = new Button(); mcu.getPin(42).connectInput(button.output); addDevice("button", button); } }
src/avrora/sim/platform/Inga.java
/** * Copyright (c) 2013-2014, TU Braunschweig * 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 University of California, Los Angeles 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 avrora.sim.platform; import avrora.core.Program; import avrora.sim.Simulation; import avrora.sim.Simulator; import avrora.sim.clock.ClockDomain; import avrora.sim.mcu.ATMega1284p; import avrora.sim.mcu.AtmelMicrocontroller; import avrora.sim.mcu.Microcontroller; import avrora.sim.mcu.SPI; import avrora.sim.mcu.SPIDevice; import avrora.sim.mcu.TWI; import avrora.sim.platform.devices.ADXL345; import avrora.sim.platform.devices.AT45DB; import avrora.sim.platform.devices.BMP085; import avrora.sim.platform.devices.Button; import avrora.sim.platform.devices.L3G4200D; import avrora.sim.radio.AT86RF231Radio; import avrora.sim.radio.ATmega128RFA1Radio; import avrora.sim.util.LCX138; import cck.text.Terminal; /** * The <code>Inga</code> class is an implementation of the <code>Platform</code> * interface that represents * both a specific microcontroller and the devices connected to it. This * implements the Inga * configuration, an ATMega1284p with SPI connection to an AT86RF230 radio, and * some other peripherals. * * @author Ben L. Titzer * @author Daniel Lee * @author David Kopf * @author S. Willenborg */ public class Inga extends Platform { protected static final int MAIN_HZ = 8000000; protected static final Simulation mysim = null; public static class Factory implements PlatformFactory { /** * The <code>newPlatform()</code> method is a factory method used to create new instances of the * <code>Raven</code> class. * @param id the integer ID of the node * @param sim the simulation * @param p the program to load onto the node @return a new instance of the <code>Mica2</code> platform * @return new Inga platform */ @Override public Platform newPlatform(int id, Simulation sim, Program p) { ClockDomain cd = new ClockDomain(MAIN_HZ); cd.newClock("external", 32768); return new Inga(new ATMega1284p(id, sim, cd, p)); } } protected final Simulator sim; protected ATmega128RFA1Radio radio; protected LED.LEDGroup ledGroup; private Inga(Microcontroller m) { super(m); sim = m.getSimulator(); addDevices(); } /** * The <code>addDevices()</code> method is used to add * the external (off-chip) devices to the platform. */ private void addDevices() { LED red = new LED(sim, Terminal.COLOR_RED, "Red"); LED green = new LED(sim, Terminal.COLOR_GREEN, "Green"); LED blue = new LED(sim, Terminal.COLOR_BLUE, "Blue"); ledGroup = new LED.LEDGroup(sim, new LED[]{red, green, blue}); addDevice("leds", ledGroup); //AtmelMicrocontroller amcu = (AtmelMicrocontroller)mcu; mcu.getPin("PD5").connectOutput(blue); mcu.getPin("PD6").connectOutput(green); mcu.getPin("PD7").connectOutput(red); // install the new AT86RF230 radio. Actually an AT86RF231. AT86RF231Radio radio = new AT86RF231Radio(mcu, MAIN_HZ * 2); // mcu.getPin("PB7").connectOutput(radio.SCLK_pin); mcu.getPin(3).connectOutput(radio.SCLK_pin); //PB7 mcu.getPin(1).connectOutput(radio.MOSI_pin); //PB5 mcu.getPin(2).connectInput(radio.MISO_pin); //PB6 mcu.getPin(41).connectOutput(radio.RSTN_pin); //PB1 mcu.getPin(43).connectOutput(radio.SLPTR_pin);//PB3 mcu.getPin(44).connectOutput(radio.CS_pin); //PB4 SPI spi = (SPI) ((AtmelMicrocontroller) mcu).getDevice("spi"); SPIDevice spi2 = (SPIDevice) ((AtmelMicrocontroller) mcu).getDevice("usart1"); spi.connect(radio.spiInterface); addDevice("radio", radio); radio.RF231_interrupt = mcu.getProperties().getInterrupt("TIMER1 CAPT"); TWI twi = (TWI) ((AtmelMicrocontroller) mcu).getDevice("twi"); BMP085 pressure = new BMP085(); twi.connect(pressure); addDevice("bmp085", pressure); L3G4200D gyroscope = new L3G4200D(); twi.connect(gyroscope); addDevice("l3g4200d", gyroscope); LCX138 decoder = new LCX138(); mcu.getPin(32).connectOutput(decoder.A0); mcu.getPin(31).connectOutput(decoder.A1); mcu.getPin(30).connectOutput(decoder.A2); decoder.E1.write(false); decoder.E2.write(false); decoder.E3.write(true); addDevice("lcx138", decoder); AT45DB flash = new AT45DB(); flash.connectCS(decoder.O1); spi2.connect(flash); addDevice("at45db", flash); ADXL345 accelerometer = new ADXL345(sim); accelerometer.connectCS(decoder.O2); spi2.connect(accelerometer); addDevice("adxl345", accelerometer); Button button = new Button(); mcu.getPin(42).connectInput(button.output); addDevice("button", button); } }
[inga] Correct LEDs for INGA platfrom The INGA platform has exactly two controller-driven LEDs: A green one and an orange one.
src/avrora/sim/platform/Inga.java
[inga] Correct LEDs for INGA platfrom
<ide><path>rc/avrora/sim/platform/Inga.java <ide> * the external (off-chip) devices to the platform. <ide> */ <ide> private void addDevices() { <del> LED red = new LED(sim, Terminal.COLOR_RED, "Red"); <ide> LED green = new LED(sim, Terminal.COLOR_GREEN, "Green"); <del> LED blue = new LED(sim, Terminal.COLOR_BLUE, "Blue"); <add> LED orange = new LED(sim, Terminal.COLOR_YELLOW, "Orange"); <ide> <ide> <del> ledGroup = new LED.LEDGroup(sim, new LED[]{red, green, blue}); <add> ledGroup = new LED.LEDGroup(sim, new LED[]{green, orange}); <ide> addDevice("leds", ledGroup); <ide> <ide> //AtmelMicrocontroller amcu = (AtmelMicrocontroller)mcu; <del> mcu.getPin("PD5").connectOutput(blue); <del> mcu.getPin("PD6").connectOutput(green); <del> mcu.getPin("PD7").connectOutput(red); <add> mcu.getPin("PD5").connectOutput(green); <add> mcu.getPin("PD7").connectOutput(orange); <ide> <ide> // install the new AT86RF230 radio. Actually an AT86RF231. <ide> AT86RF231Radio radio = new AT86RF231Radio(mcu, MAIN_HZ * 2);
Java
mit
9b0efdc81dbcee0dcabb29758b9e4c7b821ff28f
0
douggie/XChange
package org.knowm.xchange.bithumb; import org.apache.commons.lang3.StringUtils; import org.knowm.xchange.bithumb.dto.account.BithumbAccount; import org.knowm.xchange.bithumb.dto.account.BithumbBalance; import org.knowm.xchange.bithumb.dto.account.BithumbOrder; import org.knowm.xchange.bithumb.dto.account.BithumbTransaction; import org.knowm.xchange.bithumb.dto.marketdata.*; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.Wallet; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; public final class BithumbAdapters { /** private Constructor */ private BithumbAdapters() {} public static OrderBook adaptOrderBook(BithumbOrderbook orderbook) { final CurrencyPair currencyPair = new CurrencyPair(orderbook.getOrderCurrency(), orderbook.getPaymentCurrency()); return new OrderBook( new Date(orderbook.getTimestamp()), createOrder(currencyPair, orderbook.getAsks(), Order.OrderType.ASK), createOrder(currencyPair, orderbook.getBids(), Order.OrderType.BID)); } private static List<LimitOrder> createOrder( CurrencyPair currencyPair, List<BithumbOrderbookEntry> orders, Order.OrderType orderType) { return orders.stream() .map(order -> createOrder(currencyPair, orderType, order.getQuantity(), order.getPrice())) .collect(Collectors.toList()); } private static LimitOrder createOrder( CurrencyPair currencyPair, Order.OrderType orderType, BigDecimal originalAmount, BigDecimal limitPrice) { return new LimitOrder(orderType, originalAmount, currencyPair, "", null, limitPrice); } public static AccountInfo adaptAccountInfo(BithumbAccount account, BithumbBalance balance) { List<Balance> balances = new ArrayList<>(); balances.add( new Balance( Currency.KRW, balance.getTotalKrw(), balance.getAvailableKrw(), balance.getInUseKrw())); for (String currency : balance.getCurrencies()) { final Balance xchangeBalance = new Balance( Currency.getInstance(currency), balance.getTotal(currency), balance.getAvailable(currency), balance.getFrozen(currency)); balances.add(xchangeBalance); } return new AccountInfo(null, account.getTradeFee(), Wallet.Builder.from(balances).build()); } public static Ticker adaptTicker(BithumbTicker bithumbTicker, CurrencyPair currencyPair) { return new Ticker.Builder() .currencyPair(currencyPair) .ask(bithumbTicker.getSellPrice()) .bid(bithumbTicker.getBuyPrice()) .high(bithumbTicker.getMaxPrice()) .low(bithumbTicker.getMinPrice()) .last(bithumbTicker.getClosingPrice()) .open(bithumbTicker.getOpeningPrice()) .vwap(bithumbTicker.getAveragePrice()) .volume(bithumbTicker.getUnitsTraded()) .timestamp(new Date(bithumbTicker.getDate())) .build(); } public static List<Ticker> adaptTickers(BithumbTickersReturn bithumbTickers) { return bithumbTickers.getTickers().entrySet().stream() .map( tickerEntry -> { final CurrencyPair currencyPair = new CurrencyPair(tickerEntry.getKey(), Currency.KRW.getCurrencyCode()); return adaptTicker(tickerEntry.getValue(), currencyPair); }) .collect(Collectors.toList()); } public static Trades adaptTrades( List<BithumbTransactionHistory> bithumbTrades, CurrencyPair currencyPair) { final List<Trade> trades = bithumbTrades.stream() .map(trade -> adaptTrade(trade, currencyPair)) .collect(Collectors.toList()); return new Trades(trades); } public static Trade adaptTrade(BithumbTransactionHistory trade, CurrencyPair currencyPair) { return new Trade.Builder() .currencyPair(currencyPair) .id(String.valueOf(trade.getContNo())) .originalAmount(trade.getUnitsTraded()) .price(trade.getPrice()) .type(adaptOrderType(trade.getType())) .timestamp(trade.getTimestamp()) .build(); } private static Order.OrderType adaptOrderType(OrderType orderType) { return orderType == OrderType.bid ? Order.OrderType.BID : Order.OrderType.ASK; } public static OpenOrders adaptOrders(List<BithumbOrder> bithumbOrders) { final List<LimitOrder> orders = bithumbOrders.stream() .map(BithumbAdapters::adaptOrder) .collect(Collectors.toList()); return new OpenOrders(orders); } public static LimitOrder adaptOrder(BithumbOrder order) { final CurrencyPair currencyPair = new CurrencyPair(order.getOrderCurrency(), order.getPaymentCurrency()); final Order.OrderType orderType = adaptOrderType(order.getType()); Order.OrderStatus status = Order.OrderStatus.UNKNOWN; if (order.getUnitsRemaining().compareTo(order.getUnits()) == 0) status = Order.OrderStatus.NEW; else if (order.getUnitsRemaining().compareTo(BigDecimal.ZERO) == 0) status = Order.OrderStatus.FILLED; else status = Order.OrderStatus.PARTIALLY_FILLED; return new LimitOrder.Builder(orderType, currencyPair) .id(String.valueOf(order.getOrderId())) .limitPrice(order.getPrice()) .originalAmount(order.getUnits()) .remainingAmount(order.getUnitsRemaining()) .orderStatus(status) .timestamp(new Date(order.getOrderDate() / 1000L)) .build(); } public static UserTrades adaptUserTrades( List<BithumbTransaction> transactions, CurrencyPair currencyPair) { final List<UserTrade> userTrades = transactions.stream() .filter(BithumbTransaction::isBuyOrSell) .map(transaction -> adaptUserTrade(transaction, currencyPair)) .collect(Collectors.toList()); return new UserTrades(userTrades, Trades.TradeSortType.SortByTimestamp); } private static UserTrade adaptUserTrade( BithumbTransaction bithumbTransaction, CurrencyPair currencyPair) { final String units = StringUtils.remove(bithumbTransaction.getUnits(), ' '); return new UserTrade.Builder() .id(Long.toString(bithumbTransaction.getTransferDate())) .currencyPair(currencyPair) .originalAmount(new BigDecimal(units).abs()) .type(adaptTransactionSearch(bithumbTransaction.getSearch())) .feeAmount(bithumbTransaction.getFee()) .feeCurrency(currencyPair.counter) .price(bithumbTransaction.getPrice()) .timestamp(new Date(bithumbTransaction.getTransferDate() / 1000L)) .build(); } private static Order.OrderType adaptTransactionSearch(String search) { switch (search) { case BithumbTransaction.SEARCH_BUY: return Order.OrderType.BID; case BithumbTransaction.SEARCH_SELL: return Order.OrderType.ASK; default: return null; } } public enum OrderType { bid, ask } }
xchange-bithumb/src/main/java/org/knowm/xchange/bithumb/BithumbAdapters.java
package org.knowm.xchange.bithumb; import org.apache.commons.lang3.StringUtils; import org.knowm.xchange.bithumb.dto.account.BithumbAccount; import org.knowm.xchange.bithumb.dto.account.BithumbBalance; import org.knowm.xchange.bithumb.dto.account.BithumbOrder; import org.knowm.xchange.bithumb.dto.account.BithumbTransaction; import org.knowm.xchange.bithumb.dto.marketdata.*; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.Wallet; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; public final class BithumbAdapters { /** private Constructor */ private BithumbAdapters() {} public static OrderBook adaptOrderBook(BithumbOrderbook orderbook) { final CurrencyPair currencyPair = new CurrencyPair(orderbook.getOrderCurrency(), orderbook.getPaymentCurrency()); return new OrderBook( new Date(orderbook.getTimestamp()), createOrder(currencyPair, orderbook.getAsks(), Order.OrderType.ASK), createOrder(currencyPair, orderbook.getBids(), Order.OrderType.BID)); } private static List<LimitOrder> createOrder( CurrencyPair currencyPair, List<BithumbOrderbookEntry> orders, Order.OrderType orderType) { return orders.stream() .map(order -> createOrder(currencyPair, orderType, order.getQuantity(), order.getPrice())) .collect(Collectors.toList()); } private static LimitOrder createOrder( CurrencyPair currencyPair, Order.OrderType orderType, BigDecimal originalAmount, BigDecimal limitPrice) { return new LimitOrder(orderType, originalAmount, currencyPair, "", null, limitPrice); } public static AccountInfo adaptAccountInfo(BithumbAccount account, BithumbBalance balance) { List<Balance> balances = new ArrayList<>(); balances.add( new Balance( Currency.KRW, balance.getTotalKrw(), balance.getAvailableKrw(), balance.getInUseKrw())); for (String currency : balance.getCurrencies()) { final Balance xchangeBalance = new Balance( Currency.getInstance(currency), balance.getTotal(currency), balance.getAvailable(currency), balance.getFrozen(currency)); balances.add(xchangeBalance); } return new AccountInfo(null, account.getTradeFee(), Wallet.Builder.from(balances).build()); } public static Ticker adaptTicker(BithumbTicker bithumbTicker, CurrencyPair currencyPair) { return new Ticker.Builder() .currencyPair(currencyPair) .ask(bithumbTicker.getSellPrice()) .bid(bithumbTicker.getBuyPrice()) .high(bithumbTicker.getMaxPrice()) .low(bithumbTicker.getMinPrice()) .last(bithumbTicker.getClosingPrice()) .open(bithumbTicker.getOpeningPrice()) .vwap(bithumbTicker.getAveragePrice()) .volume(bithumbTicker.getUnitsTraded()) .timestamp(new Date(bithumbTicker.getDate())) .build(); } public static List<Ticker> adaptTickers(BithumbTickersReturn bithumbTickers) { return bithumbTickers.getTickers().entrySet().stream() .map( tickerEntry -> { final CurrencyPair currencyPair = new CurrencyPair(tickerEntry.getKey(), Currency.KRW.getCurrencyCode()); return adaptTicker(tickerEntry.getValue(), currencyPair); }) .collect(Collectors.toList()); } public static Trades adaptTrades( List<BithumbTransactionHistory> bithumbTrades, CurrencyPair currencyPair) { final List<Trade> trades = bithumbTrades.stream() .map(trade -> adaptTrade(trade, currencyPair)) .collect(Collectors.toList()); return new Trades(trades); } public static Trade adaptTrade(BithumbTransactionHistory trade, CurrencyPair currencyPair) { return new Trade.Builder() .currencyPair(currencyPair) .id(String.valueOf(trade.getContNo())) .originalAmount(trade.getUnitsTraded()) .price(trade.getPrice()) .type(adaptOrderType(trade.getType())) .timestamp(trade.getTimestamp()) .build(); } private static Order.OrderType adaptOrderType(OrderType orderType) { return orderType == OrderType.bid ? Order.OrderType.BID : Order.OrderType.ASK; } public static OpenOrders adaptOrders(List<BithumbOrder> bithumbOrders) { final List<LimitOrder> orders = bithumbOrders.stream() .map(BithumbAdapters::adaptOrder) .peek(order -> {}) .collect(Collectors.toList()); return new OpenOrders(orders); } public static LimitOrder adaptOrder(BithumbOrder order) { final CurrencyPair currencyPair = new CurrencyPair(order.getOrderCurrency(), order.getPaymentCurrency()); final Order.OrderType orderType = adaptOrderType(order.getType()); Order.OrderStatus status = Order.OrderStatus.UNKNOWN; if (order.getUnitsRemaining().compareTo(order.getUnits()) == 0) status = Order.OrderStatus.NEW; else if (order.getUnitsRemaining().compareTo(BigDecimal.ZERO) == 0) status = Order.OrderStatus.FILLED; else status = Order.OrderStatus.PARTIALLY_FILLED; return new LimitOrder.Builder(orderType, currencyPair) .id(String.valueOf(order.getOrderId())) .limitPrice(order.getPrice()) .originalAmount(order.getUnits()) .remainingAmount(order.getUnitsRemaining()) .orderStatus(status) .timestamp(new Date(order.getOrderDate() / 1000L)) .build(); } public static UserTrades adaptUserTrades( List<BithumbTransaction> transactions, CurrencyPair currencyPair) { final List<UserTrade> userTrades = transactions.stream() .filter(BithumbTransaction::isBuyOrSell) .map(transaction -> adaptUserTrade(transaction, currencyPair)) .collect(Collectors.toList()); return new UserTrades(userTrades, Trades.TradeSortType.SortByTimestamp); } private static UserTrade adaptUserTrade( BithumbTransaction bithumbTransaction, CurrencyPair currencyPair) { final String units = StringUtils.remove(bithumbTransaction.getUnits(), ' '); return new UserTrade.Builder() .id(Long.toString(bithumbTransaction.getTransferDate())) .currencyPair(currencyPair) .originalAmount(new BigDecimal(units).abs()) .type(adaptTransactionSearch(bithumbTransaction.getSearch())) .feeAmount(bithumbTransaction.getFee()) .feeCurrency(currencyPair.counter) .price(bithumbTransaction.getPrice()) .timestamp(new Date(bithumbTransaction.getTransferDate() / 1000L)) .build(); } private static Order.OrderType adaptTransactionSearch(String search) { switch (search) { case BithumbTransaction.SEARCH_BUY: return Order.OrderType.BID; case BithumbTransaction.SEARCH_SELL: return Order.OrderType.ASK; default: return null; } } public enum OrderType { bid, ask } }
Bithumb API Changes Fixes #2 - cleanup
xchange-bithumb/src/main/java/org/knowm/xchange/bithumb/BithumbAdapters.java
Bithumb API Changes Fixes #2 - cleanup
<ide><path>change-bithumb/src/main/java/org/knowm/xchange/bithumb/BithumbAdapters.java <ide> final List<LimitOrder> orders = <ide> bithumbOrders.stream() <ide> .map(BithumbAdapters::adaptOrder) <del> .peek(order -> {}) <ide> .collect(Collectors.toList()); <ide> return new OpenOrders(orders); <ide> }
Java
apache-2.0
0d41a2cfde9f885500638191340c5360ab1cf932
0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
RobotControl/src/de/naoth/rc/componentsFx/CheckableTreeCell.java
package de.naoth.rc.componentsFx; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.scene.control.CheckBox; import javafx.scene.control.CheckBoxTreeItem; import javafx.scene.control.Tooltip; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.util.Callback; /** * @author Philipp Strobel <[email protected]> * @param <T> */ public class CheckableTreeCell<T extends Object> extends TreeCell<T> { private final CheckBox checkBox; private ObservableValue<Boolean> booleanProperty; private BooleanProperty indeterminateProperty; // --- selected state callback property private ObjectProperty<Callback<TreeItem<T>, ObservableValue<Boolean>>> selectedStateCallback = new SimpleObjectProperty<>(this, "selectedStateCallback"); public CheckableTreeCell() { this.getStyleClass().add("check-box-tree-cell"); selectedStateCallback.set(item -> { if (item instanceof CheckBoxTreeItem<?>) { return ((CheckBoxTreeItem<?>)item).selectedProperty(); } return null; }); this.checkBox = new CheckBox(); this.checkBox.setAllowIndeterminate(false); // by default the graphic is null until the cell stops being empty setGraphic(null); } /** * Returns the {@link Callback} that is bound to by the CheckBox shown on screen. * @return */ public final Callback<TreeItem<T>, ObservableValue<Boolean>> getSelectedStateCallback() { return selectedStateCallbackProperty().get(); } /** * Property representing the {@link Callback} that is bound to by the * CheckBox shown on screen. * @return */ public final ObjectProperty<Callback<TreeItem<T>, ObservableValue<Boolean>>> selectedStateCallbackProperty() { return selectedStateCallback; } @Override public void updateItem(T item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { TreeItem<T> treeItem = getTreeItem(); // update the node content setText(String.valueOf(treeItem.getValue())); checkBox.setGraphic(treeItem == null ? null : treeItem.getGraphic()); setGraphic(checkBox); checkBox.setDisable(!getTreeItem().isLeaf()); // install tooltip if we have one if (treeItem instanceof TreeNode) { String tooltip = ((TreeNode<T>) treeItem).getTooltip(); if (tooltip != null) { setTooltip(new Tooltip(tooltip)); } } // uninstall bindings if (booleanProperty != null) { checkBox.selectedProperty().unbindBidirectional((BooleanProperty)booleanProperty); } if (indeterminateProperty != null) { checkBox.indeterminateProperty().unbindBidirectional(indeterminateProperty); } // install new bindings. // We special case things when the TreeItem is a CheckBoxTreeItem if (treeItem instanceof CheckBoxTreeItem) { CheckBoxTreeItem<String> cbti = (CheckBoxTreeItem<String>) treeItem; booleanProperty = cbti.selectedProperty(); checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty); indeterminateProperty = cbti.indeterminateProperty(); checkBox.indeterminateProperty().bindBidirectional(indeterminateProperty); } else { Callback<TreeItem<T>, ObservableValue<Boolean>> callback = getSelectedStateCallback(); if (callback == null) { throw new NullPointerException( "The CheckBoxTreeCell selectedStateCallbackProperty can not be null"); } booleanProperty = callback.call(treeItem); if (booleanProperty != null) { checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty); } } } } // updateItem() }
removed the old tree cell
RobotControl/src/de/naoth/rc/componentsFx/CheckableTreeCell.java
removed the old tree cell
<ide><path>obotControl/src/de/naoth/rc/componentsFx/CheckableTreeCell.java <del>package de.naoth.rc.componentsFx; <del> <del>import javafx.beans.property.BooleanProperty; <del>import javafx.beans.property.ObjectProperty; <del>import javafx.beans.property.SimpleObjectProperty; <del>import javafx.beans.value.ObservableValue; <del>import javafx.scene.control.CheckBox; <del>import javafx.scene.control.CheckBoxTreeItem; <del>import javafx.scene.control.Tooltip; <del>import javafx.scene.control.TreeCell; <del>import javafx.scene.control.TreeItem; <del>import javafx.util.Callback; <del> <del>/** <del> * @author Philipp Strobel <[email protected]> <del> * @param <T> <del> */ <del>public class CheckableTreeCell<T extends Object> extends TreeCell<T> <del>{ <del> private final CheckBox checkBox; <del> <del> private ObservableValue<Boolean> booleanProperty; <del> <del> private BooleanProperty indeterminateProperty; <del> <del> // --- selected state callback property <del> private ObjectProperty<Callback<TreeItem<T>, ObservableValue<Boolean>>> <del> selectedStateCallback = new SimpleObjectProperty<>(this, "selectedStateCallback"); <del> <del> public CheckableTreeCell() { <del> this.getStyleClass().add("check-box-tree-cell"); <del> selectedStateCallback.set(item -> { <del> if (item instanceof CheckBoxTreeItem<?>) { <del> return ((CheckBoxTreeItem<?>)item).selectedProperty(); <del> } <del> return null; <del> }); <del> <del> this.checkBox = new CheckBox(); <del> this.checkBox.setAllowIndeterminate(false); <del> <del> // by default the graphic is null until the cell stops being empty <del> setGraphic(null); <del> } <del> <del> /** <del> * Returns the {@link Callback} that is bound to by the CheckBox shown on screen. <del> * @return <del> */ <del> public final Callback<TreeItem<T>, ObservableValue<Boolean>> getSelectedStateCallback() { <del> return selectedStateCallbackProperty().get(); <del> } <del> <del> /** <del> * Property representing the {@link Callback} that is bound to by the <del> * CheckBox shown on screen. <del> * @return <del> */ <del> public final ObjectProperty<Callback<TreeItem<T>, ObservableValue<Boolean>>> selectedStateCallbackProperty() { <del> return selectedStateCallback; <del> } <del> <del> @Override <del> public void updateItem(T item, boolean empty) { <del> super.updateItem(item, empty); <del> <del> if (empty) { <del> setText(null); <del> setGraphic(null); <del> } else { <del> TreeItem<T> treeItem = getTreeItem(); <del> <del> // update the node content <del> setText(String.valueOf(treeItem.getValue())); <del> checkBox.setGraphic(treeItem == null ? null : treeItem.getGraphic()); <del> <del> setGraphic(checkBox); <del> <del> checkBox.setDisable(!getTreeItem().isLeaf()); <del> <del> // install tooltip if we have one <del> if (treeItem instanceof TreeNode) { <del> String tooltip = ((TreeNode<T>) treeItem).getTooltip(); <del> if (tooltip != null) { <del> setTooltip(new Tooltip(tooltip)); <del> } <del> } <del> <del> // uninstall bindings <del> if (booleanProperty != null) { <del> checkBox.selectedProperty().unbindBidirectional((BooleanProperty)booleanProperty); <del> } <del> if (indeterminateProperty != null) { <del> checkBox.indeterminateProperty().unbindBidirectional(indeterminateProperty); <del> } <del> <del> // install new bindings. <del> // We special case things when the TreeItem is a CheckBoxTreeItem <del> if (treeItem instanceof CheckBoxTreeItem) { <del> CheckBoxTreeItem<String> cbti = (CheckBoxTreeItem<String>) treeItem; <del> booleanProperty = cbti.selectedProperty(); <del> checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty); <del> <del> indeterminateProperty = cbti.indeterminateProperty(); <del> checkBox.indeterminateProperty().bindBidirectional(indeterminateProperty); <del> } else { <del> Callback<TreeItem<T>, ObservableValue<Boolean>> callback = getSelectedStateCallback(); <del> if (callback == null) { <del> throw new NullPointerException( <del> "The CheckBoxTreeCell selectedStateCallbackProperty can not be null"); <del> } <del> <del> booleanProperty = callback.call(treeItem); <del> if (booleanProperty != null) { <del> checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty); <del> } <del> } <del> } <del> } // updateItem() <del>}
Java
mit
55886b9869cb682b5c86be53110e770cc8cad577
0
rostykerei/cci
package nl.rostykerei.cci.ch04.q10; import nl.rostykerei.cci.ch04.q02.MinimalTreeImpl; import nl.rostykerei.cci.common.AbstractFactoryTest; import nl.rostykerei.cci.datastructure.BinaryTreeNode; import nl.rostykerei.cci.datastructure.impl.BinaryTreeNodeImpl; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public abstract class CheckSubtreeAbstractTest extends AbstractFactoryTest<CheckSubtree<Integer>> { @Test public void checkTrue() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(6), 7), new BinaryTreeNodeImpl<>(8), 9), new BinaryTreeNodeImpl<>(20), 10), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(6), 7); assertTrue(testInstance.isSubtree(tree1, tree2)); } @Test public void checkTrue2() throws Exception { BinaryTreeNode<Integer> tree = new MinimalTreeImpl<Integer>().buildBST( new Integer[] {1, 2, 3, 4, 5, 6, 7} ); assertTrue(testInstance.isSubtree(tree, new BinaryTreeNodeImpl<>(1) )); assertTrue(testInstance.isSubtree(tree, new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(3), 2) )); } @Test public void checkFalse1() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(7), 6), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(11), 6); assertFalse(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse2() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(7), 6), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), null, 6); assertFalse(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse3() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( null, new BinaryTreeNodeImpl<>(7), 6), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), null, 6); assertFalse(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse4() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(75), new BinaryTreeNodeImpl<>(6), 7), new BinaryTreeNodeImpl<>(8), 9), new BinaryTreeNodeImpl<>(20), 10), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(6), 7); assertFalse(testInstance.isSubtree(tree1, tree2)); } }
src/test/java/nl/rostykerei/cci/ch04/q10/CheckSubtreeAbstractTest.java
package nl.rostykerei.cci.ch04.q10; import nl.rostykerei.cci.common.AbstractFactoryTest; import nl.rostykerei.cci.datastructure.BinaryTreeNode; import nl.rostykerei.cci.datastructure.impl.BinaryTreeNodeImpl; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public abstract class CheckSubtreeAbstractTest extends AbstractFactoryTest<CheckSubtree<Integer>> { @Test public void checkTrue() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(6), 7), new BinaryTreeNodeImpl<>(8), 9), new BinaryTreeNodeImpl<>(20), 10), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(6), 7); assertTrue(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse1() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(7), 6), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(11), 6); assertFalse(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse2() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(7), 6), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), null, 6); assertFalse(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse3() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( null, new BinaryTreeNodeImpl<>(7), 6), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), null, 6); assertFalse(testInstance.isSubtree(tree1, tree2)); } @Test public void checkFalse4() throws Exception { BinaryTreeNode<Integer> tree1 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(1), new BinaryTreeNodeImpl<>(2), 3), new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(75), new BinaryTreeNodeImpl<>(6), 7), new BinaryTreeNodeImpl<>(8), 9), new BinaryTreeNodeImpl<>(20), 10), 4); BinaryTreeNode<Integer> tree2 = new BinaryTreeNodeImpl<>( new BinaryTreeNodeImpl<>(5), new BinaryTreeNodeImpl<>(6), 7); assertFalse(testInstance.isSubtree(tree1, tree2)); } }
q4.10 new test
src/test/java/nl/rostykerei/cci/ch04/q10/CheckSubtreeAbstractTest.java
q4.10 new test
<ide><path>rc/test/java/nl/rostykerei/cci/ch04/q10/CheckSubtreeAbstractTest.java <ide> package nl.rostykerei.cci.ch04.q10; <ide> <add>import nl.rostykerei.cci.ch04.q02.MinimalTreeImpl; <ide> import nl.rostykerei.cci.common.AbstractFactoryTest; <ide> import nl.rostykerei.cci.datastructure.BinaryTreeNode; <ide> import nl.rostykerei.cci.datastructure.impl.BinaryTreeNodeImpl; <ide> 7); <ide> <ide> assertTrue(testInstance.isSubtree(tree1, tree2)); <add> } <add> <add> <add> @Test <add> public void checkTrue2() throws Exception { <add> BinaryTreeNode<Integer> tree = new MinimalTreeImpl<Integer>().buildBST( <add> new Integer[] {1, 2, 3, 4, 5, 6, 7} <add> ); <add> <add> assertTrue(testInstance.isSubtree(tree, <add> new BinaryTreeNodeImpl<>(1) <add> )); <add> <add> assertTrue(testInstance.isSubtree(tree, <add> new BinaryTreeNodeImpl<>( <add> new BinaryTreeNodeImpl<>(1), <add> new BinaryTreeNodeImpl<>(3), <add> 2) <add> )); <ide> } <ide> <ide> @Test
Java
apache-2.0
cd8c70b079425cfb099786d5e58aecae38486b00
0
glawson6/box-java-sdk,itsmanishagarwal/box-java-sdk,TLuthra/box-java-sdk,sarattall/box-java-sdk,manywho/box-java-sdk,bgoldman/box-java-sdk,codyebberson/box-java-sdk,box/box-java-sdk,gcurtis/box-java-sdk
package com.box.sdk; import java.net.URL; import java.util.Iterator; import com.eclipsesource.json.JsonObject; /** * Represents a set of Box users. */ public class BoxGroup extends BoxCollaborator { private static final URLTemplate GROUPS_URL_TEMPLATE = new URLTemplate("groups"); private static final URLTemplate GROUP_URL_TEMPLATE = new URLTemplate("groups/%s"); /** * Constructs a BoxGroup for a group with a given ID. * @param api the API connection to be used by the group. * @param id the ID of the group. */ public BoxGroup(BoxAPIConnection api, String id) { super(api, id); } /** * Creates a new group with a specified name. * @param api the API connection to be used by the group. * @param name the name of the new group. * @return info about the created group. */ public static BoxGroup.Info createGroup(BoxAPIConnection api, String name) { JsonObject requestJSON = new JsonObject(); requestJSON.add("name", name); URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxGroup group = new BoxGroup(api, responseJSON.get("id").asString()); return group.new Info(responseJSON); } /** * Gets an iterable of all the groups that the current user is a member of. * @param api the API connection to be used when retrieving the groups. * @return an iterable containing info about all the groups. */ public static Iterable<BoxGroup.Info> getAllGroups(final BoxAPIConnection api) { return new Iterable<BoxGroup.Info>() { public Iterator<BoxGroup.Info> iterator() { URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); return new BoxGroupIterator(api, url); } }; } /** * Deletes this group. */ public void delete() { URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); BoxAPIResponse response = request.send(); response.disconnect(); } /** * Contains information about a BoxGroup. */ public class Info extends BoxCollaborator.Info { /** * Constructs an empty Info object. */ public Info() { super(); } /** * Constructs an Info object by parsing information from a JSON string. * @param json the JSON string to parse. */ public Info(String json) { super(json); } /** * Constructs an Info object using an already parsed JSON object. * @param jsonObject the parsed JSON object. */ Info(JsonObject jsonObject) { super(jsonObject); } @Override public BoxGroup getResource() { return BoxGroup.this; } } }
src/main/java/com/box/sdk/BoxGroup.java
package com.box.sdk; import java.net.URL; import java.util.Iterator; import com.eclipsesource.json.JsonObject; public class BoxGroup extends BoxCollaborator { private static final URLTemplate GROUPS_URL_TEMPLATE = new URLTemplate("groups"); private static final URLTemplate GROUP_URL_TEMPLATE = new URLTemplate("groups/%s"); public BoxGroup(BoxAPIConnection api, String id) { super(api, id); } public static BoxGroup.Info createGroup(BoxAPIConnection api, String name) { JsonObject requestJSON = new JsonObject(); requestJSON.add("name", name); URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxGroup group = new BoxGroup(api, responseJSON.get("id").asString()); return group.new Info(responseJSON); } public static Iterable<BoxGroup.Info> getAllGroups(final BoxAPIConnection api) { return new Iterable<BoxGroup.Info>() { public Iterator<BoxGroup.Info> iterator() { URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); return new BoxGroupIterator(api, url); } }; } public void delete() { URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); BoxAPIResponse response = request.send(); response.disconnect(); } public class Info extends BoxCollaborator.Info { /** * Constructs an empty Info object. */ public Info() { super(); } /** * Constructs an Info object by parsing information from a JSON string. * @param json the JSON string to parse. */ public Info(String json) { super(json); } /** * Constructs an Info object using an already parsed JSON object. * @param jsonObject the parsed JSON object. */ Info(JsonObject jsonObject) { super(jsonObject); } @Override public BoxGroup getResource() { return BoxGroup.this; } } }
Add javadocs to BoxGroup
src/main/java/com/box/sdk/BoxGroup.java
Add javadocs to BoxGroup
<ide><path>rc/main/java/com/box/sdk/BoxGroup.java <ide> <ide> import com.eclipsesource.json.JsonObject; <ide> <add>/** <add> * Represents a set of Box users. <add> */ <ide> public class BoxGroup extends BoxCollaborator { <ide> private static final URLTemplate GROUPS_URL_TEMPLATE = new URLTemplate("groups"); <ide> private static final URLTemplate GROUP_URL_TEMPLATE = new URLTemplate("groups/%s"); <ide> <add> /** <add> * Constructs a BoxGroup for a group with a given ID. <add> * @param api the API connection to be used by the group. <add> * @param id the ID of the group. <add> */ <ide> public BoxGroup(BoxAPIConnection api, String id) { <ide> super(api, id); <ide> } <ide> <add> /** <add> * Creates a new group with a specified name. <add> * @param api the API connection to be used by the group. <add> * @param name the name of the new group. <add> * @return info about the created group. <add> */ <ide> public static BoxGroup.Info createGroup(BoxAPIConnection api, String name) { <ide> JsonObject requestJSON = new JsonObject(); <ide> requestJSON.add("name", name); <ide> return group.new Info(responseJSON); <ide> } <ide> <add> /** <add> * Gets an iterable of all the groups that the current user is a member of. <add> * @param api the API connection to be used when retrieving the groups. <add> * @return an iterable containing info about all the groups. <add> */ <ide> public static Iterable<BoxGroup.Info> getAllGroups(final BoxAPIConnection api) { <ide> return new Iterable<BoxGroup.Info>() { <ide> public Iterator<BoxGroup.Info> iterator() { <ide> }; <ide> } <ide> <add> /** <add> * Deletes this group. <add> */ <ide> public void delete() { <ide> URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); <ide> BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); <ide> response.disconnect(); <ide> } <ide> <add> /** <add> * Contains information about a BoxGroup. <add> */ <ide> public class Info extends BoxCollaborator.Info { <ide> /** <ide> * Constructs an empty Info object.
Java
apache-2.0
7032a90fb8134ed093de83a29836fe94995973de
0
kensipe/logstash,triforkse/logstash-mesos,frankscholten/logstash,frankscholten/logstash,suppandi/logstash,suppandi/logstash,alex-glv/logstash,triforkse/logstash-mesos,kensipe/logstash,mesosphere/logstash,mesos/logstash,frankscholten/logstash,mesos/logstash,drewrobb/logstash,suppandi/logstash,mesosphere/logstash,kensipe/logstash,alex-glv/logstash,alex-glv/logstash,triforkse/logstash-mesos,mesosphere/logstash,drewrobb/logstash,frankscholten/logstash,suppandi/logstash,mesosphere/logstash,kensipe/logstash,alex-glv/logstash,drewrobb/logstash,triforkse/logstash-mesos,drewrobb/logstash
package org.apache.mesos.logstash.executor; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.mesos.logstash.executor.docker.ContainerizerClient; import org.apache.mesos.logstash.executor.docker.DockerLogSteamManager; import org.apache.mesos.logstash.executor.state.DockerInfoCache; import org.apache.mesos.logstash.executor.frameworks.FrameworkInfo; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Set; import static org.mockito.Mockito.*; public class ConfigManagerTest { private ConfigManager configManager; private ContainerizerClient client; private LogstashManager logstash; @Before public void s() { client = mock(ContainerizerClient.class); logstash = mock(LogstashManager.class); DockerLogSteamManager streamManager = mock(DockerLogSteamManager.class); configManager = new ConfigManager(client, logstash, streamManager, new DockerInfoCache()); } @Test public void onlyWritesConfigsForRunningContainers() { List<FrameworkInfo> frameworks = Lists.newArrayList(); frameworks.add(new FrameworkInfo("foo", "foo-config")); frameworks.add(new FrameworkInfo("bar", "bar-config")); frameworks.add(new FrameworkInfo("bas", "bas-config")); Set<String> containerIds = Sets.newHashSet("123", "456", "789", "012"); when(client.getRunningContainers()).thenReturn(containerIds); when(client.getImageNameOfContainer("123")).thenReturn("foo"); when(client.getImageNameOfContainer("456")).thenReturn("quux"); when(client.getImageNameOfContainer("789")).thenReturn("bas"); when(client.getImageNameOfContainer("012")).thenReturn("foo"); configManager.onConfigUpdated(LogType.DOCKER, frameworks.stream()); verify(logstash, times(1)).updateConfig(LogType.DOCKER, "# bas\nbas-config\n# foo\nfoo-config\n# foo\nfoo-config"); } }
executor/src/test/java/org/apache/mesos/logstash/executor/ConfigManagerTest.java
package org.apache.mesos.logstash.executor; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.mesos.logstash.executor.docker.ContainerizerClient; import org.apache.mesos.logstash.executor.docker.DockerLogSteamManager; import org.apache.mesos.logstash.executor.state.DockerInfoCache; import org.apache.mesos.logstash.executor.frameworks.FrameworkInfo; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Set; import static org.mockito.Mockito.*; public class ConfigManagerTest { private ConfigManager configManager; private ContainerizerClient client; private LogstashManager logstash; @Before public void s() { client = mock(ContainerizerClient.class); logstash = mock(LogstashManager.class); DockerLogSteamManager streamManager = mock(DockerLogSteamManager.class); configManager = new ConfigManager(client, logstash, streamManager, new DockerInfoCache()); } @Test public void onlyWritesConfigsForRunningContainers() { List<FrameworkInfo> frameworks = Lists.newArrayList(); frameworks.add(new FrameworkInfo("foo", "foo-config")); frameworks.add(new FrameworkInfo("bar", "bar-config")); frameworks.add(new FrameworkInfo("bas", "bas-config")); Set<String> containerIds = Sets.newHashSet("123", "456", "789", "012"); when(client.getRunningContainers()).thenReturn(containerIds); when(client.getImageNameOfContainer("123")).thenReturn("foo"); when(client.getImageNameOfContainer("456")).thenReturn("quux"); when(client.getImageNameOfContainer("789")).thenReturn("bas"); when(client.getImageNameOfContainer("012")).thenReturn("foo"); configManager.onConfigUpdated(LogType.DOCKER, frameworks.stream()); verify(logstash, times(1)).updateConfig(LogType.DOCKER, "bas-config\nfoo-config\nfoo-config"); } }
Fix broken tests
executor/src/test/java/org/apache/mesos/logstash/executor/ConfigManagerTest.java
Fix broken tests
<ide><path>xecutor/src/test/java/org/apache/mesos/logstash/executor/ConfigManagerTest.java <ide> <ide> configManager.onConfigUpdated(LogType.DOCKER, frameworks.stream()); <ide> <del> verify(logstash, times(1)).updateConfig(LogType.DOCKER, "bas-config\nfoo-config\nfoo-config"); <add> verify(logstash, times(1)).updateConfig(LogType.DOCKER, "# bas\nbas-config\n# foo\nfoo-config\n# foo\nfoo-config"); <ide> } <ide> <ide> }
Java
lgpl-2.1
98f28a4fd9414ce133a34c5da620e7062fdf5cd8
0
tomck/intermine,kimrutherford/intermine,kimrutherford/intermine,drhee/toxoMine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,JoeCarlson/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,drhee/toxoMine,elsiklab/intermine,justincc/intermine,JoeCarlson/intermine,tomck/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,tomck/intermine,justincc/intermine,joshkh/intermine,kimrutherford/intermine,tomck/intermine,drhee/toxoMine,kimrutherford/intermine,drhee/toxoMine,elsiklab/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,joshkh/intermine,joshkh/intermine,tomck/intermine,zebrafishmine/intermine,kimrutherford/intermine,justincc/intermine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,kimrutherford/intermine,JoeCarlson/intermine,elsiklab/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,joshkh/intermine,JoeCarlson/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,joshkh/intermine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine,elsiklab/intermine,zebrafishmine/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,tomck/intermine,JoeCarlson/intermine,zebrafishmine/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine
package org.intermine.metadata; /* * Copyright (C) 2002-2008 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.Set; import java.util.Stack; import java.util.TreeSet; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import org.intermine.model.InterMineObject; import org.intermine.modelproduction.MetadataManager; import org.intermine.util.TypeUtil; import org.intermine.util.XmlUtil; /** * Represents a named business model, makes available metadata for each class * within model. * * @author Richard Smith */ public class Model { private static Map<String, Model> models = new HashMap<String, Model>(); private final String modelName; private final URI nameSpace; private final Map<String, ClassDescriptor> cldMap = new LinkedHashMap<String, ClassDescriptor>(); private final Map<ClassDescriptor, Set<ClassDescriptor>> subMap = new LinkedHashMap<ClassDescriptor, Set<ClassDescriptor>>(); private final Map<Class, Set<ClassDescriptor>> classToClassDescriptorSet = new HashMap<Class, Set<ClassDescriptor>>(); private final Map<Class, Map<String, FieldDescriptor>> classToFieldDescriptorMap = new HashMap<Class, Map<String, FieldDescriptor>>(); private boolean generatedClassesAvailable = true; /** * Return a Model for specified model name (loading Model if necessary) * @param name the name of the model * @return the relevant metadata */ public static Model getInstanceByName(String name) { if (!models.containsKey(name)) { models.put(name, MetadataManager.loadModel(name)); } return models.get(name); } /** * Adds model to known models. * @param name the model name * @param model the model */ public static void addModel(String name, Model model) { models.put(name, model); } /** * Construct a Model with a name and set of ClassDescriptors. The model will be * set to this in each of the ClassDescriptors. NB This method should only be called * by members of the modelproduction package, eventually it may be replaced with * a static addModel method linked to getInstanceByName. * @param name name of model * @param nameSpace the nameSpace uri for this model * @param clds a Set of ClassDescriptors in the model * @throws MetaDataException if inconsistencies found in model * @throws URISyntaxException if nameSpace string is invalid */ public Model(String name, String nameSpace, Set<ClassDescriptor> clds) throws MetaDataException, URISyntaxException { if (name == null) { throw new NullPointerException("Model name cannot be null"); } if (name.equals("")) { throw new IllegalArgumentException("Model name cannot be empty"); } if (nameSpace == null) { throw new NullPointerException("Model nameSpace cannot be null"); } if (nameSpace.equals("")) { throw new IllegalArgumentException("Model nameSpace cannot be empty"); } if (clds == null) { throw new NullPointerException("Model ClassDescriptors list cannot be null"); } this.modelName = name; this.nameSpace = new URI(XmlUtil.correctNamespace(nameSpace)); LinkedHashSet<ClassDescriptor> orderedClds = new LinkedHashSet<ClassDescriptor>(clds); Set<ReferenceDescriptor> emptyRefs = Collections.emptySet(); Set<CollectionDescriptor> emptyCols = Collections.emptySet(); ClassDescriptor intermineObject = new ClassDescriptor( "org.intermine.model.InterMineObject", null, true, Collections.singleton(new AttributeDescriptor("id", "java.lang.Integer")), emptyRefs, emptyCols); orderedClds.add(intermineObject); // 1. Put all ClassDescriptors in model. for (ClassDescriptor cld : orderedClds) { cldMap.put(cld.getName(), cld); // create maps of ClassDescriptor to empty sets for subclasses and implementors subMap.put(cld, new LinkedHashSet<ClassDescriptor>()); } // 2. Now set model in each ClassDescriptor, this sets up superDescriptors // etc. Set ClassDescriptors and reverse refs in ReferenceDescriptors. for (ClassDescriptor cld : orderedClds) { cld.setModel(this); } for (ClassDescriptor cld : orderedClds) { // add this class to subMap sets for any interfaces and superclasses Set<ClassDescriptor> supers = cld.getSuperDescriptors(); for (ClassDescriptor iCld : supers) { Set<ClassDescriptor> subs = subMap.get(iCld); subs.add(cld); } } // 3. Now run setAllFieldDescriptors on everything for (ClassDescriptor cld : orderedClds) { cld.setAllFieldDescriptors(); } } /** * Return name of the model's package. * @return package name */ public String getPackageName() { return TypeUtil.packageName(((ClassDescriptor) cldMap.values().iterator().next()) .getName()); } /** * Get the ClassDescriptors for the direct subclasses of a class * @param cld the parent ClassDescriptor * @return the ClassDescriptors of its children */ public Set<ClassDescriptor> getDirectSubs(ClassDescriptor cld) { return subMap.get(cld); } /** * Get the ClassDescriptors for the all subclasses of a class * @param cld the parent ClassDescriptor * @return the ClassDescriptors of all decedents */ public Set<ClassDescriptor> getAllSubs(ClassDescriptor cld) { Set<ClassDescriptor> returnSubs = new TreeSet<ClassDescriptor>(); Set<ClassDescriptor> directSubs = getDirectSubs(cld); returnSubs.addAll(directSubs); for (ClassDescriptor sub : directSubs) { returnSubs.addAll(getAllSubs(sub)); } return returnSubs; } /** * Get a ClassDescriptor by name, null if no ClassDescriptor of given name in Model. * @param name unqualified or fully-qualified class name of ClassDescriptor requested * @return the requested ClassDescriptor */ public ClassDescriptor getClassDescriptorByName(String name) { ClassDescriptor cd = cldMap.get(name); if (cd == null) { return cldMap.get(getPackageName() + "." + name); } else { return cd; } } /** * Get all ClassDescriptors in this model. * @return a set of all ClassDescriptors in the model */ public Set<ClassDescriptor> getClassDescriptors() { return new LinkedHashSet<ClassDescriptor>(cldMap.values()); } /** * Return true if named ClassDescriptor is found in the model. * @param name named of ClassDescriptor search for * @return true if named descriptor found */ public boolean hasClassDescriptor(String name) { return cldMap.containsKey(name); } /** * Get a Set of fully qualified class names in this model (i.e. including * package name). * @return Set of fully qualified class names */ public Set<String> getClassNames() { return cldMap.keySet(); } /** * Get the name of this model - i.e. package name. * @return name of the model */ public String getName() { return modelName; } /** * Get the nameSpace URI of this model * @return nameSpace URI of the model */ public URI getNameSpace() { return nameSpace; } /** * {@inheritDoc} */ public boolean equals(Object obj) { if (obj instanceof Model) { Model model = (Model) obj; return modelName.equals(model.modelName) && nameSpace.equals(model.nameSpace) && cldMap.equals(model.cldMap); } return false; } /** * {@inheritDoc} */ public int hashCode() { return 3 * modelName.hashCode() + 5 * cldMap.hashCode(); } /** * {@inheritDoc} */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<model name=\"" + modelName + "\" namespace=\"" + nameSpace + "\">"); for (ClassDescriptor cld : getClassDescriptors()) { if (!"org.intermine.model.InterMineObject".equals(cld.getName())) { sb.append(cld.toString()); } } sb.append("</model>"); return sb.toString(); } /** * Takes a Class, and generates a Set of all ClassDescriptors that are the Class * or any of its parents. The Class may be a dynamic class - ie not in the model, although * at least one of its parents are in the model. * * @param c a Class * @return a Set of ClassDescriptor objects */ public Set<ClassDescriptor> getClassDescriptorsForClass(Class c) { synchronized (classToClassDescriptorSet) { Set<ClassDescriptor> retval = classToClassDescriptorSet.get(c); if (retval == null) { retval = new LinkedHashSet<ClassDescriptor>(); Stack<Class> todo = new Stack<Class>(); Set<Class> done = new HashSet<Class>(); todo.push(c); while (!todo.empty()) { Class toAdd = todo.pop(); if (!done.contains(toAdd)) { ClassDescriptor cld = getClassDescriptorByName(toAdd.getName()); if (cld != null) { retval.add(cld); } Class superClass = toAdd.getSuperclass(); if ((superClass != null) && (InterMineObject.class.isAssignableFrom(superClass))) { todo.push(superClass); } Class[] interfaces = toAdd.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (InterMineObject.class.isAssignableFrom(interfaces[i])) { todo.push(interfaces[i]); } } done.add(toAdd); } } classToClassDescriptorSet.put(c, retval); } return retval; } } /** * Takes a Class, and generates a Map of all FieldDescriptors that are the class fields * or any of its parents. The Class may be a dynamic class - ie not in the model, although * at least one of its parents are in the model. * * @param c a Class * @return a Map of FieldDescriptor objects */ public Map<String, FieldDescriptor> getFieldDescriptorsForClass(Class c) { synchronized (classToFieldDescriptorMap) { Map<String, FieldDescriptor> retval = classToFieldDescriptorMap.get(c); if (retval == null) { retval = new LinkedHashMap<String, FieldDescriptor>(); for (ClassDescriptor cld : getClassDescriptorsForClass(c)) { for (FieldDescriptor fd : cld.getFieldDescriptors()) { retval.put(fd.getName(), fd); } } classToFieldDescriptorMap.put(c, retval); } return retval; } } /** * Return the qualified name of the given unqualified class name. The className must be in the * given model or in the java.lang package or one of java.util.Date or java.math.BigDecimal. * @param className the name of the class * @return the fully qualified name of the class * @throws ClassNotFoundException if the class can't be found */ public String getQualifiedTypeName(String className) throws ClassNotFoundException { if (className.indexOf(".") != -1) { throw new IllegalArgumentException("Expected an unqualified class name: " + className); } if (TypeUtil.instantiate(className) != null) { // a primative type return className; } else { if ("InterMineObject".equals(className)) { return "org.intermine.model.InterMineObject"; } else { try { return Class.forName(getPackageName() + "." + className).getName(); } catch (ClassNotFoundException e) { // fall through and try java.lang } } if ("Date".equals(className)) { return Date.class.getName(); } if ("BigDecimal".equals(className)) { return BigDecimal.class.getName(); } return Class.forName("java.lang." + className).getName(); } } /** * @return true if generated classes are available * */ public boolean isGeneratedClassesAvailable() { return generatedClassesAvailable; } /** * Sets if generated classes are available. * @param available if generated class is available */ public void setGeneratedClassesAvailable(boolean available) { this.generatedClassesAvailable = available; } /** * @param className class name * @return true if class is defined else false */ public boolean isGeneratedClassAvailable(String className) { try { getQualifiedTypeName(className); return true; } catch (ClassNotFoundException ex) { return false; } } }
intermine/objectstore/main/src/org/intermine/metadata/Model.java
package org.intermine.metadata; /* * Copyright (C) 2002-2008 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.Set; import java.util.Stack; import java.util.TreeSet; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import org.intermine.model.InterMineObject; import org.intermine.modelproduction.MetadataManager; import org.intermine.util.TypeUtil; import org.intermine.util.XmlUtil; /** * Represents a named business model, makes available metadata for each class * within model. * * @author Richard Smith */ public class Model { private static Map<String, Model> models = new HashMap<String, Model>(); private final String modelName; private final URI nameSpace; private final Map<String, ClassDescriptor> cldMap = new LinkedHashMap<String, ClassDescriptor>(); private final Map<ClassDescriptor, Set<ClassDescriptor>> subMap = new LinkedHashMap<ClassDescriptor, Set<ClassDescriptor>>(); private final Map<Class, Set<ClassDescriptor>> classToClassDescriptorSet = new HashMap<Class, Set<ClassDescriptor>>(); private final Map<Class, Map<String, FieldDescriptor>> classToFieldDescriptorMap = new HashMap<Class, Map<String, FieldDescriptor>>(); /** * Return a Model for specified model name (loading Model if necessary) * @param name the name of the model * @return the relevant metadata */ public static Model getInstanceByName(String name) { if (!models.containsKey(name)) { models.put(name, MetadataManager.loadModel(name)); } return models.get(name); } /** * Adds model to known models. * @param name the model name * @param model the model */ public static void addModel(String name, Model model) { models.put(name, model); } /** * Construct a Model with a name and set of ClassDescriptors. The model will be * set to this in each of the ClassDescriptors. NB This method should only be called * by members of the modelproduction package, eventually it may be replaced with * a static addModel method linked to getInstanceByName. * @param name name of model * @param nameSpace the nameSpace uri for this model * @param clds a Set of ClassDescriptors in the model * @throws MetaDataException if inconsistencies found in model * @throws URISyntaxException if nameSpace string is invalid */ public Model(String name, String nameSpace, Set<ClassDescriptor> clds) throws MetaDataException, URISyntaxException { if (name == null) { throw new NullPointerException("Model name cannot be null"); } if (name.equals("")) { throw new IllegalArgumentException("Model name cannot be empty"); } if (nameSpace == null) { throw new NullPointerException("Model nameSpace cannot be null"); } if (nameSpace.equals("")) { throw new IllegalArgumentException("Model nameSpace cannot be empty"); } if (clds == null) { throw new NullPointerException("Model ClassDescriptors list cannot be null"); } this.modelName = name; this.nameSpace = new URI(XmlUtil.correctNamespace(nameSpace)); LinkedHashSet<ClassDescriptor> orderedClds = new LinkedHashSet<ClassDescriptor>(clds); Set<ReferenceDescriptor> emptyRefs = Collections.emptySet(); Set<CollectionDescriptor> emptyCols = Collections.emptySet(); ClassDescriptor intermineObject = new ClassDescriptor( "org.intermine.model.InterMineObject", null, true, Collections.singleton(new AttributeDescriptor("id", "java.lang.Integer")), emptyRefs, emptyCols); orderedClds.add(intermineObject); // 1. Put all ClassDescriptors in model. for (ClassDescriptor cld : orderedClds) { cldMap.put(cld.getName(), cld); // create maps of ClassDescriptor to empty sets for subclasses and implementors subMap.put(cld, new LinkedHashSet<ClassDescriptor>()); } // 2. Now set model in each ClassDescriptor, this sets up superDescriptors // etc. Set ClassDescriptors and reverse refs in ReferenceDescriptors. for (ClassDescriptor cld : orderedClds) { cld.setModel(this); } for (ClassDescriptor cld : orderedClds) { // add this class to subMap sets for any interfaces and superclasses Set<ClassDescriptor> supers = cld.getSuperDescriptors(); for (ClassDescriptor iCld : supers) { Set<ClassDescriptor> subs = subMap.get(iCld); subs.add(cld); } } // 3. Now run setAllFieldDescriptors on everything for (ClassDescriptor cld : orderedClds) { cld.setAllFieldDescriptors(); } } /** * Return name of the model's package. * @return package name */ public String getPackageName() { return TypeUtil.packageName(((ClassDescriptor) cldMap.values().iterator().next()) .getName()); } /** * Get the ClassDescriptors for the direct subclasses of a class * @param cld the parent ClassDescriptor * @return the ClassDescriptors of its children */ public Set<ClassDescriptor> getDirectSubs(ClassDescriptor cld) { return subMap.get(cld); } /** * Get the ClassDescriptors for the all subclasses of a class * @param cld the parent ClassDescriptor * @return the ClassDescriptors of all decedents */ public Set<ClassDescriptor> getAllSubs(ClassDescriptor cld) { Set<ClassDescriptor> returnSubs = new TreeSet<ClassDescriptor>(); Set<ClassDescriptor> directSubs = getDirectSubs(cld); returnSubs.addAll(directSubs); for (ClassDescriptor sub : directSubs) { returnSubs.addAll(getAllSubs(sub)); } return returnSubs; } /** * Get a ClassDescriptor by name, null if no ClassDescriptor of given name in Model. * @param name unqualified or fully-qualified class name of ClassDescriptor requested * @return the requested ClassDescriptor */ public ClassDescriptor getClassDescriptorByName(String name) { ClassDescriptor cd = cldMap.get(name); if (cd == null) { return cldMap.get(getPackageName() + "." + name); } else { return cd; } } /** * Get all ClassDescriptors in this model. * @return a set of all ClassDescriptors in the model */ public Set<ClassDescriptor> getClassDescriptors() { return new LinkedHashSet<ClassDescriptor>(cldMap.values()); } /** * Return true if named ClassDescriptor is found in the model. * @param name named of ClassDescriptor search for * @return true if named descriptor found */ public boolean hasClassDescriptor(String name) { return cldMap.containsKey(name); } /** * Get a Set of fully qualified class names in this model (i.e. including * package name). * @return Set of fully qualified class names */ public Set<String> getClassNames() { return cldMap.keySet(); } /** * Get the name of this model - i.e. package name. * @return name of the model */ public String getName() { return modelName; } /** * Get the nameSpace URI of this model * @return nameSpace URI of the model */ public URI getNameSpace() { return nameSpace; } /** * {@inheritDoc} */ public boolean equals(Object obj) { if (obj instanceof Model) { Model model = (Model) obj; return modelName.equals(model.modelName) && nameSpace.equals(model.nameSpace) && cldMap.equals(model.cldMap); } return false; } /** * {@inheritDoc} */ public int hashCode() { return 3 * modelName.hashCode() + 5 * cldMap.hashCode(); } /** * {@inheritDoc} */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<model name=\"" + modelName + "\" namespace=\"" + nameSpace + "\">"); for (ClassDescriptor cld : getClassDescriptors()) { if (!"org.intermine.model.InterMineObject".equals(cld.getName())) { sb.append(cld.toString()); } } sb.append("</model>"); return sb.toString(); } /** * Takes a Class, and generates a Set of all ClassDescriptors that are the Class * or any of its parents. The Class may be a dynamic class - ie not in the model, although * at least one of its parents are in the model. * * @param c a Class * @return a Set of ClassDescriptor objects */ public Set<ClassDescriptor> getClassDescriptorsForClass(Class c) { synchronized (classToClassDescriptorSet) { Set<ClassDescriptor> retval = classToClassDescriptorSet.get(c); if (retval == null) { retval = new LinkedHashSet<ClassDescriptor>(); Stack<Class> todo = new Stack<Class>(); Set<Class> done = new HashSet<Class>(); todo.push(c); while (!todo.empty()) { Class toAdd = todo.pop(); if (!done.contains(toAdd)) { ClassDescriptor cld = getClassDescriptorByName(toAdd.getName()); if (cld != null) { retval.add(cld); } Class superClass = toAdd.getSuperclass(); if ((superClass != null) && (InterMineObject.class.isAssignableFrom(superClass))) { todo.push(superClass); } Class[] interfaces = toAdd.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (InterMineObject.class.isAssignableFrom(interfaces[i])) { todo.push(interfaces[i]); } } done.add(toAdd); } } classToClassDescriptorSet.put(c, retval); } return retval; } } /** * Takes a Class, and generates a Map of all FieldDescriptors that are the class fields * or any of its parents. The Class may be a dynamic class - ie not in the model, although * at least one of its parents are in the model. * * @param c a Class * @return a Map of FieldDescriptor objects */ public Map<String, FieldDescriptor> getFieldDescriptorsForClass(Class c) { synchronized (classToFieldDescriptorMap) { Map<String, FieldDescriptor> retval = classToFieldDescriptorMap.get(c); if (retval == null) { retval = new LinkedHashMap<String, FieldDescriptor>(); for (ClassDescriptor cld : getClassDescriptorsForClass(c)) { for (FieldDescriptor fd : cld.getFieldDescriptors()) { retval.put(fd.getName(), fd); } } classToFieldDescriptorMap.put(c, retval); } return retval; } } /** * Return the qualified name of the given unqualified class name. The className must be in the * given model or in the java.lang package or one of java.util.Date or java.math.BigDecimal. * @param className the name of the class * @return the fully qualified name of the class * @throws ClassNotFoundException if the class can't be found */ public String getQualifiedTypeName(String className) throws ClassNotFoundException { if (className.indexOf(".") != -1) { throw new IllegalArgumentException("Expected an unqualified class name: " + className); } if (TypeUtil.instantiate(className) != null) { // a primative type return className; } else { if ("InterMineObject".equals(className)) { return "org.intermine.model.InterMineObject"; } else { try { return Class.forName(getPackageName() + "." + className).getName(); } catch (ClassNotFoundException e) { // fall through and try java.lang } } if ("Date".equals(className)) { return Date.class.getName(); } if ("BigDecimal".equals(className)) { return BigDecimal.class.getName(); } return Class.forName("java.lang." + className).getName(); } } }
Checks if class in model is available are performed only if classes were generated.
intermine/objectstore/main/src/org/intermine/metadata/Model.java
Checks if class in model is available are performed only if classes were generated.
<ide><path>ntermine/objectstore/main/src/org/intermine/metadata/Model.java <ide> = new HashMap<Class, Set<ClassDescriptor>>(); <ide> private final Map<Class, Map<String, FieldDescriptor>> classToFieldDescriptorMap <ide> = new HashMap<Class, Map<String, FieldDescriptor>>(); <add> <add> private boolean generatedClassesAvailable = true; <ide> <ide> /** <ide> * Return a Model for specified model name (loading Model if necessary) <ide> return Class.forName("java.lang." + className).getName(); <ide> } <ide> } <add> <add> /** <add> * @return true if generated classes are available <add> * <add> */ <add> public boolean isGeneratedClassesAvailable() { <add> return generatedClassesAvailable; <add> } <add> <add> /** <add> * Sets if generated classes are available. <add> * @param available if generated class is available <add> */ <add> public void setGeneratedClassesAvailable(boolean available) { <add> this.generatedClassesAvailable = available; <add> } <add> <add> /** <add> * @param className class name <add> * @return true if class is defined else false <add> */ <add> public boolean isGeneratedClassAvailable(String className) { <add> try { <add> getQualifiedTypeName(className); <add> return true; <add> } catch (ClassNotFoundException ex) { <add> return false; <add> } <add> } <ide> }
Java
apache-2.0
d3f570179ec5bad07f40c57e722674d56f0d51d5
0
linqs/psl,linqs/psl,linqs/psl
/* * This file is part of the PSL software. * Copyright 2011-2013 University of Maryland * * 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 edu.umd.cs.psl.util.database; import java.util.Date; import java.util.HashSet; import java.util.Set; import com.google.common.base.Preconditions; import edu.umd.cs.psl.database.Database; import edu.umd.cs.psl.database.DatabaseQuery; import edu.umd.cs.psl.database.ResultList; import edu.umd.cs.psl.model.argument.*; import edu.umd.cs.psl.model.atom.GroundAtom; import edu.umd.cs.psl.model.atom.QueryAtom; import edu.umd.cs.psl.model.predicate.Predicate; import org.joda.time.DateTime; /** * Utility methods for common {@link Database} and {@link DatabaseQuery} tasks. */ public class Queries { /** * Returns all GroundAtoms of a Predicate persisted in a Database. * <p> * GroundAtoms are retrieved by executing the query returned by * {@link #getQueryForAllAtoms(Predicate)} and calling * {@link Database#getAtom(Predicate, GroundTerm...)} on each result. * * @param db the Database to query for GroundAtoms * @param p the Predicate of the GroundAtoms to return * @return all GroundAtoms of p in db */ public static Set<GroundAtom> getAllAtoms(Database db, Predicate p) { DatabaseQuery query = getQueryForAllAtoms(p); ResultList results = db.executeQuery(query); Set<GroundAtom> atoms = new HashSet<GroundAtom>(results.size()); for (int i = 0; i < results.size(); i++) atoms.add(db.getAtom(p, results.get(i))); return atoms; } /** * Returns a DatabaseQuery that matches any GroundAtom of a Predicate. * <p> * The query is a {@link QueryAtom} of the given Predicate with a different * {@link Variable} for each argument. * * @param p the Predicate of the Atoms to return * @return the query */ public static DatabaseQuery getQueryForAllAtoms(Predicate p) { Variable[] args = new Variable[p.getArity()]; for (int i = 0; i < args.length; i++) args[i] = new Variable("Vars" + i); QueryAtom atom = new QueryAtom(p, args); return new DatabaseQuery(atom); } /** * Constructs a {@link QueryAtom} from raw arguments using * {@link #convertArguments(Database, Predicate, Object...)}. * * @param db the Database to use to get a {@link UniqueID} * @param p the Predicate of the QueryAtom * @param rawArgs the arguments to the QueryAtom (after conversion) * @return the QueryAtom * @throws IllegalArgumentException if any element of rawArgs could not be * converted to a valid type or is already * a GroundTerm of an invalid type */ public static QueryAtom getQueryAtom(Database db, Predicate p, Object... rawArgs) { return new QueryAtom(p, convertArguments(db, p, rawArgs)); } /** * Converts raw arguments to {@link Term Terms} that fit a given Predicate. * <p> * Returns Terms such that they match the ArgumentTypes of a Predicate. Any * raw argument that is already a Term is returned as is. Any other raw * argument will be used to construct a {@link GroundTerm} of the appropriate * type if possible. * * @param db the Database to use to get a {@link UniqueID} * @param p the Predicate to match the arguments to * @param rawArgs the arguments to convert * @return the converted terms * @throws IllegalArgumentException if any element of rawArgs could not be * converted to a valid type or is already * a GroundTerm of an invalid type */ public static Term[] convertArguments(Database db, Predicate p, Object... rawArgs) { Preconditions.checkArgument(p.getArity()==rawArgs.length); Term[] args = new Term[rawArgs.length]; ArgumentType type; for (int i=0;i<rawArgs.length;i++) { type = p.getArgumentType(i); if (rawArgs[i] instanceof Variable) { args[i] = (Variable) rawArgs[i]; } else if (rawArgs[i] instanceof GroundTerm && type.isInstance((GroundTerm) rawArgs[i])) { args[i] = (GroundTerm) rawArgs[i]; } else { switch (type) { case UniqueID: args[i] = db.getUniqueID(rawArgs[i]); break; case String: args[i] = new StringAttribute(rawArgs[i].toString()); break; case Double: if (rawArgs[i] instanceof Double) args[i] = new DoubleAttribute((Double) rawArgs[i]); else if (rawArgs[i] instanceof String) args[i] = new DoubleAttribute(Double.parseDouble((String) rawArgs[i])); else throw new IllegalArgumentException("Could not convert raw arg " + i + " to Double."); break; case Integer: if (rawArgs[i] instanceof Integer) args[i] = new IntegerAttribute((Integer) rawArgs[i]); else if (rawArgs[i] instanceof String) args[i] = new IntegerAttribute(Integer.parseInt((String) rawArgs[i])); else throw new IllegalArgumentException("Could not convert raw arg " + i + " to Integer."); break; case Long: if (rawArgs[i] instanceof Long) args[i] = new LongAttribute((Long) rawArgs[i]); else throw new IllegalArgumentException("Could not convert raw arg " + i + " to Long."); case Date: try { args[i] = new DateAttribute(new DateTime(rawArgs[i])); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not convert raw arg " + i + " to Date."); } break; default: throw new IllegalArgumentException("Unrecognized argument type " + type + " at index " + i + "."); } } } return args; } }
psl-core/src/main/java/edu/umd/cs/psl/util/database/Queries.java
/* * This file is part of the PSL software. * Copyright 2011-2013 University of Maryland * * 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 edu.umd.cs.psl.util.database; import java.util.Date; import java.util.HashSet; import java.util.Set; import com.google.common.base.Preconditions; import edu.umd.cs.psl.database.Database; import edu.umd.cs.psl.database.DatabaseQuery; import edu.umd.cs.psl.database.ResultList; import edu.umd.cs.psl.model.argument.*; import edu.umd.cs.psl.model.atom.GroundAtom; import edu.umd.cs.psl.model.atom.QueryAtom; import edu.umd.cs.psl.model.predicate.Predicate; import org.joda.time.DateTime; /** * Utility methods for common {@link Database} and {@link DatabaseQuery} tasks. */ public class Queries { /** * Returns all GroundAtoms of a Predicate persisted in a Database. * <p> * GroundAtoms are retrieved by executing the query returned by * {@link #getQueryForAllAtoms(Predicate)} and calling * {@link Database#getAtom(Predicate, GroundTerm...)} on each result. * * @param db the Database to query for GroundAtoms * @param p the Predicate of the GroundAtoms to return * @return all GroundAtoms of p in db */ public static Set<GroundAtom> getAllAtoms(Database db, Predicate p) { DatabaseQuery query = getQueryForAllAtoms(p); ResultList results = db.executeQuery(query); Set<GroundAtom> atoms = new HashSet<GroundAtom>(results.size()); for (int i = 0; i < results.size(); i++) atoms.add(db.getAtom(p, results.get(i))); return atoms; } /** * Returns a DatabaseQuery that matches any GroundAtom of a Predicate. * <p> * The query is a {@link QueryAtom} of the given Predicate with a different * {@link Variable} for each argument. * * @param p the Predicate of the Atoms to return * @return the query */ public static DatabaseQuery getQueryForAllAtoms(Predicate p) { Variable[] args = new Variable[p.getArity()]; for (int i = 0; i < args.length; i++) args[i] = new Variable("Vars" + i); QueryAtom atom = new QueryAtom(p, args); return new DatabaseQuery(atom); } /** * Constructs a {@link QueryAtom} from raw arguments using * {@link #convertArguments(Database, Predicate, Object...)}. * * @param db the Database to use to get a {@link UniqueID} * @param p the Predicate of the QueryAtom * @param rawArgs the arguments to the QueryAtom (after conversion) * @return the QueryAtom * @throws IllegalArgumentException if any element of rawArgs could not be * converted to a valid type or is already * a GroundTerm of an invalid type */ public static QueryAtom getQueryAtom(Database db, Predicate p, Object... rawArgs) { return new QueryAtom(p, convertArguments(db, p, rawArgs)); } /** * Converts raw arguments to {@link Term Terms} that fit a given Predicate. * <p> * Returns Terms such that they match the ArgumentTypes of a Predicate. Any * raw argument that is already a Term is returned as is. Any other raw * argument will be used to construct a {@link GroundTerm} of the appropriate * type if possible. * * @param db the Database to use to get a {@link UniqueID} * @param p the Predicate to match the arguments to * @param rawArgs the arguments to convert * @return the converted terms * @throws IllegalArgumentException if any element of rawArgs could not be * converted to a valid type or is already * a GroundTerm of an invalid type */ public static Term[] convertArguments(Database db, Predicate p, Object... rawArgs) { Preconditions.checkArgument(p.getArity()==rawArgs.length); Term[] args = new Term[rawArgs.length]; ArgumentType type; for (int i=0;i<rawArgs.length;i++) { type = p.getArgumentType(i); if (rawArgs[i] instanceof Variable) { args[i] = (Variable) rawArgs[i]; } else if (rawArgs[i] instanceof GroundTerm && type.isInstance((GroundTerm) rawArgs[i])) { args[i] = (GroundTerm) rawArgs[i]; } else { switch (type) { case UniqueID: args[i] = db.getUniqueID(rawArgs[i]); break; case String: args[i] = new StringAttribute(rawArgs[i].toString()); break; case Double: if (rawArgs[i] instanceof Double) args[i] = new DoubleAttribute((Double) rawArgs[i]); else if (rawArgs[i] instanceof String) args[i] = new DoubleAttribute(Double.parseDouble((String) rawArgs[i])); else throw new IllegalArgumentException("Could not convert raw arg " + i + " to Double."); break; case Integer: if (rawArgs[i] instanceof Integer) args[i] = new IntegerAttribute((Integer) rawArgs[i]); else if (rawArgs[i] instanceof String) args[i] = new IntegerAttribute(Integer.parseInt((String) rawArgs[i])); else throw new IllegalArgumentException("Could not convert raw arg " + i + " to Integer."); break; case Long: if (rawArgs[i] instanceof Long) args[i] = new LongAttribute((Integer) rawArgs[i]); else throw new IllegalArgumentException("Could not convert raw arg " + i + " to Long."); case Date: try { args[i] = new DateAttribute(new DateTime(rawArgs[i])); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not convert raw arg " + i + " to Date."); } break; default: throw new IllegalArgumentException("Unrecognized argument type " + type + " at index " + i + "."); } } } return args; } }
One more fix for #7 #8
psl-core/src/main/java/edu/umd/cs/psl/util/database/Queries.java
One more fix for #7 #8
<ide><path>sl-core/src/main/java/edu/umd/cs/psl/util/database/Queries.java <ide> break; <ide> case Long: <ide> if (rawArgs[i] instanceof Long) <del> args[i] = new LongAttribute((Integer) rawArgs[i]); <add> args[i] = new LongAttribute((Long) rawArgs[i]); <ide> else <ide> throw new IllegalArgumentException("Could not convert raw arg " + i + " to Long."); <ide> case Date:
Java
apache-2.0
5d8491cccb1550126d4cc0178056ecccbb853c90
0
yanagishima/yanagishima,yanagishima/yanagishima,yanagishima/yanagishima,yanagishima/yanagishima
package yanagishima.servlet; import me.geso.tinyorm.TinyORM; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import yanagishima.config.YanagishimaConfig; import yanagishima.exception.HiveQueryErrorException; import yanagishima.result.HiveQueryResult; import yanagishima.row.Query; import yanagishima.service.HiveService; import yanagishima.util.AccessControlUtil; import yanagishima.util.HttpRequestUtil; import yanagishima.util.JsonUtil; import yanagishima.util.MetadataUtil; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static yanagishima.util.Constants.YANAGISHIMA_COMMENT; @Singleton public class HiveServlet extends HttpServlet { private static Logger LOGGER = LoggerFactory .getLogger(HiveServlet.class); private static final long serialVersionUID = 1L; @Inject private TinyORM db; private YanagishimaConfig yanagishimaConfig; private final HiveService hiveService; @Inject public HiveServlet(YanagishimaConfig yanagishimaConfig, HiveService hiveService) { this.yanagishimaConfig = yanagishimaConfig; this.hiveService = hiveService; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, Object> retVal = new HashMap<String, Object>(); Optional<String> queryOptional = Optional.ofNullable(request.getParameter("query")); queryOptional.ifPresent(query -> { try { String userName = null; Optional<String> hiveUser = Optional.ofNullable(request.getParameter("user")); Optional<String> hivePassword = Optional.ofNullable(request.getParameter("password")); if(yanagishimaConfig.isUseAuditHttpHeaderName()) { userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName()); } else { if (hiveUser.isPresent() && hivePassword.isPresent()) { userName = hiveUser.get(); } } if (yanagishimaConfig.isUserRequired() && userName == null) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } String datasource = HttpRequestUtil.getParam(request, "datasource"); if (yanagishimaConfig.isCheckDatasource()) { if (!AccessControlUtil.validateDatasource(request, datasource)) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } } if (userName != null) { LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource)); } boolean storeFlag = Boolean.parseBoolean(Optional.ofNullable(request.getParameter("store")).orElse("false")); int limit = yanagishimaConfig.getSelectLimit(); String engine = HttpRequestUtil.getParam(request, "engine"); try { HiveQueryResult hiveQueryResult = hiveService.doQuery(engine, datasource, query, userName, hiveUser, hivePassword, storeFlag, limit); String queryid = hiveQueryResult.getQueryId(); retVal.put("queryid", queryid); retVal.put("headers", hiveQueryResult.getColumns()); if(query.startsWith("SHOW SCHEMAS")) { List<String> invisibleDatabases = yanagishimaConfig.getInvisibleDatabases(datasource); retVal.put("results", hiveQueryResult.getRecords().stream().filter(list -> !invisibleDatabases.contains(list.get(0))).collect(Collectors.toList())); } else { retVal.put("results", hiveQueryResult.getRecords()); } retVal.put("lineNumber", Integer.toString(hiveQueryResult.getLineNumber())); retVal.put("rawDataSize", hiveQueryResult.getRawDataSize().toString()); Optional<String> warningMessageOptinal = Optional.ofNullable(hiveQueryResult.getWarningMessage()); warningMessageOptinal.ifPresent(warningMessage -> { retVal.put("warn", warningMessage); }); if(query.startsWith("DESCRIBE")) { if(yanagishimaConfig.getMetadataServiceUrl(datasource).isPresent()) { String[] strings = query.substring("DESCRIBE ".length()).split("\\."); String schema = strings[0]; String table = null; if(engine.equals("hive")) { table = strings[1].substring(1, strings[1].length() - 1); } else if(engine.equals("spark")) { table = strings[1]; } else { throw new IllegalArgumentException(engine + " is illegal"); } MetadataUtil.setMetadata(yanagishimaConfig.getMetadataServiceUrl(datasource).get(), retVal, schema, table, hiveQueryResult.getRecords()); } } } catch (HiveQueryErrorException e) { LOGGER.error(e.getMessage()); retVal.put("queryid", e.getQueryId()); retVal.put("error", e.getCause().getMessage()); } } catch (Throwable e) { LOGGER.error(e.getMessage(), e); retVal.put("error", e.getMessage()); } }); JsonUtil.writeJSON(response, retVal); } }
src/main/java/yanagishima/servlet/HiveServlet.java
package yanagishima.servlet; import me.geso.tinyorm.TinyORM; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import yanagishima.config.YanagishimaConfig; import yanagishima.exception.HiveQueryErrorException; import yanagishima.result.HiveQueryResult; import yanagishima.row.Query; import yanagishima.service.HiveService; import yanagishima.util.AccessControlUtil; import yanagishima.util.HttpRequestUtil; import yanagishima.util.JsonUtil; import yanagishima.util.MetadataUtil; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static yanagishima.util.Constants.YANAGISHIMA_COMMENT; @Singleton public class HiveServlet extends HttpServlet { private static Logger LOGGER = LoggerFactory .getLogger(HiveServlet.class); private static final long serialVersionUID = 1L; @Inject private TinyORM db; private YanagishimaConfig yanagishimaConfig; private final HiveService hiveService; @Inject public HiveServlet(YanagishimaConfig yanagishimaConfig, HiveService hiveService) { this.yanagishimaConfig = yanagishimaConfig; this.hiveService = hiveService; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, Object> retVal = new HashMap<String, Object>(); Optional<String> queryOptional = Optional.ofNullable(request.getParameter("query")); queryOptional.ifPresent(query -> { try { String userName = null; Optional<String> hiveUser = Optional.ofNullable(request.getParameter("user")); Optional<String> hivePassword = Optional.ofNullable(request.getParameter("password")); if(yanagishimaConfig.isUseAuditHttpHeaderName()) { userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName()); } else { if (hiveUser.isPresent() && hivePassword.isPresent()) { userName = hiveUser.get(); } } if (yanagishimaConfig.isUserRequired() && userName == null) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } String datasource = HttpRequestUtil.getParam(request, "datasource"); if (yanagishimaConfig.isCheckDatasource()) { if (!AccessControlUtil.validateDatasource(request, datasource)) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } } if (userName != null) { LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource)); } boolean storeFlag = Boolean.parseBoolean(Optional.ofNullable(request.getParameter("store")).orElse("false")); int limit = yanagishimaConfig.getSelectLimit(); String engine = HttpRequestUtil.getParam(request, "engine"); try { HiveQueryResult hiveQueryResult = hiveService.doQuery(engine, datasource, query, userName, hiveUser, hivePassword, storeFlag, limit); String queryid = hiveQueryResult.getQueryId(); retVal.put("queryid", queryid); retVal.put("headers", hiveQueryResult.getColumns()); if(query.toLowerCase().indexOf("SHOW SCHEMAS") != -1) { List<String> invisibleDatabases = yanagishimaConfig.getInvisibleDatabases(datasource); retVal.put("results", hiveQueryResult.getRecords().stream().filter(list -> !invisibleDatabases.contains(list.get(0))).collect(Collectors.toList())); } else { retVal.put("results", hiveQueryResult.getRecords()); } retVal.put("lineNumber", Integer.toString(hiveQueryResult.getLineNumber())); retVal.put("rawDataSize", hiveQueryResult.getRawDataSize().toString()); Optional<String> warningMessageOptinal = Optional.ofNullable(hiveQueryResult.getWarningMessage()); warningMessageOptinal.ifPresent(warningMessage -> { retVal.put("warn", warningMessage); }); if(query.toLowerCase().startsWith("DESCRIBE")) { if(yanagishimaConfig.getMetadataServiceUrl(datasource).isPresent()) { String[] strings = query.toLowerCase().substring("DESCRIBE ".length()).split("\\."); String schema = strings[0]; String table = strings[1].substring(1, strings[1].length() - 1); MetadataUtil.setMetadata(yanagishimaConfig.getMetadataServiceUrl(datasource).get(), retVal, schema, table, hiveQueryResult.getRecords()); } } } catch (HiveQueryErrorException e) { LOGGER.error(e.getMessage()); retVal.put("queryid", e.getQueryId()); retVal.put("error", e.getCause().getMessage()); } } catch (Throwable e) { LOGGER.error(e.getMessage(), e); retVal.put("error", e.getMessage()); } }); JsonUtil.writeJSON(response, retVal); } }
remove back slash because it's not necessary in sparksql
src/main/java/yanagishima/servlet/HiveServlet.java
remove back slash because it's not necessary in sparksql
<ide><path>rc/main/java/yanagishima/servlet/HiveServlet.java <ide> String queryid = hiveQueryResult.getQueryId(); <ide> retVal.put("queryid", queryid); <ide> retVal.put("headers", hiveQueryResult.getColumns()); <del> if(query.toLowerCase().indexOf("SHOW SCHEMAS") != -1) { <add> if(query.startsWith("SHOW SCHEMAS")) { <ide> List<String> invisibleDatabases = yanagishimaConfig.getInvisibleDatabases(datasource); <ide> retVal.put("results", hiveQueryResult.getRecords().stream().filter(list -> !invisibleDatabases.contains(list.get(0))).collect(Collectors.toList())); <ide> } else { <ide> warningMessageOptinal.ifPresent(warningMessage -> { <ide> retVal.put("warn", warningMessage); <ide> }); <del> if(query.toLowerCase().startsWith("DESCRIBE")) { <add> if(query.startsWith("DESCRIBE")) { <ide> if(yanagishimaConfig.getMetadataServiceUrl(datasource).isPresent()) { <del> String[] strings = query.toLowerCase().substring("DESCRIBE ".length()).split("\\."); <add> String[] strings = query.substring("DESCRIBE ".length()).split("\\."); <ide> String schema = strings[0]; <del> String table = strings[1].substring(1, strings[1].length() - 1); <add> String table = null; <add> if(engine.equals("hive")) { <add> table = strings[1].substring(1, strings[1].length() - 1); <add> } else if(engine.equals("spark")) { <add> table = strings[1]; <add> } else { <add> throw new IllegalArgumentException(engine + " is illegal"); <add> } <ide> MetadataUtil.setMetadata(yanagishimaConfig.getMetadataServiceUrl(datasource).get(), retVal, schema, table, hiveQueryResult.getRecords()); <ide> } <ide> }