answer
stringlengths
17
10.2M
// OrcLabelProvider.java -- Java class OrcLabelProvider // Project OrcEclipse package orc.imp.treeModelBuilder; import java.util.HashSet; import java.util.Set; import orc.ast.extended.ASTNode; import orc.ast.extended.declaration.ClassDeclaration; import orc.ast.extended.declaration.SiteDeclaration; import orc.ast.extended.declaration.ValDeclaration; import orc.ast.extended.declaration.def.DefMember; import orc.ast.extended.declaration.type.DatatypeDeclaration; import orc.ast.extended.declaration.type.TypeAliasDeclaration; import orc.ast.extended.declaration.type.TypeDeclaration; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.imp.editor.ModelTreeNode; import org.eclipse.imp.services.ILabelProvider; import org.eclipse.imp.utils.MarkerUtils; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.DecorationOverlayIcon; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.swt.graphics.Image; import edu.utexas.cs.orc.orceclipse.Activator; import edu.utexas.cs.orc.orceclipse.OrcResources; /** * Label provider for the Orc Language. * <p> * A label provider maps an element of a tree model to * an optional image and optional text string used to display * the element in the user interface. */ public class OrcLabelProvider implements ILabelProvider { private final Set<ILabelProviderListener> fListeners = new HashSet<ILabelProviderListener>(); private static ImageRegistry orcImageRegistry = Activator.getInstance().getImageRegistry(); private static Image ORC_FILE_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_FILE_OBJ); private static Image ORC_FILE_W_ERROR = new DecorationOverlayIcon(ORC_FILE_OBJ_IMAGE, orcImageRegistry.getDescriptor(OrcResources.ERROR_OVR), IDecoration.BOTTOM_LEFT).createImage(); private static Image ORC_FILE_W_WARNING = new DecorationOverlayIcon(ORC_FILE_OBJ_IMAGE, orcImageRegistry.getDescriptor(OrcResources.WARNING_OVR), IDecoration.BOTTOM_LEFT).createImage(); private static Image ORC_INCLUDE_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_INCLUDE_OBJ); private static Image ORC_INCLUDE_W_ERROR = new DecorationOverlayIcon(ORC_INCLUDE_OBJ_IMAGE, orcImageRegistry.getDescriptor(OrcResources.ERROR_OVR), IDecoration.BOTTOM_LEFT).createImage(); private static Image ORC_INCLUDE_W_WARNING = new DecorationOverlayIcon(ORC_INCLUDE_OBJ_IMAGE, orcImageRegistry.getDescriptor(OrcResources.WARNING_OVR), IDecoration.BOTTOM_LEFT).createImage(); private static Image ORC_GENERIC_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_GENERIC_OBJ); private static Image ORC_DEF_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_DEF_OBJ); private static Image ORC_SITE_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_SITE_OBJ); private static Image ORC_CLASS_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_CLASS_OBJ); private static Image ORC_VARIABLE_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_VARIABLE_OBJ); private static Image ORC_TYPE_OBJ_IMAGE = orcImageRegistry.get(OrcResources.ORC_TYPE_OBJ); /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(final Object element) { if (element instanceof IFile) { final IFile file = (IFile) element; Image elemImage = null; final int sev = MarkerUtils.getMaxProblemMarkerSeverity(file, IResource.DEPTH_ONE); if (!file.getName().toLowerCase().endsWith(".inc")) { // Assume Orc file switch (sev) { case IMarker.SEVERITY_ERROR: elemImage = ORC_INCLUDE_W_ERROR; break; case IMarker.SEVERITY_WARNING: elemImage = ORC_FILE_W_WARNING; break; default: elemImage = ORC_INCLUDE_W_WARNING; break; } } else { // Include file switch (sev) { case IMarker.SEVERITY_ERROR: elemImage = ORC_FILE_W_ERROR; break; case IMarker.SEVERITY_WARNING: elemImage = ORC_FILE_W_WARNING; break; default: elemImage = ORC_FILE_OBJ_IMAGE; break; } } return elemImage; } final ASTNode n = element instanceof ModelTreeNode ? (ASTNode) ((ModelTreeNode) element).getASTNode() : (ASTNode) element; return getImageFor(n); } /** * @param n AST node to retrieve an image * @return Image representing the type of the given AST node */ public static Image getImageFor(final ASTNode n) { if (n instanceof DefMember) { return ORC_DEF_OBJ_IMAGE; } if (n instanceof SiteDeclaration) { return ORC_SITE_OBJ_IMAGE; } if (n instanceof ClassDeclaration) { return ORC_CLASS_OBJ_IMAGE; } if (n instanceof ValDeclaration) { return ORC_VARIABLE_OBJ_IMAGE; } if (n instanceof TypeDeclaration) { return ORC_TYPE_OBJ_IMAGE; } if (n instanceof TypeAliasDeclaration) { return ORC_TYPE_OBJ_IMAGE; } if (n instanceof DatatypeDeclaration) { return ORC_TYPE_OBJ_IMAGE; } return ORC_GENERIC_OBJ_IMAGE; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(final Object element) { final ASTNode n = element instanceof ModelTreeNode ? (ASTNode) ((ModelTreeNode) element).getASTNode() : (ASTNode) element; return getLabelFor(n); } /** * @param n AST node to label * @return String representing a label of the given AST node */ public static String getLabelFor(final ASTNode n) { if (n instanceof DefMember) { final String name = ((DefMember) n).name; return name.equals("") ? "lambda" : "def " + name; } if (n instanceof SiteDeclaration) { return "site " + ((SiteDeclaration) n).varname; } if (n instanceof ClassDeclaration) { return "class " + ((ClassDeclaration) n).varname; } if (n instanceof ValDeclaration) { return "val " + ((ValDeclaration) n).p; } if (n instanceof TypeDeclaration) { return "type " + ((TypeDeclaration) n).varname; } if (n instanceof TypeAliasDeclaration) { return "type " + ((TypeAliasDeclaration) n).typename; } if (n instanceof DatatypeDeclaration) { return "type " + ((DatatypeDeclaration) n).typename; } return "<" + n.getClass().getSimpleName() + ">"; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void addListener(final ILabelProviderListener listener) { fListeners.add(listener); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose() */ public void dispose() { } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String) */ public boolean isLabelProperty(final Object element, final String property) { return false; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void removeListener(final ILabelProviderListener listener) { fListeners.remove(listener); } }
package v; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import static v.VMaths.*; public class D3 { static final float DEGREES_PER_SECOND = 50f / 1000f; static final float[][] UNIT = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static float[] xs = new float[8]; static float[] ys = new float[8]; static float[] zs = new float[8]; static float[] normal_xs = {0f, 0f, 1f, -1f, 0f, 0f}; static float[] normal_ys = {1f, 0f, 0f, 0f, 0f, -1f}; static float[] normal_zs = {0f, 1f, 0f, 0f, -1f, 0f}; static float[] rotation = {1f, 0f, 0f}; static float rotation_speed = 0f; static int rx = 0; static int ry = 0; static int rxy = 0; static int rg = 0; public static void main(String... args) throws InterruptedException { for (int i = 0; i < 8; i++) { xs[i] = ((i & 1) != 0 ? 1f : 0f) - 0.5f; ys[i] = ((i & 2) != 0 ? 1f : 0f) - 0.5f; zs[i] = ((i & 4) != 0 ? 1f : 0f) - 0.5f; } final JFrame window = new JFrame(); final JPanel panel; window.pack(); window.setLayout(new BorderLayout()); window.add(panel = new JPanel() { { this.setBackground(Color.BLACK); } @Override public void paint(Graphics g) { super.paint(g); int[] z = new int[6]; for (int i = 0; i < 6; i++) { int v = (int)(normal_zs[i] * 1000f); z[i] = (v << 8) | i; } Arrays.sort(z); for (int i = 0; i < 6; i++) { int side = z[i] & 7; switch (side) { case 0: draw(188, 188, 188, 0, 1, 5, 4, g, normal_zs[0]); break; case 1: draw(188, 0, 0, 0, 1, 3, 2, g, normal_zs[1]); break; case 2: draw( 0, 188, 0, 0, 2, 6, 4, g, normal_zs[2]); break; case 3: draw( 0, 0, 188, 1, 3, 7, 5, g, normal_zs[3]); break; case 4: draw(188, 128, 0, 4, 5, 7, 6, g, normal_zs[4]); break; case 5: draw(188, 188, 0, 2, 3, 7, 6, g, normal_zs[5]); break; } } draw(new Color(255, 0, 0), 0, 1, g); draw(new Color( 0, 0, 255), 0, 2, g); draw(new Color(210, 0, 210), 0, 4, g); draw(new Color(255, 255, 0), 1, 3, g); draw(new Color(210, 128, 0), 1, 5, g); draw(new Color( 0, 255, 0), 2, 3, g); draw(new Color( 0, 210, 210), 2, 6, g); draw(new Color(188, 210, 0), 3, 7, g); draw(new Color(188, 0, 0), 4, 5, g); draw(new Color( 0, 0, 188), 4, 6, g); draw(new Color(188, 188, 0), 5, 7, g); draw(new Color( 0, 188, 0), 6, 7, g); } private void draw(int R, int G, int B, int a, int b, int c, int d, Graphics g, float normal_z) { int A = (int)(255f * normal_z); if (A > 0) { A = A / 2 + 128; if (A > 255) A = 255; g.setColor(new Color(R, G, B, A)); g.fillPolygon(new int[] {Px(a), Px(b), Px(c), Px(d)}, new int[] {Py(a), Py(b), Py(c), Py(d)}, 4); } } private void draw(Color colour, int i, int j, Graphics g) { g.setColor(colour); g.drawLine(Px(i), Py(i), Px(j), Py(j)); } static final float SCREEN_Z = 50f; static final float MODEL_Z = 55f; static final float VIEWER_Z = 50f; static final float VIEWER_X = 0f; static final float VIEWER_Y = 0f; static final float CAMERA_Z = 10f; static final float CAMERA_X = 0f; static final float CAMERA_Y = 0f; private int Px(int i) { /* Orthogonal projection */ //float z = SCREEN_Z / (zs[i] + MODEL_Z); //return (int)(xs[i] * z * 300f + 400f); /* Perspective projection */ float model_z = zs[i] + MODEL_Z; float model_x = xs[i]; float p = VIEWER_Z / (model_z - CAMERA_Z) * (model_x - CAMERA_X) - VIEWER_X; return (int)(p * 300f + 400f); } private int Py(int i) { /* Orthogonal projection */ //float z = SCREEN_Z / (zs[i] + MODEL_Z); //return (int)(ys[i] * z * 300f + 300f); /* Perspective projection */ float model_z = zs[i] + MODEL_Z; float model_y = ys[i]; float p = VIEWER_Z / (model_z - CAMERA_Z) * (model_y - CAMERA_Y) - VIEWER_Y; return (int)(p * 300f + 300f); } }); window.setBackground(Color.BLACK); final Insets in = window.getInsets(); window.setSize(new Dimension(in.left + 800 + in.right, in.top + 600 + in.bottom)); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); final float SPEED = (float)(Math.sqrt(25.5f / 2f)) * DEGREES_PER_SECOND; window.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_D: rx = 0; break; case KeyEvent.VK_A: rx = 0; break; case KeyEvent.VK_W: ry = 0; break; case KeyEvent.VK_S: ry = 0; break; case KeyEvent.VK_E: rxy = 0; break; case KeyEvent.VK_Q: rxy = 0; break; case KeyEvent.VK_F: rg = 0; break; case KeyEvent.VK_C: rg = 0; break; } } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_D: rx = +1; break; case KeyEvent.VK_A: rx = -1; break; case KeyEvent.VK_W: ry = +1; break; case KeyEvent.VK_S: ry = -1; break; case KeyEvent.VK_E: rxy = +1; break; case KeyEvent.VK_Q: rxy = -1; break; case KeyEvent.VK_F: rg = +1; break; case KeyEvent.VK_C: rg = -1; break; case KeyEvent.VK_R: rotation_speed = 0; break; } } }); for (;;) { Thread.sleep(50); if (rx != 0) { float[] v = mul(rx * SPEED, createRotation("x")); v = add(mul(rotation_speed, rotation), v); rotation_speed = length(v); rotation = normalise(v); } if (ry != 0) { float[] v = mul(ry * SPEED, createRotation("y")); v = add(mul(rotation_speed, rotation), v); rotation_speed = length(v); rotation = normalise(v); } if (rxy != 0) { float[] v = mul(rxy * SPEED, createRotation("xy")); v = add(mul(rotation_speed, rotation), v); rotation_speed = length(v); rotation = normalise(v); } if (rg == 1) rotation_speed *= 1.1f; else if (rg == -1) rotation_speed /= 1.1f; if (rotation_speed != 0) transform(createRotation(rotation, rotation_speed)); panel.repaint(); } } public static void transform(float[][] m) { /* This is not a transformation of the object, but * rather its projection onto the screen. (This * program combines the object and the projection.) */ for (int i = 0; i < 8; i++) { float[] v = mul(m, xs[i], ys[i], zs[i]); xs[i] = v[0]; ys[i] = v[1]; zs[i] = v[2]; } for (int i = 0; i < 6; i++) { float[] v = mul(m, normal_xs[i], normal_ys[i], normal_zs[i]); normal_xs[i] = v[0]; normal_ys[i] = v[1]; normal_zs[i] = v[2]; } } }
package cgeo.geocaching.files; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.R; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.capability.ILogin; import cgeo.geocaching.connector.tc.TerraCachingLogType; import cgeo.geocaching.connector.tc.TerraCachingType; import cgeo.geocaching.enumerations.CacheAttribute; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.LoadFlag; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.log.LogEntry; import cgeo.geocaching.log.LogType; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.models.Trackable; import cgeo.geocaching.models.Waypoint; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.utils.DisposableHandler; import cgeo.geocaching.utils.HtmlUtils; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.MatcherWrapper; import cgeo.geocaching.utils.SynchronizedDateFormat; import android.sax.Element; import android.sax.EndElementListener; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Xml; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; abstract class GPXParser extends FileParser { private static final SynchronizedDateFormat formatSimple = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); // 2010-04-20T07:00:00 private static final SynchronizedDateFormat formatSimpleZ = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); // 2010-04-20T07:00:00Z private static final SynchronizedDateFormat formatTimezone = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US); // 2010-04-20T01:01:03-04:00 /** * Attention: case sensitive geocode pattern to avoid matching normal words in the name or description of the cache. */ private static final Pattern PATTERN_GEOCODE = Pattern.compile("([0-9A-Z]{5,})"); private static final Pattern PATTERN_GUID = Pattern.compile(".*" + Pattern.quote("guid=") + "([0-9a-z\\-]+)", Pattern.CASE_INSENSITIVE); private static final Pattern PATTERN_URL_GEOCODE = Pattern.compile(".*" + Pattern.quote("wp=") + "([A-Z][0-9A-Z]+)", Pattern.CASE_INSENSITIVE); /** * supported groundspeak extensions of the GPX format */ private static final String[] GROUNDSPEAK_NAMESPACE = { "http: "http: "http: }; /** * supported GSAK extension of the GPX format */ private static final String[] GSAK_NS = { "http: "http: "http: "http: "http: "http: }; /** * c:geo extensions of the gpx format */ private static final String CGEO_NS = "http: private static final Pattern PATTERN_MILLISECONDS = Pattern.compile("\\.\\d{3,7}"); private int listId = StoredList.STANDARD_LIST_ID; protected final String namespace; private final String version; private Geocache cache; private Trackable trackable = new Trackable(); private LogEntry.Builder logBuilder = null; private String type = null; private String sym = null; private String name = null; private String cmt = null; private String desc = null; protected final String[] userData = new String[5]; // take 5 cells, that makes indexing 1..4 easier private String parentCacheCode = null; private boolean wptVisited = false; private boolean wptUserDefined = false; private List<LogEntry> logs = new ArrayList<>(); /** * Parser result. Maps geocode to cache. */ private final Set<String> result = new HashSet<>(100); private ProgressInputStream progressStream; /** * URL contained in the header of the GPX file. Used to guess where the file is coming from. */ protected String scriptUrl; /** * original longitude in case of modified coordinates */ @Nullable protected String originalLon; /** * original latitude in case of modified coordinates */ @Nullable protected String originalLat; /** * Unfortunately we can only detect terracaching child waypoints by remembering the state of the parent */ private boolean terraChildWaypoint = false; private final class UserDataListener implements EndTextElementListener { private final int index; UserDataListener(final int index) { this.index = index; } @Override public void end(final String user) { userData[index] = validate(user); } } protected GPXParser(final int listIdIn, final String namespaceIn, final String versionIn) { listId = listIdIn; namespace = namespaceIn; version = versionIn; } static Date parseDate(final String inputUntrimmed) throws ParseException { // remove milliseconds to reduce number of needed patterns final MatcherWrapper matcher = new MatcherWrapper(PATTERN_MILLISECONDS, inputUntrimmed.trim()); final String input = matcher.replaceFirst(""); if (input.contains("Z")) { return formatSimpleZ.parse(input); } if (StringUtils.countMatches(input, ":") == 3) { final String removeColon = input.substring(0, input.length() - 3) + input.substring(input.length() - 2); return formatTimezone.parse(removeColon); } return formatSimple.parse(input); } @Override @NonNull public Collection<Geocache> parse(@NonNull final InputStream stream, @Nullable final DisposableHandler progressHandler) throws IOException, ParserException { // when importing a ZIP, reset the child waypoint state terraChildWaypoint = false; resetCache(); final RootElement root = new RootElement(namespace, "gpx"); final Element waypoint = root.getChild(namespace, "wpt"); root.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { scriptUrl = body; } }); root.getChild(namespace, "creator").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { scriptUrl = body; } }); // waypoint - attributes waypoint.setStartElementListener(new StartElementListener() { @Override public void start(final Attributes attrs) { try { if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) { final String latitude = attrs.getValue("lat"); final String longitude = attrs.getValue("lon"); // latitude and longitude are required attributes, but we export them empty for waypoints without coordinates if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) { cache.setCoords(new Geopoint(Double.parseDouble(latitude), Double.parseDouble(longitude))); } } } catch (final NumberFormatException e) { Log.w("Failed to parse waypoint's latitude and/or longitude", e); } } }); // waypoint waypoint.setEndElementListener(new EndElementListener() { @Override public void end() { // try to find geocode somewhere else if (StringUtils.isBlank(cache.getGeocode())) { findGeoCode(name); findGeoCode(desc); findGeoCode(cmt); } // take the name as code, if nothing else is available if (StringUtils.isBlank(cache.getGeocode()) && StringUtils.isNotBlank(name)) { cache.setGeocode(name.trim()); } if (isValidForImport()) { fixCache(cache); if (listId != StoredList.TEMPORARY_LIST.id) { cache.getLists().add(listId); } cache.setDetailed(true); createNoteFromGSAKUserdata(); final String geocode = cache.getGeocode(); if (result.contains(geocode)) { Log.w("Duplicate geocode during GPX import: " + geocode); } // modify cache depending on the use case/connector afterParsing(cache); // finally store the cache in the database result.add(geocode); DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)); DataStore.saveLogs(cache.getGeocode(), logs); // avoid the cachecache using lots of memory for caches which the user did not actually look at DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); showProgressMessage(progressHandler, progressStream.getProgress()); } else if (StringUtils.isNotBlank(cache.getName()) && (StringUtils.containsIgnoreCase(type, "waypoint") || terraChildWaypoint)) { addWaypointToCache(); } resetCache(); } private void addWaypointToCache() { fixCache(cache); if (cache.getName().length() > 2 || StringUtils.isNotBlank(parentCacheCode)) { if (StringUtils.isBlank(parentCacheCode)) { if (StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) { parentCacheCode = cache.getName().substring(2); } else if (terraChildWaypoint) { parentCacheCode = StringUtils.left(cache.getGeocode(), cache.getGeocode().length() - 1); } else { parentCacheCode = "GC" + cache.getName().substring(2).toUpperCase(Locale.US); } } if ("GC_WayPoint1".equals(cache.getShortDescription())) { cache.setShortDescription(""); } final Geocache cacheForWaypoint = findParentCache(); if (cacheForWaypoint != null) { final Waypoint waypoint = new Waypoint(cache.getShortDescription(), WaypointType.fromGPXString(sym), false); if (wptUserDefined) { waypoint.setUserDefined(); } waypoint.setId(-1); waypoint.setGeocode(parentCacheCode); waypoint.setPrefix(cacheForWaypoint.getWaypointPrefix(cache.getName())); waypoint.setLookup(" // there is no lookup code in gpx file waypoint.setCoords(cache.getCoords()); waypoint.setNote(cache.getDescription()); waypoint.setVisited(wptVisited); final List<Waypoint> mergedWayPoints = new ArrayList<>(cacheForWaypoint.getWaypoints()); final List<Waypoint> newPoints = new ArrayList<>(); newPoints.add(waypoint); Waypoint.mergeWayPoints(newPoints, mergedWayPoints, true); cacheForWaypoint.setWaypoints(newPoints, false); DataStore.saveCache(cacheForWaypoint, EnumSet.of(SaveFlag.DB)); showProgressMessage(progressHandler, progressStream.getProgress()); } } } }); // waypoint.time waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { try { cache.setHidden(parseDate(body)); } catch (final Exception e) { Log.w("Failed to parse cache date", e); } } }); // waypoint.name waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { name = body; String content = body.trim(); // extremcaching.com manipulates the GC code by adding GC in front of ECxxx if (StringUtils.startsWithIgnoreCase(content, "GCEC") && StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) { content = content.substring(2); } cache.setName(content); findGeoCode(cache.getName()); } }); // waypoint.desc waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { desc = body; cache.setShortDescription(validate(body)); } }); // waypoint.cmt waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { cmt = body; cache.setDescription(validate(body)); } }); // waypoint.getType() waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { final String[] content = StringUtils.split(body, '|'); if (content.length > 0) { type = content[0].toLowerCase(Locale.US).trim(); } } }); // waypoint.sym waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { sym = body.toLowerCase(Locale.US); if (sym.contains("geocache") && sym.contains("found")) { cache.setFound(true); } } }); // waypoint.url waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String url) { final MatcherWrapper matcher = new MatcherWrapper(PATTERN_GUID, url); if (matcher.matches()) { final String guid = matcher.group(1); if (StringUtils.isNotBlank(guid)) { cache.setGuid(guid); } } final MatcherWrapper matcherCode = new MatcherWrapper(PATTERN_URL_GEOCODE, url); if (matcherCode.matches()) { final String geocode = matcherCode.group(1); cache.setGeocode(geocode); } } }); // waypoint.urlname (name for waymarks) waypoint.getChild(namespace, "urlname").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String urlName) { if (cache.getName().equals(cache.getGeocode()) && StringUtils.startsWith(cache.getGeocode(), "WM")) { cache.setName(StringUtils.trim(urlName)); } } }); // for GPX 1.0, cache info comes from waypoint node (so called private children, // for GPX 1.1 from extensions node final Element cacheParent = getCacheParent(waypoint); registerGsakExtensions(cacheParent); registerTerraCachingExtensions(cacheParent); registerCgeoExtensions(cacheParent); // 3 different versions of the GC schema for (final String nsGC : GROUNDSPEAK_NAMESPACE) { // waypoints.cache final Element gcCache = cacheParent.getChild(nsGC, "cache"); gcCache.setStartElementListener(new StartElementListener() { @Override public void start(final Attributes attrs) { try { if (attrs.getIndex("id") > -1) { cache.setCacheId(attrs.getValue("id")); } if (attrs.getIndex("archived") > -1) { cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true")); } if (attrs.getIndex("available") > -1) { cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true")); } } catch (final RuntimeException e) { Log.w("Failed to parse cache attributes", e); } } }); // waypoint.cache.getName() gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String cacheName) { cache.setName(validate(cacheName)); } }); // waypoint.cache.getOwner() gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String ownerUserId) { cache.setOwnerUserId(validate(ownerUserId)); } }); // waypoint.cache.getOwner() gcCache.getChild(nsGC, "placed_by").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String ownerDisplayName) { cache.setOwnerDisplayName(validate(ownerDisplayName)); } }); // waypoint.cache.getType() gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String bodyIn) { String body = validate(bodyIn); // lab caches wrongly contain a prefix in the type if (body.startsWith("Geocache|")) { body = StringUtils.substringAfter(body, "Geocache|").trim(); } cache.setType(CacheType.getByPattern(body)); } }); // waypoint.cache.container gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { cache.setSize(CacheSize.getById(validate(body))); } }); // waypoint.cache.getAttributes() // @see issue #299 // <groundspeak:attributes> // <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute> // <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute> // where inc = 0 => _no, inc = 1 => _yes // IDs see array CACHE_ATTRIBUTES final Element gcAttributes = gcCache.getChild(nsGC, "attributes"); // waypoint.cache.attribute final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute"); gcAttribute.setStartElementListener(new StartElementListener() { @Override public void start(final Attributes attrs) { try { if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) { final int attributeId = Integer.parseInt(attrs.getValue("id")); final boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0; final CacheAttribute attribute = CacheAttribute.getById(attributeId); if (attribute != null) { cache.getAttributes().add(attribute.getValue(attributeActive)); } } } catch (final NumberFormatException ignored) { // nothing } } }); // waypoint.cache.getDifficulty() gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { try { cache.setDifficulty(Float.parseFloat(body)); } catch (final NumberFormatException e) { Log.w("Failed to parse difficulty", e); } } }); // waypoint.cache.getTerrain() gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { try { cache.setTerrain(Float.parseFloat(body)); } catch (final NumberFormatException e) { Log.w("Failed to parse terrain", e); } } }); // waypoint.cache.country gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String country) { if (StringUtils.isBlank(cache.getLocation())) { cache.setLocation(validate(country)); } else { cache.setLocation(cache.getLocation() + ", " + country.trim()); } } }); // waypoint.cache.state gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String state) { final String trimmedState = state.trim(); if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty if (StringUtils.isBlank(cache.getLocation())) { cache.setLocation(validate(state)); } else { cache.setLocation(trimmedState + ", " + cache.getLocation()); } } } }); // waypoint.cache.encoded_hints gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String encoded) { cache.setHint(validate(encoded)); } }); gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String shortDesc) { cache.setShortDescription(validate(shortDesc)); } }); gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String desc) { cache.setDescription(validate(desc)); } }); // waypoint.cache.travelbugs final Element gcTBs = gcCache.getChild(nsGC, "travelbugs"); // waypoint.cache.travelbug final Element gcTB = gcTBs.getChild(nsGC, "travelbug"); // waypoint.cache.travelbugs.travelbug gcTB.setStartElementListener(new StartElementListener() { @Override public void start(final Attributes attrs) { trackable = new Trackable(); try { if (attrs.getIndex("ref") > -1) { trackable.setGeocode(attrs.getValue("ref")); } } catch (final RuntimeException ignored) { // nothing } } }); gcTB.setEndElementListener(new EndElementListener() { @Override public void end() { if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) { cache.addInventoryItem(trackable); } } }); // waypoint.cache.travelbugs.travelbug.getName() gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String tbName) { trackable.setName(validate(tbName)); } }); // waypoint.cache.logs final Element gcLogs = gcCache.getChild(nsGC, "logs"); // waypoint.cache.log final Element gcLog = gcLogs.getChild(nsGC, "log"); gcLog.setStartElementListener(new StartElementListener() { @Override public void start(final Attributes attrs) { logBuilder = new LogEntry.Builder(); try { if (attrs.getIndex("id") > -1) { logBuilder.setId(Integer.parseInt(attrs.getValue("id"))); } } catch (final NumberFormatException ignored) { // nothing } } }); gcLog.setEndElementListener(new EndElementListener() { @Override public void end() { final LogEntry log = logBuilder.build(); if (log.getType() != LogType.UNKNOWN) { if (log.getType().isFoundLog() && StringUtils.isNotBlank(log.author)) { final IConnector connector = ConnectorFactory.getConnector(cache); if (connector instanceof ILogin && StringUtils.equals(log.author, ((ILogin) connector).getUserName())) { cache.setFound(true); cache.setVisitedDate(log.date); } } logs.add(log); } } }); // waypoint.cache.logs.log.date gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { try { logBuilder.setDate(parseDate(body).getTime()); } catch (final Exception e) { Log.w("Failed to parse log date", e); } } }); // waypoint.cache.logs.log.getType() gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { final String logType = validate(body); logBuilder.setLogType(LogType.getByType(logType)); } }); // waypoint.cache.logs.log.finder gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String finderName) { logBuilder.setAuthor(validate(finderName)); } }); // waypoint.cache.logs.log.text gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String logText) { logBuilder.setLog(validate(logText)); } }); } try { progressStream = new ProgressInputStream(stream); final BufferedReader reader = new BufferedReader(new InputStreamReader(progressStream, CharEncoding.UTF_8)); Xml.parse(new InvalidXMLCharacterFilterReader(reader), root.getContentHandler()); return DataStore.loadCaches(result, EnumSet.of(LoadFlag.DB_MINIMAL)); } catch (final SAXException e) { throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e); } } /** * Add listeners for GSAK extensions * */ private void registerGsakExtensions(final Element cacheParent) { for (final String gsakNamespace : GSAK_NS) { final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension"); gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String watchList) { cache.setOnWatchlist(Boolean.parseBoolean(watchList.trim())); } }); gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1)); for (int i = 2; i <= 4; i++) { gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i)); } gsak.getChild(gsakNamespace, "Parent").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { parentCacheCode = body; } }); gsak.getChild(gsakNamespace, "FavPoints").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String favoritePoints) { try { cache.setFavoritePoints(Integer.parseInt(favoritePoints)); } catch (final NumberFormatException e) { Log.w("Failed to parse favorite points", e); } } }); gsak.getChild(gsakNamespace, "GcNote").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String personalNote) { cache.setPersonalNote(StringUtils.trim(personalNote)); } }); gsak.getChild(gsakNamespace, "IsPremium").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String premium) { cache.setPremiumMembersOnly(Boolean.parseBoolean(premium)); } }); gsak.getChild(gsakNamespace, "LatBeforeCorrect").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String latitude) { originalLat = latitude; addOriginalCoordinates(); } }); gsak.getChild(gsakNamespace, "LonBeforeCorrect").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String longitude) { originalLon = longitude; addOriginalCoordinates(); } }); gsak.getChild(gsakNamespace, "Code").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String geocode) { if (StringUtils.isNotBlank(geocode)) { cache.setGeocode(StringUtils.trim(geocode)); } } }); } } /** * Add listeners for TerraCaching extensions * */ private void registerTerraCachingExtensions(final Element cacheParent) { final String terraNamespace = "http: final Element terraCache = cacheParent.getChild(terraNamespace, "terracache"); terraCache.getChild(terraNamespace, "name").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String name) { cache.setName(StringUtils.trim(name)); } }); terraCache.getChild(terraNamespace, "owner").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String ownerName) { cache.setOwnerDisplayName(validate(ownerName)); } }); terraCache.getChild(terraNamespace, "style").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String style) { cache.setType(TerraCachingType.getCacheType(style)); } }); terraCache.getChild(terraNamespace, "size").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String size) { cache.setSize(CacheSize.getById(size)); } }); terraCache.getChild(terraNamespace, "country").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String country) { if (StringUtils.isNotBlank(country)) { cache.setLocation(StringUtils.trim(country)); } } }); terraCache.getChild(terraNamespace, "state").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String state) { final String trimmedState = state.trim(); if (StringUtils.isNotEmpty(trimmedState)) { if (StringUtils.isBlank(cache.getLocation())) { cache.setLocation(validate(state)); } else { cache.setLocation(trimmedState + ", " + cache.getLocation()); } } } }); terraCache.getChild(terraNamespace, "description").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String description) { cache.setDescription(trimHtml(description)); } }); terraCache.getChild(terraNamespace, "hint").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String hint) { cache.setHint(HtmlUtils.extractText(hint)); } }); final Element terraLogs = terraCache.getChild(terraNamespace, "logs"); final Element terraLog = terraLogs.getChild(terraNamespace, "log"); terraLog.setStartElementListener(new StartElementListener() { @Override public void start(final Attributes attrs) { logBuilder = new LogEntry.Builder(); try { if (attrs.getIndex("id") > -1) { logBuilder.setId(Integer.parseInt(attrs.getValue("id"))); } } catch (final NumberFormatException ignored) { // nothing } } }); terraLog.setEndElementListener(new EndElementListener() { @Override public void end() { final LogEntry log = logBuilder.build(); if (log.getType() != LogType.UNKNOWN) { if (log.getType().isFoundLog() && StringUtils.isNotBlank(log.author)) { final IConnector connector = ConnectorFactory.getConnector(cache); if (connector instanceof ILogin && StringUtils.equals(log.author, ((ILogin) connector).getUserName())) { cache.setFound(true); cache.setVisitedDate(log.date); } } logs.add(log); } } }); // waypoint.cache.logs.log.date terraLog.getChild(terraNamespace, "date").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { try { logBuilder.setDate(parseDate(body).getTime()); } catch (final Exception e) { Log.w("Failed to parse log date", e); } } }); // waypoint.cache.logs.log.type terraLog.getChild(terraNamespace, "type").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String body) { final String logType = validate(body); logBuilder.setLogType(TerraCachingLogType.getLogType(logType)); } }); // waypoint.cache.logs.log.finder terraLog.getChild(terraNamespace, "user").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String finderName) { logBuilder.setAuthor(validate(finderName)); } }); // waypoint.cache.logs.log.text terraLog.getChild(terraNamespace, "entry").setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String entry) { logBuilder.setLog(trimHtml(validate(entry))); } }); } private static String trimHtml(final String html) { return StringUtils.trim(StringUtils.removeEnd(StringUtils.removeStart(html, "<br>"), "<br>")); } protected void addOriginalCoordinates() { if (StringUtils.isNotEmpty(originalLat) && StringUtils.isNotEmpty(originalLon)) { final Waypoint waypoint = new Waypoint(CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false); waypoint.setCoords(new Geopoint(originalLat, originalLon)); cache.addOrChangeWaypoint(waypoint, false); cache.setUserModifiedCoords(true); } } /** * Add listeners for c:geo extensions * */ private void registerCgeoExtensions(final Element cacheParent) { final Element cgeoVisited = cacheParent.getChild(CGEO_NS, "visited"); cgeoVisited.setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String visited) { wptVisited = Boolean.parseBoolean(visited.trim()); } }); final Element cgeoUserDefined = cacheParent.getChild(CGEO_NS, "userdefined"); cgeoUserDefined.setEndTextElementListener(new EndTextElementListener() { @Override public void end(final String userDefined) { wptUserDefined = Boolean.parseBoolean(userDefined.trim()); } }); } /** * Overwrite this method in a GPX parser sub class to modify the {@link Geocache}, after it has been fully parsed * from the GPX file and before it gets stored. * * @param cache * currently imported cache */ protected void afterParsing(final Geocache cache) { if ("GC_WayPoint1".equals(cache.getShortDescription())) { cache.setShortDescription(""); } } /** * GPX 1.0 and 1.1 use different XML elements to put the cache into, therefore needs to be overwritten in the * version specific subclasses * */ protected abstract Element getCacheParent(Element waypoint); protected static String validate(final String input) { if ("nil".equalsIgnoreCase(input)) { return ""; } return input.trim(); } private void findGeoCode(final String input) { if (input == null || StringUtils.isNotBlank(cache.getGeocode())) { return; } final String trimmed = input.trim(); final MatcherWrapper matcherGeocode = new MatcherWrapper(PATTERN_GEOCODE, trimmed); if (matcherGeocode.find()) { final String geocode = matcherGeocode.group(1); // a geocode should not be part of a word if (geocode.length() == trimmed.length() || Character.isWhitespace(trimmed.charAt(geocode.length()))) { if (ConnectorFactory.canHandle(geocode)) { cache.setGeocode(geocode); } } } } /** * reset all fields that are used to store cache fields over the duration of parsing a single cache */ private void resetCache() { type = null; sym = null; name = null; desc = null; cmt = null; parentCacheCode = null; wptVisited = false; wptUserDefined = false; logs = new ArrayList<>(); cache = createCache(); // explicitly set all properties which could lead to database access, if left as null value cache.setLocation(""); cache.setDescription(""); cache.setShortDescription(""); cache.setHint(""); for (int i = 0; i < userData.length; i++) { userData[i] = null; } originalLon = null; originalLat = null; } /** * Geocache factory method. This explicitly sets several members to empty lists, which does not happen with the * default constructor. */ private static Geocache createCache() { final Geocache newCache = new Geocache(); newCache.setReliableLatLon(true); // always assume correct coordinates, when importing from file instead of website newCache.setAttributes(Collections.<String> emptyList()); // override the lazy initialized list newCache.setWaypoints(Collections.<Waypoint> emptyList(), false); // override the lazy initialized list return newCache; } /** * create a cache note from the UserData1 to UserData4 fields supported by GSAK */ private void createNoteFromGSAKUserdata() { if (StringUtils.isBlank(cache.getPersonalNote())) { final StringBuilder buffer = new StringBuilder(); for (final String anUserData : userData) { if (StringUtils.isNotBlank(anUserData)) { buffer.append(' ').append(anUserData); } } final String note = buffer.toString().trim(); if (StringUtils.isNotBlank(note)) { cache.setPersonalNote(note); } } } private boolean isValidForImport() { if (StringUtils.isBlank(cache.getGeocode())) { return false; } if (cache.getCoords() == null) { return false; } final boolean valid = (type == null && sym == null) || StringUtils.contains(type, "geocache") || StringUtils.contains(sym, "geocache") || StringUtils.containsIgnoreCase(sym, "waymark") || (StringUtils.containsIgnoreCase(sym, "terracache") && !terraChildWaypoint); if ("GC_WayPoint1".equals(cache.getShortDescription())) { terraChildWaypoint = true; } return valid; } @Nullable private Geocache findParentCache() { if (StringUtils.isBlank(parentCacheCode)) { return null; } // first match by geocode only Geocache cacheForWaypoint = DataStore.loadCache(parentCacheCode, LoadFlags.LOAD_CACHE_OR_DB); if (cacheForWaypoint == null) { // then match by title final String geocode = DataStore.getGeocodeForTitle(parentCacheCode); if (StringUtils.isNotBlank(geocode)) { cacheForWaypoint = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); } } return cacheForWaypoint; } }
package polytheque.view; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; import com.toedter.calendar.JDateChooser; import polytheque.model.pojos.Adherent; /** * Classe permettant de gerer la modification des informations lies au compte de l'utilisateur. * * @author Godefroi Roussel * */ @SuppressWarnings("serial") public class AffichageCreationAdherent extends JPanel implements ActionListener { private JTextField userName; private JTextField userFirstName; private JTextField userPseudo; private JTextField userRue; private JTextField userCP; private JTextField userVille; private JTextField userPhone; private JTextField userMail; private JDateChooser dateChooser; private JPasswordField password; private JButton boutonValider; JComboBox<Boolean> userIsAdmin; JComboBox<Boolean> userPeutEmprunter; JComboBox<Boolean> userEstAJour; /** * Une tache d'affichage de l'application. */ private TacheDAffichage tacheDAffichageDeLApplication; /** * Creation de la page d'accueil. * * @param tacheDAffichageDeLApplication * Une tache d'affichage de l'application. * @return */ public AffichageCreationAdherent(TacheDAffichage afficheAppli) { this.tacheDAffichageDeLApplication = afficheAppli; this.setLayout(null); ajouterChamps(); creerPanneauDate(); ajouterBoutons(); } public void ajouterChamps() { /*JPanel grosPanel = new JPanel(); grosPanel.setLayout(new BorderLayout()); JPanel titrePanel = new JPanel();*/ JLabel titrePrincipal = new JLabel("Cration Adhrent"); titrePrincipal.setHorizontalAlignment(SwingConstants.CENTER); titrePrincipal.setBounds(480, 20, 260, 30); //titrePanel.add(titrePrincipal); //this.add(titrePanel, BorderLayout.NORTH); this.add(titrePrincipal); //grosPanel.add(titrePanel, BorderLayout.NORTH); //JPanel userInfoPanel = new JPanel(); JLabel labelUserName = new JLabel("Nom :"); labelUserName.setBounds(150, 150, 100, 30); //userInfoPanel.add(labelUserName); this.add(labelUserName); this.userName = new JTextField(); this.userName.setBounds(200, 150, 100, 30); //userInfoPanel.add(this.userName); //this.add(userInfoPanel,BorderLayout.WEST); this.add(userName); JLabel labelUserFirstName = new JLabel("Prenom :"); labelUserFirstName.setBounds(150, 200, 100, 30); //userInfoPanel.add(labelUserFirstName); this.add(labelUserFirstName); this.userFirstName = new JTextField(); this.userFirstName.setBounds(210, 200, 100, 30); //userInfoPanel.add(this.userFirstName); //this.add(userInfoPanel,BorderLayout.WEST); //grosPanel.add(userInfoPanel, BorderLayout.WEST); this.add(userFirstName); JLabel labelUserRue = new JLabel("Rue :"); labelUserRue.setBounds(150, 240, 100, 30); this.add(labelUserRue); this.userRue = new JTextField(); this.userRue.setBounds(200, 240, 130, 30); this.add(this.userRue); //this.add(this.userInfoPanel, BorderLayout.WEST); JLabel labelUserCP = new JLabel("Code Postal:"); labelUserCP.setBounds(150, 270, 100, 30); this.add(labelUserCP); this.userCP = new JTextField(); this.userCP.setBounds(240, 270, 100, 30); this.add(this.userCP); //this.add(this.userInfoPanel, BorderLayout.WEST); JLabel labelUserVille = new JLabel("Ville :"); labelUserVille.setBounds(150, 300, 100, 30); this.add(labelUserVille); this.userVille = new JTextField(); this.userVille.setBounds(200, 300, 100, 30); this.add(this.userVille); //this.add(this.userInfoPanel, BorderLayout.WEST); JLabel labelUserMail = new JLabel("Mail :"); labelUserMail.setBounds(150, 330, 100, 30); this.add(labelUserMail); this.userMail = new JTextField(); this.userMail.setBounds(200, 330, 100, 30); this.add(this.userMail); //this.add(this.userInfoPanel, BorderLayout.WEST); JLabel labelUserTelephone = new JLabel("Telephone :"); labelUserTelephone.setBounds(150, 360, 100, 30); this.add(labelUserTelephone); this.userPhone = new JTextField(); this.userPhone.setBounds(220, 360, 100, 30); this.add(this.userPhone); //this.add(this.userInfoPanel, BorderLayout.WEST); JLabel labelUserPseudo = new JLabel("Pseudo :"); labelUserPseudo.setBounds(150, 390, 100, 30); this.add(labelUserPseudo); this.userPseudo = new JTextField(); this.userPseudo.setBounds(210, 390, 100, 30); this.add(this.userPseudo); //this.add(this.userInfoPanel, BorderLayout.WEST); JLabel labelpassword = new JLabel("Mot de passe :"); labelpassword.setBounds(150, 420, 100, 30); this.add(labelpassword); this.password = new JPasswordField(); this.password.setBounds(230, 420, 190, 30); this.password.setColumns(10); this.add(this.password); //this.add(this.userInfoPanel, BorderLayout.WEST); //userIsAdminPanel = new JPanel(); //userIsAdminPanel.setPreferredSize(new Dimension(100, 20)); JLabel labelUserIsAdmin = new JLabel("Admin :"); labelUserIsAdmin.setBounds(600, 300, 100, 30); this.add(labelUserIsAdmin); //this.userIsAdminPanel.add(labelUserIsAdmin); this.userIsAdmin = new JComboBox<Boolean>(); this.userIsAdmin.addItem(Boolean.TRUE); this.userIsAdmin.addItem(Boolean.FALSE); this.userIsAdmin.setPreferredSize(new Dimension(100, 20)); this.userIsAdmin.setBounds(600, 350, 100, 30); this.add(userIsAdmin); //userIsAdminPanel.add(this.userIsAdmin); //this.add(userIsAdminPanel, BorderLayout.CENTER); //grosPanel.add(userIsAdminPanel, BorderLayout.CENTER); //userPeutEmprunterPanel = new JPanel(); //userPeutEmprunterPanel.setPreferredSize(new Dimension(100, 20)); JLabel labelUserPeutEmprunter = new JLabel("Peut Emprunter :"); labelUserPeutEmprunter.setBounds(600, 100, 100, 30); this.add(labelUserPeutEmprunter); //this.userPeutEmprunterPanel.add(labelUserPeutEmprunter); this.userPeutEmprunter = new JComboBox<Boolean>(); this.userPeutEmprunter.addItem(Boolean.TRUE); this.userPeutEmprunter.addItem(Boolean.FALSE); this.userPeutEmprunter.setPreferredSize(new Dimension(100, 20)); this.userPeutEmprunter.setBounds(600, 150, 100, 30); // userPeutEmprunterPanel.add(this.userPeutEmprunter); this.add(userPeutEmprunter); //this.add(userPeutEmprunterPanel, BorderLayout.CENTER); // grosPanel.add(userPeutEmprunterPanel, BorderLayout.CENTER); //userEstAJourPanel = new JPanel(); //userEstAJourPanel.setPreferredSize(new Dimension(20, 20)); JLabel labelUserEstAJour = new JLabel("Est a jour :"); labelUserEstAJour.setBounds(600, 200, 100, 30); this.add(labelUserEstAJour); //userEstAJourPanel.add(labelUserEstAJour); this.userEstAJour = new JComboBox<Boolean>(); this.userEstAJour.addItem(Boolean.TRUE); this.userEstAJour.addItem(Boolean.FALSE); this.userEstAJour.setPreferredSize(new Dimension(20, 20)); this.userEstAJour.setBounds(600, 250, 100, 30); this.add(this.userEstAJour); } private void creerPanneauDate() { //JPanel DatePanel = new JPanel(); //DatePanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50)); JLabel labelUserBirthday = new JLabel("Date de naissance :"); labelUserBirthday.setBounds(850, 150, 150, 30); this.add(labelUserBirthday); this.dateChooser = new JDateChooser(); this.dateChooser.setBounds(850, 200, 150, 30); this.add(this.dateChooser); //this.add(DatePanel, BorderLayout.EAST); } public void ajouterBoutons(){ //JPanel panelButton = new JPanel(); this.boutonValider = new JButton("Valider"); this.boutonValider.setBounds(480, 500, 200, 30); this.boutonValider.addActionListener(this); this.add(this.boutonValider); //this.add(panelButton, BorderLayout.SOUTH); } @Override public void actionPerformed(ActionEvent event) { JButton boutonSelectionne = (JButton) event.getSource(); if (boutonSelectionne == this.boutonValider) { if (this.userName.getText() != null && this.userFirstName.getText() != null && this.dateChooser.getDate() != null && this.userRue.getText() != null && this.userCP.getText() != null && this.userVille.getText() != null && this.userPseudo.getText() != null && this.password.getPassword() != null) { String password = new String(this.password.getPassword()); Date dateNaissance = new Date(this.dateChooser.getDate().getTime()); boolean admin = (boolean) this.userIsAdmin.getSelectedItem(); boolean peutEmprunter = (boolean) this.userPeutEmprunter.getSelectedItem(); boolean AJour = (boolean) this.userEstAJour.getSelectedItem(); Adherent adherent = new Adherent(this.userName.getText(), this.userFirstName.getText(), dateNaissance, this.userRue.getText(), this.userCP.getText(), this.userVille.getText(), this.userMail.getText(), this.userPhone.getText(), this.userPseudo.getText(), password, admin, AJour, peutEmprunter, 0); if (this.tacheDAffichageDeLApplication.creerAdherent(adherent) == false) { this.tacheDAffichageDeLApplication.afficherMessage("Erreur lors de la cration d'un nouvel adhrent", "Erreur de cration", JOptionPane.ERROR_MESSAGE); } else { this.tacheDAffichageDeLApplication.afficherMessage("Un nouvel adhrent a t cr !", "Cration termine", JOptionPane.INFORMATION_MESSAGE); //rafrachir pour enlever les infos aprs la cration de l'adhrent return; } } else { this.tacheDAffichageDeLApplication.afficherMessage("Veuillez renseigner tous les champs !", "Erreur champ(s) vide(s)", JOptionPane.ERROR_MESSAGE); } } return; } }
package polytheque.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; import com.toedter.calendar.JDateChooser; import polytheque.model.pojos.Adherent; /** * Classe permettant de gerer la modification des informations lies au compte de l'utilisateur. * * @author Godefroi Roussel * */ @SuppressWarnings("serial") public class AffichageCreationAdherent extends JPanel implements ActionListener { private JTextField userName; private JTextField userFirstName; private JTextField userBirthday; private JTextField userPseudo; private JTextField userRue; private JTextField userCP; private JTextField userVille; private JTextField userPhone; private JTextField userMail; private JTextField userCptRetard; private JPasswordField password; private JButton boutonValider; private JButton boutonRetourAccueil; private JPanel userInfoPanel; private JPanel userIsAdminPanel; private JPanel userPeutEmprunterPanel; private JPanel userEstAJourPanel; private Adherent adherentCourant; JComboBox<Boolean> userIsAdmin; JComboBox<Boolean> userPeutEmprunter; JComboBox<Boolean> userEstAJour; /** * Une tache d'affichage de l'application. */ private TacheDAffichage tacheDAffichageDeLApplication; /** * Creation de la page d'accueil. * * @param tacheDAffichageDeLApplication * Une tache d'affichage de l'application. * @return */ public AffichageCreationAdherent(TacheDAffichage afficheAppli) { this.tacheDAffichageDeLApplication = afficheAppli; this.setLayout(new BorderLayout()); ajouterChamps(); creerPanneauDate(); //ajouterBoutons(); } public void ajouterChamps() { JLabel titrePrincipal = new JLabel("Mon compte"); titrePrincipal.setHorizontalAlignment(SwingConstants.CENTER); titrePrincipal.setBounds(350, 20, 260, 30); this.add(titrePrincipal); this.userInfoPanel = new JPanel(); JLabel labelUserName = new JLabel("Nom :"); this.userInfoPanel.add(labelUserName); /*this.userName = new JTextField(); this.userName.setColumns(10); this.add(this.userName, BorderLayout.CENTER); */ this.userInfoPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50)); this.userInfoPanel.add(labelUserName); labelUserName.setBounds(300, 150, 100, 30); this.userName = new JTextField(); this.userName.setBounds(350, 150, 100, 30); this.userInfoPanel.add(this.userName); this.add(this.userInfoPanel); /*JLabel labelUserFirstName = new JLabel("Prenom :"); labelUserFirstName.setBounds(300, 180, 100, 30); this.userInfoPanel.add(labelUserFirstName); this.userFirstName = new JTextField(); this.userFirstName.setBounds(360, 180, 100, 30); this.userInfoPanel.add(this.userFirstName); //this.add(this.userInfoPanel); JLabel labelUserRue = new JLabel("Rue :"); labelUserRue.setBounds(300, 240, 100, 30); this.userInfoPanel.add(labelUserRue); this.userRue = new JTextField(); this.userRue.setBounds(350, 240, 100, 30); this.userInfoPanel.add(this.userRue); //this.add(this.userInfoPanel); JLabel labelUserCP = new JLabel("Code Postal:"); labelUserCP.setBounds(300, 270, 100, 30); this.userInfoPanel.add(labelUserCP); this.userCP = new JTextField(); this.userCP.setBounds(390, 270, 100, 30); this.userInfoPanel.add(this.userCP); //this.add(this.userInfoPanel); JLabel labelUserVille = new JLabel("Ville :"); labelUserVille.setBounds(300, 300, 100, 30); this.userInfoPanel.add(labelUserVille); this.userVille = new JTextField(); this.userVille.setBounds(350, 300, 100, 30); this.userInfoPanel.add(this.userVille); //this.add(this.userInfoPanel); JLabel labelUserMail = new JLabel("Mail :"); labelUserMail.setBounds(300, 330, 100, 30); this.userInfoPanel.add(labelUserMail); this.userMail = new JTextField(); this.userMail.setBounds(350, 330, 100, 30); this.userInfoPanel.add(this.userMail); //this.add(this.userInfoPanel); JLabel labelUserTelephone = new JLabel("Telephone :"); labelUserTelephone.setBounds(300, 360, 100, 30); this.userInfoPanel.add(labelUserTelephone); this.userPhone = new JTextField(); this.userPhone.setBounds(370, 360, 100, 30); this.userInfoPanel.add(this.userPhone); //this.add(this.userInfoPanel); JLabel labelUserPseudo = new JLabel("Pseudo :"); labelUserPseudo.setBounds(300, 390, 100, 30); this.userInfoPanel.add(labelUserPseudo); this.userPseudo = new JTextField(); this.userPseudo.setBounds(360, 390, 100, 30); this.userInfoPanel.add(this.userPseudo); //this.add(this.userInfoPanel); JLabel labelpassword = new JLabel("Mot de passe :"); labelpassword.setBounds(300, 420, 100, 30); this.userInfoPanel.add(labelpassword); this.password = new JPasswordField(); this.password.setBounds(380, 420, 190, 30); this.password.setColumns(10); this.userInfoPanel.add(this.password); //this.add(this.userInfoPanel); JLabel labelUserCptRetard = new JLabel("Compteur Retard :"); labelUserCptRetard.setBounds(300, 450, 100, 30); this.userInfoPanel.add(labelUserCptRetard); this.userCptRetard = new JTextField(); this.userCptRetard.setBounds(380, 450, 190, 30); this.userInfoPanel.add(this.userCptRetard); this.add(this.userInfoPanel); this.userIsAdminPanel = new JPanel(); this.userIsAdminPanel.setPreferredSize(new Dimension(100, 20)); JLabel labelUserIsAdmin = new JLabel("Admin :"); labelUserIsAdmin.setBounds(800, 450, 100, 30); this.userIsAdminPanel.add(labelUserIsAdmin); this.userIsAdmin = new JComboBox<Boolean>(); this.userIsAdmin.addItem(Boolean.TRUE); this.userIsAdmin.addItem(Boolean.FALSE); this.userIsAdmin.setPreferredSize(new Dimension(100, 20)); this.userIsAdmin.setBounds(860, 450, 100, 30); this.userIsAdminPanel.add(this.userIsAdmin); this.add(this.userIsAdminPanel, BorderLayout.CENTER); this.userPeutEmprunterPanel = new JPanel(); this.userPeutEmprunterPanel.setPreferredSize(new Dimension(100, 20)); JLabel labelUserPeutEmprunter = new JLabel("Peut Emprunter :"); labelUserPeutEmprunter.setBounds(600, 100, 100, 30); this.userPeutEmprunterPanel.add(labelUserPeutEmprunter); this.userPeutEmprunter = new JComboBox<Boolean>(); this.userPeutEmprunter.addItem(Boolean.TRUE); this.userPeutEmprunter.addItem(Boolean.FALSE); this.userPeutEmprunter.setPreferredSize(new Dimension(100, 20)); this.userPeutEmprunter.setBounds(600, 150, 100, 30); this.userPeutEmprunterPanel.add(this.userPeutEmprunter); this.add(this.userPeutEmprunterPanel); this.userEstAJourPanel = new JPanel(); this.userEstAJourPanel.setPreferredSize(new Dimension(20, 20)); JLabel labelUserEstAJour = new JLabel("Est a jour :"); labelUserEstAJour.setBounds(600, 200, 100, 30); this.userEstAJourPanel.add(labelUserEstAJour); this.userEstAJour = new JComboBox<Boolean>(); this.userEstAJour.addItem(Boolean.TRUE); this.userEstAJour.addItem(Boolean.FALSE); this.userEstAJour.setPreferredSize(new Dimension(20, 20)); this.userEstAJour.setBounds(600, 250, 100, 30); this.userEstAJourPanel.add(this.userEstAJour); this.add(this.userEstAJourPanel);*/ } private void creerPanneauDate() { JPanel DatePanel = new JPanel(); DatePanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50)); JLabel labelUserBirthday = new JLabel("Cliquez sur votre date de naissance :"); labelUserBirthday.setBounds(400, 150, 200, 30); DatePanel.add(labelUserBirthday); JDateChooser dateChooser = new JDateChooser(); dateChooser.setBounds(400, 200, 200, 30); DatePanel.add(dateChooser); this.add(DatePanel); } public void ajouterBoutons(){ this.boutonValider = new JButton("Valider"); this.boutonValider.setBounds(200, 500, 200, 30); this.boutonValider.addActionListener(this); this.add(this.boutonValider); } @Override public void actionPerformed(ActionEvent event) { JButton boutonSelectionne = (JButton) event.getSource(); if (boutonSelectionne == this.boutonValider) { int cptRetard = Integer.parseInt(this.userCptRetard.getText()); String password = new String(this.password.getPassword()); Adherent adherent = new Adherent(this.userName.getText(), this.userFirstName.getText(),this.adherentCourant.getDateNaissance(), this.userRue.getText(), this.userCP.getText(), this.userVille.getText(), this.userMail.getText(), this.userPhone.getText(), this.userPseudo.getText(), password, this.userIsAdmin.getAutoscrolls(), this.userEstAJour.getAutoscrolls(),this.userPeutEmprunter.getAutoscrolls(), cptRetard); this.tacheDAffichageDeLApplication.afficherMessage("Un nouvel adhérent a ete crée !", "Création terminée", JOptionPane.INFORMATION_MESSAGE); this.tacheDAffichageDeLApplication.creerAdherent(adherent); this.tacheDAffichageDeLApplication.afficherGestionAdherent(); return; } return; } }
package com.sometrik.framework; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.android.trivialdrivesample.util.IabHelper; import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException; import com.android.trivialdrivesample.util.IabResult; import com.android.trivialdrivesample.util.Inventory; import com.android.trivialdrivesample.util.Purchase; import android.app.ActionBar; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.ScrollView; import android.widget.TextView; public class NativeCommand { private int internalId = 0; private int childInternalId = 0; private int value = 0; private int flags = 0; private String textValue = ""; private String textValue2 = ""; private CommandType command; private String key; private FrameWork frame; private ArrayList<PopupMenu> menuList = new ArrayList<PopupMenu>(); private int rowNumber = -1; private int columnNumber = -1; private final int FLAG_PADDING_LEFT = 1; private final int FLAG_PADDING_RIGHT = 2; private final int FLAG_PADDING_TOP = 4; private final int FLAG_PADDING_BOTTOM = 8; private final int FLAG_PASSWORD = 16; private final int FLAG_NUMERIC = 32; private final int FLAG_HYPERLINK = 64; private final int FLAG_USE_PURCHASES_API = 128; public enum CommandType { CREATE_PLATFORM, CREATE_APPLICATION, CREATE_BASICVIEW, CREATE_FORMVIEW, CREATE_OPENGL_VIEW, CREATE_TEXTFIELD, // For viewing single value CREATE_TEXTVIEW, // For viewing multiline text CREATE_LISTVIEW, // For viewing lists CREATE_GRIDVIEW, // For viewing tables CREATE_BUTTON, CREATE_SWITCH, CREATE_PICKER, // called Spinner in Android CREATE_LINEAR_LAYOUT, CREATE_TABLE_LAYOUT, CREATE_AUTO_COLUMN_LAYOUT, CREATE_HEADING_TEXT, CREATE_TEXT, CREATE_DIALOG, // For future CREATE_IMAGEVIEW, CREATE_ACTION_SHEET, CREATE_CHECKBOX, CREATE_RADIO_GROUP, CREATE_SEPARATOR, CREATE_SLIDER, CREATE_ACTIONBAR, DELETE_ELEMENT, SHOW_MESSAGE_DIALOG, SHOW_INPUT_DIALOG, SHOW_ACTION_SHEET, LAUNCH_BROWSER, POST_NOTIFICATION, HISTORY_GO_BACK, HISTORY_GO_FORWARD, CLEAR, // Clears the contents of GridView SET_INT_VALUE, // Sets value of radio groups, checkboxes and pickers SET_TEXT_VALUE, // Sets value of textfields, labels and images SET_INT_DATA, SET_TEXT_DATA, // Sets the cell value of GridView SET_LABEL, // Sets label for buttons and checkboxes SET_ENABLED, SET_READONLY, SET_VISIBILITY, SET_SHAPE, // Specifies the number of rows and columns in a GridView SET_STYLE, SET_ERROR, FLUSH_VIEW, // Flushes GridView content UPDATE_PREFERENCE, ADD_OPTION, ADD_COLUMN, QUIT_APP, // Timers CREATE_TIMER, // In-app purchases LIST_PRODUCTS, BUY_PRODUCT, LIST_PURCHASES, CONSUME_PURCHASE } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags, int rowNumber, int columnNumber){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; this.rowNumber = rowNumber; this.columnNumber = columnNumber; if (textValue != null) { this.textValue = new String(textValue, frame.getCharset()); } if (textValue2 != null) { this.textValue2 = new String(textValue2, frame.getCharset()); } } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; if (textValue != null) { this.textValue = new String(textValue, frame.getCharset()); } if (textValue2 != null) { this.textValue2 = new String(textValue2, frame.getCharset()); } } public void apply(NativeCommandHandler view) { System.out.println("Processing message " + command + " id: " + internalId + " Child id: " + getChildInternalId()); switch (command) { case CREATE_FORMVIEW: FWScrollView scrollView = new FWScrollView(frame, textValue); scrollView.setId(getChildInternalId()); scrollView.setPadding(10, 10, 10, 10); FrameWork.addToViewList(scrollView); if (view == null){ System.out.println("view was null"); if (frame.getCurrentViewId() == 0){ scrollView.setValue(1); } } else { view.addChild(scrollView); } break; case CREATE_BASICVIEW: case CREATE_LINEAR_LAYOUT: FWLayout layout = createLinearLayout(); view.addChild(layout); break; case CREATE_AUTO_COLUMN_LAYOUT:{ FWAuto auto = new FWAuto(frame); auto.setId(getChildInternalId()); FrameWork.addToViewList(auto); view.addChild(auto); } break; case CREATE_TABLE_LAYOUT: FWTable table = createTableLayout(false); view.addChild(table); break; case CREATE_BUTTON: FWButton button = createButton(); view.addChild(button); break; case CREATE_PICKER: FWPicker picker = createSpinner(); view.addChild(picker); break; case CREATE_SWITCH: FWSwitch click = createSwitch(); view.addChild(click); break; case CLEAR: //FWList clears list on 0 view.setValue(0); break; case CREATE_GRIDVIEW: //TODO //Fix from being debug status // FWLayout debugList = createDebugResultsScreen(); FWList debugList = new FWList(frame, new FWAdapter(frame, null)); debugList.setId(childInternalId); FrameWork.addToViewList(debugList); view.addChild(debugList); break; case CREATE_TIMER: Timer timer = new Timer(); timer.schedule((new TimerTask(){ @Override public void run() { FrameWork.timerEvent(System.currentTimeMillis() / 1000, internalId, childInternalId); } }), value, value); break; case CREATE_CHECKBOX: FWCheckBox checkBox = createCheckBox(); FrameWork.addToViewList(checkBox); view.addChild(checkBox); break; case CREATE_OPENGL_VIEW: frame.createNativeOpenGLView(childInternalId); break; case CREATE_TEXTVIEW: FWEditText editTextView = createBigEditText(); view.addChild(editTextView); break; case CREATE_TEXTFIELD: FWEditText editText = createEditText(); view.addChild(editText); break; case CREATE_RADIO_GROUP: FWRadioGroup radioGroup = new FWRadioGroup(frame); radioGroup.setId(childInternalId); break; case CREATE_HEADING_TEXT: FWTextView headingText = createTextView(true); view.addChild(headingText); break; case CREATE_TEXT: FWTextView textView = createTextView(false); view.addChild(textView); break; case CREATE_IMAGEVIEW: ImageView imageView = createImageView(); view.addChild(imageView); break; case ADD_OPTION: // Forward Command to FWPicker view.addOption(getValue(), getTextValue()); break; case ADD_COLUMN: view.addOption(getValue(), getTextValue()); break; case POST_NOTIFICATION: frame.createNotification(getTextValue(), getTextValue2()); break; case CREATE_APPLICATION: frame.setAppId(getInternalId()); frame.setSharedPreferences(textValue); if (isSet(FLAG_USE_PURCHASES_API)) { System.out.println("Initializing purchaseHelper"); frame.initializePurchaseHelper(textValue2, new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { if (result.isSuccess()) { System.out.println("PurchaseHelper successfully setup"); sendInventory(frame.getPurchaseHelperInventory()); } else { System.out.println("PurchaseHelper failed to setup"); } } }); } break; case SET_INT_VALUE: view.setValue(getValue()); break; case SET_TEXT_VALUE: view.setValue(textValue); break; case SET_TEXT_DATA: view.addData(rowNumber, columnNumber, textValue); break; case SET_VISIBILITY: if (value == 0){ view.setViewVisibility(false); } else { view.setViewVisibility(true); } break; case SET_ENABLED: view.setViewEnabled(value != 0); break; case SET_STYLE: view.setStyle(textValue, textValue2); break; case SET_ERROR: view.setError(value != 0, textValue); break; case LAUNCH_BROWSER: frame.launchBrowser(getTextValue()); break; case SHOW_MESSAGE_DIALOG: showMessageDialog(textValue, textValue2); break; case SHOW_INPUT_DIALOG: showInputDialog(textValue, textValue2); break; case CREATE_ACTION_SHEET: createActionSheet(); break; case CREATE_ACTIONBAR: //TODO not everything is set ActionBar ab = frame.getActionBar(); ab.setTitle(textValue); break; case QUIT_APP: // TODO frame.finish(); break; case UPDATE_PREFERENCE: //Now stores String value to string key. frame.getPreferencesEditor().putString(textValue, textValue2); frame.getPreferencesEditor().apply(); break; case DELETE_ELEMENT: deleteElement(view, childInternalId); break; case BUY_PRODUCT: try { launchPurchase(textValue); } catch (IabAsyncInProgressException e) { e.printStackTrace(); System.out.println("Error on launchPurchase with message: " + e.getMessage()); } default: System.out.println("Message couldn't be handled"); break; } } private void createActionSheet(){ PopupMenu menu = new PopupMenu(frame, null); menu.setOnMenuItemClickListener(new OnMenuItemClickListener(){ @Override public boolean onMenuItemClick(MenuItem item) { return false; } }); menuList.add(menu); } private FWTable createTableLayout(boolean autoSize){ FWTable table = new FWTable(frame); table.setId(getChildInternalId()); if (autoSize){ table.setAutoSize(true); } else { Log.d("table", "ALERT " + value); table.setColumnCount(value); } table.setStretchAllColumns(true); table.setShrinkAllColumns(true); FrameWork.addToViewList(table); return table; } private FWSwitch createSwitch() { FWSwitch click = new FWSwitch(frame); click.setId(childInternalId); if (textValue != "") { click.setTextOn(textValue); } if (textValue2 != "") { click.setTextOff(textValue2); } click.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, buttonView.getId(), isChecked ? 1 : 0); } }); FrameWork.addToViewList(click); return click; } private void deleteElement(NativeCommandHandler parent, int childId) { FrameWork.views.remove(childInternalId); ViewGroup group = (ViewGroup) parent; int childCount = group.getChildCount(); for (int i = 0; i < childCount; i++) { View view = group.getChildAt(i); if (view.getId() == childInternalId) { ((ViewGroup) parent).removeViewAt(i); break; } } } private ImageView createImageView() { ImageView imageView = new ImageView(frame); imageView.setId(childInternalId); try { InputStream is = frame.getAssets().open(textValue); Bitmap bitmap = BitmapFactory.decodeStream(is); imageView.setImageBitmap(bitmap); return imageView; } catch (IOException e) { e.printStackTrace(); System.out.println("error loading asset file to imageView"); System.exit(1); } return null; } private FWLayout createLinearLayout() { FWLayout layout = new FWLayout(frame); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // params.weight = 1.0f; // params.gravity = Gravity.FILL; // layout.setBaselineAligned(false); layout.setLayoutParams(params); layout.setId(getChildInternalId()); FrameWork.addToViewList(layout); if (getValue() == 2) { layout.setOrientation(LinearLayout.HORIZONTAL); } else { layout.setOrientation(LinearLayout.VERTICAL); } return layout; } private FWButton createButton() { FWButton button = new FWButton(frame); button.setId(getChildInternalId()); button.setText(getTextValue()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); button.setLayoutParams(params); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.println("Java: my button was clicked with id " + getChildInternalId()); if (!FrameWork.transitionAnimation) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), 1); } } }); FrameWork.addToViewList(button); return button; } private FWEditText createEditText(){ final FWEditText editText = new FWEditText(frame); editText.setId(getChildInternalId()); editText.setText(getTextValue()); editText.setMinWidth(80); editText.setSingleLine(); editText.setImeOptions(EditorInfo.IME_ACTION_DONE); if (isSet(FLAG_PASSWORD) && isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD); } else if (isSet(FLAG_PASSWORD)) { editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } else if (isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_CLASS_NUMBER); } editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable editable) { String inputText = editable.toString(); byte[] b = inputText.getBytes(frame.getCharset()); frame.textChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), b); } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) {} }); FrameWork.addToViewList(editText); return editText; } private FWEditText createBigEditText() { final FWEditText editText = new FWEditText(frame); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); editText.setMinLines(4); editText.setLayoutParams(params); editText.setId(getChildInternalId()); editText.setText(getTextValue()); editText.setVerticalScrollBarEnabled(true); editText.setMovementMethod(new ScrollingMovementMethod()); editText.addDelayedChangeListener(getChildInternalId()); FrameWork.addToViewList(editText); return editText; } private FWPicker createSpinner(){ FWPicker picker = new FWPicker(frame); picker.setId(getChildInternalId()); FrameWork.addToViewList(picker); return picker; } private FWCheckBox createCheckBox() { FWCheckBox checkBox = new FWCheckBox(frame); checkBox.setPadding(0, 0, 10, 0); checkBox.setId(childInternalId); if (textValue != "") { checkBox.setText(textValue); } checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton box, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, isChecked ? 1 : 0); } }); return checkBox; } private FWTextView createTextView(boolean bolded) { FWTextView textView = new FWTextView(frame); textView.setId(getChildInternalId()); if (bolded) { textView.setTypeface(null, Typeface.BOLD); } if (isSet(FLAG_HYPERLINK)) { textView.setMovementMethod(LinkMovementMethod.getInstance()); String text = "<a href='" + textValue2 + "'>" + textValue + "</a>"; textView.setText(Html.fromHtml(text)); } else { textView.setText(textValue); } FrameWork.addToViewList(textView); return textView; } // Create dialog with user text input private void showInputDialog(String title, String message) { System.out.println("Creating input dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); final EditText input = new EditText(frame); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Negative button listener builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); dialog.cancel(); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String inputText = String.valueOf(input.getText()); byte[] b = inputText.getBytes(frame.getCharset()); frame.endModal(System.currentTimeMillis() / 1000.0, 1, b); dialog.cancel(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); } // create Message dialog private void showMessageDialog(String title, String message) { System.out.println("creating message dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 1, null); dialog.dismiss(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); System.out.println("message dialog created"); } private void launchPurchase(final String productId) throws IabAsyncInProgressException { // Sku = product id from google account frame.getPurchaseHelper().launchPurchaseFlow(frame, productId, IabHelper.ITEM_TYPE_INAPP, null, 1, new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase info) { if (result.isSuccess()) { System.out.println("Purchase of product id " + productId + " completed"); FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), info.getSku(), true, info.getPurchaseTime() / 1000.0); // TODO } else { System.out.println("Purchase of product id " + productId + " failed"); // TODO } } }, ""); } private void sendInventory(Inventory inventory) { List<Purchase> purchaseList = inventory.getAllPurchases(); System.out.println("getting purchase history. Purchase list size: " + purchaseList.size()); for (Purchase purchase : inventory.getAllPurchases()) { FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), purchase.getSku(), false, purchase.getPurchaseTime() / 1000.0); } } private Boolean isSet(int flag) { return (flags & flag) != 0; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getInternalId() { return internalId; } public int getChildInternalId() { return childInternalId; } public String getTextValue() { return textValue; } public String getTextValue2() { return textValue2; } public CommandType getCommand() { return command; } public int getValue() { return value; } }
package com.sometrik.framework; import android.graphics.Bitmap.Config; import com.sometrik.framework.NativeCommand.Selector; import android.util.DisplayMetrics; import android.view.View; import android.widget.LinearLayout; public class NavigationBar extends LinearLayout implements NativeCommandHandler { FrameWork frame; ViewStyleManager normalStyle, activeStyle, currentStyle; public NavigationBar(FrameWork frame) { super(frame); this.frame = frame; setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); setLayoutParams(params); final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true); this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addChild(View view) { final int buttonId = view.getId(); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("Navigation OnClick: " + buttonId); frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getId(), 1, buttonId); } }); addView(view); } @Override public void addOption(int optionId, String text) { } @Override public void addColumn(String text, int columnType) { } @Override public void addData(String text, int row, int column, int sheet) { // TODO Auto-generated method stub } @Override public void setValue(String v) { // TODO Auto-generated method stub } @Override public void setValue(int v) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setViewVisibility(boolean visible) { // TODO Auto-generated method stub } @Override public void setStyle(Selector selector, String key, String value) { if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); if (normalStyle == currentStyle) normalStyle.apply(this); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); if (activeStyle == currentStyle) activeStyle.apply(this); } } @Override public void setError(boolean hasError, String errorText) { // TODO Auto-generated method stub } @Override public void clear() { // TODO Auto-generated method stub } @Override public void flush() { // TODO Auto-generated method stub } @Override public int getElementId() { return getId(); } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } @Override public void deinitialize() { // TODO Auto-generated method stub } }
import com.licel.jcardsim.base.Simulator; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Arrays; import java.util.Date; import javacard.framework.AID; import javacard.framework.Util; import javax.smartcardio.CommandAPDU; import javax.smartcardio.ResponseAPDU; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSAPublicKey; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.asn1.x509.V1TBSCertificateGenerator; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.TBSCertificate; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.cryptonit.CryptonitApplet; /** * @author Mathias Brossard */ class piv { private static String toHex(String prefix, byte[] bytes) { StringBuilder sb = new StringBuilder(); sb.append(prefix); for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02x ", bytes[i])); } return sb.toString(); } private static TBSCertificate createTBS(ByteArrayOutputStream bOut, SubjectPublicKeyInfo ski, AlgorithmIdentifier algo) throws IOException { TBSCertificate tbs = null; V1TBSCertificateGenerator tbsGen = new V1TBSCertificateGenerator(); tbsGen.setSerialNumber(new ASN1Integer(0x1)); tbsGen.setStartDate(new Time(new Date(100, 01, 01, 00, 00, 00))); tbsGen.setEndDate(new Time(new Date(130, 12, 31, 23, 59, 59))); tbsGen.setIssuer(new X500Name("CN=Cryptonit")); tbsGen.setSubject(new X500Name("CN=Cryptonit")); tbsGen.setSignature(algo); tbsGen.setSubjectPublicKeyInfo(ski); tbs = tbsGen.generateTBSCertificate(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(tbs); System.out.println("Build TBS"); System.out.println(toHex(bOut.toByteArray())); Base64.encode(bOut.toByteArray(), System.out); System.out.println(); return tbs; } private static ResponseAPDU sendAPDU(Simulator simulator, CommandAPDU command) { ResponseAPDU response; System.out.println(toHex(" > ", command.getBytes())); response = new ResponseAPDU(simulator.transmitCommand(command.getBytes())); System.out.println(toHex(" < ", response.getData()) + String.format("[sw=%04X l=%d]", response.getSW(), response.getData().length)); return response; } public static void main(String[] args) { ResponseAPDU response; Simulator simulator = new Simulator(); byte[] arg; byte[] appletAIDBytes = new byte[]{ (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00 }; short sw, le; AID appletAID = new AID(appletAIDBytes, (short) 0, (byte) appletAIDBytes.length); simulator.installApplet(appletAID, CryptonitApplet.class); System.out.println("Select Applet"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[]{ (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08 })); System.out.println("Management key authentication (part 1)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x03, 0x9B, new byte[]{ (byte) 0x7C, (byte) 0x02, (byte) 0x80, (byte) 0x00 })); arg = new byte[]{ (byte) 0x7C, (byte) 0x14, (byte) 0x80, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x81, (byte) 0x08, (byte) 0x2B, (byte) 0x65, (byte) 0x4B, (byte) 0x22, (byte) 0xB2, (byte) 0x2D, (byte) 0x99, (byte) 0x7F }; SecretKey key = new SecretKeySpec(new byte[]{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }, "DESede"); try { Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, key); cipher.doFinal(response.getData(), 4, 8, arg, 4); } catch (Exception ex) { ex.printStackTrace(System.out); } System.out.println("Management key authentication (part 2)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x03, 0x9B, arg)); System.out.println("Generate RSA key (9A)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x47, 0x00, 0x9A, new byte[]{ (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x07 })); arg = response.getData(); if (arg.length < 9 || arg[7] != 0x1 || arg[8] != 0x0) { System.err.println("Error modulus"); return; } byte[] n = new byte[257]; byte[] e = new byte[3]; short s = (short) (arg.length - 9); Util.arrayCopy(arg, (short) 9, n, (short) 1, s); sw = (short) response.getSW(); le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); arg = response.getData(); if(arg.length < (256 - s)) { System.err.println("Error remaining modulus"); return; } Util.arrayCopy(arg, (short) 0, n, (short) (s + 1), (short) (256 - s)); s = (short) (256 - s); if (arg[s] != (byte) 0x82 || arg[s + 1] != (byte) 0x3) { System.err.println("Error exponent"); return; } Util.arrayCopy(arg, (short) (s + 2), e, (short) 0, (short) 3); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); TBSCertificate tbs; try { RSAPublicKey rsa_pub = new RSAPublicKey(new BigInteger(n), new BigInteger(e)); AlgorithmIdentifier palgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), salgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE); tbs = createTBS(bOut, new SubjectPublicKeyInfo(palgo, rsa_pub), salgo); } catch (Exception ex) { ex.printStackTrace(System.err); return; } byte[] digest = null; try { MessageDigest md; md = MessageDigest.getInstance("SHA-256"); md.update(bOut.toByteArray()); digest = md.digest(); } catch (Exception ex) { ex.printStackTrace(System.err); return; } System.out.println("Verify PIN"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x20, 0x00, 0x80, new byte[]{ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 })); /* RSA signature request */ byte[] sig_request = new byte[266], sig_prefix = new byte[]{ (byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x06, (byte) 0x82, (byte) 0x00, (byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; Util.arrayFillNonAtomic(sig_request, (short) 0, (short) sig_request.length, (byte) 0xFF); Util.arrayCopy(sig_prefix, (short) 0, sig_request, (short) 0, (short) sig_prefix.length); sig_request[sig_request.length - digest.length - 1] = 0x0; Util.arrayCopy(digest, (short) 0, sig_request, (short) (sig_request.length - digest.length), (short) (digest.length)); System.out.println("RSA signature file (chained APDUs) first command"); arg = Arrays.copyOfRange(sig_request, 0, 255); response = sendAPDU(simulator, new CommandAPDU(0x10, 0x87, 0x07, 0x9A, arg)); System.out.println("RSA signature file (chained APDUs) second command"); arg = Arrays.copyOfRange(sig_request, 255, sig_request.length); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x07, 0x9A, arg)); arg = response.getData(); byte[] sig = new byte[256]; if (arg.length > 8 && arg[6] == 0x1 && arg[7] == 0x0) { s = (short) (arg.length - 8); Util.arrayCopy(arg, (short) 8, sig, (short) 0, s); } else { System.err.println("Error in signature"); return; } sw = (short) response.getSW(); le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); arg = response.getData(); Util.arrayCopy(arg, (short) 0, sig, s, (short) (256 - s)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbs); v.add(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE)); v.add(new DERBitString(sig)); byte [] crt = null; try { Certificate c = Certificate.getInstance(new DERSequence(v)); crt = c.getEncoded(); } catch (Exception ex) { ex.printStackTrace(System.out); } byte[] prefix = new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05, (byte) 0x53, (byte) 0x82 }, postfix = new byte[]{ (byte) 0x71, (byte) 0x01, (byte) 0x00, (byte) 0xFE, (byte) 0x00 }; short len = (short) (prefix.length + crt.length + 6 + postfix.length); byte[] buffer = new byte[len]; Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length); int off = prefix.length; buffer[off++] = (byte) (((crt.length + postfix.length + 4) >> 8) & 0xFF); buffer[off++] = (byte) ((crt.length + postfix.length + 4) & 0xFF); buffer[off++] = (byte) 0x70; buffer[off++] = (byte) 0x82; buffer[off++] = (byte) ((crt.length >> 8) & 0xFF); buffer[off++] = (byte) (crt.length & 0xFF); Util.arrayCopy(crt, (short) 0, buffer, (short) off, (short) crt.length); off += crt.length; Util.arrayCopy(postfix, (short) 0, buffer, (short) off, (short) postfix.length); int i = 1, left = buffer.length, sent = 0; while(left > 0) { System.out.println(String.format("Uploading certificate part %d", i++)); int cla = (left <= 255) ? 0x00 : 0x10; int sending = (left <= 255) ? left : 255; arg = Arrays.copyOfRange(buffer, sent, sent + sending); response = sendAPDU(simulator, new CommandAPDU(cla, 0xDB, 0x3F, 0xFF, arg)); sent += sending; left -= sending; } System.out.println("Read 0x5FC105 file (large)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xCB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05 })); while (((sw = (short) response.getSW()) & 0xFF00) == 0x6100) { le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); } System.out.println("Generate EC P256 key (9C)"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x47, 0x00, 0x9C, new byte[]{ (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x11 })); arg = response.getData(); if (arg.length < 9 || arg[3] != (byte) 0x86 || arg[4] != 0x41) { System.err.println("Error EC Public key"); return; } prefix = new byte[]{ (byte) 0x30, (byte) 0x59, (byte) 0x30, (byte) 0x13, (byte) 0x06, (byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x3D, (byte) 0x02, (byte) 0x01, (byte) 0x06, (byte) 0x08, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x3D, (byte) 0x03, (byte) 0x01, (byte) 0x07, (byte) 0x03, (byte) 0x42, (byte) 0x00 }; buffer = new byte[prefix.length + 65]; Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length); Util.arrayCopy(arg, (short) 5, buffer, (short) prefix.length, (short) 65); bOut = new ByteArrayOutputStream(); try { ASN1InputStream aIn = new ASN1InputStream(buffer); ASN1Sequence aSeq = (ASN1Sequence) aIn.readObject(); AlgorithmIdentifier palgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), salgo = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1, DERNull.INSTANCE); tbs = createTBS(bOut, new SubjectPublicKeyInfo(aSeq), salgo); } catch (Exception ex) { ex.printStackTrace(System.err); return; } digest = null; try { MessageDigest md; md = MessageDigest.getInstance("SHA1"); md.update(bOut.toByteArray()); digest = md.digest(); } catch (Exception ex) { ex.printStackTrace(System.err); return; } /* ECDSA signature request */ sig_prefix = new byte[]{ (byte) 0x7C, (byte) 0x18, (byte) 0x82, (byte) 0x00, (byte) 0x81, (byte) 0x14, }; sig_request = new byte[sig_prefix.length + 20]; Util.arrayCopy(sig_prefix, (short) 0, sig_request, (short) 0, (short) sig_prefix.length); Util.arrayCopy(digest, (short) 0, sig_request, (short) (sig_prefix.length), (short) (digest.length)); response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x07, 0x9C, sig_request)); arg = response.getData(); sig = Arrays.copyOfRange(arg, 4, arg.length); v = new ASN1EncodableVector(); v.add(tbs); v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1, DERNull.INSTANCE)); v.add(new DERBitString(sig)); crt = null; try { Certificate c = Certificate.getInstance(new DERSequence(v)); crt = c.getEncoded(); } catch (Exception ex) { ex.printStackTrace(System.out); } // Writing now to 5FC10A prefix = new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x0A, (byte) 0x53, (byte) 0x82 }; len = (short) (prefix.length + crt.length + 6 + postfix.length); buffer = new byte[len]; Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length); off = prefix.length; buffer[off++] = (byte) (((crt.length + postfix.length + 4) >> 8) & 0xFF); buffer[off++] = (byte) ((crt.length + postfix.length + 4) & 0xFF); buffer[off++] = (byte) 0x70; buffer[off++] = (byte) 0x82; buffer[off++] = (byte) ((crt.length >> 8) & 0xFF); buffer[off++] = (byte) (crt.length & 0xFF); Util.arrayCopy(crt, (short) 0, buffer, (short) off, (short) crt.length); off += crt.length; Util.arrayCopy(postfix, (short) 0, buffer, (short) off, (short) postfix.length); i = 1; left = buffer.length; sent = 0; while(left > 0) { System.out.println(String.format("Uploading certificate part %d", i++)); int cla = (left <= 255) ? 0x00 : 0x10; int sending = (left <= 255) ? left : 255; arg = Arrays.copyOfRange(buffer, sent, sent + sending); response = sendAPDU(simulator, new CommandAPDU(cla, 0xDB, 0x3F, 0xFF, arg)); sent += sending; left -= sending; } System.out.println("Read 0x5FC10A file"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xCB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x0A })); while (((sw = (short) response.getSW()) & 0xFF00) == 0x6100) { le = (short) (sw & 0xFF); System.out.println("Call GET RESPONSE"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le)); } System.out.println("Set Card Capabilities Container"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x07, (byte) 0x53, (byte) 0x33, (byte) 0xF0, (byte) 0x15, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x16, (byte) 0xFF, (byte) 0x02, (byte) 0x30, (byte) 0x1D, (byte) 0x9C, (byte) 0x5D, (byte) 0xB7, (byte) 0xA3, (byte) 0x87, (byte) 0xF1, (byte) 0xBE, (byte) 0x25, (byte) 0x1F, (byte) 0xB9, (byte) 0xFB, (byte) 0x1A, (byte) 0xF1, (byte) 0x01, (byte) 0x21, (byte) 0xF2, (byte) 0x01, (byte) 0x21, (byte) 0xF3, (byte) 0x00, (byte) 0xF4, (byte) 0x01, (byte) 0x00, (byte) 0xF5, (byte) 0x01, (byte) 0x10, (byte) 0xF6, (byte) 0x00, (byte) 0xF7, (byte) 0x00, (byte) 0xFA, (byte) 0x00, (byte) 0xFB, (byte) 0x00, (byte) 0xFC, (byte) 0x00, (byte) 0xFD, (byte) 0x00, (byte) 0xFE, (byte) 0x00 })); System.out.println("Set CHUID"); response = sendAPDU(simulator, new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, new byte[]{ (byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x02, (byte) 0x53, (byte) 0x3B, (byte) 0x30, (byte) 0x19, (byte) 0xD4, (byte) 0xE7, (byte) 0x39, (byte) 0xDA, (byte) 0x73, (byte) 0x9C, (byte) 0xED, (byte) 0x39, (byte) 0xCE, (byte) 0x73, (byte) 0x9D, (byte) 0x83, (byte) 0x68, (byte) 0x58, (byte) 0x21, (byte) 0x08, (byte) 0x42, (byte) 0x10, (byte) 0x84, (byte) 0x21, (byte) 0x38, (byte) 0x42, (byte) 0x10, (byte) 0xC3, (byte) 0xF5, (byte) 0x34, (byte) 0x10, (byte) 0xFB, (byte) 0x0C, (byte) 0xB0, (byte) 0x46, (byte) 0x75, (byte) 0x85, (byte) 0xD3, (byte) 0x8D, (byte) 0xE2, (byte) 0xA4, (byte) 0x96, (byte) 0x83, (byte) 0x5E, (byte) 0x0D, (byte) 0xA7, (byte) 0x78, (byte) 0x35, (byte) 0x08, (byte) 0x32, (byte) 0x30, (byte) 0x33, (byte) 0x30, (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x31, (byte) 0x3E, (byte) 0x00, (byte) 0xFE, (byte) 0x00 })); } }
package com.pedro.encoder.utils; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.os.Build; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CodecUtil { private static final String TAG = "CodecUtil"; public static final String H264_MIME = "video/avc"; public static final String H265_MIME = "video/hevc"; public static final String AAC_MIME = "audio/mp4a-latm"; public enum Force { FIRST_COMPATIBLE_FOUND, SOFTWARE, HARDWARE } public static List<String> showAllCodecsInfo() { List<MediaCodecInfo> mediaCodecInfoList = getAllCodecs(false); List<String> infos = new ArrayList<>(); for (MediaCodecInfo mediaCodecInfo : mediaCodecInfoList) { String info = " info += "Name: " + mediaCodecInfo.getName() + "\n"; for (String type : mediaCodecInfo.getSupportedTypes()) { info += "Type: " + type + "\n"; MediaCodecInfo.CodecCapabilities codecCapabilities = mediaCodecInfo.getCapabilitiesForType(type); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { info += "Max instances: " + codecCapabilities.getMaxSupportedInstances() + "\n"; } if (mediaCodecInfo.isEncoder()) { info += " MediaCodecInfo.EncoderCapabilities encoderCapabilities = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { encoderCapabilities = codecCapabilities.getEncoderCapabilities(); info += "Complexity range: " + encoderCapabilities.getComplexityRange().getLower() + " - " + encoderCapabilities.getComplexityRange().getUpper() + "\n"; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { info += "Quality range: " + encoderCapabilities.getQualityRange().getLower() + " - " + encoderCapabilities.getQualityRange().getUpper() + "\n"; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { info += "CBR supported: " + encoderCapabilities.isBitrateModeSupported( MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR) + "\n"; info += "VBR supported: " + encoderCapabilities.isBitrateModeSupported( MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR) + "\n"; info += "CQ supported: " + encoderCapabilities.isBitrateModeSupported( MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ) + "\n"; } info += " } else { info += " info += " } if (codecCapabilities.colorFormats != null && codecCapabilities.colorFormats.length > 0) { info += " info += "Supported colors: \n"; for (int color : codecCapabilities.colorFormats) info += color + "\n"; for (MediaCodecInfo.CodecProfileLevel profile : codecCapabilities.profileLevels) info += "Profile: " + profile.profile + ", level: " + profile.level + "\n"; MediaCodecInfo.VideoCapabilities videoCapabilities = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { videoCapabilities = codecCapabilities.getVideoCapabilities(); info += "Bitrate range: " + videoCapabilities.getBitrateRange().getLower() + " - " + videoCapabilities.getBitrateRange().getUpper() + "\n"; info += "Frame rate range: " + videoCapabilities.getSupportedFrameRates().getLower() + " - " + videoCapabilities.getSupportedFrameRates().getUpper() + "\n"; info += "Width range: " + videoCapabilities.getSupportedWidths().getLower() + " - " + videoCapabilities.getSupportedWidths().getUpper() + "\n"; info += "Height range: " + videoCapabilities.getSupportedHeights().getLower() + " - " + videoCapabilities.getSupportedHeights().getUpper() + "\n"; } info += " } else { info += " for (MediaCodecInfo.CodecProfileLevel profile : codecCapabilities.profileLevels) info += "Profile: " + profile.profile + ", level: " + profile.level + "\n"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { MediaCodecInfo.AudioCapabilities audioCapabilities = codecCapabilities.getAudioCapabilities(); info += "Bitrate range: " + audioCapabilities.getBitrateRange().getLower() + " - " + audioCapabilities.getBitrateRange().getUpper() + "\n"; info += "Channels supported: " + audioCapabilities.getMaxInputChannelCount() + "\n"; try { if (audioCapabilities.getSupportedSampleRates() != null && audioCapabilities.getSupportedSampleRates().length > 0) { info += "Supported sample rate: \n"; for (int sr : audioCapabilities.getSupportedSampleRates()) info += sr + "\n"; } } catch (Exception e) { } } info += " } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { info += "Max instances: " + codecCapabilities.getMaxSupportedInstances() + "\n"; } } info += " infos.add(info); } return infos; } public static List<MediaCodecInfo> getAllCodecs(boolean filterBroken) { List<MediaCodecInfo> mediaCodecInfoList = new ArrayList<>(); if (Build.VERSION.SDK_INT >= 21) { MediaCodecList mediaCodecList = new MediaCodecList(MediaCodecList.ALL_CODECS); MediaCodecInfo[] mediaCodecInfos = mediaCodecList.getCodecInfos(); mediaCodecInfoList.addAll(Arrays.asList(mediaCodecInfos)); } else { int count = MediaCodecList.getCodecCount(); for (int i = 0; i < count; i++) { MediaCodecInfo mci = MediaCodecList.getCodecInfoAt(i); mediaCodecInfoList.add(mci); } } return filterBroken ? filterBrokenCodecs(mediaCodecInfoList) : mediaCodecInfoList; } public static List<MediaCodecInfo> getAllHardwareEncoders(String mime) { List<MediaCodecInfo> mediaCodecInfoList = getAllEncoders(mime); List<MediaCodecInfo> mediaCodecInfoHardware = new ArrayList<>(); for (MediaCodecInfo mediaCodecInfo : mediaCodecInfoList) { if (isHardwareAccelerated(mediaCodecInfo)) { mediaCodecInfoHardware.add(mediaCodecInfo); } } return mediaCodecInfoHardware; } public static List<MediaCodecInfo> getAllHardwareDecoders(String mime) { List<MediaCodecInfo> mediaCodecInfoList = getAllDecoders(mime); List<MediaCodecInfo> mediaCodecInfoHardware = new ArrayList<>(); for (MediaCodecInfo mediaCodecInfo : mediaCodecInfoList) { if (isHardwareAccelerated(mediaCodecInfo)) { mediaCodecInfoHardware.add(mediaCodecInfo); } } return mediaCodecInfoHardware; } public static List<MediaCodecInfo> getAllSoftwareEncoders(String mime) { List<MediaCodecInfo> mediaCodecInfoList = getAllEncoders(mime); List<MediaCodecInfo> mediaCodecInfoSoftware = new ArrayList<>(); for (MediaCodecInfo mediaCodecInfo : mediaCodecInfoList) { if (isSoftwareOnly(mediaCodecInfo)) { mediaCodecInfoSoftware.add(mediaCodecInfo); } } return mediaCodecInfoSoftware; } public static List<MediaCodecInfo> getAllSoftwareDecoders(String mime) { List<MediaCodecInfo> mediaCodecInfoList = getAllDecoders(mime); List<MediaCodecInfo> mediaCodecInfoSoftware = new ArrayList<>(); for (MediaCodecInfo mediaCodecInfo : mediaCodecInfoList) { if (isSoftwareOnly(mediaCodecInfo)) { mediaCodecInfoSoftware.add(mediaCodecInfo); } } return mediaCodecInfoSoftware; } /** * choose the video encoder by mime. */ public static List<MediaCodecInfo> getAllEncoders(String mime) { List<MediaCodecInfo> mediaCodecInfoList = new ArrayList<>(); List<MediaCodecInfo> mediaCodecInfos = getAllCodecs(true); for (MediaCodecInfo mci : mediaCodecInfos) { if (!mci.isEncoder()) { continue; } String[] types = mci.getSupportedTypes(); for (String type : types) { if (type.equalsIgnoreCase(mime)) { mediaCodecInfoList.add(mci); } } } return mediaCodecInfoList; } /** * choose the video encoder by mime. */ public static List<MediaCodecInfo> getAllDecoders(String mime) { List<MediaCodecInfo> mediaCodecInfoList = new ArrayList<>(); List<MediaCodecInfo> mediaCodecInfos = getAllCodecs(true); for (MediaCodecInfo mci : mediaCodecInfos) { if (mci.isEncoder()) { continue; } String[] types = mci.getSupportedTypes(); for (String type : types) { if (type.equalsIgnoreCase(mime)) { mediaCodecInfoList.add(mci); } } } return mediaCodecInfoList; } private static boolean isHardwareAccelerated(MediaCodecInfo codecInfo) { if (Build.VERSION.SDK_INT >= 29) { return codecInfo.isHardwareAccelerated(); } // codecInfo.isHardwareAccelerated() != codecInfo.isSoftwareOnly() is not necessarily true. // However, we assume this to be true as an approximation. return !isSoftwareOnly(codecInfo); } private static boolean isSoftwareOnly(MediaCodecInfo mediaCodecInfo) { if (Build.VERSION.SDK_INT > 29) { return mediaCodecInfo.isSoftwareOnly(); } String name = mediaCodecInfo.getName().toLowerCase(); if (name.startsWith("arc.")) { // App Runtime for Chrome (ARC) codecs return false; } return name.startsWith("omx.google.") || name.startsWith("omx.ffmpeg.") || (name.startsWith("omx.sec.") && name.contains(".sw.")) || name.equals("omx.qcom.video.decoder.hevcswvdec") || name.startsWith("c2.android.") || name.startsWith("c2.google.") || (!name.startsWith("omx.") && !name.startsWith("c2.")); } /** * Filter broken codecs by name and device model. * * Note: * There is no way to know broken encoders so we will check by name and device. * Please add your encoder to this method if you detect one. * * @param codecs All device codecs * @return a list without broken codecs */ private static List<MediaCodecInfo> filterBrokenCodecs(List<MediaCodecInfo> codecs) { List<MediaCodecInfo> listFilter = new ArrayList<>(); for (MediaCodecInfo mediaCodecInfo : codecs) { if (isValid(mediaCodecInfo.getName())) { listFilter.add(mediaCodecInfo); } } return listFilter; } /** * For now, none broken codec reported. */ private static boolean isValid(String name) { return true; } }
package com.jme3.system.android; import android.app.Activity; import android.content.Context; import android.graphics.PixelFormat; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView.EGLConfigChooser; import android.view.SurfaceHolder; import com.jme3.app.AndroidHarness; import com.jme3.app.Application; import com.jme3.input.JoyInput; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.TouchInput; import com.jme3.input.android.AndroidInput; import com.jme3.input.controls.TouchTrigger; import com.jme3.input.dummy.DummyKeyInput; import com.jme3.input.dummy.DummyMouseInput; import com.jme3.renderer.android.OGLESShaderRenderer; import com.jme3.system.AppSettings; import com.jme3.system.JmeContext; import com.jme3.system.SystemListener; import com.jme3.system.Timer; import com.jme3.system.android.AndroidConfigChooser.ConfigType; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.opengles.GL10; public class OGLESContext implements JmeContext, GLSurfaceView.Renderer { private static final Logger logger = Logger.getLogger(OGLESContext.class.getName()); protected final AtomicBoolean created = new AtomicBoolean(false); protected final AtomicBoolean renderable = new AtomicBoolean(false); protected final AtomicBoolean needClose = new AtomicBoolean(false); protected final AppSettings settings = new AppSettings(true); /* >= OpenGL ES 2.0 (Android 2.2+) */ protected OGLESShaderRenderer renderer; protected Timer timer; protected SystemListener listener; protected boolean wasActive = false; protected boolean autoFlush = true; protected AndroidInput view; private long milliStart; private long milliDelta; protected int frameRate = 33; //protected int minFrameDuration = 1000 / frameRate; // Set a max FPS of 33 protected int minFrameDuration = 0; // No FPS cap /** * EGL_RENDERABLE_TYPE: EGL_OPENGL_ES_BIT = OpenGL ES 1.0 | EGL_OPENGL_ES2_BIT = OpenGL ES 2.0 */ protected int clientOpenGLESVersion = 1; protected boolean verboseLogging = false; final private String ESCAPE_EVENT = "TouchEscape"; public OGLESContext() { } @Override public Type getType() { return Type.Display; } /** * <code>createView</code> * @param activity The Android activity which is parent for the GLSurfaceView * @return GLSurfaceView The newly created view */ public GLSurfaceView createView(Activity activity) { return createView(new AndroidInput(activity)); } /** * <code>createView</code> * @param view The Android input which will be used as the GLSurfaceView for this context * @return GLSurfaceView The newly created view */ public GLSurfaceView createView(AndroidInput view) { return createView(view, ConfigType.FASTEST, false); } /** * <code>createView</code> initializes the GLSurfaceView * @param view The Android input which will be used as the GLSurfaceView for this context * @param configType ConfigType.FASTEST (Default) | ConfigType.LEGACY | ConfigType.BEST * @param eglConfigVerboseLogging if true show all found configs * @return GLSurfaceView The newly created view */ public GLSurfaceView createView(AndroidInput view, ConfigType configType, boolean eglConfigVerboseLogging) { return createView(view, configType, eglConfigVerboseLogging, false); } public GLSurfaceView createView(AndroidInput view, ConfigType configType, boolean eglConfigVerboseLogging, boolean antialias) { // Start to set up the view this.view = view; verboseLogging = eglConfigVerboseLogging; if (configType == ConfigType.LEGACY) { // Hardcoded egl setup clientOpenGLESVersion = 2; view.setEGLContextClientVersion(2); //RGB565, Depth16 // view.setEGLConfigChooser(5, 6, 5, 0, 16, 0); logger.info("ConfigType.LEGACY using RGB565"); view.setEGLConfigChooser(8, 8, 8, 8, 16, 0); view.getHolder().setFormat(PixelFormat.TRANSLUCENT); view.setZOrderOnTop(true); } else { EGL10 egl = (EGL10) EGLContext.getEGL(); EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; if (egl.eglInitialize(display, version) == true) { logger.info("Display EGL Version: " + version[0] + "." + version[1]); } // Create a config chooser AndroidConfigChooser configChooser = new AndroidConfigChooser(configType, eglConfigVerboseLogging, antialias); // Init chooser if (!configChooser.findConfig(egl, display)) { logger.severe("Unable to find suitable EGL config"); } clientOpenGLESVersion = configChooser.getClientOpenGLESVersion(); if (clientOpenGLESVersion < 2) { logger.severe("OpenGL ES 2.0 is not supported on this device"); } if (display != null) egl.eglTerminate(display); /* * Requesting client version from GLSurfaceView which is extended by * AndroidInput. */ view.setEGLContextClientVersion(clientOpenGLESVersion); // view.setEGLConfigChooser(configChooser); // view.getHolder().setFormat(configChooser.getPixelFormat()); view.setEGLConfigChooser(8, 8, 8, 8, 16, 0); view.getHolder().setFormat(PixelFormat.TRANSLUCENT); view.setZOrderOnTop(true); } view.setFocusableInTouchMode(true); view.setFocusable(true); view.getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU); view.setRenderer(this); return view; } // renderer:initialize @Override public void onSurfaceCreated(GL10 gl, EGLConfig cfg) { if (created.get() && renderer != null) { renderer.resetGLObjects(); } else { if (!created.get()) { logger.info("GL Surface created, doing JME3 init"); initInThread(); } else { logger.warning("GL Surface already created"); } } } protected void initInThread() { created.set(true); logger.info("OGLESContext create"); logger.info("Running on thread: "+Thread.currentThread().getName()); final Context ctx = this.view.getContext(); // Setup unhandled Exception Handler if (ctx instanceof AndroidHarness) { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread thread, Throwable thrown) { ((AndroidHarness)ctx).handleError("Exception thrown in " + thread.toString(), thrown); } }); } else { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread thread, Throwable thrown) { listener.handleError("Exception thrown in " + thread.toString(), thrown); } }); } if (clientOpenGLESVersion < 2) { throw new UnsupportedOperationException("OpenGL ES 2.0 is not supported on this device"); } timer = new AndroidTimer(); renderer = new OGLESShaderRenderer(); // renderer.setUseVA(true); renderer.setVerboseLogging(verboseLogging); renderer.initialize(); listener.initialize(); // Setup exit hook if (ctx instanceof AndroidHarness) { Application app = ((AndroidHarness)ctx).getJmeApplication(); if (app.getInputManager() != null) { app.getInputManager().addMapping(ESCAPE_EVENT, new TouchTrigger(TouchInput.KEYCODE_BACK)); app.getInputManager().addListener((AndroidHarness)ctx, new String[]{ESCAPE_EVENT}); } } needClose.set(false); renderable.set(true); } /** * De-initialize in the OpenGL thread. */ protected void deinitInThread() { if (renderable.get()) { created.set(false); if (renderer != null) renderer.cleanup(); listener.destroy(); listener = null; renderer = null; timer = null; // do android specific cleaning here logger.info("Display destroyed."); renderable.set(false); } } protected void applySettingsToRenderer(OGLESShaderRenderer renderer, AppSettings settings) { logger.warning("setSettings.USE_VA: [" + settings.getBoolean("USE_VA") + "]"); logger.warning("setSettings.VERBOSE_LOGGING: [" + settings.getBoolean("VERBOSE_LOGGING") + "]"); renderer.setUseVA(settings.getBoolean("USE_VA")); renderer.setVerboseLogging(settings.getBoolean("VERBOSE_LOGGING")); } protected void applySettings(AppSettings settings) { setSettings(settings); if (renderer != null) applySettingsToRenderer(renderer, this.settings); } @Override public void setSettings(AppSettings settings) { this.settings.copyFrom(settings); } @Override public void setSystemListener(SystemListener listener){ this.listener = listener; } @Override public AppSettings getSettings() { return settings; } @Override public com.jme3.renderer.Renderer getRenderer() { return renderer; } @Override public MouseInput getMouseInput() { return new DummyMouseInput(); } @Override public KeyInput getKeyInput() { return new DummyKeyInput(); } @Override public JoyInput getJoyInput() { return null; } @Override public TouchInput getTouchInput() { return view; } @Override public Timer getTimer() { return timer; } @Override public void setTitle(String title) { } @Override public boolean isCreated() { return created.get(); } @Override public void setAutoFlushFrames(boolean enabled) { this.autoFlush = enabled; } // SystemListener:reshape @Override public void onSurfaceChanged(GL10 gl, int width, int height) { logger.info("GL Surface changed, width: " + width + " height: " + height); settings.setResolution(width, height); listener.reshape(width, height); } // SystemListener:update @Override public void onDrawFrame(GL10 gl) { if (needClose.get()) { deinitInThread(); return; } if (renderable.get()) { if (!created.get()) throw new IllegalStateException("onDrawFrame without create"); milliStart = System.currentTimeMillis(); listener.update(); if (autoFlush) { renderer.onFrame(); } milliDelta = System.currentTimeMillis() - milliStart; // Enforce a FPS cap if (milliDelta < minFrameDuration) { //logger.log(Level.INFO, "Time per frame {0}", milliDelta); try { Thread.sleep(minFrameDuration - milliDelta); } catch (InterruptedException e) { } } } // if (renderer.adreno_finish_bug) { // GLES20.glFinish(); } @Override public boolean isRenderable() { return renderable.get(); } @Override public void create(boolean waitFor) { if (waitFor) waitFor(true); } public void create() { create(false); } @Override public void restart() { } @Override public void destroy(boolean waitFor) { needClose.set(true); if (waitFor) { waitFor(false); } else { listener.destroy(); listener = null; } } public void destroy() { destroy(true); } protected void waitFor(boolean createdVal) { while (renderable.get() != createdVal){ try { Thread.sleep(10); } catch (InterruptedException ex) { } } } public int getClientOpenGLESVersion() { return clientOpenGLESVersion; } public int getMinFrameDuration() { return minFrameDuration; } public void setMinFrameDuration(int minFrameDuration) { this.minFrameDuration = minFrameDuration; } }
package io.realm; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import io.realm.internal.Table; //NOTE: We may decide it is cleaner to NOT subclass ArrayAdapter public class RealmArrayAdapter<E extends RealmObject> extends ArrayAdapter<E> { public static final String TAG = RealmArrayAdapter.class.getName(); private int resId = -1; private int fieldId = -1; private boolean notifyOnChange = true; private RealmResults<E> rList; private Context context = null; private LayoutInflater mInflater = null; private ArrayFilter mFilter; public RealmArrayAdapter(Context context, int resId, RealmResults<E> rList) { this(context, resId, -1, rList); } public RealmArrayAdapter(Context context, int resId, int fieldId, RealmResults<E> rList) { super(context, resId, fieldId, rList); this.context = context; this.resId = resId; this.fieldId = fieldId; this.rList = rList; //Temporary solution for the fact that we can't create a RealmResults if (rList == null) { throw new NullPointerException("Can't use RealmResults with a null list"); } mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return rList.size(); } @Override public E getItem(int i) { super.getItem(i); if (rList.size() > i) { return (E) rList.get(i); } else { return null; } } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View v, ViewGroup viewGroup) { View view; TextView text; if (v == null) { // Adapter fails if resId does not exist view = mInflater.inflate(resId, null, false); } else { view = v; } try { if (fieldId == 0) { text = (TextView) view; } else { text = (TextView) view.findViewById(fieldId); } } catch (ClassCastException e) { Log.e(TAG, "You must supply a resource ID for a TextView"); throw new IllegalStateException( "RealmArrayAdapter requires the resource ID to be a TextView", e); } RealmObject item = getItem(i); if (item instanceof CharSequence) { text.setText((CharSequence) item); } else { text.setText(item.toString()); } return view; } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); notifyOnChange = true; } public void setNotifyOnChange(boolean notifyOnChange) { this.notifyOnChange = notifyOnChange; } // RealmLists are thread safe, so no locking should be required. public void add(E object) { // TODO: Need solution for ArrayAdapter (add() is deprecated) if (notifyOnChange) notifyDataSetChanged(); } public void addAll(Collection<? extends E> collection) { rList.addAll(collection); if (notifyOnChange) notifyDataSetChanged(); } public void addAll(E... items) { for (E it : items) { // TODO: Need solution for ArrayAdapter (add() is deprecated) } if (notifyOnChange) notifyDataSetChanged(); } public void insert(E object, int index) { rList.add(index, object); if (notifyOnChange) notifyDataSetChanged(); } public void remove(E object) { rList.remove(object); if (notifyOnChange) notifyDataSetChanged(); } public void clear() { rList.clear(); if (notifyOnChange) notifyDataSetChanged(); } public void sort(Comparator<? super E> comparator) { // Collections.sort is a static helper method Collections.sort(rList, comparator); if (notifyOnChange) notifyDataSetChanged(); } public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } private class ArrayFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (prefix == null || prefix.length() == 0) { results.values = rList; results.count = rList.size(); } else { RealmObject obj = rList.first(); Table t = obj.getRealm().getTable(obj.getClass()); // We assume column one for a table comparison RealmResults<E> filteredResults = rList.where().beginsWith(t.getColumnName(0), prefix.toString().toLowerCase().toString(), false).findAll(); results.values = filteredResults; results.count = filteredResults.size(); } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } }
package hudson.remoting; import hudson.remoting.ExportTable.ExportList; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.Vector; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents a communication channel to the remote peer. * * <p> * A {@link Channel} is a mechanism for two JVMs to communicate over * bi-directional {@link InputStream}/{@link OutputStream} pair. * {@link Channel} represents an endpoint of the stream, and thus * two {@link Channel}s are always used in a pair. * * <p> * Communication is established as soon as two {@link Channel} instances * are created at the end fo the stream pair * until the stream is terminated via {@link #close()}. * * <p> * The basic unit of remoting is an executable {@link Callable} object. * An application can create a {@link Callable} object, and execute it remotely * by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method. * * <p> * In this sense, {@link Channel} is a mechanism to delegate/offload computation * to other JVMs and somewhat like an agent system. This is bit different from * remoting technologies like CORBA or web services, where the server exposes a * certain functionality that clients invoke. * * <p> * {@link Callable} object, as well as the return value / exceptions, * are transported by using Java serialization. All the necessary class files * are also shipped over {@link Channel} on-demand, so there's no need to * pre-deploy such classes on both JVMs. * * * <h2>Implementor's Note</h2> * <p> * {@link Channel} builds its features in a layered model. Its higher-layer * features are built on top of its lower-layer features, and they * are called layer-0, layer-1, etc. * * <ul> * <li> * <b>Layer 0</b>: * See {@link Command} for more details. This is for higher-level features, * and not likely useful for applications directly. * <li> * <b>Layer 1</b>: * See {@link Request} for more details. This is for higher-level features, * and not likely useful for applications directly. * </ul> * * @author Kohsuke Kawaguchi */ public class Channel implements VirtualChannel { private final ObjectInputStream ois; private final ObjectOutputStream oos; private final String name; /*package*/ final ExecutorService executor; /** * If true, the incoming link is already shut down, * and reader is already terminated. */ private volatile boolean inClosed = false; /** * If true, the outgoing link is already shut down, * and no command can be sent. */ private volatile boolean outClosed = false; /*package*/ final Map<Integer,Request<?,?>> pendingCalls = new Hashtable<Integer,Request<?,?>>(); /** * Records the {@link Request}s being executed on this channel, sent by the remote peer. */ /*package*/ final Map<Integer,Request<?,?>> executingCalls = Collections.synchronizedMap(new Hashtable<Integer,Request<?,?>>()); /** * {@link ClassLoader}s that are proxies of the remote classloaders. */ /*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this); /** * Objects exported via {@link #export(Class, Object)}. */ private final ExportTable<Object> exportedObjects = new ExportTable<Object>(); /** * Registered listeners. */ private final Vector<Listener> listeners = new Vector<Listener>(); private int gcCounter; public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException { this(name,exec,is,os,null); } /** * Creates a new channel. * * @param name * Human readable name of this channel. Used for debug/logging. Can be anything. * @param exec * Commands sent from the remote peer will be executed by using this {@link Executor}. * @param is * Stream connected to the remote peer. * @param os * Stream connected to the remote peer. * @param header * If non-null, receive the portion of data in <tt>is</tt> before * the data goes into the "binary mode". This is useful * when the established communication channel might include some data that might * be useful for debugging/trouble-shooting. */ public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException { this.name = name; this.executor = exec; // write the magic preamble. // certain communication channel, such as forking JVM via ssh, // may produce some garbage at the beginning (for example a remote machine // might print some warning before the program starts outputting its own data.) // so use magic preamble and discard all the data up to that to improve robustness. os.write(new byte[]{0,0,0,0}); // preamble this.oos = new ObjectOutputStream(os); oos.flush(); // make sure that stream header is sent to the other end. avoids dead-lock {// read the input until we hit preamble int ch; int count=0; while(true) { ch = is.read(); if(ch==-1) { throw new EOFException("unexpected stream termination"); } if(ch==0) { count++; if(count==4) break; } else { if(header!=null) header.write(ch); count=0; } } } this.ois = new ObjectInputStream(is); new ReaderThread(name).start(); } /** * Callback "interface" for changes in the state of {@link Channel}. */ public static abstract class Listener { /** * When the channel was closed normally or abnormally due to an error. * * @param cause * if the channel is closed abnormally, this parameter * represents an exception that has triggered it. */ public void onClosed(Channel channel, IOException cause) {} } /** * Sends a command to the remote end and executes it there. * * <p> * This is the lowest layer of abstraction in {@link Channel}. * {@link Command}s are executed on a remote system in the order they are sent. */ /*package*/ synchronized void send(Command cmd) throws IOException { if(outClosed) throw new IOException("already closed"); if(logger.isLoggable(Level.FINE)) logger.fine("Send "+cmd); Channel old = Channel.setCurrent(this); try { oos.writeObject(cmd); oos.flush(); // make sure the command reaches the other end. } finally { Channel.setCurrent(old); } oos.reset(); } /** * {@inheritDoc} */ public <T> T export(Class<T> type, T instance) { return export(type,instance,true); } /** * @param userProxy * If true, the returned proxy will be capable to handle classes * defined in the user classloader as parameters and return values. * Such proxy relies on {@link RemoteClassLoader} and related mechanism, * so it's not usable for implementing lower-layer services that are * used by {@link RemoteClassLoader}. * * To create proxies for objects inside remoting, pass in false. */ /*package*/ <T> T export(Class<T> type, T instance, boolean userProxy) { if(instance==null) return null; // every so often perform GC on the remote system so that // unused RemoteInvocationHandler get released, which triggers // unexport operation. if((++gcCounter)%10000==0) try { send(new GCCommand()); } catch (IOException e) { // for compatibility reason we can't change the export method signature logger.log(Level.WARNING, "Unable to send GC command",e); } // proxy will unexport this instance when it's GC-ed on the remote machine. final int id = export(instance); return type.cast(Proxy.newProxyInstance( type.getClassLoader(), new Class[]{type}, new RemoteInvocationHandler(id,userProxy))); } /*package*/ int export(Object instance) { return exportedObjects.export(instance); } /*package*/ int export(Object instance, boolean automaticUnexport) { return exportedObjects.export(instance,automaticUnexport); } /*package*/ Object getExportedObject(int oid) { return exportedObjects.get(oid); } /*package*/ void unexport(int id) { exportedObjects.unexport(id); } /** * {@inheritDoc} */ public <V,T extends Throwable> V call(Callable<V,T> callable) throws IOException, T, InterruptedException { UserRequest<V,T> request=null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); // re-wrap the exception so that we can capture the stack trace of the caller. } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call failed"); x.initCause(e); throw x; } finally { // since this is synchronous operation, when the round trip is over // we assume all the exported objects are out of scope. // (that is, the operation shouldn't spawn a new thread or altter // global state in the remote system. if(request!=null) request.releaseExports(); } } /** * {@inheritDoc} */ public <V,T extends Throwable> Future<V> callAsync(final Callable<V,T> callable) throws IOException { final Future<UserResponse<V,T>> f = new UserRequest<V,T>(this, callable).callAsync(this); return new FutureAdapter<V,UserResponse<V,T>>(f) { protected V adapt(UserResponse<V,T> r) throws ExecutionException { try { return r.retrieve(Channel.this, UserRequest.getClassLoader(callable)); } catch (Throwable t) {// really means catch(T t) throw new ExecutionException(t); } } }; } /** * Aborts the connection in response to an error. */ protected synchronized void terminate(IOException e) { outClosed=inClosed=true; try { synchronized(pendingCalls) { for (Request<?,?> req : pendingCalls.values()) req.abort(e); pendingCalls.clear(); } } finally { notifyAll(); for (Listener l : listeners.toArray(new Listener[listeners.size()])) l.onClosed(this,e); } } /** * Registers a new {@link Listener}. * * @see #removeListener(Listener) */ public void addListener(Listener l) { listeners.add(l); } /** * Removes a listener. * * @return * false if the given listener has not been registered to begin with. */ public boolean removeListener(Listener l) { return listeners.remove(l); } /** * Waits for this {@link Channel} to be closed down. * * The close-down of a {@link Channel} might be initiated locally or remotely. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. */ public synchronized void join() throws InterruptedException { while(!inClosed || !outClosed) wait(); } /** * Notifies the remote peer that we are closing down. * * Execution of this command also triggers the {@link ReaderThread} to shut down * and quit. The {@link CloseCommand} is always the last command to be sent on * {@link ObjectOutputStream}, and it's the last command to be read. */ private static final class CloseCommand extends Command { protected void execute(Channel channel) { try { channel.close(); channel.terminate(new OrderlyShutdown(createdAt)); } catch (IOException e) { logger.log(Level.SEVERE,"close command failed on "+channel.name,e); logger.log(Level.INFO,"close command created at",createdAt); } } public String toString() { return "close"; } } /** * Signals the orderly shutdown of the channel, but captures * where the termination was initiated as a nested exception. */ private static final class OrderlyShutdown extends IOException { private OrderlyShutdown(Throwable cause) { super(cause.getMessage()); initCause(cause); } private static final long serialVersionUID = 1L; } /** * {@inheritDoc} */ public synchronized void close() throws IOException { if(outClosed) return; // already closed send(new CloseCommand()); outClosed = true; // last command sent. no further command allowed. lock guarantees that no command will slip inbetween try { oos.close(); } catch (IOException e) { // there's a race condition here. // the remote peer might have already responded to the close command // and closed the connection, in which case our close invocation // could fail with errors like // "java.io.IOException: The pipe is being closed" // so let's ignore this error. } // termination is done by CloseCommand when we received it. } public String toString() { return super.toString()+":"+name; } /** * Dumps the list of exported objects and their allocation traces to the given output. */ public void dumpExportTable(PrintWriter w) throws IOException { exportedObjects.dump(w); } public ExportList startExportRecording() { return exportedObjects.startRecording(); } private final class ReaderThread extends Thread { public ReaderThread(String name) { super("Channel reader thread: "+name); } public void run() { Command cmd = null; try { while(!inClosed) { try { Channel old = Channel.setCurrent(Channel.this); try { cmd = (Command)ois.readObject(); } finally { Channel.setCurrent(old); } } catch (ClassNotFoundException e) { logger.log(Level.SEVERE, "Unable to read a command",e); } if(logger.isLoggable(Level.FINE)) logger.fine("Received "+cmd); try { cmd.execute(Channel.this); } catch (Throwable t) { logger.log(Level.SEVERE, "Failed to execute command "+cmd,t); logger.log(Level.SEVERE, "This command is created here",cmd.createdAt); } } ois.close(); } catch (IOException e) { logger.log(Level.SEVERE, "I/O error in channel "+name,e); terminate(e); } } } /*package*/ static Channel setCurrent(Channel channel) { Channel old = CURRENT.get(); CURRENT.set(channel); return old; } /** * This method can be invoked during the serialization/deserialization of * objects when they are transferred to the remote {@link Channel}, * as well as during {@link Callable#call()} is invoked. * * @return null * if the calling thread is not performing serialization. */ public static Channel current() { return CURRENT.get(); } /** * Remembers the current "channel" associated for this thread. */ private static final ThreadLocal<Channel> CURRENT = new ThreadLocal<Channel>(); private static final Logger logger = Logger.getLogger(Channel.class.getName()); }
package mondrian.test; import mondrian.olap.*; import mondrian.rolap.RolapCube; import mondrian.rolap.RolapStar; import mondrian.rolap.RolapLevel; import mondrian.rolap.sql.SqlQuery; import javax.sql.DataSource; import java.sql.Statement; import java.sql.ResultSet; /** * Test generation of SQL to access the fact table data underlying an MDX * result set. * * @author jhyde * @since May 10, 2006 * @version $Id$ */ public class DrillThroughTest extends FoodMartTestCase { public DrillThroughTest() { super(); } public DrillThroughTest(String name) { super(name); } public void testTrivalCalcMemberDrillThrough() throws Exception { Result result = executeQuery( "WITH MEMBER [Measures].[Formatted Unit Sales] AS '[Measures].[Unit Sales]', FORMAT_STRING='$ "SELECT {[Measures].[Unit Sales], [Measures].[Formatted Unit Sales]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); final Cell cell = result.getCell(new int[]{0, 0}); assertTrue(cell.canDrillThrough()); String sql = cell.getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `product_class`.`product_family` as `Product Family`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `product_class` =as= `product_class`," + " `product` =as= `product` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink' " + "order by `time_by_day`.`the_year` ASC," + " `product_class`.`product_family` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 7978); // Can drill through a trivial calc member. final Cell calcCell = result.getCell(new int[]{1, 0}); assertTrue(calcCell.canDrillThrough()); sql = calcCell.getDrillThroughSQL(false); assertNotNull(sql); expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `product_class`.`product_family` as `Product Family`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `product_class` =as= `product_class`," + " `product` =as= `product` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink' " + "order by `time_by_day`.`the_year` ASC," + " `product_class`.`product_family` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 7978); assertEquals(calcCell.getDrillThroughCount(), 7978); } public void testDrillThrough() throws Exception { Result result = executeQuery( "WITH MEMBER [Measures].[Price] AS '[Measures].[Store Sales] / [Measures].[Unit Sales]'" + nl + "SELECT {[Measures].[Unit Sales], [Measures].[Price]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); final Cell cell = result.getCell(new int[]{0, 0}); assertTrue(cell.canDrillThrough()); String sql = cell.getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `product_class`.`product_family` as `Product Family`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `product_class` =as= `product_class`," + " `product` =as= `product` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink' " + "order by `time_by_day`.`the_year` ASC," + " `product_class`.`product_family` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 7978); // Cannot drill through a calc member. final Cell calcCell = result.getCell(new int[]{1, 1}); assertFalse(calcCell.canDrillThrough()); sql = calcCell.getDrillThroughSQL(false); assertNull(sql); } private String getNameExp( Result result, String hierName, String levelName) { final Cube cube = result.getQuery().getCube(); RolapStar star = ((RolapCube) cube).getStar(); Hierarchy h = cube.lookupHierarchy( new Id.Segment(hierName, Id.Quoting.UNQUOTED), false); if (h == null) { return null; } for (Level l : h.getLevels()) { if (l.getName().equals(levelName)) { MondrianDef.Expression exp = ((RolapLevel) l).getNameExp(); String nameExpStr = exp.getExpression(star.getSqlQuery()); nameExpStr = nameExpStr.replace('"', '`') ; return nameExpStr; } } return null; } public void testDrillThrough2() throws Exception { Result result = executeQuery( "WITH MEMBER [Measures].[Price] AS '[Measures].[Store Sales] / [Measures].[Unit Sales]'" + nl + "SELECT {[Measures].[Unit Sales], [Measures].[Price]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(true); String nameExpStr = getNameExp(result, "Customers", "Name"); String expectedSql = "select `store`.`store_country` as `Store Country`," + " `store`.`store_state` as `Store State`," + " `store`.`store_city` as `Store City`," + " `store`.`store_name` as `Store Name`," + " `store`.`store_sqft` as `Store Sqft`," + " `store`.`store_type` as `Store Type`," + " `time_by_day`.`the_year` as `Year`," + " `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.`month_of_year` as `Month`," + " `product_class`.`product_family` as `Product Family`," + " `product_class`.`product_department` as `Product Department`," + " `product_class`.`product_category` as `Product Category`," + " `product_class`.`product_subcategory` as `Product Subcategory`," + " `product`.`brand_name` as `Brand Name`," + " `product`.`product_name` as `Product Name`," + " `promotion`.`media_type` as `Media Type`," + " `promotion`.`promotion_name` as `Promotion Name`," + " `customer`.`country` as `Country`," + " `customer`.`state_province` as `State Province`," + " `customer`.`city` as `City`, " + nameExpStr + " as `Name`," + " `customer`.`customer_id` as `Name (Key)`," + " `customer`.`education` as `Education Level`," + " `customer`.`gender` as `Gender`," + " `customer`.`marital_status` as `Marital Status`," + " `customer`.`yearly_income` as `Yearly Income`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` =as= `store`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `time_by_day` =as= `time_by_day`," + " `product_class` =as= `product_class`," + " `product` =as= `product`," + " `promotion` =as= `promotion`," + " `customer` =as= `customer` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink'" + " and `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id`" + " and `sales_fact_1997`.`customer_id` = `customer`.`customer_id` " + "order by `store`.`store_country` ASC," + " `store`.`store_state` ASC," + " `store`.`store_city` ASC," + " `store`.`store_name` ASC," + " `store`.`store_sqft` ASC," + " `store`.`store_type` ASC," + " `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC," + " `time_by_day`.`month_of_year` ASC," + " `product_class`.`product_family` ASC," + " `product_class`.`product_department` ASC," + " `product_class`.`product_category` ASC," + " `product_class`.`product_subcategory` ASC," + " `product`.`brand_name` ASC," + " `product`.`product_name` ASC," + " `promotion`.`media_type` ASC," + " `promotion`.`promotion_name` ASC," + " `customer`.`country` ASC," + " `customer`.`state_province` ASC," + " `customer`.`city` ASC, " + nameExpStr + " ASC," + " `customer`.`customer_id` ASC," + " `customer`.`education` ASC," + " `customer`.`gender` ASC," + " `customer`.`marital_status` ASC," + " `customer`.`yearly_income` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 7978); // Drillthrough SQL is null for cell based on calc member sql = result.getCell(new int[] {1, 1}).getDrillThroughSQL(true); assertNull(sql); } public void testDrillThrough3() throws Exception { Result result = executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON COLUMNS, " + nl + "Hierarchize(Union(Union(Crossjoin({[Promotion Media].[All Media]}, {[Product].[All Products]}), " + nl + "Crossjoin({[Promotion Media].[All Media]}, [Product].[All Products].Children)), Crossjoin({[Promotion Media].[All Media]}, [Product].[All Products].[Drink].Children))) ON ROWS " + nl + "from [Sales] where [Time].[1997].[Q4].[12]"); // [Promotion Media].[All Media], [Product].[All Products].[Drink].[Dairy], [Measures].[Store Cost] Cell cell = result.getCell(new int[] {0, 4}); String sql = cell.getDrillThroughSQL(true); String nameExpStr = getNameExp(result, "Customers", "Name"); String expectedSql = "select " + "`store`.`store_country` as `Store Country`, `store`.`store_state` as `Store State`, `store`.`store_city` as `Store City`, `store`.`store_name` as `Store Name`, " + "`store`.`store_sqft` as `Store Sqft`, `store`.`store_type` as `Store Type`, " + "`time_by_day`.`the_year` as `Year`, `time_by_day`.`quarter` as `Quarter`, `time_by_day`.`month_of_year` as `Month`, " + "`product_class`.`product_family` as `Product Family`, `product_class`.`product_department` as `Product Department`, " + "`product_class`.`product_category` as `Product Category`, `product_class`.`product_subcategory` as `Product Subcategory`, " + "`product`.`brand_name` as `Brand Name`, `product`.`product_name` as `Product Name`, " + "`promotion`.`media_type` as `Media Type`, `promotion`.`promotion_name` as `Promotion Name`, " + "`customer`.`country` as `Country`, `customer`.`state_province` as `State Province`, `customer`.`city` as `City`, " + "fname + ' ' + lname as `Name`, `customer`.`customer_id` as `Name (Key)`, " + "`customer`.`education` as `Education Level`, `customer`.`gender` as `Gender`, `customer`.`marital_status` as `Marital Status`, " + "`customer`.`yearly_income` as `Yearly Income`, " + "`sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store =as= `store`, " + "`sales_fact_1997` =as= `sales_fact_1997`, " + "`time_by_day` =as= `time_by_day`, " + "`product_class` =as= `product_class`, " + "`product` =as= `product`, " + "`promotion` =as= `promotion`, " + "`customer` =as= `customer` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id` and " + "`sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and " + "`time_by_day`.`the_year` = 1997 and " + "`time_by_day`.`quarter` = 'Q4' and " + "`time_by_day`.`month_of_year` = 12 and " + "`sales_fact_1997`.`product_id` = `product`.`product_id` and " + "`product`.`product_class_id` = `product_class`.`product_class_id` and " + "`product_class`.`product_family` = 'Drink' and " + "`product_class`.`product_department` = 'Dairy' and " + "`sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id` and " + "`sales_fact_1997`.`customer_id` = `customer`.`customer_id` " + "order by `store`.`store_country` ASC, `store`.`store_state` ASC, `store`.`store_city` ASC, `store`.`store_name` ASC, `store`.`store_sqft` ASC, " + "`store`.`store_type` ASC, `time_by_day`.`the_year` ASC, `time_by_day`.`quarter` ASC, `time_by_day`.`month_of_year` ASC, " + "`product_class`.`product_family` ASC, `product_class`.`product_department` ASC, `product_class`.`product_category` ASC, " + "`product_class`.`product_subcategory` ASC, `product`.`brand_name` ASC, `product`.`product_name` ASC, " + "`promotion.media_type` ASC, `promotion`.`promotion_name` ASC, " + "`customer`.`country` ASC, `customer`.`state_province` ASC, `customer`.`city` ASC, " + nameExpStr + " ASC, " + "`customer`.`customer_id` ASC, `customer`.`education` ASC, `customer`.gender` ASC, `customer`.`marital_status` ASC, `customer`.`yearly_income` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 141); } /** * Testcase for bug 1472311, "Drillthrough fails, if Aggregate in * MDX-query". The problem actually occurs with any calculated member, * not just Aggregate. The bug was causing a syntactically invalid * constraint to be added to the WHERE clause; after the fix, we do * not constrain on the member at all. */ public void testDrillThroughBug1472311() throws Exception { /* * "with set [Date Range] as" + nl + "'{[Time].[1997].[Q1],[Time].[1997].[Q2]}'" + nl + "member [Time].[Date Range] as 'Aggregate([Date Range])'" + nl + "select {[Store]} on rows," + nl + "{[Measures].[Unit Sales]} on columns" + nl + "from [Sales]" + nl + "where [Time].[Date Range]"); */ Result result = executeQuery( "with set [Date Range] as '{[Time].[1997].[Q1], [Time].[1997].[Q2]}'" + nl + "member [Time].[Date Range] as 'Aggregate([Date Range])'" + nl + "select {[Measures].[Unit Sales]} ON COLUMNS," + nl + "Hierarchize(Union(Union(Union({[Store].[All Stores]}, [Store].[All Stores].Children), [Store].[All Stores].[USA].Children), [Store].[All Stores].[USA].[CA].Children)) ON ROWS" + nl + "from [Sales]" + nl + "where [Time].[Date Range]" ); //String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(true); String sql = result.getCell(new int[] {0, 6}).getDrillThroughSQL(true); String nameExpStr = getNameExp(result, "Customers", "Name"); final String expectedSql = "select" + //`store`.`store_country` as `Store Country`," + " `store`.`store_state` as `Store State`," + " `store`.`store_city` as `Store City`," + " `store`.`store_name` as `Store Name`," + " `store`.`store_sqft` as `Store Sqft`," + " `store`.`store_type` as `Store Type`," + " `time_by_day`.`the_year` as `Year`," + " `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.`month_of_year` as `Month`," + " `product_class`.`product_family` as `Product Family`," + " `product_class`.`product_department` as `Product Department`," + " `product_class`.`product_category` as `Product Category`," + " `product_class`.`product_subcategory` as `Product Subcategory`," + " `product`.`brand_name` as `Brand Name`," + " `product`.`product_name` as `Product Name`," + " `promotion`.`media_type` as `Media Type`," + " `promotion`.`promotion_name` as `Promotion Name`," + " `customer`.`country` as `Country`," + " `customer`.`state_province` as `State Province`," + " `customer`.`city` as `City`, " + nameExpStr + " as `Name`," + " `customer`.`customer_id` as `Name (Key)`," + " `customer`.`education` as `Education Level`," + " `customer`.`gender` as `Gender`," + " `customer`.`marital_status` as `Marital Status`," + " `customer`.`yearly_income` as `Yearly Income`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` =as= `store`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `time_by_day` =as= `time_by_day`," + " `product_class` =as= `product_class`," + " `product` =as= `product`," + " `promotion` =as= `promotion`," + " `customer` =as= `customer` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id` and" + " `store`.`store_state` = 'CA' and" + " `store`.`store_city` = 'Beverly Hills' and" + " `sales_fact_1997`.time_id` = `time_by_day`.`time_id` and" + " `sales_fact_1997`.`product_id` = `product`.`product_id` and" + " `product`.`product_class_id` = `product_class`.`product_class_id` and" + " `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id` and" + " `sales_fact_1997`.`customer_id` = `customer`.`customer_id`" + " order by" + // `store`.`store_country` ASC," + " `store`.`store_state` ASC," + " `store`.`store_city` ASC," + " `store`.`store_name` ASC," + " `store`.`store_sqft` ASC," + " `store`.`store_type` ASC," + " `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC," + " `time_by_day`.`month_of_year` ASC," + " `product_class`.`product_family` ASC," + " `product_class`.`product_department` ASC," + " `product_class`.`product_category` ASC," + " `product_class`.`product_subcategory` ASC," + " `product`.`brand_name` ASC," + " `product`.`product_name` ASC," + " `promotion`.`media_type` ASC," + " `promotion`.`promotion_name` ASC," + " `customer`.`country` ASC," + " `customer`.`state_province` ASC," + " `customer`.`city` ASC, " + nameExpStr + " ASC," + " `customer`.`customer_id` ASC," + " `customer`.`education` ASC," + " `customer`.`gender` ASC," + " `customer`.`marital_status` ASC," + " `customer`.`yearly_income` ASC"; //getTestContext().assertSqlEquals(expectedSql, sql, 86837); getTestContext().assertSqlEquals(expectedSql, sql, 6815); } // Test that proper SQL is being generated for a Measure specified // as an expression public void testDrillThroughMeasureExp() throws Exception { Result result = executeQuery( "SELECT {[Measures].[Promotion Sales]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `product_class`.`product_family` as `Product Family`," + " (case when `sales_fact_1997`.`promotion_id` = 0 then 0" + " else `sales_fact_1997`.`store_sales` end)" + " as `Promotion Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `product_class` =as= `product_class`," + " `product` =as= `product` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink' " + "order by `time_by_day`.`the_year` ASC, `product_class`.`product_family` ASC"; final Cube cube = result.getQuery().getCube(); RolapStar star = ((RolapCube) cube).getStar(); SqlQuery.Dialect dialect = star.getSqlQueryDialect(); if (dialect.isAccess()) { String caseStmt = " \\(case when `sales_fact_1997`.`promotion_id` = 0 then 0" + " else `sales_fact_1997`.`store_sales` end\\)"; expectedSql = expectedSql.replaceAll( caseStmt, " Iif(`sales_fact_1997`.`promotion_id` = 0, 0," + " `sales_fact_1997`.`store_sales`)"); } getTestContext().assertSqlEquals(expectedSql, sql, 7978); } /** * Tests that drill-through works if two dimension tables have primary key * columns with the same name. Related to bug 1592556, "XMLA Drill through * bug". */ public void testDrillThroughDupKeys() throws Exception { /* * Note here that the type on the Store Id level is Integer or Numeric. The default, of course, would be String. * * For DB2 and Derby, we need the Integer type, otherwise the generated SQL will be something like: * * `store_ragged`.`store_id` = '19' * * and DB2 and Derby don't like converting from CHAR to INTEGER */ final TestContext testContext = TestContext.createSubstitutingCube( "Sales", " <Dimension name=\"Store2\" foreignKey=\"store_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">\n" + " <Table name=\"store_ragged\"/>\n" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store Id\" column=\"store_id\" captionColumn=\"store_name\" uniqueMembers=\"true\" type=\"Integer\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Store3\" foreignKey=\"store_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">\n" + " <Table name=\"store\"/>\n" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store Id\" column=\"store_id\" captionColumn=\"store_name\" uniqueMembers=\"true\" type=\"Numeric\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n"); Result result = testContext.executeQuery( "SELECT {[Store2].[Store Id].Members} on columns," + nl + " NON EMPTY([Store3].[Store Id].Members) on rows" + nl + "from Sales"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `store_ragged`.`store_id` as `Store Id`," + " `store`.`store_id` as `Store Id_0`," + " `sales_fact_1997`.`unit_sales` as" + " `Unit Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `store_ragged` =as= `store_ragged`," + " `store` =as= `store` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`store_id` = `store_ragged`.`store_id`" + " and `store_ragged`.`store_id` = 19" + " and `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `store`.`store_id` = 2 " + "order by `time_by_day`.`the_year` ASC, `store_ragged`.`store_id` ASC, `store`.`store_id` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 0); } /** * Tests that cells in a virtual cube say they can be drilled through. */ public void testDrillThroughVirtualCube() throws Exception { Result result = executeQuery( "select Crossjoin([Customers].[All Customers].[USA].[OR].Children, {[Measures].[Unit Sales]}) ON COLUMNS, " + " [Gender].[All Gender].Children ON ROWS" + " from [Warehouse and Sales]" + " where [Time].[1997].[Q4].[12]"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.month_of_year` as `Month`," + " `customer`.`state_province` as `State Province`," + " `customer`.`city` as `City`," + " `customer`.`gender` as `Gender`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales`" + " from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `customer` =as= `customer`" + " where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and" + " `time_by_day`.`the_year` = 1997 and" + " `time_by_day`.`quarter` = 'Q4' and" + " `time_by_day`.`month_of_year` = 12 and" + " `sales_fact_1997`.`customer_id` = `customer`.customer_id` and" + " `customer`.`state_province` = 'OR' and" + " `customer`.`city` = 'Albany' and" + " `customer`.`gender` = 'F'" + " order by `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC," + " `time_by_day`.`month_of_year` ASC," + " `customer`.`state_province` ASC," + " `customer`.`city` ASC," + " `customer`.`gender` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 73); } /** * This tests for bug 1438285, "nameColumn cannot be column in level * definition". */ public void testBug1438285() throws Exception { // Specify the column and nameColumn to be the same // in order to reproduce the problem final TestContext testContext = TestContext.createSubstitutingCube( "Sales", " <Dimension name=\"Store2\" foreignKey=\"store_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Stores\" >\n" + " <Table name=\"store_ragged\"/>\n" + " <Level name=\"Store Id\" column=\"store_id\" nameColumn=\"store_id\" ordinalColumn=\"region_id\" uniqueMembers=\"true\">\n" + " </Level>" + " </Hierarchy>\n" + " </Dimension>\n"); Result result = testContext.executeQuery( "SELECT {[Measures].[Unit Sales]} on columns, " + "{[Store2].members} on rows FROM [Sales]"); // Prior to fix the request for the drill through SQL would result in // an assertion error String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(true); String expectedSql = "select `store`.`store_country` as `Store Country`," + " `store`.`store_state` as `Store State`," + " `store`.`store_city` as `Store City`, `store`.`store_name` as `Store Name`," + " `store`.`store_sqft` as `Store Sqft`, `store`.`store_type` as `Store Type`," + " `time_by_day`.`the_year` as `Year`, `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.`month_of_year` as `Month`," + " `product_class`.`product_family` as `Product Family`," + " `product_class`.`product_department` as `Product Department`," + " `product_class`.`product_category` as `Product Category`," + " `product_class`.`product_subcategory` as `Product Subcategory`," + " `product`.`brand_name` as `Brand Name`," + " `product`.`product_name` as `Product Name`, `store_ragged`.`store_id` as `Store Id`," + " `store_ragged`.`store_id` as `Store Id (Key)`, `promotion`.`media_type` as `Media Type`," + " `promotion`.`promotion_name` as `Promotion Name`, `customer`.`country` as `Country`," + " `customer`.`state_province` as `State Province`, `customer`.`city` as `City`," + " fname + ' ' + lname as `Name`, `customer`.`customer_id` as `Name (Key)`," + " `customer`.`education` as `Education Level`, `customer`.`gender` as `Gender`," + " `customer`.`marital_status` as `Marital Status`," + " `customer`.`yearly_income` as `Yearly Income`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales`" + " from `store` =as= `store`, `sales_fact_1997` =as= `sales_fact_1997`," + " `time_by_day` =as= `time_by_day`, `product_class` =as= `product_class`," + " `product` =as= `product`, `store_ragged` =as= `store_ragged`," + " `promotion` =as= `promotion`, `customer` =as= `customer`" + " where `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `sales_fact_1997`.`store_id` = `store_ragged`.`store_id`" + " and `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id`" + " and `sales_fact_1997`.`customer_id` = `customer`.`customer_id`" + " order by `store`.`store_country` ASC, `store`.`store_state` ASC," + " `store`.`store_city` ASC, `store`.`store_name` ASC, `store`.`store_sqft` ASC," + " `store`.`store_type` ASC, `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC, `time_by_day`.`month_of_year` ASC," + " `product_class`.`product_family` ASC, `product_class`.`product_department` ASC," + " `product_class`.`product_category` ASC," + " `product_class`.`product_subcategory` ASC, `product`.`brand_name` ASC," + " `product`.`product_name` ASC, `store_ragged`.`store_id` ASC," + " `promotion`.`media_type` ASC, `promotion`.`promotion_name` ASC," + " `customer`.`country` ASC, `customer`.`state_province` ASC," + " `customer`.`city` ASC, fname + ' ' + lname ASC," + " `customer`.`customer_id` ASC, `customer`.`education` ASC," + " `customer`.`gender` ASC, `customer`.`marital_status` ASC," + " `customer`.`yearly_income` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 86837); } /** * Tests that long levels do not result in column aliases larger than the * database can handle. For example, Access allows maximum of 64; Oracle * allows 30. * * <p>Testcase for bug 1893959, "Generated drill-through columns too long * for DBMS". * * @throws Exception on error */ public void testTruncateLevelName() throws Exception { final TestContext testContext = TestContext.createSubstitutingCube( "Sales", " <Dimension name=\"Education Level2\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Education Level but with a very long name that will be too long if converted directly into a column\" column=\"education\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>", null); Result result = testContext.executeQuery( "SELECT {[Measures].[Unit Sales]} on columns,\n" + "{[Education Level2].Children} on rows\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q1].[1], [Product].[Non-Consumable].[Carousel].[Specialty].[Sunglasses].[ADJ].[ADJ Rosy Sunglasses]) "); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); // Check that SQL is valid. java.sql.Connection connection = null; try { DataSource dataSource = getConnection().getDataSource(); connection = dataSource.getConnection(); final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery(sql); assertEquals(6, resultSet.getMetaData().getColumnCount()); final String columnName = resultSet.getMetaData().getColumnName(5); assertTrue( columnName, columnName.startsWith("Education Level but with a")); int n = 0; while (resultSet.next()) { ++n; } assertEquals(2, n); } finally { if (connection != null) { connection.close(); } } } } // End DrillThroughTest.java
package edu.wustl.catissuecore.bizlogic; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.Vector; import edu.wustl.catissuecore.domain.CancerResearchGroup; import edu.wustl.catissuecore.domain.Department; import edu.wustl.catissuecore.domain.Institution; import edu.wustl.catissuecore.domain.Password; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.EmailHandler; import edu.wustl.catissuecore.util.Roles; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SecurityDataBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.dao.DAO; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.PasswordManager; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.authorization.domainobjects.Role; /** * UserBizLogic is used to add user information into the database using Hibernate. * @author kapil_kaveeshwar */ public class UserBizLogic extends DefaultBizLogic { public static final int FAIL_SAME_AS_LAST_N = 8; public static final int FAIL_FIRST_LOGIN = 9; public static final int FAIL_EXPIRE = 10; public static final int FAIL_CHANGED_WITHIN_SOME_DAY = 11; public static final int FAIL_SAME_NAME_SURNAME_EMAIL = 12; public static final int FAIL_PASSWORD_EXPIRED = 13; public static final int SUCCESS = 0; /** * Saves the user object in the database. * @param obj The user object to be saved. * @param session The session in which the object is saved. * @throws DAOException */ protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { User user = (User) obj; gov.nih.nci.security.authorization.domainobjects.User csmUser = new gov.nih.nci.security.authorization.domainobjects.User(); try { List list = dao.retrieve(Department.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getDepartment().getId()); Department department = null; if (list.size() != 0) { department = (Department) list.get(0); } list = dao.retrieve(Institution.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getInstitution().getId()); Institution institution = null; if (list.size() != 0) { institution = (Institution) list.get(0); } list = dao.retrieve(CancerResearchGroup.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getCancerResearchGroup().getId()); CancerResearchGroup cancerResearchGroup = null; if (list.size() != 0) { cancerResearchGroup = (CancerResearchGroup) list.get(0); } user.setDepartment(department); user.setInstitution(institution); user.setCancerResearchGroup(cancerResearchGroup); // If the page is of signup user don't create the csm user. if (user.getPageOf().equals(Constants.PAGEOF_SIGNUP) == false) { csmUser.setLoginName(user.getLoginName()); csmUser.setLastName(user.getLastName()); csmUser.setFirstName(user.getFirstName()); csmUser.setEmailId(user.getEmailAddress()); csmUser.setStartDate(user.getStartDate()); csmUser.setPassword(PasswordManager.encode(PasswordManager.generatePassword())); SecurityManager.getInstance(UserBizLogic.class).createUser(csmUser); if (user.getRoleId() != null) { SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser(csmUser.getUserId().toString(), user.getRoleId()); } user.setCsmUserId(csmUser.getUserId()); // user.setPassword(csmUser.getPassword()); //Add password of user in password table.Updated by Supriya Dankh Password password = new Password(); password.setUser(user); password.setPassword(csmUser.getPassword()); password.setUpdateDate(new Date()); user.getPasswordCollection().add(password); Logger.out.debug("password stored in passwore table"); // user.setPassword(csmUser.getPassword()); } // Create address and the user in catissue tables. dao.insert(user.getAddress(), sessionDataBean, true, false); dao.insert(user, sessionDataBean, true, false); Set protectionObjects = new HashSet(); protectionObjects.add(user); EmailHandler emailHandler = new EmailHandler(); // Send the user registration email to user and the administrator. if (Constants.PAGEOF_SIGNUP.equals(user.getPageOf())) { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, null); emailHandler.sendUserSignUpEmail(user); } else // Send the user creation email to user and the administrator. { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user), protectionObjects, null); emailHandler.sendApprovalEmail(user); } } catch (DAOException daoExp) { Logger.out.debug(daoExp.getMessage(), daoExp); deleteCSMUser(csmUser); throw daoExp; } catch (SMException e) { // added to format constrainviolation message deleteCSMUser(csmUser); throw handleSMException(e); } } /** * Deletes the csm user from the csm user table. * @param csmUser The csm user to be deleted. * @throws DAOException */ private void deleteCSMUser(gov.nih.nci.security.authorization.domainobjects.User csmUser) throws DAOException { try { if (csmUser.getUserId() != null) { SecurityManager.getInstance(ApproveUserBizLogic.class).removeUser(csmUser.getUserId().toString()); } } catch (SMException smExp) { throw handleSMException(smExp); } } /** * This method returns collection of UserGroupRoleProtectionGroup objects that speciefies the * user group protection group linkage through a role. It also specifies the groups the protection * elements returned by this class should be added to. * @return */ private Vector getAuthorizationData(AbstractDomainObject obj) throws SMException { Logger.out.debug(" Vector authorizationData = new Vector(); Set group = new HashSet(); User aUser = (User) obj; String userId = String.valueOf(aUser.getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User user = SecurityManager.getInstance(this.getClass()).getUserById(userId); Logger.out.debug(" User: " + user.getLoginName()); group.add(user); // Protection group of User String protectionGroupName = Constants.getUserPGName(aUser.getId()); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(userId); userGroupRoleProtectionGroupBean.setRoleName(Roles.UPDATE_ONLY); userGroupRoleProtectionGroupBean.setGroupName(Constants.getUserGroupName(aUser.getId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); Logger.out.debug(authorizationData.toString()); return authorizationData; } /** * Updates the persistent object in the database. * @param obj The object to be updated. * @param session The session in which the object is saved. * @throws DAOException */ protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { User user = (User) obj; User oldUser = (User) oldObj; //If the user is rejected, its record cannot be updated. if (Constants.ACTIVITY_STATUS_REJECT.equals(oldUser.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("errors.editRejectedUser")); } else if (Constants.ACTIVITY_STATUS_NEW.equals(oldUser.getActivityStatus()) || Constants.ACTIVITY_STATUS_PENDING.equals(oldUser.getActivityStatus())) { //If the user is not approved yet, its record cannot be updated. throw new DAOException(ApplicationProperties.getValue("errors.editNewPendingUser")); } try { // Get the csm userId if present. String csmUserId = null; if (user.getCsmUserId() != null) { csmUserId = user.getCsmUserId().toString(); } gov.nih.nci.security.authorization.domainobjects.User csmUser = SecurityManager.getInstance(UserBizLogic.class).getUserById(csmUserId); // If the page is of change password, // update the password of the user in csm and catissue tables. if (user.getPageOf().equals(Constants.PAGEOF_CHANGE_PASSWORD)) { if (!user.getOldPassword().equals(PasswordManager.decode(csmUser.getPassword()))) { throw new DAOException(ApplicationProperties.getValue("errors.oldPassword.wrong")); } //Added for Password validation by Supriya Dankh. Validator validator = new Validator(); if (!validator.isEmpty(user.getNewPassword()) && !validator.isEmpty(user.getOldPassword())) { int result = validatePassword(oldUser, user.getNewPassword(), user.getOldPassword()); Logger.out.debug("return from Password validate " + result); //if validatePassword method returns value greater than zero then validation fails if (result != SUCCESS) { // get error message of validation failure String errorMessage = getPasswordErrorMsg(result); Logger.out.debug("Error Message from method" + errorMessage); throw new DAOException(errorMessage); } } csmUser.setPassword(PasswordManager.encode(user.getNewPassword())); // Set values in password domain object and adds changed password in Password Collection Password password = new Password(csmUser.getPassword(), user); user.getPasswordCollection().add(password); } else { csmUser.setLoginName(user.getLoginName()); csmUser.setLastName(user.getLastName()); csmUser.setFirstName(user.getFirstName()); csmUser.setEmailId(user.getEmailAddress()); // Assign Role only if the page is of Administrative user edit. if ((Constants.PAGEOF_USER_PROFILE.equals(user.getPageOf()) == false) && (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false)) { SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser(csmUser.getUserId().toString(), user.getRoleId()); } dao.update(user.getAddress(), sessionDataBean, true, false, false); // Audit of user address. dao.audit(user.getAddress(), oldUser.getAddress(), sessionDataBean, true); } // Modify the csm user. SecurityManager.getInstance(UserBizLogic.class).modifyUser(csmUser); dao.update(user, sessionDataBean, true, true, true); //Audit of user. dao.audit(obj, oldObj, sessionDataBean, true); if (Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus())) { Set protectionObjects = new HashSet(); protectionObjects.add(user); SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user), protectionObjects, null); } } catch (SMException e) { throw handleSMException(e); } } /** * Returns the list of NameValueBeans with name as "LastName,Firstname" * and value as systemtIdentifier, of all users who are not disabled. * @return the list of NameValueBeans with name as "LastName,Firstname" * and value as systemtIdentifier, of all users who are not disabled. * @throws DAOException */ public Vector getUsers(String operation) throws DAOException { String sourceObjectName = User.class.getName(); String[] selectColumnName = null; String[] whereColumnName; String[] whereColumnCondition; Object[] whereColumnValue; String joinCondition; if (operation != null && operation.equalsIgnoreCase(Constants.ADD)) { String tmpArray1[] = {Constants.ACTIVITY_STATUS}; String tmpArray2[] = {"="}; String tmpArray3[] = {Constants.ACTIVITY_STATUS_ACTIVE}; whereColumnName = tmpArray1; whereColumnCondition = tmpArray2; whereColumnValue = tmpArray3; joinCondition = null; } else { String tmpArray1[] = {Constants.ACTIVITY_STATUS, Constants.ACTIVITY_STATUS}; String tmpArray2[] = {"=", "="}; String tmpArray3[] = {Constants.ACTIVITY_STATUS_ACTIVE, Constants.ACTIVITY_STATUS_CLOSED}; whereColumnName = tmpArray1; whereColumnCondition = tmpArray2; whereColumnValue = tmpArray3; joinCondition = Constants.OR_JOIN_CONDITION; // whereColumnName = {Constants.ACTIVITY_STATUS,Constants.ACTIVITY_STATUS}; // whereColumnCondition = {"=","="}; // whereColumnValue = {Constants.ACTIVITY_STATUS_ACTIVE,Constants.ACTIVITY_STATUS_CLOSED }; // joinCondition = Constants.OR_JOIN_CONDITION ; } //Retrieve the users whose activity status is not disabled. List users = retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); Vector nameValuePairs = new Vector(); nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, String.valueOf(Constants.SELECT_OPTION_VALUE))); // If the list of users retrieved is not empty. if (users.isEmpty() == false) { // Creating name value beans. for (int i = 0; i < users.size(); i++) { User user = (User) users.get(i); NameValueBean nameValueBean = new NameValueBean(); nameValueBean.setName(user.getLastName() + ", " + user.getFirstName()); nameValueBean.setValue(String.valueOf(user.getId())); Logger.out.debug(nameValueBean.toString() + " : " + user.getActivityStatus()); nameValuePairs.add(nameValueBean); } } Collections.sort(nameValuePairs); return nameValuePairs; } /** * Returns the list of NameValueBeans with name as "LastName,Firstname" * and value as systemtIdentifier, of all users who are not disabled. * @return the list of NameValueBeans with name as "LastName,Firstname" * and value as systemtIdentifier, of all users who are not disabled. * @throws DAOException */ public Vector getCSMUsers() throws DAOException, SMException { //Retrieve the users whose activity status is not disabled. List users = SecurityManager.getInstance(UserBizLogic.class).getUsers(); Vector nameValuePairs = new Vector(); nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, String.valueOf(Constants.SELECT_OPTION_VALUE))); // If the list of users retrieved is not empty. if (users.isEmpty() == false) { // Creating name value beans. for (int i = 0; i < users.size(); i++) { gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) users.get(i); NameValueBean nameValueBean = new NameValueBean(); nameValueBean.setName(user.getLastName() + ", " + user.getFirstName()); nameValueBean.setValue(String.valueOf(user.getUserId())); Logger.out.debug(nameValueBean.toString()); nameValuePairs.add(nameValueBean); } } Collections.sort(nameValuePairs); return nameValuePairs; } /** * Returns a list of users according to the column name and value. * @param colName column name on the basis of which the user list is to be retrieved. * @param colValue Value for the column name. * @throws DAOException */ public List retrieve(String className, String colName, Object colValue) throws DAOException { List userList = null; Logger.out.debug("In user biz logic retrieve........................"); try { // Get the caTISSUE user. userList = super.retrieve(className, colName, colValue); User appUser = null; if (!userList.isEmpty()) { appUser = (User) userList.get(0); if (appUser.getCsmUserId() != null) { //Get the role of the user. Role role = SecurityManager.getInstance(UserBizLogic.class).getUserRole(appUser.getCsmUserId().longValue()); Logger.out.debug("In USer biz logic.............role........id......." + role.getId().toString()); if (role != null) { appUser.setRoleId(role.getId().toString()); } } } } catch (SMException e) { throw handleSMException(e); } return userList; } /** * Retrieves and sends the login details email to the user whose email address is passed * else returns the error key in case of an error. * @param emailAddress the email address of the user whose password is to be sent. * @return the error key in case of an error. * @throws DAOException */ public String sendForgotPassword(String emailAddress) throws DAOException { String statusMessageKey = null; List list = retrieve(User.class.getName(), "emailAddress", emailAddress); if (!list.isEmpty()) { User user = (User) list.get(0); if (user.getActivityStatus().equals(Constants.ACTIVITY_STATUS_ACTIVE)) { EmailHandler emailHandler = new EmailHandler(); //Send the login details email to the user. boolean emailStatus = emailHandler.sendLoginDetailsEmail(user, null); if (emailStatus) { statusMessageKey = "password.send.success"; } else { statusMessageKey = "password.send.failure"; } } else { //Error key if the user is not active. statusMessageKey = "errors.forgotpassword.user.notApproved"; } } else { // Error key if the user is not present. statusMessageKey = "errors.forgotpassword.user.unknown"; } return statusMessageKey; } /** * Overriding the parent class's method to validate the enumerated attribute values */ protected boolean validate(Object obj, DAO dao, String operation) throws DAOException { User user = (User) obj; if (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false) { if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_STATE_LIST, null), user .getAddress().getState())) { throw new DAOException(ApplicationProperties.getValue("state.errMsg")); } if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COUNTRY_LIST, null), user .getAddress().getCountry())) { throw new DAOException(ApplicationProperties.getValue("country.errMsg")); } if (Constants.PAGEOF_USER_ADMIN.equals(user.getPageOf())) { try { if (!Validator.isEnumeratedValue(getRoles(), user.getRoleId())) { throw new DAOException(ApplicationProperties.getValue("user.role.errMsg")); } } catch (SMException e) { throw handleSMException(e); } if (operation.equals(Constants.ADD)) { if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg")); } } else { if (!Validator.isEnumeratedValue(Constants.USER_ACTIVITY_STATUS_VALUES, user.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg")); } } } } return true; } /** * Returns a list of all roles that can be assigned to a user. * @return a list of all roles that can be assigned to a user. * @throws SMException */ private List getRoles() throws SMException { //Sets the roleList attribute to be used in the Add/Edit User Page. Vector roleList = SecurityManager.getInstance(UserBizLogic.class).getRoles(); List roleNameValueBeanList = new ArrayList(); NameValueBean nameValueBean = new NameValueBean(); nameValueBean.setName(Constants.SELECT_OPTION); nameValueBean.setValue("-1"); roleNameValueBeanList.add(nameValueBean); ListIterator iterator = roleList.listIterator(); while (iterator.hasNext()) { Role role = (Role) iterator.next(); nameValueBean = new NameValueBean(); nameValueBean.setName(role.getName()); nameValueBean.setValue(String.valueOf(role.getId())); roleNameValueBeanList.add(nameValueBean); } return roleNameValueBeanList; } /** * @param oldUser User object * @param newPassword New Password value * @param validator VAlidator object * @param oldPassword Old Password value * @return SUCCESS (constant int 0) if all condition passed * else return respective error code (constant int) value */ private int validatePassword(User oldUser, String newPassword, String oldPassword) { List oldPwdList = new ArrayList(oldUser.getPasswordCollection()); Collections.sort(oldPwdList); if (oldPwdList != null && !oldPwdList.isEmpty()) { //Check new password is equal to last n password if value if (checkPwdNotSameAsLastN(newPassword, oldPwdList)) { Logger.out.debug("Password is not valid returning FAIL_SAME_AS_LAST_N"); return FAIL_SAME_AS_LAST_N; } //Get the last updated date of the password Date lastestUpdateDate = ((Password) oldPwdList.get(0)).getUpdateDate(); if(oldPwdList.size() > 1) { if (checkPwdUpdatedOnSameDay(lastestUpdateDate)) { Logger.out.debug("Password is not valid returning FAIL_CHANGED_WITHIN_SOME_DAY"); return FAIL_CHANGED_WITHIN_SOME_DAY; } } /** * to check password does not contain user name,surname,email address. if same return FAIL_SAME_NAME_SURNAME_EMAIL * eg. username=XabcY@abc.com newpassword=abc is not valid */ String emailAddress = oldUser.getEmailAddress(); int usernameBeforeMailaddress = emailAddress.indexOf('@'); // get substring of emailAddress before '@' character emailAddress = emailAddress.substring(0, usernameBeforeMailaddress); String userFirstName = oldUser.getFirstName(); String userLastName = oldUser.getLastName(); StringBuffer sb = new StringBuffer(newPassword); if (emailAddress != null && newPassword.toLowerCase().indexOf(emailAddress.toLowerCase())!=-1) { Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL"); return FAIL_SAME_NAME_SURNAME_EMAIL; } if (userFirstName != null && newPassword.toLowerCase().indexOf(userFirstName.toLowerCase())!=-1) { Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL"); return FAIL_SAME_NAME_SURNAME_EMAIL; } if (userLastName != null && newPassword.toLowerCase().indexOf(userLastName.toLowerCase())!=-1) { Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL"); return FAIL_SAME_NAME_SURNAME_EMAIL; } } return SUCCESS; } /** * This function checks whether user has logged in for first time or whether user's password is expired. * In both these case user needs to change his password so Error key is returned * @param user - user object * @throws DAOException - throws DAOException */ public String checkFirstLoginAndExpiry(User user) { List passwordList = new ArrayList(user.getPasswordCollection()); if(passwordList.size()==1) { return "errors.changePassword.changeFirstLogin"; } Collections.sort(passwordList); Password lastPassword = (Password)passwordList.get(0); Date lastUpdateDate = lastPassword.getUpdateDate(); Validator validator = new Validator(); //Get difference in days between last password update date and current date. long dayDiff = validator.getDateDiff(lastUpdateDate, new Date()); int expireDaysCount = Integer.parseInt(XMLPropertyHandler.getValue("password.expire_after_n_days")); if (dayDiff > expireDaysCount) { return "errors.changePassword.expire"; } return Constants.SUCCESS; } private boolean checkPwdNotSameAsLastN(String newPassword, List oldPwdList) { int noOfPwdNotSameAsLastN = 0; String pwdNotSameAsLastN = XMLPropertyHandler.getValue("password.not_same_as_last_n"); if (pwdNotSameAsLastN != null && !pwdNotSameAsLastN.equals("")) { noOfPwdNotSameAsLastN = Integer.parseInt(pwdNotSameAsLastN); noOfPwdNotSameAsLastN = Math.max(0, noOfPwdNotSameAsLastN); } boolean isSameFound = false; int loopCount = Math.min(oldPwdList.size(), noOfPwdNotSameAsLastN); for (int i = 0; i < loopCount; i++) { Password pasword = (Password) oldPwdList.get(i); if (newPassword.equals(PasswordManager.decode(pasword.getPassword()))) { isSameFound = true; break; } } return isSameFound; } private boolean checkPwdUpdatedOnSameDay(Date lastUpdateDate) { Validator validator = new Validator(); //Get difference in days between last password update date and current date. long dayDiff = validator.getDateDiff(lastUpdateDate, new Date()); int dayDiffConstant = Integer.parseInt(XMLPropertyHandler.getValue("daysCount")); if (dayDiff <= dayDiffConstant) { Logger.out.debug("Password is not valid returning FAIL_CHANGED_WITHIN_SOME_DAY"); return true; } return false; } /** * @param errorCode int value return by validatePassword() method * @return String error message with respect to error code */ private String getPasswordErrorMsg(int errorCode) { String errMsg = ""; switch (errorCode) { case FAIL_SAME_AS_LAST_N : List parameters = new ArrayList(); String dayCount = "" + Integer.parseInt(XMLPropertyHandler.getValue("password.not_same_as_last_n")); parameters.add(dayCount); errMsg = ApplicationProperties.getValue("errors.newPassword.sameAsLastn",parameters); break; case FAIL_FIRST_LOGIN : errMsg = ApplicationProperties.getValue("errors.changePassword.changeFirstLogin"); break; case FAIL_EXPIRE : errMsg = ApplicationProperties.getValue("errors.changePassword.expire"); break; case FAIL_CHANGED_WITHIN_SOME_DAY : errMsg = ApplicationProperties.getValue("errors.changePassword.afterSomeDays"); break; case FAIL_SAME_NAME_SURNAME_EMAIL : errMsg = ApplicationProperties.getValue("errors.changePassword.sameAsNameSurnameEmail"); break; case FAIL_PASSWORD_EXPIRED : errMsg = ApplicationProperties.getValue("errors.changePassword.expire"); default : errMsg = PasswordManager.getErrorMessage(errorCode); break; } return errMsg; } // //method to return a comma seperated list of emails of administrators of a particular institute // private String getInstitutionAdmins(Long instID) throws DAOException,SMException // String retStr=""; // String[] userEmail; // Long[] csmAdminIDs = SecurityManager.getInstance(UserBizLogic.class).getAllAdministrators() ; // if (csmAdminIDs != null ) // for(int cnt=0;cnt<csmAdminIDs.length ;cnt++ ) // String sourceObjectName = User.class.getName(); // String[] selectColumnName = null; // String[] whereColumnName = {"institution","csmUserId"}; // String[] whereColumnCondition = {"=","="}; // Object[] whereColumnValue = {instID, csmAdminIDs[cnt] }; // String joinCondition = Constants.AND_JOIN_CONDITION; // //Retrieve the users for given institution and who are administrators. // List users = retrieve(sourceObjectName, selectColumnName, whereColumnName, // whereColumnCondition, whereColumnValue, joinCondition); // if(!users.isEmpty() ) // User adminUser = (User)users.get(0); // retStr = retStr + "," + adminUser.getEmailAddress(); // Logger.out.debug(retStr); // retStr = retStr.substring(retStr.indexOf(",")+1 ); // Logger.out.debug(retStr); // return retStr; }
package edu.wustl.catissuecore.util.global; /** * This class stores the constants used in the operations in the application. * @author gautam_shetty */ public class Constants { public static final String AND_JOIN_CONDITION = "AND"; public static final String OR_JOIN_CONDITION = "OR"; //DAO Constants. public static final int HIBERNATE_DAO = 1; public static final int JDBC_DAO = 2; public static final String SUCCESS = "success"; public static final String FAILURE = "failure"; public static final String ADD = "add"; public static final String EDIT = "edit"; public static final String VIEW = "view"; public static final String SEARCH = "search"; public static final String NEWUSERFORM = "newUserForm"; //Constants required for Forgot Password public static final String FORGOT_PASSWORD = "forgotpassword"; public static final String YOUR_PASSWORD = "Your Password"; public static final String IDENTIFIER = "systemIdentifier"; public static final String LOGINNAME = "loginName"; public static final String LASTNAME = "lastName"; public static final String FIRSTNAME = "firstName"; public static final String INSTITUTION = "institution"; public static final String EMAIL = "email"; public static final String DEPARTMENT = "department"; public static final String ADDRESS = "address"; public static final String CITY = "city"; public static final String STATE = "state"; public static final String COUNTRY = "country"; public static final String OPERATION = "operation"; public static final String ACTIVITY_STATUS = "activityStatus"; public static final String INSTITUTIONLIST = "institutionList"; public static final String DEPARTMENTLIST = "departmentList"; public static final String STATELIST = "stateList"; public static final String COUNTRYLIST = "countryList"; public static final String ROLELIST = "roleList"; public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList"; public static final String GENOTYPIC_GENDER_LIST = "genotypicGenderList"; public static final String ETHNICITY_LIST = "ethnicityList"; public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList"; public static final String RACELIST = "raceList"; public static final String PARTICIPANTLIST = "participantList"; public static final String PARTICIPANTIDLIST = "participantIdList"; public static final String PROTOCOLLIST = "protocolList"; public static final String TIMEHOURLIST = "timeHourList"; public static final String TIMEMINUTESLIST = "timeMinutesList"; public static final String TIMEAMPMLIST = "timeAMPMList"; public static final String RECEIVEDBYLIST = "receivedByList"; public static final String COLLECTEDBYLIST = "collectedByList"; public static final String COLLECTIONSITELIST = "collectionSiteList"; public static final String RECEIVEDSITELIST = "receivedSiteList"; public static final String RECEIVEDMODELIST = "receivedModeList"; public static final String ACTIVITYSTATUSLIST = "activityStatusList"; public static final String USERLIST = "userList"; public static final String SITETYPELIST = "siteTypeList"; public static final String STORAGECONTAINERLIST="storageContainerList"; public static final String SITELIST="siteList"; public static final String USERIDLIST = "userIdList"; //New Specimen lists. public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList"; public static final String SPECIMEN_TYPE_LIST = "specimenTypeList"; public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList"; public static final String TISSUE_SITE_LIST = "tissueSiteList"; public static final String TISSUE_SIDE_LIST = "tissueSideList"; public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList"; public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList"; public static final String BIOHAZARD_NAME_LIST = "biohazardNameList"; //SpecimenCollecionGroup lists. public static final String PROTOCOL_TITLE_LIST = "protocolTitleList"; public static final String PARTICIPANT_NAME_LIST = "participantNameList"; public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList"; public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList"; public static final String CLINICAL_STATUS_LIST = "cinicalStatusList"; //Constants required in User.jsp Page public static final String USER_SEARCH_ACTION = "UserSearch.do"; public static final String USER_ADD_ACTION = "UserAdd.do"; public static final String USER_EDIT_ACTION = "UserEdit.do"; //Constants required in Accession.jsp Page public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do"; public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do"; public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do"; // Constants required in StorageType.jsp Page public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do"; public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do"; public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do"; // Constants required in StorageContainer.jsp Page public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do"; public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do"; public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do"; // Constants required in Site.jsp Page public static final String SITE_SEARCH_ACTION = "SiteSearch.do"; public static final String SITE_ADD_ACTION = "SiteAdd.do"; public static final String SITE_EDIT_ACTION = "SiteEdit.do"; //Constants required in Partcipant.jsp Page public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do"; public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do"; public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do"; //Constants required in Institution.jsp Page public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do"; public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do"; public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do"; // Constants required in Department.jsp Page public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do"; public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do"; public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do"; //Constants required for Approve user public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do"; public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do"; //Reported Problem Constants public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do"; public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do"; //Query Results view Actions public static final String TREE_VIEW_ACTION = "TreeView.do"; //New Specimen Data Actions. public static final String SPECIMEN_ADD_ACTION = "SpecimenAdd.do"; public static final String SPECIMEN_EDIT_ACTION = "SpecimenEdit.do"; public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do"; public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do"; //Levels of nodes in query results tree. public static final int MAX_LEVEL = 5; public static final int MIN_LEVEL = 1; public static final String[] DEFAULT_TREE_SELECT_COLUMNS = { Constants.QUERY_RESULTS_PARTICIPANT_ID, Constants.QUERY_RESULTS_ACCESSION_ID, Constants.QUERY_RESULTS_SPECIMEN_ID, Constants.QUERY_RESULTS_SEGMENT_ID, Constants.QUERY_RESULTS_SAMPLE_ID}; //Frame names in Query Results page. public static final String DATA_VIEW_FRAME = "myframe1"; public static final String APPLET_VIEW_FRAME = "appletViewFrame"; //NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view). public static final String DATA_VIEW_ACTION = "/catissuecore/DataView.do?nodeName="; public static final String VIEW_TYPE = "viewType"; //Constants for type of query results view. public static final String SPREADSHEET_VIEW = "Spreadsheet View"; public static final String OBJECT_VIEW = "Object View"; //Spreadsheet view Constants in DataViewAction. public static final String PARTICIPANT = "Participant"; public static final String ACCESSION = "Accession"; public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier="; public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier="; //Individual view Constants in DataViewAction. public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList"; public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList"; public static final String SELECT_COLUMN_LIST = "selectColumnList"; //Tree Data Action public static final String TREE_DATA_ACTION = "/catissuecore/Data.do"; //Constants for default column names to be shown for query result. public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {"PARTICIPANT_ID","ACCESSION_ID","SPECIMEN_ID", "TISSUE_SITE","SPECIMEN_TYPE","SEGMENT_ID", "SAMPLE_ID","SAMPLE_TYPE"}; public static final String SPECIMEN = "Specimen"; public static final String SEGMENT = "Segment"; public static final String SAMPLE = "Sample"; public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID"; public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID"; public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID"; public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID"; public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID"; //Identifiers for various Form beans public static final int USER_FORM_ID = 1; public static final int PARTICIPANT_FORM_ID = 2; public static final int ACCESSION_FORM_ID = 3; public static final int REPORTEDPROBLEM_FORM_ID = 4; public static final int INSTITUTION_FORM_ID = 5; public static final int APPROVE_USER_FORM_ID = 6; public static final int ACTIVITY_STATUS_FORM_ID = 7; public static final int DEPARTMENT_FORM_ID = 8; public static final int COLLECTIONPROTOCOL_FORM_ID = 9; public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10; public static final int STORAGE_CONTAINER_FORM_ID = 11; public static final int STORAGE_TYPE_FORM_ID = 12; public static final int SITE_FORM_ID = 13; //Status message key Constants public static final String STATUS_MESSAGE_KEY = "statusMessageKey"; //Identifiers for JDBC DAO. public static final int QUERY_RESULT_TREE_JDBC_DAO = 1; //Activity Status values public static final String ACTIVITY_STATUS_ACTIVE = "Active"; public static final String ACTIVITY_STATUS_APPROVE = "Approve"; public static final String ACTIVITY_STATUS_REJECT = "Reject"; public static final String ACTIVITY_STATUS_NEW = "New"; public static final String ACTIVITY_STATUS_PENDING = "Pending"; public static final String ACTIVITY_STATUS_CLOSED = "Closed"; //Approve User Constants public static final int ZERO = 0; public static final int START_PAGE = 1; public static final int NUMBER_RESULTS_PER_PAGE = 5; public static final String PAGE_NUMBER = "pageNum"; public static final String RESULTS_PER_PAGE = "numResultsPerPage"; public static final String TOTAL_RESULTS = "totalResults"; public static final String PREVIOUS_PAGE = "prevpage"; public static final String NEXT_PAGE = "nextPage"; public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList"; public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList"; public static final String USER_DETAILS = "details"; public static final String CURRENT_RECORD = "currentRecord"; public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core."; //Query Interface Tree View Constants. public static final String ROOT = "Root"; //Query Interface Results View Constants public static final String PAGEOF = "pageOf"; public static final String QUERY = "query"; //Query results view temporary table name. public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS"; //Query results view temporary table columns. public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID"; public static final String QUERY_RESULTS_ACCESSION_ID = "ACCESSION_ID"; public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID"; public static final String QUERY_RESULTS_SEGMENT_ID = "SEGMENT_ID"; public static final String QUERY_RESULTS_SAMPLE_ID = "SAMPLE_ID"; //Query results edit constants - MakeEditableAction. public static final String EDITABLE = "editable"; //URL paths for Applet in TreeView.jsp public static final String QUERY_TREE_APPLET = "QueryTree.class"; public static final String APPLET_CODEBASE = "Applet"; public static final String [] RECEIVEDMODEARRAY = { "by hand", "courier", "FedEX", "UPS" }; public static final String [] GENOTYPIC_GENDER_ARRAY = { "Male", "Female" }; public static final String [] RACEARRAY = { "Asian", "American" }; public static final String [] PROTOCOLARRAY = { "aaaa", "bbbb", "cccc" }; public static final String [] RECEIVEDBYARRAY = { "xxxx", "yyyy", "zzzz" }; public static final String [] COLLECTEDBYARRAY = { "xxxx", "yyyy", "zzzz" }; public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"}; public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"}; public static final String [] STATEARRAY = { "Alabama",//Alabama "Alaska",//Alaska "Arizona",//Arizona "Arkansas",//Arkansas "California",//California "Colorado",//Colorado "Connecticut",//Connecticut "Delaware",//Delaware "D.C.", "Florida",//Florida "Georgia",//Georgia "Hawaii",//Hawaii "Idaho",//Idaho "Illinois",//Illinois "Indiana",//Indiana "Iowa",//Iowa "Kansas",//Kansas "Kentucky",//Kentucky "Louisiana",//Louisiana "Maine",//Maine "Maryland",//Maryland "Massachusetts",//Massachusetts "Michigan",//Michigan "Minnesota",//Minnesota "Mississippi",//Mississippi "Missouri",//Missouri "Montana",//Montana "Nebraska",//Nebraska "Nevada",//Nevada "New Hampshire",//New Hampshire "New Jersey",//New Jersey "New Mexico",//New Mexico "New York",//New York "North Carolina",//North Carolina "North Dakota",//North Dakota "Ohio",//Ohio "Oklahoma",//Oklahoma "Oregon",//Oregon "Pennsylvania",//Pennsylvania "Rhode Island",//Rhode Island "South Carolina",//South Carolina "South Dakota",//South Dakota "Tennessee",//Tennessee "Texas",//Texas "Utah",//Utah "Vermont",//Vermont "Virginia",//Virginia "Washington",//Washington "West Virginia",//West Virginia "Wisconsin",//Wisconsin "Wyoming",//Wyoming "Other",//Other }; public static final String [] COUNTRYARRAY = { "United States", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon",//Cameroon "Cape Verde",//Cape Verde "Cayman Islands",//Cayman Islands "Central African Republic",//Central African Republic "Chad",//Chad "Chile",//Chile "China",//China "Christmas Island",//Christmas Island "Cocos Islands",//Cocos Islands "Colombia",//Colombia "Comoros",//Comoros "Congo",//Congo "Cook Islands",//Cook Islands "Costa Rica",//Costa Rica "Cote D ivoire",//Cote D ivoire "Croatia",//Croatia "Cyprus",//Cyprus "Czech Republic",//Czech Republic "Denmark",//Denmark "Djibouti",//Djibouti "Dominica",//Dominica "Dominican Republic",//Dominican Republic "East Timor",//East Timor "Ecuador",//Ecuador "Egypt",//Egypt "El Salvador",//El Salvador "Equatorial Guinea",//Equatorial Guinea "Eritrea",//Eritrea "Estonia",//Estonia "Ethiopia",//Ethiopia "Falkland Islands",//Falkland Islands "Faroe Islands",//Faroe Islands "Fiji",//Fiji "Finland",//Finland "France",//France "French Guiana",//French Guiana "French Polynesia",//French Polynesia "French S. Territories",//French S. Territories "Gabon",//Gabon "Gambia",//Gambia "Georgia",//Georgia "Germany",//Germany "Ghana",//Ghana "Gibraltar",//Gibraltar "Greece",//Greece "Greenland",//Greenland "Grenada",//Grenada "Guadeloupe",//Guadeloupe "Guam",//Guam "Guatemala",//Guatemala "Guinea",//Guinea "Guinea-Bissau",//Guinea-Bissau "Guyana",//Guyana "Haiti",//Haiti "Honduras",//Honduras "Hong Kong",//Hong Kong "Hungary",//Hungary "Iceland",//Iceland "India",//India "Indonesia",//Indonesia "Iran",//Iran "Iraq",//Iraq "Ireland",//Ireland "Israel",//Israel "Italy",//Italy "Jamaica",//Jamaica "Japan",//Japan "Jordan",//Jordan "Kazakhstan",//Kazakhstan "Kenya",//Kenya "Kiribati",//Kiribati "Korea",//Korea "Kuwait",//Kuwait "Kyrgyzstan",//Kyrgyzstan "Laos",//Laos "Latvia",//Latvia "Lebanon",//Lebanon "Lesotho",//Lesotho "Liberia",//Liberia "Liechtenstein",//Liechtenstein "Lithuania",//Lithuania "Luxembourg",//Luxembourg "Macau",//Macau "Macedonia",//Macedonia "Madagascar",//Madagascar "Malawi",//Malawi "Malaysia",//Malaysia "Maldives",//Maldives "Mali",//Mali "Malta",//Malta "Marshall Islands",//Marshall Islands "Martinique",//Martinique "Mauritania",//Mauritania "Mauritius",//Mauritius "Mayotte",//Mayotte "Mexico",//Mexico "Micronesia",//Micronesia "Moldova",//Moldova "Monaco",//Monaco "Mongolia",//Mongolia "Montserrat",//Montserrat "Morocco",//Morocco "Mozambique",//Mozambique "Myanmar",//Myanmar "Namibia",//Namibia "Nauru",//Nauru "Nepal",//Nepal "Netherlands",//Netherlands "Netherlands Antilles",//Netherlands Antilles "New Caledonia",//New Caledonia "New Zealand",//New Zealand "Nicaragua",//Nicaragua "Niger",//Niger "Nigeria",//Nigeria "Niue",//Niue "Norfolk Island",//Norfolk Island "Norway",//Norway "Oman",//Oman "Pakistan",//Pakistan "Palau",//Palau "Panama",//Panama "Papua New Guinea",//Papua New Guinea "Paraguay",//Paraguay "Peru",//Peru "Philippines",//Philippines "Pitcairn",//Pitcairn "Poland",//Poland "Portugal",//Portugal "Puerto Rico",//Puerto Rico "Qatar",//Qatar "Reunion",//Reunion "Romania",//Romania "Russian Federation",//Russian Federation "Rwanda",//Rwanda "Saint Helena",//Saint Helena "Saint Kitts and Nevis",//Saint Kitts and Nevis "Saint Lucia",//Saint Lucia "Saint Pierre",//Saint Pierre "Saint Vincent",//Saint Vincent "Samoa",//Samoa "San Marino",//San Marino "Sao Tome and Principe",//Sao Tome and Principe "Saudi Arabia",//Saudi Arabia "Senegal",//Senegal "Seychelles",//Seychelles "Sierra Leone",//Sierra Leone "Singapore",//Singapore "Slovakia",//Slovakia "Slovenia",//Slovenia "Solomon Islands",//Solomon Islands "Somalia",//Somalia "South Africa",//South Africa "Spain",//Spain "Sri Lanka",//Sri Lanka "Sudan",//Sudan "Suriname",//Suriname "Swaziland",//Swaziland "Sweden",//Sweden "Switzerland",//Switzerland "Syrian Arab Republic",//Syrian Arab Republic "Taiwan",//Taiwan "Tajikistan",//Tajikistan "Tanzania",//Tanzania "Thailand",//Thailand "Togo",//Togo "Tokelau",//Tokelau "Tonga",//Tonga "Trinidad and Tobago",//Trinidad and Tobago "Tunisia",//Tunisia "Turkey",//Turkey "Turkmenistan",//Turkmenistan "Turks and Caicos Islands",//Turks and Caicos Islands "Tuvalu",//Tuvalu "Uganda",//Uganda "Ukraine",//Ukraine "United Arab Emirates",//United Arab Emirates "United Kingdom",//United Kingdom "Uruguay",//Uruguay "Uzbekistan",//Uzbekistan "Vanuatu",//Vanuatu "Vatican City State",//Vatican City State "Venezuela",//Venezuela "Vietnam",//Vietnam "Virgin Islands",//Virgin Islands "Wallis And Futuna Islands",//Wallis And Futuna Islands "Western Sahara",//Western Sahara "Yemen",//Yemen "Yugoslavia",//Yugoslavia "Zaire",//Zaire "Zambia",//Zambia "Zimbabwe",//Zimbabwe }; // Constants required in CollectionProtocol.jsp Page public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do"; public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do"; public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do"; // Constants required in DistributionProtocol.jsp Page public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do"; public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do"; public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do"; public static final String [] CANCER_RESEARCH_GROUP_VALUES = { "Siteman Cancer Center", "Washington University" }; public static final String [] ACTIVITY_STATUS_VALUES = { "Active", "Disabled", "Closed", "New", "Reject", "Pending" }; //Only for showing UI. public static final String [] ROLE_VALUES = { "Administrator", "Clinician", "Technician", "Scientist", "Public", "Collector" }; public static final String [] INSTITUTE_VALUES = { "Washington University" }; public static final String [] DEPARTMENT_VALUES = { "Cardiology", "Pathology" }; public static final String [] SPECIMEN_TYPE_VALUES = { "Tissue", "Fluid", "Cell", "Molecular" }; public static final String [] SPECIMEN_SUB_TYPE_VALUES = { "Blood", "Serum", "Plasma", }; public static final String [] TISSUE_SITE_VALUES = { "Adrenal-Cortex", "Adrenal-Medulla", "Adrenal-NOS" }; public static final String [] TISSUE_SIDE_VALUES = { "Lavage", "Metastatic Lesion", }; public static final String [] PATHOLOGICAL_STATUS_VALUES = { "Primary Tumor", "Metastatic Node", "Non-Maglignant Tissue", }; public static final String [] BIOHAZARD_NAME_VALUES = { "" }; public static final String [] BIOHAZARD_TYPE_VALUES = { "Radioactive" }; public static final String [] ETHNICITY_VALUES = { "-- Select --" }; public static final String [] PARTICIPANT_MEDICAL_RECORD_SOURCE_VALUES = { "-- Select --" }; public static final String [] PROTOCOL_TITLE_ARRAY = { "Protocol-1" }; public static final String [] PARTICIPANT_NAME_ARRAY = { "LastName,FirstName" }; public static final String [] PROTOCOL_PARTICIPANT_NUMBER_ARRAY = { "1","2","3","4" }; public static final String [] STUDY_CALENDAR_EVENT_POINT_ARRAY = { "30","60","90" }; public static final String [] CLINICAL_STATUS_ARRAY = { "Pre-Opt", "Post-Opt" }; public static final String [] SITE_TYPE_ARRAY = { "Collection", "Laboratory", "Repository" }; }
package edu.wustl.catissuecore.util.global; /** * This class stores the constants used in the operations in the application. * @author gautam_shetty */ public class Constants extends edu.wustl.common.util.global.Constants { //Constants used for authentication module. public static final String LOGIN = "login"; public static final String SESSION_DATA = "sessionData"; public static final String AND_JOIN_CONDITION = "AND"; public static final String OR_JOIN_CONDITION = "OR"; //Sri: Changed the format for displaying in Specimen Event list (#463) public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm"; public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd"; public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy"; // Mandar: Used for Date Validations in Validator Class public static final String DATE_SEPARATOR = "-"; public static final String DATE_SEPARATOR_DOT = "."; public static final String DATE_SEPARATOR_SLASH = "/"; public static final String MIN_YEAR = "1900"; public static final String MAX_YEAR = "9999"; //Database constants. public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y"; //DAO Constants. public static final int HIBERNATE_DAO = 1; public static final int JDBC_DAO = 2; public static final String SUCCESS = "success"; public static final String FAILURE = "failure"; public static final String EDIT = "edit"; public static final String VIEW = "view"; public static final String SEARCH = "search"; public static final String DELETE = "delete"; public static final String EXPORT = "export"; public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; public static final String SHOPPING_CART_EXPORT = "shoppingCartExport"; public static final String NEWUSERFORM = "newUserForm"; public static final String ACCESS_DENIED = "access_denied"; public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect"; public static final String CALLED_FROM = "calledFrom"; //Constants required for Forgot Password public static final String FORGOT_PASSWORD = "forgotpassword"; public static final String IDENTIFIER = "IDENTIFIER"; public static final String LOGINNAME = "loginName"; public static final String LASTNAME = "lastName"; public static final String FIRSTNAME = "firstName"; public static final String ERROR_DETAIL = "Error Detail"; public static final String INSTITUTION = "institution"; public static final String EMAIL = "email"; public static final String DEPARTMENT = "department"; public static final String ADDRESS = "address"; public static final String CITY = "city"; public static final String STATE = "state"; public static final String COUNTRY = "country"; public static final String OPERATION = "operation"; public static final String ACTIVITY_STATUS = "activityStatus"; public static final String NEXT_CONTAINER_NO = "startNumber"; public static final String CSM_USER_ID = "csmUserId"; public static final String INSTITUTIONLIST = "institutionList"; public static final String DEPARTMENTLIST = "departmentList"; public static final String STATELIST = "stateList"; public static final String COUNTRYLIST = "countryList"; public static final String ROLELIST = "roleList"; public static final String ROLEIDLIST = "roleIdList"; public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList"; public static final String GENDER_LIST = "genderList"; public static final String GENOTYPE_LIST = "genotypeList"; public static final String ETHNICITY_LIST = "ethnicityList"; public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList"; public static final String RACELIST = "raceList"; public static final String PARTICIPANT_LIST = "participantList"; public static final String PARTICIPANT_ID_LIST = "participantIdList"; public static final String PROTOCOL_LIST = "protocolList"; public static final String TIMEHOURLIST = "timeHourList"; public static final String TIMEMINUTESLIST = "timeMinutesList"; public static final String TIMEAMPMLIST = "timeAMPMList"; public static final String RECEIVEDBYLIST = "receivedByList"; public static final String COLLECTEDBYLIST = "collectedByList"; public static final String COLLECTIONSITELIST = "collectionSiteList"; public static final String RECEIVEDSITELIST = "receivedSiteList"; public static final String RECEIVEDMODELIST = "receivedModeList"; public static final String ACTIVITYSTATUSLIST = "activityStatusList"; public static final String USERLIST = "userList"; public static final String SITETYPELIST = "siteTypeList"; public static final String STORAGETYPELIST="storageTypeList"; public static final String STORAGECONTAINERLIST="storageContainerList"; public static final String SITELIST="siteList"; // public static final String SITEIDLIST="siteIdList"; public static final String USERIDLIST = "userIdList"; public static final String STORAGETYPEIDLIST="storageTypeIdList"; public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList"; public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant"; public static final String APPROVE_USER_STATUS_LIST = "statusList"; public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; //New Specimen lists. public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList"; public static final String SPECIMEN_TYPE_LIST = "specimenTypeList"; public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList"; public static final String TISSUE_SITE_LIST = "tissueSiteList"; public static final String TISSUE_SIDE_LIST = "tissueSideList"; public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList"; public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList"; public static final String BIOHAZARD_NAME_LIST = "biohazardNameList"; public static final String BIOHAZARD_ID_LIST = "biohazardIdList"; public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList"; public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList"; public static final String RECEIVED_QUALITY_LIST = "receivedQualityList"; //Constants for audit of disabled objects. public static final String UPDATE_OPERATION = "UPDATE"; public static final String ACTIVITY_STATUS_COLUMN = "ACTIVITY_STATUS"; //SpecimenCollecionGroup lists. public static final String PROTOCOL_TITLE_LIST = "protocolTitleList"; public static final String PARTICIPANT_NAME_LIST = "participantNameList"; public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList"; //public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList"; public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList"; //public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList"; public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray"; //public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray"; public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId"; public static final String REQ_PATH = "redirectTo"; public static final String CLINICAL_STATUS_LIST = "cinicalStatusList"; public static final String SPECIMEN_CLASS_LIST = "specimenClassList"; public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList"; public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap"; //Simple Query Interface Lists public static final String OBJECT_NAME_LIST = "objectNameList"; public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList"; public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle"; public static final String ATTRIBUTE_NAME_LIST = "attributeNameList"; public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList"; //Constants for Storage Container. public static final String STORAGE_CONTAINER_TYPE = "storageType"; public static final String STORAGE_CONTAINER_TO_BE_SELECTED = "storageToBeSelected"; public static final String STORAGE_CONTAINER_POSITION = "position"; public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject"; public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus"; public static final String START_NUMBER = "startNumber"; public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers"; public static final int STORAGE_CONTAINER_FIRST_ROW = 1; public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1; //event parameters lists public static final String METHOD_LIST = "methodList"; public static final String HOUR_LIST = "hourList"; public static final String MINUTES_LIST = "minutesList"; public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList"; public static final String PROCEDURE_LIST = "procedureList"; public static final String PROCEDUREIDLIST = "procedureIdList"; public static final String CONTAINER_LIST = "containerList"; public static final String CONTAINERIDLIST = "containerIdList"; public static final String FROMCONTAINERLIST="fromContainerList"; public static final String TOCONTAINERLIST="toContainerList"; public static final String FIXATION_LIST = "fixationList"; public static final String FROM_SITE_LIST="fromsiteList"; public static final String TO_SITE_LIST="tositeList"; public static final String ITEMLIST="itemList"; public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList"; public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList"; public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList"; public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList"; public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList"; public static final String STORAGE_STATUS_LIST="storageStatusList"; public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList"; public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList"; //For Specimen Event Parameters. public static final String SPECIMEN_ID = "specimenId"; public static final String FROM_POSITION_DATA = "fromPositionData"; public static final String POS_ONE ="posOne"; public static final String POS_TWO ="posTwo"; public static final boolean switchSecurity = true; public static final String STORAGE_CONTAINER_ID ="storContId"; public static final String IS_RNA = "isRNA"; public static final String MOLECULAR = "Molecular"; public static final String RNA = "RNA"; // New Participant Event Parameters public static final String PARTICIPANT_ID="participantId"; //Constants required in User.jsp Page public static final String USER_SEARCH_ACTION = "UserSearch.do"; public static final String USER_ADD_ACTION = "UserAdd.do"; public static final String USER_EDIT_ACTION = "UserEdit.do"; public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do"; public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do"; public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do"; public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do"; public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do"; //Constants required in Accession.jsp Page public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do"; public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do"; public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do"; //Constants required in StorageType.jsp Page public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do"; public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do"; public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do"; //Constants required in StorageContainer.jsp Page public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do"; public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do"; public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do"; public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "ShowStorageGridView.do"; //Constants required in Site.jsp Page public static final String SITE_SEARCH_ACTION = "SiteSearch.do"; public static final String SITE_ADD_ACTION = "SiteAdd.do"; public static final String SITE_EDIT_ACTION = "SiteEdit.do"; //Constants required in Site.jsp Page public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do"; public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do"; public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do"; //Constants required in Partcipant.jsp Page public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do"; public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do"; public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do"; //Constants required in Institution.jsp Page public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do"; public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do"; public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do"; //Constants required in Department.jsp Page public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do"; public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do"; public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do"; //Constants required in CollectionProtocolRegistration.jsp Page public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do"; public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do"; public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do"; //Constants required in CancerResearchGroup.jsp Page public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do"; public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do"; public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do"; //Constants required for Approve user public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do"; public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do"; //Reported Problem Constants public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do"; public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do"; public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do"; public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do"; //Query Results view Actions public static final String TREE_VIEW_ACTION = "TreeView.do"; public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do"; public static final String SIMPLE_QUERY_INTERFACE_ACTION = "/SimpleQueryInterface.do"; public static final String SEARCH_OBJECT_ACTION = "/SearchObject.do"; public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17"; //New Specimen Data Actions. public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do"; public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do"; public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do"; public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //Create Specimen Data Actions. public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do"; public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do"; public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do"; //ShoppingCart Actions. public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do"; public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do"; public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do"; public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do"; //Constants required in FrozenEventParameters.jsp Page public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do"; public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do"; public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do"; //Constants required in CheckInCheckOutEventParameters.jsp Page public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do"; //Constants required in ReceivedEventParameters.jsp Page public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do"; public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do"; public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do"; //Constants required in FluidSpecimenReviewEventParameters.jsp Page public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do"; //Constants required in CELLSPECIMENREVIEWParameters.jsp Page public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do"; //Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do"; // Constants required in DisposalEventParameters.jsp Page public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do"; public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do"; public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do"; // Constants required in ThawEventParameters.jsp Page public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do"; public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do"; public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do"; // Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do"; // Constants required in CollectionEventParameters.jsp Page public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do"; public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do"; public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do"; // Constants required in SpunEventParameters.jsp Page public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do"; public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do"; public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do"; // Constants required in EmbeddedEventParameters.jsp Page public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do"; public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do"; public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do"; // Constants required in TransferEventParameters.jsp Page public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do"; public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do"; public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do"; // Constants required in FixedEventParameters.jsp Page public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do"; public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do"; public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do"; // Constants required in ProcedureEventParameters.jsp Page public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do"; public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do"; public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do"; // Constants required in Distribution.jsp Page public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do"; public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do"; public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do"; //Spreadsheet Export Action public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do"; //Levels of nodes in query results tree. public static final int MAX_LEVEL = 5; public static final int MIN_LEVEL = 1; public static final String[] DEFAULT_TREE_SELECT_COLUMNS = { }; public static final String TABLE_DATA_TABLE_NAME = "CATISSUE_QUERY_INTERFACE_TABLE_DATA"; public static final String TABLE_DISPLAY_NAME_COLUMN = "DISPLAY_NAME"; public static final String TABLE_ALIAS_NAME_COLUMN = "ALIAS_NAME"; public static final String TABLE_FOR_SQI_COLUMN = "FOR_SQI"; //Frame names in Query Results page. public static final String DATA_VIEW_FRAME = "myframe1"; public static final String APPLET_VIEW_FRAME = "appletViewFrame"; //NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view). public static final String DATA_VIEW_ACTION = "DataView.do?nodeName="; public static final String VIEW_TYPE = "viewType"; //TissueSite Tree View Constants. public static final String PROPERTY_NAME = "propertyName"; //Constants for type of query results view. public static final String SPREADSHEET_VIEW = "Spreadsheet View"; public static final String OBJECT_VIEW = "Edit View"; //Spreadsheet view Constants in DataViewAction. public static final String PARTICIPANT = "Participant"; public static final String ACCESSION = "Accession"; public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier="; public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?systemIdentifier="; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?systemIdentifier="; public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?systemIdentifier="; //public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier="; //Individual view Constants in DataViewAction. public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList"; public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList"; public static final String SELECT_COLUMN_LIST = "selectColumnList"; public static final String CONFIGURED_SELECT_COLUMN_LIST = "configuredSelectColumnList"; public static final String CONFIGURED_COLUMN_DISPLAY_NAMES = "configuredColumnDisplayNames"; public static final String SELECTED_NODE = "selectedNode"; //Tree Data Action public static final String TREE_DATA_ACTION = "Data.do"; public static final String SPECIMEN = "Specimen"; public static final String SEGMENT = "Segment"; public static final String SAMPLE = "Sample"; public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration"; public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID"; public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID"; public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID"; public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID"; public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID"; //SimpleSearchAction public static final String SIMPLE_QUERY_NO_RESULTS = "noResults"; public static final String SIMPLE_QUERY_SINGLE_RESULT = "singleResult"; //For getting the tables for Simple Query and Fcon Query. public static final int SIMPLE_QUERY_TABLES = 1; public static final int ADVANCE_QUERY_TABLES = 2; //Identifiers for various Form beans public static final int USER_FORM_ID = 1; public static final int PARTICIPANT_FORM_ID = 2; public static final int ACCESSION_FORM_ID = 3; public static final int REPORTED_PROBLEM_FORM_ID = 4; public static final int INSTITUTION_FORM_ID = 5; public static final int APPROVE_USER_FORM_ID = 6; public static final int ACTIVITY_STATUS_FORM_ID = 7; public static final int DEPARTMENT_FORM_ID = 8; public static final int COLLECTION_PROTOCOL_FORM_ID = 9; public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10; public static final int STORAGE_CONTAINER_FORM_ID = 11; public static final int STORAGE_TYPE_FORM_ID = 12; public static final int SITE_FORM_ID = 13; public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14; public static final int BIOHAZARD_FORM_ID = 15; public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16; public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17; public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18; public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19; public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20; public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21; public static final int NEW_SPECIMEN_FORM_ID = 22; public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23; public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24; public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25; public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26; public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27; public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28; public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29; public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30; public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31; public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32; public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33; public static final int CREATE_SPECIMEN_FORM_ID = 34; public static final int FORGOT_PASSWORD_FORM_ID = 35; public static final int SIGNUP_FORM_ID = 36; public static final int DISTRIBUTION_FORM_ID = 37; public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38; public static final int SHOPPING_CART_FORM_ID = 39; public static final int SIMPLE_QUERY_INTERFACE_ID = 40; public static final int CONFIGURE_RESULT_VIEW_ID = 41; public static final int ADVANCE_QUERY_INTERFACE_ID = 42; public static final int QUERY_INTERFACE_ID = 43; //Misc public static final String SEPARATOR = " : "; //Status message key Constants public static final String STATUS_MESSAGE_KEY = "statusMessageKey"; //Identifiers for JDBC DAO. public static final int QUERY_RESULT_TREE_JDBC_DAO = 1; //Activity Status values public static final String ACTIVITY_STATUS_APPROVE = "Approve"; public static final String ACTIVITY_STATUS_REJECT = "Reject"; public static final String ACTIVITY_STATUS_NEW = "New"; public static final String ACTIVITY_STATUS_PENDING = "Pending"; public static final String ACTIVITY_STATUS_CLOSED = "Closed"; public static final String ACTIVITY_STATUS_DISABLED = "Disabled"; //Approve User status values. public static final String APPROVE_USER_APPROVE_STATUS = "Approve"; public static final String APPROVE_USER_REJECT_STATUS = "Reject"; public static final String APPROVE_USER_PENDING_STATUS = "Pending"; //Approve User Constants public static final int ZERO = 0; public static final int START_PAGE = 1; public static final int NUMBER_RESULTS_PER_PAGE = 5; public static final String PAGE_NUMBER = "pageNum"; public static final String RESULTS_PER_PAGE = "numResultsPerPage"; public static final String TOTAL_RESULTS = "totalResults"; public static final String PREVIOUS_PAGE = "prevpage"; public static final String NEXT_PAGE = "nextPage"; public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList"; public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList"; public static final String USER_DETAILS = "details"; public static final String CURRENT_RECORD = "currentRecord"; public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core."; //Tree View Constants. public static final String ROOT = "Root"; public static final String CATISSUE_CORE = "caTISSUE Core"; public static final String TISSUE_SITE = "Tissue Site"; public static final int TISSUE_SITE_TREE_ID = 1; public static final int STORAGE_CONTAINER_TREE_ID = 2; public static final int QUERY_RESULTS_TREE_ID = 3; //Edit Object Constants. public static final String TABLE_ALIAS_NAME = "aliasName"; public static final String FIELD_TYPE_VARCHAR = "varchar"; public static final String FIELD_TYPE_BIGINT = "bigint"; public static final String FIELD_TYPE_DATE = "date"; public static final String FIELD_TYPE_TEXT = "text"; public static final String FIELD_TYPE_TINY_INT = "tinyint"; public static final String CONDITION_VALUE_YES = "yes"; public static final String TINY_INT_VALUE_ONE = "1"; public static final String TINY_INT_VALUE_ZERO = "0"; //Query Interface Results View Constants public static final String PAGEOF = "pageOf"; public static final String QUERY = "query"; public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser"; public static final String PAGEOF_SIGNUP = "pageOfSignUp"; public static final String PAGEOF_USERADD = "pageOfUserAdd"; public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin"; public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile"; public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword"; //For Tree Applet public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults"; public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation"; public static final String PAGEOF_SPECIMEN = "pageOfSpecimen"; public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite"; //For Simple Query Interface and Edit. public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface"; public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject"; //Query results view temporary table name. public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS"; //Query results view temporary table columns. public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID"; public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID"; public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID"; public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE"; // Assign Privilege Constants. public static final boolean PRIVILEGE_DEASSIGN = false; //Constants for default column names to be shown for query result. public static final String[] DEFAULT_SPREADSHEET_COLUMNS = { // QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID, // QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID, // QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE "IDENTIFIER","TYPE","ONE_DIMENSION_LABEL" }; //Query results edit constants - MakeEditableAction. public static final String EDITABLE = "editable"; //URL paths for Applet in TreeView.jsp public static final String QUERY_TREE_APPLET = "QueryTree.class"; public static final String APPLET_CODEBASE = "Applet"; public static final String TREE_APPLET_NAME = "treeApplet"; //Shopping Cart public static final String SHOPPING_CART = "shoppingCart"; public static final int SELECT_OPTION_VALUE = -1; // public static final String[] TISSUE_SITE_ARRAY = { // SELECT_OPTION,"Sex","male","female", // "Tissue","kidney","Left kidney","Right kidney" public static final String[] ATTRIBUTE_NAME_ARRAY = { SELECT_OPTION }; public static final String[] ATTRIBUTE_CONDITION_ARRAY = { "=","<",">" }; public static final String [] RECEIVEDMODEARRAY = { SELECT_OPTION, "by hand", "courier", "FedEX", "UPS" }; public static final String [] GENDER_ARRAY = { SELECT_OPTION, "Male", "Female" }; public static final String [] GENOTYPE_ARRAY = { SELECT_OPTION, "XX", "XY" }; public static final String [] RACEARRAY = { SELECT_OPTION, "Asian", "American" }; public static final String [] PROTOCOLARRAY = { SELECT_OPTION, "aaaa", "bbbb", "cccc" }; public static final String [] RECEIVEDBYARRAY = { SELECT_OPTION, "xxxx", "yyyy", "zzzz" }; public static final String [] COLLECTEDBYARRAY = { SELECT_OPTION, "xxxx", "yyyy", "zzzz" }; public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"}; public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"}; public static final String [] STATEARRAY = { SELECT_OPTION, "Alabama",//Alabama "Alaska",//Alaska "Arizona",//Arizona "Arkansas",//Arkansas "California",//California "Colorado",//Colorado "Connecticut",//Connecticut "Delaware",//Delaware "D.C.", "Florida",//Florida "Georgia",//Georgia "Hawaii",//Hawaii "Idaho",//Idaho "Illinois",//Illinois "Indiana",//Indiana "Iowa",//Iowa "Kansas",//Kansas "Kentucky",//Kentucky "Louisiana",//Louisiana "Maine",//Maine "Maryland",//Maryland "Massachusetts",//Massachusetts "Michigan",//Michigan "Minnesota",//Minnesota "Mississippi",//Mississippi "Missouri",//Missouri "Montana",//Montana "Nebraska",//Nebraska "Nevada",//Nevada "New Hampshire",//New Hampshire "New Jersey",//New Jersey "New Mexico",//New Mexico "New York",//New York "North Carolina",//North Carolina "North Dakota",//North Dakota "Ohio",//Ohio "Oklahoma",//Oklahoma "Oregon",//Oregon "Pennsylvania",//Pennsylvania "Rhode Island",//Rhode Island "South Carolina",//South Carolina "South Dakota",//South Dakota "Tennessee",//Tennessee "Texas",//Texas "Utah",//Utah "Vermont",//Vermont "Virginia",//Virginia "Washington",//Washington "West Virginia",//West Virginia "Wisconsin",//Wisconsin "Wyoming",//Wyoming "Other",//Other }; public static final String [] COUNTRYARRAY = { SELECT_OPTION, "United States", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon",//Cameroon "Cape Verde",//Cape Verde "Cayman Islands",//Cayman Islands "Central African Republic",//Central African Republic "Chad",//Chad "Chile",//Chile "China",//China "Christmas Island",//Christmas Island "Cocos Islands",//Cocos Islands "Colombia",//Colombia "Comoros",//Comoros "Congo",//Congo "Cook Islands",//Cook Islands "Costa Rica",//Costa Rica "Cote D ivoire",//Cote D ivoire "Croatia",//Croatia "Cyprus",//Cyprus "Czech Republic",//Czech Republic "Denmark",//Denmark "Djibouti",//Djibouti "Dominica",//Dominica "Dominican Republic",//Dominican Republic "East Timor",//East Timor "Ecuador",//Ecuador "Egypt",//Egypt "El Salvador",//El Salvador "Equatorial Guinea",//Equatorial Guinea "Eritrea",//Eritrea "Estonia",//Estonia "Ethiopia",//Ethiopia "Falkland Islands",//Falkland Islands "Faroe Islands",//Faroe Islands "Fiji",//Fiji "Finland",//Finland "France",//France "French Guiana",//French Guiana "French Polynesia",//French Polynesia "French S. Territories",//French S. Territories "Gabon",//Gabon "Gambia",//Gambia "Georgia",//Georgia "Germany",//Germany "Ghana",//Ghana "Gibraltar",//Gibraltar "Greece",//Greece "Greenland",//Greenland "Grenada",//Grenada "Guadeloupe",//Guadeloupe "Guam",//Guam "Guatemala",//Guatemala "Guinea",//Guinea "Guinea-Bissau",//Guinea-Bissau "Guyana",//Guyana "Haiti",//Haiti "Honduras",//Honduras "Hong Kong",//Hong Kong "Hungary",//Hungary "Iceland",//Iceland "India",//India "Indonesia",//Indonesia "Iran",//Iran "Iraq",//Iraq "Ireland",//Ireland "Israel",//Israel "Italy",//Italy "Jamaica",//Jamaica "Japan",//Japan "Jordan",//Jordan "Kazakhstan",//Kazakhstan "Kenya",//Kenya "Kiribati",//Kiribati "Korea",//Korea "Kuwait",//Kuwait "Kyrgyzstan",//Kyrgyzstan "Laos",//Laos "Latvia",//Latvia "Lebanon",//Lebanon "Lesotho",//Lesotho "Liberia",//Liberia "Liechtenstein",//Liechtenstein "Lithuania",//Lithuania "Luxembourg",//Luxembourg "Macau",//Macau "Macedonia",//Macedonia "Madagascar",//Madagascar "Malawi",//Malawi "Malaysia",//Malaysia "Maldives",//Maldives "Mali",//Mali "Malta",//Malta "Marshall Islands",//Marshall Islands "Martinique",//Martinique "Mauritania",//Mauritania "Mauritius",//Mauritius "Mayotte",//Mayotte "Mexico",//Mexico "Micronesia",//Micronesia "Moldova",//Moldova "Monaco",//Monaco "Mongolia",//Mongolia "Montserrat",//Montserrat "Morocco",//Morocco "Mozambique",//Mozambique "Myanmar",//Myanmar "Namibia",//Namibia "Nauru",//Nauru "Nepal",//Nepal "Netherlands",//Netherlands "Netherlands Antilles",//Netherlands Antilles "New Caledonia",//New Caledonia "New Zealand",//New Zealand "Nicaragua",//Nicaragua "Niger",//Niger "Nigeria",//Nigeria "Niue",//Niue "Norfolk Island",//Norfolk Island "Norway",//Norway "Oman",//Oman "Pakistan",//Pakistan "Palau",//Palau "Panama",//Panama "Papua New Guinea",//Papua New Guinea "Paraguay",//Paraguay "Peru",//Peru "Philippines",//Philippines "Pitcairn",//Pitcairn "Poland",//Poland "Portugal",//Portugal "Puerto Rico",//Puerto Rico "Qatar",//Qatar "Reunion",//Reunion "Romania",//Romania "Russian Federation",//Russian Federation "Rwanda",//Rwanda "Saint Helena",//Saint Helena "Saint Kitts and Nevis",//Saint Kitts and Nevis "Saint Lucia",//Saint Lucia "Saint Pierre",//Saint Pierre "Saint Vincent",//Saint Vincent "Samoa",//Samoa "San Marino",//San Marino "Sao Tome and Principe",//Sao Tome and Principe "Saudi Arabia",//Saudi Arabia "Senegal",//Senegal "Seychelles",//Seychelles "Sierra Leone",//Sierra Leone "Singapore",//Singapore "Slovakia",//Slovakia "Slovenia",//Slovenia "Solomon Islands",//Solomon Islands "Somalia",//Somalia "South Africa",//South Africa "Spain",//Spain "Sri Lanka",//Sri Lanka "Sudan",//Sudan "Suriname",//Suriname "Swaziland",//Swaziland "Sweden",//Sweden "Switzerland",//Switzerland "Syrian Arab Republic",//Syrian Arab Republic "Taiwan",//Taiwan "Tajikistan",//Tajikistan "Tanzania",//Tanzania "Thailand",//Thailand "Togo",//Togo "Tokelau",//Tokelau "Tonga",//Tonga "Trinidad and Tobago",//Trinidad and Tobago "Tunisia",//Tunisia "Turkey",//Turkey "Turkmenistan",//Turkmenistan "Turks and Caicos Islands",//Turks and Caicos Islands "Tuvalu",//Tuvalu "Uganda",//Uganda "Ukraine",//Ukraine "United Arab Emirates",//United Arab Emirates "United Kingdom",//United Kingdom "Uruguay",//Uruguay "Uzbekistan",//Uzbekistan "Vanuatu",//Vanuatu "Vatican City State",//Vatican City State "Venezuela",//Venezuela "Vietnam",//Vietnam "Virgin Islands",//Virgin Islands "Wallis And Futuna Islands",//Wallis And Futuna Islands "Western Sahara",//Western Sahara "Yemen",//Yemen "Yugoslavia",//Yugoslavia "Zaire",//Zaire "Zambia",//Zambia "Zimbabwe",//Zimbabwe }; // Constants required in CollectionProtocol.jsp Page public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do"; public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do"; public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do"; // Constants required in DistributionProtocol.jsp Page public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do"; public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do"; public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do"; public static final String [] ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed", "Disabled" }; public static final String [] SITE_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] USER_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] APPROVE_USER_STATUS_VALUES = { SELECT_OPTION, APPROVE_USER_APPROVE_STATUS, APPROVE_USER_REJECT_STATUS, APPROVE_USER_PENDING_STATUS, }; public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Closed", "Pending" }; public static final String [] SPECIMEN_TYPE_VALUES = { SELECT_OPTION, "Tissue", "Fluid", "Cell", "Molecular" }; public static final String [] HOUR_ARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public static final String [] MINUTES_ARRAY = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public static final String [] METHODARRAY = { SELECT_OPTION, "LN2", "Dry Ice", "Iso pentane" }; public static final String [] EMBEDDINGMEDIUMARRAY = { SELECT_OPTION, "Plastic", "Glass", }; public static final String [] ITEMARRAY = { SELECT_OPTION, "Item1", "Item2", }; public static final String UNIT_GM = "gm"; public static final String UNIT_ML = "ml"; public static final String UNIT_CC = "cell count"; public static final String UNIT_MG = "g"; public static final String UNIT_CN = "count"; public static final String [] PROCEDUREARRAY = { SELECT_OPTION, "Procedure 1", "Procedure 2", "Procedure 3" }; public static final String [] CONTAINERARRAY = { SELECT_OPTION, "Container 1", "Container 2", "Container 3" }; public static final String [] FIXATIONARRAY = { SELECT_OPTION, "FIXATION 1", "FIXATION 2", "FIXATION 3" }; public static final String CDE_NAME_TISSUE_SITE = "Tissue Site"; public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status"; public static final String CDE_NAME_GENDER = "Gender"; public static final String CDE_NAME_GENOTYPE = "Genotype"; public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen"; public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type"; public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side"; public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status"; public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality"; public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type"; public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure"; public static final String CDE_NAME_CONTAINER = "Container"; public static final String CDE_NAME_METHOD = "Method"; public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium"; public static final String CDE_NAME_BIOHAZARD = "Biohazard"; public static final String CDE_NAME_ETHNICITY = "Ethnicity"; public static final String CDE_NAME_RACE = "Race"; public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis"; public static final String CDE_NAME_SITE_TYPE = "Site Type"; //Constants for Advanced Search public static final String STRING_OPERATORS = "StringOperators"; public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators"; public static final String ENUMERATED_OPERATORS = "EnumeratedOperators"; public static final String [] STORAGE_STATUS_ARRAY = { SELECT_OPTION, "CHECK IN", "CHECK OUT" }; public static final String [] CLINICALDIAGNOSISARRAY = { SELECT_OPTION, "CLINICALDIAGNOSIS 1", "CLINICALDIAGNOSIS 2", "CLINICALDIAGNOSIS 3" }; public static final String [] HISTOLOGICAL_QUALITY_ARRAY = { SELECT_OPTION, "GOOD", "OK", "DAMAGED" }; // constants for Data required in query public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames"; public static final String SYSTEM_IDENTIFIER = "systemIdentifier"; public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER"; public static final String NAME = "name"; public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION, "Cell Specimen Review", "Check In Check Out", "Collection", "Disposal", "Embedded", "Fixed", "Fluid Specimen Review", "Frozen", "Molecular Specimen Review", "Procedure", "Received", "Spun", "Thaw", "Tissue Specimen Review", "Transfer" }; public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier", "Event Parameter", "User", "Date / Time", "PageOf"}; public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier", "Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"}; public static final String ACCESS_DENIED_ADMIN = "access_denied_admin"; public static final String ACCESS_DENIED_BIOSPECIMEN = "access_denied_biospecimen"; //Constants required in AssignPrivileges.jsp public static final String ASSIGN = "assignOperation"; public static final String PRIVILEGES = "privileges"; public static final String OBJECT_TYPES = "objectTypes"; public static final String OBJECT_TYPE_VALUES = "objectTypeValues"; public static final String RECORD_IDS = "recordIds"; public static final String ATTRIBUTES = "attributes"; public static final String GROUPS = "groups"; public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do"; public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2; /** * @param systemIdentifier * @return */ public static String getUserPGName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } /** * @param systemIdentifier * @return */ public static String getUserGroupName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } public static final String SLIDE = "Slide"; public static final String PARAFFIN_BLOCK = "Paraffin Block"; public static final String FROZEN_BLOCK = "Frozen Block"; // constants required for Distribution Report public static final String CONFIGURATION_TABLES = "configurationTables"; public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtocolRegistration","Participant","Specimen", "SpecimenCollectionGroup","DistributedItem"}; public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap"; public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do"; public static final String TABLE_NAMES_LIST = "tableNamesList"; public static final String COLUMN_NAMES_LIST = "columnNamesList"; public static final String DISTRIBUTION_ID = "distributionId"; public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do"; public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do"; public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do"; public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Specimen Identifier", "Specimen.TYPE.Specimen Type", "SpecimenCharacteristics.TISSUE_SITE.Tissue Site", "SpecimenCharacteristics.TISSUE_SIDE.Tissue Side", "SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status", "DistributedItem.QUANTITY.Specimen Quantity"}; public static final String SPECIMEN_ID_LIST = "specimenIdList"; public static final String DISTRIBUTION_ACTION = "Distribution.do?operation=add&pageOf=pageOfDistribution&specimenIdKey="; public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.tsv"; public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm"; public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData"; //constants for Simple Query Interface Configuration public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do"; public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do"; public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do"; public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do"; public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do"; public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution"; public static final String RESULT_VIEW_VECTOR = "resultViewVector"; public static final String SIMPLE_QUERY_MAP = "simpleQueryMap"; public static final String SIMPLE_QUERY_ALIAS_NAME = "simpleQueryAliasName"; public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount"; public static final String UNDEFINED = "Undefined"; public static final String UNKNOWN = "Unknown"; public static final String SEARCH_RESULT = "SearchResult.tsv"; // MD : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587 public static final String ODD_COLOR = "#FEFB85"; public static final String EVEN_COLOR = "#A7FEAB"; // Light and dark shades of GREY. // public static final String ODD_COLOR = "#E5E5E5"; // public static final String EVEN_COLOR = "#F7F7F7"; // TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do"; public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do"; public static final String PARENT_SPECIMEN_ID = "parentSpecimenId"; public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId"; public static final String FORWARDLIST = "forwardToList"; public static final String [][] SPECIMEN_FORWARD_TO_LIST = { {"Normal Submit", "success"}, {"Derive New From This Specimen", "createNew"}, {"Add Events", "eventParameters"}, {"Add More To Same Collection Group", "sameCollectionGroup"} }; public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = { {"Normal Submit", "success"}, {"Add New Specimen", "createNewSpecimen"} }; public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = { {"Normal Submit", "success"}, {"New Specimen Collection Group", "createSpecimenCollectionGroup"} }; public static final String [][] PARTICIPANT_FORWARD_TO_LIST = { {"Normal Submit", "success"}, {"New Participant Registration", "createParticipantRegistration"} }; //Constants Required for Advance Search //Tree related //public static final String PARTICIPANT ='Participant'; public static final String COLLECTION_PROTOCOL ="CollectionProtocol"; public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup"; public static final String DISTRIBUTION = "Distribution"; public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String CP = "CP"; public static final String SCG = "SCG"; public static final String D = "D"; public static final String DP = "DP"; public static final String C = "C"; public static final String S = "S"; public static final String P = "P"; public static final String ADVANCED_CONDITION_NODES_MAP = "advancedConditionNodesMap"; public static final String TREE_VECTOR = "treeVector"; public static final String ADVANCED_CONDITIONS_ROOT = "advancedCondtionsRoot"; public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView"; public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do"; public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do"; public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do"; public static final String ADVANCED_QUERY_ADD = "Add"; public static final String ADVANCED_QUERY_EDIT = "Edit"; public static final String ADVANCED_QUERY_DELETE = "Delete"; public static final String ADVANCED_QUERY_OPERATOR = "Operator"; public static final String ADVANCED_QUERY_OR = "OR"; public static final String ADVANCED_QUERY_AND = "AND"; public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap"; public static final String COLUMN_ID_MAP = "columnIdsMap"; public static final String PARENT_SPECIMEN_ID_COLUMN = "PARENT_SPECIMEN_ID"; public static final String COLUMN = "Column"; public static final String COLUMN_DISPLAY_NAMES = "columnDisplayNames"; public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit"; public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit"; public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit"; public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit"; public static final String PARTICIPANT_COLUMNS = "particpantColumns"; public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns"; public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns"; public static final String SPECIMEN_COLUMNS = "SpecimenColumns"; // -- menu selection related public static final String MENU_SELECTED = "menuSelected"; public static final String CONSTRAINT_VOILATION_ERROR = "Submission failed since a {0} with the same {1} already exists"; public static final String GENERIC_DATABASE_ERROR = "An error occured during a database operation. Please report this problem to the adminstrator"; // The unique key voilation message is "Duplicate entry %s for key %d" // This string is used for searching " for key " string in the above error message public static final String MYSQL_DUPL_KEY_MSG = " for key "; public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator"; public static final String DATABASE_IN_USED = "MYSQL"; public static final String PASSWORD_CHANGE_IN_SESSION = "changepassword"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain"; //Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic public static final boolean IS_AUDITABLE_TRUE = true; public static final boolean IS_SECURE_UPDATE_TRUE = true; public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false; }
package edu.wustl.catissuecore.util.global; import java.util.HashMap; /** * This class stores the constants used in the operations in the application. * @author gautam_shetty */ public class Constants { //Constants used for authentication module. public static final String LOGIN = "login"; public static final String SESSION_DATA = "sessionData"; public static final String AND_JOIN_CONDITION = "AND"; public static final String OR_JOIN_CONDITION = "OR"; public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm aa"; public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd"; public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy"; //Database constants. public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y"; //DAO Constants. public static final int HIBERNATE_DAO = 1; public static final int JDBC_DAO = 2; public static final String SUCCESS = "success"; public static final String FAILURE = "failure"; public static final String ADD = "add"; public static final String EDIT = "edit"; public static final String VIEW = "view"; public static final String SEARCH = "search"; public static final String DELETE = "delete"; public static final String EXPORT = "export"; public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; public static final String SHOPPING_CART_EXPORT = "shoppingCartExport"; public static final String NEWUSERFORM = "newUserForm"; public static final String ACCESS_DENIED = "access_denied"; //Constants required for Forgot Password public static final String FORGOT_PASSWORD = "forgotpassword"; public static final String IDENTIFIER = "systemIdentifier"; public static final String LOGINNAME = "loginName"; public static final String LASTNAME = "lastName"; public static final String FIRSTNAME = "firstName"; public static final String ERROR_DETAIL = "Error Detail"; public static final String INSTITUTION = "institution"; public static final String EMAIL = "email"; public static final String DEPARTMENT = "department"; public static final String ADDRESS = "address"; public static final String CITY = "city"; public static final String STATE = "state"; public static final String COUNTRY = "country"; public static final String OPERATION = "operation"; public static final String ACTIVITY_STATUS = "activityStatus"; public static final String NEXT_CONTAINER_NO = "startNumber"; public static final String INSTITUTIONLIST = "institutionList"; public static final String DEPARTMENTLIST = "departmentList"; public static final String STATELIST = "stateList"; public static final String COUNTRYLIST = "countryList"; public static final String ROLELIST = "roleList"; public static final String ROLEIDLIST = "roleIdList"; public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList"; public static final String GENDER_LIST = "genderList"; public static final String GENOTYPE_LIST = "genotypeList"; public static final String ETHNICITY_LIST = "ethnicityList"; public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList"; public static final String RACELIST = "raceList"; public static final String PARTICIPANT_LIST = "participantList"; public static final String PARTICIPANT_ID_LIST = "participantIdList"; public static final String PROTOCOL_LIST = "protocolList"; public static final String TIMEHOURLIST = "timeHourList"; public static final String TIMEMINUTESLIST = "timeMinutesList"; public static final String TIMEAMPMLIST = "timeAMPMList"; public static final String RECEIVEDBYLIST = "receivedByList"; public static final String COLLECTEDBYLIST = "collectedByList"; public static final String COLLECTIONSITELIST = "collectionSiteList"; public static final String RECEIVEDSITELIST = "receivedSiteList"; public static final String RECEIVEDMODELIST = "receivedModeList"; public static final String ACTIVITYSTATUSLIST = "activityStatusList"; public static final String USERLIST = "userList"; public static final String SITETYPELIST = "siteTypeList"; public static final String STORAGETYPELIST="storageTypeList"; public static final String STORAGECONTAINERLIST="storageContainerList"; public static final String SITELIST="siteList"; // public static final String SITEIDLIST="siteIdList"; public static final String USERIDLIST = "userIdList"; public static final String STORAGETYPEIDLIST="storageTypeIdList"; public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList"; public static final String APPROVE_USER_STATUS_LIST = "statusList"; public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; //New Specimen lists. public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList"; public static final String SPECIMEN_TYPE_LIST = "specimenTypeList"; public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList"; public static final String TISSUE_SITE_LIST = "tissueSiteList"; public static final String TISSUE_SIDE_LIST = "tissueSideList"; public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList"; public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList"; public static final String BIOHAZARD_NAME_LIST = "biohazardNameList"; public static final String BIOHAZARD_ID_LIST = "biohazardIdList"; public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList"; public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList"; public static final String RECEIVED_QUALITY_LIST = "receivedQualityList"; //SpecimenCollecionGroup lists. public static final String PROTOCOL_TITLE_LIST = "protocolTitleList"; public static final String PARTICIPANT_NAME_LIST = "participantNameList"; public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList"; //public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList"; public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList"; //public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList"; public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray"; //public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray"; public static final String CLINICAL_STATUS_LIST = "cinicalStatusList"; public static final String SPECIMEN_CLASS_LIST = "specimenClassList"; public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList"; public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap"; //Simple Query Interface Lists public static final String OBJECT_NAME_LIST = "objectNameList"; public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList"; public static final String ATTRIBUTE_NAME_LIST = "attributeNameList"; public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList"; //Constants for Storage Container. public static final String STORAGE_CONTAINER_TYPE = "storageType"; public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject"; public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus"; public static final String START_NUMBER = "startNumber"; public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers"; //event parameters lists public static final String METHODLIST = "methodList"; public static final String HOURLIST = "hourList"; public static final String MINUTESLIST = "minutesList"; public static final String EMBEDDINGMEDIUMLIST = "embeddingMediumList"; public static final String PROCEDURELIST = "procedureList"; public static final String PROCEDUREIDLIST = "procedureIdList"; public static final String CONTAINERLIST = "containerList"; public static final String CONTAINERIDLIST = "containerIdList"; public static final String FROMCONTAINERLIST="fromContainerList"; public static final String TOCONTAINERLIST="toContainerList"; public static final String FIXATIONLIST = "fixationList"; public static final String FROMSITELIST="fromsiteList"; public static final String TOSITELIST="tositeList"; public static final String ITEMLIST="itemList"; public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList"; public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList"; public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList"; public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList"; public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList"; public static final String STORAGESTATUSLIST="storageStatusList"; public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList"; public static final String HISTOLOGICALQUALITYLIST="histologicalQualityList"; //For Specimen Event Parameters. public static final String SPECIMEN_ID = "specimenId"; public static final String FROM_POSITION_DATA = "fromPositionData"; public static final String POS_ONE ="posOne"; public static final String POS_TWO ="posTwo"; public static final String STORAGE_CONTAINER_ID ="storContId"; public static final String IS_RNA = "isRNA"; //Constants required in User.jsp Page public static final String USER_SEARCH_ACTION = "UserSearch.do"; public static final String USER_ADD_ACTION = "UserAdd.do"; public static final String USER_EDIT_ACTION = "UserEdit.do"; public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do"; public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do"; public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do"; //Constants required in Accession.jsp Page public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do"; public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do"; public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do"; //Constants required in StorageType.jsp Page public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do"; public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do"; public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do"; //Constants required in StorageContainer.jsp Page public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do"; public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do"; public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do"; public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "/catissuecore/ShowStorageGridView.do"; //Constants required in Site.jsp Page public static final String SITE_SEARCH_ACTION = "SiteSearch.do"; public static final String SITE_ADD_ACTION = "SiteAdd.do"; public static final String SITE_EDIT_ACTION = "SiteEdit.do"; //Constants required in Site.jsp Page public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do"; public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do"; public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do"; //Constants required in Partcipant.jsp Page public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do"; public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do"; public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do"; //Constants required in Institution.jsp Page public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do"; public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do"; public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do"; //Constants required in Department.jsp Page public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do"; public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do"; public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do"; //Constants required in CollectionProtocolRegistration.jsp Page public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do"; public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do"; public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do"; //Constants required in CancerResearchGroup.jsp Page public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do"; public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do"; public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do"; //Constants required for Approve user public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do"; public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do"; //Reported Problem Constants public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do"; public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do"; public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do"; public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do"; //Query Results view Actions public static final String TREE_VIEW_ACTION = "TreeView.do"; public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do"; //New Specimen Data Actions. public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do"; public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do"; public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do"; public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "NewSpecimenEventParameters.do"; //Create Specimen Data Actions. public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do"; public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do"; public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do"; //ShoppingCart Actions. public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do"; public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do"; public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do"; public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do"; //Constants required in FrozenEventParameters.jsp Page public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do"; public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do"; public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do"; //Constants required in CheckInCheckOutEventParameters.jsp Page public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do"; //Constants required in ReceivedEventParameters.jsp Page public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do"; public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do"; public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do"; //Constants required in FluidSpecimenReviewEventParameters.jsp Page public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do"; //Constants required in CELLSPECIMENREVIEWParameters.jsp Page public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do"; //Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do"; // Constants required in DisposalEventParameters.jsp Page public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do"; public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do"; public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do"; // Constants required in ThawEventParameters.jsp Page public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do"; public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do"; public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do"; // Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do"; // Constants required in CollectionEventParameters.jsp Page public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do"; public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do"; public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do"; // Constants required in SpunEventParameters.jsp Page public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do"; public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do"; public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do"; // Constants required in EmbeddedEventParameters.jsp Page public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do"; public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do"; public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do"; // Constants required in TransferEventParameters.jsp Page public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do"; public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do"; public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do"; // Constants required in FixedEventParameters.jsp Page public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do"; public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do"; public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do"; // Constants required in ProcedureEventParameters.jsp Page public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do"; public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do"; public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do"; // Constants required in Distribution.jsp Page public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do"; public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do"; public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do"; //Levels of nodes in query results tree. public static final int MAX_LEVEL = 5; public static final int MIN_LEVEL = 1; public static final String[] DEFAULT_TREE_SELECT_COLUMNS = { }; //Frame names in Query Results page. public static final String DATA_VIEW_FRAME = "myframe1"; public static final String APPLET_VIEW_FRAME = "appletViewFrame"; //NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view). public static final String DATA_VIEW_ACTION = "/catissuecore/DataView.do?nodeName="; public static final String VIEW_TYPE = "viewType"; //TissueSite Tree View Constants. public static final String PROPERTY_NAME = "propertyName"; //Constants for type of query results view. public static final String SPREADSHEET_VIEW = "Spreadsheet View"; public static final String OBJECT_VIEW = "Object View"; //Spreadsheet view Constants in DataViewAction. public static final String PARTICIPANT = "Participant"; public static final String ACCESSION = "Accession"; public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier="; public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier="; //Individual view Constants in DataViewAction. public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList"; public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList"; public static final String SELECT_COLUMN_LIST = "selectColumnList"; //Tree Data Action public static final String TREE_DATA_ACTION = "/catissuecore/Data.do"; public static final String SPECIMEN = "Specimen"; public static final String SEGMENT = "Segment"; public static final String SAMPLE = "Sample"; public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID"; public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID"; public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID"; public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID"; public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID"; //Identifiers for various Form beans public static final int USER_FORM_ID = 1; public static final int PARTICIPANT_FORM_ID = 2; public static final int ACCESSION_FORM_ID = 3; public static final int REPORTEDPROBLEM_FORM_ID = 4; public static final int INSTITUTION_FORM_ID = 5; public static final int APPROVE_USER_FORM_ID = 6; public static final int ACTIVITY_STATUS_FORM_ID = 7; public static final int DEPARTMENT_FORM_ID = 8; public static final int COLLECTION_PROTOCOL_FORM_ID = 9; public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10; public static final int STORAGE_CONTAINER_FORM_ID = 11; public static final int STORAGE_TYPE_FORM_ID = 12; public static final int SITE_FORM_ID = 13; public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14; public static final int BIOHAZARD_FORM_ID = 15; public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16; public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17; public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18; public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19; public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20; public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21; public static final int NEW_SPECIMEN_FORM_ID = 22; public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23; public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24; public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25; public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26; public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27; public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28; public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29; public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30; public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31; public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32; public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33; public static final int CREATE_SPECIMEN_FORM_ID = 34; public static final int FORGOT_PASSWORD_FORM_ID = 35; public static final int SIGNUP_FORM_ID = 36; public static final int DISTRIBUTION_FORM_ID = 37; public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38; public static final int SHOPPING_CART_FORM_ID = 39; public static final int SIMPLE_QUERY_INTERFACE_ID = 40; //Misc public static final String SEPARATOR = " : "; //Status message key Constants public static final String STATUS_MESSAGE_KEY = "statusMessageKey"; //Identifiers for JDBC DAO. public static final int QUERY_RESULT_TREE_JDBC_DAO = 1; //Activity Status values public static final String ACTIVITY_STATUS_ACTIVE = "Active"; public static final String ACTIVITY_STATUS_APPROVE = "Approve"; public static final String ACTIVITY_STATUS_REJECT = "Reject"; public static final String ACTIVITY_STATUS_NEW = "New"; public static final String ACTIVITY_STATUS_PENDING = "Pending"; public static final String ACTIVITY_STATUS_CLOSED = "Closed"; public static final String ACTIVITY_STATUS_DISABLED = "Disabled"; //Approve User status values. public static final String APPROVE_USER_APPROVE_STATUS = "Approve"; public static final String APPROVE_USER_REJECT_STATUS = "Reject"; public static final String APPROVE_USER_PENDING_STATUS = "Pending"; //Approve User Constants public static final int ZERO = 0; public static final int START_PAGE = 1; public static final int NUMBER_RESULTS_PER_PAGE = 5; public static final String PAGE_NUMBER = "pageNum"; public static final String RESULTS_PER_PAGE = "numResultsPerPage"; public static final String TOTAL_RESULTS = "totalResults"; public static final String PREVIOUS_PAGE = "prevpage"; public static final String NEXT_PAGE = "nextPage"; public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList"; public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList"; public static final String USER_DETAILS = "details"; public static final String CURRENT_RECORD = "currentRecord"; public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core."; //Tree View Constants. public static final String ROOT = "Root"; public static final String CATISSUE_CORE = "caTISSUE Core"; public static final String TISSUE_SITE = "Tissue Site"; public static final int TISSUE_SITE_TREE_ID = 1; public static final int STORAGE_CONTAINER_TREE_ID = 2; public static final int QUERY_RESULTS_TREE_ID = 3; //Edit Object Constants. public static final String TABLE_ALIAS_NAME = "aliasName"; public static final String FIELD_TYPE_VARCHAR = "varchar"; public static final String FIELD_TYPE_DATE = "date"; //Query Interface Results View Constants public static final String PAGEOF = "pageOf"; public static final String QUERY = "query"; public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser"; public static final String PAGEOF_SIGNUP = "pageOfSignUp"; public static final String PAGEOF_USERADD = "pageOfUserAdd"; public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin"; //For Tree Applet public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults"; public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation"; public static final String PAGEOF_SPECIMEN = "pageOfSpecimen"; public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite"; //For Simple Query Interface and Edit. public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface"; public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject"; //Query results view temporary table name. public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS"; //Query results view temporary table columns. public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID"; public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID"; public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID"; public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE"; //Constants for default column names to be shown for query result. public static final String[] DEFAULT_SPREADSHEET_COLUMNS = { // QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID, // QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID, // QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE "IDENTIFIER","TYPE","ONE_DIMENSION_LABEL" }; //Query results edit constants - MakeEditableAction. public static final String EDITABLE = "editable"; //URL paths for Applet in TreeView.jsp public static final String QUERY_TREE_APPLET = "QueryTree.class"; public static final String APPLET_CODEBASE = "Applet"; public static final String TREE_APPLET_NAME = "treeApplet"; //Shopping Cart public static final String SHOPPING_CART = "shoppingCart"; public static final String SELECT_OPTION = "-- Select --"; // public static final String[] TISSUE_SITE_ARRAY = { // SELECT_OPTION,"Sex","male","female", // "Tissue","kidney","Left kidney","Right kidney" public static final String[] ATTRIBUTE_NAME_ARRAY = { SELECT_OPTION }; public static final String[] ATTRIBUTE_CONDITION_ARRAY = { "=","<",">" }; public static final String [] RECEIVEDMODEARRAY = { SELECT_OPTION, "by hand", "courier", "FedEX", "UPS" }; public static final String [] GENDER_ARRAY = { SELECT_OPTION, "Male", "Female" }; public static final String [] GENOTYPE_ARRAY = { SELECT_OPTION, "XX", "XY" }; public static final String [] RACEARRAY = { SELECT_OPTION, "Asian", "American" }; public static final String [] PROTOCOLARRAY = { SELECT_OPTION, "aaaa", "bbbb", "cccc" }; public static final String [] RECEIVEDBYARRAY = { SELECT_OPTION, "xxxx", "yyyy", "zzzz" }; public static final String [] COLLECTEDBYARRAY = { SELECT_OPTION, "xxxx", "yyyy", "zzzz" }; public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"}; public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"}; public static final String [] STATEARRAY = { SELECT_OPTION, "Alabama",//Alabama "Alaska",//Alaska "Arizona",//Arizona "Arkansas",//Arkansas "California",//California "Colorado",//Colorado "Connecticut",//Connecticut "Delaware",//Delaware "D.C.", "Florida",//Florida "Georgia",//Georgia "Hawaii",//Hawaii "Idaho",//Idaho "Illinois",//Illinois "Indiana",//Indiana "Iowa",//Iowa "Kansas",//Kansas "Kentucky",//Kentucky "Louisiana",//Louisiana "Maine",//Maine "Maryland",//Maryland "Massachusetts",//Massachusetts "Michigan",//Michigan "Minnesota",//Minnesota "Mississippi",//Mississippi "Missouri",//Missouri "Montana",//Montana "Nebraska",//Nebraska "Nevada",//Nevada "New Hampshire",//New Hampshire "New Jersey",//New Jersey "New Mexico",//New Mexico "New York",//New York "North Carolina",//North Carolina "North Dakota",//North Dakota "Ohio",//Ohio "Oklahoma",//Oklahoma "Oregon",//Oregon "Pennsylvania",//Pennsylvania "Rhode Island",//Rhode Island "South Carolina",//South Carolina "South Dakota",//South Dakota "Tennessee",//Tennessee "Texas",//Texas "Utah",//Utah "Vermont",//Vermont "Virginia",//Virginia "Washington",//Washington "West Virginia",//West Virginia "Wisconsin",//Wisconsin "Wyoming",//Wyoming "Other",//Other }; public static final String [] COUNTRYARRAY = { SELECT_OPTION, "United States", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon",//Cameroon "Cape Verde",//Cape Verde "Cayman Islands",//Cayman Islands "Central African Republic",//Central African Republic "Chad",//Chad "Chile",//Chile "China",//China "Christmas Island",//Christmas Island "Cocos Islands",//Cocos Islands "Colombia",//Colombia "Comoros",//Comoros "Congo",//Congo "Cook Islands",//Cook Islands "Costa Rica",//Costa Rica "Cote D ivoire",//Cote D ivoire "Croatia",//Croatia "Cyprus",//Cyprus "Czech Republic",//Czech Republic "Denmark",//Denmark "Djibouti",//Djibouti "Dominica",//Dominica "Dominican Republic",//Dominican Republic "East Timor",//East Timor "Ecuador",//Ecuador "Egypt",//Egypt "El Salvador",//El Salvador "Equatorial Guinea",//Equatorial Guinea "Eritrea",//Eritrea "Estonia",//Estonia "Ethiopia",//Ethiopia "Falkland Islands",//Falkland Islands "Faroe Islands",//Faroe Islands "Fiji",//Fiji "Finland",//Finland "France",//France "French Guiana",//French Guiana "French Polynesia",//French Polynesia "French S. Territories",//French S. Territories "Gabon",//Gabon "Gambia",//Gambia "Georgia",//Georgia "Germany",//Germany "Ghana",//Ghana "Gibraltar",//Gibraltar "Greece",//Greece "Greenland",//Greenland "Grenada",//Grenada "Guadeloupe",//Guadeloupe "Guam",//Guam "Guatemala",//Guatemala "Guinea",//Guinea "Guinea-Bissau",//Guinea-Bissau "Guyana",//Guyana "Haiti",//Haiti "Honduras",//Honduras "Hong Kong",//Hong Kong "Hungary",//Hungary "Iceland",//Iceland "India",//India "Indonesia",//Indonesia "Iran",//Iran "Iraq",//Iraq "Ireland",//Ireland "Israel",//Israel "Italy",//Italy "Jamaica",//Jamaica "Japan",//Japan "Jordan",//Jordan "Kazakhstan",//Kazakhstan "Kenya",//Kenya "Kiribati",//Kiribati "Korea",//Korea "Kuwait",//Kuwait "Kyrgyzstan",//Kyrgyzstan "Laos",//Laos "Latvia",//Latvia "Lebanon",//Lebanon "Lesotho",//Lesotho "Liberia",//Liberia "Liechtenstein",//Liechtenstein "Lithuania",//Lithuania "Luxembourg",//Luxembourg "Macau",//Macau "Macedonia",//Macedonia "Madagascar",//Madagascar "Malawi",//Malawi "Malaysia",//Malaysia "Maldives",//Maldives "Mali",//Mali "Malta",//Malta "Marshall Islands",//Marshall Islands "Martinique",//Martinique "Mauritania",//Mauritania "Mauritius",//Mauritius "Mayotte",//Mayotte "Mexico",//Mexico "Micronesia",//Micronesia "Moldova",//Moldova "Monaco",//Monaco "Mongolia",//Mongolia "Montserrat",//Montserrat "Morocco",//Morocco "Mozambique",//Mozambique "Myanmar",//Myanmar "Namibia",//Namibia "Nauru",//Nauru "Nepal",//Nepal "Netherlands",//Netherlands "Netherlands Antilles",//Netherlands Antilles "New Caledonia",//New Caledonia "New Zealand",//New Zealand "Nicaragua",//Nicaragua "Niger",//Niger "Nigeria",//Nigeria "Niue",//Niue "Norfolk Island",//Norfolk Island "Norway",//Norway "Oman",//Oman "Pakistan",//Pakistan "Palau",//Palau "Panama",//Panama "Papua New Guinea",//Papua New Guinea "Paraguay",//Paraguay "Peru",//Peru "Philippines",//Philippines "Pitcairn",//Pitcairn "Poland",//Poland "Portugal",//Portugal "Puerto Rico",//Puerto Rico "Qatar",//Qatar "Reunion",//Reunion "Romania",//Romania "Russian Federation",//Russian Federation "Rwanda",//Rwanda "Saint Helena",//Saint Helena "Saint Kitts and Nevis",//Saint Kitts and Nevis "Saint Lucia",//Saint Lucia "Saint Pierre",//Saint Pierre "Saint Vincent",//Saint Vincent "Samoa",//Samoa "San Marino",//San Marino "Sao Tome and Principe",//Sao Tome and Principe "Saudi Arabia",//Saudi Arabia "Senegal",//Senegal "Seychelles",//Seychelles "Sierra Leone",//Sierra Leone "Singapore",//Singapore "Slovakia",//Slovakia "Slovenia",//Slovenia "Solomon Islands",//Solomon Islands "Somalia",//Somalia "South Africa",//South Africa "Spain",//Spain "Sri Lanka",//Sri Lanka "Sudan",//Sudan "Suriname",//Suriname "Swaziland",//Swaziland "Sweden",//Sweden "Switzerland",//Switzerland "Syrian Arab Republic",//Syrian Arab Republic "Taiwan",//Taiwan "Tajikistan",//Tajikistan "Tanzania",//Tanzania "Thailand",//Thailand "Togo",//Togo "Tokelau",//Tokelau "Tonga",//Tonga "Trinidad and Tobago",//Trinidad and Tobago "Tunisia",//Tunisia "Turkey",//Turkey "Turkmenistan",//Turkmenistan "Turks and Caicos Islands",//Turks and Caicos Islands "Tuvalu",//Tuvalu "Uganda",//Uganda "Ukraine",//Ukraine "United Arab Emirates",//United Arab Emirates "United Kingdom",//United Kingdom "Uruguay",//Uruguay "Uzbekistan",//Uzbekistan "Vanuatu",//Vanuatu "Vatican City State",//Vatican City State "Venezuela",//Venezuela "Vietnam",//Vietnam "Virgin Islands",//Virgin Islands "Wallis And Futuna Islands",//Wallis And Futuna Islands "Western Sahara",//Western Sahara "Yemen",//Yemen "Yugoslavia",//Yugoslavia "Zaire",//Zaire "Zambia",//Zambia "Zimbabwe",//Zimbabwe }; // Constants required in CollectionProtocol.jsp Page public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do"; public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do"; public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do"; // Constants required in DistributionProtocol.jsp Page public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do"; public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do"; public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do"; public static final String [] ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Disabled", "Closed" }; public static final String [] APPROVE_USER_STATUS_VALUES = { SELECT_OPTION, APPROVE_USER_APPROVE_STATUS, APPROVE_USER_REJECT_STATUS, APPROVE_USER_PENDING_STATUS, }; public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Closed", "Pending" }; public static final String [] SPECIMEN_TYPE_VALUES = { SELECT_OPTION, "Tissue", "Fluid", "Cell", "Molecular" }; public static final String [] SITE_TYPE_ARRAY = { SELECT_OPTION, "Collection", "Laboratory", "Repository", "Hospital" }; public static final String [] HOURARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public static final String [] MINUTESARRAY = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public static final String [] METHODARRAY = { SELECT_OPTION, "LN2", "Dry Ice", "Iso pentane" }; public static final String [] EMBEDDINGMEDIUMARRAY = { SELECT_OPTION, "Plastic", "Glass", }; public static final String [] ITEMARRAY = { SELECT_OPTION, "Item1", "Item2", }; public static final String UNIT_GM = "gm"; public static final String UNIT_ML = "ml"; public static final String UNIT_CC = "cell count"; public static final String UNIT_MG = "mg"; public static final String [] PROCEDUREARRAY = { SELECT_OPTION, "Procedure 1", "Procedure 2", "Procedure 3" }; public static final String [] CONTAINERARRAY = { SELECT_OPTION, "Container 1", "Container 2", "Container 3" }; public static final String [] FIXATIONARRAY = { SELECT_OPTION, "FIXATION 1", "FIXATION 2", "FIXATION 3" }; public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap(); public static final String CDE_CONF_FILE = "CDEConfig.xml"; public static final String CDE_NAME_TISSUE_SITE = "Tissue Site"; public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status"; public static final String CDE_NAME_GENDER = "Gender"; public static final String CDE_NAME_GENOTYPE = "Genotype"; public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen"; public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type"; public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side"; public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status"; public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality"; public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type"; public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure"; public static final String CDE_NAME_CONTAINER = "Container"; public static final String CDE_NAME_METHOD = "Method"; public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium"; public static final String CDE_NAME_BIOHAZARD = "Biohazard"; public static final String CDE_NAME_ETHNICITY = "Ethnicity"; public static final String CDE_NAME_RACE = "Race"; public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis"; public static final String [] STORAGESTATUSARRAY = { SELECT_OPTION, "CHECK IN", "CHECK OUT" }; public static final String [] CLINICALDIAGNOSISARRAY = { SELECT_OPTION, "CLINICALDIAGNOSIS 1", "CLINICALDIAGNOSIS 2", "CLINICALDIAGNOSIS 3" }; public static final String [] HISTOLOGICALQUALITYARRAY = { SELECT_OPTION, "GOOD", "OK", "DAMAGED" }; // constants for Data required in query public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames"; public static final String SYSTEM_IDENTIFIER = "systemIdentifier"; public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION, "Cell Specimen Review", "Check In Check Out", "Collection", "Disposal", "Embedded", "Fixed", "Fluid Specimen Review", "Frozen", "Molecular Specimen Review", "Procedure", "Received", "Spun", "Thaw", "Tissue Specimen Review", "Transfer" }; public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier", "Event Parameter", "User", "Time", "PageOf"}; public static final String getCollectionProtocolPGName(Long identifier) { return "COLLECTION_PROTOCOL_"+identifier; } public static final String getCollectionProtocolPIGroupName(Long identifier) { return "COLLECTION_PROTOCOL_"+identifier; } public static final String getCollectionProtocolCoordinatorGroupName(Long identifier) { return "COLLECTION_PROTOCOL_"+identifier; } public static final String ACCESS_DENIED_ADMIN = "access_denied_admin"; public static final String ACCESS_DENIED_BIOSPECIMEN = "access_denied_biospecimen"; }
package edu.wustl.catissuecore.util.global; /** * This class stores the constants used in the operations in the application. * @author gautam_shetty */ public class Constants extends edu.wustl.common.util.global.Constants { public static final String MAX_IDENTIFIER = "maxIdentifier"; public static final String AND_JOIN_CONDITION = "AND"; public static final String OR_JOIN_CONDITION = "OR"; //Sri: Changed the format for displaying in Specimen Event list (#463) public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm"; public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd"; // Mandar: Used for Date Validations in Validator Class public static final String DATE_SEPARATOR = "-"; public static final String DATE_SEPARATOR_DOT = "."; public static final String MIN_YEAR = "1900"; public static final String MAX_YEAR = "9999"; public static final String VIEW = "view"; public static final String DELETE = "delete"; public static final String EXPORT = "export"; public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; public static final String SHOPPING_CART_EXPORT = "shoppingCartExport"; public static final String NEWUSERFORM = "newUserForm"; public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect"; public static final String CALLED_FROM = "calledFrom"; //Constants required for Forgot Password public static final String FORGOT_PASSWORD = "forgotpassword"; public static final String LOGINNAME = "loginName"; public static final String LASTNAME = "lastName"; public static final String FIRSTNAME = "firstName"; public static final String INSTITUTION = "institution"; public static final String EMAIL = "email"; public static final String DEPARTMENT = "department"; public static final String ADDRESS = "address"; public static final String CITY = "city"; public static final String STATE = "state"; public static final String COUNTRY = "country"; public static final String NEXT_CONTAINER_NO = "startNumber"; public static final String CSM_USER_ID = "csmUserId"; public static final String INSTITUTIONLIST = "institutionList"; public static final String DEPARTMENTLIST = "departmentList"; public static final String STATELIST = "stateList"; public static final String COUNTRYLIST = "countryList"; public static final String ROLELIST = "roleList"; public static final String ROLEIDLIST = "roleIdList"; public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList"; public static final String GENDER_LIST = "genderList"; public static final String GENOTYPE_LIST = "genotypeList"; public static final String ETHNICITY_LIST = "ethnicityList"; public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList"; public static final String RACELIST = "raceList"; public static final String VITAL_STATUS_LIST = "vitalStatusList"; public static final String PARTICIPANT_LIST = "participantList"; public static final String PARTICIPANT_ID_LIST = "participantIdList"; public static final String PROTOCOL_LIST = "protocolList"; public static final String TIMEHOURLIST = "timeHourList"; public static final String TIMEMINUTESLIST = "timeMinutesList"; public static final String TIMEAMPMLIST = "timeAMPMList"; public static final String RECEIVEDBYLIST = "receivedByList"; public static final String COLLECTEDBYLIST = "collectedByList"; public static final String COLLECTIONSITELIST = "collectionSiteList"; public static final String RECEIVEDSITELIST = "receivedSiteList"; public static final String RECEIVEDMODELIST = "receivedModeList"; public static final String ACTIVITYSTATUSLIST = "activityStatusList"; public static final String USERLIST = "userList"; public static final String SITETYPELIST = "siteTypeList"; public static final String STORAGETYPELIST="storageTypeList"; public static final String STORAGECONTAINERLIST="storageContainerList"; public static final String SITELIST="siteList"; // public static final String SITEIDLIST="siteIdList"; public static final String USERIDLIST = "userIdList"; public static final String STORAGETYPEIDLIST="storageTypeIdList"; public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList"; public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant"; public static final String APPROVE_USER_STATUS_LIST = "statusList"; public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; //New Specimen lists. public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList"; public static final String SPECIMEN_TYPE_LIST = "specimenTypeList"; public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList"; public static final String TISSUE_SITE_LIST = "tissueSiteList"; public static final String TISSUE_SIDE_LIST = "tissueSideList"; public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList"; public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList"; public static final String BIOHAZARD_NAME_LIST = "biohazardNameList"; public static final String BIOHAZARD_ID_LIST = "biohazardIdList"; public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList"; public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList"; public static final String RECEIVED_QUALITY_LIST = "receivedQualityList"; //SpecimenCollecionGroup lists. public static final String PROTOCOL_TITLE_LIST = "protocolTitleList"; public static final String PARTICIPANT_NAME_LIST = "participantNameList"; public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList"; //public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList"; public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList"; //public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList"; public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray"; //public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray"; public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId"; public static final String REQ_PATH = "redirectTo"; public static final String CLINICAL_STATUS_LIST = "cinicalStatusList"; public static final String SPECIMEN_CLASS_LIST = "specimenClassList"; public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList"; public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap"; //Simple Query Interface Lists public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList"; public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle"; public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject"; public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus"; public static final String START_NUMBER = "startNumber"; public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerIds"; public static final int STORAGE_CONTAINER_FIRST_ROW = 1; public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1; //event parameters lists public static final String METHOD_LIST = "methodList"; public static final String HOUR_LIST = "hourList"; public static final String MINUTES_LIST = "minutesList"; public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList"; public static final String PROCEDURE_LIST = "procedureList"; public static final String PROCEDUREIDLIST = "procedureIdList"; public static final String CONTAINER_LIST = "containerList"; public static final String CONTAINERIDLIST = "containerIdList"; public static final String FROMCONTAINERLIST="fromContainerList"; public static final String TOCONTAINERLIST="toContainerList"; public static final String FIXATION_LIST = "fixationList"; public static final String FROM_SITE_LIST="fromsiteList"; public static final String TO_SITE_LIST="tositeList"; public static final String ITEMLIST="itemList"; public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList"; public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList"; public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList"; public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList"; public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList"; public static final String STORAGE_STATUS_LIST="storageStatusList"; public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList"; public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList"; //For Specimen Event Parameters. public static final String SPECIMEN_ID = "specimenId"; public static final String FROM_POSITION_DATA = "fromPositionData"; public static final String POS_ONE ="posOne"; public static final String POS_TWO ="posTwo"; public static final String STORAGE_CONTAINER_ID ="storContId"; public static final String IS_RNA = "isRNA"; public static final String RNA = "RNA"; // New Participant Event Parameters public static final String PARTICIPANT_ID="participantId"; //Constants required in User.jsp Page public static final String USER_SEARCH_ACTION = "UserSearch.do"; public static final String USER_ADD_ACTION = "UserAdd.do"; public static final String USER_EDIT_ACTION = "UserEdit.do"; public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do"; public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do"; public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do"; public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do"; public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do"; //Constants required in Accession.jsp Page public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do"; public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do"; public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do"; //Constants required in StorageType.jsp Page public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do"; public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do"; public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do"; //Constants required in StorageContainer.jsp Page public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do"; public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do"; public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do"; public static final String HOLDS_LIST1 = "HoldsList1"; public static final String HOLDS_LIST2 = "HoldsList2"; //Constants required in Site.jsp Page public static final String SITE_SEARCH_ACTION = "SiteSearch.do"; public static final String SITE_ADD_ACTION = "SiteAdd.do"; public static final String SITE_EDIT_ACTION = "SiteEdit.do"; //Constants required in Site.jsp Page public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do"; public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do"; public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do"; //Constants required in Partcipant.jsp Page public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do"; public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do"; public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do"; public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do"; //Constants required in Institution.jsp Page public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do"; public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do"; public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do"; //Constants required in Department.jsp Page public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do"; public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do"; public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do"; //Constants required in CollectionProtocolRegistration.jsp Page public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do"; public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do"; public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do"; //Constants required in CancerResearchGroup.jsp Page public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do"; public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do"; public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do"; //Constants required for Approve user public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do"; public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do"; //Reported Problem Constants public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do"; public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do"; public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do"; public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do"; //Query Results view Actions public static final String TREE_VIEW_ACTION = "TreeView.do"; public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do"; public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17"; //New Specimen Data Actions. public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do"; public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do"; public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do"; public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //Create Specimen Data Actions. public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do"; public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do"; public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do"; //ShoppingCart Actions. public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do"; public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do"; public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do"; public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do"; //Constants required in FrozenEventParameters.jsp Page public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do"; public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do"; public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do"; //Constants required in CheckInCheckOutEventParameters.jsp Page public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do"; //Constants required in ReceivedEventParameters.jsp Page public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do"; public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do"; public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do"; //Constants required in FluidSpecimenReviewEventParameters.jsp Page public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do"; //Constants required in CELLSPECIMENREVIEWParameters.jsp Page public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do"; //Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do"; // Constants required in DisposalEventParameters.jsp Page public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do"; public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do"; public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do"; // Constants required in ThawEventParameters.jsp Page public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do"; public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do"; public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do"; // Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do"; // Constants required in CollectionEventParameters.jsp Page public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do"; public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do"; public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do"; // Constants required in SpunEventParameters.jsp Page public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do"; public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do"; public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do"; // Constants required in EmbeddedEventParameters.jsp Page public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do"; public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do"; public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do"; // Constants required in TransferEventParameters.jsp Page public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do"; public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do"; public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do"; // Constants required in FixedEventParameters.jsp Page public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do"; public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do"; public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do"; // Constants required in ProcedureEventParameters.jsp Page public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do"; public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do"; public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do"; // Constants required in Distribution.jsp Page public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do"; public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do"; public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do"; public static final String ARRAY_DISTRIBUTION_ADD_ACTION = "ArrayDistributionAdd.do"; //Spreadsheet Export Action public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do"; //Aliquots Action public static final String ALIQUOT_ACTION = "Aliquots.do"; public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do"; //Constants related to Aliquots functionality public static final String PAGEOF_ALIQUOT = "pageOfAliquot"; public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot"; public static final String PAGEOF_ALIQUOT_SUMMARY = "pageOfAliquotSummary"; public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap"; //Constants related to QuickEvents functionality public static final String QUICKEVENTS_ACTION = "QuickEventsSearch.do"; public static final String QUICKEVENTSPARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //SimilarContainers Action public static final String SIMILAR_CONTAINERS_ACTION = "SimilarContainers.do"; public static final String CREATE_SIMILAR_CONTAINERS_ACTION = "CreateSimilarContainers.do"; public static final String SIMILAR_CONTAINERS_ADD_ACTION = "SimilarContainersAdd.do"; //Constants related to Similar Containsers public static final String PAGEOF_SIMILAR_CONTAINERS = "pageOfSimilarContainers"; public static final String PAGEOF_CREATE_SIMILAR_CONTAINERS = "pageOfCreateSimilarContainers"; public static final String PAGEOF_STORAGE_CONTAINER = "pageOfStorageContainer"; //Levels of nodes in query results tree. public static final int MAX_LEVEL = 5; public static final int MIN_LEVEL = 1; public static final String TABLE_NAME_COLUMN = "TABLE_NAME"; //Spreadsheet view Constants in DataViewAction. public static final String PARTICIPANT = "Participant"; public static final String ACCESSION = "Accession"; public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?id="; public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do"; public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?id="; public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do"; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?id="; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do"; public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?id="; public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do"; //public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?id="; public static final String SPECIMEN = "Specimen"; public static final String SEGMENT = "Segment"; public static final String SAMPLE = "Sample"; public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration"; public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID"; public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID"; public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID"; public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID"; public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID"; //For getting the tables for Simple Query and Fcon Query. public static final int ADVANCE_QUERY_TABLES = 2; //Identifiers for various Form beans public static final int DEFAULT_BIZ_LOGIC = 0; public static final int USER_FORM_ID = 1; public static final int ACCESSION_FORM_ID = 3; public static final int REPORTED_PROBLEM_FORM_ID = 4; public static final int INSTITUTION_FORM_ID = 5; public static final int APPROVE_USER_FORM_ID = 6; public static final int ACTIVITY_STATUS_FORM_ID = 7; public static final int DEPARTMENT_FORM_ID = 8; public static final int COLLECTION_PROTOCOL_FORM_ID = 9; public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10; public static final int STORAGE_CONTAINER_FORM_ID = 11; public static final int STORAGE_TYPE_FORM_ID = 12; public static final int SITE_FORM_ID = 13; public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14; public static final int BIOHAZARD_FORM_ID = 15; public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16; public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17; public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18; public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21; public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23; public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24; public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25; public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26; public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27; public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28; public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29; public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30; public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31; public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32; public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33; public static final int CREATE_SPECIMEN_FORM_ID = 34; public static final int FORGOT_PASSWORD_FORM_ID = 35; public static final int SIGNUP_FORM_ID = 36; public static final int DISTRIBUTION_FORM_ID = 37; public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38; public static final int SHOPPING_CART_FORM_ID = 39; public static final int CONFIGURE_RESULT_VIEW_ID = 41; public static final int ADVANCE_QUERY_INTERFACE_ID = 42; public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19; public static final int PARTICIPANT_FORM_ID = 2; public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20; public static final int NEW_SPECIMEN_FORM_ID = 22; public static final int ALIQUOT_FORM_ID = 44; public static final int QUICKEVENTS_FORM_ID = 45; public static final int LIST_SPECIMEN_EVENT_PARAMETERS_FORM_ID = 46; public static final int SIMILAR_CONTAINERS_FORM_ID = 47; // chetan (13-07-2006) public static final int SPECIMEN_ARRAY_TYPE_FORM_ID = 48; // chetan (13-07-2006) public static final int ARRAY_DISTRIBUTION_FORM_ID = 49; //Misc public static final String SEPARATOR = " : "; //Identifiers for JDBC DAO. public static final int QUERY_RESULT_TREE_JDBC_DAO = 1; //Activity Status values public static final String ACTIVITY_STATUS_APPROVE = "Approve"; public static final String ACTIVITY_STATUS_REJECT = "Reject"; public static final String ACTIVITY_STATUS_NEW = "New"; public static final String ACTIVITY_STATUS_PENDING = "Pending"; //Approve User status values. public static final String APPROVE_USER_APPROVE_STATUS = "Approve"; public static final String APPROVE_USER_REJECT_STATUS = "Reject"; public static final String APPROVE_USER_PENDING_STATUS = "Pending"; //Approve User Constants public static final int ZERO = 0; public static final int START_PAGE = 1; public static final int NUMBER_RESULTS_PER_PAGE = 5; public static final String PAGE_NUMBER = "pageNum"; public static final String RESULTS_PER_PAGE = "numResultsPerPage"; public static final String TOTAL_RESULTS = "totalResults"; public static final String PREVIOUS_PAGE = "prevpage"; public static final String NEXT_PAGE = "nextPage"; public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList"; public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList"; public static final String USER_DETAILS = "details"; public static final String CURRENT_RECORD = "currentRecord"; public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core."; //Query Interface Results View Constants public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser"; public static final String PAGEOF_SIGNUP = "pageOfSignUp"; public static final String PAGEOF_USERADD = "pageOfUserAdd"; public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin"; public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile"; public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword"; //For Simple Query Interface and Edit. public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject"; //Query results view temporary table columns. public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID"; public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID"; public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID"; public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE"; // Assign Privilege Constants. public static final boolean PRIVILEGE_DEASSIGN = false; public static final String OPERATION_DISALLOW = "Disallow"; //Constants for default column names to be shown for query result. public static final String[] DEFAULT_SPREADSHEET_COLUMNS = { // QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID, // QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID, // QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE "IDENTIFIER","TYPE","ONE_DIMENSION_LABEL" }; //Query results edit constants - MakeEditableAction. public static final String EDITABLE = "editable"; //URL paths for Applet in TreeView.jsp public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class"; public static final String APPLET_CODEBASE = "Applet"; //Shopping Cart public static final String SHOPPING_CART = "shoppingCart"; public static final int SELECT_OPTION_VALUE = -1; public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"}; // Constants required in CollectionProtocol.jsp Page public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do"; public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do"; public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do"; // Constants required in DistributionProtocol.jsp Page public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do"; public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do"; public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do"; public static final String [] ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed", "Disabled" }; public static final String [] SITE_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] USER_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] APPROVE_USER_STATUS_VALUES = { SELECT_OPTION, APPROVE_USER_APPROVE_STATUS, APPROVE_USER_REJECT_STATUS, APPROVE_USER_PENDING_STATUS, }; public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Closed", "Pending" }; public static final String TISSUE = "Tissue"; public static final String FLUID = "Fluid"; public static final String CELL = "Cell"; public static final String MOLECULAR = "Molecular"; public static final String [] SPECIMEN_TYPE_VALUES = { SELECT_OPTION, TISSUE, FLUID, CELL, MOLECULAR }; public static final String [] HOUR_ARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public static final String [] MINUTES_ARRAY = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public static final String UNIT_GM = "gm"; public static final String UNIT_ML = "ml"; public static final String UNIT_CC = "cell count"; public static final String UNIT_MG = "g"; public static final String UNIT_CN = "count"; public static final String UNIT_CL = "cells"; public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status"; public static final String CDE_NAME_GENDER = "Gender"; public static final String CDE_NAME_GENOTYPE = "Genotype"; public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen"; public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type"; public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side"; public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status"; public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality"; public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type"; public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure"; public static final String CDE_NAME_CONTAINER = "Container"; public static final String CDE_NAME_METHOD = "Method"; public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium"; public static final String CDE_NAME_BIOHAZARD = "Biohazard"; public static final String CDE_NAME_ETHNICITY = "Ethnicity"; public static final String CDE_NAME_RACE = "Race"; public static final String CDE_VITAL_STATUS = "Vital Status"; public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis"; public static final String CDE_NAME_SITE_TYPE = "Site Type"; public static final String CDE_NAME_COUNTRY_LIST = "Countries"; public static final String CDE_NAME_STATE_LIST = "States"; public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality"; //Constants for Advanced Search public static final String STRING_OPERATORS = "StringOperators"; public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators"; public static final String ENUMERATED_OPERATORS = "EnumeratedOperators"; public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators"; public static final String [] STORAGE_STATUS_ARRAY = { SELECT_OPTION, "CHECK IN", "CHECK OUT" }; // constants for Data required in query public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames"; public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER"; public static final String NAME = "name"; public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION, "Cell Specimen Review", "Check In Check Out", "Collection", "Disposal", "Embedded", "Fixed", "Fluid Specimen Review", "Frozen", "Molecular Specimen Review", "Procedure", "Received", "Spun", "Thaw", "Tissue Specimen Review", "Transfer" }; public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier", "Event Parameter", "User", "Date / Time", "PageOf"}; public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier", "Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"}; //Constants required in AssignPrivileges.jsp public static final String ASSIGN = "assignOperation"; public static final String PRIVILEGES = "privileges"; public static final String OBJECT_TYPES = "objectTypes"; public static final String OBJECT_TYPE_VALUES = "objectTypeValues"; public static final String RECORD_IDS = "recordIds"; public static final String ATTRIBUTES = "attributes"; public static final String GROUPS = "groups"; public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege"; public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege"; public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do"; public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2; /** * @param id * @return */ public static String getUserPGName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } /** * @param id * @return */ public static String getUserGroupName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } //Mandar 25-Apr-06 : bug 1414 : Tissue units as per type // tissue types with unit= count public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK public static final String NOT_SPECIFIED = "Not Specified"; // tissue types with unit= g public static final String FRESH_TISSUE = "Fresh Tissue"; public static final String FROZEN_TISSUE = "Frozen Tissue"; public static final String FIXED_TISSUE = "Fixed Tissue"; public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide"; //tissue types with unit= cc public static final String MICRODISSECTED = "Microdissected"; // constants required for Distribution Report public static final String CONFIGURATION_TABLES = "configurationTables"; public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen", "SpecimenCollectionGroup","DistributedItem"}; public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap"; public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do"; public static final String TABLE_NAMES_LIST = "tableNamesList"; public static final String COLUMN_NAMES_LIST = "columnNamesList"; public static final String DISTRIBUTION_ID = "distributionId"; public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do"; public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do"; public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do"; public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Identifier : Specimen", "Specimen.TYPE.Type : Specimen", "SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen", "SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen", "SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen", "DistributedItem.QUANTITY.Quantity : Distribution"}; public static final String SPECIMEN_ID_LIST = "specimenIdList"; public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution"; public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv"; public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm"; public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData"; public static final String DISTRIBUTED_ITEM = "DistributedItem"; //constants for Simple Query Interface Configuration public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do"; public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do"; public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do"; public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do"; public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do"; public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution"; public static final String RESULT_VIEW_VECTOR = "resultViewVector"; //public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount"; public static final String UNDEFINED = "Undefined"; public static final String UNKNOWN = "Unknown"; public static final String SEARCH_RESULT = "SearchResult.csv"; // Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587 // public static final String ODD_COLOR = "#FEFB85"; // public static final String EVEN_COLOR = "#A7FEAB"; // Light and dark shades of GREY. public static final String ODD_COLOR = "#E5E5E5"; public static final String EVEN_COLOR = "#F7F7F7"; // TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do"; public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do"; public static final String PARENT_SPECIMEN_ID = "parentSpecimenId"; public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId"; public static final String FORWARDLIST = "forwardToList"; public static final String [][] SPECIMEN_FORWARD_TO_LIST = { {"Submit", "success"}, {"Derive", "createNew"}, {"Add Events", "eventParameters"}, {"More", "sameCollectionGroup"}, {"Submit and Distribute", "distribution" } }; public static final String [] SPECIMEN_BUTTON_TIPS = { "Submit only", "Submit and derive", "Submit and add events", "Submit and add more to same group", "Submit and distribute" }; public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = { {"Submit", "success"}, {"Add Specimen", "createNewSpecimen"} }; public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = { {"Submit", "success"}, {"Specimen Collection Group", "createSpecimenCollectionGroup"} }; public static final String [][] PARTICIPANT_FORWARD_TO_LIST = { {"Submit Only", "success"}, {"Submit and Register to Protocol", "createParticipantRegistration"} }; //Constants Required for Advance Search //Tree related //public static final String PARTICIPANT ='Participant'; public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol"; public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group"; public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol"; public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup"; public static final String DISTRIBUTION = "Distribution"; public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String CP = "CP"; public static final String SCG = "SCG"; public static final String D = "D"; public static final String DP = "DP"; public static final String C = "C"; public static final String S = "S"; public static final String P = "P"; public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView"; public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do"; public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do"; public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do"; public static final String ADVANCED_QUERY_ADD = "Add"; public static final String ADVANCED_QUERY_EDIT = "Edit"; public static final String ADVANCED_QUERY_DELETE = "Delete"; public static final String ADVANCED_QUERY_OPERATOR = "Operator"; public static final String ADVANCED_QUERY_OR = "OR"; public static final String ADVANCED_QUERY_AND = "pAND"; public static final String EVENT_CONDITIONS = "eventConditions"; public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap"; public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit"; public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit"; public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit"; public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit"; public static final String PARTICIPANT_COLUMNS = "particpantColumns"; public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns"; public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns"; public static final String SPECIMEN_COLUMNS = "SpecimenColumns"; public static final String USER_ID_COLUMN = "USER_ID"; public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain"; //Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic public static final boolean IS_AUDITABLE_TRUE = true; public static final boolean IS_SECURE_UPDATE_TRUE = true; public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false; //Constants for HTTP-API public static final String CONTENT_TYPE = "CONTENT-TYPE"; // For StorageContainer isFull status public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList"; public static final String [] IS_CONTAINER_FULL_VALUES = { SELECT_OPTION, "True", "False" }; public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel"; public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel"; // public static final String SPECIMEN_TYPE_TISSUE = "Tissue"; // public static final String SPECIMEN_TYPE_FLUID = "Fluid"; // public static final String SPECIMEN_TYPE_CELL = "Cell"; // public static final String SPECIMEN_TYPE_MOL = "Molecular"; public static final String SPECIMEN_TYPE_COUNT = "Count"; public static final String SPECIMEN_TYPE_QUANTITY = "Quantity"; public static final String SPECIMEN_TYPE_DETAILS = "Details"; public static final String SPECIMEN_COUNT = "totalSpecimenCount"; public static final String TOTAL = "Total"; public static final String SPECIMENS = "Specimens"; //User Roles public static final String TECHNICIAN = "Technician"; public static final String SUPERVISOR = "Supervisor"; public static final String SCIENTIST = "Scientist"; public static final String CHILD_CONTAINER_TYPE = "childContainerType"; public static final String UNUSED = "Unused"; public static final String TYPE = "Type"; //Mandar: 28-Apr-06 Bug 1129 public static final String DUPLICATE_SPECIMEN="duplicateSpecimen"; //Constants required in ParticipantLookupAction public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter"; public static final String PARTICIPANT_LOOKUP_CUTOFF="lookup.cutoff"; public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo"; public static final String PARTICIPANT_LOOKUP_SUCCESS="success"; public static final String PARTICIPANT_ADD_FORWARD="participantAdd"; public static final String PARTICIPANT_SYSTEM_IDENTIFIER="IDENTIFIER"; public static final String PARTICIPANT_LAST_NAME="LAST_NAME"; public static final String PARTICIPANT_FIRST_NAME="FIRST_NAME"; public static final String PARTICIPANT_MIDDLE_NAME="MIDDLE_NAME"; public static final String PARTICIPANT_BIRTH_DATE="BIRTH_DATE"; public static final String PARTICIPANT_DEATH_DATE="DEATH_DATE"; public static final String PARTICIPANT_VITAL_STATUS="VITAL_STATUS"; public static final String PARTICIPANT_GENDER="GENDER"; public static final String PARTICIPANT_SEX_GENOTYPE="SEX_GENOTYPE"; public static final String PARTICIPANT_RACE="RACE"; public static final String PARTICIPANT_ETHINICITY="ETHINICITY"; public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SOCIAL_SECURITY_NUMBER"; public static final String PARTICIPANT_PROBABLITY_MATCH="Probability"; //Constants for integration of caTies and CAE with caTissue Core public static final String LINKED_DATA = "linkedData"; public static final String APPLICATION_ID = "applicationId"; public static final String CATIES = "caTies"; public static final String CAE = "cae"; public static final String EDIT_TAB_LINK = "editTabLink"; public static final String CATIES_PUBLIC_SERVER_NAME = "CaTiesPublicServerName"; public static final String CATIES_PRIVATE_SERVER_NAME = "CaTiesPrivateServerName"; //Constants for StorageContainerMap Applet public static final String CONTAINER_STYLEID = "containerStyleId"; public static final String XDIM_STYLEID = "xDimStyleId"; public static final String YDIM_STYLEID = "yDimStyleId"; //Constants for QuickEvents public static final String EVENT_SELECTED = "eventSelected"; //Constant for SpecimenEvents page. public static final String EVENTS_TITLE_MESSAGE = "Existing events for this specimen"; public static final String SURGICAL_PATHOLOGY_REPORT = "Surgical Pathology Report"; public static final String CLINICAL_ANNOTATIONS = "Clinical Annotations"; //Constants for Specimen Collection Group name- new field public static final String RESET_NAME ="resetName"; // Labels for Storage Containers public static final String[] STORAGE_CONTAINER_LABEL = {" Name"," Pos1"," Pos2"}; //Constans for Any field public static final String HOLDS_ANY = "--All //Constants : Specimen -> lineage public static final String NEW_SPECIMEN = "New"; public static final String DERIVED_SPECIMEN = "Derived"; public static final String ALIQUOT = "Aliquot"; //Constant for length of messageBody in Reported problem page public static final int messageLength= 500; // public static final String getCollectionProtocolPIGroupName(Long identifier) // if(identifier == null) // return "PI_COLLECTION_PROTOCOL_"; // return "PI_COLLECTION_PROTOCOL_"+identifier; // public static final String getCollectionProtocolCoordinatorGroupName(Long identifier) // if(identifier == null) // return "COORDINATORS_COLLECTION_PROTOCOL_"; // return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier; // public static final String getDistributionProtocolPIGroupName(Long identifier) // if(identifier == null) // return "PI_DISTRIBUTION_PROTOCOL_"; // return "PI_DISTRIBUTION_PROTOCOL_"+identifier; // public static final String getCollectionProtocolPGName(Long identifier) // if(identifier == null) // return "COLLECTION_PROTOCOL_"; // return "COLLECTION_PROTOCOL_"+identifier; // public static final String getDistributionProtocolPGName(Long identifier) // if(identifier == null) // return "DISTRIBUTION_PROTOCOL_"; // return "DISTRIBUTION_PROTOCOL_"+identifier; }
package stray; import java.io.File; import java.util.Iterator; import java.util.Map.Entry; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import stray.blocks.Block; import stray.blocks.Blocks; import stray.entity.Entity; import stray.world.World; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Array; public class LevelEditor extends Updateable { public LevelEditor(Main m) { super(m); Iterator it = Blocks.instance().getAllBlocks(); while (it.hasNext()) { String b = ((Entry<String, Block>) it.next()).getKey(); if (Blocks.instance().getBlock(b).levelEditorGroup == EditorGroup.NOTPLACEABLE) { continue; } blocks.add(b); } // blocks.sort(); iothread = new Thread() { public void run() { while (true) { try { this.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (iothreadtodo != 0) { if (iothreadtodo == 1) { JFileChooser fileChooser = new JFileChooser(); if (lastFile != null) { fileChooser.setCurrentDirectory(lastFile); } else { fileChooser.setCurrentDirectory(new File(System .getProperty("user.home"), "Desktop")); } fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setSelectedFile(new File("a-custom-level.xml")); fileChooser.setDialogTitle("Select a directory to save in..."); int result = fileChooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); lastFile = selectedFile; world.save(new FileHandle(selectedFile)); } } else if (iothreadtodo == 2) { JFileChooser fileChooser = new JFileChooser(); if (lastFile != null) { fileChooser.setCurrentDirectory(lastFile); } else { fileChooser.setCurrentDirectory(new File(System .getProperty("user.home"), "Desktop")); } fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setDialogTitle("Open an .xml file"); fileChooser.setFileFilter(new FileNameExtensionFilter(".xml Files", "xml")); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); lastFile = selectedFile; world.load(new FileHandle(selectedFile)); if (world.getPlayer() != null) world.camera.forceCenterOn( world.getPlayer().x, world.getPlayer().y); world.entities.clear(); } } iothreadtodo = 0; } } } }; iothread.setDaemon(true); iothread.start(); } Array<String> blocks = new Array<String>(); private File lastFile = null; private Thread iothread; /** * 0 = nothing, 1 = save, 2 = load */ private int iothreadtodo = 0; int selx = 0; int sely = 0; int blocksel = 0; String defaultmeta = null; World world; public void resetWorld() { if (world == null) { world = new World(main); } world.renderer.showGrid = true; world.prepare(); if (world.getPlayer() != null) { world.setBlock(Blocks.instance().getBlock("spawnerplayer"), (int) world.getPlayer().x, (int) world.getPlayer().y); } world.entities.clear(); } private void setToGroup(int group) { for (int i = 0; i < blocks.size; i++) { if (Blocks.instance().getBlock(blocks.get(i)).levelEditorGroup == group) { blocksel = i; return; } } } @Override public void render(float delta) { world.renderOnly(); selx = world.getRoomX(Main.getInputX()); sely = world.getRoomY(Main.getInputY()); main.batch.begin(); if (Gdx.input.isKeyPressed(Keys.TAB)) { renderPalette(); } main.batch.setColor(1, 1, 1, 0.5f); Blocks.instance().getBlock(blocks.get(blocksel)).render(world, selx, sely); main.batch.setColor(1, 1, 1, 1); main.drawInverse("DEBUG MODE RECOMMENDED - F12", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 5); main.drawInverse("ALT+S - SAVE", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 20); main.drawInverse("ALT+O - OPEN", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 35); main.drawInverse("NUMPAD 8462 - change level dimensions (will reset level!)", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 50); main.drawInverse("ALT+D - change metadata of selected", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 65); main.drawInverse("ALT+SHFT+D - change DEFAULT metadata", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 80); main.drawInverse("ALT+T - TEST LEVEL", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 95); main.drawInverse("- / + - ADJUST VOID TIME (" + world.voidTime + " s)", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 110); main.drawInverse("hold TAB - block picker", Settings.DEFAULT_WIDTH - 5, Gdx.graphics.getHeight() - 125); main.batch.end(); world.camera.clamp(); } private void renderPalette() { for (int i = 0; i < EditorGroup.GROUP_NUMBERS; i++) { main.batch.setColor(0, 0, 0, 0.5f); main.fillRect(0, i * 64, Settings.DEFAULT_WIDTH, 64); main.batch.setColor(1, 1, 1, 1); int blockiter = 0; for (String b : blocks) { if (Blocks.instance().getBlock(b).levelEditorGroup == i) { Blocks.instance() .getBlock(b) .renderWithOffset( world, 0, 0, world.camera.camerax + (blockiter * 64) + 64, world.camera.cameray + Settings.DEFAULT_HEIGHT - World.tilesizey - (i * 64)); if (Gdx.input.getX() >= (blockiter * 64) + World.tilesizex && Gdx.input.getX() <= (blockiter * 64) + (World.tilesizex * 2)) { if (Gdx.input.getY() >= Settings.DEFAULT_HEIGHT - World.tilesizey - (i * 64) && Gdx.input.getY() <= Settings.DEFAULT_HEIGHT - World.tilesizey - (i * 64) + World.tilesizey) { blocksel = Math.max(0, blocks.lastIndexOf(b, false)); } } blockiter++; } } main.font.setScale(2.5f); main.drawCentered("" + i, 32, i * 64 - 16 + 64); main.font.setScale(1f); main.fillRect(0, i * 64 + 62, Settings.DEFAULT_WIDTH, 2); main.fillRect(64, i * 64, 2, 64); } main.batch.setColor(1, 1, 1, 1); } private void save() { for (Entity e : world.entities) { if (e == world.getPlayer()) { world.entities.removeValue(e, true); break; } } if (lastFile != null) { world.save(new FileHandle(lastFile)); } else { iothreadtodo = 1; } } @Override public void tickUpdate() { } @Override public void renderDebug(int starting) { main.font.draw(main.batch, "selx: " + selx, 5, Main.convertY(starting)); main.font.draw(main.batch, "sely: " + sely, 5, Main.convertY(starting + 15)); main.font.draw(main.batch, "block at " + selx + ", " + sely + ": " + Blocks.instance().getKey(world.getBlock(selx, sely)), 5, Main.convertY(starting + 30)); main.font.draw(main.batch, "block selected: " + blocks.get(blocksel), 5, Main.convertY(starting + 60)); main.font.draw(main.batch, "default meta: " + defaultmeta, 5, Main.convertY(starting + 75)); main.font.draw(main.batch, "block meta: " + world.getMeta(selx, sely), 5, Main.convertY(starting + 90)); main.font.draw(main.batch, "world sizex: " + world.sizex, 5, Main.convertY(starting + 120)); main.font.draw(main.batch, "world sizey: " + world.sizey, 5, Main.convertY(starting + 135)); main.font.draw(main.batch, "file location: " + (lastFile == null ? null : lastFile.getName()), 5, Main.convertY(starting + 165)); } @Override public void resize(int width, int height) { } @Override public void show() { if (world == null) { resetWorld(); } } @Override public void hide() { } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } @Override public void renderUpdate() { if (Gdx.input.isKeyPressed(Keys.UP) || Gdx.input.isKeyPressed(Keys.W)) { world.camera.cameray -= (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT) ? 32 : 16) * (Gdx.graphics.getDeltaTime() * World.tilesizey); world.camera.clamp(); } else if ((Gdx.input.isKeyPressed(Keys.DOWN) || Gdx.input.isKeyPressed(Keys.S)) && !(Gdx.input.isKeyPressed(Keys.ALT_LEFT) || Gdx.input .isKeyPressed(Keys.ALT_RIGHT))) { world.camera.cameray += (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT) ? 32 : 16) * (Gdx.graphics.getDeltaTime() * World.tilesizey); world.camera.clamp(); } if (Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A)) { world.camera.camerax -= (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT) ? 32 : 16) * (Gdx.graphics.getDeltaTime() * World.tilesizex); world.camera.clamp(); } else if (Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D)) { world.camera.camerax += (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT) ? 32 : 16) * (Gdx.graphics.getDeltaTime() * World.tilesizex); world.camera.clamp(); } if (Gdx.input.isButtonPressed(Buttons.LEFT)) { world.setBlock(Blocks.instance().getBlock(blocks.get(blocksel)), selx, sely); world.setMeta(defaultmeta, selx, sely); } else if (Gdx.input.isButtonPressed(Buttons.RIGHT)) { world.setBlock(Blocks.instance().getBlock(Blocks.defaultBlock), selx, sely); world.setMeta(null, selx, sely); } else if (Gdx.input.isButtonPressed(Buttons.MIDDLE)) { if (!Blocks.instance().getKey(world.getBlock(selx, sely)).equals(blocks.get(blocksel))) { for (int i = 0; i < blocks.size; i++) { if (blocks.get(i).equals(Blocks.instance().getKey(world.getBlock(selx, sely)))) { blocksel = i; break; } } } } if (Gdx.input.isKeyJustPressed(Keys.NUM_0)) { setToGroup(0); } else { for (int i = 0; i < 9; i++) { if (Gdx.input.isKeyJustPressed(Keys.NUM_1 + i)) { setToGroup(i + 1); break; } } } if (Gdx.input.isKeyJustPressed(Keys.ESCAPE)) { main.setScreen(Main.MAINMENU); } if (Gdx.input.isKeyJustPressed(Keys.NUMPAD_4)) { if (world.sizex > 30) world.sizex -= 2; resetWorld(); lastFile = null; } else if (Gdx.input.isKeyJustPressed(Keys.NUMPAD_6)) { if(world.sizex < 80) world.sizex += 2; resetWorld(); lastFile = null; } if (Gdx.input.isKeyJustPressed(Keys.NUMPAD_8)) { if(world.sizey < 60) world.sizey += 1; resetWorld(); lastFile = null; } else if (Gdx.input.isKeyJustPressed(Keys.NUMPAD_2)) { if (world.sizey > 20) world.sizey -= 2; resetWorld(); lastFile = null; } if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) { if (Gdx.input.isKeyJustPressed(Keys.PLUS) || Gdx.input.isKeyJustPressed(Keys.EQUALS)) { world.voidTime += 5; } else if (Gdx.input.isKeyJustPressed(Keys.MINUS)) { world.voidTime -= 5; if (world.voidTime < -1) world.voidTime = -1; } } else { if (Gdx.input.isKeyJustPressed(Keys.PLUS) || Gdx.input.isKeyJustPressed(Keys.EQUALS)) { world.voidTime++; } else if (Gdx.input.isKeyJustPressed(Keys.MINUS)) { if (world.voidTime > -1) world.voidTime } } if (Gdx.input.isKeyPressed(Keys.ALT_LEFT) || Gdx.input.isKeyPressed(Keys.ALT_RIGHT)) { if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) { if (Gdx.input.isKeyJustPressed(Keys.S)) { iothreadtodo = 1; } else if (Gdx.input.isKeyJustPressed(Keys.D)) { String result = (String) JOptionPane.showInputDialog(null, "Current default meta: " + defaultmeta, "Editing default meta", JOptionPane.PLAIN_MESSAGE, null, null, (defaultmeta == null ? "" : defaultmeta)); if (result != null) { defaultmeta = (result.equals("") ? null : result); } } } else { if (Gdx.input.isKeyJustPressed(Keys.O)) { iothreadtodo = 2; } else if (Gdx.input.isKeyJustPressed(Keys.S)) { save(); } else if (Gdx.input.isKeyJustPressed(Keys.D)) { int x = selx; int y = sely; String result = (String) JOptionPane.showInputDialog(null, "Current metadata: " + world.getMeta(x, y), "Editing tiledata (" + Blocks.instance().getKey(world.getBlock(x, y)) + ") at " + x + ", " + y, JOptionPane.PLAIN_MESSAGE, null, null, (world.getMeta(x, y) == null ? "" : world.getMeta(x, y))); if (result != null) { world.setMeta(result.equals("") ? null : result, x, y); } } else if (Gdx.input.isKeyJustPressed(Keys.T)) { if (lastFile != null) { Main.TESTLEVEL.world.load(new FileHandle(lastFile)); main.setScreen(Main.TESTLEVEL); } } } } } public static class EditorGroup { public static final int NOTPLACEABLE = -1; public static final int TOGGLE = 1; public static final int BUTTON = 2; public static final int TIMER = 3; public static final int SPAWNER = 4; public static final int COLLECTIBLE = 5; public static final int GROUP_NUMBERS = 6; } }
package test; import static org.junit.Assert.*; import java.util.Collection; import interpreter.Parser; import interpreter.expression.SLogoExpression; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import exceptions.SLogoParsingException; public class ParserTester { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void parseExceptionTest() { exception.expect(SLogoParsingException.class); Parser p = new Parser(); String input = "forward 50 50"; try { Collection<SLogoExpression> expression = p.parseSLogoExpression(input); } catch (SLogoParsingException e) { System.out.println(exception.toString()); fail(); } } @Test public void singleCommandParseTest() { exception.expect(SLogoParsingException.class); Parser p = new Parser(); String input = "forward 50"; try { Collection<SLogoExpression> expressions = p.parseSLogoExpression(input); assertEquals(expressions.size(),1); } catch (SLogoParsingException e) { // TODO Auto-generated catch block System.out.println("exception.toString()"); fail(); } } @Test public void twoCommandParseTest() { exception.expect(SLogoParsingException.class); Parser p = new Parser(); String input = "forward 50 forward 50"; try { Collection<SLogoExpression> expressions = p.parseSLogoExpression(input); assertEquals(expressions.size(),2); } catch (SLogoParsingException e) { // TODO Auto-generated catch block System.out.println("exception.toString()"); } } }
package com.creatubbles.api; public enum ContentType { URL_ENCODED("application/x-www-form-urlencoded;charset=UTF-8"), VND_JSON("application/vnd.api+json"), JSON("application/json"), PNG("png"), JPG("jpg"), JPEG("jpeg"), H264("h264"), MPEG4("mpeg4"), WMV("wmv"), WEBM("webm"), FLV("flv"), OGG("ogg"), OGV("ogv"), MP4("mp4"), M4V("m4v"), F4V("f4v"), MOV("mov"), ZIP("zip"), GIF("gif"); String res; ContentType(String res) { this.res = res; } public String getRes() { return res; } }
package tomatron; import java.util.Timer; import java.util.TimerTask; import java.awt.*; import java.awt.event.*; import java.io.IOException; import javax.swing.*; public class Tomatron { enum PomodoroState { inactive, pomodoro, shortBreak, longBreak } private PomodoroState state = PomodoroState.inactive; private TrayIcon trayIcon = new TrayIcon(TomatronUtils.createTrayIconImage("P", 0.75, new Color(100, 100, 100))); private final SystemTray tray = SystemTray.getSystemTray(); private int completedPomodoros = 0; MenuItem pomodoroCountItem = new MenuItem("Completed Pomodoros: 0"); MenuItem pomodoroItem = new MenuItem("Start Pomodoro"); MenuItem shortBreakItem = new MenuItem("Short Break"); MenuItem longBreakItem = new MenuItem("Long Break"); MenuItem cancelItem = new MenuItem("Cancel"); MenuItem restartCountItem = new MenuItem("Restart Pomodoro Count"); MenuItem exitItem = new MenuItem("Exit"); int secondsRemaining = 0; Timer timer = new Timer(); public Tomatron() { setState(PomodoroState.inactive); try { tray.add(trayIcon); } catch (AWTException e) { System.err.println("TrayIcon could not be added."); System.exit(1); } SwingUtilities.invokeLater(new Runnable() { public void run() { populateMenu(); } }); } private void displayDesktopNotification(String summary, String message) { try { // Try notify-send. This is usually available on linux String[] cmd = {"notify-send", summary, message}; Process notifySend = Runtime.getRuntime().exec(cmd); notifySend.waitFor(); } catch (IOException | InterruptedException e) { // Java AWT tray icon notification. // Looks fine on Windows. Works on Linux as a fallback, but does not look so good trayIcon.displayMessage(summary, message, TrayIcon.MessageType.NONE); } } /** * Task that is triggered every second. * Automatically transitions the state upon timer expiration and updates information presented to the user. */ class EverySecond extends TimerTask { public void run() { if (state != PomodoroState.inactive) { secondsRemaining if (secondsRemaining <= 0) { // A break or pomodoro is finished switch (state) { case pomodoro: displayDesktopNotification("Pomodoro finished", "Time for a break!"); completedPomodoros++; break; case longBreak: case shortBreak: displayDesktopNotification("Break finished", "You can start a new pomodoro when ready."); break; default: break; } setState(PomodoroState.inactive); } } updatePomodoroInfo(); } } /** * Updates the tray icon and tooltip */ private void updatePomodoroInfo() { pomodoroCountItem.setEnabled(false); pomodoroCountItem.setLabel(String.format("Completed Pomodoros: %d", completedPomodoros)); String shortTimeLeftString; if (secondsRemaining > 60) { shortTimeLeftString = Integer.toString(secondsRemaining / 60); } else { shortTimeLeftString = Integer.toString(secondsRemaining); } String timeLeftString = String.format("%02d:%02d", (secondsRemaining / 60), secondsRemaining % 60); switch (state) { case pomodoro: trayIcon.setImage(TomatronUtils.createTrayIconImage(shortTimeLeftString, 0.75, new Color(130, 30, 30))); trayIcon.setToolTip(String.format( "Pomodoro in progress\nRemaining: %s", timeLeftString) .toString()); break; case shortBreak: trayIcon.setImage(TomatronUtils.createTrayIconImage(shortTimeLeftString, 0.75, new Color(20, 100, 40))); trayIcon.setToolTip(String.format( "Short break in progress\nRemaining: %s", timeLeftString) .toString()); break; case longBreak: trayIcon.setImage(TomatronUtils.createTrayIconImage(shortTimeLeftString, 0.75, new Color(10, 80, 150))); trayIcon.setToolTip(String.format( "Long break in progress\nRemaining: %s", timeLeftString) .toString()); break; case inactive: trayIcon.setImage(TomatronUtils.createTrayIconImage("P", 0.75, new Color( 100, 100, 100))); trayIcon.setToolTip(String.format("Tomatron: inactive", timeLeftString).toString()); break; } } /** * Execute state transition and update UI/timers accordingly * @param newState new state to assume */ private void setState(PomodoroState newState) { pomodoroItem.setLabel("Start Pomodoro"); shortBreakItem.setLabel("Start Short Break"); longBreakItem.setLabel("Start Long Break"); cancelItem.setLabel("Cancel"); cancelItem.setEnabled(true); timer.cancel(); state = newState; switch (state) { case pomodoro: pomodoroItem.setLabel("Restart Pomodoro"); cancelItem.setLabel("Void Pomodoro"); secondsRemaining = 25 * 60; timer = new Timer(); timer.scheduleAtFixedRate(new EverySecond(), 0, 1000L); break; case shortBreak: shortBreakItem.setLabel("Restart Short Break"); cancelItem.setLabel("Cancel Break"); secondsRemaining = 5 * 60; timer = new Timer(); timer.scheduleAtFixedRate(new EverySecond(), 0, 1000L); break; case longBreak: longBreakItem.setLabel("Restart Long Break"); cancelItem.setLabel("Cancel Break"); secondsRemaining = 15 * 60; timer = new Timer(); timer.scheduleAtFixedRate(new EverySecond(), 0, 1000L); break; case inactive: cancelItem.setEnabled(false); secondsRemaining = 0; break; } updatePomodoroInfo(); } /** * Add all items and listeners to the right click menu */ private void populateMenu() { final PopupMenu popup = new PopupMenu(); popup.add(pomodoroCountItem); popup.addSeparator(); popup.add(pomodoroItem); popup.add(shortBreakItem); popup.add(longBreakItem); popup.addSeparator(); popup.add(cancelItem); popup.addSeparator(); popup.add(restartCountItem); popup.add(exitItem); pomodoroItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setState(PomodoroState.pomodoro); } }); shortBreakItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setState(PomodoroState.shortBreak); } }); longBreakItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setState(PomodoroState.longBreak); } }); cancelItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setState(PomodoroState.inactive); } }); restartCountItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { completedPomodoros = 0; updatePomodoroInfo(); } }); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tray.remove(trayIcon); System.exit(0); } }); trayIcon.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "You can use Tomatron by right clicking on the system tray icon."); } }); trayIcon.setPopupMenu(popup); } public static void main(String[] args) { if (!SystemTray.isSupported()) { System.err.println("System tray is not supported on this system"); System.exit(1); } new Tomatron(); } }
package com.sbugert.rnadmob; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class RNAdMobPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList( new RNAdMobInterstitialAdModule(reactContext), new RNAdMobRewardedVideoAdModule(reactContext) ); } // Deprecated from RN 0.47.0 public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> managers = new ArrayList<>(); managers.add(new RNAdMobBannerViewManager()); managers.add(new RNPublisherBannerViewManager()); return managers; } }
package org.anyline.jdbc.entity; import org.anyline.jdbc.config.db.SQLCreater; import org.anyline.listener.DDListener; import org.anyline.service.AnylineService; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; public class Index { private String catalog ; private String schema ; private String table ; private String name ; private boolean unique ; private boolean cluster ; private int type ; private LinkedHashMap<String,Column> columns = new LinkedHashMap<>(); private Index update; private DDListener listener ; public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isUnique() { return unique; } public void setUnique(boolean unique) { this.unique = unique; } public boolean isCluster() { return cluster; } public void setCluster(boolean cluster) { this.cluster = cluster; } public int getType() { return type; } public void setType(int type) { this.type = type; } public LinkedHashMap<String, Column> getColumns() { return columns; } public void setColumns(LinkedHashMap<String, Column> columns) { this.columns = columns; } public Index getUpdate() { return update; } public void setUpdate(Index update) { this.update = update; } public DDListener getListener() { return listener; } public Index setListener(DDListener listener) { this.listener = listener; return this; } public Index setService(AnylineService service){ if(null != listener){ listener.setService(service); } return this; } public Index setCreater(SQLCreater creater) { if (null != listener) { listener.setCreater(creater); } return this; } }
package net.md_5.bungee.api.chat; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import net.md_5.bungee.api.ChatColor; import java.util.ArrayList; import java.util.List; import lombok.ToString; @Setter @ToString @NoArgsConstructor public abstract class BaseComponent { @Setter(AccessLevel.NONE) BaseComponent parent; /** * The color of this component and any child components (unless overridden) */ private ChatColor color; /** * Whether this component and any child components (unless overridden) is * bold */ private Boolean bold; /** * Whether this component and any child components (unless overridden) is * italic */ private Boolean italic; /** * Whether this component and any child components (unless overridden) is * underlined */ private Boolean underlined; /** * Whether this component and any child components (unless overridden) is * strikethrough */ private Boolean strikethrough; /** * Whether this component and any child components (unless overridden) is * obfuscated */ private Boolean obfuscated; /** * Appended components that inherit this component's formatting and events */ @Getter private List<BaseComponent> extra; /** * The action to preform when this component (and child components) are * clicked */ @Getter private ClickEvent clickEvent; /** * The action to preform when this component (and child components) are * hovered over */ @Getter private HoverEvent hoverEvent; BaseComponent(BaseComponent old) { setColor( old.getColorRaw() ); setBold( old.isBoldRaw() ); setItalic( old.isItalicRaw() ); setUnderlined( old.isUnderlinedRaw() ); setStrikethrough( old.isStrikethroughRaw() ); setObfuscated( old.isObfuscatedRaw() ); setClickEvent( old.getClickEvent() ); setHoverEvent( old.getHoverEvent() ); } /** * Converts the components to a string that uses the old formatting codes * ({@link net.md_5.bungee.api.ChatColor#COLOR_CHAR} * * @param components the components to convert * @return the string in the old format */ public static String toLegacyText(BaseComponent... components) { StringBuilder builder = new StringBuilder(); for ( BaseComponent msg : components ) { builder.append( msg.toLegacyText() ); } return builder.toString(); } /** * Converts the components into a string without any formatting * * @param components the components to convert * @return the string as plain text */ public static String toPlainText(BaseComponent... components) { StringBuilder builder = new StringBuilder(); for ( BaseComponent msg : components ) { builder.append( msg.toPlainText() ); } return builder.toString(); } /** * Returns the color of this component. This uses the parent's color if this * component doesn't have one. {@link net.md_5.bungee.api.ChatColor#WHITE} * is returned if no color is found. * * @return the color of this component */ public ChatColor getColor() { if ( color == null ) { if ( parent == null ) { return ChatColor.WHITE; } return parent.getColor(); } return color; } /** * Returns the color of this component without checking the parents color. * May return null * * @return the color of this component */ public ChatColor getColorRaw() { return color; } /** * Returns whether this component is bold. This uses the parent's setting if * this component hasn't been set. false is returned if none of the parent * chain has been set. * * @return whether the component is bold */ public boolean isBold() { if ( bold == null ) { return parent != null && parent.isBold(); } return bold; } /** * Returns whether this component is bold without checking the parents * setting. May return null * * @return whether the component is bold */ public Boolean isBoldRaw() { return bold; } /** * Returns whether this component is italic. This uses the parent's setting * if this component hasn't been set. false is returned if none of the * parent chain has been set. * * @return whether the component is italic */ public boolean isItalic() { if ( italic == null ) { return parent != null && parent.isItalic(); } return italic; } /** * Returns whether this component is italic without checking the parents * setting. May return null * * @return whether the component is italic */ public Boolean isItalicRaw() { return italic; } /** * Returns whether this component is underlined. This uses the parent's * setting if this component hasn't been set. false is returned if none of * the parent chain has been set. * * @return whether the component is underlined */ public boolean isUnderlined() { if ( underlined == null ) { return parent != null && parent.isUnderlined(); } return underlined; } /** * Returns whether this component is underlined without checking the parents * setting. May return null * * @return whether the component is underlined */ public Boolean isUnderlinedRaw() { return underlined; } /** * Returns whether this component is strikethrough. This uses the parent's * setting if this component hasn't been set. false is returned if none of * the parent chain has been set. * * @return whether the component is strikethrough */ public boolean isStrikethrough() { if ( strikethrough == null ) { return parent != null && parent.isStrikethrough(); } return strikethrough; } /** * Returns whether this component is strikethrough without checking the * parents setting. May return null * * @return whether the component is strikethrough */ public Boolean isStrikethroughRaw() { return strikethrough; } /** * Returns whether this component is obfuscated. This uses the parent's * setting if this component hasn't been set. false is returned if none of * the parent chain has been set. * * @return whether the component is obfuscated */ public boolean isObfuscated() { if ( obfuscated == null ) { return parent != null && parent.isObfuscated(); } return obfuscated; } /** * Returns whether this component is obfuscated without checking the parents * setting. May return null * * @return whether the component is obfuscated */ public Boolean isObfuscatedRaw() { return obfuscated; } public void setExtra(List<BaseComponent> components) { for ( BaseComponent component : components ) { component.parent = this; } extra = components; } /** * Appends a text element to the component. The text will inherit this * component's formatting * * @param text the text to append */ public void addExtra(String text) { addExtra( new TextComponent( text ) ); } /** * Appends a component to the component. The text will inherit this * component's formatting * * @param component the component to append */ public void addExtra(BaseComponent component) { if ( extra == null ) { extra = new ArrayList<>(); } component.parent = this; extra.add( component ); } /** * Returns whether the component has any formatting or events applied to it * * @return Whether any formatting or events are applied */ public boolean hasFormatting() { return color != null || bold != null || italic != null || underlined != null || strikethrough != null || obfuscated != null || hoverEvent != null || clickEvent != null; } /** * Converts the component into a string without any formatting * * @return the string as plain text */ public String toPlainText() { StringBuilder builder = new StringBuilder(); toPlainText( builder ); return builder.toString(); } void toPlainText(StringBuilder builder) { if ( extra != null ) { for ( BaseComponent e : extra ) { e.toPlainText( builder ); } } } /** * Converts the component to a string that uses the old formatting codes * ({@link net.md_5.bungee.api.ChatColor#COLOR_CHAR} * * @return the string in the old format */ public String toLegacyText() { StringBuilder builder = new StringBuilder(); toLegacyText( builder ); return builder.toString(); } void toLegacyText(StringBuilder builder) { if ( extra != null ) { for ( BaseComponent e : extra ) { e.toLegacyText( builder ); } } } }
package com.rbmhtechnology.vind.api; import com.google.common.collect.ImmutableSet; import com.rbmhtechnology.vind.api.query.filter.Filter; import com.rbmhtechnology.vind.api.query.filter.parser.FilterLuceneParser; import com.rbmhtechnology.vind.model.DocumentFactory; import com.rbmhtechnology.vind.model.DocumentFactoryBuilder; import com.rbmhtechnology.vind.model.FieldDescriptor; import com.rbmhtechnology.vind.model.FieldDescriptorBuilder; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.Set; import static com.rbmhtechnology.vind.api.query.filter.Filter.eq; /** * @author Thomas Kurz (tkurz@apache.org) * @since 04.07.16. */ public class FilterTest { @Test public void testAndFilters() { Filter f = Filter.AndFilter.fromSet(ImmutableSet.of(eq("a", "1"),eq("b","2"),eq("b","3"))); Assert.assertTrue(f instanceof Filter.AndFilter); Assert.assertEquals(3, ((Filter.AndFilter)f).getChildren().size()); Set<String> values = ImmutableSet.of("a","b","c","d"); Filter filter = values.stream().map(v -> eq("cat",v)).collect(Filter.AndCollector); Assert.assertTrue(filter instanceof Filter.AndFilter); Assert.assertEquals(4, ((Filter.AndFilter)filter).getChildren().size()); } @Test public void testFilterSerializer() throws IOException { final FilterLuceneParser filterLuceneParser = new FilterLuceneParser(); final FieldDescriptor<String> customMetadata = new FieldDescriptorBuilder<>() .setFacet(true) .buildTextField("customMetadata"); final DocumentFactory testDocFactory = new DocumentFactoryBuilder("testDoc") .addField(customMetadata) .build(); Filter vindFilter = filterLuceneParser .parse( "+customMetadata:(\"coveragedb=true\" AND NOT \"cloudTranscoding=true\") " , testDocFactory); vindFilter = filterLuceneParser .parse( "+customMetadata:((\"meppGraph=true\" OR \"coveragedb=true\") AND NOT \"cloudTranscoding=true\") " , testDocFactory); vindFilter = filterLuceneParser .parse( "+customMetadata:((\"meppGraph=true\" OR \"coveragedb=true\") AND NOT ( \"netStorage=true\" AND \"cloudTranscoding=true\")) " , testDocFactory); } }
package edu.umd.cs.findbugs; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; /** * Starting from an Eclipse plugin, finds all required plugins * (in an Eclipse installation) and recursively finds the classpath * required to compile the original plugin. Different Eclipse * releases will generally have different version numbers on the * plugins they contain, which makes this task slightly difficult. * * <p> Basically, this is a big complicated hack to allow compilation * of the FindBugs Eclipse plugin outside of the Eclipse workspace, * in a way that doesn't depend on any specific release of Eclipse. * * @author David Hovemeyer */ public class EclipseClasspath { public static class EclipseClasspathException extends Exception { public EclipseClasspathException(String msg) { super(msg); } } /** * A customized Reader for Eclipse plugin descriptor files. * The problem is that Eclipse uses invalid XML in the form of * directives like * <pre> * &lt;?eclipse version="3.0"?&gt; * </pre> * outside of the root element. This Reader class * filters out this crap. */ private static class EclipseXMLReader extends Reader { private BufferedReader reader; private LinkedList<String> lineList; public EclipseXMLReader(Reader reader) { this.reader = new BufferedReader(reader); this.lineList = new LinkedList<String>(); } public int read(char[] cbuf, int off, int len) throws IOException { if (!fill()) return -1; String line = lineList.getFirst(); if (len > line.length()) len = line.length(); for (int i = 0; i < len; ++i) cbuf[i+off] = line.charAt(i); if (len == line.length()) lineList.removeFirst(); else lineList.set(0, line.substring(len)); return len; } public void close() throws IOException { reader.close(); } private boolean fill() throws IOException { if (!lineList.isEmpty()) return true; String line; do { line = reader.readLine(); if (line == null) return false; } while (isIllegal(line)); lineList.add(line+"\n"); return true; } private boolean isIllegal(String line) { return line.startsWith("<?eclipse"); } } private static class Plugin { private String directory; private Document document; private boolean isDependent; private String pluginId; private List<String> requiredPluginIdList; private List<String> exportedLibraryList; public Plugin(String directory, Document document, boolean isDependent) throws DocumentException, EclipseClasspathException { this.directory = directory; this.document = document; this.isDependent = isDependent; // Get the plugin id Node plugin = document.selectSingleNode("/plugin"); if (plugin == null) throw new EclipseClasspathException("No plugin node in plugin descriptor"); pluginId = plugin.valueOf("@id"); if (pluginId.equals("")) throw new EclipseClasspathException("Cannot determine plugin id"); //System.out.println("Plugin id is " + pluginId); // Extract required plugins requiredPluginIdList = new LinkedList<String>(); List requiredPluginNodeList = document.selectNodes("/plugin/requires/import"); for (Iterator i = requiredPluginNodeList.iterator(); i.hasNext(); ) { Node node = (Node) i.next(); String requiredPluginId = node.valueOf("@plugin"); if (requiredPluginId.equals("")) throw new EclipseClasspathException("Import has no plugin id"); //System.out.println(" Required plugin ==> " + requiredPluginId); requiredPluginIdList.add(requiredPluginId); } // Extract exported libraries exportedLibraryList = new LinkedList<String>(); List exportedLibraryNodeList = document.selectNodes("/plugin/runtime/library"); for (Iterator i = exportedLibraryNodeList.iterator(); i.hasNext(); ) { Node node = (Node) i.next(); String jarName = node.valueOf("@name"); if (jarName.equals("")) throw new EclipseClasspathException("Could not get name of exported library"); exportedLibraryList.add(new File(directory, jarName).getPath()); } } public String getDirectory() { return directory; } public boolean isDependent() { return isDependent; } public String getId() { return pluginId; } public Iterator<String> requiredPluginIdIterator() { return requiredPluginIdList.iterator(); } public Iterator<String> exportedLibraryIterator() { return exportedLibraryList.iterator(); } } private static final Pattern pluginDirPattern = Pattern.compile("^(\\w+(\\.\\w+)*)_(\\w+(\\.\\w+)*)$"); private static final int PLUGIN_ID_GROUP = 1; private String eclipseDir; private String rootPluginDir; private Map<String, File> pluginDirectoryMap; private List<String> importList; public EclipseClasspath(String eclipseDir, String rootPluginDir) { this.eclipseDir = eclipseDir; this.rootPluginDir = rootPluginDir; this.pluginDirectoryMap = new HashMap<String, File>(); } public void addRequiredPlugin(String pluginId, String pluginDir) { pluginDirectoryMap.put(pluginId, new File(pluginDir)); } private static class WorkListItem { private String directory; private boolean isDependent; public WorkListItem(String directory, boolean isDependent) { this.directory = directory; this.isDependent = isDependent; } public String getDirectory() { return directory; } public boolean isDependent() { return isDependent; } public String getDescriptorFileName() { return new File(directory, "plugin.xml").getPath(); } } public EclipseClasspath execute() throws EclipseClasspathException, DocumentException, IOException { // Build plugin directory map File pluginDir = new File(eclipseDir, "plugins"); File[] dirList = pluginDir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory(); } }); if (dirList == null) throw new EclipseClasspathException("Could not list plugins in directory " + pluginDir); for (int i = 0; i < dirList.length; ++i) { String pluginId = getPluginId(dirList[i].getName()); if (pluginId != null) { //System.out.println(pluginId + " ==> " + dirList[i]); pluginDirectoryMap.put(pluginId, dirList[i]); } } Map<String, Plugin> requiredPluginMap = new HashMap<String, Plugin>(); LinkedList<WorkListItem> workList = new LinkedList<WorkListItem>(); workList.add(new WorkListItem(rootPluginDir, false)); while (!workList.isEmpty()) { WorkListItem item = workList.removeFirst(); // Read the plugin file SAXReader reader = new SAXReader(); Document doc = reader.read(new EclipseXMLReader(new FileReader(item.getDescriptorFileName()))); // Add to the map Plugin plugin = new Plugin(item.getDirectory(), doc, item.isDependent()); requiredPluginMap.put(plugin.getId(), plugin); // Add unresolved required plugins to the worklist for (Iterator<String> i = plugin.requiredPluginIdIterator(); i.hasNext(); ) { String requiredPluginId = i.next(); if (requiredPluginMap.get(requiredPluginId) == null) { // Find the plugin's directory File requiredPluginDir = pluginDirectoryMap.get(requiredPluginId); if (requiredPluginDir == null) throw new EclipseClasspathException("Unable to find plugin " + requiredPluginId); workList.add(new WorkListItem(requiredPluginDir.getPath(), true)); } } } //System.out.println("Found " + requiredPluginMap.size() + " required plugins"); importList = new LinkedList<String>(); for (Iterator<Plugin> i = requiredPluginMap.values().iterator(); i.hasNext(); ) { Plugin plugin = i.next(); if (plugin.isDependent()) { for (Iterator<String> j = plugin.exportedLibraryIterator(); j.hasNext(); ) { //System.out.println("Import: " + j.next()); importList.add(j.next()); } } } return this; } public Iterator<String> importListIterator() { return importList.iterator(); } /** * Get the plugin id for given directory name. * Returns null if the directory name does not seem to * be a plugin. */ private String getPluginId(String dirName) { Matcher m = pluginDirPattern.matcher(dirName); return m.matches() ? m.group(PLUGIN_ID_GROUP) : null; } public static void main(String[] argv) throws Exception { if (argv.length < 2 || (argv.length % 2 != 0)) { System.err.println("Usage: " + EclipseClasspath.class.getName() + " <eclipse dir> <root plugin directory> [<required plugin id> <required plugin dir> ...]"); System.exit(1); } EclipseClasspath ec = new EclipseClasspath(argv[0], argv[1]); for (int i = 2; i < argv.length; i += 2) { ec.addRequiredPlugin(argv[i], argv[i+1]); } boolean first = true; Iterator <String> i = ec.execute().importListIterator(); while (i.hasNext()) { if (first) first = false; else System.out.print(File.pathSeparator); System.out.print(i.next()); } System.out.println(); } } // vim:ts=4
package nars.main; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.logging.Level; import java.util.logging.Logger; import nars.main.NAR; import nars.io.events.TextOutputHandler; /** * Run Reasoner * <p> Runs a NAR with addInput. useful for command line or batch functionality; TODO check duplicated code with {@link nars.main.NARS} * <p> * Manage the internal working thread. Communicate with Reasoner only. */ public class Shell { private final NAR nar; private boolean logging; private PrintStream out = System.out; private final boolean dumpLastState = true; int maxTime = 0; /** * The entry point of the standalone application. * <p> * @param args optional argument used : one addInput file */ public static void main(String args[]) { Shell nars = new Shell(new NAR()); nars.nar.addInput("*volume=0"); nars.run(args); // TODO only if single finish ( no reset in between ) if (nars.dumpLastState) { System.out.println("\n==== Dump Last State ====\n" + nars.nar.toString()); } } public Shell(NAR n) { this.nar = n; } private class InputThread extends Thread { private BufferedReader bufIn; NAR nar; InputThread(InputStream in, NAR nar) { this.bufIn = new BufferedReader(new InputStreamReader(in)); this.nar=nar; } public void run() { while(true) { try { String line=bufIn.readLine(); if(line!=null) nar.addInput(line); }catch(Exception ex){} try { Thread.sleep(1); }catch(Exception ex){} } } } /** * non-static equivalent to {@link #main(String[])} : finish to completion from an addInput file */ public void run(String args[]) { TextOutputHandler output = new TextOutputHandler(nar, new PrintWriter(out, true)); output.setErrors(true); output.setErrorStackTrace(true); InputThread it; int sleep = -1; boolean noFile = false; if (args.length > 0) { try { nar.addInputFile(args[0]); } catch (Exception ex) { noFile = true; sleep = Integer.valueOf(args[0]); //Integer.valueOf(args[0]); //System.err.println("NARRun.init: " + ex); } } if(args.length == 0 || noFile) { it=new InputThread(System.in,nar); it.start(); //nar.addInput(new TextInput(new BufferedReader(new InputStreamReader(System.in)))); } while (true) { if (logging) log("NARSBatch.run():" + " step " + nar.time()); nar.cycles(1); try { if(sleep > -1) { Thread.sleep(sleep); } } catch (InterruptedException ex) { Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex); } //System.out.println("step"); //System.out.println("step"); if (logging) log("NARSBatch.run(): after tick" + " step " + nar.time()); if (maxTime > 0) { if (nar.time() == maxTime) { break; } } } System.exit(0); } public void setPrintStream(PrintStream out) { this.out = out; } private void log(String mess) { if (logging) { System.out.println("/ " + mess); } } }
package de.eightbitboy.ecorealms; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import de.eightbitboy.ecorealms.config.EcoRealmsConfig; import de.eightbitboy.ecorealms.control.Control; import de.eightbitboy.ecorealms.control.ControlActionMapping; import de.eightbitboy.ecorealms.map.Map; import de.eightbitboy.ecorealms.world.camera.FlyingCamera; import de.eightbitboy.ecorealms.world.meta.GridLines; import de.eightbitboy.ecorealms.world.World; import de.eightbitboy.ecorealms.world.meta.Gizmo; import de.eightbitboy.ecorealms.world.render.ModelBatchRenderer; import de.eightbitboy.ecorealms.world.tool.Highlighter; public class EcoRealms extends ApplicationAdapter { private EcoRealmsConfig config; private Map map; private World world; private Environment environment; private PerspectiveCamera camera; private ModelBatchRenderer modelBatchRenderer; private Control control; public EcoRealms() { this.config = new EcoRealmsConfig(); } @Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); setupWorld(); setupEnvironment(); setupCamera(); setupControl(); setupRendering(); } @Override public void render() { executeGlFunctions(); control.updateCamera(); ControlActionMapping.getInstance().update(); camera.update(); modelBatchRenderer.render(); } private void executeGlFunctions() { Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL20.GL_BLEND); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); } private void setupWorld() { map = new Map(config.WORLD_SIZE_X, config.WORLD_SIZE_Y); world = new World(map); } private void setupEnvironment() { environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 1f, 0.5f, -0.8f)); } private void setupCamera() { camera = new FlyingCamera(); } private void setupControl() { control = new Control(camera, ControlActionMapping.getInstance(), map); Gdx.input.setInputProcessor(control); } private void setupRendering() { modelBatchRenderer = new ModelBatchRenderer(environment, camera); modelBatchRenderer.add(world); modelBatchRenderer.add(new GridLines(map)); modelBatchRenderer.add(new Highlighter()); //noinspection ConstantConditions if(config.showGizmo) { modelBatchRenderer.add(new Gizmo()); } } @Override public void dispose() { modelBatchRenderer.dispose(); } }
package io.ddf; import io.ddf.exception.DDFException; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.describe.DescribeTable; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectItem; import net.sf.jsqlparser.statement.select.WithItem; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TableNameReplacer extends TableVisitor { // The URI regex representation. private Pattern uriPattern = Pattern.compile("ddf:\\/\\/.*"); // The namespace. private String namespace = null; // The URI List. private List<String> uriList = null; // The UUID List. private List<UUID> uuidList = null; // The DDFManager. private DDFManager ddfManager = null; // DDF uri to table name mapping. private Map<String, String> uri2tbl = new HashMap<String, String>(); /** * @brief Constructor. * @param ddfManager The DDFManager. * @Note The default uri regex matches "ddf://". So we don't specify the urigex, we will * have default one the match. */ public TableNameReplacer(DDFManager ddfManager) { this.ddfManager = ddfManager; } /** * @brief Constructor * @param ddfManager * @param namespace The namespace. When we are handling tablename, if ddf:// regex match fail * and {number} match fail, and namespace is specified, the tablename will be * converted to ddf://namespace/tablename automatically. */ public TableNameReplacer(DDFManager ddfManager, String namespace) { this.ddfManager = ddfManager; this.namespace = namespace; } public TableNameReplacer(DDFManager ddfManager, String namespace, String uriRegex) { this.ddfManager = ddfManager; this.namespace = namespace; this.uriPattern = Pattern.compile(uriRegex); } /** * @brief Constructor. * @param ddfManager * @param uriList The list of uri. */ public TableNameReplacer(DDFManager ddfManager, List<String> uriList) { this.ddfManager = ddfManager; this.uriList = uriList; } public TableNameReplacer(DDFManager ddfManager, String namespace, List<String> uriList) { this.ddfManager = ddfManager; this.namespace = namespace; this.uriList = uriList; } /** * @brief Constructor. Combination replacer, it will check dd://, {number}, tablename format * respectively. * @param ddfManager * @param namespace * @param uriRegex * @param uriList */ public TableNameReplacer(DDFManager ddfManager, String namespace, String uriRegex, List<String> uriList) { this.ddfManager = ddfManager; this.namespace = namespace; this.uriPattern = Pattern.compile(uriRegex); this.uriList = uriList; } /** * @brief Constructor. * @param ddfManager * @param uuidList The list of uuids. */ public TableNameReplacer(DDFManager ddfManager, UUID[] uuidList) { this.ddfManager = ddfManager; this.uuidList = Arrays.asList(uuidList); } /** * @brief Run the replacer. * @param statement The SQL statement. * @brief The new statement. */ public Statement run(Statement statement) throws Exception { // Clear the with table names in case that we run several sql command. this.withTableNameList.clear(); if (statement instanceof Select) { visit(statement); } else if (statement instanceof DescribeTable){ ((DescribeTable)statement).accept(this); // TODO: Handler for other statments. } return statement; } @Override public void visit(WithItem withItem) throws Exception { // TODO: Redo this later. What's withItem list. // Add with name here. if (withItem.getName() != null) { this.withTableNameList.add(withItem.getName()); } withItem.getSelectBody().accept(this); if (withItem.getWithItemList() != null) { for (SelectItem selectItem : withItem.getWithItemList()) { selectItem.accept(this); } } } /** * @brief Override the visit function. The function takes care of 3 kinds of situation: * (1) URI is used. For example, the ddf name is ddf://adatao/ddfA, and the query is like * select * from ddf://adatao/ddfA. * (2) Dataset name and namespace is used. For example, the ddf name is ddf://adatao/ddfA, and the query is like * select * from ddfA, namespace = adatao. * (3) List is used. For example, the query is like * select {1}.a, {2}.b from {1},{2} where {1}.id={2}.id, ddfList= {"ddf://adatao/ddfA", "ddf://adatao/ddfB"}. * Here we write them in a single function so that we can handle the situation when different situations are * combined. For example, select {1}.a from ddf://adatao/ddfA, ddfList={"ddf://adatao/ddfB"}. * @param table The table that is visiting. */ public void visit(Table table) throws Exception { if (null == table || null == table.getName()) return; String name = table.getName(); for (String tablename : this.withTableNameList) { // It a table name appeared in with clause. if (tablename.equals(name)) { return; } } Matcher matcher = this.uriPattern.matcher(name); if (matcher.matches()) { // The first situation. String tablename = this.handleDDFURI(name); table.setName(tablename); } else if (namespace != null) { // The second situation. // TODO: leave structure here. String uri = "ddf://".concat(namespace.concat("/").concat(name)); if (this.ddfManager.getDDFByURI(uri) == null) { try { this.ddfManager.getOrRestoreDDFUri(uri); } catch (DDFException e) { throw new Exception("ERROR: There is no ddf with uri:" + uri); } } table.setName(this.ddfManager.getDDFByURI(uri).getTableName()); } else if (uriList != null || uuidList != null) { // The third situation. Pattern indexPattern = Pattern.compile("\\{\\d+\\}"); Matcher indexMatcher = indexPattern.matcher(name); if (indexMatcher.matches()) { String number = name.substring(name.indexOf('{') + 1, name.indexOf('}')).trim(); int index = Integer.parseInt(number); if (index < 1) { throw new Exception("In the SQL command, " + "if you use {number} as index, the number should begin from 1"); } if (null == uriList) { if (index > uuidList.size()) { throw new Exception(new ArrayIndexOutOfBoundsException()); } else { if (null == this.ddfManager.getDDF(uuidList.get(index - 1))) { try { this.ddfManager.getOrRestoreDDF(uuidList.get(index - 1)); } catch (DDFException e) { throw new Exception("ERROR: There is no ddf with uri:" + uuidList.get(index - 1).toString()); } } table.setName(this.ddfManager.getDDF(uuidList.get(index - 1)).getTableName()); } } else { if (index > uriList.size()) { throw new Exception(new ArrayIndexOutOfBoundsException()); } else { if (this.ddfManager.getDDFByURI(uriList.get(index - 1)) == null) { try { this.ddfManager.getOrRestoreDDFUri(uriList.get(index - 1)); } catch (DDFException e) { throw new Exception("ERROR: There is no ddf with uri:" + uriList.get(index - 1)); } } table.setName(this.ddfManager.getDDFByURI(uriList.get(index - 1)).getTableName()); } } } else { // Not full uri, no namespace, the index can't match. System.out.println("ddf name is:" + table.getName()); throw new Exception("ERROR: Can't find the required ddf"); } } else { // No modification. throw new Exception("ERROR: The ddf reference should either full uri, ddfname with namespace or list index"); } // We can have table name in TABLESAMPLE clause. if (table.getSampleClause() != null) { if (table.getSampleClause().getOnList() != null) { for (SelectItem selectItem : table.getSampleClause().getOnList()) { selectItem.accept(this); } } } } /** * @brief Getters and Setters. */ public Pattern getUriPattern() { return uriPattern; } public void setUriRegex(String uriRegex) { this.uriPattern = Pattern.compile(uriRegex); } public DDFManager getDdfManager() { return ddfManager; } public void setDdfManager(DDFManager ddfManager) { this.ddfManager = ddfManager; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public List<String> getUriList() { return uriList; } public void setUriList(List<String> uriList) { this.uriList = uriList; } public List<UUID> getUuidLsit() { return uuidList;} public void setUuidList(List<UUID> uuidList) {this.uuidList = uuidList;} /** * @brief This is the main function of ddf-on-x. When the user is * requesting the ddf uri, several situations exist: (1) The user wants * to access the ddf in this engine and the ddf exists, then just return * the local table name. (2) The user wants to access the ddf in this * engine but the ddf doesn't exist, then we should restore the ddf if * possbile. (3) The ddf uri indicates that the ddf is from other engine, * then we should concat other engines to get this ddf and make it a * local table. * @param ddfuri The ddf uri. * @return The local tablename. */ String handleDDFURI(String ddfuri) throws Exception { String engineName = this.ddfManager.getEngineNameOfDDF(ddfuri); if (engineName.equals(this.ddfManager.getEngineName())) { // It's in the same engine. DDF ddf = null; try { // Restore the ddf first. ddf = this.ddfManager.getOrRestoreDDFUri(ddfuri); } catch (DDFException e) { throw new Exception("ERROR: There is no ddf with uri:" + ddfuri); } return ddf.getTableName(); } else { // Transfer from the other engine. if (!uri2tbl.containsKey(ddfuri)) { DDF ddf = this.ddfManager.transfer(engineName, ddfuri); uri2tbl.put(ddfuri, ddf.getTableName()); } return uri2tbl.get(ddfuri); } } }
// modification, are permitted provided that the following conditions // are met: // provided with the distribution. // * Neither the name of the OWASP nor the names of its // contributors may be used to endorse or promote products // derived from this software without specific prior written // "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 // 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.owasp.encoder; import java.io.IOException; import java.io.Writer; import java.nio.CharBuffer; import java.nio.charset.CoderResult; /** * Encode -- fluent interface for contextual encoding. Example usage in a JSP: * * <pre> * &lt;input value="&lt;%=Encode.forHtml(value)%&gt;" /&gt; * </pre> * * <p>There are two versions of each contextual encoding method. The first * takes a {@code String} argument and returns the encoded version as a * {@code String}. The second version writes the encoded version directly * to a {@code Writer}.</p> * * <p>Please make sure to read and understand the context that the method encodes * for. Encoding for the incorrect context will likely lead to exposing a * cross-site scripting vulnerability.</p> * * @author Jeff Ichnowski */ public final class Encode { /** No instances. */ private Encode() {} public static String forHtml(String input) { return forXml(input); } /** * See {@link #forHtml(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forHtml(Writer out, String input) throws IOException { forXml(out, input); } public static String forHtmlContent(String input) { return forXmlContent(input); } /** * See {@link #forHtmlContent(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forHtmlContent(Writer out, String input) throws IOException { forXmlContent(out, input); } public static String forHtmlAttribute(String input) { return forXmlAttribute(input); } /** * See {@link #forHtmlAttribute(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forHtmlAttribute(Writer out, String input) throws IOException { forXmlAttribute(out, input); } /** * <p>Encodes for unquoted HTML attribute values. {@link * #forHtml(String)} or {@link #forHtmlAttribute(String)} should * usually be preferred over this method as quoted attributes are * XHTML compliant.</p> * * <p>When using this method, the caller is not required to * provide quotes around the attribute (since it is encoded for * such context). The caller should make sure that the attribute * value does not abut unsafe characters--and thus should usually * err on the side of including a space character after the * value.</p> * * <p>Use of this method is discouraged as quoted attributes are * generally more compatible and safer. Also note, that no * attempt has been made to optimize this encoding, though it is * still probably faster than other encoding libraries.</p> * * <b>Example JSP Usage</b> * <pre> * &lt;input value=&lt;%=Encode.forHtmlUnquotedAttribute(input)%&gt; &gt; * </pre> * * <table border="0" class="memberSummary" summary="Shows the input and results of encoding"> * <caption><b>Encoding Table</b></caption> * <thead> * <tr> * <th align="left" class="colFirst">Input</th> * <th align="left" class="colLast">Result</th> * </tr> * </thead> * <tbody> * <tr class="altColor"> * <td class="colFirst">{@code U+0009} (horizontal tab)</td> * <td class="colLast">{@code &#9;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code U+000A} (line feed)</td> * <td class="colLast">{@code &#10;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code U+000C} (form feed)</td> * <td class="colLast">{@code &#12;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code U+000D} (carriage return)</td> * <td class="colLast">{@code &#13;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code U+0020} (space)</td> * <td class="colLast">{@code &#32;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code &}</td> * <td class="colLast">{@code &amp;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code <}</td> * <td class="colLast">{@code &lt;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code >}</td> * <td class="colLast">{@code &gt;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code "}</td> * <td class="colLast">{@code &#34;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code '}</td> * <td class="colLast">{@code &#39;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code /}</td> * <td class="colLast">{@code &#47;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code =}</td> * <td class="colLast">{@code &#61;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code `}</td> * <td class="colLast">{@code &#96;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code U+0085} (next line)</td> * <td class="colLast">{@code &#133;}</td></tr> * <tr class="altColor"> * <td class="colFirst">{@code U+2028} (line separator)</td> * <td class="colLast">{@code &#8232;}</td></tr> * <tr class="rowColor"> * <td class="colFirst">{@code U+2029} (paragraph separator)</td> * <td class="colLast">{@code &#8233;}</td></tr> * </tbody> * </table> * * <p><b>Additional Notes</b></p> * <ul> * <li>The following characters are <i>not</i> encoded: * {@code 0-9, a-z, A-Z}, {@code !}, {@code * #}, {@code $}, {@code %}, * {@code (}, {@code )}, {@code * *}, {@code +}, {@code ,}, * {@code -}, {@code .}, {@code * [}, {@code \}, {@code ]}, * {@code ^}, {@code _}, {@code * }}.</li> * * <li>Surrogate pairs are passed through only if valid. Invalid * surrogate pairs are replaced by a hyphen (-).</li> * * <li>Characters in the C0 and C1 control blocks and not * otherwise listed above are considered invalid and replaced by a * hyphen (-) character.</li> * * <li>Unicode "non-characters" are replaced by hyphens (-).</li> * </ul> * * @param input the attribute value to be encoded. * @return the attribute value encoded for unquoted attribute * context. */ public static String forHtmlUnquotedAttribute(String input) { return encode(Encoders.HTML_UNQUOTED_ATTRIBUTE_ENCODER, input); } /** * See {@link #forHtmlUnquotedAttribute(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forHtmlUnquotedAttribute(Writer out, String input) throws IOException { encode(Encoders.HTML_UNQUOTED_ATTRIBUTE_ENCODER, out, input); } // HTML comment encoding is not currently supported because // of the number of vendor-specific sequences that would need // to be handled (e.g. "<!--[if IE]-->" // public static String forHtmlComment(String input) { // // only alphanumeric and space, everything else becomes a space // // HTML comment context needs to avoid browser extensions // // such as "<!--[if IE]-->" // throw new UnsupportedOperationException(); /** * Encodes for CSS strings. The context must be surrounded by quotation * characters. It is safe for use in both style blocks and attributes in * HTML. * * <b>Example JSP Usage</b> * <pre> * &lt;div style="background: url('&lt;=Encode.forCssString(...)%&gt;');"&gt; * * &lt;style type="text/css"&gt; * background: url('&lt;%=Encode.forCssString(...)%&gt;'); * &lt;/style&gt; * </pre> * * <b>Encoding Notes</b> * <ul> * * <li>The following characters are encoded using hexidecimal * encodings: {@code U+0000} - {@code U+001f}, * {@code "}, * {@code '}, * {@code \}, * {@code <}, * {@code &}, * {@code (}, * {@code )}, * {@code /}, * {@code >}, * {@code U+007f}, * line separator ({@code U+2028}), * paragraph separator ({@code U+2029}).</li> * * <li>Any character requiring encoding is encoded as {@code \xxx} * where {@code xxx} is the shortest hexidecimal representation of * its Unicode code point (after decoding surrogate pairs if * necessary). This encoding is never zero padded. Thus, for * example, the tab character is encoded as {@code \9}, not {@code * \0009}.</li> * * <li>The encoder looks ahead 1 character in the input and * appends a space to an encoding to avoid the next character * becoming part of the hexidecimal encoded sequence. Thus * &ldquo;{@code '1}&rdquo; is encoded as &ldquo;{@code \27 * 1}&rdquo;, and not as &ldquo;{@code \271}&rdquo;. If a space * is not necessary, it is not included, thus &ldquo;{@code * 'x}&rdquo; is encoded as &ldquo;{@code \27x}&rdquo;, and not as * &ldquo;{@code \27 x}&rdquo;.</li> * * <li>Surrogate pairs are passed through only if valid. Invalid * surrogate pairs are replaced by an underscore (_).</li> * * <li>Unicode "non-characters" are replaced by underscores (_).</li> * * </ul> * * @param input the input to encode * @return the encoded result */ public static String forCssString(String input) { // need to watch out for CSS expressions return encode(Encoders.CSS_STRING_ENCODER, input); } /** * See {@link #forCssString(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forCssString(Writer out, String input) throws IOException { encode(Encoders.CSS_STRING_ENCODER, out, input); } /** * Encodes for CSS URL contexts. The context must be surrounded by {@code "url("} * and {@code ")"}. It is safe for use in both style blocks and attributes in HTML. * Note: this does not do any checking on the quality or safety of the URL * itself. The caller should insure that the URL is safe for embedding * (e.g. input validation) by other means. * * <b>Example JSP Usage</b> * <pre> * &lt;div style="background:url(&lt;=Encode.forCssUrl(...)%&gt;);"&gt; * * &lt;style type="text/css"&gt; * background: url(&lt;%=Encode.forCssUrl(...)%&gt;); * &lt;/style&gt; * </pre> * <b>Encoding Notes</b> * <ul> * * <li>The following characters are encoded using hexidecimal * encodings: {@code U+0000} - {@code U+001f}, * {@code "}, * {@code '}, * {@code \}, * {@code <}, * {@code &}, * {@code /}, * {@code >}, * {@code U+007f}, * line separator ({@code U+2028}), * paragraph separator ({@code U+2029}).</li> * * <li>Any character requiring encoding is encoded as {@code \xxx} * where {@code xxx} is the shortest hexidecimal representation of * its Unicode code point (after decoding surrogate pairs if * necessary). This encoding is never zero padded. Thus, for * example, the tab character is encoded as {@code \9}, not {@code * \0009}.</li> * * <li>The encoder looks ahead 1 character in the input and * appends a space to an encoding to avoid the next character * becoming part of the hexidecimal encoded sequence. Thus * &ldquo;{@code '1}&rdquo; is encoded as &ldquo;{@code \27 * 1}&rdquo;, and not as &ldquo;{@code \271}&rdquo;. If a space * is not necessary, it is not included, thus &ldquo;{@code * 'x}&rdquo; is encoded as &ldquo;{@code \27x}&rdquo;, and not as * &ldquo;{@code \27 x}&rdquo;.</li> * * <li>Surrogate pairs are passed through only if valid. Invalid * surrogate pairs are replaced by an underscore (_).</li> * * <li>Unicode "non-characters" are replaced by underscores (_).</li> * * </ul> * * @param input the input to encode * @return the encoded result */ public static String forCssUrl(String input) { return encode(Encoders.CSS_URL_ENCODER, input); } /** * See {@link #forCssUrl(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forCssUrl(Writer out, String input) throws IOException { encode(Encoders.CSS_URL_ENCODER, out, input); } /** * <p>Performs percent-encoding of a URL according to RFC 3986. The provided * URL is assumed to a valid URL. This method does not do any checking on * the quality or safety of the URL itself. In many applications it may * be better to use {@link java.net.URI} instead. Note: this is a * particularly dangerous context to put untrusted content in, as for * example a "javascript:" URL provided by a malicious user would be * "properly" escaped, and still execute.</p> * * <b>Encoding Table</b> * <p>The following characters are <i>not</i> encoded:</p> * <pre> * U+20: ! # $ &amp; ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; = ? * U+40: @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ ] _ * U+60: a b c d e f g h i j k l m n o p q r s t u v w x y z ~ * </pre> * * <b>Encoding Notes</b> * <ul> * * <li>The single-quote character({@code '}) <b>is not encoded</b>.</li> * * <li>This encoding is not intended to be used standalone. The * output should be encoded to the target context. For example: * {@code <a * href="<%=Encode.forHtmlAttribute(Encode.forUri(uri))%>">...</a>}. * (Note, the single-quote character ({@code '}) is not * encoded.)</li> * * <li>URL encoding is an encoding for bytes, not unicode. The * input string is thus first encoded as a sequence of UTF-8 * byte. The bytes are then encoded as {@code %xx} where {@code * xx} is the two-digit hexidecimal representation of the * byte. (The implementation does this as one step for * performance.)</li> * * <li>Surrogate pairs are first decoded to a Unicode code point * before encoding as UTF-8.</li> * * <li>Invalid characters (e.g. partial or invalid surrogate * pairs), are replaced with a hyphen ({@code -}) character.</li> * * </ul> * * @param input the input to encode * @return the encoded result */ @Deprecated public static String forUri(String input) { return encode(Encoders.URI_ENCODER, input); } /** * See {@link #forUri(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer * * @deprecated There is never a need to encode a complete URI with this form of encoding. */ @Deprecated public static void forUri(Writer out, String input) throws IOException { encode(Encoders.URI_ENCODER, out, input); } public static String forUriComponent(String input) { return encode(Encoders.URI_COMPONENT_ENCODER, input); } /** * See {@link #forUriComponent(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forUriComponent(Writer out, String input) throws IOException { encode(Encoders.URI_COMPONENT_ENCODER, out, input); } /** * Encoder for XML and XHTML. See {@link #forHtml(String)} for a * description of the encoding and context. * * @see #forHtml(String) * @param input the input to encode * @return the encoded result */ public static String forXml(String input) { return encode(Encoders.XML_ENCODER, input); } /** * See {@link #forXml(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forXml(Writer out, String input) throws IOException { encode(Encoders.XML_ENCODER, out, input); } /** * Encoder for XML and XHTML text content. See {@link * #forHtmlContent(String)} for description of encoding and * context. * * @see #forHtmlContent(String) * @param input the input to encode * @return the encoded result */ public static String forXmlContent(String input) { return encode(Encoders.XML_CONTENT_ENCODER, input); } /** * See {@link #forXmlContent(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forXmlContent(Writer out, String input) throws IOException { encode(Encoders.XML_CONTENT_ENCODER, out, input); } /** * Encoder for XML and XHTML attribute content. See {@link * #forHtmlAttribute(String)} for description of encoding and * context. * * @see #forHtmlAttribute(String) * @param input the input to encode * @return the encoded result */ public static String forXmlAttribute(String input) { return encode(Encoders.XML_ATTRIBUTE_ENCODER, input); } /** * See {@link #forXmlAttribute(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forXmlAttribute(Writer out, String input) throws IOException { encode(Encoders.XML_ATTRIBUTE_ENCODER, out, input); } /** * Encoder for XML comments. <strong>NOT FOR USE WITH * (X)HTML CONTEXTS.</strong> (X)HTML comments may be interpreted by * browsers as something other than a comment, typically in vendor * specific extensions (e.g. {@code <--if[IE]-->}). * For (X)HTML it is recommend that unsafe content never be included * in a comment. * * <p>The caller must provide the comment start and end sequences.</p> * * <p>This method replaces all invalid XML characters with spaces, * and replaces the "--" sequence (which is invalid in XML comments) * with "-~" (hyphen-tilde). <b>This encoding behavior may change * in future releases.</b> If the comments need to be decoded, the * caller will need to come up with their own encode/decode system.</p> * * <pre> * out.println("&lt;?xml version='1.0'?&gt;"); * out.println("&lt;data&gt;"); * out.println("&lt;!-- "+Encode.forXmlComment(comment)+" --&gt;"); * out.println("&lt;/data&gt;"); * </pre> * * @param input the input to encode * @return the encoded result */ public static String forXmlComment(String input) { return encode(Encoders.XML_COMMENT_ENCODER, input); } /** * See {@link #forXmlComment(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forXmlComment(Writer out, String input) throws IOException { encode(Encoders.XML_COMMENT_ENCODER, out, input); } /** * Encodes data for an XML CDATA section. On the chance that the input * contains a terminating {@code "]]>"}, it will be replaced by * {@code "]]>]]<![CDATA[>"}. * As with all XML contexts, characters that are invalid according to the * XML specification will be replaced by a space character. Caller must * provide the CDATA section boundaries. * * <pre> * &lt;xml-data&gt;&lt;![CDATA[&lt;%=Encode.forCDATA(...)%&gt;]]&gt;&lt;/xml-data&gt; * </pre> * * @param input the input to encode * @return the encoded result */ public static String forCDATA(String input) { return encode(Encoders.CDATA_ENCODER, input); } /** * See {@link #forCDATA(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forCDATA(Writer out, String input) throws IOException { encode(Encoders.CDATA_ENCODER, out, input); } /** * Encodes for a Java string. This method will use "\b", "\t", "\r", "\f", * "\n", "\"", "\'", "\\", octal and unicode escapes. Valid surrogate * pairing is not checked. The caller must provide the enclosing quotation * characters. This method is useful for when writing code generators and * outputting debug messages. * * <pre> * out.println("public class Hello {"); * out.println(" public static void main(String[] args) {"); * out.println(" System.out.println(\"" + Encode.forJava(message) + "\");"); * out.println(" }"); * out.println("}"); * </pre> * * @param input the input to encode * @return the input encoded for java strings. */ public static String forJava(String input) { return encode(Encoders.JAVA_ENCODER, input); } /** * See {@link #forJava(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forJava(Writer out, String input) throws IOException { encode(Encoders.JAVA_ENCODER, out, input); } /** * <p>Encodes for a JavaScript string. It is safe for use in HTML * script attributes (such as {@code onclick}), script * blocks, JSON files, and JavaScript source. The caller MUST * provide the surrounding quotation characters for the string. * Since this performs additional encoding so it can work in all * of the JavaScript contexts listed, it may be slightly less * efficient than using one of the methods targetted to a specific * JavaScript context ({@link #forJavaScriptAttribute(String)}, * {@link #forJavaScriptBlock}, {@link #forJavaScriptSource}). * Unless you are interested in saving a few bytes of output or * are writing a framework on top of this library, it is recommend * that you use this method over the others.</p> * * <b>Example JSP Usage:</b> * <pre> * &lt;button onclick="alert('&lt;%=Encode.forJavaScript(data)%&gt;');"&gt; * &lt;script type="text/javascript"&gt; * var data = "&lt;%=Encode.forJavaScript(data)%&gt;"; * &lt;/script&gt; * </pre> * * <table cellspacing="1" class="memberSummary" cellpadding="1" border="0"> * <caption><b>Encoding Description</b></caption> * <thead> * <tr> * <th align="left" colspan="2" class="colFirst">Input Character</th> * <th align="left" class="colLast">Encoded Result</th> * <th align="left" class="colLast">Notes</th> * </tr> * </thead> * <tbody> * <tr class="altColor"> * <td class="colFirst">U+0008</td><td><i>BS</i></td> * <td class="colLast"><code>\b</code></td> * <td class="colLast">Backspace character</td> * </tr> * <tr class="rowColor"> * <td class="colFirst">U+0009</td><td><i>HT</i></td> * <td class="colLast"><code>\t</code></td> * <td class="colLast">Horizontal tab character</td> * </tr> * <tr class="altColor"> * <td class="colFirst">U+000A</td><td><i>LF</i></td> * <td class="colLast"><code>\n</code></td> * <td class="colLast">Line feed character</td> * </tr> * <tr class="rowColor"> * <td class="colFirst">U+000C</td><td><i>FF</i></td> * <td class="colLast"><code>\f</code></td> * <td class="colLast">Form feed character</td> * </tr> * <tr class="altColor"> * <td class="colFirst">U+000D</td><td><i>CR</i></td> * <td class="colLast"><code>\r</code></td> * <td class="colLast">Carriage return character</td> * </tr> * <tr class="rowColor"> * <td class="colFirst">U+0022</td><td><code>"</code></td> * <td class="colLast"><code>\x22</code></td> * <td class="colLast">The encoding <code>\"</code> is not used here because * it is not safe for use in HTML attributes. (In HTML * attributes, it would also be correct to use * "\&amp;quot;".)</td> * </tr> * <tr class="altColor"> * <td class="colFirst">U+0026</td><td><code>&amp;</code></td> * <td class="colLast"><code>\x26</code></td> * <td class="colLast">Ampersand character</td> * </tr> * <tr class="rowColor"> * <td class="colFirst">U+0027</td><td><code>'</code></td> * <td class="colLast"><code>\x27</code></td> * <td class="colLast">The encoding <code>\'</code> is not used here because * it is not safe for use in HTML attributes. (In HTML * attributes, it would also be correct to use * "\&amp;#39;".)</td> * </tr> * <tr class="altColor"> * <td class="colFirst">U+002F</td><td><code>/</code></td> * <td class="colLast"><code>\/</code></td> * <td class="colLast">This encoding is used to avoid an input sequence * "&lt;/" from prematurely terminating a &lt;/script&gt; * block.</td> * </tr> * <tr class="rowColor"> * <td class="colFirst">U+005C</td><td><code>\</code></td> * <td class="colLast"><code>\\</code></td> * <td class="colLast"></td> * </tr> * <tr class="altColor"> * <td class="colFirst" colspan="2">U+0000&nbsp;to&nbsp;U+001F</td> * <td class="colLast"><code>\x##</code></td> * <td class="colLast">Hexadecimal encoding is used for characters in this * range that were not already mentioned in above.</td> * </tr> * </tbody> * </table> * * @param input the input string to encode * @return the input encoded for JavaScript * @see #forJavaScriptAttribute(String) * @see #forJavaScriptBlock(String) */ public static String forJavaScript(String input) { return encode(Encoders.JAVASCRIPT_ENCODER, input); } /** * See {@link #forJavaScript(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forJavaScript(Writer out, String input) throws IOException { encode(Encoders.JAVASCRIPT_ENCODER, out, input); } /** * <p>This method encodes for JavaScript strings contained within * HTML script attributes (such as {@code onclick}). It is * NOT safe for use in script blocks. The caller MUST provide the * surrounding quotation characters. This method performs the * same encode as {@link #forJavaScript(String)} with the * exception that <code>/</code> is not escaped.</p> * * <p><strong>Unless you are interested in saving a few bytes of * output or are writing a framework on top of this library, it is * recommend that you use {@link #forJavaScript(String)} over this * method.</strong></p> * * <b>Example JSP Usage:</b> * <pre> * &lt;button onclick="alert('&lt;%=Encode.forJavaScriptAttribute(data)%&gt;');"&gt; * </pre> * * @param input the input string to encode * @return the input encoded for JavaScript * @see #forJavaScript(String) * @see #forJavaScriptBlock(String) */ public static String forJavaScriptAttribute(String input) { return encode(Encoders.JAVASCRIPT_ATTRIBUTE_ENCODER, input); } /** * See {@link #forJavaScriptAttribute(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forJavaScriptAttribute(Writer out, String input) throws IOException { encode(Encoders.JAVASCRIPT_ATTRIBUTE_ENCODER, out, input); } /** * <p>This method encodes for JavaScript strings contained within * HTML script blocks. It is NOT safe for use in script * attributes (such as <code>onclick</code>). The caller must * provide the surrounding quotation characters. This method * performs the same encode as {@link #forJavaScript(String)} with * the exception that <code>"</code> and <code>'</code> are * encoded as <code>\"</code> and <code>\'</code> * respectively.</p> * * <p><strong>Unless you are interested in saving a few bytes of * output or are writing a framework on top of this library, it is * recommend that you use {@link #forJavaScript(String)} over this * method.</strong></p> * * <b>Example JSP Usage:</b> * <pre> * &lt;script type="text/javascript"&gt; * var data = "&lt;%=Encode.forJavaScriptBlock(data)%&gt;"; * &lt;/script&gt; * </pre> * * @param input the input string to encode * @return the input encoded for JavaScript * @see #forJavaScript(String) * @see #forJavaScriptAttribute(String) */ public static String forJavaScriptBlock(String input) { return encode(Encoders.JAVASCRIPT_BLOCK_ENCODER, input); } /** * See {@link #forJavaScriptBlock(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forJavaScriptBlock(Writer out, String input) throws IOException { encode(Encoders.JAVASCRIPT_BLOCK_ENCODER, out, input); } /** * <p>This method encodes for JavaScript strings contained within * a JavaScript or JSON file. <strong>This method is NOT safe for * use in ANY context embedded in HTML.</strong> The caller must * provide the surrounding quotation characters. This method * performs the same encode as {@link #forJavaScript(String)} with * the exception that <code>/</code> and <code>&amp;</code> are not * escaped and <code>"</code> and <code>'</code> are encoded as * <code>\"</code> and <code>\'</code> respectively.</p> * * <p><strong>Unless you are interested in saving a few bytes of * output or are writing a framework on top of this library, it is * recommend that you use {@link #forJavaScript(String)} over this * method.</strong></p> * * <b>Example JSP Usage:</b> * This example is serving up JavaScript source directly: * <pre> * &lt;%@page contentType="text/javascript; charset=UTF-8"%&gt; * var data = "&lt;%=Encode.forJavaScriptSource(data)%&gt;"; * </pre> * * This example is serving up JSON data (users of this use-case * are encouraged to read up on "JSON Hijacking"): * <pre> * &lt;%@page contentType="application/json; charset=UTF-8"%&gt; * &lt;% myapp.jsonHijackingPreventionMeasure(); %&gt; * {"data":"&lt;%=Encode.forJavaScriptSource(data)%&gt;"} * </pre> * * @param input the input string to encode * @return the input encoded for JavaScript * @see #forJavaScript(String) * @see #forJavaScriptAttribute(String) * @see #forJavaScriptBlock(String) */ public static String forJavaScriptSource(String input) { return encode(Encoders.JAVASCRIPT_SOURCE_ENCODER, input); } /** * See {@link #forJavaScriptSource(String)} for description of encoding. This * version writes directly to a Writer without an intervening string. * * @param out where to write encoded output * @param input the input string to encode * @throws IOException if thrown by writer */ public static void forJavaScriptSource(Writer out, String input) throws IOException { encode(Encoders.JAVASCRIPT_SOURCE_ENCODER, out, input); } // Additional? // MySQL // PostreSQL // Oracle /** * Core encoding loop shared by public methods. It first uses the * encoder to scan the input for characters that need encoding. If * no characters require encoding, the input string is returned. * Otherwise a buffer is used to encode the remainder * of the input. * * @param encoder the encoder to use * @param str the string to encode * @return the input string encoded with the provided encoder. */ static String encode(Encoder encoder, String str) { if (str == null) { // consistent with String.valueOf(...) use "null" for null. str = "null"; } // quick pass--see if we need to actually encode anything, if not // return the value unchanged. final int n = str.length(); int j = encoder.firstEncodedOffset(str, 0, n); if (j == n) { return str; } // otherwise, we need to encode. We use a buffer to avoid // excessive memory allocation for these calls. Note: this means that // an encoder implementation must NEVER call this method internally. return new Buffer().encode(encoder, str, j); } /** * Core encoding loop shared by public methods. It first uses the * encoder to scan the input for characters that need encoding. If no * characters require encoding, the input string is written directly to * the writer. Otherwise a buffer is used to encode the * remainder of the input to the buffers. This version saves a wrapping * in an String. * * @param encoder the encoder to use * @param out the writer for the encoded output * @param str the string to encode * @throws IOException if thrown by the writer */ static void encode(Encoder encoder, Writer out, String str) throws IOException { if (str == null) { // consistent with String.valueOf(...) use "null" for null. str = "null"; } // quick pass--see if we need to actually encode anything, if not // return the value unchanged. final int n = str.length(); int j = encoder.firstEncodedOffset(str, 0, n); if (j == n) { out.write(str); return; } // otherwise, we need to encode. We use a buffer to avoid // excessive memory allocation for these calls. Note: this means that // an encoder implementation must NEVER call this method internally. new Buffer().encode(encoder, out, str, j); } /** * A buffer used for encoding. */ static class Buffer { /** * Input buffer size, used to extract a copy of the input * from a string and then send to the encoder. */ static final int INPUT_BUFFER_SIZE = 1024; /** * Output buffer size used to store the encoded output before * wrapping in a string. */ static final int OUTPUT_BUFFER_SIZE = INPUT_BUFFER_SIZE * 2; /** * The input buffer. A heap-allocated, array-backed buffer of * INPUT_BUFFER_SIZE used for holding the characters to encode. */ final CharBuffer _input = CharBuffer.allocate(INPUT_BUFFER_SIZE); /** * The output buffer. A heap-allocated, array-backed buffer of * OUTPUT_BUFFER_SIZE used for holding the encoded output. */ final CharBuffer _output = CharBuffer.allocate(OUTPUT_BUFFER_SIZE); /** * The core String encoding routine of this class. It uses the input * and output buffers to allow the encoders to work in reuse arrays. * When the input and/or output exceeds the capacity of the reused * arrays, temporary ones are allocated and then discarded after * the encode is done. * * @param encoder the encoder to use * @param str the string to encode * @param j the offset in {@code str} to start encoding * @return the encoded result */ String encode(Encoder encoder, String str, int j) { final int n = str.length(); final int remaining = n - j; if (remaining <= INPUT_BUFFER_SIZE && j <= OUTPUT_BUFFER_SIZE) { // the remaining input to encode fits completely in the pre- // allocated buffer. str.getChars(0, j, _output.array(), 0); str.getChars(j, n, _input.array(), 0); _input.limit(remaining).position(0); _output.clear().position(j); CoderResult cr = encoder.encodeArrays(_input, _output, true); if (cr.isUnderflow()) { return new String(_output.array(), 0, _output.position()); } // else, it's an overflow, we need to use a new output buffer // we'll allocate this buffer to be the exact size of the worst // case, guaranteeing a second overflow would not be possible. CharBuffer tmp = CharBuffer.allocate(_output.position() + encoder.maxEncodedLength(_input.remaining())); // copy over everything that has been encoded so far tmp.put(_output.array(), 0, _output.position()); cr = encoder.encodeArrays(_input, tmp, true); if (cr.isOverflow()) { throw new AssertionError("unexpected result from encoder"); } return new String(tmp.array(), 0, tmp.position()); } else { // the input it too large for our pre-allocated buffers // we'll use a temporary direct heap allocation final int m = j + encoder.maxEncodedLength(remaining); CharBuffer buffer = CharBuffer.allocate(m); str.getChars(0, j, buffer.array(), 0); str.getChars(j, n, buffer.array(), m - remaining); CharBuffer input = buffer.duplicate(); input.limit(m).position(m-remaining); buffer.position(j); CoderResult cr = encoder.encodeArrays(input, buffer, true); if (cr.isOverflow()) { throw new AssertionError("unexpected result from encoder"); } return new String(buffer.array(), 0, buffer.position()); } } /** * The core Writer encoding routing of this class. It uses the * input and output buffers to allow the encoders to reuse arrays. * Unlike the string version, this method will never allocate more * memory, instead encoding is done in batches and flushed to the * writer in batches as large as possible. * * @param encoder the encoder to use * @param out where to write the encoded output * @param str the string to encode * @param j the position in the string at which the first character * needs encoding. * @throws IOException if thrown by the writer. */ void encode(Encoder encoder, Writer out, String str, int j) throws IOException { out.write(str, 0, j); final int n = str.length(); _input.clear(); _output.clear(); final char[] inputArray = _input.array(); final char[] outputArray = _output.array(); for (;;) { final int remainingInput = n - j; final int startPosition = _input.position(); final int batchSize = Math.min(remainingInput, _input.remaining()); str.getChars(j, j+batchSize, inputArray, startPosition); _input.limit(startPosition + batchSize); for (;;) { CoderResult cr = encoder.encodeArrays( _input, _output, batchSize == remainingInput); if (cr.isUnderflow()) { // get next input batch break; } // else, output buffer full, flush and continue. out.write(outputArray, 0, _output.position()); _output.clear(); } j += _input.position() - startPosition; if (j == n) { // done. flush remaining output buffer and return out.write(outputArray, 0, _output.position()); return; } _input.compact(); } } } }
package edu.rutgers.css.Rutgers; /** * App configuration */ public final class Config { private Config() {} // Build info public static final String APPTAG = "Rutgers-" + BuildConfig.FLAVOR; public static final String PACKAGE_NAME = BuildConfig.APPLICATION_ID; public static final String VERSION = BuildConfig.VERSION_NAME; public static final String OSNAME = "android"; public static final String BETAMODE = "dev"; public static final Boolean BETA = true; // Server and API level public static final String API_LEVEL = "1"; public static final String API_BASE = "https://nstanlee.rutgers.edu/~rfranknj/mobile/"+API_LEVEL+"/"; // Location-based services config public static final float NEARBY_RANGE = 300.0f; // Within 300 meters is considered "nearby" }
package com.ayros.historycleaner.ui; import java.io.IOException; import java.util.List; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Surface; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.ayros.historycleaner.Globals; import com.ayros.historycleaner.R; import com.ayros.historycleaner.cleaning.CategoryList; import com.ayros.historycleaner.cleaning.CleanItem; import com.ayros.historycleaner.cleaning.CleanListener; import com.ayros.historycleaner.cleaning.Cleaner; import com.ayros.historycleaner.cleaning.Cleaner.CleanResults; import com.ayros.historycleaner.cleaning.Profile; import com.ayros.historycleaner.cleaning.ProfileList; import com.ayros.historycleaner.helpers.Logger; import com.stericson.RootTools.RootTools; import com.stericson.RootTools.exceptions.RootDeniedException; import com.stericson.RootTools.execution.Shell; public class CleanFragment extends Fragment implements OnClickListener, OnProfileUpdated { protected class ConfirmOverwriteListener implements DialogInterface.OnClickListener { private String profileName; public ConfirmOverwriteListener(String profName) { profileName = profName; } public void onClick(DialogInterface dialog, int whichButton) { Profile newProf = ProfileList.create(profileName); catList.saveProfile(newProf); } } private static final String ACTION_VIEW_ITEMS = "View Items"; private CategoryList catList = null; private Profile autoCleanProfile = null; private String displayTip = null; // Life-cycle Methods public static CleanFragment newInstance() { CleanFragment fragment = new CleanFragment(); Bundle args = new Bundle(); fragment.setArguments(args); fragment.displayTip = getTip(); return fragment; } public static CleanFragment newInstance(Profile autoCleanProfile) { CleanFragment fragment = new CleanFragment(); Bundle args = new Bundle(); fragment.setArguments(args); fragment.autoCleanProfile = autoCleanProfile; return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.frag_clean, container, false); ProfileList.load(); catList = new CategoryList(); LinearLayout catView = (LinearLayout)rootView.findViewById(R.id.clean_categories); catView.addView(catList.makeCategoriesView(this.getActivity())); return rootView; } @Override public void onStart() { super.onStart(); catList.loadProfile(ProfileList.get(null)); catList.registerContextMenu(this); Button cleanButton = (Button)getView().findViewById(R.id.clean_btnClear); cleanButton.setOnClickListener(this); if (Logger.isDebugMode() || Logger.isLogToFileMode()) { if (Logger.isDebugMode()) { Toast.makeText(getActivity(), "Debug mode is on.", Toast.LENGTH_SHORT).show(); } if (Logger.isLogToFileMode()) { Toast.makeText(getActivity(), "Log-to-file mode is on.", Toast.LENGTH_SHORT).show(); } } else if (autoCleanProfile != null) { catList.loadProfile(autoCleanProfile); autoCleanProfile = null; cleanItems(catList, true); } else if (displayTip != null) { Toast.makeText(getActivity(), displayTip, Toast.LENGTH_LONG).show(); displayTip = null; } } @Override public void onPause() { super.onPause(); if (catList != null) { catList.saveProfile(ProfileList.get(null)); } } @Override public void onResume() { super.onResume(); catList.loadProfile(ProfileList.get(null)); } @Override public void onDestroy() { if (catList != null) { catList.saveProfile(ProfileList.get(null)); } try { RootTools.closeAllShells(); } catch (IOException e) { e.printStackTrace(); } super.onDestroy(); } // Other Methods @SuppressLint("InlinedApi") @SuppressWarnings("deprecation") public void cleanItems(final CategoryList categoryList, final boolean exitOnFinish) { // Lock orientation final int prevOrientation = getActivity().getRequestedOrientation(); WindowManager wm = (WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE); int REVERSE_PORTRAIT = Build.VERSION.SDK_INT >= 9 ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; int REVERSE_LANDSCAPE = Build.VERSION.SDK_INT >= 9 ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; switch (wm.getDefaultDisplay().getOrientation()) { case Surface.ROTATION_0: getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case Surface.ROTATION_90: getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case Surface.ROTATION_180: getActivity().setRequestedOrientation(REVERSE_PORTRAIT); break; default: getActivity().setRequestedOrientation(REVERSE_LANDSCAPE); } if (categoryList.getAllItems(true).size() == 0) { Toast.makeText(getActivity(), "Please select at least one item to clear!", Toast.LENGTH_LONG).show(); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } Cleaner itemCleaner = new Cleaner(categoryList.getAllItems(true)); if (itemCleaner.isRootRequired()) { if (!RootTools.isRootAvailable()) { Toast.makeText(getActivity(), "Error: This app requires root access", Toast.LENGTH_LONG).show(); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } if (!Shell.isRootShellOpen()) { try { Shell.startRootShell(); } catch (RootDeniedException rde) { Toast.makeText(getActivity(), "Error: Could not obtain root access! This app requires root!", Toast.LENGTH_LONG).show(); Logger.errorST("Root access denied", rde); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } catch (Exception e) { Toast.makeText(getActivity(), "Error: There was a problem when trying to gain root access", Toast.LENGTH_LONG).show(); Logger.errorST("Problem starting root shell", e); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } } } final ProgressDialog pd = new ProgressDialog(getActivity()); pd.setTitle("Clearing History..."); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setIndeterminate(false); pd.setMax(categoryList.getAllItems(true).size()); pd.setCancelable(false); pd.setCanceledOnTouchOutside(false); pd.show(); itemCleaner.cleanAsync(getActivity(), new CleanListener() { @Override public void progressChanged(Cleaner.CleanProgressEvent cpe) { pd.setMessage("Cleaning " + cpe.item.getUniqueName()); pd.setProgress(cpe.itemIndex + 1); } @Override public void cleaningComplete(CleanResults results) { pd.cancel(); final AlertDialog.Builder resultsDialog = new AlertDialog.Builder(getActivity()); resultsDialog.setTitle("Cleaning Results"); resultsDialog.setMessage(results.toString()); resultsDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } } }); resultsDialog.show(); try { RootTools.closeAllShells(); } catch (IOException e) { e.printStackTrace(); } } }); } public static String getTip() { String[] tips = new String[] { "TIP: Long pressing on an item will allow you to view the data to be cleared", "TIP: Is there an application you wished was supported? Leave us a message and we'll see if we can add it!", "TIP: You can add shortcuts on your homescreen so you can clear your history in one click" }; return tips[(int)(Math.random() * tips.length)]; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_clean, menu); } @Override public void onClick(View v) { cleanItems(catList, false); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getTitle().equals(ACTION_VIEW_ITEMS)) { int itemId = item.getItemId(); CleanItem ci = catList.getItemByUniqueId(itemId); if (ci != null) { Globals.itemDataView = ci; Intent intent = new Intent(getActivity(), DataViewActivity.class); startActivity(intent); return true; } } return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { int id = catList.getItemByView(v).getUniqueId(); super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Actions"); menu.add(ContextMenu.NONE, id, 0, ACTION_VIEW_ITEMS); } @Override public boolean onOptionsItemSelected(MenuItem item) { List<CleanItem> items; switch (item.getItemId()) { case R.id.clean_menu_save_as_profile: showSaveProfileDialog(); return true; case R.id.clean_menu_select_all: items = catList.getAllItems(false); for (CleanItem ci : items) { // Only check item if there is no warning message (don't accidently clean something sensitive) if (ci.getWarningMessage() == null) { ci.setChecked(true); } } return true; case R.id.clean_menu_select_none: items = catList.getAllItems(false); for (CleanItem ci : items) { ci.setChecked(false); } return true; } return super.onOptionsItemSelected(item); } @Override public void onProfileUpdated() { catList.loadProfile(ProfileList.get(null)); } public void showSaveProfileDialog() { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Save Profile"); alert.setMessage("Enter a name for the profile to be saved to."); // Set an EditText view to get user input final EditText input = new EditText(getActivity()); if (Globals.saveProfileText != null) { input.setText(Globals.saveProfileText); } alert.setView(input); alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String newName = input.getText().toString().trim(); if (newName.length() == 0) { Toast.makeText(getActivity(), "Error: You must enter a name for a new profile!", Toast.LENGTH_LONG).show(); } else if (ProfileList.get(newName) != null) { AlertDialog.Builder confirmOverwrite = new AlertDialog.Builder(getActivity()); confirmOverwrite.setTitle("Overwrite?"); confirmOverwrite.setMessage("A profile with this name already exists, do you want to overwrite it?"); confirmOverwrite.setPositiveButton(android.R.string.yes, new ConfirmOverwriteListener(newName)); confirmOverwrite.setNegativeButton(android.R.string.no, null); confirmOverwrite.show(); } else { Profile newProf = ProfileList.create(newName); catList.saveProfile(newProf); ((OnProfileUpdated)getActivity()).onProfileUpdated(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } }
package com.ayros.historycleaner.ui; import java.io.IOException; import java.util.List; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Surface; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.ayros.historycleaner.Globals; import com.ayros.historycleaner.R; import com.ayros.historycleaner.cleaning.CategoryList; import com.ayros.historycleaner.cleaning.CleanItem; import com.ayros.historycleaner.cleaning.CleanListener; import com.ayros.historycleaner.cleaning.Cleaner; import com.ayros.historycleaner.cleaning.Cleaner.CleanResults; import com.ayros.historycleaner.cleaning.Profile; import com.ayros.historycleaner.cleaning.ProfileList; import com.ayros.historycleaner.helpers.Logger; import com.stericson.RootTools.RootTools; import com.stericson.RootTools.exceptions.RootDeniedException; import com.stericson.RootTools.execution.Shell; public class CleanFragment extends Fragment implements OnClickListener, OnProfileUpdated { protected class ConfirmOverwriteListener implements DialogInterface.OnClickListener { private String profileName; public ConfirmOverwriteListener(String profName) { profileName = profName; } public void onClick(DialogInterface dialog, int whichButton) { Profile newProf = ProfileList.create(profileName); catList.saveProfile(newProf); } } private static final String ACTION_VIEW_ITEMS = "View Items"; private CategoryList catList = null; private Profile autoCleanProfile = null; private String displayTip = null; // Life-cycle Methods public static CleanFragment newInstance() { CleanFragment fragment = new CleanFragment(); Bundle args = new Bundle(); fragment.setArguments(args); fragment.displayTip = getTip(); return fragment; } public static CleanFragment newInstance(Profile autoCleanProfile) { CleanFragment fragment = new CleanFragment(); Bundle args = new Bundle(); fragment.setArguments(args); fragment.autoCleanProfile = autoCleanProfile; return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.frag_clean, container, false); ProfileList.load(); catList = new CategoryList(); LinearLayout catView = (LinearLayout)rootView.findViewById(R.id.clean_categories); catView.addView(catList.makeCategoriesView(this.getActivity())); return rootView; } @Override public void onStart() { super.onStart(); catList.loadProfile(ProfileList.get(null)); catList.registerContextMenu(this); Button cleanButton = (Button)getView().findViewById(R.id.clean_btnClear); cleanButton.setOnClickListener(this); if (Logger.isDebugMode() || Logger.isLogToFileMode()) { if (Logger.isDebugMode()) { Toast.makeText(getActivity(), "Debug mode is on.", Toast.LENGTH_SHORT).show(); } if (Logger.isLogToFileMode()) { Toast.makeText(getActivity(), "Log-to-file mode is on.", Toast.LENGTH_SHORT).show(); } } else if (autoCleanProfile != null) { catList.loadProfile(autoCleanProfile); autoCleanProfile = null; cleanItems(catList, true); } else if (displayTip != null) { Toast.makeText(getActivity(), displayTip, Toast.LENGTH_LONG).show(); displayTip = null; } } @Override public void onPause() { super.onPause(); if (catList != null) { catList.saveProfile(ProfileList.get(null)); } } @Override public void onResume() { super.onResume(); catList.loadProfile(ProfileList.get(null)); } @Override public void onDestroy() { if (catList != null) { catList.saveProfile(ProfileList.get(null)); } try { RootTools.closeAllShells(); } catch (IOException e) { e.printStackTrace(); } super.onDestroy(); } // Other Methods @SuppressLint("InlinedApi") @SuppressWarnings("deprecation") public void cleanItems(final CategoryList categoryList, final boolean exitOnFinish) { // Lock orientation final int prevOrientation = getActivity().getRequestedOrientation(); WindowManager wm = (WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE); int REVERSE_PORTRAIT = Build.VERSION.SDK_INT >= 9 ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; int REVERSE_LANDSCAPE = Build.VERSION.SDK_INT >= 9 ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; switch (wm.getDefaultDisplay().getOrientation()) { case Surface.ROTATION_0: getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case Surface.ROTATION_90: getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case Surface.ROTATION_180: getActivity().setRequestedOrientation(REVERSE_PORTRAIT); break; default: getActivity().setRequestedOrientation(REVERSE_LANDSCAPE); } if (categoryList.getAllItems(true).size() == 0) { Toast.makeText(getActivity(), "Please select at least one item to clear!", Toast.LENGTH_LONG).show(); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } Cleaner itemCleaner = new Cleaner(categoryList.getAllItems(true)); if (itemCleaner.isRootRequired()) { if (!RootTools.isRootAvailable()) { Toast.makeText(getActivity(), "Error: This app requires root access", Toast.LENGTH_LONG).show(); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } if (!Shell.isRootShellOpen()) { try { Shell.startRootShell(); } catch (RootDeniedException rde) { Toast.makeText(getActivity(), "Error: Could not obtain root access! This app requires root!", Toast.LENGTH_LONG).show(); Logger.errorST("Root access denied", rde); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } catch (Exception e) { Toast.makeText(getActivity(), "Error: There was a problem when trying to gain root access", Toast.LENGTH_LONG).show(); Logger.errorST("Problem starting root shell", e); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } return; } } } final ProgressDialog pd = new ProgressDialog(getActivity()); pd.setTitle("Clearing History..."); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setIndeterminate(false); pd.setMax(categoryList.getAllItems(true).size()); pd.setCancelable(false); pd.setCanceledOnTouchOutside(false); pd.show(); itemCleaner.cleanAsync(getActivity(), new CleanListener() { @Override public void progressChanged(Cleaner.CleanProgressEvent cpe) { pd.setMessage("Cleaning " + cpe.item.getUniqueName()); pd.setProgress(cpe.itemIndex + 1); } @Override public void cleaningComplete(CleanResults results) { try { pd.cancel(); } catch (Exception e) { Logger.errorST("Problem closing progress dialog upon cleaning completion", e); } final AlertDialog.Builder resultsDialog = new AlertDialog.Builder(getActivity()); resultsDialog.setTitle("Cleaning Results"); resultsDialog.setMessage(results.toString()); resultsDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); if (exitOnFinish) { getActivity().finish(); } else { getActivity().setRequestedOrientation(prevOrientation); } } }); resultsDialog.show(); try { RootTools.closeAllShells(); } catch (IOException e) { e.printStackTrace(); } } }); } public static String getTip() { String[] tips = new String[] { "TIP: Long pressing on an item will allow you to view the data to be cleared", "TIP: Is there an application you wished was supported? Leave us a message and we'll see if we can add it!", "TIP: You can add shortcuts on your homescreen so you can clear your history in one click" }; return tips[(int)(Math.random() * tips.length)]; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_clean, menu); } @Override public void onClick(View v) { cleanItems(catList, false); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getTitle().equals(ACTION_VIEW_ITEMS)) { int itemId = item.getItemId(); CleanItem ci = catList.getItemByUniqueId(itemId); if (ci != null) { Globals.itemDataView = ci; Intent intent = new Intent(getActivity(), DataViewActivity.class); startActivity(intent); return true; } } return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { int id = catList.getItemByView(v).getUniqueId(); super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Actions"); menu.add(ContextMenu.NONE, id, 0, ACTION_VIEW_ITEMS); } @Override public boolean onOptionsItemSelected(MenuItem item) { List<CleanItem> items; switch (item.getItemId()) { case R.id.clean_menu_save_as_profile: showSaveProfileDialog(); return true; case R.id.clean_menu_select_all: items = catList.getAllItems(false); for (CleanItem ci : items) { // Only check item if there is no warning message (don't accidently clean something sensitive) if (ci.getWarningMessage() == null) { ci.setChecked(true); } } return true; case R.id.clean_menu_select_none: items = catList.getAllItems(false); for (CleanItem ci : items) { ci.setChecked(false); } return true; } return super.onOptionsItemSelected(item); } @Override public void onProfileUpdated() { catList.loadProfile(ProfileList.get(null)); } public void showSaveProfileDialog() { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Save Profile"); alert.setMessage("Enter a name for the profile to be saved to."); // Set an EditText view to get user input final EditText input = new EditText(getActivity()); if (Globals.saveProfileText != null) { input.setText(Globals.saveProfileText); } alert.setView(input); alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String newName = input.getText().toString().trim(); if (newName.length() == 0) { Toast.makeText(getActivity(), "Error: You must enter a name for a new profile!", Toast.LENGTH_LONG).show(); } else if (ProfileList.get(newName) != null) { AlertDialog.Builder confirmOverwrite = new AlertDialog.Builder(getActivity()); confirmOverwrite.setTitle("Overwrite?"); confirmOverwrite.setMessage("A profile with this name already exists, do you want to overwrite it?"); confirmOverwrite.setPositiveButton(android.R.string.yes, new ConfirmOverwriteListener(newName)); confirmOverwrite.setNegativeButton(android.R.string.no, null); confirmOverwrite.show(); } else { Profile newProf = ProfileList.create(newName); catList.saveProfile(newProf); ((OnProfileUpdated)getActivity()).onProfileUpdated(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } }
package activities; import android.animation.LayoutTransition; import android.app.ActionBar; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import com.tutos.android.ui.R; public class LoginDisplayActivity extends Activity { final String EXTRA_LOGIN = "user_login"; final String EXTRA_PASSWORD = "user_password"; int test=9; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_display); Intent intent = getIntent(); TextView loginDisplay = (TextView) findViewById(R.id.email_display); TextView passwordDisplay = (TextView) findViewById(R.id.password_display); if (intent != null) { loginDisplay.setText(intent.getStringExtra(EXTRA_LOGIN)); passwordDisplay.setText(intent.getStringExtra(EXTRA_PASSWORD)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.login_display, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: // Comportement du bouton "Recherche" return true; default: return super.onOptionsItemSelected(item); } } }
package app.iamin.iamin.ui; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.squareup.otto.Subscribe; import java.util.List; import app.iamin.iamin.R; import app.iamin.iamin.data.BusProvider; import app.iamin.iamin.data.PullAppointmentsTask; import app.iamin.iamin.data.PullVolunteeringsTask; import app.iamin.iamin.data.event.VolunteeringsEvent; import app.iamin.iamin.data.model.Need; import app.iamin.iamin.data.model.User; import app.iamin.iamin.util.EndpointUtils; import app.iamin.iamin.util.UiUtils; import io.realm.Realm; import io.realm.RealmResults; public class UserActivity extends AppCompatActivity { private NeedsRecyclerView mNeedsView; private RecyclerView.LayoutManager mLayoutManager; private NeedsAdapter mAdapter; private ImageButton mRetryButton; private ProgressBar mProgressBar; private TextView mEmptyTextView; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); User user = EndpointUtils.getUser(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(""); actionBar.setDisplayHomeAsUpEnabled(true); } mAdapter = new NeedsAdapter(this); mLayoutManager = new LinearLayoutManager(this); realm = Realm.getInstance(this); RealmResults<Need> needs = realm.where(Need.class).equalTo("isAttending", true).findAll(); mAdapter.setData(needs); RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST); mNeedsView = (NeedsRecyclerView) findViewById(R.id.recycler_view); mNeedsView.setLayoutManager(mLayoutManager); mNeedsView.setEmptyView(findViewById(R.id.empty_view)); mNeedsView.addItemDecoration(itemDecoration); mNeedsView.setAdapter(mAdapter); mRetryButton = (ImageButton) findViewById(R.id.retry_button); mProgressBar = (ProgressBar) findViewById(R.id.progress_bar); mEmptyTextView = (TextView) findViewById(R.id.empty_message); TextView titleTextView = (TextView) findViewById(R.id.header_title); titleTextView.setText(user.getFirstName()); } public void onRetry(View v) { mRetryButton.setEnabled(false); mRetryButton.setVisibility(View.GONE); mProgressBar.setVisibility(View.VISIBLE); new PullAppointmentsTask(this).execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_user, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.action_settings: UiUtils.fireSettingsIntent(UserActivity.this); overridePendingTransition(R.anim.enter_left, R.anim.leave_right); return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); BusProvider.getInstance().register(this); new PullVolunteeringsTask(this).execute(); } @Subscribe public void onVolunteeringsUpdate(VolunteeringsEvent event) { List<String> errors = event.getErrors(); if (errors == null) { RealmResults<Need> needs = realm.where(Need.class).equalTo("isAttending", true).findAll(); if (needs.size() == 0) { mProgressBar.setVisibility(View.GONE); mEmptyTextView.setVisibility(View.VISIBLE); } else { mAdapter.setData(needs); } } else { mProgressBar.setVisibility(View.GONE); mRetryButton.setVisibility(View.VISIBLE); mRetryButton.setEnabled(true); } } @Override public void onPause() { super.onPause(); BusProvider.getInstance().unregister(this); } @Override protected void onDestroy() { super.onDestroy(); realm.close(); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.enter_right, R.anim.leave_left); } }
package bg.nijel.xswiftkey; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.util.DisplayMetrics; import android.view.View; import android.widget.BaseAdapter; import java.io.File; import java.io.FileInputStream; import java.util.Arrays; import java.util.List; import de.robv.android.xposed.IXposedHookInitPackageResources; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.IXposedHookZygoteInit; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.callbacks.XC_InitPackageResources; import de.robv.android.xposed.callbacks.XC_LoadPackage; import static de.robv.android.xposed.XposedHelpers.callMethod; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findClass; import static de.robv.android.xposed.XposedHelpers.getIntField; import static de.robv.android.xposed.XposedHelpers.getObjectField; public class XSwiftkeyMod implements IXposedHookInitPackageResources, IXposedHookLoadPackage, IXposedHookZygoteInit { private static String MY_PACKAGE_NAME; private String selectedThemeId; private static XSharedPreferences myPrefs; private static String scrDensityFolder; private int count; @Override public void initZygote(IXposedHookZygoteInit.StartupParam startupParam) throws Throwable { MY_PACKAGE_NAME = XSwiftkeyMod.class.getPackage().getName(); loadPrefs(); } @Override public void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam) throws Throwable { if (resparam.packageName.contains("com.touchtype.swiftkey")) { try {
package com.abhi.fyberdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.abhi.fyberdemo.fragments.FormFragment; import com.abhi.fyberdemo.fragments.OffersFragment; import com.abhi.fyberdemo.listeners.FragmentListener; import com.abhi.fyberdemo.models.OfferResponse; import com.abhi.fyberdemo.utilities.FiberController; import com.noob.lumberjack.LogLevel; import com.noob.lumberjack.LumberJack; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements FragmentListener{ FormFragment mFormFragment; OffersFragment mOffersFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); if(!BuildConfig.DEBUG){ LumberJack.setLogLevel(LogLevel.None); } FiberController.getInstance().init(this); showFormFragment(); } public void showFormFragment() { if (mFormFragment == null) { mFormFragment = FormFragment.newInstance(this); } getSupportFragmentManager() .beginTransaction() .replace(R.id.frag_container, mFormFragment) .commit(); } public void showOffersFragment(OfferResponse offerResponse) { if (mOffersFragment == null) { mOffersFragment = OffersFragment.newInstance(this, offerResponse); } getSupportFragmentManager() .beginTransaction() .replace(R.id.frag_container, mOffersFragment) .addToBackStack(null) .commit(); } @Override public void onOfferReceived(OfferResponse response) { showOffersFragment(response); } }
package com.estore.pojo; import java.util.Map; public class InsertOrderBean { Integer estoreId; public Integer getEstoreId() { return estoreId; } public void setEstoreId(Integer estoreId) { this.estoreId = estoreId; } Integer userId; Integer addressId; double totalPrice; Map<Product.Products, Integer> details; public Integer getUserId() { return userId; } public InsertOrderBean(){ } public InsertOrderBean(Integer userId, Integer addressId, double totalPrice, Map<Product.Products, Integer> details) { super(); this.userId = userId; this.addressId = addressId; this.totalPrice = totalPrice; this.details = details; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getAddressId() { return addressId; } public void setAddressId(Integer addressId) { this.addressId = addressId; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public Map<Product.Products, Integer> getDetails() { return details; } public void setDetails(Map<Product.Products, Integer> details) { this.details = details; } }
package com.kickstarter.models; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import com.kickstarter.R; import com.kickstarter.libs.KSColorUtils; import com.kickstarter.libs.ViewUtils; import com.kickstarter.libs.qualifiers.AutoGson; import auto.parcel.AutoParcel; @AutoParcel @AutoGson abstract public class Category implements Parcelable { public abstract int color(); public abstract long id(); public abstract String name(); @Nullable public abstract Category parent(); @Nullable public abstract Long parentId(); public abstract int position(); @Nullable public abstract Integer projectsCount(); public abstract String slug(); @AutoParcel.Builder public abstract static class Builder { public abstract Builder color(int __); public abstract Builder id(long __); public abstract Builder name(String __); public abstract Builder parent(Category __); public abstract Builder parentId(Long __); public abstract Builder position(int __); public abstract Builder projectsCount(Integer __); public abstract Builder slug(String __); public abstract Category build(); } public static Builder builder() { return new AutoParcel_Category.Builder(); } public abstract Builder toBuilder(); public String baseImageName() { switch ((int) rootId()) { case 1: return "art"; case 3: return "comics"; case 26: return "crafts"; case 6: return "dance"; case 7: return "design"; case 9: return "fashion"; case 11: return "film"; case 10: return "food"; case 12: return "games"; case 13: return "journalism"; case 14: return "music"; case 15: return "photography"; case 18: return "publishing"; case 16: return "technology"; case 17: return "theater"; default: return null; } } public @ColorInt int colorWithAlpha() { return KSColorUtils.setAlpha(color(), 255); } public int discoveryFilterCompareTo(@NonNull final Category other) { if (id() == other.id()) { return 0; } if (isRoot() && id() == other.rootId()) { return -1; } else if (!isRoot() && rootId() == other.id()) { return 1; } return root().name().compareTo(other.root().name()); } public @Nullable Drawable imageWithOrientation(final Context context, final int orientation) { final String baseImageName = baseImageName(); if (baseImageName == null) { return null; } final String name = "category_" + baseImageName + "_" + (ViewUtils.isPortrait(context) ? "portrait" : "landscape"); final @DrawableRes int identifier = context.getResources().getIdentifier(name, "drawable", context.getPackageName()); if (identifier == 0) { return null; } return ContextCompat.getDrawable(context, identifier); } public boolean isRoot() { return parentId() == null || parentId() == 0; } public Category root() { return isRoot() ? this : parent(); } public long rootId() { return isRoot() ? id() : parentId(); } public int secondaryColor(@NonNull final Context context) { final int identifier; switch ((int) rootId()) { case 1: identifier = R.color.category_secondary_art; break; case 3: identifier = R.color.category_secondary_comics; break; case 26: identifier = R.color.category_secondary_crafts; break; case 6: identifier = R.color.category_secondary_dance; break; case 7: identifier = R.color.category_secondary_design; break; case 9: identifier = R.color.category_secondary_fashion; break; case 11: identifier = R.color.category_secondary_film; break; case 10: identifier = R.color.category_secondary_food; break; case 12: identifier = R.color.category_secondary_games; break; case 13: identifier = R.color.category_secondary_journalism; break; case 14: identifier = R.color.category_secondary_music; break; case 15: identifier = R.color.category_secondary_photography; break; case 18: identifier = R.color.category_secondary_publishing; break; case 16: identifier = R.color.category_secondary_technology; break; case 17: identifier = R.color.category_secondary_theater; break; default: identifier = R.color.white; break; } return context.getResources().getColor(identifier); } public boolean overlayShouldBeDark() { switch ((int) rootId()) { case 1: case 3: case 14: case 15: case 18: return true; default: return false; } } public boolean overlayShouldBeLight() { return !overlayShouldBeDark(); } }
package com.sgwares.android.models; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.Exclude; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.IgnoreExtraProperties; import com.google.firebase.database.ServerValue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @IgnoreExtraProperties public class Game { public static final int SPACING = 200; private static final String TAG = Game.class.getSimpleName(); private static final int DOT_SIZE = 6; private String key; private List<Move> moves; private boolean finished; private boolean open; private String background; private Object createdAt; public Game() { this.moves = new CopyOnWriteArrayList<>(); this.createdAt = ServerValue.TIMESTAMP; } @Exclude public String getKey() { return key; } @Exclude public void setKey(String key) { this.key = key; } @Exclude public List<Move> getMoves() { return moves; } @Exclude public void setMoves(List<Move> moves) { this.moves = moves; } public boolean isFinished() { return finished; } public void setFinished(boolean finished) { this.finished = finished; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public String getBackground() { return background; } public void setBackground(String background) { this.background = background; } public void setCreatedAt(Object createdAt) { this.createdAt = createdAt; } public Object getCreatedAt() { return createdAt; } @Exclude public void addMove(Move move) { FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference movesRef = database.getReference("moves").child(getKey()); DatabaseReference moveRef = movesRef.push(); move.setKey(moveRef.getKey()); if (isWinningMove(move)) { //TODO Move to awardPoints and only keep game points on /participants and global points on /users User user = move.getUser(); int points = user.getPoints() + 1; user.setPoints(points); Log.d(TAG, "Winning move - awarding " + points + " points to " + user); // Update /users DatabaseReference userRef = database.getReference("users").child(user.getKey()); userRef.setValue(user); // Update /participants DatabaseReference ref = database.getReference("participants").child(getKey()).child(user.getKey()).child("points"); ref.setValue(points); } moveRef.setValue(move); } @Exclude public void draw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.WHITE); // Draw Background canvas.drawColor(Color.parseColor(getBackground())); // Draw dots for (int x = 0; x < canvas.getWidth(); x = x + SPACING) { for (int y = 0; y < canvas.getHeight(); y = y + SPACING) { canvas.drawCircle(x, y, DOT_SIZE, paint); } } // Draw moves Paint winningPaint = new Paint(); winningPaint.setStyle(Paint.Style.FILL); for (Move move : getMoves()) { move.draw(canvas); // Draw the users box if this is a winning move if (isWinningMove(move)) { winningPaint.setColor(Color.parseColor(move.getUser().getColour())); Rect rect = new Rect((move.getX() * SPACING), (move.getY() * SPACING), (move.getX() * SPACING) + SPACING, (move.getY() * SPACING) + SPACING); canvas.drawRect(rect, winningPaint); } } } private boolean isWinningMove(Move move) { if (move.getDirection() == Move.HORIZONTAL) { List<Move> requiredMoves = new ArrayList<>(); requiredMoves.add(new Move(move.getX(), move.getY() + 1, Move.HORIZONTAL, null)); requiredMoves.add(new Move(move.getX(), move.getY(), Move.VERTICAL, null)); requiredMoves.add(new Move(move.getX() + 1, move.getY(), Move.VERTICAL, null)); for (Move m : moves) { requiredMoves.remove(m); if (requiredMoves.isEmpty()) { return true; } } } else if (move.getDirection() == Move.VERTICAL) { List<Move> requiredMoves = new ArrayList<>(); requiredMoves.add(new Move(move.getX() + 1, move.getY(), Move.VERTICAL, null)); requiredMoves.add(new Move(move.getX(), move.getY(), Move.HORIZONTAL, null)); requiredMoves.add(new Move(move.getX(), move.getY() + 1, Move.HORIZONTAL, null)); for (Move m : getMoves()) { requiredMoves.remove(m); if (requiredMoves.isEmpty()) { return true; } } } return false; } @Override public String toString() { return "Game{" + "key='" + key + '\'' + ", createdAt=" + createdAt + '}'; } }
package com.t28.rxweather.model; import android.text.TextUtils; import android.util.Log; import com.android.volley.RequestQueue; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.t28.rxweather.request.WeatherRequest; import com.t28.rxweather.util.CollectionUtils; import com.t28.rxweather.volley.RxSupport; import java.util.Map; import rx.Observable; @JsonDeserialize(builder = Weather.Builder.class) public class Weather implements Validatable { public static final int NO_CITY_ID = -1; private final int mCityId; private final String mCityName; private final String mCountryCode; private final long mSunriseTime; private final long mSunsetTime; private final Coordinate mCoordinate; private final MainAttribute mAttribute; private Weather(Builder builder) { mCityId = builder.mCityId; mCityName = builder.mCityName; mCountryCode = builder.mCountryCode; mSunriseTime = builder.mSunriseTime; mSunsetTime = builder.mSunsetTime; mCoordinate = builder.mCoordinate; mAttribute = builder.mAttribute; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(this.getClass().getSimpleName()); try { final ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.PUBLIC_ONLY); builder.append(mapper.writeValueAsString(this)); } catch (JsonProcessingException e) { builder.append(super.toString()); } return builder.toString(); } @Override public boolean isValid() { if (mCityId == NO_CITY_ID) { return false; } if (TextUtils.isEmpty(mCityName) || TextUtils.isEmpty(mCountryCode)) { return false; } if (mSunriseTime <= 0 || mSunsetTime <= 0) { return false; } if (mCoordinate == null || !mCoordinate.isValid()) { return false; } if (mAttribute == null || !mAttribute.isValid()) { return false; } return true; } public int getCityId() { return mCityId; } public String getCityName() { return mCityName; } public String getCountryCode() { return mCountryCode; } public long getSunriseTime() { return mSunriseTime; } public long getSunsetTime() { return mSunsetTime; } public Coordinate getCoordinate() { return mCoordinate; } public MainAttribute getAttribute() { return mAttribute; } public static Observable<Weather> findByCityName(RxSupport support, String name) { final WeatherRequest request = new WeatherRequest.Builder("") .setCityName(name) .build(); return support.createObservableRequest(request); } public static Observable<Weather> findByCityId(RxSupport support, int id) { final WeatherRequest request = new WeatherRequest.Builder("") .setCityId(id) .build(); return support.createObservableRequest(request); } public static Observable<Weather> findByCoordinate(RxSupport support, Coordinate coordinate) { final WeatherRequest request = new WeatherRequest.Builder("") .setLat(coordinate.getLat()) .setLon(coordinate.getLon()) .build(); return support.createObservableRequest(request); } @JsonPOJOBuilder(withPrefix = "set") @JsonIgnoreProperties(ignoreUnknown = true) public static class Builder { private int mCityId = NO_CITY_ID; private String mCityName; private String mCountryCode; private long mSunriseTime; private long mSunsetTime; private Coordinate mCoordinate; private MainAttribute mAttribute; public Builder() { } @JsonProperty("id") public Builder setCityId(int cityId) { mCityId = cityId; return this; } @JsonProperty("name") public Builder setCityName(String cityName) { mCityName = cityName; return this; } @JsonProperty("sys") public Builder setSystem(Map<String, Object> systems) { mCountryCode = CollectionUtils.getValue(systems, "country", "").toString(); mSunriseTime = Long.valueOf(CollectionUtils.getValue(systems, "sunrise", 0).toString()); mSunsetTime = Long.valueOf(CollectionUtils.getValue(systems, "sunset", 0).toString()); return this; } @JsonProperty("coord") public Builder setCoordinate(Coordinate coordinate) { mCoordinate = coordinate; return this; } @JsonProperty("main") public Builder setAttribute(MainAttribute attribute) { mAttribute = attribute; return this; } public Weather build() { return new Weather(this); } } }
package mn.devfest.api.model; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import org.joda.time.DateTime; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Map; import java.util.Set; public class Conference { public double version = 1; public ArrayList<Session> schedule = new ArrayList<>(); public ArrayList<Speaker> speakers = new ArrayList<>(); public String toString() { return "Version: " + version + " has " + schedule.size() + " sessions and " + speakers.size() + " speakers"; } public void parseSessions(JsonObject object) { Gson gson = new GsonBuilder(). registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() { @Override public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsString()); } }) .setDateFormat("yyyy-MM-dd'T'HH:mm") .create(); Set<Map.Entry<String,JsonElement>> entrySet = object.entrySet(); for(Map.Entry<String,JsonElement> entry:entrySet){ Log.d("SCHEDULE", entry.getKey()); try { JsonObject obj = object.getAsJsonObject(entry.getKey()); Session session = gson.fromJson(obj, Session.class); session.setId(entry.getKey()); schedule.add(session); } catch (ClassCastException e) { // Do nothing } } } public void parseSpeakers(JsonObject object) { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm") .create(); Set<Map.Entry<String,JsonElement>> entrySet = object.entrySet(); for(Map.Entry<String,JsonElement> entry:entrySet){ Log.d("SPEAKER", entry.getKey()); try { JsonObject obj = object.getAsJsonObject(entry.getKey()); Speaker speaker = gson.fromJson(obj, Speaker.class); speaker.id = entry.getKey(); speakers.add(speaker); } catch (ClassCastException e) { // Do nothing } } } }
package org.radarcns; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Timer; import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; public class RadarConfiguration { public static final String RADAR_PREFIX = "org.radarcns.android."; public static final String KAFKA_REST_PROXY_URL_KEY = "kafka_rest_proxy_url"; public static final String SCHEMA_REGISTRY_URL_KEY = "schema_registry_url"; public static final String DEVICE_GROUP_ID_KEY = "device_group_id"; public static final String EMPATICA_API_KEY = "empatica_api_key"; public static final String UI_REFRESH_RATE_KEY = "ui_refresh_rate_millis"; public static final String KAFKA_UPLOAD_RATE_KEY = "kafka_upload_rate"; public static final String DATABASE_COMMIT_RATE_KEY = "database_commit_rate"; public static final String KAFKA_CLEAN_RATE_KEY = "kafka_clean_rate"; public static final String KAFKA_RECORDS_SEND_LIMIT_KEY = "kafka_records_send_limit"; public static final String SENDER_CONNECTION_TIMEOUT_KEY = "sender_connection_timeout"; public static final String DATA_RETENTION_KEY = "data_retention_ms"; public static final String FIREBASE_FETCH_TIMEOUT_KEY = "firebase_fetch_timeout"; public static final String CONDENSED_DISPLAY_KEY = "is_condensed_n_records_display"; public static final Pattern IS_TRUE = Pattern.compile( "^(1|true|t|yes|y|on)$", CASE_INSENSITIVE); public static final Pattern IS_FALSE = Pattern.compile( "^(0|false|f|no|n|off|)$", CASE_INSENSITIVE); public static final Set<String> LONG_VALUES = new HashSet<>(Arrays.asList( UI_REFRESH_RATE_KEY, KAFKA_UPLOAD_RATE_KEY, DATABASE_COMMIT_RATE_KEY, KAFKA_CLEAN_RATE_KEY, SENDER_CONNECTION_TIMEOUT_KEY, DATA_RETENTION_KEY, FIREBASE_FETCH_TIMEOUT_KEY)); public static final Set<String> INT_VALUES = Collections.singleton( KAFKA_RECORDS_SEND_LIMIT_KEY); public static final Set<String> BOOLEAN_VALUES = Collections.singleton( CONDENSED_DISPLAY_KEY); private static final Object syncObject = new Object(); private static RadarConfiguration instance = null; private final FirebaseRemoteConfig config; public static final long FIREBASE_FETCH_TIMEOUT_DEFAULT = 43200L; private final Handler handler; private Activity onFetchActivity; private OnCompleteListener<Void> onFetchCompleteHandler; private RadarConfiguration(@NonNull FirebaseRemoteConfig config) { this.config = config; this.onFetchCompleteHandler = null; this.handler = new Handler(); this.handler.postDelayed(new Runnable() { @Override public void run() { fetch(); long delay = getLong(FIREBASE_FETCH_TIMEOUT_KEY, FIREBASE_FETCH_TIMEOUT_DEFAULT); handler.postDelayed(this, delay); } }, getLong(FIREBASE_FETCH_TIMEOUT_KEY, FIREBASE_FETCH_TIMEOUT_DEFAULT)); } public FirebaseRemoteConfig getFirebase() { return config; } public boolean isInDevelopmentMode() { return config.getInfo().getConfigSettings().isDeveloperModeEnabled(); } public static RadarConfiguration getInstance() { synchronized (syncObject) { if (instance == null) { throw new IllegalStateException("RadarConfiguration instance is not yet " + "initialized"); } return instance; } } public static RadarConfiguration configure(boolean inDevelopmentMode, int defaultSettings) { synchronized (syncObject) { if (instance == null) { FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setDeveloperModeEnabled(inDevelopmentMode) .build(); FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance(); config.setConfigSettings(configSettings); config.setDefaults(defaultSettings); instance = new RadarConfiguration(config); } return instance; } } public Task<Void> fetch() { long delay; if (isInDevelopmentMode()) { delay = 0L; } else { delay = getLong(FIREBASE_FETCH_TIMEOUT_KEY, FIREBASE_FETCH_TIMEOUT_DEFAULT); } return fetch(delay); } private Task<Void> fetch(long delay) { Task<Void> task = config.fetch(delay); synchronized (this) { if (onFetchCompleteHandler != null) { if (onFetchActivity != null) { task.addOnCompleteListener(onFetchActivity, onFetchCompleteHandler); } else { task.addOnCompleteListener(onFetchCompleteHandler); } } } return task; } public Task<Void> forceFetch() { return fetch(0L); } public synchronized void onFetchComplete(Activity activity, OnCompleteListener<Void> completeListener) { onFetchActivity = activity; onFetchCompleteHandler = completeListener; } public boolean activateFetched() { return config.activateFetched(); } public String getString(@NonNull String key) { String result = config.getString(key); if (result == null || result.isEmpty()) { throw new IllegalArgumentException("Key does not have a value"); } return result; } public String getString(@NonNull String key, String defaultValue) { String result = config.getString(key); if (result == null || result.isEmpty()) { return defaultValue; } return result; } public long getLong(@NonNull String key) { return Long.parseLong(getString(key)); } public int getInt(@NonNull String key) { return Integer.parseInt(getString(key)); } /** * Get a configured long value. If the configured value is not present or not a valid long, * return a default value. * @param key key of the value * @param defaultValue default value * @return configured long value, or defaultValue if no suitable value was found. */ public long getLong(@NonNull String key, long defaultValue) { try { String result = config.getString(key); if (result != null && !result.isEmpty()) { return Long.parseLong(result); } } catch (NumberFormatException ex) { // return default } return defaultValue; } /** * Get a configured long value. If the configured value is not present or not a valid long, * return a default value. * @param key key of the value * @param defaultValue default value * @return configured long value, or defaultValue if no suitable value was found. */ public int getInt(@NonNull String key, int defaultValue) { try { String result = config.getString(key); if (result != null && !result.isEmpty()) { return Integer.parseInt(result); } } catch (NumberFormatException ex) { // return default } return defaultValue; } public boolean containsKey(@NonNull String key) { return config.getKeysByPrefix(key).contains(key); } public boolean getBoolean(@NonNull String key) { String str = getString(key); if (IS_TRUE.matcher(str).find()) { return true; } else if (IS_FALSE.matcher(str).find()) { return false; } else { throw new NumberFormatException("String '" + str + "' of property '" + key + "' is not a boolean"); } } public boolean getBoolean(@NonNull String key, boolean defaultValue) { String str = getString(key, null); if (str == null) { return defaultValue; } if (IS_TRUE.matcher(str).find()) { return true; } else if (IS_FALSE.matcher(str).find()) { return false; } else { return defaultValue; } } public Set<String> keySet() { Set<String> baseKeys = new HashSet<>(config.getKeysByPrefix(null)); Iterator<String> iter = baseKeys.iterator(); while (iter.hasNext()) { if (getString(iter.next(), null) == null) { iter.remove(); } } return baseKeys; } public boolean equals(Object obj) { return obj != null && !obj.getClass().equals(getClass()) && config.equals(((RadarConfiguration) obj).config); } public int hashCode() { return config.hashCode(); } public void putExtras(Bundle bundle, String... extras) { for (String extra : extras) { try { String key = RADAR_PREFIX + extra; if (LONG_VALUES.contains(extra)) { bundle.putLong(key, getLong(extra)); } else if (INT_VALUES.contains(extra)) { bundle.putInt(key, getInt(extra)); } else if (BOOLEAN_VALUES.contains(extra)) { bundle.putBoolean(key, getString(extra).equals("true")); } else { bundle.putString(key, getString(extra)); } } catch (IllegalArgumentException ex) { // do nothing } } } public static boolean hasExtra(Bundle bundle, String key) { return bundle.containsKey(RADAR_PREFIX + key); } public static int getIntExtra(Bundle bundle, String key, int defaultValue) { return bundle.getInt(RADAR_PREFIX + key, defaultValue); } public static int getIntExtra(Bundle bundle, String key) { return bundle.getInt(RADAR_PREFIX + key); } public static long getLongExtra(Bundle bundle, String key, long defaultValue) { return bundle.getLong(RADAR_PREFIX + key, defaultValue); } public static long getLongExtra(Bundle bundle, String key) { return bundle.getLong(RADAR_PREFIX + key); } public static String getStringExtra(Bundle bundle, String key, String defaultValue) { return bundle.getString(RADAR_PREFIX + key, defaultValue); } public static String getStringExtra(Bundle bundle, String key) { return bundle.getString(RADAR_PREFIX + key); } }
package ph.pakete.view; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import ph.pakete.BackHandledFragment; import ph.pakete.CouriersAdapter; import ph.pakete.R; import ph.pakete.databinding.FragmentCouriersBinding; import ph.pakete.helpers.OnErrorObserver; import ph.pakete.model.Courier; import ph.pakete.helpers.MixpanelHelper; import ph.pakete.viewmodel.PackagesViewModel; public class CouriersFragment extends BackHandledFragment { private PackagesViewModel viewModel; private FragmentCouriersBinding binding; public static CouriersFragment newInstance(PackagesViewModel viewModel) { final CouriersFragment fragment = new CouriersFragment(); fragment.viewModel = viewModel; return fragment; } public CouriersFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem menuItem = menu.findItem(R.id.action_settings); menuItem.setVisible(false); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_couriers, container, false); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(binding.toolbar); ActionBar actionBar = activity.getSupportActionBar(); if (actionBar != null) { actionBar.setTitle("Couriers"); // add back button actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); } binding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); viewModel.couriers .map(couriers -> couriers.size() > 0 ? View.GONE : View.VISIBLE) .subscribe(binding.progress::setVisibility); setupRecyclerView(binding.couriersRecyclerView); // track mixpanel MixpanelHelper.getMixpanel(getActivity()).track("Couriers View"); return binding.getRoot(); } @Override public boolean onBackPressed() { if (getFragmentManager() != null) { getFragmentManager().popBackStack(); // show fab ((MainActivity) getActivity()).showFAB(); return true; } return false; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // get couriers for update if (viewModel.couriers.getValue().size() == 0) { viewModel.getCouriers() .subscribe(new OnErrorObserver<Void>() { @Override public void onError(Throwable e) { // hide progress view binding.progress.setVisibility(View.GONE); // if we didn't have the cached data then we show the error if (viewModel.couriers.getValue().isEmpty()) { // show toast error Toast.makeText(getActivity(), "There was a problem fetching Couriers. Please try again.", Toast.LENGTH_SHORT).show(); onBackPressed(); } } }); } } private void setupRecyclerView(RecyclerView recyclerView) { CouriersAdapter adapter = new CouriersAdapter(); adapter.setCouriers(viewModel.couriers); adapter.onSelectCourier.subscribe(this::showAddPackage); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); } private void showAddPackage(Courier courier) { AddPackageFragment addPackageFragment = AddPackageFragment.newInstance(viewModel, courier); getFragmentManager() .beginTransaction() .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out) .replace(R.id.root_layout, addPackageFragment) .addToBackStack(null) .commit(); } }
package ru.valle.ankidrive; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public final class ScanFragment extends Fragment { public static final String TAG = "Anki"; private TextView statusLabel; private GameSession gameSession; private ArrayAdapter<AnkiCarInfo> listAdapter; private final Handler handler = new Handler(); private View progressView; private OnCarSelectedListener carSelectionListener; public ScanFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View parentView = inflater.inflate(R.layout.fragment_scan, container, false); statusLabel = (TextView) parentView.findViewById(R.id.status_label); progressView = parentView.findViewById(R.id.scan_progress_bar); gameSession = GameSession.getInstance(getActivity()); listAdapter = new ArrayAdapter<AnkiCarInfo>(getActivity(), android.R.layout.simple_list_item_1, gameSession.activeCars); ListView listView = (ListView) parentView.findViewById(R.id.list); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { carSelectionListener.onCarSelected(gameSession.activeCars.get(position)); } }); parentView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scan(); } }); scan(); return parentView; } private void scan() { if (!gameSession.scanningForDevices) { handler.postDelayed(new Runnable() { @Override public void run() { Log.d(TAG, "scan finished " + gameSession.activeCars.size()); gameSession.stopScanning(); progressView.setVisibility(View.GONE); statusLabel.setText(gameSession.activeCars.isEmpty() ? "No cars found" : "Connecting..."); for (AnkiCarInfo carInfo : gameSession.activeCars) { carInfo.connect(getActivity().getApplicationContext()); } } }, 2000); gameSession.closeAllConnections(); listAdapter.notifyDataSetChanged(); progressView.setVisibility(View.VISIBLE); statusLabel.setText("Scanning..."); gameSession.startScanning(); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); carSelectionListener = (OnCarSelectedListener) activity; } @Override public void onDetach() { super.onDetach(); carSelectionListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } }
package teammemes.tritonbudget; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Date; import teammemes.tritonbudget.Menus.Menu; import teammemes.tritonbudget.db.HistoryDataSource; import teammemes.tritonbudget.db.MenuDataSource; import teammemes.tritonbudget.db.TranHistory; public class Checkout extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { LinearLayout mainLayout; Toolbar mToolbar; ActionBarDrawerToggle mToggle; double total = 0; private DrawerLayout mDrawerLayout; private ArrayList<TranHistory> trans; private float dX; private float dY; private int lastAction; @Override protected void onCreate(Bundle savedInstanceState) { User usr = User.getInstance(this); super.onCreate(savedInstanceState); setContentView(R.layout.drawer_checkout); //Creates the toolbar to the one defined in nav_action mToolbar = (Toolbar) findViewById(R.id.nav_action); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Checkout"); //Create the Drawer layout and the toggle mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_checkout_layout); mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close); mDrawerLayout.addDrawerListener(mToggle); mToggle.syncState(); //Create the navigationView and add a listener to listen for menu selections NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); //Get the navigation drawer header and set's the name to user's name View navHeaderView = navigationView.getHeaderView(0); TextView usrName = (TextView) navHeaderView.findViewById(R.id.header_name); usrName.setText(usr.getName()); //Fetches the main empty layout mainLayout = (LinearLayout) findViewById(R.id.page); //Uses custom adapter to populate list view populateCOList(); TextView display_total = (TextView)findViewById(R.id.total_cost); display_total.setText("Total:\t\t\t$" + double_to_string(total)); } @Override public boolean onCreateOptionsMenu(android.view.Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.checkout_menu, menu); return true; } private void populateCOList() { LinearLayout ll = (LinearLayout) findViewById(R.id.Checkout); ll.setBackgroundResource(R.drawable.border_set_top_bottom); Intent it = getIntent(); ArrayList<String> transtring = it.getStringArrayListExtra("Transactions"); trans = new ArrayList<>(); ArrayList<String> num = it.getStringArrayListExtra("number"); MenuDataSource data = new MenuDataSource(getApplicationContext()); for (int i = 0; i < transtring.size(); i++) { Menu men = data.getMenuById(Integer.parseInt(transtring.get(i))); String menuName = men.getName(); int numItems = Integer.parseInt(num.get(i)); if (numItems > 1){ menuName += " x"+numItems; } trans.add(new TranHistory(men.getId(), menuName, numItems, new Date(), men.getCost()*numItems)); String cost = "$" + double_to_string(trans.get(i).getCost()); total += (trans.get(i).getCost()); total *= 100; total = Math.round(total); total /= 100; LinearLayout borderll = makeLL(); LinearLayout quantityll = makeLL(); quantityll.setBackgroundResource(0); quantityll.setGravity(Gravity.RIGHT); TextView item = new TextView(this); item.setPadding(8, 8, 8, 8); item.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); item.setTextSize(20); String itemName = trans.get(i).getName(); item.setText(itemName); TextView t = makeTV(cost); //, quantity); t.setPadding(8,8,8,8); ll.addView(borderll); borderll.addView(item); borderll.addView(quantityll); quantityll.addView(t); } } private LinearLayout makeLL() { LinearLayout nestedll = new LinearLayout(this); nestedll.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); nestedll.setOrientation(LinearLayout.VERTICAL); nestedll.setBackgroundResource(R.drawable.border_set_top_bottom); return nestedll; } private TextView makeTV(String cost) { TextView tv = new TextView(this); tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv.setText(cost); tv.setTextSize(20); return tv; } // add button then call this in listener private boolean change_balance(double bal) { User usr = User.getInstance(getApplicationContext()); if (usr.getBalance() < bal) { return false; } usr.setBalance(usr.getBalance() - bal); HistoryDataSource data = new HistoryDataSource(getApplicationContext()); for (int i = 0; i < trans.size(); i++) { data.createTransaction(trans.get(i)); } return true; } private String double_to_string(double number) { //Gets the balance from the user String str = "" + number; int decimalIdx = str.indexOf('.'); //Edge case, where balance == $XXX.00, it wrongly displays one instance of 0. This fixes it. if (decimalIdx + 1 == str.length() - 1) { str = str + "0"; } return str; } @Override public boolean onNavigationItemSelected(MenuItem item) { // Gets the id of the item that was selected int id = item.getItemId(); Intent nextScreen; //Reacts to the item selected depending on which was pressed //Creates a new Intent for the new page and starts that activity switch (id) { case R.id.nav_home: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, HomeScreen.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_history: mDrawerLayout.closeDrawer(GravityCompat.START); return false; case R.id.nav_statistics: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Statistics.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_menus: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, DiningHallSelection.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_settings: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Settings.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_help: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Help.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; default: mDrawerLayout.closeDrawer(GravityCompat.START); return false; } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mToggle.onOptionsItemSelected(item)) { return true; } int id = item.getItemId(); if (id == R.id.confirmBtn){ if (change_balance(total)) { Intent intent = new Intent(getApplicationContext(), HomeScreen.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Purchased!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "You broke though.", Toast.LENGTH_LONG).show(); } } return super.onOptionsItemSelected(item); } }
package tw.com.akdg.thsrreceipt; import android.accounts.NetworkErrorException; import android.content.Context; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Receipt { public static final String PDF_DIR_NAME = "PDF"; private final String THSR_RECEIPT_URL = "http://www4.thsrc.com.tw/tc/TExp/page_print.asp?lang=tc&pnr=%s&tid=%s"; private final String TAG = "Receipt"; private static final int BUFFER_SIZE = 1024; private Context context; /** * * @param context */ public Receipt(Context context) { this.context = context; } /** * @param pnr (8) * @param tid (13) */ private void downloadReceipt(String pnr, String tid, File file) throws IOException, NetworkErrorException { if (pnr.length() != 8) { throw new NumberFormatException("pnr length number not 8"); } if (tid.length() != 13) { throw new NumberFormatException("tid length number not 16"); } if (!file.exists()) { file.mkdirs(); } File pdf = new File(file.getAbsolutePath(), pnr + "-" + tid + ".pdf"); if (pdf.exists()) { return; } URL mUrl = new URL(String.format(THSR_RECEIPT_URL, pnr, tid)); HttpURLConnection mHttpURLCooenction = (HttpURLConnection) mUrl.openConnection(); mHttpURLCooenction.setRequestMethod("GET"); mHttpURLCooenction.connect(); if (mHttpURLCooenction.getResponseCode() != 200) { throw new NetworkErrorException( "Connent to " + String.format(THSR_RECEIPT_URL, pnr, tid) + ", status number code :" + mHttpURLCooenction.getResponseCode()); } InputStream inputStream = mHttpURLCooenction.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(pdf); int totalSize = mHttpURLCooenction.getContentLength(); byte[] buffer = new byte[totalSize]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutputStream.write(buffer, 0, bufferLength); } } /** * @param pnr (8) * @param tid (13) */ public void downloadReceipt(String pnr, String tid) throws IOException, NetworkErrorException { if (pnr.length() != 8) { throw new NumberFormatException("pnr length number not 8"); } if (tid.length() != 13) { throw new NumberFormatException("tid length number not 16"); } downloadReceipt(pnr, tid, context.getDir(PDF_DIR_NAME, Context.MODE_PRIVATE)); } /** * @param pnr (8) * @param tid (13) * @param path */ private void downloadReceipt(String pnr, String tid, String path) throws IOException, NetworkErrorException { if (pnr.length() != 8) { throw new NumberFormatException("tid length number not 8"); } if (tid.length() != 13) { throw new NumberFormatException("pnr length number not 16"); } downloadReceipt(pnr, tid, new File(path)); } /** * Receipt zip * * @return zip path */ public String getZipFilePath() throws IOException { File[] files = context.getDir(FILD_DIR_NAME, Context.MODE_PRIVATE).listFiles(); File zipFile = new File(context.getCacheDir(), "Receipt.zip"); BufferedInputStream origin = null; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); try { byte data[] = new byte[BUFFER_SIZE]; for (int i = 0; i < files.length; i++) { FileInputStream fi = new FileInputStream(files[i]); origin = new BufferedInputStream(fi, BUFFER_SIZE); try { ZipEntry entry = new ZipEntry( files[i].getName().substring(files[i].getName().lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, count); } } finally { origin.close(); } } } finally { out.close(); } return zipFile.getAbsolutePath(); } }
package org.commcare.activities; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.ActionBar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.Rect; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import androidx.core.app.ActivityCompat; import android.util.Log; import android.util.Pair; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; import android.widget.VideoView; import org.commcare.CommCareApplication; import org.commcare.activities.components.FormEntryConstants; import org.commcare.activities.components.FormEntryDialogs; import org.commcare.activities.components.FormEntryInstanceState; import org.commcare.activities.components.FormEntrySessionWrapper; import org.commcare.activities.components.FormFileSystemHelpers; import org.commcare.activities.components.FormNavigationUI; import org.commcare.activities.components.ImageCaptureProcessing; import org.commcare.android.database.app.models.FormDefRecord; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.javarosa.PollSensorAction; import org.commcare.android.javarosa.PollSensorController; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.google.services.analytics.AnalyticsParamValue; import org.commcare.google.services.analytics.FirebaseAnalyticsUtil; import org.commcare.google.services.analytics.FormAnalyticsHelper; import org.commcare.interfaces.AdvanceToNextListener; import org.commcare.interfaces.CommCareActivityUIController; import org.commcare.interfaces.FormSaveCallback; import org.commcare.interfaces.FormSavedListener; import org.commcare.interfaces.RuntimePermissionRequester; import org.commcare.interfaces.WidgetChangedListener; import org.commcare.interfaces.WithUIController; import org.commcare.logging.analytics.TimedStatsTracker; import org.commcare.logic.AndroidFormController; import org.commcare.models.ODKStorage; import org.commcare.models.database.SqlStorage; import org.commcare.tasks.FormLoaderTask; import org.commcare.tasks.SaveToDiskTask; import org.commcare.util.LogTypes; import org.commcare.utils.Base64Wrapper; import org.commcare.utils.CompoundIntentList; import org.commcare.utils.FileUtil; import org.commcare.utils.GeoUtils; import org.commcare.utils.SessionUnavailableException; import org.commcare.utils.StringUtils; import org.commcare.views.QuestionsView; import org.commcare.views.ResizingImageView; import org.commcare.views.UserfacingErrorHandling; import org.commcare.views.dialogs.CustomProgressDialog; import org.commcare.views.media.MediaLayout; import org.commcare.views.widgets.BarcodeWidget; import org.commcare.views.widgets.ImageWidget; import org.commcare.views.widgets.IntentWidget; import org.commcare.views.widgets.QuestionWidget; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.trace.EvaluationTraceReporter; import org.javarosa.core.model.trace.ReducingTraceReporter; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.form.api.FormEntryController; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.crypto.spec.SecretKeySpec; /** * Displays questions, animates transitions between * questions, and allows the user to enter data. */ public class FormEntryActivity extends SaveSessionCommCareActivity<FormEntryActivity> implements FormSavedListener, FormSaveCallback, WithUIController, AdvanceToNextListener, WidgetChangedListener, RuntimePermissionRequester { private static final String TAG = FormEntryActivity.class.getSimpleName(); public static final String KEY_FORM_RECORD_ID = "key_form_record_id"; public static final String KEY_FORM_DEF_ID = "key_form_def_id"; public static final String KEY_AES_STORAGE_KEY = "key_aes_storage"; public static final String KEY_HEADER_STRING = "form_header"; public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management"; public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled"; public static final String KEY_IS_RESTART_AFTER_EXPIRATION = "is-restart-after-session-expiration"; private static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved"; private static final String KEY_WIDGET_WITH_VIDEO_PLAYING = "index-of-widget-with-video-playing-on-pause"; private static final String KEY_POSITION_OF_VIDEO_PLAYING = "position-of-video-playing-on-pause"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String KEY_FORM_LOAD_HAS_TRIGGERED = "newform"; private static final String KEY_FORM_LOAD_FAILED = "form-failed"; private static final String KEY_LOC_ERROR = "location-not-enabled"; private static final String KEY_LOC_ERROR_PATH = "location-based-xpath-error"; private static final String KEY_IS_READ_ONLY = "instance-is-read-only"; private FormEntryInstanceState instanceState; private FormEntrySessionWrapper formEntryRestoreSession = new FormEntrySessionWrapper(); private SecretKeySpec symetricKey = null; public static AndroidFormController mFormController; private boolean mIncompleteEnabled = true; private boolean instanceIsReadOnly = false; private boolean hasFormLoadBeenTriggered = false; private boolean hasFormLoadFailed = false; private String locationRecieverErrorAction = null; private String badLocationXpath = null; private GestureDetector mGestureDetector; private int indexOfWidgetWithVideoPlaying = -1; private int positionOfVideoProgress = -1; private FormLoaderTask<FormEntryActivity> mFormLoaderTask; private SaveToDiskTask mSaveToDiskTask; private static String mHeaderString; // Was the form saved? Used to set activity return code. private boolean hasSaved = false; private BroadcastReceiver mLocationServiceIssueReceiver; // This will be set if a unique action needs to be taken // at the end of saving a form - like continuing a logout // or proceeding unblocked private Runnable customFormSaveCallback = null; private FormEntryActivityUIController uiController; private SqlStorage<FormRecord> formRecordStorage; private boolean fullFormProfilingEnabled = false; private EvaluationTraceReporter traceReporter; @Override @SuppressLint("NewApi") public void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); formRecordStorage = CommCareApplication.instance().getUserStorage(FormRecord.class); instanceState = new FormEntryInstanceState(formRecordStorage); // must be at the beginning of any activity that can be called from an external intent try { ODKStorage.createODKDirs(); } catch (RuntimeException e) { Logger.exception("Error creating storage directories", e); UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), FormEntryConstants.EXIT); return; } uiController.setupUI(); mGestureDetector = new GestureDetector(this, this); if (savedInstanceState != null) { loadStateFromBundle(savedInstanceState); } // Check to see if this is a screen flip or a new form load. Object data = this.getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask)data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask)data; mSaveToDiskTask.setFormSavedListener(this); } else if (hasFormLoadBeenTriggered && !hasFormLoadFailed) { // Screen orientation change if (mFormController == null) { throw new SessionUnavailableException( "Resuming form entry after process was killed. Form state is unrecoverable."); } uiController.refreshView(); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { /* * EventLog accepts only proper Strings as input, but prior to this version, * Android would try to send SpannedStrings to it, thus crashing the app. * This makes sure the title is actually a String. * This fixes bug 174626. */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 && item.getTitleCondensed() != null) { item.setTitleCondensed(item.getTitleCondensed().toString()); } return super.onMenuItemSelected(featureId, item); } @Override public void formSaveCallback(Runnable listener) { // note that we have started saving the form customFormSaveCallback = listener; // Set flag that will allow us to restore this form when we log back in CommCareApplication.instance().getCurrentSessionWrapper().setCurrentStateAsInterrupted(); // Start saving form; will trigger expireUserSession() on completion saveIncompleteFormToDisk(); } private void registerFormEntryReceiver() { //BroadcastReceiver for: // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged // b) Checking if GPS services are not available mLocationServiceIssueReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.removeStickyBroadcast(intent); badLocationXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH); locationRecieverErrorAction = intent.getAction(); } }; IntentFilter filter = new IntentFilter(); filter.addAction(PollSensorAction.XPATH_ERROR_ACTION); filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED); registerReceiver(mLocationServiceIssueReceiver, filter); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); instanceState.saveState(outState); outState.putBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, hasFormLoadBeenTriggered); outState.putBoolean(KEY_FORM_LOAD_FAILED, hasFormLoadFailed); outState.putString(KEY_LOC_ERROR, locationRecieverErrorAction); outState.putString(KEY_LOC_ERROR_PATH, badLocationXpath); outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled); outState.putBoolean(KEY_HAS_SAVED, hasSaved); outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod); outState.putBoolean(KEY_IS_READ_ONLY, instanceIsReadOnly); formEntryRestoreSession.saveFormEntrySession(outState); if (indexOfWidgetWithVideoPlaying != -1) { outState.putInt(KEY_WIDGET_WITH_VIDEO_PLAYING, indexOfWidgetWithVideoPlaying); outState.putInt(KEY_POSITION_OF_VIDEO_PLAYING, positionOfVideoProgress); } if (symetricKey != null) { try { outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded())); } catch (ClassNotFoundException e) { // we can't really get here anyway, since we couldn't have decoded the string to begin with throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key"); } } uiController.saveInstanceState(outState); } @Override public void onActivityResultSessionSafe(int requestCode, int resultCode, Intent intent) { if (requestCode == FormEntryConstants.FORM_PREFERENCES_KEY) { uiController.refreshCurrentView(false); return; } if (resultCode == RESULT_CANCELED) { if (requestCode == FormEntryConstants.HIERARCHY_ACTIVITY_FIRST_START) { // They pressed 'back' on the first hierarchy screen, so we should assume they want // to back out of form entry all together finishReturnInstance(false); } else if (requestCode == FormEntryConstants.INTENT_CALLOUT) { processIntentResponse(intent, true); Toast.makeText(this, Localization.get("intent.callout.cancelled"), Toast.LENGTH_SHORT).show(); } } else { switch (requestCode) { case FormEntryConstants.INTENT_CALLOUT: if (!processIntentResponse(intent, false)) { Toast.makeText(this, Localization.get("intent.callout.unable.to.process"), Toast.LENGTH_SHORT).show(); } break; case FormEntryConstants.IMAGE_CAPTURE: ImageCaptureProcessing.processCaptureResponse(this, FormEntryInstanceState.getInstanceFolder(), true); break; case FormEntryConstants.SIGNATURE_CAPTURE: boolean saved = ImageCaptureProcessing.processCaptureResponse(this, FormEntryInstanceState.getInstanceFolder(), false); if (saved && !uiController.questionsView.isQuestionList()) { // attempt to auto-advance if a signature was captured advance(); } break; case FormEntryConstants.IMAGE_CHOOSER: ImageCaptureProcessing.processImageChooserResponse(this, FormEntryInstanceState.getInstanceFolder(), intent); break; case FormEntryConstants.AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case FormEntryConstants.LOCATION_CAPTURE: String sl = intent.getStringExtra(FormEntryConstants.LOCATION_RESULT); uiController.questionsView.setBinaryData(sl, mFormController); saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); break; case FormEntryConstants.HIERARCHY_ACTIVITY: case FormEntryConstants.HIERARCHY_ACTIVITY_FIRST_START: if (resultCode == FormHierarchyActivity.RESULT_XPATH_ERROR) { finish(); } else { // We may have jumped to a new index in hierarchy activity, so refresh uiController.refreshCurrentView(false); } break; } } resetPendingCalloutIndex(); } private void resetPendingCalloutIndex() { if (mFormController != null) { mFormController.setPendingCalloutFormIndex(null); } } public void saveImageWidgetAnswer(String imagePath) { uiController.questionsView.setBinaryData(imagePath, mFormController); saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); updateFormMediaToDisk(); uiController.refreshView(); } private void processChooserResponse(Intent intent) { // For audio/video capture/chooser, we get the URI from the content provider // then the widget copies the file and makes a new entry in the content provider. Uri media = intent.getData(); if (!FileUtil.isSupportedMultiMediaFile(media)) { // don't let the user select a file that won't be included in the // upload to the server uiController.questionsView.clearAnswer(); Toast.makeText(FormEntryActivity.this, Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); } else { uiController.questionsView.setBinaryData(media, mFormController); } saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); updateFormMediaToDisk(); uiController.refreshView(); } /** * Search the the current view's widgets for one that has registered a * pending callout with the form controller */ public QuestionWidget getPendingWidget() { if (mFormController != null) { FormIndex pendingIndex = mFormController.getPendingCalloutFormIndex(); if (pendingIndex == null) { return null; } for (QuestionWidget q : uiController.questionsView.getWidgets()) { if (q.getFormId().equals(pendingIndex)) { return q; } } Logger.log(LogTypes.SOFT_ASSERT, "getPendingWidget couldn't find question widget with a form index that " + "matches the pending callout."); } return null; } /** * @return Was answer set from intent? */ private boolean processIntentResponse(Intent response, boolean wasIntentCancelled) { // keep track of whether we should auto advance boolean wasAnswerSet = false; boolean isQuick = false; try { IntentWidget pendingIntentWidget = (IntentWidget)getPendingWidget(); if (pendingIntentWidget != null) { if (!wasIntentCancelled) { isQuick = "quick".equals(pendingIntentWidget.getAppearance()); TreeReference contextRef = null; if (mFormController.getPendingCalloutFormIndex() != null) { contextRef = mFormController.getPendingCalloutFormIndex().getReference(); } if (pendingIntentWidget instanceof BarcodeWidget) { String scanResult = response.getStringExtra("SCAN_RESULT"); if (scanResult != null) { ((BarcodeWidget)pendingIntentWidget).processBarcodeResponse(contextRef, scanResult); wasAnswerSet = true; } } else { // Set our instance destination for binary data if needed String destination = instanceState.getInstanceFolder(); wasAnswerSet = pendingIntentWidget.getIntentCallout() .processResponse(response, contextRef, new File(destination)); } } if (wasIntentCancelled) { mFormController.setPendingCalloutAsCancelled(); } } // auto advance if we got a good result and are in quick mode if (wasAnswerSet && isQuick) { uiController.showNextView(); } else { uiController.refreshView(); } return wasAnswerSet; } catch (XPathException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, true); return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (CommCareApplication.instance().isConsumerApp()) { // Do not show options menu at all if this is a consumer app return super.onCreateOptionsMenu(menu); } super.onCreateOptionsMenu(menu); menu.add(0, FormEntryConstants.MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)) .setIcon(android.R.drawable.ic_menu_save); menu.add(0, FormEntryConstants.MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)) .setIcon(R.drawable.ic_menu_goto); menu.add(0, FormEntryConstants.MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation); menu.add(0, FormEntryConstants.MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.form_entry_settings)) .setIcon(android.R.drawable.ic_menu_preferences); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (CommCareApplication.instance().isConsumerApp()) { // Do not show options menu at all if this is a consumer app return super.onPrepareOptionsMenu(menu); } super.onPrepareOptionsMenu(menu); menu.findItem(FormEntryConstants.MENU_SAVE).setVisible(mIncompleteEnabled && !instanceIsReadOnly); boolean hasMultipleLanguages = (!(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1)); menu.findItem(FormEntryConstants.MENU_LANGUAGES).setEnabled(hasMultipleLanguages); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Map<Integer, String> menuIdToAnalyticsParam = createMenuItemToAnalyticsParamMapping(); FirebaseAnalyticsUtil.reportOptionsMenuItemClick(this.getClass(), menuIdToAnalyticsParam.get(item.getItemId())); switch (item.getItemId()) { case FormEntryConstants.MENU_LANGUAGES: FormEntryDialogs.createLanguageDialog(this); return true; case FormEntryConstants.MENU_SAVE: saveFormToDisk(FormEntryConstants.DO_NOT_EXIT); return true; case FormEntryConstants.MENU_HIERARCHY_VIEW: if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, FormEntryConstants.HIERARCHY_ACTIVITY); return true; case FormEntryConstants.MENU_PREFERENCES: Intent pref = new Intent(this, SessionAwarePreferenceActivity.class); pref.putExtra(CommCarePreferenceActivity.EXTRA_PREF_TYPE, CommCarePreferenceActivity.PREF_TYPE_FORM_ENTRY); startActivityForResult(pref, FormEntryConstants.FORM_PREFERENCES_KEY); return true; case android.R.id.home: FirebaseAnalyticsUtil.reportFormQuitAttempt(AnalyticsParamValue.NAV_BUTTON_PRESS); triggerUserQuitInput(); return true; } return super.onOptionsItemSelected(item); } private static Map<Integer, String> createMenuItemToAnalyticsParamMapping() { Map<Integer, String> menuIdToAnalyticsEvent = new HashMap<>(); menuIdToAnalyticsEvent.put(FormEntryConstants.MENU_LANGUAGES, AnalyticsParamValue.ITEM_CHANGE_LANGUAGE); menuIdToAnalyticsEvent.put(FormEntryConstants.MENU_SAVE, AnalyticsParamValue.ITEM_SAVE_FORM); menuIdToAnalyticsEvent.put(FormEntryConstants.MENU_HIERARCHY_VIEW, AnalyticsParamValue.ITEM_FORM_HIERARCHY); menuIdToAnalyticsEvent.put(FormEntryConstants.MENU_PREFERENCES, AnalyticsParamValue.ITEM_CHANGE_FORM_SETTINGS); return menuIdToAnalyticsEvent; } /** * @return true If the current index of the form controller contains questions */ protected boolean currentPromptIsQuestion() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController .getEvent() == FormEntryController.EVENT_GROUP); } public boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { return saveAnswersForCurrentScreen(evaluateConstraints, true, false); } /** * Attempt to save the answer(s) in the current screen to into the data model. * * @param failOnRequired Whether or not the constraint evaluation * should return false if the question is only * required. (this is helpful for incomplete * saves) * @param headless running in a process that can't display graphics * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { // only try to save if the current event is a question or a field-list // group boolean success = true; if (isEventQuestionOrListGroup()) { HashMap<FormIndex, IAnswerData> answers = uiController.questionsView.getAnswers(); // Sort the answers so if there are multiple errors, we can // bring focus to the first one List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, FormIndex::compareTo); try { for (FormIndex index : indexKeys) { // Within a group, you can only save for question events if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { uiController.showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog(this, e.getLocalizedMessage(), true); } } return success; } private boolean isEventQuestionOrListGroup() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION) || (mFormController.getEvent() == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList()); } /** * Clears the answer on the screen. */ public void clearAnswer(QuestionWidget qw) { qw.clearAnswer(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer)); menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { // We don't have the right view here, so we store the View's ID as the // item ID and loop through the possible views to find the one the user // clicked on. for (QuestionWidget qw : uiController.questionsView.getWidgets()) { if (item.getItemId() == qw.getId()) { FormEntryDialogs.createClearDialog(this, qw); } } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainCustomNonConfigurationInstance() { // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (mFormController != null && currentPromptIsQuestion() && uiController.questionsView != null) { saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); } return null; } @SuppressLint("NewApi") @Override public boolean dispatchTouchEvent(MotionEvent mv) { //We need to ignore this even if it's processed by the action //bar (if one exists) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar bar = getActionBar(); if (bar != null) { View customView = bar.getCustomView(); if (customView != null && customView.dispatchTouchEvent(mv)) { return true; } } } boolean handled = mGestureDetector.onTouchEvent(mv); return handled || super.dispatchTouchEvent(mv); } protected void fireCompoundIntentDispatch() { CompoundIntentList i = uiController.questionsView.getAggregateIntentCallout(); if (i == null) { uiController.hideCompoundIntentCalloutButton(); Log.e(TAG, "Multiple intent dispatch button shouldn't have been shown"); return; } // We don't process the result on this yet, but Android won't maintain the backstack // state for the current activity unless it thinks we're going to process the callout // result. this.startActivityForResult(i.getCompoundedIntent(), FormEntryConstants.INTENT_COMPOUND_CALLOUT); } public void saveFormToDisk(boolean exit) { if (formHasLoaded()) { boolean isFormComplete = instanceState.isFormRecordComplete(); saveDataToDisk(exit, isFormComplete, null, false); } else if (exit) { showSaveErrorAndExit(); } } private void saveCompletedFormToDisk(String updatedSaveName) { saveDataToDisk(FormEntryConstants.EXIT, true, updatedSaveName, false); } private void saveIncompleteFormToDisk() { saveDataToDisk(FormEntryConstants.EXIT, false, null, true); } private void updateFormMediaToDisk() { // Works only when we are editing a saved form. FormRecord formRecord = FormRecord.getFormRecord(formRecordStorage, FormEntryInstanceState.mFormRecordPath); if (formRecord == null) { return; } String formStatus = formRecord.getStatus(); if (FormRecord.STATUS_INCOMPLETE.equals(formStatus)) { saveDataToDisk(false, false, null, true); } } private void showSaveErrorAndExit() { Toast.makeText(this, Localization.get("form.entry.save.error"), Toast.LENGTH_SHORT).show(); hasSaved = false; finishReturnInstance(); } /** * Saves form data to disk. * * @param exit If set, will exit program after save. * @param complete Has the user marked the instances as complete? * @param updatedSaveName Set name of the instance's content provider, if * non-null * @param headless Disables GUI warnings and lets answers that * violate constraints be saved. */ private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) { if (!formHasLoaded()) { if (exit) { showSaveErrorAndExit(); } return; } // save current answer; if headless, don't evaluate the constraints // before doing so. boolean wasScreenSaved = saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS, complete, headless); if (!wasScreenSaved) { return; } // If a save task is already running, just let it do its thing if ((mSaveToDiskTask != null) && (mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) { return; } // A form save has already been triggered, ignore subsequent form saves if (FormEntryActivity.mFormController.isFormCompleteAndSaved()) { return; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getIntExtra(KEY_FORM_RECORD_ID, -1), getIntent().getIntExtra(KEY_FORM_DEF_ID, -1), FormEntryInstanceState.mFormRecordPath, exit, complete, updatedSaveName, symetricKey, headless); if (!headless) { mSaveToDiskTask.connect(this); } mSaveToDiskTask.setFormSavedListener(this); mSaveToDiskTask.executeParallel(); } public void discardChangesAndExit() { FormFileSystemHelpers.removeMediaAttachedToUnsavedForm(this, FormEntryInstanceState.mFormRecordPath, formRecordStorage); finishReturnInstance(false); } public void setFormLanguage(String[] languages, int index) { mFormController.setLanguage(languages[index]); dismissAlertDialog(); if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); } uiController.refreshView(); invalidateOptionsMenu(); } @Override public CustomProgressDialog generateProgressDialog(int id) { CustomProgressDialog dialog = null; switch (id) { case FormLoaderTask.FORM_LOADER_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.loading_form), StringUtils.getStringRobust(this, R.string.please_wait), id); dialog.addCancelButton(); break; case SaveToDiskTask.SAVING_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.saving_form), StringUtils.getStringRobust(this, R.string.please_wait), id); break; } return dialog; } @Override public void taskCancelled() { finish(); } @Override protected void onPause() { super.onPause(); if (!isFinishing() && uiController.questionsView != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(FormEntryConstants.DO_NOT_EVALUATE_CONSTRAINTS); } if (mLocationServiceIssueReceiver != null) { try { unregisterReceiver(mLocationServiceIssueReceiver); } catch (IllegalArgumentException e) { // Thrown when given receiver isn't registered. // This shouldn't ever happen, but seems to come up in production Logger.log(LogTypes.TYPE_ERROR_ASSERTION, "Tried to unregister a BroadcastReceiver that wasn't registered: " + e.getMessage()); } } saveInlineVideoState(); if (isFinishing()) { PollSensorController.INSTANCE.stopLocationPolling(); } } private void saveInlineVideoState() { if (uiController.questionsView != null) { for (int i = 0; i < uiController.questionsView.getWidgets().size(); i++) { QuestionWidget q = uiController.questionsView.getWidgets().get(i); if (q.findViewById(MediaLayout.INLINE_VIDEO_PANE_ID) != null) { VideoView inlineVideo = q.findViewById(MediaLayout.INLINE_VIDEO_PANE_ID); if (inlineVideo.isPlaying()) { indexOfWidgetWithVideoPlaying = i; positionOfVideoProgress = inlineVideo.getCurrentPosition(); return; } } } } } private void restoreInlineVideoState() { if (indexOfWidgetWithVideoPlaying != -1) { QuestionWidget widgetWithVideoToResume = uiController.questionsView.getWidgets().get(indexOfWidgetWithVideoPlaying); VideoView inlineVideo = widgetWithVideoToResume.findViewById(MediaLayout.INLINE_VIDEO_PANE_ID); if (inlineVideo != null) { inlineVideo.seekTo(positionOfVideoProgress); inlineVideo.start(); } else { Logger.log(LogTypes.SOFT_ASSERT, "No inline video was found at the question widget index for which a " + "video had been playing before the activity was paused"); } // Reset values now that we have restored indexOfWidgetWithVideoPlaying = -1; positionOfVideoProgress = -1; } } @Override public void onResumeSessionSafe() { if (!hasFormLoadBeenTriggered) { loadForm(); } registerFormEntryReceiver(); restorePriorStates(); reportVideoUsageIfAny(); } private void reportVideoUsageIfAny() { if (mFormController != null) { FormAnalyticsHelper formAnalyticsHelper = mFormController.getFormAnalyticsHelper(); if (formAnalyticsHelper.getVideoStartTime() != -1) { FirebaseAnalyticsUtil.reportVideoPlayEvent(formAnalyticsHelper.getVideoName(), formAnalyticsHelper.getVideoDuration(), formAnalyticsHelper.getVideoStartTime()); formAnalyticsHelper.resetVideoPlaybackInfo(); } } } private void restorePriorStates() { if (uiController.questionsView != null) { uiController.questionsView.restoreTimePickerData(); uiController.restoreFocusToCalloutQuestion(); restoreInlineVideoState(); } } private void loadForm() { mFormController = null; instanceState.setFormRecordPath(null); Intent intent = getIntent(); if (intent != null) { loadIntentFormData(intent); setTitleToLoading(); int formId; try { SqlStorage<FormDefRecord> formDefStorage = CommCareApplication.instance().getAppStorage(FormDefRecord.class); if (intent.hasExtra(KEY_FORM_RECORD_ID)) { Pair<Integer, Boolean> instanceAndStatus = instanceState.getFormDefIdForRecord( formDefStorage, intent.getIntExtra(KEY_FORM_RECORD_ID, -1), instanceState); formId = instanceAndStatus.first; instanceIsReadOnly = instanceAndStatus.second; } else if (intent.hasExtra(KEY_FORM_DEF_ID)) { formId = intent.getIntExtra(KEY_FORM_DEF_ID, -1); instanceState.setFormDefPath(FormFileSystemHelpers.getFormDefPath(formDefStorage, formId)); } else { UserfacingErrorHandling.createErrorDialog(this, "Intent to start FormEntryActivity must contain either instance id or form def id", FormEntryConstants.EXIT); return; } } catch (FormQueryException e) { UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), FormEntryConstants.EXIT); return; } mFormLoaderTask = new FormLoaderTask<FormEntryActivity>(symetricKey, instanceIsReadOnly, formEntryRestoreSession.isRecording(), FormEntryInstanceState.mFormRecordPath, this) { @Override protected void deliverResult(FormEntryActivity receiver, FECWrapper wrapperResult) { receiver.handleFormLoadCompletion(wrapperResult.getController()); } @Override protected void deliverUpdate(FormEntryActivity receiver, String... update) { } @Override protected void deliverError(FormEntryActivity receiver, Exception e) { receiver.setFormLoadFailure(); receiver.dismissProgressDialog(); if (e != null) { UserfacingErrorHandling.createErrorDialog(receiver, e.getMessage(), FormEntryConstants.EXIT); } else { UserfacingErrorHandling.createErrorDialog(receiver, StringUtils.getStringRobust(receiver, R.string.parse_error), FormEntryConstants.EXIT); } if (intent.hasExtra(KEY_FORM_RECORD_ID)) { // log the form record id for which form load has failed FormRecord formRecord = FormRecord.getFormRecord(formRecordStorage, intent.getIntExtra(KEY_FORM_RECORD_ID, -1)); Logger.log(LogTypes.TYPE_FORM_ENTRY, "Form load failed for form with id " + formRecord.getInstanceID()); } } }; if (fullFormProfilingEnabled) { traceReporter = new ReducingTraceReporter(true); mFormLoaderTask.setProfilingOnFullForm(traceReporter); } mFormLoaderTask.connect(this); mFormLoaderTask.executeParallel(formId); hasFormLoadBeenTriggered = true; } } private void handleFormLoadCompletion(AndroidFormController fc) { if (GeoUtils.ACTION_CHECK_GPS_ENABLED.equals(locationRecieverErrorAction)) { FormEntryDialogs.handleNoGpsBroadcast(this); } else if (PollSensorAction.XPATH_ERROR_ACTION.equals(locationRecieverErrorAction)) { handleXpathErrorBroadcast(); } mFormController = fc; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Newer menus may have already built the menu, before all data was ready invalidateOptionsMenu(); } registerSessionFormSaveCallback(); boolean isRestartAfterSessionExpiration = getIntent().getBooleanExtra(KEY_IS_RESTART_AFTER_EXPIRATION, false); // Set saved answer path if (FormEntryInstanceState.mFormRecordPath == null) { instanceState.initFormRecordPath(); } else if (!isRestartAfterSessionExpiration) { // we've just loaded a saved form, so start in the hierarchy view Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, FormEntryConstants.HIERARCHY_ACTIVITY_FIRST_START); return; // so we don't show the intro screen before jumping to the hierarchy } reportFormEntryTime(); formEntryRestoreSession.replaySession(this); uiController.refreshView(); FormNavigationUI.updateNavigationCues(this, mFormController, uiController.questionsView); if (isRestartAfterSessionExpiration) { Toast.makeText(this, Localization.get("form.entry.restart.after.expiration"), Toast.LENGTH_LONG).show(); } } private void handleXpathErrorBroadcast() { UserfacingErrorHandling.createErrorDialog(FormEntryActivity.this, "There is a bug in one of your form's XPath Expressions \n" + badLocationXpath, FormEntryConstants.EXIT); } /** * Call when the user provides input that they want to quit the form */ protected void triggerUserQuitInput() { if (!formHasLoaded()) { finish(); } else if (mFormController.isFormReadOnly()) { // If we're just reviewing a read only form, don't worry about saving // or what not, just quit // It's possible we just want to "finish" here, but // I don't really wanna break any c compatibility finishReturnInstance(false); } else { FormEntryDialogs.createQuitDialog(this, mIncompleteEnabled); return; } } /** * Call when the user is ready to save and return the current form as complete */ protected void triggerUserFormComplete() { if (!isFinishing()) { if (mFormController.isFormReadOnly()) { finishReturnInstance(false); } else { int formRecordId = getIntent().getIntExtra(KEY_FORM_RECORD_ID, -1); saveCompletedFormToDisk(instanceState.getDefaultFormTitle(formRecordId)); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: FirebaseAnalyticsUtil.reportFormQuitAttempt(AnalyticsParamValue.BACK_BUTTON_PRESS); triggerUserQuitInput(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !uiController.shouldIgnoreSwipeAction()) { uiController.setIsAnimatingSwipe(); uiController.showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !uiController.shouldIgnoreSwipeAction()) { uiController.setIsAnimatingSwipe(); uiController.showPreviousView(true); return true; } break; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mFormLoaderTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } super.onDestroy(); } private void registerSessionFormSaveCallback() { if (mFormController != null && !mFormController.isFormReadOnly()) { try { // CommCareSessionService will call this.formSaveCallback when // the key session is closing down and we need to save any // intermediate results before they become un-saveable. CommCareApplication.instance().getSession().registerFormSaveCallback(this); } catch (SessionUnavailableException e) { Log.w(TAG, "Couldn't register form save callback because session doesn't exist"); } } } /** * {@inheritDoc} * * Display save status notification and exit or continue on in the form. * If form entry is being saved because key session is expiring then * continue closing the session/logging out. */ @Override public void savingComplete(SaveToDiskTask.SaveStatus saveStatus, String errorMessage) { // Did we just save a form because the key session // (CommCareSessionService) is ending? if (customFormSaveCallback != null) { Runnable toCall = customFormSaveCallback; customFormSaveCallback = null; toCall.run(); returnAsInterrupted(); } else if (saveStatus != null) { String toastMessage = ""; switch (saveStatus) { case SAVED_COMPLETE: toastMessage = Localization.get("form.entry.complete.save.success"); hasSaved = true; break; case SAVED_INCOMPLETE: toastMessage = Localization.get("form.entry.incomplete.save.success"); hasSaved = true; break; case SAVED_AND_EXIT: toastMessage = Localization.get("form.entry.complete.save.success"); hasSaved = true; finishReturnInstance(); break; case INVALID_ANSWER: // an answer constraint was violated, so try to save the // current question to trigger the constraint violation message uiController.refreshView(); saveAnswersForCurrentScreen(FormEntryConstants.EVALUATE_CONSTRAINTS); return; case SAVE_ERROR: if (!CommCareApplication.instance().isConsumerApp()) { UserfacingErrorHandling.createErrorDialog(this, errorMessage, Localization.get("notification.formentry.save_error.title"), FormEntryConstants.EXIT); } return; } if (!"".equals(toastMessage) && !CommCareApplication.instance().isConsumerApp()) { Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show(); } uiController.refreshView(); } } private void returnAsInterrupted() { Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(FormEntryConstants.WAS_INTERRUPTED, true); setResult(RESULT_CANCELED, formReturnIntent); finish(); } /** * Attempts to save an answer to the specified index. * * @param evaluateConstraints Should form constraints be checked when saving answer? * @return status as determined in FormEntryController */ private int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { try { if (evaluateConstraints) { return mFormController.answerQuestion(index, answer); } else { mFormController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } catch (XPathException e) { //this is where runtime exceptions get triggered after the form has loaded UserfacingErrorHandling.logErrorAndShowDialog(this, e, FormEntryConstants.EXIT); //We're exiting anyway return FormEntryController.ANSWER_OK; } } private void finishReturnInstance() { finishReturnInstance(true); } /** * Returns the instance that was just filled out to the calling activity, * if requested. * * @param reportSaved was a form saved? Delegates the result code of the * activity */ private void finishReturnInstance(boolean reportSaved) { String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(FormEntryConstants.IS_ARCHIVED_FORM, mFormController.isFormReadOnly()); formReturnIntent.putExtra(KEY_IS_RESTART_AFTER_EXPIRATION, getIntent().getBooleanExtra(KEY_IS_RESTART_AFTER_EXPIRATION, false)); if (reportSaved || hasSaved) { setResult(RESULT_OK, formReturnIntent); } else { setResult(RESULT_CANCELED, formReturnIntent); } } try { CommCareApplication.instance().getSession().unregisterFormSaveCallback(); } catch (SessionUnavailableException sue) { // looks like the session expired, swallow exception because we // might be auto-saving a form due to user session expiring } if (fullFormProfilingEnabled) { // Uncomment 1 of the following expressions for whichever trace serialization format you're interested in //InstrumentationUtils.printAndClearTraces(this.traceReporter, "FULL FORM ENTRY TRACE:", EvaluationTraceSerializer.TraceInfoType.CACHE_INFO_ONLY); //InstrumentationUtils.printExpressionsThatUsedCaching(this.traceReporter, "EXPRESSIONS THAT USED CACHING:"); //InstrumentationUtils.printCachedAndNotCachedExpressions(this.traceReporter, "CACHED AND NOT CACHED EXPRESSIONS:"); } dismissProgressDialog(); reportFormExitTime(); finish(); } @Override protected boolean onBackwardSwipe() { FirebaseAnalyticsUtil.reportFormNav( AnalyticsParamValue.DIRECTION_BACKWARD, AnalyticsParamValue.SWIPE); uiController.showPreviousView(true); return true; } @Override protected boolean onForwardSwipe() { FirebaseAnalyticsUtil.reportFormNav( AnalyticsParamValue.DIRECTION_FORWARD, AnalyticsParamValue.SWIPE); if (canNavigateForward()) { uiController.next(); return true; } else { FormNavigationUI.animateFinishArrow(this); return true; } } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long pressed. // We don't wnat that, so cancel it. if (uiController.questionsView != null) { uiController.questionsView.cancelLongPress(); } return false; } @Override public void advance() { if (canNavigateForward()) { uiController.next(); } } @Override public void widgetEntryChanged(QuestionWidget changedWidget) { try { uiController.recordLastChangedWidgetIndex(changedWidget); uiController.updateFormRelevancies(); } catch (XPathTypeMismatchException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, FormEntryConstants.EXIT); return; } FormNavigationUI.updateNavigationCues(this, mFormController, uiController.questionsView); } private boolean canNavigateForward() { ImageButton nextButton = this.findViewById(R.id.nav_btn_next); return FormEntryConstants.NAV_STATE_NEXT.equals(nextButton.getTag()); } /** * Has form loading (via FormLoaderTask) completed? */ private boolean formHasLoaded() { return mFormController != null; } private void loadStateFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { instanceState.loadState(savedInstanceState); if (savedInstanceState.containsKey(KEY_FORM_LOAD_HAS_TRIGGERED)) { hasFormLoadBeenTriggered = savedInstanceState.getBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, false); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_FAILED)) { hasFormLoadFailed = savedInstanceState.getBoolean(KEY_FORM_LOAD_FAILED, false); } locationRecieverErrorAction = savedInstanceState.getString(KEY_LOC_ERROR); badLocationXpath = savedInstanceState.getString(KEY_LOC_ERROR_PATH); if (savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) { mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED); } if (savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED); } if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) { String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if (savedInstanceState.containsKey(KEY_HEADER_STRING)) { mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING); } if (savedInstanceState.containsKey(KEY_HAS_SAVED)) { hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED); } formEntryRestoreSession.restoreFormEntrySession(savedInstanceState, CommCareApplication.instance().getPrototypeFactory(this)); if (savedInstanceState.containsKey(KEY_WIDGET_WITH_VIDEO_PLAYING)) { indexOfWidgetWithVideoPlaying = savedInstanceState.getInt(KEY_WIDGET_WITH_VIDEO_PLAYING); positionOfVideoProgress = savedInstanceState.getInt(KEY_POSITION_OF_VIDEO_PLAYING); } if (savedInstanceState.containsKey(KEY_IS_READ_ONLY)) { this.instanceIsReadOnly = savedInstanceState.getBoolean(KEY_IS_READ_ONLY); } uiController.restoreSavedState(savedInstanceState); } } private void loadIntentFormData(Intent intent) { instanceState.loadFromIntent(intent); if (intent.hasExtra(KEY_AES_STORAGE_KEY)) { String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if (intent.hasExtra(KEY_HEADER_STRING)) { FormEntryActivity.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING); } if (intent.hasExtra(KEY_INCOMPLETE_ENABLED)) { this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true); } if (intent.hasExtra(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED); } formEntryRestoreSession.loadFromIntent(intent); } private void setTitleToLoading() { if (mHeaderString != null) { setTitle(mHeaderString); } else { setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form)); } } protected String getHeaderString() { if (mHeaderString != null) { //Localization? return mHeaderString; } else { return StringUtils.getStringRobust(this, R.string.application_name) + " > " + FormEntryActivity.mFormController.getFormTitle(); } } @Override @TargetApi(Build.VERSION_CODES.M) public void requestNeededPermissions(int requestCode) { switch (requestCode) { case ImageWidget.REQUEST_CAMERA_PERMISSION: ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, requestCode); return; } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case ImageWidget.REQUEST_CAMERA_PERMISSION: { QuestionWidget pendingWidget = getPendingWidget(); resetPendingCalloutIndex(); // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { pendingWidget.notifyPermission(permissions[0], true); } else { pendingWidget.notifyPermission(permissions[0], false); } return; } } } public static class FormQueryException extends Exception { public FormQueryException(String msg) { super(msg); } } private void setFormLoadFailure() { hasFormLoadFailed = true; } @Override protected void onMajorLayoutChange(Rect newRootViewDimensions) { uiController.recalcShouldHideGroupLabel(newRootViewDimensions); } private void reportFormEntryTime() { TimedStatsTracker.registerEnterForm(getCurrentFormID()); } private void reportFormExitTime() { TimedStatsTracker.registerExitForm(getCurrentFormID()); } private int getCurrentFormID() { return mFormController.getFormID(); } /** * For Testing purposes only */ public QuestionsView getODKView() { if (BuildConfig.DEBUG) { return uiController.questionsView; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } public static String getFormEntrySessionString() { if (mFormController == null) { return ""; } else { return mFormController.getFormEntrySessionString(); } } @Override public void initUIController() { uiController = new FormEntryActivityUIController(this); } @Override public CommCareActivityUIController getUIController() { return uiController; } }
package org.commcare.activities; import android.annotation.SuppressLint; import android.app.ActionBar; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Rect; import android.location.LocationManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore.Images; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.SpannableStringBuilder; import android.util.Log; import android.util.Pair; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextThemeWrapper; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.commcare.CommCareApplication; import org.commcare.activities.components.FormFileSystemHelpers; import org.commcare.activities.components.FormLayoutHelpers; import org.commcare.activities.components.FormNavigationController; import org.commcare.activities.components.FormNavigationUI; import org.commcare.activities.components.FormRelevancyUpdating; import org.commcare.activities.components.ImageCaptureProcessing; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.engine.extensions.IntentCallout; import org.commcare.engine.extensions.PollSensorAction; import org.commcare.interfaces.AdvanceToNextListener; import org.commcare.interfaces.FormSaveCallback; import org.commcare.interfaces.FormSavedListener; import org.commcare.interfaces.WidgetChangedListener; import org.commcare.logging.AndroidLogger; import org.commcare.logging.analytics.GoogleAnalyticsFields; import org.commcare.logging.analytics.GoogleAnalyticsUtils; import org.commcare.logging.analytics.TimedStatsTracker; import org.commcare.logic.FormController; import org.commcare.logic.PropertyManager; import org.commcare.models.ODKStorage; import org.commcare.models.database.DbUtil; import org.commcare.preferences.FormEntryPreferences; import org.commcare.provider.FormsProviderAPI.FormsColumns; import org.commcare.provider.InstanceProviderAPI; import org.commcare.provider.InstanceProviderAPI.InstanceColumns; import org.commcare.tasks.FormLoaderTask; import org.commcare.tasks.SaveToDiskTask; import org.commcare.utils.Base64Wrapper; import org.commcare.utils.FileUtil; import org.commcare.utils.FormUploadUtil; import org.commcare.utils.GeoUtils; import org.commcare.utils.SessionUnavailableException; import org.commcare.utils.StringUtils; import org.commcare.utils.UriToFilePath; import org.commcare.views.QuestionsView; import org.commcare.views.ResizingImageView; import org.commcare.views.UserfacingErrorHandling; import org.commcare.views.dialogs.AlertDialogFactory; import org.commcare.views.dialogs.CustomProgressDialog; import org.commcare.views.dialogs.DialogChoiceItem; import org.commcare.views.dialogs.HorizontalPaneledChoiceDialog; import org.commcare.views.dialogs.PaneledChoiceDialog; import org.commcare.views.widgets.IntentWidget; import org.commcare.views.widgets.QuestionWidget; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.form.api.FormEntrySession; import org.javarosa.form.api.FormEntrySessionReplayer; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathArityException; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.crypto.spec.SecretKeySpec; /** * Displays questions, animates transitions between * questions, and allows the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends SaveSessionCommCareActivity<FormEntryActivity> implements AnimationListener, FormSavedListener, FormSaveCallback, AdvanceToNextListener, WidgetChangedListener { private static final String TAG = FormEntryActivity.class.getSimpleName(); // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_VIDEO_FETCH = 3; public static final int LOCATION_CAPTURE = 5; private static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; private static final int FORM_PREFERENCES_KEY = 8; public static final int INTENT_CALLOUT = 10; private static final int HIERARCHY_ACTIVITY_FIRST_START = 11; public static final int SIGNATURE_CAPTURE = 12; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; // Identifies the gp of the form used to launch form entry private static final String KEY_FORMPATH = "formpath"; public static final String KEY_INSTANCEDESTINATION = "instancedestination"; public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment"; public static final String KEY_FORM_CONTENT_URI = "form_content_uri"; public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri"; public static final String KEY_AES_STORAGE_KEY = "key_aes_storage"; public static final String KEY_HEADER_STRING = "form_header"; public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management"; public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled"; private static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved"; public static final String KEY_FORM_ENTRY_SESSION = "form_entry_session"; public static final String KEY_RECORD_FORM_ENTRY_SESSION = "record_form_entry_session"; /** * Intent extra flag to track if this form is an archive. Used to trigger * return logic when this activity exits to the home screen, such as * whether to redirect to archive view or sync the form. */ public static final String IS_ARCHIVED_FORM = "is-archive-form"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String KEY_FORM_LOAD_HAS_TRIGGERED = "newform"; private static final String KEY_FORM_LOAD_FAILED = "form-failed"; private static final String KEY_LOC_ERROR = "location-not-enabled"; private static final String KEY_LOC_ERROR_PATH = "location-based-xpath-error"; private static final int MENU_LANGUAGES = Menu.FIRST + 1; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 2; private static final int MENU_SAVE = Menu.FIRST + 3; private static final int MENU_PREFERENCES = Menu.FIRST + 4; public static final String NAV_STATE_NEXT = "next"; public static final String NAV_STATE_DONE = "done"; public static final String NAV_STATE_QUIT = "quit"; public static final String NAV_STATE_BACK = "back"; private String mFormPath; // Path to a particular form instance public static String mInstancePath; private String mInstanceDestination; private GestureDetector mGestureDetector; private SecretKeySpec symetricKey = null; public static FormController mFormController; private Animation mInAnimation; private Animation mOutAnimation; private ViewGroup mViewPane; private QuestionsView questionsView; private boolean mIncompleteEnabled = true; private boolean hasFormLoadBeenTriggered = false; private boolean hasFormLoadFailed = false; private String locationRecieverErrorAction = null; private String badLocationXpath = null; // used to limit forward/backward swipes to one per question private boolean isAnimatingSwipe; private boolean isDialogShowing; private FormLoaderTask<FormEntryActivity> mFormLoaderTask; private SaveToDiskTask mSaveToDiskTask; private Uri formProviderContentURI = FormsColumns.CONTENT_URI; private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI; private static String mHeaderString; // Was the form saved? Used to set activity return code. private boolean hasSaved = false; private BroadcastReceiver mLocationServiceIssueReceiver; // marked true if we are in the process of saving a form because the user // database & key session are expiring. Being set causes savingComplete to // broadcast a form saving intent. private boolean savingFormOnKeySessionExpiration = false; private boolean mGroupForcedInvisible = false; private boolean mGroupNativeVisibility = false; private FormEntrySession formEntryRestoreSession; private boolean recordEntrySession; enum AnimationType { LEFT, RIGHT, FADE } @Override @SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addBreadcrumbBar(); // must be at the beginning of any activity that can be called from an external intent try { ODKStorage.createODKDirs(); } catch (RuntimeException e) { Logger.exception(e); UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), EXIT); return; } setupUI(); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager( getApplicationContext())); loadStateFromBundle(savedInstanceState); // Check to see if this is a screen flip or a new form load. Object data = this.getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; mSaveToDiskTask.setFormSavedListener(this); } else if (hasFormLoadBeenTriggered && !hasFormLoadFailed) { // Screen orientation change refreshCurrentView(); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { /* * EventLog accepts only proper Strings as input, but prior to this version, * Android would try to send SpannedStrings to it, thus crashing the app. * This makes sure the title is actually a String. * This fixes bug 174626. */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 && item.getTitleCondensed() != null) { item.setTitleCondensed(item.getTitleCondensed().toString()); } return super.onMenuItemSelected(featureId, item); } @Override public void formSaveCallback() { // note that we have started saving the form savingFormOnKeySessionExpiration = true; // start saving form, which will call the key session logout completion // function when it finishes. saveIncompleteFormToDisk(); } private void registerFormEntryReceiver() { //BroadcastReceiver for: // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged // b) Checking if GPS services are not available mLocationServiceIssueReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.removeStickyBroadcast(intent); badLocationXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH); locationRecieverErrorAction = intent.getAction(); } }; IntentFilter filter = new IntentFilter(); filter.addAction(PollSensorAction.XPATH_ERROR_ACTION); filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED); registerReceiver(mLocationServiceIssueReceiver, filter); } private void setupUI() { setContentView(R.layout.screen_form_entry); ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev); View finishButton = this.findViewById(R.id.nav_btn_finish); TextView finishText = (TextView)finishButton.findViewById(R.id.nav_btn_finish_text); finishText.setText(Localization.get("form.entry.finish.button").toUpperCase()); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_ARROW, GoogleAnalyticsFields.VALUE_FORM_NOT_DONE); FormEntryActivity.this.showNextView(); } }); prevButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!NAV_STATE_QUIT.equals(v.getTag())) { GoogleAnalyticsUtils.reportFormNavBackward(GoogleAnalyticsFields.LABEL_ARROW); FormEntryActivity.this.showPreviousView(true); } else { GoogleAnalyticsUtils.reportFormQuitAttempt(GoogleAnalyticsFields.LABEL_PROGRESS_BAR_ARROW); FormEntryActivity.this.triggerUserQuitInput(); } } }); finishButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_ARROW, GoogleAnalyticsFields.VALUE_FORM_DONE); triggerUserFormComplete(); } }); mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane); requestMajorLayoutUpdates(); if (questionsView != null) { questionsView.teardownView(); } // re-set defaults in case the app got in a bad state. isAnimatingSwipe = false; isDialogShowing = false; questionsView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); outState.putBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, hasFormLoadBeenTriggered); outState.putBoolean(KEY_FORM_LOAD_FAILED, hasFormLoadFailed); outState.putString(KEY_LOC_ERROR, locationRecieverErrorAction); outState.putString(KEY_LOC_ERROR_PATH, badLocationXpath); outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString()); outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString()); outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination); outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled); outState.putBoolean(KEY_HAS_SAVED, hasSaved); outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod); saveFormEntrySession(outState); outState.putBoolean(KEY_RECORD_FORM_ENTRY_SESSION, recordEntrySession); if(symetricKey != null) { try { outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded())); } catch (ClassNotFoundException e) { // we can't really get here anyway, since we couldn't have decoded the string to begin with throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key"); } } } private void saveFormEntrySession(Bundle outState) { if (formEntryRestoreSession != null) { ByteArrayOutputStream objectSerialization = new ByteArrayOutputStream(); try { formEntryRestoreSession.writeExternal(new DataOutputStream(objectSerialization)); outState.putByteArray(KEY_FORM_ENTRY_SESSION, objectSerialization.toByteArray()); } catch (IOException e) { outState.putByteArray(KEY_FORM_ENTRY_SESSION, null); } finally { try { objectSerialization.close(); } catch (IOException e) { Log.w(TAG, "failed to store form entry session in instance bundle"); } } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == FORM_PREFERENCES_KEY) { refreshCurrentView(false); return; } if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { // They pressed 'back' on the first hierarchy screen, so we should assume they want // to back out of form entry all together finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } // request was canceled, so do nothing return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); questionsView.setBinaryData(sb, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), true); break; case SIGNATURE_CAPTURE: boolean saved = ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), false); if (saved) { // attempt to auto-advance if a signature was captured advance(); } break; case IMAGE_CHOOSER: ImageCaptureProcessing.processImageChooserResponse(this, getInstanceFolder(), intent); break; case AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); questionsView.setBinaryData(sl, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: case HIERARCHY_ACTIVITY_FIRST_START: if (resultCode == FormHierarchyActivity.RESULT_XPATH_ERROR) { finish(); } else { // We may have jumped to a new index in hierarchy activity, so refresh refreshCurrentView(false); } break; } } private String getInstanceFolder() { return mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); } public void saveImageWidgetAnswer(ContentValues values) { Uri imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(TAG, "Inserting image returned uri = " + imageURI); questionsView.setBinaryData(imageURI, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } private void processChooserResponse(Intent intent) { // For audio/video capture/chooser, we get the URI from the content provider // then the widget copies the file and makes a new entry in the content provider. Uri media = intent.getData(); String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { // don't let the user select a file that won't be included in the // upload to the server questionsView.clearAnswer(); Toast.makeText(FormEntryActivity.this, Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); } else { questionsView.setBinaryData(media, mFormController); } saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } /** * Search the the current view's widgets for one that has registered a * pending callout with the form controller */ public QuestionWidget getPendingWidget() { FormIndex pendingIndex = mFormController.getPendingCalloutFormIndex(); if (pendingIndex == null) { Logger.log(AndroidLogger.SOFT_ASSERT, "getPendingWidget called when pending callout form index was null"); return null; } for (QuestionWidget q : questionsView.getWidgets()) { if (q.getFormId().equals(pendingIndex)) { return q; } } Logger.log(AndroidLogger.SOFT_ASSERT, "getPendingWidget couldn't find question widget with a form index that matches the pending callout."); return null; } private void processIntentResponse(Intent response){ processIntentResponse(response, false); } private void processIntentResponse(Intent response, boolean cancelled) { // keep track of whether we should auto advance boolean advance = false; boolean quick = false; IntentWidget pendingIntentWidget = (IntentWidget)getPendingWidget(); TreeReference context; if (mFormController.getPendingCalloutFormIndex() != null) { context = mFormController.getPendingCalloutFormIndex().getReference(); } else { context = null; } if(pendingIntentWidget != null) { //Set our instance destination for binary data if needed String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); //get the original intent callout IntentCallout ic = pendingIntentWidget.getIntentCallout(); quick = "quick".equals(ic.getAppearance()); //And process it advance = ic.processResponse(response, context, new File(destination)); ic.setCancelled(cancelled); } refreshCurrentView(); // auto advance if we got a good result and are in quick mode if(advance && quick){ showNextView(); } } private void updateFormRelevancies() { ArrayList<QuestionWidget> oldWidgets = questionsView.getWidgets(); // These 2 calls need to be made here, rather than in the for loop below, because at that // point the widgets will have already started being updated to the values for the new view ArrayList<Vector<SelectChoice>> oldSelectChoices = FormRelevancyUpdating.getOldSelectChoicesForEachWidget(oldWidgets); ArrayList<String> oldQuestionTexts = FormRelevancyUpdating.getOldQuestionTextsForEachWidget(oldWidgets); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> promptsLeftInView = new HashSet<>(); ArrayList<Integer> shouldRemoveFromView = new ArrayList<>(); // Loop through all of the old widgets to determine which ones should stay in the new view for (int i = 0; i < oldWidgets.size(); i++) { FormEntryPrompt oldPrompt = oldWidgets.get(i).getPrompt(); String priorQuestionTextForThisWidget = oldQuestionTexts.get(i); Vector<SelectChoice> priorSelectChoicesForThisWidget = oldSelectChoices.get(i); FormEntryPrompt equivalentNewPrompt = FormRelevancyUpdating.getEquivalentPromptInNewList(newValidPrompts, oldPrompt, priorQuestionTextForThisWidget, priorSelectChoicesForThisWidget); if (equivalentNewPrompt != null) { promptsLeftInView.add(equivalentNewPrompt); } else { // If there is no equivalent prompt in the list of new prompts, then this prompt is // no longer relevant in the new view, so it should get removed shouldRemoveFromView.add(i); } } // Remove "atomically" to not mess up iterations questionsView.removeQuestionsFromIndex(shouldRemoveFromView); // Now go through add add any new prompts that we need for (int i = 0; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if (!promptsLeftInView.contains(prompt)) { // If the old version of this prompt was NOT left in the view, then add it questionsView.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView() { refreshCurrentView(true); } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView(boolean animateLastView) { if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); } int event = mFormController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back to the previous // question. // Also, if we're within a group labeled 'field list', step back to the beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not field-lists, // repeat events, and indexes in field-lists that is not the containing group. while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT || (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList()) || event == FormEntryController.EVENT_REPEAT || (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) { event = mFormController.stepToPreviousEvent(); } //If we're at the beginning of form event, but don't show the screen for that, we need //to get the next valid screen if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { showNextView(true); } else if(event == FormEntryController.EVENT_END_OF_FORM) { showPreviousView(false); } else { QuestionsView current = createView(); showView(current, AnimationType.FADE, animateLastView); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { GoogleAnalyticsUtils.reportOptionsMenuEntry(GoogleAnalyticsFields.CATEGORY_FORM_ENTRY); menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); menu.removeItem(MENU_PREFERENCES); if(mIncompleteEnabled) { menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon( android.R.drawable.ic_menu_save); } menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon( R.drawable.ic_menu_goto); boolean hasMultipleLanguages = (!(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1)); menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled(hasMultipleLanguages); menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.form_entry_settings)).setIcon( android.R.drawable.ic_menu_preferences); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Map<Integer, String> menuIdToAnalyticsEventLabel = createMenuItemToEventMapping(); GoogleAnalyticsUtils.reportOptionsMenuItemEntry( GoogleAnalyticsFields.CATEGORY_FORM_ENTRY, menuIdToAnalyticsEventLabel.get(item.getItemId())); switch (item.getItemId()) { case MENU_LANGUAGES: createLanguageDialog(); return true; case MENU_SAVE: saveFormToDisk(DO_NOT_EXIT); return true; case MENU_HIERARCHY_VIEW: if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Intent pref = new Intent(this, FormEntryPreferences.class); startActivityForResult(pref, FORM_PREFERENCES_KEY); return true; case android.R.id.home: GoogleAnalyticsUtils.reportFormQuitAttempt(GoogleAnalyticsFields.LABEL_NAV_BAR_ARROW); triggerUserQuitInput(); return true; } return super.onOptionsItemSelected(item); } private static Map<Integer, String> createMenuItemToEventMapping() { Map<Integer, String> menuIdToAnalyticsEvent = new HashMap<>(); menuIdToAnalyticsEvent.put(MENU_LANGUAGES, GoogleAnalyticsFields.LABEL_CHANGE_LANGUAGE); menuIdToAnalyticsEvent.put(MENU_SAVE, GoogleAnalyticsFields.LABEL_SAVE_FORM); menuIdToAnalyticsEvent.put(MENU_HIERARCHY_VIEW, GoogleAnalyticsFields.LABEL_FORM_HIERARCHY); menuIdToAnalyticsEvent.put(MENU_PREFERENCES, GoogleAnalyticsFields.LABEL_CHANGE_SETTINGS); return menuIdToAnalyticsEvent; } /** * @return true If the current index of the form controller contains questions */ private boolean currentPromptIsQuestion() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController .getEvent() == FormEntryController.EVENT_GROUP); } private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { return saveAnswersForCurrentScreen(evaluateConstraints, true, false); } /** * Attempt to save the answer(s) in the current screen to into the data model. * * @param failOnRequired Whether or not the constraint evaluation * should return false if the question is only * required. (this is helpful for incomplete * saves) * @param headless running in a process that can't display graphics * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { // only try to save if the current event is a question or a field-list // group boolean success = true; if (isEventQuestionOrListGroup()) { HashMap<FormIndex, IAnswerData> answers = questionsView.getAnswers(); // Sort the answers so if there are multiple errors, we can // bring focus to the first one List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, new Comparator<FormIndex>() { @Override public int compare(FormIndex arg0, FormIndex arg1) { return arg0.compareTo(arg1); } }); for (FormIndex index : indexKeys) { // Within a group, you can only save for question events if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } return success; } private boolean isEventQuestionOrListGroup() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION) || (mFormController.getEvent() == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList()); } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { qw.clearAnswer(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer)); menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { // We don't have the right view here, so we store the View's ID as the // item ID and loop through the possible views to find the one the user // clicked on. for (QuestionWidget qw : questionsView.getWidgets()) { if (item.getItemId() == qw.getId()) { createClearDialog(qw); } } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainCustomNonConfigurationInstance() { // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (mFormController != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } private String getHeaderString() { if(mHeaderString != null) { //Localization? return mHeaderString; } else { return StringUtils.getStringRobust(this, R.string.application_name) + " > " + mFormController.getFormTitle(); } } private QuestionsView createView() { setTitle(getHeaderString()); QuestionsView odkv; // should only be a group here if the event_group is a field-list try { odkv = new QuestionsView(this, mFormController.getQuestionPrompts(), mFormController.getGroupsForCurrentIndex(), mFormController.getWidgetFactory(), this); Log.i(TAG, "created view for group"); } catch (RuntimeException e) { Logger.exception(e); UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), EXIT); // this is badness to avoid a crash. // really a next view should increment the formcontroller, create the view // if the view is null, then keep the current view and pop an error. return new QuestionsView(this); } // Makes a "clear answer" menu pop up on long-click of // select-one/select-multiple questions for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly() && !mFormController.isFormReadOnly() && (qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE || qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) { registerForContextMenu(qw); } } FormNavigationUI.updateNavigationCues(this, mFormController, odkv); return odkv; } @SuppressLint("NewApi") @Override public boolean dispatchTouchEvent(MotionEvent mv) { //We need to ignore this even if it's processed by the action //bar (if one exists) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar bar = getActionBar(); if (bar != null) { View customView = bar.getCustomView(); if (customView != null && customView.dispatchTouchEvent(mv)) { return true; } } } boolean handled = mGestureDetector.onTouchEvent(mv); return handled || super.dispatchTouchEvent(mv); } /** * Determines what should be displayed on the screen. Possible options are: a question, an ask * repeat dialog, or the submit screen. Also saves answers to the data model after checking * constraints. */ private void showNextView() { showNextView(false); } private void showNextView(boolean resuming) { if (currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. return; } } if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) { int event; try{ group_skip: do { event = mFormController.stepToNextEvent(FormEntryController.STEP_OVER_GROUP); switch (event) { case FormEntryController.EVENT_QUESTION: QuestionsView next = createView(); if (!resuming) { showView(next, AnimationType.RIGHT); } else { showView(next, AnimationType.FADE, false); } break group_skip; case FormEntryController.EVENT_END_OF_FORM: // auto-advance questions might advance past the last form quesion triggerUserFormComplete(); break group_skip; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break group_skip; case FormEntryController.EVENT_GROUP: //We only hit this event if we're at the _opening_ of a field //list, so it seems totally fine to do it this way, technically //though this should test whether the index is the field list //host. if (mFormController.indexIsInFieldList() && mFormController.getQuestionPrompts().length != 0) { QuestionsView nextGroupView = createView(); if(!resuming) { showView(nextGroupView, AnimationType.RIGHT); } else { showView(nextGroupView, AnimationType.FADE, false); } break group_skip; } // otherwise it's not a field-list group, so just skip it break; case FormEntryController.EVENT_REPEAT: Log.i(TAG, "repeat: " + mFormController.getFormIndex().getReference()); // skip repeats break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(TAG, "repeat juncture: " + mFormController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(TAG, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } while (event != FormEntryController.EVENT_END_OF_FORM); }catch(XPathTypeMismatchException | XPathArityException e){ UserfacingErrorHandling.logErrorAndShowDialog(this, e, EXIT); } } } /** * Determines what should be displayed between a question, or the start screen and displays the * appropriate view. Also saves answers to the data model without checking constraints. */ private void showPreviousView(boolean showSwipeAnimation) { // The answer is saved on a back swipe, but question constraints are ignored. if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } FormIndex startIndex = mFormController.getFormIndex(); FormIndex lastValidIndex = startIndex; if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = mFormController.stepToPreviousEvent(); //Step backwards until we either find a question, the beginning of the form, //or a field list with valid questions inside while (event != FormEntryController.EVENT_BEGINNING_OF_FORM && event != FormEntryController.EVENT_QUESTION && !(event == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList() && mFormController .getQuestionPrompts().length != 0)) { event = mFormController.stepToPreviousEvent(); lastValidIndex = mFormController.getFormIndex(); } if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { // we can't go all the way back to the beginning, so we've // gotta hit the last index that was valid mFormController.jumpToIndex(lastValidIndex); //Did we jump at all? (not sure how we could have, but there might be a mismatch) if(lastValidIndex.equals(startIndex)) { //If not, don't even bother changing the view. //NOTE: This needs to be the same as the //exit condition below, in case either changes FormEntryActivity.this.triggerUserQuitInput(); return; } //We might have walked all the way back still, which isn't great, //so keep moving forward again until we find it if(lastValidIndex.isBeginningOfFormIndex()) { //there must be a repeat between where we started and the beginning of hte form, walk back up to it this.showNextView(true); return; } } QuestionsView next = createView(); if (showSwipeAnimation) { showView(next, AnimationType.LEFT); } else { showView(next, AnimationType.FADE, false); } } else { FormEntryActivity.this.triggerUserQuitInput(); } } /** * Displays the View specified by the parameter 'next', animating both the current view and next * appropriately given the AnimationType. Also updates the progress bar. */ private void showView(QuestionsView next, AnimationType from) { showView(next, from, true); } private void showView(QuestionsView next, AnimationType from, boolean animateLastView) { switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } if (questionsView != null) { if(animateLastView) { questionsView.startAnimation(mOutAnimation); } mViewPane.removeView(questionsView); questionsView.teardownView(); } mInAnimation.setAnimationListener(this); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); questionsView = next; mViewPane.addView(questionsView, lp); questionsView.startAnimation(mInAnimation); FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); this.mGroupNativeVisibility = false; FormLayoutHelpers.updateGroupViewVisibility(this, mGroupNativeVisibility, mGroupForcedInvisible); questionsView.setFocus(this); SpannableStringBuilder groupLabelText = questionsView.getGroupLabel(); // don't consider '>' char when evaluating whether there's a group label if (groupLabelText != null && !groupLabelText.toString().replace(">","").trim().equals("")) { groupLabel.setText(groupLabelText); this.mGroupNativeVisibility = true; FormLayoutHelpers.updateGroupViewVisibility(this, mGroupNativeVisibility, mGroupForcedInvisible); } } /** * Creates and displays a dialog displaying the violated constraint. */ private void showConstraintWarning(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) { switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: if (constraintText == null) { constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error); } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error); break; } boolean displayed = false; //We need to see if question in violation is on the screen, so we can show this cleanly. for(QuestionWidget q : questionsView.getWidgets()) { if(index.equals(q.getFormId())) { q.notifyInvalid(constraintText, requestFocus); displayed = true; break; } } if(!displayed) { showCustomToast(constraintText, Toast.LENGTH_SHORT); } isAnimatingSwipe = false; } public void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a repeat of the * current group. */ private void createRepeatDialog() { isDialogShowing = true; // Determine the effect that back and next buttons should have FormNavigationController.NavigationDetails details; try { details = FormNavigationController.calculateNavigationStatus(mFormController, questionsView); } catch (XPathTypeMismatchException | XPathArityException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, EXIT); return; } final boolean backExitsForm = !details.relevantBeforeCurrentScreen; final boolean nextExitsForm = details.relevantAfterCurrentScreen == 0; // Assign title and text strings based on the current state String title, addAnotherText, skipText, backText; backText = StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back).toString(); if (mFormController.getLastRepeatCount() > 0) { title = StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat, mFormController.getLastGroupText()).toString(); addAnotherText = StringUtils.getStringSpannableRobust(this, R.string.add_another).toString(); if (!nextExitsForm) { skipText = StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes).toString(); } else { skipText = StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits).toString(); } } else { title = StringUtils.getStringSpannableRobust(this, R.string.add_repeat, mFormController.getLastGroupText()).toString(); addAnotherText = StringUtils.getStringSpannableRobust(this, R.string.entering_repeat).toString(); if (!nextExitsForm) { skipText = StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no).toString(); } else { skipText = StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits).toString(); } } // Create the choice dialog ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme); final PaneledChoiceDialog dialog = new HorizontalPaneledChoiceDialog(wrapper, title); // Panel 1: Back option View.OnClickListener backListener = new OnClickListener() { @Override public void onClick(View v) { if (backExitsForm) { FormEntryActivity.this.triggerUserQuitInput(); } else { dialog.dismiss(); FormEntryActivity.this.refreshCurrentView(false); } } }; int backIconId; if (backExitsForm) { backIconId = R.drawable.icon_exit; } else { backIconId = R.drawable.icon_back; } DialogChoiceItem backItem = new DialogChoiceItem(backText, backIconId, backListener); // Panel 2: Add another option View.OnClickListener addAnotherListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); try { mFormController.newRepeat(); } catch (XPathTypeMismatchException | XPathArityException e) { Logger.exception(e); UserfacingErrorHandling.logErrorAndShowDialog(FormEntryActivity.this, e, EXIT); return; } showNextView(); } }; DialogChoiceItem addAnotherItem = new DialogChoiceItem(addAnotherText, R.drawable.icon_new, addAnotherListener); // Panel 3: Skip option View.OnClickListener skipListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (!nextExitsForm) { showNextView(); } else { triggerUserFormComplete(); } } }; int skipIconId; if (nextExitsForm) { skipIconId = R.drawable.icon_done; } else { skipIconId = R.drawable.icon_next; } DialogChoiceItem skipItem = new DialogChoiceItem(skipText, skipIconId, skipListener); dialog.setChoiceItems(new DialogChoiceItem[]{backItem, addAnotherItem, skipItem}); dialog.makeNotCancelable(); dialog.setOnDismissListener( new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface d) { isDialogShowing = false; } } ); dialog.show(); } private void saveFormToDisk(boolean exit) { if (formHasLoaded()) { boolean isFormComplete = isInstanceComplete(); saveDataToDisk(exit, isFormComplete, null, false); } else if (exit) { showSaveErrorAndExit(); } } private void saveCompletedFormToDisk(String updatedSaveName) { saveDataToDisk(EXIT, true, updatedSaveName, false); } private void saveIncompleteFormToDisk() { saveDataToDisk(EXIT, false, null, true); } private void showSaveErrorAndExit() { Toast.makeText(this, Localization.get("form.entry.save.error"), Toast.LENGTH_SHORT).show(); hasSaved = false; finishReturnInstance(); } /** * Saves form data to disk. * * @param exit If set, will exit program after save. * @param complete Has the user marked the instances as complete? * @param updatedSaveName Set name of the instance's content provider, if * non-null * @param headless Disables GUI warnings and lets answers that * violate constraints be saved. */ private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) { if (!formHasLoaded()) { if (exit) { showSaveErrorAndExit(); } return; } // save current answer; if headless, don't evaluate the constraints // before doing so. boolean wasScreenSaved = saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless); if (!wasScreenSaved) { return; } // If a save task is already running, just let it do its thing if ((mSaveToDiskTask != null) && (mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) { return; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless); if (!headless){ mSaveToDiskTask.connect(this); } mSaveToDiskTask.setFormSavedListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSaveToDiskTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { mSaveToDiskTask.execute(); } } /** * Create a dialog with options to save and exit, save, or quit without saving */ private void createQuitDialog() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, StringUtils.getStringRobust(this, R.string.quit_form_title)); View.OnClickListener stayInFormListener = new View.OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_BACK_TO_FORM); dialog.dismiss(); } }; DialogChoiceItem stayInFormItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.do_not_exit), R.drawable.ic_blue_forward, stayInFormListener); View.OnClickListener exitFormListener = new View.OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_EXIT_NO_SAVE); discardChangesAndExit(); dialog.dismiss(); } }; DialogChoiceItem quitFormItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.do_not_save), R.drawable.icon_exit_form, exitFormListener); DialogChoiceItem[] items; if (mIncompleteEnabled) { View.OnClickListener saveIncompleteListener = new View.OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_SAVE_AND_EXIT); saveFormToDisk(EXIT); dialog.dismiss(); } }; DialogChoiceItem saveIncompleteItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.keep_changes), R.drawable.ic_incomplete_orange, saveIncompleteListener); items = new DialogChoiceItem[] {stayInFormItem, quitFormItem, saveIncompleteItem}; } else { items = new DialogChoiceItem[] {stayInFormItem, quitFormItem}; } dialog.setChoiceItems(items); dialog.show(); } private void discardChangesAndExit() { FormFileSystemHelpers.removeMediaAttachedToUnsavedForm(this, mInstancePath, instanceProviderContentURI); finishReturnInstance(false); } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { String title = StringUtils.getStringRobust(this, R.string.clear_answer_ask); String question = qw.getPrompt().getLongText(); if (question.length() > 50) { question = question.substring(0, 50) + "..."; } String msg = StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question).toString(); AlertDialogFactory factory = new AlertDialogFactory(this, title, msg); factory.setIcon(android.R.drawable.ic_dialog_info); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON_NEGATIVE: break; } dialog.dismiss(); } }; factory.setPositiveButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener); factory.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener); showAlertDialog(factory); } /** * Creates and displays a dialog allowing the user to set the language for the form. */ private void createLanguageDialog() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, StringUtils.getStringRobust(this, R.string.choose_language)); final String[] languages = mFormController.getLanguages(); DialogChoiceItem[] choiceItems = new DialogChoiceItem[languages.length]; for (int i = 0; i < languages.length; i++) { final int index = i; View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { // Update the language in the content provider when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[index]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update(formProviderContentURI, values, selection, selectArgs); Log.i(TAG, "Updated language to: " + languages[index] + " in " + updated + " rows"); mFormController.setLanguage(languages[index]); dialog.dismiss(); if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }; choiceItems[i] = new DialogChoiceItem(languages[i], -1, listener); } dialog.addButton(StringUtils.getStringSpannableRobust(this, R.string.cancel).toString(), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } } ); dialog.setChoiceItems(choiceItems); dialog.show(); } @Override public CustomProgressDialog generateProgressDialog(int id) { CustomProgressDialog dialog = null; switch (id) { case FormLoaderTask.FORM_LOADER_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.loading_form), StringUtils.getStringRobust(this, R.string.please_wait), id); dialog.addCancelButton(); break; case SaveToDiskTask.SAVING_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.saving_form), StringUtils.getStringRobust(this, R.string.please_wait), id); break; } return dialog; } @Override public void taskCancelled() { finish(); } @Override protected void onPause() { super.onPause(); if (questionsView != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (mLocationServiceIssueReceiver != null) { unregisterReceiver(mLocationServiceIssueReceiver); } } @Override protected void onResume() { super.onResume(); if (!hasFormLoadBeenTriggered) { loadForm(); } registerFormEntryReceiver(); if (questionsView != null) { questionsView.restoreTimePickerData(); } if (mFormController != null) { // clear pending callout post onActivityResult processing mFormController.setPendingCalloutFormIndex(null); } } private void loadForm() { mFormController = null; mInstancePath = null; Intent intent = getIntent(); if (intent != null) { loadIntentFormData(intent); setTitleToLoading(); Uri uri = intent.getData(); final String contentType = getContentResolver().getType(uri); Uri formUri; if (contentType == null){ UserfacingErrorHandling.createErrorDialog(this, "form URI resolved to null", EXIT); return; } boolean isInstanceReadOnly = false; try { switch (contentType) { case InstanceColumns.CONTENT_ITEM_TYPE: Pair<Uri, Boolean> instanceAndStatus = getInstanceUri(uri); formUri = instanceAndStatus.first; isInstanceReadOnly = instanceAndStatus.second; break; case FormsColumns.CONTENT_ITEM_TYPE: formUri = uri; mFormPath = FormFileSystemHelpers.getFormPath(this, uri); break; default: Log.e(TAG, "unrecognized URI"); UserfacingErrorHandling.createErrorDialog(this, "unrecognized URI: " + uri, EXIT); return; } } catch (FormQueryException e) { UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), EXIT); return; } if(formUri == null) { Log.e(TAG, "unrecognized URI"); UserfacingErrorHandling.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask<FormEntryActivity>(symetricKey, isInstanceReadOnly, recordEntrySession, this) { @Override protected void deliverResult(FormEntryActivity receiver, FECWrapper wrapperResult) { receiver.handleFormLoadCompletion(wrapperResult.getController()); } @Override protected void deliverUpdate(FormEntryActivity receiver, String... update) { } @Override protected void deliverError(FormEntryActivity receiver, Exception e) { receiver.setFormLoadFailure(); receiver.dismissProgressDialog(); if (e != null) { UserfacingErrorHandling.createErrorDialog(receiver, e.getMessage(), EXIT); } else { UserfacingErrorHandling.createErrorDialog(receiver, StringUtils.getStringRobust(receiver, R.string.parse_error), EXIT); } } }; mFormLoaderTask.connect(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mFormLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, formUri); } else { mFormLoaderTask.execute(formUri); } hasFormLoadBeenTriggered = true; } } private void handleFormLoadCompletion(FormController fc) { if (GeoUtils.ACTION_CHECK_GPS_ENABLED.equals(locationRecieverErrorAction)) { handleNoGpsBroadcast(); } else if (PollSensorAction.XPATH_ERROR_ACTION.equals(locationRecieverErrorAction)) { handleXpathErrorBroadcast(); } mFormController = fc; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ // Newer menus may have already built the menu, before all data was ready invalidateOptionsMenu(); } Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced(); if(mLocalizer != null){ String mLocale = mLocalizer.getLocale(); if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){ fc.setLanguage(mLocale); } else{ Logger.log("formloader", "The current locale is not set"); } } else{ Logger.log("formloader", "Could not get the localizer"); } registerSessionFormSaveCallback(); // Set saved answer path if (mInstancePath == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss") .format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = mInstanceDestination + file + "_" + time; if (FileUtil.createFolder(path)) { mInstancePath = path + "/" + file + "_" + time + ".xml"; } } else { // we've just loaded a saved form, so start in the hierarchy view Intent i = new Intent(FormEntryActivity.this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START); return; // so we don't show the intro screen before jumping to the hierarchy } reportFormEntry(); try { FormEntrySessionReplayer.tryReplayingFormEntry(mFormController.getFormEntryController(), formEntryRestoreSession); } catch (FormEntrySessionReplayer.ReplayError e) { UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), EXIT); } refreshCurrentView(); FormNavigationUI.updateNavigationCues(this, mFormController, questionsView); } private void handleNoGpsBroadcast() { LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Set<String> providers = GeoUtils.evaluateProviders(manager); if (providers.isEmpty()) { DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { if (i == DialogInterface.BUTTON_POSITIVE) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } dialog.dismiss(); } }; GeoUtils.showNoGpsDialog(this, onChangeListener); } } private void handleXpathErrorBroadcast() { UserfacingErrorHandling.createErrorDialog(FormEntryActivity.this, "There is a bug in one of your form's XPath Expressions \n" + badLocationXpath, EXIT); } /** * Call when the user provides input that they want to quit the form */ private void triggerUserQuitInput() { if(!formHasLoaded()) { finish(); } else if (mFormController.isFormReadOnly()) { // If we're just reviewing a read only form, don't worry about saving // or what not, just quit // It's possible we just want to "finish" here, but // I don't really wanna break any c compatibility finishReturnInstance(false); } else { createQuitDialog(); return; } GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_NO_DIALOG); } /** * Get the default title for ODK's "Form title" field */ private String getDefaultFormTitle() { String saveName = mFormController.getFormTitle(); if (InstanceColumns.CONTENT_ITEM_TYPE.equals(getContentResolver().getType(getIntent().getData()))) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance != null && instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } return saveName; } /** * Call when the user is ready to save and return the current form as complete */ private void triggerUserFormComplete() { if (mFormController.isFormReadOnly()) { finishReturnInstance(false); } else { saveCompletedFormToDisk(getDefaultFormTitle()); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: GoogleAnalyticsUtils.reportFormQuitAttempt(GoogleAnalyticsFields.LABEL_DEVICE_BUTTON); triggerUserQuitInput(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showPreviousView(true); return true; } break; } return super.onKeyDown(keyCode, event); } private boolean shouldIgnoreSwipeAction() { return isAnimatingSwipe || isDialogShowing; } @Override protected void onDestroy() { if (mFormLoaderTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } super.onDestroy(); } @Override public void onAnimationEnd(Animation arg0) { isAnimatingSwipe = false; } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } private void registerSessionFormSaveCallback() { if (mFormController != null && !mFormController.isFormReadOnly()) { try { // CommCareSessionService will call this.formSaveCallback when // the key session is closing down and we need to save any // intermediate results before they become un-saveable. CommCareApplication._().getSession().registerFormSaveCallback(this); } catch (SessionUnavailableException e) { Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Couldn't register form save callback because session doesn't exist"); } } } /** * {@inheritDoc} * * Display save status notification and exit or continue on in the form. * If form entry is being saved because key session is expiring then * continue closing the session/logging out. */ @Override public void savingComplete(SaveToDiskTask.SaveStatus saveStatus, String errorMessage) { // Did we just save a form because the key session // (CommCareSessionService) is ending? if (savingFormOnKeySessionExpiration) { savingFormOnKeySessionExpiration = false; // Notify the key session that the form state has been saved (or at // least attempted to be saved) so CommCareSessionService can // continue closing down key pool and user database. CommCareApplication._().expireUserSession(); } else if (saveStatus != null) { switch (saveStatus) { case SAVED_COMPLETE: Toast.makeText(this, Localization.get("form.entry.complete.save.success"), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SAVED_INCOMPLETE: Toast.makeText(this, Localization.get("form.entry.incomplete.save.success"), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SAVED_AND_EXIT: Toast.makeText(this, Localization.get("form.entry.complete.save.success"), Toast.LENGTH_SHORT).show(); hasSaved = true; finishReturnInstance(); break; case INVALID_ANSWER: // an answer constraint was violated, so try to save the // current question to trigger the constraint violation message refreshCurrentView(); saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS); return; case SAVE_ERROR: UserfacingErrorHandling.createErrorDialog(this, errorMessage, Localization.get("notification.formentry.save_error.title"), EXIT); return; } refreshCurrentView(); } } /** * Attempts to save an answer to the specified index. * * @param evaluateConstraints Should form constraints be checked when saving answer? * @return status as determined in FormEntryController */ private int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { try { if (evaluateConstraints) { return mFormController.answerQuestion(index, answer); } else { mFormController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } catch (XPathException e) { //this is where runtime exceptions get triggered after the form has loaded UserfacingErrorHandling.logErrorAndShowDialog(this, e, EXIT); //We're exiting anyway return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has already been * 'marked completed'. A form can be 'unmarked' complete and then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete() { // default to false if we're mid form boolean complete = false; // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } private void next() { if (!shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showNextView(); } } private void finishReturnInstance() { finishReturnInstance(true); } /** * Returns the instance that was just filled out to the calling activity, * if requested. * * @param reportSaved was a form saved? Delegates the result code of the * activity */ private void finishReturnInstance(boolean reportSaved) { String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id); Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly()); if (reportSaved || hasSaved) { setResult(RESULT_OK, formReturnIntent.setData(instance)); } else { setResult(RESULT_CANCELED, formReturnIntent.setData(instance)); } } } finally { if (c != null) { c.close(); } } } try { CommCareApplication._().getSession().unregisterFormSaveCallback(); } catch (SessionUnavailableException sue) { // looks like the session expired } dismissProgressDialog(); reportFormExit(); finish(); } @Override protected boolean onBackwardSwipe() { GoogleAnalyticsUtils.reportFormNavBackward(GoogleAnalyticsFields.LABEL_SWIPE); showPreviousView(true); return true; } @Override protected boolean onForwardSwipe() { if (canNavigateForward()) { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_SWIPE, GoogleAnalyticsFields.VALUE_FORM_NOT_DONE); next(); return true; } else { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_SWIPE, GoogleAnalyticsFields.VALUE_FORM_DONE); FormNavigationUI.animateFinishArrow(this); return true; } } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long pressed. // We don't wnat that, so cancel it. if (questionsView != null) { questionsView.cancelLongPress(); } return false; } @Override public void advance() { if (!questionsView.isQuestionList() && canNavigateForward()) { next(); } } @Override public void widgetEntryChanged() { try { updateFormRelevancies(); } catch (XPathTypeMismatchException | XPathArityException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, EXIT); return; } FormNavigationUI.updateNavigationCues(this, mFormController, questionsView); } private boolean canNavigateForward() { ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); return NAV_STATE_NEXT.equals(nextButton.getTag()); } /** * Has form loading (via FormLoaderTask) completed? */ private boolean formHasLoaded() { return mFormController != null; } private void addBreadcrumbBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final String fragmentClass = this.getIntent().getStringExtra(TITLE_FRAGMENT_TAG); if (fragmentClass != null) { final FragmentManager fm = this.getSupportFragmentManager(); Fragment bar = fm.findFragmentByTag(TITLE_FRAGMENT_TAG); if (bar == null) { try { bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance(); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit(); } catch(Exception e) { Log.w(TAG, "couldn't instantiate fragment: " + fragmentClass); } } } } } private void loadStateFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_HAS_TRIGGERED)) { hasFormLoadBeenTriggered = savedInstanceState.getBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, false); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_FAILED)) { hasFormLoadFailed = savedInstanceState.getBoolean(KEY_FORM_LOAD_FAILED, false); } locationRecieverErrorAction = savedInstanceState.getString(KEY_LOC_ERROR); badLocationXpath = savedInstanceState.getString(KEY_LOC_ERROR_PATH); if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) { formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) { instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) { mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION); } if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) { mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED); } if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED); } if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) { String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(savedInstanceState.containsKey(KEY_HEADER_STRING)) { mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING); } if(savedInstanceState.containsKey(KEY_HAS_SAVED)) { hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED); } restoreFormEntrySession(savedInstanceState); recordEntrySession = savedInstanceState.getBoolean(KEY_RECORD_FORM_ENTRY_SESSION, false); } } private void restoreFormEntrySession(Bundle savedInstanceState) { byte[] serializedObject = savedInstanceState.getByteArray(KEY_FORM_ENTRY_SESSION); if (serializedObject != null) { formEntryRestoreSession = new FormEntrySession(); DataInputStream objectInputStream = new DataInputStream(new ByteArrayInputStream(serializedObject)); try { formEntryRestoreSession.readExternal(objectInputStream, DbUtil.getPrototypeFactory(this)); } catch (IOException | DeserializationException e) { Log.e(TAG, "failed to deserialize form entry session during saved instance restore"); } finally { try { objectInputStream.close(); } catch (IOException e) { Log.e(TAG, "failed to close deserialization stream for form entry session during saved instance restore"); } } } } private Pair<Uri, Boolean> getInstanceUri(Uri uri) throws FormQueryException { Cursor instanceCursor = null; Cursor formCursor = null; Boolean isInstanceReadOnly = false; Uri formUri = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor == null) { throw new FormQueryException("Bad URI: resolved to null"); } else if (instanceCursor.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { instanceCursor.moveToFirst(); mInstancePath = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String jrFormId = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); //If this form is both already completed if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) { if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) { isInstanceReadOnly = true; } } final String[] selectionArgs = { jrFormId }; final String selection = FormsColumns.JR_FORM_ID + " like ?"; formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null); if (formCursor == null || formCursor.getCount() < 1) { throw new FormQueryException("Parent form does not exist"); } else if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor.getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID))); } else if (formCursor.getCount() > 1) { throw new FormQueryException("More than one possible parent form"); } } } finally { if (instanceCursor != null) { instanceCursor.close(); } if (formCursor != null) { formCursor.close(); } } return new Pair<>(formUri, isInstanceReadOnly); } private void loadIntentFormData(Intent intent) { if(intent.hasExtra(KEY_FORM_CONTENT_URI)) { this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) { this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCEDESTINATION)) { this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION); } else { mInstanceDestination = ODKStorage.INSTANCES_PATH; } if(intent.hasExtra(KEY_AES_STORAGE_KEY)) { String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(intent.hasExtra(KEY_HEADER_STRING)) { FormEntryActivity.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING); } if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) { this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true); } if(intent.hasExtra(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED); } if (intent.hasExtra(KEY_FORM_ENTRY_SESSION)) { formEntryRestoreSession = FormEntrySession.fromString(intent.getStringExtra(KEY_FORM_ENTRY_SESSION)); } recordEntrySession = intent.getBooleanExtra(KEY_RECORD_FORM_ENTRY_SESSION, false); } private void setTitleToLoading() { if(mHeaderString != null) { setTitle(mHeaderString); } else { setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form)); } } public static class FormQueryException extends Exception { public FormQueryException(String msg) { super(msg); } } private void setFormLoadFailure() { hasFormLoadFailed = true; } @Override protected void onMajorLayoutChange(Rect newRootViewDimensions) { mGroupForcedInvisible = FormLayoutHelpers.determineNumberOfValidGroupLines(this, newRootViewDimensions, mGroupNativeVisibility, mGroupForcedInvisible); } private void reportFormEntry() { TimedStatsTracker.registerEnterForm(getCurrentFormID()); } private void reportFormExit() { TimedStatsTracker.registerExitForm(getCurrentFormID()); } private int getCurrentFormID() { return mFormController.getFormID(); } /** * For Testing purposes only */ public QuestionsView getODKView() { if (BuildConfig.DEBUG) { return questionsView; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } public static String getFormEntrySessionString() { if (mFormController == null) { return ""; } else { return mFormController.getFormEntrySessionString(); } } }
// Optics.java // xal package xal.app.opticseditor; import xal.tools.data.*; import xal.tools.xml.XmlDataAdaptor; import java.io.File; import java.net.URL; import java.util.*; /** Optics Model */ public class Optics { /** node records */ final private List<NodeRecord> _nodeRecords; /** base URL */ final private URL BASE_URL; /** hardware status URL */ private URL _hardwareStatusURL; /** Constructor */ public Optics( final URL baseURL, final String designURLSpec, final String hardwareStatusURLSpec ) { try { BASE_URL = baseURL; final Map<String, NodeRecord> records = new HashMap<String, NodeRecord>(); if ( baseURL != null ) { if ( designURLSpec != null ) { final URL designURL = new URL( baseURL, designURLSpec ); final DataAdaptor designAdaptor = XmlDataAdaptor.adaptorForUrl( designURL, false ); loadNodesFromOpticsAdaptor( designAdaptor, records ); if ( hardwareStatusURLSpec != null ) { final URL hardwareStatusURL = new URL( baseURL, hardwareStatusURLSpec ); _hardwareStatusURL = hardwareStatusURL; final DataAdaptor hardwareStatusAdaptor = XmlDataAdaptor.adaptorForUrl( hardwareStatusURL, false ); loadNodesFromOpticsAdaptor( hardwareStatusAdaptor, records ); } } } final List<NodeRecord> nodeRecords = new ArrayList<NodeRecord>( records.values() ); Collections.sort( nodeRecords ); _nodeRecords = nodeRecords; } catch ( Exception exception ) { exception.printStackTrace(); throw new RuntimeException( "Exception loading optics.", exception ); } } /** load the nodes design nodes from the Optics adaptor */ private void loadNodesFromOpticsAdaptor( final DataAdaptor opticsAdaptor, final Map<String, NodeRecord> records ) { final DataAdaptor acceleratorAdaptor = opticsAdaptor.childAdaptor( "xdxf" ); final List<DataAdaptor> sequenceAdaptors = acceleratorAdaptor.childAdaptors( "sequence" ); for ( final DataAdaptor sequenceAdaptor : sequenceAdaptors ) { loadNodesFromSequenceAdaptor( sequenceAdaptor, records ); } } /** load the nodes design nodes from the sequence adaptor */ private void loadNodesFromSequenceAdaptor( final DataAdaptor sequenceAdaptor, final Map<String, NodeRecord> records ) { final String sequenceID = sequenceAdaptor.stringValue( "id" ); final List<DataAdaptor> nodeAdaptors = sequenceAdaptor.childAdaptors( "node" ); for ( final DataAdaptor nodeAdaptor : nodeAdaptors ) { final String nodeID = nodeAdaptor.stringValue( "id" ); final boolean status = nodeAdaptor.hasAttribute( "status" ) ? nodeAdaptor.booleanValue( "status" ) : true; final boolean exclude = nodeAdaptor.hasAttribute( "exclude" ) ? nodeAdaptor.booleanValue( "exclude" ) : false; final String modComment = nodeAdaptor.hasAttribute( "mod-comment" ) ? nodeAdaptor.stringValue( "mod-comment" ) : null; if ( records.containsKey( nodeID ) ) { final NodeRecord record = records.get( nodeID ); record.setStatus( status ); record.setExclude( exclude ); record.setModificationComment( modComment ); } else { final NodeRecord record = new NodeRecord( nodeID, sequenceID, status, exclude, modComment ); records.put( nodeID, record ); } } } /** get the node records */ public List<NodeRecord> getNodeRecords() { return _nodeRecords; } /** * save the hardware status file * @return true upon success and false otherwise */ protected boolean save( final OpticsEditorDocument document ) throws Exception { if ( _hardwareStatusURL == null ) { if ( !createHardwareStatusFile( document ) ) { return false; } } final XmlDataAdaptor hardwareStatusAdaptor = XmlDataAdaptor.newEmptyDocumentAdaptor(); final DataAdaptor opticsAdaptor = hardwareStatusAdaptor.createChild( "xdxf" ); opticsAdaptor.setValue( "version", "1.0.0" ); opticsAdaptor.setValue( "date", new Date().toString() ); writeSequences( opticsAdaptor ); hardwareStatusAdaptor.writeToUrl( _hardwareStatusURL ); return true; } /** create a hardware status file */ private boolean createHardwareStatusFile( final OpticsEditorDocument document ) throws Exception { final XmlDataAdaptor baseAdaptor = XmlDataAdaptor.adaptorForUrl( BASE_URL, false ); final DataAdaptor sourcesAdaptor = baseAdaptor.childAdaptor( "sources" ); final DataAdaptor hardwareStatusRefAdaptor = sourcesAdaptor.createChild( "hardware_status" ); hardwareStatusRefAdaptor.setValue( "name", "Hardware Status" ); final String hardwareStatusURLSpec = document.newHardwareStatusURLSpec( BASE_URL ); if ( hardwareStatusURLSpec != null ) { hardwareStatusRefAdaptor.setValue( "url", hardwareStatusURLSpec ); _hardwareStatusURL = new URL( BASE_URL, hardwareStatusURLSpec ); baseAdaptor.writeToUrl( BASE_URL ); return true; } else { return false; } } /** write the modified sequences to the optics adaptor */ private void writeSequences( final DataAdaptor opticsAdaptor ) { // determine the modified node records and organize them by sequence final Map<String, List<NodeRecord>> modificationTable = new HashMap<String, List<NodeRecord>>(); for ( final NodeRecord record : _nodeRecords ) { if ( record.isModified() ) { final String sequenceID = record.getSequenceID(); if ( modificationTable.containsKey( sequenceID ) ) { modificationTable.get( sequenceID ).add( record ); } else { final List<NodeRecord> nodeRecords = new ArrayList<NodeRecord>(); nodeRecords.add( record ); modificationTable.put( sequenceID, nodeRecords ); } } } modificationTable.entrySet().forEach((entry) -> { final DataAdaptor sequenceAdaptor = opticsAdaptor.createChild( "sequence" ); sequenceAdaptor.setValue( "id", entry.getKey() ); final List<NodeRecord> records = entry.getValue(); writeNodes( sequenceAdaptor, records ); }); } /** write the node records to the specified sequence adaptor */ private void writeNodes( final DataAdaptor sequenceAdaptor, final List<NodeRecord> records ) { for ( final NodeRecord record : records ) { final DataAdaptor nodeAdaptor = sequenceAdaptor.createChild( "node" ); record.writeTo( nodeAdaptor ); } } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.tools; import net.opentsdb.utils.Config; /** * Various options to use during fsck over OpenTSDB tables */ final class FsckOptions { private boolean fix; private boolean compact; private boolean resolve_dupes; private boolean last_write_wins; private boolean delete_orphans; private boolean delete_unknown_columns; private boolean delete_bad_values; private boolean delete_bad_rows; private boolean delete_bad_compacts; private int threads; private long fix_timeout; // fix timeout for each operation results, time unit: milliseconds private boolean fix_in_sync_mode = false; // wait for each fix operation to finish to continue public FsckOptions(final ArgP argp, final Config config) { fix = argp.has("--fix") || argp.has("--fix-all"); compact = argp.has("--compact") || argp.has("--fix-all"); resolve_dupes = argp.has("--resolve-duplicates") || argp.has("--fix-all"); last_write_wins = argp.has("--last-write-wins") || config.getBoolean("tsd.storage.fix_duplicates"); delete_orphans = argp.has("--delete-orphans") || argp.has("--fix-all"); delete_unknown_columns = argp.has("--delete-unknown-columns") || argp.has("--fix-all"); delete_bad_values = argp.has("--delete-bad-values") || argp.has("--fix-all"); delete_bad_rows = argp.has("--delete-bad-rows") || argp.has("--fix-all"); delete_bad_compacts = argp.has("--delete-bad-compacts") || argp.has("--fix-all"); fix_in_sync_mode = argp.has("--sync"); if (argp.has("--threads")) { threads = Integer.parseInt(argp.get("--threads")); if (threads < 1) { throw new IllegalArgumentException("Must have at least one thread"); } if (threads > Runtime.getRuntime().availableProcessors() * 4) { throw new IllegalArgumentException( "Not allowed to run more than 4 threads per core"); } } else { threads = 0; } } /** * Add data table fsck options to the command line parser * @param argp The parser to add options to */ public static void addDataOptions(final ArgP argp) { argp.addOption("--full-scan", "Scan the entire data table."); argp.addOption("--fix", "Fix errors as they're found. Use in combination with" + " other flags."); argp.addOption("--fix-all", "Set all flags and fix errors as they're found."); argp.addOption("--compact", "Compacts rows after parsing."); argp.addOption("--resolve-duplicates", "Keeps the oldest (default) or newest duplicates. See --last-write-wins"); argp.addOption("--last-write-wins", "Last data point written will be kept when fixing duplicates.\n" + " May be set via config file and the 'tsd.storage.fix_duplicates' option."); argp.addOption("--delete-orphans", "Delete any time series rows where one or more UIDs fail resolution."); argp.addOption("--delete-unknown-columns", "Delete any unrecognized column that doesn't belong to OpenTSDB."); argp.addOption("--delete-bad-values", "Delete single column datapoints with bad values."); argp.addOption("--delete-bad-rows", "Delete rows with invalid keys."); argp.addOption("--delete-bad-compacts", "Delete compacted columns that cannot be parsed."); argp.addOption("--threads", "NUMBER", "Number of threads to use when executing a full table scan."); argp.addOption("--sync", "Wait for each fix operation to finish to continue."); } /** @return Whether or not to fix errors while processing. Does not affect * compacting */ public boolean fix() { return fix; } /** @return Whether or not to compact rows while processing. Can cause * compaction without the --fix flag. Will skip rows with duplicate data * points unless --last-write-wins is also specified or set in the config * file */ public boolean compact() { return compact; } /** @return Whether or not to fix duplicates */ public boolean resolveDupes() { return resolve_dupes; } /** @return Accept data points with the most recent timestamp when duplicates * are found */ public boolean lastWriteWins() { return last_write_wins; } /** @return Whether or not to delete rows where the UIDs failed to resolve * to a name */ public boolean deleteOrphans() { return delete_orphans; } /** @return Delete columns that aren't recognized */ public boolean deleteUnknownColumns() { return delete_unknown_columns; } /** @return Remove data points with bad values */ public boolean deleteBadValues() { return delete_bad_values; } /** @return Remove rows with invalid keys */ public boolean deleteBadRows() { return delete_bad_rows; } /** @return Remove compacted columns that can't be parsed */ public boolean deleteBadCompacts() { return delete_bad_compacts; } /** @return The number of threads to run. If 0, default to cores * 2 */ public int threads() { return threads; } /** @param fix Whether or not to fix errors while processing. Does not affect * compacting */ public void setFix(final boolean fix) { this.fix = fix; } /** @param compact Whether or not to compact rows while processing. Can cause * compaction without the --fix flag. Will skip rows with duplicate data * points unless --last-write-wins is also specified or set in the config * file */ public void setCompact(final boolean compact) { this.compact = compact; } /** @param fix_dupes Whether or not to fix duplicate data points */ public void setResolveDupes(final boolean fix_dupes) { this.resolve_dupes = fix_dupes; } /** @param last_write_wins Accept data points with the most recent timestamp when duplicates * are found */ public void setLastWriteWins(final boolean last_write_wins) { this.last_write_wins = last_write_wins; } /** @param delete_orphans Whether or not to delete rows where the UIDs failed to resolve * to a name */ public void setDeleteOrphans(final boolean delete_orphans) { this.delete_orphans = delete_orphans; } /** @param delete_unknown_columns Delete columns that aren't recognized */ public void setDeleteUnknownColumns(final boolean delete_unknown_columns) { this.delete_unknown_columns = delete_unknown_columns; } /** @param delete_bad_values Remove data points with bad values */ public void setDeleteBadValues(final boolean delete_bad_values) { this.delete_bad_values = delete_bad_values; } /** @param delete_bad_rows Remove data points with invalid keys */ public void setDeleteBadRows(final boolean delete_bad_rows) { this.delete_bad_rows = delete_bad_rows; } /** @param delete_bad_compacts Remove compated columns that can't be parsed */ public void setDeleteBadCompacts(final boolean delete_bad_compacts) { this.delete_bad_compacts = delete_bad_compacts; } public void setThreads(final int threads) { if (threads < 1) { throw new IllegalArgumentException("Must have at least one thread"); } if (threads > Runtime.getRuntime().availableProcessors() * 4) { throw new IllegalArgumentException( "Not allowed to run more than 4 threads per core"); } this.threads = threads; } /** * @param timeout The maximum time to wait in milliseconds. A value of 0 * means no timeout. */ public void setFixTimeout(long timeout) { this.fix_timeout = timeout; } /** * @return timeout */ public long getFixTimeout() { return this.fix_timeout; } /** * @param flag Wheather to wait for the result of the fix operation. */ public void setFixInSync(boolean flag) { this.fix_in_sync_mode = flag; } /** * Wait for each fix operation to finish to continue. * @return true if in sync mode */ public boolean fixInSync() { return this.fix_in_sync_mode; } }
package tp.pr5.logic; import tp.pr5.Resources.Counter; public abstract class Move { protected int column; protected int row; protected Counter currentPlayer; public Move(Counter color, int column) { currentPlayer = color; this.column = column; } // ejecutaMovimiento(Tablero tab) public abstract boolean executeMove(Board board) throws InvalidMove; // getJugador() devuelve el color del jugador al que pertenece el movimiento public Counter getPlayer() { return currentPlayer; } // undo(Tablero tab) deshace el ultimo movimiento del tablero recibido como parametro public abstract void undo(Board board); public abstract int getColumn(); public abstract int getRow(); // Devuelve si es posible formar tiles en celdas empty public boolean availableEmpty(Board board) { return true; } public Counter getCurrentPlayer() { return this.currentPlayer; } public void setCurrentPlayer(Counter c) { currentPlayer = c; } }
package traci.math; public class Matrix { private static final Matrix EYE = newEye(); private final double[] data; private Matrix() { data = new double[16]; } public double at(final int row, final int col) { return data[row * 4 + col]; } private static Matrix newEye() { final Matrix res = newZero(); res.data[0] = 1.0; res.data[5] = 1.0; res.data[10] = 1.0; res.data[15] = 1.0; return res; } private static Matrix newZero() { return new Matrix(); } static Matrix eye() { return EYE; } static Matrix rotx(final double theta) { return rotx(Math.sin(theta), Math.cos(theta)); } static Matrix rotx(final double sinTheta, final double cosTheta) { final Matrix res = newZero(); res.data[0] = 1.0; res.data[5] = cosTheta; res.data[6] = -sinTheta; res.data[9] = sinTheta; res.data[10] = cosTheta; res.data[15] = 1.0; return res; } static Matrix roty(final double theta) { return roty(Math.sin(theta), Math.cos(theta)); } static Matrix roty(final double sinTheta, final double cosTheta) { final Matrix res = newZero(); res.data[0] = cosTheta; res.data[2] = sinTheta; res.data[5] = 1.0; res.data[8] = -sinTheta; res.data[10] = cosTheta; res.data[15] = 1.0; return res; } static Matrix rotz(final double theta) { return rotz(Math.sin(theta), Math.cos(theta)); } static Matrix rotz(final double sinTheta, final double cosTheta) { final Matrix res = newZero(); res.data[0] = cosTheta; res.data[1] = -sinTheta; res.data[4] = sinTheta; res.data[5] = cosTheta; res.data[10] = 1.0; res.data[15] = 1.0; return res; } static Matrix scale(final Vector scale) { final Matrix res = newZero(); res.data[0] = scale.x(); res.data[5] = scale.y(); res.data[10] = scale.z(); res.data[15] = 1.0; return res; } static Matrix translate(final Vector translate) { final Matrix res = newEye(); res.data[3] = translate.x(); res.data[7] = translate.y(); res.data[11] = translate.z(); return res; } static Matrix make(final Vector v0, final Vector v1, final Vector v2) { final Matrix res = newZero(); res.data[0] = v0.x(); res.data[4] = v0.y(); res.data[8] = v0.z(); res.data[1] = v1.x(); res.data[5] = v1.y(); res.data[9] = v1.z(); res.data[2] = v2.x(); res.data[6] = v2.y(); res.data[10] = v2.z(); res.data[15] = 1.0; return res; } Matrix mul(final Matrix mat) { final Matrix res = newZero(); for (int row = 0; row < 4; ++row) { for (int col = 0; col < 4; ++col) { res.data[row * 4 + col] = data[row * 4 + 0] * mat.data[0 * 4 + col] + data[row * 4 + 1] * mat.data[1 * 4 + col] + data[row * 4 + 2] * mat.data[2 * 4 + col] + data[row * 4 + 3] * mat.data[3 * 4 + col]; } } return res; } Vector mul(final Vector vec) { final double vx = vec.x(); final double vy = vec.y(); final double vz = vec.z(); final double[] tmpData = data; return Vector.make(vx * tmpData[0] + vy * tmpData[1] + vz * tmpData[2] + tmpData[3], vx * tmpData[4] + vy * tmpData[5] + vz * tmpData[6] + tmpData[7], vx * tmpData[8] + vy * tmpData[9] + vz * tmpData[10] + tmpData[11]); } Vector mulDir(final Vector vec) { final double vx = vec.x(); final double vy = vec.y(); final double vz = vec.z(); final double[] tmpData = data; return Vector.make(vx * tmpData[0] + vy * tmpData[1] + vz * tmpData[2], vx * tmpData[4] + vy * tmpData[5] + vz * tmpData[6], vx * tmpData[8] + vy * tmpData[9] + vz * tmpData[10]); } Vector mulNormal(final Vector vec) { final double vx = vec.x(); final double vy = vec.y(); final double vz = vec.z(); final double[] tmpData = data; return Vector.make(vx * tmpData[0] + vy * tmpData[4] + vz * tmpData[8], vx * tmpData[1] + vy * tmpData[5] + vz * tmpData[9], vx * tmpData[2] + vy * tmpData[6] + vz * tmpData[10]); } @Override public int hashCode() { int hash = 0; for (int i = 0; i < data.length; ++i) { hash = 31 * hash + Double.valueOf(data[i]).hashCode(); } return hash; } @Override public boolean equals(final Object other) { if (other == null) { return false; } else if (other == this) { return true; } else if (other.getClass() != getClass()) { return false; } final Matrix otherMatrix = (Matrix) other; for (int i = 0; i < data.length; ++i) { if (!Double.valueOf(data[i]).equals(Double.valueOf(otherMatrix.data[i]))) { return false; } } return true; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append("[ ["); for (int row = 0; row < 4; ++row) { if (row > 0) { buf.append("\n ["); } for (int col = 0; col < 4; ++col) { buf.append(' '); buf.append(data[row * 4 + col]); } buf.append(" ]"); } buf.append(" ]"); return buf.toString(); } }
package utilities; import interfaces.TimerTimeout; import javax.swing.JPanel; import java.applet.Applet; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.Color; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Font; public class MyTimer extends JPanel { private static final long serialVersionUID = -6457684504590405968L; private JLabel lblTime; private TimerTimeout event; private Timer timer; private int seconds; private boolean sound; private boolean visual; private boolean running; private AudioClip countdown; private AudioClip timeoutHorn; /** * Create the panel. */ public MyTimer() { setLayout(new BorderLayout(0, 0)); add(getLblTime(), BorderLayout.CENTER); this.running = false; getLblTime().setText("0"); try { this.countdown = Applet.newAudioClip(new URL("file:./src/resources/pulse.wav")); this.timeoutHorn = Applet.newAudioClip(new URL("file:./src/resources/horn.wav")); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public MyTimer(TimerTimeout event, int seconds, boolean sound, boolean visual) { this(); this.event = event; this.seconds = seconds; this.sound = sound; this.visual = visual; getLblTime().setText(this.seconds+""); } private TimerTimeout getEvent() { return this.event; } private Timer getTimer() { return this.timer; } private AudioClip getCountdown() { return this.countdown; } private AudioClip getTimeoutHorn() { return this.timeoutHorn; } public int getSeconds() { return this.seconds; } public void setSeconds(int seconds) { this.seconds = seconds; } public boolean isSound() { return sound; } public void setSound(boolean sound) { this.sound = sound; } public boolean isVisual() { return visual; } public void setVisual(boolean visual) { this.visual = visual; } private JLabel getLblTime() { if (lblTime == null) { lblTime = new JLabel(""); lblTime.setFont(new Font("Dialog", Font.BOLD, 20)); lblTime.setHorizontalAlignment(SwingConstants.CENTER); } return lblTime; } public void startTimer() { if (!this.running) { this.timer = new Timer(); this.running = true; getLblTime().setForeground(null); this.timer.schedule(new TimerTask() { int counter = getSeconds(); @Override public void run() { // TODO Auto-generated method stub if (counter == -1) { getTimer().cancel(); return; } if(counter < 11 && counter != 0) { if(isSound()) { getCountdown().play(); } if(isVisual()) { getLblTime().setForeground(Color.RED); } } getLblTime().setText(counter+""); if(counter == 0) { if(isSound()) { getTimeoutHorn().play(); } getEvent().timerTimeout(); running = false; } counter } }, new Date(), 1000); } } public void stopTimer() { this.running = false; if(getTimer() == null) { return; } getTimer().cancel(); } }
/** * No Rights Reserved. * This program and the accompanying materials * are made available under the terms of the Public Domain. */ package logbook.gui; import logbook.config.GlobalConfig; import logbook.config.ShipConfig; import logbook.gui.background.AsyncExecApplicationMain; import logbook.gui.background.AsyncExecApplicationMainConsole; import logbook.gui.background.AsyncExecUpdateCheck; import logbook.gui.listener.BathwaterTableAdapter; import logbook.gui.listener.CalcExpAdapter; import logbook.gui.listener.CaptureDialogAdapter; import logbook.gui.listener.ConfigDialogAdapter; import logbook.gui.listener.CreateItemReportAdapter; import logbook.gui.listener.CreateShipReportAdapter; import logbook.gui.listener.DropReportAdapter; import logbook.gui.listener.HelpEventListener; import logbook.gui.listener.ItemListReportAdapter; import logbook.gui.listener.MainShellAdapter; import logbook.gui.listener.MissionResultReportAdapter; import logbook.gui.listener.ShipListReportAdapter; import logbook.gui.listener.TraySelectionListener; import logbook.gui.logic.LayoutLogic; import logbook.gui.logic.Sound; import logbook.server.proxy.ProxyServer; import logbook.thread.ThreadManager; import logbook.thread.ThreadStateObserver; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tray; import org.eclipse.swt.widgets.TrayItem; import org.eclipse.wb.swt.SWTResourceManager; public final class ApplicationMain { private static final Logger LOG = LogManager.getLogger(ApplicationMain.class); private Shell shell; private TrayItem trayItem; private Composite commandComposite; private Button itemList; private Button shipList; private CTabFolder tabFolder; private Composite mainComposite; private Group deckGroup; private Button deckNotice; private Label deck1name; private Text deck1time; private Label deck2name; private Text deck2time; private Label deck3name; private Text deck3time; private Group ndockGroup; private Button ndockNotice; private Label ndock1name; private Text ndock1time; private Label ndock2name; private Text ndock2time; private Label ndock3name; private Text ndock3time; private Label ndock4name; private Text ndock4time; private Composite consoleComposite; private List console; /** * Launch the application. * @param args */ public static void main(String[] args) { try { ShipConfig.load(); ApplicationMain window = new ApplicationMain(); window.open(); GlobalConfig.store(); ShipConfig.store(); } catch (Error e) { LOG.fatal("", e); } catch (Exception e) { LOG.fatal("", e); } finally { SWTResourceManager.dispose(); ProxyServer.end(); } } /** * Open the window. */ public void open() { Display display = Display.getDefault(); this.createContents(); this.shell.open(); this.shell.layout(); while (!this.shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } this.trayItem.dispose(); } public void createContents() { final Display display = Display.getDefault(); this.shell = new Shell(SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.RESIZE | GlobalConfig.getOnTop()); this.shell.setText(" " + GlobalConfig.VERSION); this.shell.setAlpha(GlobalConfig.getAlpha()); GridLayout glShell = new GridLayout(1, false); glShell.horizontalSpacing = 1; glShell.marginTop = 0; glShell.marginWidth = 0; glShell.marginHeight = 0; glShell.marginBottom = 0; glShell.verticalSpacing = 1; this.shell.setLayout(glShell); this.shell.addShellListener(new ShellAdapter() { @Override public void shellClosed(ShellEvent e) { GlobalConfig.setLocation(ApplicationMain.this.shell.getLocation()); MessageBox box = new MessageBox(ApplicationMain.this.shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION); box.setText(""); box.setMessage(""); if (box.open() == SWT.YES) { e.doit = true; } else { e.doit = false; } } }); Menu menubar = new Menu(this.shell, SWT.BAR); this.shell.setMenuBar(menubar); MenuItem cmdmenuroot = new MenuItem(menubar, SWT.CASCADE); cmdmenuroot.setText(""); Menu cmdmenu = new Menu(cmdmenuroot); cmdmenuroot.setMenu(cmdmenu); MenuItem calcmenuroot = new MenuItem(menubar, SWT.CASCADE); calcmenuroot.setText(""); Menu calcmenu = new Menu(calcmenuroot); calcmenuroot.setMenu(calcmenu); MenuItem etcroot = new MenuItem(menubar, SWT.CASCADE); etcroot.setText(""); Menu etcmenu = new Menu(etcroot); etcroot.setMenu(etcmenu); MenuItem capture = new MenuItem(cmdmenu, SWT.NONE); capture.setText("(&C)"); capture.addSelectionListener(new CaptureDialogAdapter(this.shell)); new MenuItem(cmdmenu, SWT.SEPARATOR); MenuItem cmddrop = new MenuItem(cmdmenu, SWT.NONE); cmddrop.setText("(&D)\tCtrl+D"); cmddrop.setAccelerator(SWT.CTRL + 'D'); cmddrop.addSelectionListener(new DropReportAdapter(this.shell)); MenuItem cmdcreateship = new MenuItem(cmdmenu, SWT.NONE); cmdcreateship.setText("(&B)\tCtrl+B"); cmdcreateship.setAccelerator(SWT.CTRL + 'B'); cmdcreateship.addSelectionListener(new CreateShipReportAdapter(this.shell)); MenuItem cmdcreateitem = new MenuItem(cmdmenu, SWT.NONE); cmdcreateitem.setText("(&E)\tCtrl+E"); cmdcreateitem.setAccelerator(SWT.CTRL + 'E'); cmdcreateitem.addSelectionListener(new CreateItemReportAdapter(this.shell)); MenuItem cmdmissionresult = new MenuItem(cmdmenu, SWT.NONE); cmdmissionresult.setText("(&M)\tCtrl+M"); cmdmissionresult.setAccelerator(SWT.CTRL + 'M'); cmdmissionresult.addSelectionListener(new MissionResultReportAdapter(this.shell)); new MenuItem(cmdmenu, SWT.SEPARATOR); MenuItem cmditemlist = new MenuItem(cmdmenu, SWT.NONE); cmditemlist.setText("(&I)\tCtrl+I"); cmditemlist.setAccelerator(SWT.CTRL + 'I'); cmditemlist.addSelectionListener(new ItemListReportAdapter(this.shell)); MenuItem cmdshiplist = new MenuItem(cmdmenu, SWT.NONE); cmdshiplist.setText("(&S)\tCtrl+S"); cmdshiplist.setAccelerator(SWT.CTRL + 'S'); cmdshiplist.addSelectionListener(new ShipListReportAdapter(this.shell)); new MenuItem(cmdmenu, SWT.SEPARATOR); MenuItem cmdbathwaterlist = new MenuItem(cmdmenu, SWT.NONE); cmdbathwaterlist.setText("(&N)\tCtrl+N"); cmdbathwaterlist.setAccelerator(SWT.CTRL + 'N'); cmdbathwaterlist.addSelectionListener(new BathwaterTableAdapter(this.shell)); new MenuItem(cmdmenu, SWT.SEPARATOR); final MenuItem dispsize = new MenuItem(cmdmenu, SWT.CHECK); dispsize.setText("(&M)\tCtrl+M"); dispsize.setAccelerator(SWT.CTRL + 'M'); new MenuItem(cmdmenu, SWT.SEPARATOR); final MenuItem dispose = new MenuItem(cmdmenu, SWT.NONE); dispose.setText("(&X)"); dispose.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ApplicationMain.this.shell.close(); } }); MenuItem calcexp = new MenuItem(calcmenu, SWT.NONE); calcexp.setText("(&C)\tCtrl+C"); calcexp.setAccelerator(SWT.CTRL + 'C'); calcexp.addSelectionListener(new CalcExpAdapter(this.shell)); MenuItem config = new MenuItem(etcmenu, SWT.NONE); config.setText("(&P)"); config.addSelectionListener(new ConfigDialogAdapter(this.shell)); MenuItem pack = new MenuItem(etcmenu, SWT.NONE); pack.setText(""); pack.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new CreatePacFileDialog(ApplicationMain.this.shell).open(); } }); MenuItem version = new MenuItem(etcmenu, SWT.NONE); version.setText("(&A)"); version.addSelectionListener(new HelpEventListener(this.shell)); this.shell.addShellListener(new MainShellAdapter()); this.shell.addHelpListener(new HelpEventListener(this.shell)); this.trayItem = this.addTrayItem(display); this.commandComposite = new Composite(this.shell, SWT.NONE); this.commandComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); this.commandComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.itemList = new Button(this.commandComposite, SWT.PUSH); this.itemList.setText("(0/0)"); this.itemList.addSelectionListener(new ItemListReportAdapter(this.shell)); this.shipList = new Button(this.commandComposite, SWT.PUSH); this.shipList.setText("(0/0)"); this.shipList.addSelectionListener(new ShipListReportAdapter(this.shell)); this.tabFolder = new CTabFolder(this.shell, SWT.NONE); this.tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor( SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); this.tabFolder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.tabFolder.setTabHeight(26); this.tabFolder.marginWidth = 0; this.tabFolder.setMinimumCharacters(5); CTabItem mainItem = new CTabItem(this.tabFolder, SWT.NONE); mainItem.setFont(SWTResourceManager.getBoldFont(this.shell.getFont())); this.tabFolder.setSelection(mainItem); mainItem.setText(""); this.mainComposite = new Composite(this.tabFolder, SWT.NONE); GridLayout glMain = new GridLayout(1, false); glMain.horizontalSpacing = 1; glMain.marginTop = 0; glMain.marginWidth = 0; glMain.marginHeight = 0; glMain.marginBottom = 0; glMain.verticalSpacing = 1; this.mainComposite.setLayout(glMain); this.mainComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); mainItem.setControl(this.mainComposite); this.deckGroup = new Group(this.mainComposite, SWT.NONE); this.deckGroup.setText(""); this.deckGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout glDeckGroup = new GridLayout(2, false); glDeckGroup.verticalSpacing = 1; glDeckGroup.marginTop = 0; glDeckGroup.marginWidth = 0; glDeckGroup.marginHeight = 0; glDeckGroup.marginBottom = 0; glDeckGroup.horizontalSpacing = 1; this.deckGroup.setLayout(glDeckGroup); this.deckNotice = new Button(this.deckGroup, SWT.CHECK); this.deckNotice.setSelection(GlobalConfig.getNoticeDeckmission()); this.deckNotice.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, SWT.CENTER, false, false, 2, 1)); this.deckNotice.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GlobalConfig.setNoticeDeckmission(ApplicationMain.this.deckNotice.getSelection()); } }); this.deckNotice.setText("1"); this.deck1name = new Label(this.deckGroup, SWT.NONE); this.deck1name.setText("2"); this.deck1name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.deck1time = new Text(this.deckGroup, SWT.SINGLE | SWT.BORDER); this.deck1time.setText("2"); GridData gddeck1time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gddeck1time.widthHint = 75; this.deck1time.setLayoutData(gddeck1time); this.deck2name = new Label(this.deckGroup, SWT.NONE); this.deck2name.setText("3"); this.deck2name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.deck2time = new Text(this.deckGroup, SWT.SINGLE | SWT.BORDER); this.deck2time.setText("3"); GridData gddeck2time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gddeck2time.widthHint = 75; this.deck2time.setLayoutData(gddeck2time); this.deck3name = new Label(this.deckGroup, SWT.NONE); this.deck3name.setText("4"); this.deck3name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.deck3time = new Text(this.deckGroup, SWT.SINGLE | SWT.BORDER); this.deck3time.setText("4"); GridData gddeck3time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gddeck3time.widthHint = 75; this.deck3time.setLayoutData(gddeck3time); this.ndockGroup = new Group(this.mainComposite, SWT.NONE); this.ndockGroup.setText(""); this.ndockGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout glNdockGroup = new GridLayout(2, false); glNdockGroup.verticalSpacing = 1; glNdockGroup.marginTop = 0; glNdockGroup.marginWidth = 0; glNdockGroup.marginHeight = 0; glNdockGroup.marginBottom = 0; glNdockGroup.horizontalSpacing = 1; this.ndockGroup.setLayout(glNdockGroup); this.ndockNotice = new Button(this.ndockGroup, SWT.CHECK); this.ndockNotice.setSelection(GlobalConfig.getNoticeNdock()); this.ndockNotice.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, SWT.CENTER, false, false, 2, 1)); this.ndockNotice.setText("1"); this.ndockNotice.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GlobalConfig.setNoticeNdock(ApplicationMain.this.ndockNotice.getSelection()); } }); this.ndock1name = new Label(this.ndockGroup, SWT.NONE); this.ndock1name.setText("1"); this.ndock1name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.ndock1time = new Text(this.ndockGroup, SWT.SINGLE | SWT.BORDER); this.ndock1time.setText(""); GridData gdndock1time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gdndock1time.widthHint = 75; this.ndock1time.setLayoutData(gdndock1time); this.ndock2name = new Label(this.ndockGroup, SWT.NONE); this.ndock2name.setText("2"); this.ndock2name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.ndock2time = new Text(this.ndockGroup, SWT.SINGLE | SWT.BORDER); this.ndock2time.setText(""); GridData gdndock2time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gdndock2time.widthHint = 75; this.ndock2time.setLayoutData(gdndock2time); this.ndock3name = new Label(this.ndockGroup, SWT.NONE); this.ndock3name.setText("3"); this.ndock3name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.ndock3time = new Text(this.ndockGroup, SWT.SINGLE | SWT.BORDER); this.ndock3time.setText(""); GridData gdndock3time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gdndock3time.widthHint = 75; this.ndock3time.setLayoutData(gdndock3time); this.ndock4name = new Label(this.ndockGroup, SWT.NONE); this.ndock4name.setText("4"); this.ndock4name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.ndock4time = new Text(this.ndockGroup, SWT.SINGLE | SWT.BORDER); this.ndock4time.setText(""); GridData gdndock4time = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gdndock4time.widthHint = 75; this.ndock4time.setLayoutData(gdndock4time); this.consoleComposite = new Composite(this.shell, SWT.NONE); GridLayout loglayout = new GridLayout(1, false); loglayout.verticalSpacing = 1; loglayout.marginTop = 0; loglayout.marginWidth = 0; loglayout.marginHeight = 0; loglayout.marginBottom = 0; loglayout.horizontalSpacing = 1; this.consoleComposite.setLayout(loglayout); this.consoleComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL)); this.console = new List(this.consoleComposite, SWT.BORDER | SWT.V_SCROLL); this.console.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL)); if (GlobalConfig.getMinimumLayout()) { this.shell.setRedraw(false); ApplicationMain.this.hide(true, this.commandComposite, this.deckNotice, this.deck1name, this.deck2name, this.deck3name, this.ndockNotice, this.ndock1name, this.ndock2name, this.ndock3name, this.ndock4name, this.consoleComposite); dispsize.setSelection(true); this.shell.pack(); this.shell.setRedraw(true); } else { this.shell.setSize(GlobalConfig.getWidth(), GlobalConfig.getHeight()); } dispsize.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Shell shell = ApplicationMain.this.shell; shell.setRedraw(false); boolean minimum = dispsize.getSelection(); ApplicationMain.this.hide(minimum, ApplicationMain.this.commandComposite, ApplicationMain.this.deckNotice, ApplicationMain.this.deck1name, ApplicationMain.this.deck2name, ApplicationMain.this.deck3name, ApplicationMain.this.ndockNotice, ApplicationMain.this.ndock1name, ApplicationMain.this.ndock2name, ApplicationMain.this.ndock3name, ApplicationMain.this.ndock4name, ApplicationMain.this.consoleComposite); ApplicationMain.this.tabFolder.setSelection(0); shell.setRedraw(true); if (minimum) { ApplicationMain.this.tabFolder.setSingle(true); CTabItem[] tabitems = ApplicationMain.this.tabFolder.getItems(); for (CTabItem tabitem : tabitems) { Control control = tabitem.getControl(); if (control instanceof AsyncExecApplicationMain.FleetComposite) { ApplicationMain.this.hide(true, control); } } shell.pack(); ApplicationMain.this.tabFolder.setSingle(false); for (CTabItem tabitem : tabitems) { Control control = tabitem.getControl(); if (control instanceof AsyncExecApplicationMain.FleetComposite) { ApplicationMain.this.hide(false, control); } } } else { shell.setSize(GlobalConfig.getWidth(), GlobalConfig.getHeight()); } GlobalConfig.setMinimumLayout(minimum); } }); Point location = GlobalConfig.getLocation(); if (location != null) { this.shell.setLocation(location); } this.startThread(); } /** * * * @param display * @return */ private TrayItem addTrayItem(final Display display) { Tray tray = display.getSystemTray(); TrayItem item = new TrayItem(tray, SWT.NONE); Image image = display.getSystemImage(SWT.ICON_INFORMATION); item.setImage(image); item.addListener(SWT.Selection, new TraySelectionListener(this.shell)); return item; } /** * * * @param minimum * @param controls */ private void hide(boolean minimum, Control... controls) { for (Control control : controls) { LayoutLogic.hide(control, minimum); } this.shell.layout(); } private void startThread() { ThreadManager.regist(ProxyServer.getInstance()); ThreadManager.regist(new AsyncExecApplicationMain(this)); ThreadManager.regist(new AsyncExecApplicationMainConsole(this.console)); ThreadManager.regist(new Sound.PlayerThread()); ThreadManager.regist(new ThreadStateObserver(this.shell)); ThreadManager.start(); if (GlobalConfig.getCheckUpdate()) { new AsyncExecUpdateCheck(this.shell).start(); } } /** * @return shell */ public Shell getShell() { return this.shell; } /** * @return */ public TrayItem getTrayItem() { return this.trayItem; } /** * @return */ public Composite getCommandComposite() { return this.commandComposite; } /** * @return */ public Button getItemList() { return this.itemList; } /** * @return */ public Button getShipList() { return this.shipList; } /** * @return */ public CTabFolder getTabFolder() { return this.tabFolder; } /** * @return */ public Composite getMainComposite() { return this.mainComposite; } /** * @return */ public Group getDeckGroup() { return this.deckGroup; } /** * @return 1() */ public Button getDeckNotice() { return this.deckNotice; } /** * @return .2 */ public Label getDeck1name() { return this.deck1name; } /** * @return .2 */ public Text getDeck1time() { return this.deck1time; } /** * @return .3 */ public Label getDeck2name() { return this.deck2name; } /** * @return .3 */ public Text getDeck2time() { return this.deck2time; } /** * @return .4 */ public Label getDeck3name() { return this.deck3name; } /** * @return .4 */ public Text getDeck3time() { return this.deck3time; } /** * @return */ public Group getNdockGroup() { return this.ndockGroup; } /** * @return 1() */ public Button getNdockNotice() { return this.ndockNotice; } /** * @return .1. */ public Label getNdock1name() { return this.ndock1name; } /** * @return .1. */ public Text getNdock1time() { return this.ndock1time; } /** * @return .2. */ public Label getNdock2name() { return this.ndock2name; } /** * @return .2. */ public Text getNdock2time() { return this.ndock2time; } /** * @return .3. */ public Label getNdock3name() { return this.ndock3name; } /** * @return .3. */ public Text getNdock3time() { return this.ndock3time; } /** * @return .4. */ public Label getNdock4name() { return this.ndock4name; } /** * @return .4. */ public Text getNdock4time() { return this.ndock4time; } /** * @return */ public Composite getConsoleComposite() { return this.consoleComposite; } /** * @return */ public List getConsole() { return this.console; } }
import java.awt.*; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Line2D; import java.awt.geom.Ellipse2D; import javax.swing.*; import java.util.List; import java.util.ArrayList; import java.net.*; import java.text.*; import java.io.*; public class UTTT { //JFrame Variables public final int WIDTH = 550; public final int HEIGHT = 650; public final String TITLE = "Ultamite Tic Tac Toe!"; //Box arrays public Box newBoxes[][][][] = new Box[3][3][3][3]; public Box boxes[][][][] = new Box[3][3][3][3]; public Box big_boxes[][] = new Box[3][3]; private char big_box_move[][] = new char[3][3]; //Variables used for drawing public List<Line2D> drawLines = new ArrayList<Line2D>(); public Box hoverBox; public List<Box> availableToPlay = new ArrayList<Box>(); public List<Ellipse2D> o_moves = new ArrayList<Ellipse2D>(); public List<Ellipse2D> big_o_moves = new ArrayList<Ellipse2D>(); public List<Line2D> x_moves = new ArrayList<Line2D>(); public List<Line2D> big_x_moves = new ArrayList<Line2D>(); public String message = "Welcome to UTTT"; public static Boolean done = false; public char player_symbol; public Boolean my_turn = false; public int row_to_play = 0, col_to_play = 0; private BufferedReader fromServer; private BufferedWriter toServer; public static void main(String[] args) throws IOException{ UTTT uttt = new UTTT(); uttt.initilizeLines(); final Container cp = uttt.setupJFrame(); uttt.connectToServer(); while (!done) { uttt.readInput(cp); } } class Box { private int x, y, height, width, big_row, big_col, little_row, little_col; private Color color; private Boolean taken; Box(int x, int y, int width, int height, int big_row, int big_col, int little_row, int little_col) { this.x = x; this.y = y; this.height = height; this.width = width; this.big_row = big_row; this.big_col = big_col; this.little_row = little_row; this.little_col = little_col; taken = false; //System.out.println("("+x+", "+y+", "+(x+width)+", "+(y+height)+")"); } // Screw setters. Getters are what it's all about public int getX(){ return x; } public int getY(){ return y; } public int getHeight(){ return height; } public int getWidth(){ return width; } public int getBigRow(){ return big_row; } public int getBigCol(){ return big_col; } public int getLittleRow(){ return little_row; } public int getLittleCol(){ return little_col; } public Color getColor(){ return color; } public Boolean isTaken(){ return taken; } public void setTaken(){ taken = true; } // Ok, technically this is a setter, but it isn't called setColor, so it doesn't count public void changeColor(Color new_color){ //Add this box to the drawHoverBoxes list color = new_color; } } public Box findBox(int x, int y) { //We use this process quite a bit, so it makes sense to make it a function Boolean found = false; for (int i = 0; i<3; i++){ for (int j = 0; j<3; j++){ for (int k = 0; k<3; k++){ for (int l = 0;l<3; l++){ double top = boxes[i][j][k][l].getY(); double bottom = top + boxes[i][j][k][l].getHeight(); double left = boxes[i][j][k][l].getX(); double right = left + boxes[i][j][k][l].getWidth(); //System.out.println(i+":"+j+" (" + (int) left + ", "+(int) top+", "+(int) right+", "+(int) bottom+")"); if (y > top && y < bottom && x > left && x < right) { //System.out.println("Correct Location: " + (i+1) + ","+(j+1) + ","+(k+1)+","+(l+1)); found = true; if (boxes[i][j][k][l].isTaken() || big_box_move[i][j] != ' ') { return null; } else if ((row_to_play == 0 && col_to_play == 0) || (boxes[i][j][k][l].getBigRow() == row_to_play && boxes[i][j][k][l].getBigCol() == col_to_play)) { return boxes[i][j][k][l]; } else { return null; } } } } } } return null; } /* Find what box we're pointing at. If it's not a box, it returns null ** If we're still pointing at the same box, there's no need to repaint the screen, ** so only repaint if the old_box is different from the new box. */ public void highlightBox(int x, int y, Color new_color, Container cp) { if (my_turn) { Box old_box = hoverBox; hoverBox = findBox(x,y); if (old_box != hoverBox ) { if (hoverBox != null) { hoverBox.changeColor(new_color); //System.out.println(hoverBox.getBigRow()+", " + hoverBox.getBigCol()+ "| " + hoverBox.getLittleRow()+ ", "+ hoverBox.getLittleCol()); //if (hoverBox.getBigRow() != 2 || hoverBox.getBigCol() != 2) { //Demoing out how we can restrict them to play in the correct spot on the board // hoverBox = null; } cp.repaint(); } } } public void selectBox(int x, int y, Color new_color, Container cp) throws IOException{ String move = sendBoxPosition(x,y); if (move != "" && my_turn) { toServer.write(move); toServer.newLine(); toServer.flush(); } } /*Sends box position to the server * Returns string for server to receive */ public String sendBoxPosition(int x, int y) { Box temp = findBox(x,y); if (temp != null && ((row_to_play == 0 && col_to_play == 0) || (temp.getBigRow() == row_to_play && temp.getBigCol() == col_to_play))) { //if temp is not null, then display the position of the mouse return (temp.getBigRow()+"," + temp.getBigCol()+ "," + temp.getLittleRow()+ ","+ temp.getLittleCol()); } else { //otherwise return nothing (empty string) return ""; } } public void initilizeLines(){ UTTT uttt = new UTTT(); // everything is based off of these start and offset points, // which makes it easy to move everything if we want to int x_start = 32; int y_start = 102; int y_offset = 161; int x_offset = 161; drawLines.add(new Line2D.Float(x_start+156, y_start+4, x_start+156, y_start+469)); drawLines.add(new Line2D.Float(x_start+317, y_start+4, x_start+317, y_start+469)); drawLines.add(new Line2D.Float(x_start+4, y_start+156, x_start+469, y_start+156)); drawLines.add(new Line2D.Float(x_start+4, y_start+317, x_start+469, y_start+317)); for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ drawLines.add(new Line2D.Float(x_start+55+(j*x_offset), y_start+20+(i*y_offset), x_start+55+(j*x_offset), y_start+130+(i*y_offset))); drawLines.add(new Line2D.Float(x_start+94+(j*x_offset), y_start+20+(i*y_offset), x_start+94+(j*x_offset), y_start+130+(i*y_offset))); drawLines.add(new Line2D.Float(x_start+20+(j*x_offset), y_start+56+(i*y_offset), x_start+130+(j*x_offset), y_start+56+(i*y_offset))); drawLines.add(new Line2D.Float(x_start+20+(j*x_offset), y_start+95+(i*y_offset), x_start+130+(j*x_offset), y_start+95+(i*y_offset))); } } //uttt.new MoveSymbol(90,90,120,30, 120, 60, 90,180); for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ for (int k=0;k<3;k++){ for (int l=0;l<3;l++){ boxes[i][j][k][l] = uttt.new Box((x_start+18+(39*l + j*x_offset)), (y_start+19+(39*k + i*y_offset)), 34, 34, i+1, j+1, k+1, l+1); } } big_boxes[i][j] = uttt.new Box(x_start+(j*x_offset),y_start+(i*y_offset),150,150, i+1, j+1, 0, 0); big_box_move[i][j] = ' '; } } } public Container setupJFrame() { // Now the fun part JFrame jf = new JFrame(TITLE); Container cp = jf.getContentPane(); cp.add(new JComponent() { //Our lovely component that does all the work public void paintComponent(Graphics g) { /*Basically, we have 1 paint statement, and it draws things that are ** in the lists. This way, when we want to draw something new to the screen ** we just add it to its appropriate list, and then repaint */ super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g.setColor(new Color(50,210,50)); for (int i=0;i<availableToPlay.size();i++){ Box temp = availableToPlay.get(i); g2.fillRect(temp.getX(), temp.getY(), temp.getWidth(), temp.getHeight()); } /*g.setColor(new_color); g2.fillRect(x, y, width, height);*/ if (hoverBox != null) { g.setColor(hoverBox.getColor()); g2.fillRect(hoverBox.getX(), hoverBox.getY(), hoverBox.getWidth(), hoverBox.getHeight()); } g2.setStroke(new BasicStroke(10)); g.setColor(new Color(75,75,75)); for (int i=0;i<drawLines.size();i++){ if (i == 4) { g2.setStroke(new BasicStroke(2)); } g2.draw(drawLines.get(i)); } g2.setStroke(new BasicStroke(5)); g.setColor(new Color(0,0,0)); for (int i=0;i<o_moves.size();i++){ if (i == o_moves.size()-1 && player_symbol == 'X' && my_turn){ g.setColor(new Color(255,0,0)); } g2.draw(o_moves.get(i)); } g.setColor(new Color(0,0,0)); for (int i=0;i<x_moves.size();i++){ if (i >= x_moves.size()-2 && player_symbol == 'O' && my_turn){ g.setColor(new Color(255,0,0)); } g2.draw(x_moves.get(i)); } g2.setStroke(new BasicStroke(8)); g.setColor(new Color(0,0,0)); for (int i=0;i<big_o_moves.size();i++){ g2.draw(big_o_moves.get(i)); } for (int i=0;i<big_x_moves.size();i++){ g2.draw(big_x_moves.get(i)); } g.setColor(new Color(0,0,0)); Font font = new Font("Serif", Font.PLAIN, 30); g2.setFont(font); g2.drawString(message, 125 ,75); } }); // Now we add MouseListeners to that component cp.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { } //Unused methods, but still need to override them @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { try { selectBox(e.getX(), e.getY(), new Color(0,0,255), cp); } catch (IOException ex) { System.err.println(ex); } } }); cp.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent e) { highlightBox(e.getX(), e.getY(), new Color(255,0,0), cp); } @Override public void mouseDragged(MouseEvent e) { } }); jf.setSize(WIDTH, HEIGHT); jf.setVisible(true); return cp; } public void connectToServer() { try { Socket socket = new Socket("localhost", 8001); fromServer = new BufferedReader (new InputStreamReader(socket.getInputStream())); toServer = new BufferedWriter (new OutputStreamWriter(socket.getOutputStream())); message = "Waiting for the other player... "; player_symbol = fromServer.readLine().charAt(0); } catch (Exception e) { System.err.println(e); } } public void readInput(Container cp) throws IOException{ final String input = fromServer.readLine(); System.out.println(input); if (input.charAt(0) == player_symbol) { my_turn = false; hoverBox = null; } else { my_turn = true; } switch (input.charAt(1)) { case '1' : done = true; message = (player_symbol == 'X') ? "You Win!!!" : "You lose!"; break; case '2' : done = true; message = (player_symbol == 'O') ? "You Win!!!" : "You loose!"; break; case '3' : done = true; message = "It's a draw!"; break; case '4' : done = false; message = (my_turn) ? "Your Turn" : "Waiting for other player..."; break; } for (int i=2;i<input.length();i=i+4) { if (input.charAt(i+2) != '0') { int a = input.charAt(i)-49; int b = input.charAt(i+1)-49; int c = input.charAt(i+2)-49; int d = input.charAt(i+3)-49; Box temp = boxes[a][b][c][d]; temp.setTaken(); if (input.charAt(0) == 'X') { x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+5, temp.getX()+temp.getWidth()-5, temp.getY()+temp.getHeight()-5)); x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+temp.getHeight()-5, temp.getX()+temp.getWidth()-5, temp.getY()+5)); } else { o_moves.add(new Ellipse2D.Double(temp.getX()+5, temp.getY()+5, temp.getWidth()-10, temp.getHeight()-10)); } } else { int a = input.charAt(i)-49; int b = input.charAt(i+1)-49; Box temp = big_boxes[a][b]; big_box_move[a][b] = input.charAt(0); if (input.charAt(0) == 'X') { big_x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+5, temp.getX()+temp.getWidth()-5, temp.getY()+temp.getHeight()-5)); big_x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+temp.getHeight()-5, temp.getX()+temp.getWidth()-5, temp.getY()+5)); } else { big_o_moves.add(new Ellipse2D.Double(temp.getX()+5, temp.getY()+5, temp.getWidth()-10, temp.getHeight()-10)); } } } if (input.length() != 2) { row_to_play = input.charAt(4)-48; col_to_play = input.charAt(5)-48; availableToPlay.clear(); if (big_box_move[row_to_play-1][col_to_play-1] == ' ') { if (my_turn) { availableToPlay.add(big_boxes[row_to_play-1][col_to_play-1]); } } else { for (int i=0; i<3; i++) { for (int j=0; j<3; j++){ if (big_box_move[i][j] == ' ' && my_turn) { availableToPlay.add(big_boxes[i][j]); } } } row_to_play = 0; col_to_play = 0; } } cp.repaint(); } }
package com.sun.star.lib.uno.typeinfo; /** Defines a class to describe additional type information. */ public class TypeInfo { public static final int IN = 0x00000001; public static final int OUT = 0x00000002; public static final int UNSIGNED = 0x00000004; public static final int READONLY = 0x00000008; public static final int ONEWAY = 0x00000010; public static final int CONST = 0x00000020; public static final int ANY = 0x00000040; public static final int INTERFACE = 0x00000080; /** Marks an extended attribute of an interface type as bound. <p>Only used in the <code>flags</code> argument of the <code>AttributeTypeInfo</code> constructors.</p> @since UDK 3.2 */ public static final int BOUND = 0x00000100; protected int m_flags; protected String m_name; public TypeInfo(String name, int flags) { m_name = name; m_flags = flags; } public String getName() { return m_name; } public int getFlags() { return m_flags; } public boolean isUnsigned() { return (m_flags & TypeInfo.UNSIGNED) != 0; } public boolean isAny() { return (m_flags & TypeInfo.ANY) != 0; } public boolean isInterface() { return (m_flags & TypeInfo.INTERFACE) != 0; } }
package com.exedio.cope.instrument; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl; public final class Wrapper { private final String methodName; private final String comment; private final String modifier; public Wrapper( final String methodName, final String comment, final String modifier) { this(void.class, methodName, comment, modifier); } public Wrapper( final java.lang.reflect.Type methodReturnType, final String methodName, final String comment, final String modifier) { this.methodReturnType = methodReturnType; this.methodName = methodName; this.comment = comment; this.modifier = modifier; if(methodReturnType==null) throw new NullPointerException("methodReturnType must not be null"); if(methodName==null) throw new NullPointerException("methodName must not be null"); if(comment==null) throw new NullPointerException("comment must not be null"); if(modifier==null) throw new NullPointerException("modifier must not be null"); } public String getMethodName() { return methodName; } public String getComment() { return comment; } public String getModifier() { return modifier; } private boolean isStatic = false; public Wrapper setStatic() { isStatic = true; return this; } public boolean isStatic() { return isStatic; } private java.lang.reflect.Type methodReturnType; public Wrapper setReturn(final Class methodReturnType, final String comment) { if(methodReturnType==null) throw new NullPointerException("methodReturnType must not be null"); if(this.methodReturnType!=void.class) throw new NullPointerException("methodReturnType must not be set twice"); this.methodReturnType = methodReturnType; if(comment!=null) addCommentPrivate("@return " + comment); return this; } public java.lang.reflect.Type getMethodReturnType() { return methodReturnType; } private ArrayList<java.lang.reflect.Type> parameterTypes; private ArrayList<String> parameterNames; public Wrapper addParameter(final java.lang.reflect.Type type) { return addParameter(type, "{1}", null); } public Wrapper addParameter(final java.lang.reflect.Type type, final String name) { return addParameter(type, name, null); } public Wrapper addParameter(final java.lang.reflect.Type type, final String name, final String comment) { if(type==null) throw new NullPointerException("type must not be null"); if(name==null) throw new NullPointerException("name must not be null"); if(parameterTypes==null) { parameterTypes = new ArrayList<java.lang.reflect.Type>(); parameterNames = new ArrayList<String>(); } parameterTypes.add(type); parameterNames.add(name); if(comment!=null) addCommentPrivate("@param " + name + ' ' + comment); return this; } public List<java.lang.reflect.Type> getParameterTypes() { return parameterTypes!=null ? Collections.unmodifiableList(parameterTypes) : Collections.<java.lang.reflect.Type>emptyList(); } public List<String> getParameterNames() { return parameterNames!=null ? Collections.unmodifiableList(parameterNames) : Collections.<String>emptyList(); } private ArrayList<Class<? extends Throwable>> throwsClause; public Wrapper addThrows(final Collection<Class<? extends Throwable>> throwables) { for(final Class<? extends Throwable> throwable : throwables) addThrows(throwable, null); return this; } public Wrapper addThrows(final Class<? extends Throwable> throwable) { return addThrows(throwable, null); } public Wrapper addThrows(final Class<? extends Throwable> throwable, final String comment) { if(throwable==null) throw new NullPointerException("throwable must not be null"); if(throwsClause==null) throwsClause = new ArrayList<Class<? extends Throwable>>(); throwsClause.add(throwable); if(comment!=null) addCommentPrivate("@throws " + throwable.getName() + ' ' + comment); return this; } public List<Class<? extends Throwable>> getThrowsClause() { return throwsClause!=null ? Collections.unmodifiableList(throwsClause) : Collections.<Class<? extends Throwable>>emptyList(); } private String methodWrapperPattern; public Wrapper setMethodWrapperPattern(final String pattern) { this.methodWrapperPattern = pattern; return this; } public String getMethodWrapperPattern() { return methodWrapperPattern; } private ArrayList<String> comments = null; public Wrapper addComment(final String comment) { if(comment.startsWith("@")) throw new RuntimeException(comment); return addCommentPrivate(comment); } private Wrapper addCommentPrivate(final String comment) { if(comment==null) throw new NullPointerException("comment must not be null"); if(comments==null) comments = new ArrayList<String>(); comments.add(comment); return this; } public List<String> getComments() { return comments!=null ? Collections.unmodifiableList(comments) : Collections.<String>emptyList(); } private String deprecationComment = null; public Wrapper deprecate(final String comment) { if(comment==null) throw new NullPointerException(); deprecationComment = comment; return this; } public boolean isDeprecated() { return deprecationComment!=null; } public String getDeprecationComment() { return deprecationComment; } public class ClassVariable { /* OK, just a placeholder */ } public class TypeVariable0 { /* OK, just a placeholder */ } public class TypeVariable1 { /* OK, just a placeholder */ } public class DynamicModelType { /* OK, just a placeholder */ } // TODO remove, is a hack public class DynamicModelField { /* OK, just a placeholder */ } // TODO remove, is a hack public static final java.lang.reflect.Type makeType(final Class rawType, final Class... actualTypeArguments) { return ParameterizedTypeImpl.make(rawType, actualTypeArguments, null); } public static class ExtendsType implements java.lang.reflect.Type { private final Class rawType; private final Class[] actualTypeArguments; ExtendsType( final Class rawType, final Class[] actualTypeArguments) { this.rawType = rawType; this.actualTypeArguments = actualTypeArguments; } public Class getRawType() { return rawType; } public Class[] getActualTypeArguments() { return actualTypeArguments; } } public static final java.lang.reflect.Type makeTypeExtends(final Class rawType, final Class... actualTypeArguments) { return new ExtendsType(rawType, actualTypeArguments); } }
package net.sf.saffron.oj; import net.sf.saffron.core.ImplementableTable; import net.sf.saffron.oj.convert.*; import net.sf.saffron.oj.rel.*; import org.eigenbase.oj.rel.*; import org.eigenbase.rel.*; import org.eigenbase.rel.convert.ConverterRule; import org.eigenbase.rel.convert.FactoryConverterRule; import org.eigenbase.rel.jdbc.JdbcQuery; import org.eigenbase.relopt.*; import org.eigenbase.relopt.RelOptPlanner; import org.eigenbase.relopt.volcano.*; import org.eigenbase.reltype.RelDataType; /** * OJPlannerFactory constructs planners initialized to handle all calling * conventions, rules, and relational expressions needed to preprocess Saffron * extended Java. * * @version $Id$ */ public class OJPlannerFactory { private static ThreadLocal<OJPlannerFactory> threadInstances = new ThreadLocal<OJPlannerFactory>(); public static void setThreadInstance(OJPlannerFactory plannerFactory) { threadInstances.set(plannerFactory); } public static OJPlannerFactory threadInstance() { return threadInstances.get(); } public RelOptPlanner newPlanner() { VolcanoPlanner planner = new VolcanoPlanner(); planner.addRelTraitDef(CallingConventionTraitDef.instance); // Create converter rules for all of the standard calling conventions. add( planner, new CollectionToArrayConvertlet()); add( planner, new VectorToArrayConvertlet()); add( planner, new ArrayToJavaConvertlet()); add( planner, new IteratorToJavaConvertlet()); add( planner, new EnumerationToJavaConvertlet()); add( planner, new VectorToJavaConvertlet()); add( planner, new MapToJavaConvertlet()); add( planner, new HashtableToJavaConvertlet()); add( planner, new IterableToJavaConvertlet()); add( planner, new ResultSetToJavaConvertlet()); add( planner, new JavaToCollectionConvertlet()); add( planner, new VectorToEnumerationConvertlet()); add( planner, new JavaToExistsConvertlet()); add( planner, new ArrayToExistsConvertlet()); add( planner, new IteratorToExistsConvertlet()); add( planner, new MapToExistsConvertlet()); add( planner, new HashtableToExistsConvertlet()); add( planner, new EnumerationToExistsConvertlet()); add( planner, new CollectionToExistsConvertlet()); add( planner, new JavaToIterableConvertlet()); add( planner, new IteratorToIterableConvertlet()); add( planner, new CollectionToIterableConvertlet()); add( planner, new VectorToIterableConvertlet()); add( planner, new IterableToIteratorConvertlet()); add( planner, new CollectionToIteratorConvertlet()); add( planner, new VectorToIteratorConvertlet()); add( planner, new EnumerationToIteratorConvertlet()); add( planner, new ResultSetToIteratorConvertlet()); add( planner, new IteratorToResultSetConvertlet()); add( planner, new JavaToVectorConvertlet()); planner.registerAbstractRelationalRules(); // custom rules // REVIEW jvs 24-Sept-2003: These were commented out in // VolcanoPlanner. /* addRule(new ExpressionReader.MapToHashtableReaderRule()); addRule(new Exp.IteratorExpressionRule()); // todo: enable addRule(new Exp.PlanExpressionRule()); // todo: enable addRule(new Query.TranslateRule()); addRule(new In.InSemiJoinRule()); // todo: enable addRule(new RelWrapper.RemoveWrapperRule()); // todo: enable */ RelOptUtil.registerAbstractRels(planner); registerJavaRels(planner); registerIterRels(planner); // custom rels JdbcQuery.register(planner); return planner; } /** * Register all of the Java implementations for the abstract relational * operators, along with appropriate conversion rules. * * @param planner the planner in which to register the rules */ public static void registerJavaRels(VolcanoPlanner planner) { planner.addRule(new AggregateToJavaRule()); planner.addRule(new FilterToJavaRule()); planner.addRule(new OneRowToJavaRule()); planner.addRule(new DistinctToJavaRule()); planner.addRule(new DistinctToExistsRule()); planner.addRule(new JoinToJavaRule()); planner.addRule(new ProjectToJavaRule()); planner.addRule(new TableAccessToJavaRule()); planner.addRule(new UnionToJavaRule()); } public static void registerIterRels(VolcanoPlanner planner) { planner.addRule(new IterRules.UnionToIteratorRule()); planner.addRule(IterRules.OneRowToIteratorRule.instance); } /** * Wraps a convertlet in a {@link ConverterRule}, then registers it with a * planner. */ private static void add( RelOptPlanner planner, JavaConvertlet convertlet) { planner.addRule(new FactoryConverterRule(convertlet)); } public static class AggregateToJavaRule extends ConverterRule { public AggregateToJavaRule() { super(AggregateRel.class, CallingConvention.NONE, CallingConvention.JAVA, "AggregateToJavaRule"); } public RelNode convert(RelNode rel) { final AggregateRel aggregate = (AggregateRel) rel; final RelNode javaChild = mergeTraitsAndConvert( aggregate.getTraits(), CallingConvention.JAVA, aggregate.getChild()); if (javaChild == null) { return null; } return new JavaAggregateRel( aggregate.getCluster(), javaChild, aggregate.getGroupCount(), aggregate.getAggCallList()); } } /** * Rule to translate a {@link net.sf.saffron.oj.rel.JavaDistinctRel} into a * {@link net.sf.saffron.oj.rel.JavaExistsRel}, provided that the select * list contains zero columns. */ public static class DistinctToExistsRule extends RelOptRule { public DistinctToExistsRule() { super(new RelOptRuleOperand(JavaDistinctRel.class, ANY)); } public void onMatch(RelOptRuleCall call) { JavaDistinctRel distinct = (JavaDistinctRel) call.rels[0]; RelDataType rowType = distinct.getChild().getRowType(); if (rowType.getFieldList().size() == 0) { call.transformTo( new JavaExistsRel( distinct.getCluster(), distinct.getChild())); } } } public static class DistinctToJavaRule extends ConverterRule { public DistinctToJavaRule() { super( AggregateRel.class, CallingConvention.NONE, CallingConvention.JAVA, "DistinctToJavaRule"); } public RelNode convert(RelNode rel) { final AggregateRel distinct = (AggregateRel) rel; if (!distinct.isDistinct()) { return null; } final RelNode javaChild = mergeTraitsAndConvert( distinct.getTraits(), CallingConvention.JAVA, distinct.getChild()); if (javaChild == null) { return null; } return new JavaDistinctRel( distinct.getCluster(), javaChild); } } public static class FilterToJavaRule extends ConverterRule { public FilterToJavaRule() { super(FilterRel.class, CallingConvention.NONE, CallingConvention.JAVA, "FilterToJavaRule"); } public RelNode convert(RelNode rel) { final FilterRel filter = (FilterRel) rel; final RelNode javaChild = mergeTraitsAndConvert( filter.getTraits(), CallingConvention.JAVA, filter.getChild()); if (javaChild == null) { return null; } return new JavaFilterRel( filter.getCluster(), javaChild, filter.getCondition()); } } public static class JoinToJavaRule extends ConverterRule { public JoinToJavaRule() { super(JoinRel.class, CallingConvention.NONE, CallingConvention.JAVA, "JoinToJavaRule"); } public RelNode convert(RelNode rel) { final JoinRel join = (JoinRel) rel; CallingConvention convention = CallingConvention.JAVA; String [] variables = RelOptUtil.getVariablesSetAndUsed( join.getRight(), join.getLeft()); if (variables.length > 0) { // Can't implement if left is dependent upon right (don't worry, // we'll be called with left and right swapped, if that's // possible) return null; } final RelNode convertedLeft = mergeTraitsAndConvert( join.getTraits(), convention, join.getLeft()); if (convertedLeft == null) { return null; } final RelNode convertedRight = mergeTraitsAndConvert( join.getTraits(), convention, join.getRight()); if (convertedRight == null) { return null; } return new JavaNestedLoopJoinRel( join.getCluster(), convertedLeft, convertedRight, join.getCondition().clone(), join.getJoinType(), join.getVariablesStopped()); } } /** * Converts a {@link OneRowRel} to {@link CallingConvention#JAVA Java * calling convention}. */ public static class OneRowToJavaRule extends ConverterRule { public OneRowToJavaRule() { super(OneRowRel.class, CallingConvention.NONE, CallingConvention.JAVA, "OneRowToJavaRule"); } public RelNode convert(RelNode rel) { // REVIEW: SWZ: 3/5/2005: Might need to propagate other // traits fro OneRowRel to JavaOneRowRel final OneRowRel oneRow = (OneRowRel) rel; return new JavaOneRowRel(oneRow.getCluster()); } } /** * Converts a {@link ProjectRel} to {@link CallingConvention#JAVA Java * calling convention}. */ public static class ProjectToJavaRule extends ConverterRule { public ProjectToJavaRule() { super(ProjectRel.class, CallingConvention.NONE, CallingConvention.JAVA, "ProjectToJavaRule"); } public RelNode convert(RelNode rel) { final ProjectRel project = (ProjectRel) rel; final RelNode javaChild = mergeTraitsAndConvert( project.getTraits(), CallingConvention.JAVA, project.getChild()); if (javaChild == null) { return null; } return new JavaProjectRel( project.getCluster(), javaChild, project.getProjectExps(), project.getRowType(), project.getFlags()); } } /** * Rule to converts a {@link TableAccessRel} to {@link * CallingConvention#JAVA Java calling convention}. */ public static class TableAccessToJavaRule extends ConverterRule { public TableAccessToJavaRule() { super(TableAccessRel.class, CallingConvention.NONE, CallingConvention.JAVA, "TableAccessToJavaRule"); } public RelNode convert(RelNode rel) { final TableAccessRel tableAccess = (TableAccessRel) rel; if (!(tableAccess.getTable() instanceof ImplementableTable)) { return null; } return new JavaTableAccessRel( tableAccess.getCluster(), (ImplementableTable) tableAccess.getTable(), tableAccess.getConnection()); } } /** * Rule to converts a {@link UnionRel} to {@link CallingConvention#JAVA * Java calling convention}. */ public static class UnionToJavaRule extends ConverterRule { public UnionToJavaRule() { super(UnionRel.class, CallingConvention.NONE, CallingConvention.JAVA, "UnionToJavaRule"); } public RelNode convert(RelNode rel) { final UnionRel union = (UnionRel) rel; if (union.isDistinct()) { return null; // can only convert non-distinct Union } RelNode [] newInputs = new RelNode[union.getInputs().length]; for (int i = 0; i < newInputs.length; i++) { newInputs[i] = mergeTraitsAndConvert( union.getTraits(), CallingConvention.JAVA, union.getInputs()[i]); if (newInputs[i] == null) { return null; // cannot convert this input } } return new JavaUnionAllRel( union.getCluster(), newInputs); } } } // End OJPlannerFactory.java
/* * $Id$ * $URL$ */ package org.subethamail.web.action; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.subethamail.core.admin.i.ConfigData; import org.subethamail.web.Backend; import org.subethamail.web.action.auth.AuthAction; import org.subethamail.web.model.ErrorMapModel; import org.tagonist.propertize.Property; /** * Configures settings specific to the site. * * @author Jon Stevens */ public class GetSiteSettings extends AuthAction { private static Log log = LogFactory.getLog(GetSiteSettings.class); public static class Model extends ErrorMapModel { @Property List<ConfigData> configData; @Property String siteUrl; } public void initialize() { this.getCtx().setModel(new Model()); } public void execute() throws Exception { Model model = (Model)this.getCtx().getModel(); model.configData = Backend.instance().getAdmin().getSiteConfig(); for (ConfigData cd : model.configData) { //TODO: don't use this string here, use the key when it is accessible. if(cd.getId().equals("siteUrl")) { model.siteUrl = cd.getValue().toString(); break; } } } }
package org.goplayer.game; import static org.junit.Assert.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.goplayer.go.Goban; import org.goplayer.go.Stone; import org.goplayer.go.StoneColor; import org.goplayer.util.Coord; import org.junit.Test; public class BlockTest { @Test public void testGenerationFromFreePlace() { int size = 5; Goban goban = new Goban(size); int startRow = 2; int startCol = 3; try { Block.generateFrom(goban, startRow, startCol); fail("No exception thrown"); } catch (IllegalArgumentException e) { } } @Test public void testGenerationFromIsolatedPlace() { int size = 5; Goban goban = new Goban(size); int startRow = 2; int startCol = 3; goban.setCoordContent(startRow, startCol, new Stone(StoneColor.BLACK)); Block block = Block.generateFrom(goban, startRow, startCol); assertEquals(1, block.getStones().size()); assertTrue(block.getStones().contains( goban.getCoordContent(startRow, startCol))); assertEquals(4, block.getLiberties().size()); assertTrue(block.getLiberties().contains( new Coord(startRow + 1, startCol))); assertTrue(block.getLiberties().contains( new Coord(startRow - 1, startCol))); assertTrue(block.getLiberties().contains( new Coord(startRow, startCol + 1))); assertTrue(block.getLiberties().contains( new Coord(startRow, startCol - 1))); assertEquals(StoneColor.BLACK, block.getColor()); } @Test public void testGenerationFromFullGoban() { int size = 5; Goban goban = Goban.createFullGoban(size, size, StoneColor.BLACK); int startRow = 2; int startCol = 3; Block block = Block.generateFrom(goban, startRow, startCol); assertEquals(size * size, block.getStones().size()); for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { assertTrue(block.getStones().contains( goban.getCoordContent(row, col))); } } assertEquals(0, block.getLiberties().size()); assertEquals(StoneColor.BLACK, block.getColor()); } @Test public void testGenerationFromCustomBlock() { int size = 5; Goban goban = new Goban(size); // create custom white block // --000 Map<Coord, Stone> target = new HashMap<Coord, Stone>(); target.put(new Coord(1, 3), new Stone(StoneColor.WHITE)); target.put(new Coord(2, 2), new Stone(StoneColor.WHITE)); target.put(new Coord(2, 3), new Stone(StoneColor.WHITE)); target.put(new Coord(2, 4), new Stone(StoneColor.WHITE)); target.put(new Coord(3, 4), new Stone(StoneColor.WHITE)); target.put(new Coord(4, 4), new Stone(StoneColor.WHITE)); target.put(new Coord(4, 3), new Stone(StoneColor.WHITE)); // fill block for (Map.Entry<Coord, Stone> entry : target.entrySet()) { int row = entry.getKey().getRow(); int col = entry.getKey().getCol(); Stone stone = entry.getValue(); goban.setCoordContent(row, col, stone); } // add whites which touch only // --000 goban.setCoordContent(0, 0, new Stone(StoneColor.WHITE)); goban.setCoordContent(1, 1, new Stone(StoneColor.WHITE)); goban.setCoordContent(3, 1, new Stone(StoneColor.WHITE)); // add some blacks // -0X0- // X-000 // -X-00 goban.setCoordContent(0, 3, new Stone(StoneColor.BLACK)); goban.setCoordContent(1, 2, new Stone(StoneColor.BLACK)); goban.setCoordContent(2, 0, new Stone(StoneColor.BLACK)); goban.setCoordContent(4, 1, new Stone(StoneColor.BLACK)); // compute expected liberties Set<Coord> liberties = new HashSet<Coord>(); liberties.add(new Coord(1, 4)); liberties.add(new Coord(2, 1)); liberties.add(new Coord(3, 2)); liberties.add(new Coord(3, 3)); liberties.add(new Coord(4, 2)); // check equivalence whatever we take as a start for (Coord start : target.keySet()) { Block block = Block.generateFrom(goban, start); assertTrue(block.getStones().containsAll(target.values())); assertTrue(target.values().containsAll(block.getStones())); assertTrue(block.getLiberties().containsAll(liberties)); assertTrue(liberties.containsAll(block.getLiberties())); assertEquals(StoneColor.WHITE, block.getColor()); } } }
package org.genericsystem.ui; import java.util.IdentityHashMap; import java.util.Map; import java.util.function.Function; import javafx.collections.ObservableList; public class ViewContext<N> { private final ViewContext<?> parent; private final Element<N> template; private final N node; private final ObservableList<N> nodeChildren; public ViewContext(ViewContext<?> parent, ModelContext modelContext, Element<N> template, N node) { this.parent = parent; this.template = template; this.node = node != null ? node : template.createNode(parent != null ? parent.getNode() : null); nodeChildren = this.parent != null ? (ObservableList<N>) ((Function) this.template.getGraphicChildren).apply(parent.node) : null; init(modelContext); } private void init(ModelContext modelContext) { modelContext.register(this); this.template.getBootList().forEach(boot -> boot.init(node)); for (Binding<N, ?, ?> binding : template.bindings) binding.init(modelContext, getNode()); for (Element<N> childElement : template.<N> getChildren()) { for (MetaBinding<N, ?> metaBinding : childElement.metaBindings) metaBinding.init(modelContext, this, childElement); if (childElement.metaBindings.isEmpty()) new ViewContext<>(this, modelContext, childElement, null); } if (parent != null) { int indexInChildren = parent.computeIndex(template); parent.incrementSize(template); nodeChildren.add(indexInChildren, node); map2.put(template, indexInChildren); } } public N getNode() { return node; } Map<Element<?>, Integer> map2 = new IdentityHashMap<Element<?>, Integer>() { private static final long serialVersionUID = 1L; @Override public Integer get(Object key) { Integer size = super.get(key); if (size == null) put((Element<?>) key, size = 0); return size; }; }; void destroyChild() { parent.decrementSize(template); nodeChildren.remove(getNode()); } void incrementSize(Element<?> child) { map2.put(child, map2.get(child) + 1); } void decrementSize(Element<?> child) { int size = map2.get(child) - 1; assert size >= 0; if (size == 0) map2.remove(child);// remove map if 0 for avoid heap pollution else map2.put(child, size); } int computeIndex(Element<?> childElement) { int indexInChildren = 0; for (Element<?> child : template.getChildren()) { indexInChildren += map2.get(child); if (child == childElement) break; } return indexInChildren; } }
package com.github.gwtd3.api.time; import java.util.Date; import com.github.gwtd3.api.arrays.Array; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsDate; public class Time extends JavaScriptObject { protected Time() { super(); } public final native TimeFormat format(String specifier) /*-{ return this.format(specifier); }-*/; /** * Create a TimeFormat builder. * * @return the builter. */ public final native TimeFormat.Builder format() /*-{ return this.format; }-*/; /** * Construct a linear time scale. * * @return time scale */ public final native TimeScale scale()/*-{ return this.scale(); }-*/; /** * Factory for interval of Seconds (e.g., 01:23:45.0000 AM). Always 1,000 * milliseconds long. * <p> * * @return the {@link Interval} */ public final native Interval second()/*-{ return this.second; }-*/; /** * Factory for interval of Minutes (e.g., 01:02:00 AM). Most browsers do not * support leap seconds, so minutes are almost always 60 seconds (6e4 * milliseconds) long. * * <p> * * @return the {@link Interval} */ public final native Interval minute()/*-{ return this.minute; }-*/; /** * Factory for interval of Hours (e.g., 01:00 AM). 60 minutes long (36e5 * milliseconds). Note that advancing time by one hour can return the same * hour number, or skip an hour number, due to Daylight Savings Time. * <p> * * @return the {@link Interval} */ public final native Interval hour()/*-{ return this.hour; }-*/; /** * Days (e.g., February 7, 2012 at 12:00 AM). Most days are 24 hours long * (864e5 milliseconds); however, with Daylight Savings Time, a day may be * 23 or 25 hours long. * * <p> * * @return the {@link Interval} */ public final native Interval day()/*-{ return this.day; }-*/; /** * Alias for {@link #sunday}. A week is always 7 days, but ranges between * 167 and 169 hours depending on Daylight Savings Time. * <p> * * @return the {@link Interval} */ public final native Interval week()/*-{ return this.week; }-*/; /** * Sunday-based weeks (e.g., February 5, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval sunday()/*-{ return this.sunday; }-*/; /** * Monday-based weeks (e.g., February 6, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval monday()/*-{ return this.monday; }-*/; /** * Tuesday-based weeks (e.g., February 7, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval tuesday()/*-{ return this.tuesday; }-*/; /** * Wednesday-based weeks (e.g., February 8, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval wednesday()/*-{ return this.wednesday; }-*/; /** * Thursday-based weeks (e.g., February 9, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval thursday()/*-{ return this.thursday; }-*/; /** * Friday-based weeks (e.g., February 10, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval friday()/*-{ return this.friday; }-*/; /** * Saturday-based weeks (e.g., February 11, 2012 at 12:00 AM). * <p> * * @return the {@link Interval} */ public final native Interval saturday()/*-{ return this.saturday; }-*/; /** * Months (e.g., February 1, 2012 at 12:00 AM). Ranges between 28 and 31 * days. * <p> * * @return the {@link Interval} */ public final native Interval month()/*-{ return this.month; }-*/; /** * Years (e.g., January 1, 2012 at 12:00 AM). Normal years are 365 days * long; leap years are 366. * <p> * * @return the {@link Interval} */ public final native Interval year()/*-{ return this.year; }-*/; /** * Alias for {@link #second().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> seconds(JsDate start, JsDate stop) { return second().range(start, stop); } /** * Alias for {@link #second().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> seconds(Date start, Date stop) { return second().range(start, stop); } /** * Alias for {@link #second().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> seconds(double start, double stop) { return second().range(start, stop); } /** * Alias for {@link #second().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> seconds(JsDate start, JsDate stop, double step) { return second().range(start, stop, step); } /** * Alias for {@link #second().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> seconds(Date start, Date stop, double step) { return second().range(start, stop, step); } /** * Alias for {@link #second().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> seconds(double start, double stop, double step) { return second().range(start, stop, step); } /** * Alias for {@link #minute().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> minutes(JsDate start, JsDate stop) { return minute().range(start, stop); } /** * Alias for {@link #minute().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> minutes(Date start, Date stop) { return minute().range(start, stop); } /** * Alias for {@link #minute().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> minutes(double start, double stop) { return minute().range(start, stop); } /** * Alias for {@link #minute().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> minutes(JsDate start, JsDate stop, double step) { return minute().range(start, stop, step); } /** * Alias for {@link #minute().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> minutes(Date start, Date stop, double step) { return minute().range(start, stop, step); } /** * Alias for {@link #minute().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> minutes(double start, double stop, double step) { return minute().range(start, stop, step); } /** * Alias for {@link #hour().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> hours(JsDate start, JsDate stop) { return hour().range(start, stop); } /** * Alias for {@link #hour().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> hours(Date start, Date stop) { return hour().range(start, stop); } /** * Alias for {@link #hour().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> hours(double start, double stop) { return hour().range(start, stop); } /** * Alias for {@link #hour().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> hours(JsDate start, JsDate stop, double step) { return hour().range(start, stop, step); } /** * Alias for {@link #hour().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> hours(Date start, Date stop, double step) { return hour().range(start, stop, step); } /** * Alias for {@link #hour().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> hours(double start, double stop, double step) { return hour().range(start, stop, step); } /** * Alias for {@link #day().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> days(JsDate start, JsDate stop) { return day().range(start, stop); } /** * Alias for {@link #day().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> days(Date start, Date stop) { return day().range(start, stop); } /** * Alias for {@link #day().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> days(double start, double stop) { return day().range(start, stop); } /** * Alias for {@link #day().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> days(JsDate start, JsDate stop, double step) { return day().range(start, stop, step); } /** * Alias for {@link #day().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> days(Date start, Date stop, double step) { return day().range(start, stop, step); } /** * Alias for {@link #day().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> days(double start, double stop, double step) { return day().range(start, stop, step); } /** * Alias for {@link #week().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> weeks(JsDate start, JsDate stop) { return week().range(start, stop); } /** * Alias for {@link #week().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> weeks(Date start, Date stop) { return week().range(start, stop); } /** * Alias for {@link #week().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> weeks(double start, double stop) { return week().range(start, stop); } /** * Alias for {@link #week().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> weeks(JsDate start, JsDate stop, double step) { return week().range(start, stop, step); } /** * Alias for {@link #week().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> weeks(Date start, Date stop, double step) { return week().range(start, stop, step); } /** * Alias for {@link #week().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> weeks(double start, double stop, double step) { return week().range(start, stop, step); } /** * Alias for {@link #sunday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> sundays(JsDate start, JsDate stop) { return sunday().range(start, stop); } /** * Alias for {@link #sunday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> sundays(Date start, Date stop) { return sunday().range(start, stop); } /** * Alias for {@link #sunday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> sundays(double start, double stop) { return sunday().range(start, stop); } /** * Alias for {@link #sunday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> sundays(JsDate start, JsDate stop, double step) { return sunday().range(start, stop, step); } /** * Alias for {@link #sunday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> sundays(Date start, Date stop, double step) { return sunday().range(start, stop, step); } /** * Alias for {@link #sunday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> sundays(double start, double stop, double step) { return sunday().range(start, stop, step); } /** * Alias for {@link #monday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> mondays(JsDate start, JsDate stop) { return monday().range(start, stop); } /** * Alias for {@link #monday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> mondays(Date start, Date stop) { return monday().range(start, stop); } /** * Alias for {@link #monday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> mondays(double start, double stop) { return monday().range(start, stop); } /** * Alias for {@link #monday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> mondays(JsDate start, JsDate stop, double step) { return monday().range(start, stop, step); } /** * Alias for {@link #monday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> mondays(Date start, Date stop, double step) { return monday().range(start, stop, step); } /** * Alias for {@link #monday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> mondays(double start, double stop, double step) { return monday().range(start, stop, step); } /** * Alias for {@link #tuesday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> tuesdays(JsDate start, JsDate stop) { return tuesday().range(start, stop); } /** * Alias for {@link #tuesday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> tuesdays(Date start, Date stop) { return tuesday().range(start, stop); } /** * Alias for {@link #tuesday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> tuesdays(double start, double stop) { return tuesday().range(start, stop); } /** * Alias for {@link #tuesday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> tuesdays(JsDate start, JsDate stop, double step) { return tuesday().range(start, stop, step); } /** * Alias for {@link #tuesday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> tuesdays(Date start, Date stop, double step) { return tuesday().range(start, stop, step); } /** * Alias for {@link #tuesday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> tuesdays(double start, double stop, double step) { return tuesday().range(start, stop, step); } /** * Alias for {@link #wednesday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> wednesdays(JsDate start, JsDate stop) { return wednesday().range(start, stop); } /** * Alias for {@link #wednesday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> wednesdays(Date start, Date stop) { return wednesday().range(start, stop); } /** * Alias for {@link #wednesday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> wednesdays(double start, double stop) { return wednesday().range(start, stop); } /** * Alias for {@link #wednesday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> wednesdays(JsDate start, JsDate stop, double step) { return wednesday().range(start, stop, step); } /** * Alias for {@link #wednesday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> wednesdays(Date start, Date stop, double step) { return wednesday().range(start, stop, step); } /** * Alias for {@link #wednesday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> wednesdays(double start, double stop, double step) { return wednesday().range(start, stop, step); } /** * Alias for {@link #thursday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> thursdays(JsDate start, JsDate stop) { return thursday().range(start, stop); } /** * Alias for {@link #thursday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> thursdays(Date start, Date stop) { return thursday().range(start, stop); } /** * Alias for {@link #thursday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> thursdays(double start, double stop) { return thursday().range(start, stop); } /** * Alias for {@link #thursday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> thursdays(JsDate start, JsDate stop, double step) { return thursday().range(start, stop, step); } /** * Alias for {@link #thursday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> thursdays(Date start, Date stop, double step) { return thursday().range(start, stop, step); } /** * Alias for {@link #thursday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> thursdays(double start, double stop, double step) { return thursday().range(start, stop, step); } /** * Alias for {@link #friday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> fridays(JsDate start, JsDate stop) { return friday().range(start, stop); } /** * Alias for {@link #friday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> fridays(Date start, Date stop) { return friday().range(start, stop); } /** * Alias for {@link #friday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> fridays(double start, double stop) { return friday().range(start, stop); } /** * Alias for {@link #friday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> fridays(JsDate start, JsDate stop, double step) { return friday().range(start, stop, step); } /** * Alias for {@link #friday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> fridays(Date start, Date stop, double step) { return friday().range(start, stop, step); } /** * Alias for {@link #friday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> fridays(double start, double stop, double step) { return friday().range(start, stop, step); } /** * Alias for {@link #saturday().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> saturdays(JsDate start, JsDate stop) { return saturday().range(start, stop); } /** * Alias for {@link #saturday().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> saturdays(Date start, Date stop) { return saturday().range(start, stop); } /** * Alias for {@link #saturday().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> saturdays(double start, double stop) { return saturday().range(start, stop); } /** * Alias for {@link #saturday().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> saturdays(JsDate start, JsDate stop, double step) { return saturday().range(start, stop, step); } /** * Alias for {@link #saturday().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> saturdays(Date start, Date stop, double step) { return saturday().range(start, stop, step); } /** * Alias for {@link #saturday().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> saturdays(double start, double stop, double step) { return saturday().range(start, stop, step); } /** * Alias for {@link #month().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> months(JsDate start, JsDate stop) { return month().range(start, stop); } /** * Alias for {@link #month().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> months(Date start, Date stop) { return month().range(start, stop); } /** * Alias for {@link #month().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> months(double start, double stop) { return month().range(start, stop); } /** * Alias for {@link #month().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> months(JsDate start, JsDate stop, double step) { return month().range(start, stop, step); } /** * Alias for {@link #month().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> months(Date start, Date stop, double step) { return month().range(start, stop, step); } /** * Alias for {@link #month().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> months(double start, double stop, double step) { return month().range(start, stop, step); } /** * Alias for {@link #year().range(JsDate start, JsDate stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> years(JsDate start, JsDate stop) { return year().range(start, stop); } /** * Alias for {@link #year().range(Date start, Date stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> years(Date start, Date stop) { return year().range(start, stop); } /** * Alias for {@link #year().range(double start, double stop)}. * * @param start * @param stop * @return */ public final Array<JsDate> years(double start, double stop) { return year().range(start, stop); } /** * Alias for {@link #year().range(JsDate start, JsDate stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> years(JsDate start, JsDate stop, double step) { return year().range(start, stop, step); } /** * Alias for {@link #year().range(Date start, Date stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> years(Date start, Date stop, double step) { return year().range(start, stop, step); } /** * Alias for {@link #year().range(double start, double stop, double step)}. * * @param start * @param stop * @return */ public final Array<JsDate> years(double start, double stop, double step) { return year().range(start, stop, step); } }
package com.exedio.cope; import java.util.Collection; import java.util.List; public final class CompositeCondition extends Condition { private final Operator operator; public final Condition[] conditions; /** * @throws NullPointerException if <tt>conditions==null</tt> * @throws RuntimeException if <tt>conditions.size()==0</tt> */ public CompositeCondition(final Operator operator, final List<? extends Condition> conditions) { this(operator, conditions.toArray(new Condition[conditions.size()])); } /** * @throws NullPointerException if <tt>conditions==null</tt> * @throws RuntimeException if <tt>conditions.length==0</tt> */ public CompositeCondition(final Operator operator, final Condition[] conditions) { if(operator==null) throw new NullPointerException("operator must not be null"); if(conditions==null) throw new NullPointerException("conditions must not be null"); if(conditions.length==0) throw new RuntimeException("composite condition must have at least one subcondition"); for(int i = 0; i<conditions.length; i++) if(conditions[i]==null) throw new NullPointerException("condition " + i + " must not be null"); this.operator = operator; this.conditions = conditions; } void append(final Statement bf) { bf.append('('); conditions[0].append(bf); for(int i = 1; i<conditions.length; i++) { bf.append(operator.sql); conditions[i].append(bf); } bf.append(')'); } void check(final Query query) { for(int i = 0; i<conditions.length; i++) conditions[i].check(query); } public boolean equals(final Object other) { if(!(other instanceof CompositeCondition)) return false; final CompositeCondition o = (CompositeCondition)other; if(!operator.equals(o.operator) || conditions.length!=o.conditions.length) return false; for(int i = 0; i<conditions.length; i++) { if(!conditions[i].equals(o.conditions[i])) return false; } return true; } public int hashCode() { int result = operator.hashCode(); for(int i = 0; i<conditions.length; i++) result = (31*result) + conditions[i].hashCode(); // may not be commutative return result; } public String toString() { final StringBuffer bf = new StringBuffer(); bf.append('('); bf.append(conditions[0].toString()); for(int i = 1; i<conditions.length; i++) { bf.append(operator). append(' '). append(conditions[i].toString()); } bf.append(')'); return bf.toString(); } public static final <E> CompositeCondition in(final Function<E> function, final Collection<E> values) { final EqualCondition[] result = new EqualCondition[values.size()]; int i = 0; for(E value : values) result[i++] = function.equal(value); return new CompositeCondition(Operator.OR, result); } static enum Operator { AND(" and "), OR(" or "); private final String sql; Operator(final String sql) { this.sql = sql; } } }
package com.cryart.sabbathschool; import android.app.Application; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.crashlytics.android.Crashlytics; import com.google.firebase.database.FirebaseDatabase; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.materialdrawer.util.AbstractDrawerImageLoader; import com.mikepenz.materialdrawer.util.DrawerImageLoader; import com.mikepenz.materialdrawer.util.DrawerUIUtils; import net.danlew.android.joda.JodaTimeAndroid; import io.fabric.sdk.android.Fabric; import rx.Scheduler; import rx.schedulers.Schedulers; public class SSApplication extends Application { private static SSApplication instance; private Scheduler defaultSubscribeScheduler; public static SSApplication get(Context context) { return (SSApplication) context.getApplicationContext(); } public static SSApplication get(){ return instance; } @Override public void onCreate() { super.onCreate(); instance = this; JodaTimeAndroid.init(this); FirebaseDatabase.getInstance().setPersistenceEnabled(true); Fabric.with(this, new Crashlytics()); DrawerImageLoader.init(new AbstractDrawerImageLoader() { @Override public void set(ImageView imageView, Uri uri, Drawable placeholder) { Glide.with(imageView.getContext()).load(uri).placeholder(placeholder).into(imageView); } @Override public void cancel(ImageView imageView) { Glide.clear(imageView); } @Override public Drawable placeholder(Context ctx, String tag) { if (DrawerImageLoader.Tags.PROFILE.name().equals(tag)) { return DrawerUIUtils.getPlaceHolder(ctx); } else if (DrawerImageLoader.Tags.ACCOUNT_HEADER.name().equals(tag)) { return new IconicsDrawable(ctx).iconText(" ").backgroundColorRes(com.mikepenz.materialdrawer.R.color.primary).sizeDp(56); } else if ("customUrlItem".equals(tag)) { return new IconicsDrawable(ctx).iconText(" ").backgroundColorRes(R.color.md_red_500).sizeDp(56); } return super.placeholder(ctx, tag); } }); } public Scheduler defaultSubscribeScheduler() { if (defaultSubscribeScheduler == null) { defaultSubscribeScheduler = Schedulers.io(); } return defaultSubscribeScheduler; } }
package com.cylexia.mobile.glyde.glue; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import android.view.KeyEvent; import com.cylexia.mobile.glyde.ViewActivity; import com.cylexia.mobile.lib.glue.FileManager; import com.cylexia.mobile.lib.glue.Glue; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import com.cylexia.mobile.glyde.VecText; public class ExtGlyde implements Glue.Plugin { public static final int GLUE_STOP_ACTION = -200; public static final String KEYDEF_USEID = "useid"; public static final String KEYDEF_LABEL = "label"; private final FileManager filemanager; private Bitmap bitstore; private Canvas plane; private Map<String, ImageMap> resources; private Map<String, Map<String, String>> styles; private Map<String, Button> buttons; private Map<String, Map<String, String>> keys; private List<String> button_sequence; private String action, action_params; private String resume_label; private String last_action_id; private String last_error_msg; private String window_title; private int window_width; private int window_height; private Timer timer; private String timer_label; private int timer_interval; private Paint background; private ViewActivity activity; private int _offset_x; private int _offset_y; public ExtGlyde( ViewActivity activity, FileManager fm) { super(); this.activity = activity; this.filemanager = fm; this.timer_interval = -1; } public void setSize( int width, int height ) { this.window_width = width; this.window_height = height; this.bitstore = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 ); this.plane = new Canvas( bitstore ); if( background != null ) { plane.drawRect( 0, 0, plane.getWidth(), plane.getHeight(), background ); } } public String getWindowTitle() { return window_title; } public int getWindowWidth() { return window_width; } public int getWindowHeight() { return window_height; } /** * If set then the script requests that the given action be performed then resumed from * getResumeLabel(). This is cleared once read * @return */ public String getAction() { String o = action; this.action = null; return o; } public String getActionParams() { return action_params; } /** * Certain actions call back to the runtime host and need to be resumed, resume from this label * This is cleared once read * @return */ public String getResumeLabel() { String o = resume_label; this.resume_label = null; return o; } /** * Called when this is attached to a {@link com.cylexia.mobile.lib.glue.Glue} instance * * @param g the instance being attached to */ @Override public void glueAttach(Glue g) { } /** * The bitmap the drawing operations use * @return */ public Bitmap getBitmap() { return bitstore; } /** * Called to execute a glue command * * @param w the command line. The command is in "_" * @param vars the current Glue variables map * @return 1 if the command was successful, 0 if it failed or -1 if it didn't belong to this * plugin */ @Override public int glueCommand( Glue glue, Map<String, String> w, Map<String, String> vars ) { String c = w.get( "_" ); if( c.startsWith( "f." ) ) { String wc = w.get( c ); String cmd = c.substring( 2 ); if( cmd.equals( "setwidth" ) || cmd.equals( "setviewwidth" ) ) { return setupView( w ); } else if( cmd.equals( "settitle" ) ) { this.window_title = wc; activity.setTitle( wc ); return 1; } else if( cmd.equals( "setoffsetx" ) ) { this._offset_x = intValueOf( w, c ); this._offset_y = intValueOf( w, "y", intValueOf( w, "aty" ) ); } else if( cmd.equals( "doaction" ) ) { return doAction( glue, wc, w ); } else if( cmd.equals( "clear" ) || cmd.equals( "clearview" ) ) { clearUI(); } else if( cmd.equals( "shade" ) || cmd.equals( "shadeview" ) ) { shadeUI(); } else if( cmd.equals( "loadresource" ) ) { return loadResource( glue, wc, valueOf( w, "as" ) ); } else if( cmd.equals( "removeresource" ) ) { if( resources != null ) { resources.remove( wc ); } } else if( cmd.equals( "definestyle" ) ) { defineStyle( wc, w ); } else if( cmd.equals( "getlastactionid" ) ) { vars.put( valueOf( w, "into" ), last_action_id ); } else if( cmd.equals( "onkeypressed" ) ) { addKeyPressedHandler( wc, w ); } else if( cmd.equals( "starttimerwithinterval" ) ) { startTimer( glue, intValueOf( w, c ), valueOf( w, "ontickgoto" ) ); } else if( cmd.equals( "stoptimer" ) ) { if( this.timer != null ) { timer.cancel(); this.timer = null; } } else if( cmd.equals( "drawas" ) ) { drawAs( wc, w ); } else if( cmd.equals( "writeas" ) ) { // TODO: colour return writeAs( wc, w ); } else if( cmd.equals( "markas" ) || cmd.equals( "addbutton" ) ) { return markAs( wc, w ); } else if( cmd.equals( "paintrectas" ) ) { return paintRectAs( wc, w, false ); } else if( cmd.equals( "paintfilledrectas" ) ) { return paintRectAs( wc, w, true ); } else if( cmd.equals( "exit" ) ) { activity.finish(); } else { if( cmd.endsWith( "as" ) ) { cmd = cmd.substring( 0, (cmd.length() - 2) ); if( styles.containsKey( cmd ) ) { w.put( "style", cmd ); return writeAs( wc, w ); } } return -1; } return 1; } return 0; } public void activityStart() { } public void activityStop() { // should we suspend the timer? } public void activityDestroy() { if( timer != null ) { timer.cancel(); } } public String tryKeyAction( int keycode, KeyEvent event ) { if( keys == null ) { return null; } String keyname; switch( keycode ) { case KeyEvent.KEYCODE_DPAD_UP: keyname = "$direction_up"; break; case KeyEvent.KEYCODE_DPAD_LEFT: keyname = "$direction_left"; break; case KeyEvent.KEYCODE_DPAD_DOWN: keyname = "$direction_down"; break; case KeyEvent.KEYCODE_DPAD_RIGHT: keyname = "$direction_right"; break; case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_BUTTON_A: keyname = "$direction_fire"; break; default: keyname = String.valueOf( keycode ); break; } if( keys.containsKey( keyname ) ) { Map<String, String> kdata = keys.get( keyname ); this.last_action_id = kdata.get( KEYDEF_USEID ); return kdata.get( KEYDEF_LABEL ); } return null; } public String getLabelForButtonAt( int x, int y ) { if( buttons != null ) { for( String id : button_sequence ) { Button btn = buttons.get( id ); if( btn.rect.contains( x, y ) ) { this.last_action_id = id; return btn.label; } } } return null; } /** * Get the id of the button at the given index * @param index the index of the button * @return the id or null if the index is out of bounds */ public String getButtonIdAtIndex( int index ) { if( button_sequence != null ) { if( (index >= 0) && (index < button_sequence.size()) ) { return button_sequence.get( index ); } } return null; } /** * Get the rect of the given indexed button * @param index the button index * @return the rect or null if index is out of bounds */ public Rect getButtonRectAtIndex( int index ) { if( button_sequence != null ) { String id = getButtonIdAtIndex( index ); if( id != null ) { return buttons.get( id ).rect; } } return null; } /** * Return the label for the given indexed button. Also sets the lastActionId value * @param index the index * @return the label or null if index is out of bounds */ public String getButtonLabelAtIndex( int index ) { if( button_sequence != null ) { if( (index >= 0) && (index < button_sequence.size()) ) { String id = button_sequence.get( index ); if( id != null ) { this.last_action_id = id; return buttons.get( id ).label; } } } return null; } public int getButtonSize() { if( button_sequence != null ) { return button_sequence.size(); } else { return 0; } } public String getLastErrorMessage() { try { return last_error_msg; } finally { this.last_error_msg = null; } } private void addKeyPressedHandler( String key, Map<String, String> data ) { if( keys == null ) { keys = new HashMap<String, Map<String, String>>(); } if( key.equals( " key = " } else if( (key.length() > 0) && key.startsWith( " try { key = String.valueOf( (char)Integer.parseInt( key.substring( 1 ) ) ); } catch( NumberFormatException ex ) { return; } } Map<String, String> k = new HashMap<String, String>(); k.put( "id", valueOf( data, KEYDEF_USEID ) ); k.put( "label", valueOf( data, KEYDEF_LABEL ) ); keys.put( key, k ); } /** * Add a definition to the (lazily created) styles map. Note, the complete string is stored * so beware that keys like "_" and "f.setstyle" are added too * @param name the name of the style * @param data the complete arguments string */ private void defineStyle(String name, Map<String, String> data) { if( styles == null ) { this.styles = new HashMap<String, Map<String, String>>(); } applyStyle( data ); styles.put( name, data ); } private int setupView( Map<String, String> w ) { if( w.containsKey( "backgroundcolour" ) ) { this.background = new Paint(); background.setColor( parseColour( w.get( "backgroundcolour" ) ) ); background.setStyle( Paint.Style.FILL_AND_STROKE ); plane.drawRect( 0, 0, plane.getWidth(), plane.getHeight(), background ); } else { this.background = null; } setSize( intValueOf( w, valueOf( w, "_" ) ), intValueOf( w, "height" ) ); return 1; } private void clearUI() { this.button_sequence = null; this.buttons = null; this.keys = null; setSize( window_width, window_height ); } private void shadeUI() { this.button_sequence = null; this.buttons = null; this.keys = null; Paint p = new Paint(); p.setColor( Color.BLACK ); p.setStrokeWidth( 1 ); int i, e, s; if( window_width > window_height ) { e = (window_width * 2); s = window_height; } else { e = (window_height * 2); s = window_width; } for( i = 0; i <= e; i += 10 ) { plane.drawLine( i, 0, (i - s), s, p ); } } private int doAction( Glue g, String action, Map<String, String> w ) { this.action = action; this.action_params = valueOf( w, "args", valueOf( w, "withargs" ) ); String done_label = valueOf( w, "ondonegoto" ); // internal actions we can handle if( action.equals( "chrome.hide" ) ) { if( activity.getActionBar() != null ) { activity.getActionBar().hide(); } } else if( action.equals( "chrome.show" ) ) { if( activity.getActionBar() != null ) { activity.getActionBar().show(); } } else { // pass the action up to the activity to see if it can do it StringBuilder b = new StringBuilder(); b.append( done_label ).append( "\t" ); b.append( valueOf( w, "onerrorgoto", done_label ) ).append( "\t" ); b.append( valueOf( w, "onunsupportedgoto", done_label ) ); this.resume_label = b.toString(); return ExtGlyde.GLUE_STOP_ACTION; // expects labels to be DONE|ERROR|UNSUPPORTED } g.setRedirectLabel( done_label ); return Glue.PLUGIN_INLINE_REDIRECT; } private int createEntityAs( String id, Map<String, String> args ) { /* param used by does value text the text value size text thickness text textcolour text text colour linecolour rect the border colour fillcolour filledrect the fill colour align text text alignment */ int rx = intValueOf( args, "x", intValueOf( args, "atx" ) ); int ry = intValueOf( args, "y", intValueOf( args, "aty" ) ); int rw = intValueOf( args, "width" ); int rh = intValueOf( args, "height" ); Rect rect = new Rect( rx, ry, (rx + rw), (ry + rh) ); // if we're given an ID or RESOURCE value, the width and height values will be replaced // with those of the resource ImageMap resource = null; String resid, imgid = null; if( args.containsKey( "id" ) || args.containsKey( "resource" ) ) { String rid = valueOf( args, "id", valueOf( args, "resource" ) ); if( resources == null ) { return 0; } int b = rid.indexOf( '.' ); if( b > -1 ) { resid = rid.substring( 0, b ); imgid = rid.substring( (b + 1) ); if( resources.containsKey( resid ) ) { resource = resources.get( resid ); // imgmap: ExtGlyde.ImageMap Rect resrect = resource.getRectWithId( imgid ); rect = new Rect( rect.left, rect.top, (rect.left + resrect.width()), (rect.top + resrect.height()) ); } else { error( ("No such resource: " + resid) ); return 0; } } else { error( ("Invalid resource: " + rid) ); return 0; } } // filled rect first, then empty rect, resource and text int d, x, y; if( args.containsKey( "fillcolour" ) ) { drawRect( rect, parseColour( valueOf( args, "fillcolour" ) ), true ); } if( args.containsKey( "linecolour" ) ) { drawRect( rect, parseColour( valueOf( args, "linecolour" ) ), false ); } if( resource != null ) { if( !resource.drawToCanvas( imgid, plane, rect.left, rect.top ) ) { error( "[Glyde] Unable to draw resource" ); return 0; } } String text = valueOf( args, "value", "" ); if( text.length() > 0 ) { x = (rect.left + _offset_x); y = (rect.top + _offset_y); rw = rect.width(); rh = rect.height(); int size = intValueOf( args, "size", 2 ); int thickness = intValueOf( args, "thickness", 1 ); VecText v = VecText.getInstance(); int tw = (v.getGlyphWidth( size, thickness ) * text.length()); int th = v.getGlyphHeight( size, thickness ); int tx, ty; if( rw > 0 ) { String align = valueOf( args, "align", "2" ); if( align.equals( "2" ) || align.equals( "centre" ) ) { tx = (x + ((rw - tw) / 2)); } else if( align.equals( "1" ) || align.equals( "right" ) ) { tx = (x + (rw - tw)); } else { tx = x; } } else { rw = tw; tx = x; } if( rh > 0 ) { ty = (y + ((rh - th) / 2)); } else { rh = th; ty = y; } int clr = parseColour( valueOf( args, "textcolour", "#000" ) ); v.drawString( plane, text, clr, tx, ty, size, thickness, (thickness + 1) ); // if w/h were 0 then replace with the text w/h rect = new Rect( x, y, (x + rw), (y + rh) ); } return buttonise( id, rect.left, rect.top, rect.width(), rect.height(), args ); } private void drawRect( Rect r, int clr, boolean filled ) { Paint p = new Paint(); p.setColor( clr ); p.setStrokeWidth( 1 ); if( filled ) { p.setStyle( Paint.Style.FILL_AND_STROKE ); } else { p.setStyle( Paint.Style.STROKE ); } plane.drawRect( (r.left + _offset_x), (r.top + _offset_y), (r.right + _offset_x), (r.bottom + _offset_y), p ); } private void error( String msg ) { this.last_error_msg = msg; } // TODO: this should use a rect and alignment options along with colour support private int writeAs( String id, Map<String, String> args ) { applyStyle( args ); if( !args.containsKey( "textcolour" ) ) { args.put( "textcolour", valueOf( args, "colour" ) ); } return createEntityAs( id, args ); } private int drawAs( String id, Map<String, String> args ) { applyStyle( args ); return createEntityAs( id, args ); } private int markAs( String id, Map<String, String> args ) { applyStyle( args ); return buttonise( id, (intValueOf( args, "x", intValueOf( args, "atx" ) ) + _offset_x), (intValueOf( args, "y", intValueOf( args, "aty" ) ) + _offset_y), intValueOf( args, "width" ), intValueOf( args, "height" ), args ); } private int paintRectAs( String id, Map<String, String> args, boolean filled ) { applyStyle( args ); if( !args.containsKey( "linecolour" ) ) { args.put( "linecolour", valueOf( args, "colour", "#000" ) ); } if( filled ) { if( !args.containsKey( "fillcolour" ) ) { args.put( "fillcolour", valueOf( args, "colour", "#000" ) ); } } return createEntityAs( id, args ); } private int buttonise( String id, int x, int y, int w, int h, Map<String, String> args ) { if( args.containsKey( "border" ) ) { Paint p = new Paint(); p.setStrokeWidth( 1 ); // TODO: illegal colours (#xxx) throw an exception. this needs to be sorted for all parseColour instances p.setColor( parseColour( valueOf( args, "border" ) ) ); p.setStyle( Paint.Style.STROKE ); plane.drawRect( x, y, (x + w), (y + h), p ); } if( args.containsKey( "onclickgoto" ) ) { if( buttons == null ) { this.buttons = new HashMap<>(); this.button_sequence = new ArrayList<String>(); } if( !buttons.containsKey( id ) ) { buttons.put( id, new Button( x, y, w, h, valueOf( args, "onclickgoto" ) ) ); button_sequence.add( id ); return 1; } return 0; } else { return 1; } } private void applyStyle(Map<String, String> a) { if( styles == null ) { return; } if( a.containsKey( "style" ) ) { Map<String, String> style = styles.get( valueOf( a, "style" ) ); for( Map.Entry<String, String> kv : style.entrySet() ) { String k = kv.getKey(); if( !a.containsKey( k ) ) { a.put( k, kv.getValue() ); } } } } private void startTimer( Glue g, int interval, String label ) { if( timer != null ) { timer.cancel(); } this.timer = new Timer(); timer.schedule( new IntervalTask( g, label ), (interval * 100), (interval * 100) ); } private int loadResource( Glue g, String src, String id ) { if( resources == null ) { this.resources = new HashMap<String, ImageMap>(); } if( !resources.containsKey( id ) ) { try { g.setExtraErrorInfo( ("Unable to read from file [src=" + src + "; root=" + filemanager.getRoot().toString() + "]") ); String data = filemanager.readFromFile( src ); g.setExtraErrorInfo( ("Unable to load image map [data=" + ((data != null) ? data.substring( 0, 20 ) : "(null)") + "]") ); resources.put( id, new ImageMap( filemanager, data ) ); g.setExtraErrorInfo( null ); } catch( IOException ex ) { Log.e( "loadResource", ex.toString() ); return 0; } } return 1; } private int intValueOf( Map<String, String> w, String k ) { return intValueOf( w, k, 0 ); } private int intValueOf( Map<String, String> w, String k, int def ) { if( w.containsKey( k ) ) { try { return Integer.parseInt( w.get( k ) ); } catch( NumberFormatException ex ) { return 0; } } else { return def; } } private String valueOf( Map<String, String> w, String k ) { return valueOf( w, k, "" ); } private String valueOf( Map<String, String> w, String k, String def ) { if( w.containsKey( k ) ) { return w.get( k ); } else { return def; } } private static int parseColour( String clr ) { if( (clr == null) || (clr.length() == 0) ) { return Color.BLACK; } try { return Color.parseColor( clr ); } catch( IllegalArgumentException ex ) { if( (clr.length() == 4) && (clr.charAt( 0 ) == ' StringBuilder nclr = new StringBuilder( 7 ); nclr.append( ' nclr.append( clr.charAt( 1 ) ).append( clr.charAt( 1 ) ); nclr.append( clr.charAt( 2 ) ).append( clr.charAt( 2 ) ); nclr.append( clr.charAt( 3 ) ).append( clr.charAt( 3 ) ); try { return Color.parseColor( nclr.toString() ); } catch( IllegalArgumentException ex2 ) { return Color.BLACK; } } else { return Color.BLACK; } } } /** * Stores a button */ private static class Button { public final Rect rect; public final String label; public Button( int x, int y, int w, int h, String label ) { super(); this.rect = new Rect( x, y, (x + w), (y + h) ); this.label = label; } } /** * Processes a .map source loading the image named in it or the specified image */ private static class ImageMap { private Bitmap bitmap; private final HashMap<String, Rect> rects; public ImageMap( FileManager fm, String mapdata ) throws IOException { this( fm, mapdata, null ); } public ImageMap( FileManager fm, String mapdata, String bmpsrc ) throws IOException { super(); this.rects = new HashMap<>(); int e; String key, value; for( String line : mapdata.split( ";" ) ) { line = line.trim(); e = line.indexOf( "=" ); if( e > -1 ) { key = line.substring( 0, e ); value = line.substring( (e + 1) ); if( key.startsWith( "." ) ) { if( key.equals( ".img" ) ) { if( bmpsrc == null ) { bmpsrc = value; } } } else { rects.put( key, _decodeRect( value ) ); } } } _loadBitmap( fm, bmpsrc ); } public Rect getRectWithId( String id ) { return rects.get( id ); } public boolean drawToCanvas( String id, Canvas g, int x, int y ) { return drawToCanvas( id, g, x, y, null ); } public boolean drawToCanvas( String id, Canvas g, int x, int y, Paint p ) { if( bitmap == null ) { return false; } Rect src = getRectWithId( id ); if( src != null ) { Rect dest = new Rect( x, y, (x + src.width()), (y + src.height()) ); g.drawBitmap( bitmap, src, dest, p ); return true; } return false; } private void _loadBitmap( FileManager fm, String src ) throws IOException { if( src.isEmpty() ) { return; } this.bitmap = fm.getBitmap( src ); if( bitmap == null ) { throw new IOException( ("Unable to load map specified bitmap: " + fm.getFile( src ).getAbsolutePath()) ); } } private Rect _decodeRect( String e ) { if( e.charAt( 1 ) == ':' ) { int l = ((int)e.charAt( 0 ) - (int)'0'); int i = 2, x, y, w, h; try { x = Integer.parseInt( e.substring( i, (i + l) ) ); i += l; y = Integer.parseInt( e.substring( i, (i + l) ) ); i += l; w = Integer.parseInt( e.substring( i, (i + l) ) ); i += l; h = Integer.parseInt( e.substring( i ) ); return new Rect( x, y, (x + w), (y + h) ); } catch( NumberFormatException ex ) { return null; } } return null; } } /** * Runs a label on a timer */ private class IntervalTask extends TimerTask { private Glue glue; private String label; /** * Creates a new {@code TimerTask}. */ protected IntervalTask( Glue g, String label ) { super(); this.glue = g; this.label = label; } /** * The task to run should be specified in the implementation of the {@code run()} method. */ @Override public void run() { // we're on a different thread, Glue needs to run on the UI thread: ExtGlyde.this.activity.runOnUiThread( new Runnable() { public void run() { activity.runScriptAndSync( label ); } } ); } } }
package com.evgenii.walktocircle; public class WalkConstants { public static double mReachPositionVariationMeters = 50; // The height of the status bar in pixels. Used to avoid the circle from overlapping with the status bar. public static float statusBarHeightPixels = 50; // Name of the shared preferences for the app. public static String walkPreferencesName = "WalkToCirclePreferences91"; // The maximum time period for the location update to be running. // Location updates are stopped if they are running for longer time to save battery. public static int maximumLocationUpdatesRunningTimeSeconds = 30 * 60; // 30 minutes // How often the location updates are delivered to the app public static int locationUpdateIntervalMilliseconds = 5000; // Map position and zoom // The duration of the animation that centers the map on current user location // before dropping the pin, in milliseconds. public static int mapPositionAnimationDurationMilliseconds = 400; // The default zoom level of the map. The map is zoomed it this level before the pin is dropped. public static double mapInitialZoom = 16.3; // The maximum allowed difference between the current map zoom level and the "mapInitialZoom" // setting. If the difference is greater the map is zoomed at the "mapInitialZoom" level. // Units: the GoogleMap zoom level units. public static double mapZoomLevelDelta = 1; // The maximum allowed bearing from zero degrees. If bearing is greater the map's bearing // is set back to zero. public static float mapMaxBearing = 20; // The maximum allowed tilt of the map in degrees. If the map tilt is greater // the tilt is restored to zero. public static float mapMaxTilt = 10; // The multiplier to get the padding from the edge of the circle to the edge of the map on screen. // Example, if it is 1.3 and the radius of the circle is 100 pixels, the distance from circle center // to the map screen will be 130 pixels. public static float mapPaddingMultiplierFromCircleToMapEdgePixels = (float)1.3; // Map pin and circle public static float mapPinStrokeWidth = 4; public static long mapPinDropAnimationDuration = 700; public static double mapPinDropAnimationAmplitude = 0.11; public static double mapPinDropAnimationFrequency = 4.6; public static double mCircleRadiusMeters = 90; // Minimum distance of a pin from the current location, in meters public static double minCircleDistanceFromCurrentLocationMeters = 300; // Maximum distance of a pin from the current location, in meters public static double maxCircleDistanceFromCurrentLocationMeters = 500; // Sounds public static double mapPinThrowAndDropVolume = 1.0; public static double mapStartButtonBlopVolume = 0.4; public static double mapShowWalkScreenVolume = 0.2; public static double mapStartButtonCountdownClickVolume = 0.4; public static double congratsApplauseVolume = 0.4; }
package com.example.androidspp; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.view.View; import android.widget.TextView; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.UUID; public class TruePulseReader { private BluetoothDevice device; private BluetoothSocket btSocket; private TextView output; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); public TruePulseReader(BluetoothDevice device, TextView debugOutput) { this.device = device; output = debugOutput; } public void sendTestMessage() { try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { output.append("Fatal Error In onResume() and socket create failed: " + e.getMessage() + "."); e.printStackTrace(); return; } output.append("BluetoothSocket created \n"); try { btSocket.connect(); } catch (IOException e) { output.append("Fatal Error In onResume() and socket connect failed: " + e.getMessage() + "."); e.printStackTrace(); return; } output.append("BluetoothSocket connected \n"); DataOutputStream dos = null; try { dos = new DataOutputStream(btSocket.getOutputStream()); } catch (IOException e) { output.append("Fatal Error In onResume() output stream creation failed: " + e.getMessage() + "."); e.printStackTrace(); return; } output.append("Output stream created \n"); String message = "$DU,0\r\n"; try { dos.writeChars(message); dos.writeChars("$MM,0\r\n"); dos.writeChars("$GO\r\n"); dos.flush(); } catch (Exception e) { output.append("Fatal Error In onResume() output stream write failed: " + e.getMessage() + "."); e.printStackTrace(); return; } output.append("Message sent \n"); DataInputStream dataInputStream; try { dataInputStream = new DataInputStream(btSocket.getInputStream()); while (true) { String response = dataInputStream.readLine(); output.append("Response: " + response); Thread.sleep(500); dos.writeChars("$GO\r\n"); dos.flush(); } } catch (Exception e) { output.append("Fatal Error In onResume() input stream read failed: " + e.getMessage() + "."); e.printStackTrace(); return; } } }
package com.example.kanjuice; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.GridView; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class JuiceMenuActivity extends Activity { private static final String TAG = "JuiceMenuActivity"; private JuiceAdapter adapter; private boolean isInMultiSelectMode = false; private View goButton; private View cancelButton; private View actionButtonLayout; private View noNetworkView; private GridView juicesView; private View menuLoadingView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_juice_menu); setupViews(); startBluetoothDataReaderService(); } private void startBluetoothDataReaderService() { startService(new Intent(this, BluetoothReaderService.class)); } @Override protected void onPause() { super.onPause(); disableRecentAppsClick(); } @Override protected void onResume() { super.onResume(); exitMultiSelectMode(); fetchMenu(); } @Override public void onBackPressed() { if (isInMultiSelectMode) { exitMultiSelectMode(); } // else block back button } private void disableRecentAppsClick() { ActivityManager activityManager = (ActivityManager) getApplicationContext() .getSystemService(Context.ACTIVITY_SERVICE); activityManager.moveTaskToFront(getTaskId(), 0); } private void fetchMenu() { getJuiceServer().getJuices(new Callback<List<Juice>>() { @Override public void success(final List<Juice> juices, Response response) { JuiceMenuActivity.this.runOnUiThread(new Runnable() { @Override public void run() { menuLoadingView.setVisibility(View.GONE); juicesView.setVisibility(View.VISIBLE); onJuicesListReceived(juices); } }); } @Override public void failure(RetrofitError error) { Log.d(TAG, "Failed to fetch menu list : " + error); JuiceMenuActivity.this.runOnUiThread(new Runnable() { @Override public void run() { showNoNetworkView(); } }); } }); } private void showNoNetworkView() { noNetworkView.setVisibility(View.VISIBLE); juicesView.setVisibility(View.GONE); menuLoadingView.setVisibility(View.GONE); } private void onJuicesListReceived(List<Juice> juices) { decorate(juices); adapter.addAll(juices); } private void decorate(List<Juice> juices) { for (Juice juice : juices) { juice.imageId = JuiceDecorator.matchImage(juice.name); juice.kanId = JuiceDecorator.matchKannadaName(juice.name); } } private KanJuiceApp getApp() { return (KanJuiceApp) getApplication(); } private JuiceServer getJuiceServer() { return getApp().getJuiceServer(); } private void setupViews() { juicesView = (GridView) findViewById(R.id.grid); setupAdapter(juicesView); juicesView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onJuiceItemClick(position); } }); juicesView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { return onJuiceItemLongClick(position); } }); setupActionLayout(); setupNoNetworkLayout(); menuLoadingView = findViewById(R.id.loading); } private void setupNoNetworkLayout() { noNetworkView = findViewById(R.id.no_network_layout); findViewById(R.id.retry).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { menuLoadingView.setVisibility(View.VISIBLE); noNetworkView.setVisibility(View.INVISIBLE); fetchMenu(); } }); } private boolean onJuiceItemLongClick(int position) { if(((JuiceItem) adapter.getItem(position)).juiceName.equals("Register User")) { return false; } adapter.toggleSelectionChoice(position); if (!isInMultiSelectMode) { enterMultiSelectionMode(); } return true; } private void onJuiceItemClick(int position) { if (isInMultiSelectMode) { adapter.toggleSelectionChoice(position); } else { gotoSwipingScreen(position); } } private void setupActionLayout() { actionButtonLayout = findViewById(R.id.action_button_layout); goButton = actionButtonLayout.findViewById(R.id.order); goButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gotoSwipingScreen(); } }); cancelButton = actionButtonLayout.findViewById(R.id.cancel); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { exitMultiSelectMode(); } }); } private void setupAdapter(GridView juicesView) { adapter = new JuiceAdapter(this); juicesView.setAdapter(adapter); } private void exitMultiSelectMode() { adapter.reset(); isInMultiSelectMode = false; ObjectAnimator anim = ObjectAnimator.ofFloat(actionButtonLayout, "translationY", -20f, 200f); anim.setDuration(500); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { actionButtonLayout.setVisibility(View.INVISIBLE); } }); anim.start(); } private void enterMultiSelectionMode() { isInMultiSelectMode = true; actionButtonLayout.setVisibility(View.VISIBLE); ObjectAnimator anim = ObjectAnimator.ofFloat(actionButtonLayout, "translationY", 100f, -15f); anim.setDuration(500); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { actionButtonLayout.setVisibility(View.VISIBLE); } }); anim.start(); } private void gotoSwipingScreen() { gotoSwipingScreen(adapter.getSelectedJuices()); } private void gotoSwipingScreen(int position) { gotoSwipingScreen(new JuiceItem[]{ (JuiceItem) adapter.getItem(position)}); } private void gotoSwipingScreen(JuiceItem[] juiceItems) { Intent intent = new Intent(JuiceMenuActivity.this, UserInputActivity.class); intent.putExtra("juices", juiceItems); startActivity(intent); } }
package com.gabmus.co2photoeditor; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.MediaStore; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ShareActionProvider; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; public class MainActivity extends Activity { private final int REQUEST_IMAGE_CHOOSE=1; public static MainHelper helper; public static Bitmap appIcon; private Intent mShareIntent; private ShareActionProvider mShareActionProvider; public static DrawerLayout fxDrawer; public static int FXselected = -1; public static FrameLayout customViewLayout; public static Switch fxToggle; public static TextView textViewFXTitle; public static String strNoFXSelected; public static ListView slidersListView; public static FilterSurfaceView fsv; public static FXHandler FX; public static CustomFXAdapter effectsListAdapter; ListView effectsList; ListView presetList; public static Context context; ActionBarDrawerToggle drawerToggle; public static Handler toastHandler = new Handler(); public static Runnable toastRunnable; public static Runnable loadingRunnableShow; public static Runnable loadingRunnableDismiss; private boolean isFsvBig=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); helper= new MainHelper(this); setContentView(R.layout.activity_main); context = this; FX = new FXHandler(context); //initialize the filtersurfaceview customViewLayout = (FrameLayout) findViewById(R.id.customViewLayout); fsv = new FilterSurfaceView(getApplicationContext(), this); fsv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); customViewLayout.addView(fsv); fsv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { float scale = context.getResources().getDisplayMetrics().density; int pixels; if (!isFsvBig) { pixels = (int) (380 * scale + 0.5f); isFsvBig=true; } else { pixels = (int) (230 * scale + 0.5f); isFsvBig=false; } customViewLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, pixels)); if (helper.currentBitmap!=null) fsv.LoadBitmap(helper.currentBitmap); } }); //set default values on startup FX.initializeAll(fsv); appIcon=BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher); //receive share implicit intent helper.receiveShareIntent(); if (!helper.gotSharedPic && helper.choosePicOnStart && helper.currentBitmap==null) { startPickerIntent(); } toastRunnable = new Runnable() { public void run() { Toast.makeText(context, getString(R.string.toast_image_saved) + fsv.renderer.SavePath, Toast.LENGTH_LONG).show(); }}; loadingRunnableShow = new Runnable() { public void run() { helper.loadingDialog.show(); }}; loadingRunnableDismiss = new Runnable() { public void run() { helper.loadingDialog.dismiss(); }}; //welcome activity helper.checkAndWelcomeUser(); slidersListView = (ListView) findViewById(R.id.sliders_list_view); //navigation drawer management fxDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); getActionBar().setDisplayHomeAsUpEnabled(true); drawerToggle = new ActionBarDrawerToggle(this, fxDrawer, R.string.drawer_open, R.string.drawer_close) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); invalidateOptionsMenu(); } }; fxDrawer.setDrawerListener(drawerToggle); textViewFXTitle = (TextView) findViewById(R.id.textViewEffectTitle); strNoFXSelected = getString(R.string.effect_title_textview); fxToggle = (Switch) findViewById(R.id.switch1); effectsListAdapter=new CustomFXAdapter(this, FX.getFXnames(), FX.getFXicons()); effectsList = (ListView) findViewById(R.id.listView); effectsList.setAdapter(effectsListAdapter); effectsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { FXselected=i; FX.SelectFX(i); if (!FX.FXList[i].fxActive && (helper.sharedpreferences.getBoolean("pref_activate_onclick_key", true))) { fxToggle.setChecked(true); } fxDrawer.closeDrawers(); } }); //DONE: implement on switch state changed. //this makes the switches consistent and changes the FXList value to match the switch fxToggle.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { FX.enableFX(FXselected, fsv, true); } else { FX.enableFX(FXselected, fsv, false); } } }); presetList = (ListView) findViewById(R.id.listViewPresets); presetList.setAdapter(new CustomPresetAdapter(this, FX.getPresetNames())); presetList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { FXselected = -1; FX.resetAllFX(fsv); FX.PresetList[i].toggleAllFX(FX, fsv, true); fxDrawer.closeDrawers(); } }); mShareIntent = new Intent(); mShareIntent.setAction(Intent.ACTION_SEND);
package com.jigdraw.draw.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import com.jigdraw.draw.R; import com.jigdraw.draw.model.Difficulty; import com.jigdraw.draw.tasks.JigsawGenerator; import com.jigdraw.draw.views.DrawingView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Main activity class represents all the activities that a user starts with * such as draw, choose to create a new drawing, save the current drawing, * choose eraser and brush sizes etc. * * @author Jay Paulynice */ public class DrawActivity extends Activity implements OnClickListener { /** activity name for logging */ private static final String TAG = "DrawActivity"; /** custom drawing view */ private DrawingView drawView; /** buttons for drawing */ private ImageButton currPaint, eraseBtn, newBtn, saveBtn; /** brush sizes */ private float smallBrush, mediumBrush, largeBrush, largestBrush; /** list of brushes */ private List<ImageButton> brushes = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View view) { Log.d(TAG, "view id clicked: " + view.getId()); if (view.getId() == R.id.erase_btn) { handleEraseButton(); } else if (view.getId() == R.id.new_btn) { handleNewButton(); } else if (view.getId() == R.id.save_btn) { handleSaveButton(); } } /** * Handle the change of the brush size * * @param view the current brush view */ public void handleBrushSize(View view) { //default to medium brush float bSize = mediumBrush; if (view.getId() == R.id.small_brush) { Log.d(TAG, "small brush clicked."); bSize = smallBrush; } else if (view.getId() == R.id.large_brush) { Log.d(TAG, "large brush clicked."); bSize = largeBrush; } else if (view.getId() == R.id.largest_brush) { Log.d(TAG, "largest brush clicked."); bSize = largestBrush; } drawView.setErase(false); drawView.setBrushSize(bSize); drawView.setLastBrushSize(bSize); } /** * Handles the change of color chosen * * @param view the view for the color chosen */ public void paintClicked(View view) { drawView.setErase(false); drawView.setBrushSize(drawView.getLastBrushSize()); if (view != currPaint) { String color = changeColor(view); setBrushColor(Color.parseColor(color)); } } /** * Change to selected color * * @param view the image button clicked * @return the color to set */ private String changeColor(View view) { ImageButton imgView = (ImageButton) view; String color = view.getTag().toString(); drawView.setColor(color); updateUI(imgView, view); return color; } /** * Update UI with new selected color * * @param imgView the image view * @param view the view */ private void updateUI(ImageButton imgView, View view) { imgView.setImageDrawable(getResources().getDrawable(R.drawable .paint_pressed)); currPaint.setImageDrawable(getResources().getDrawable(R.drawable .paint)); currPaint = (ImageButton) view; } /** * Set the brushes to the color chosen * * @param color the chosen color */ public void setBrushColor(int color) { initBrushList(); for (ImageButton im : brushes) { GradientDrawable d = (GradientDrawable) im.getDrawable(); d.setColor(color); } } /** * Make a list of the brushes */ private void initBrushList() { if (brushes.isEmpty()) { brushes.addAll(Arrays.asList( (ImageButton) findViewById(R.id.small_brush), (ImageButton) findViewById(R.id.medium_brush), (ImageButton) findViewById(R.id.large_brush), (ImageButton) findViewById(R.id.largest_brush))); } } /** * Initialize all the ui components */ private void init() { setContentView(R.layout.activity_main); initBrushes(); initView(); initLayout(); initButtons(); setBrushColor(drawView.getPaintColor()); } /** * Initialize the layout and set current color to first one */ private void initLayout() { LinearLayout paintLayout = (LinearLayout) findViewById(R.id .paint_colors); currPaint = (ImageButton) paintLayout.getChildAt(0); currPaint.setImageDrawable(getResources().getDrawable(R.drawable .paint_pressed)); } /** * Initialize the drawing view */ private void initView() { drawView = (DrawingView) findViewById(R.id.drawing); drawView.setBrushSize(mediumBrush); } /** * Initialize the brushes */ private void initBrushes() { smallBrush = getResources().getInteger(R.integer.small_size); mediumBrush = getResources().getInteger(R.integer.medium_size); largeBrush = getResources().getInteger(R.integer.large_size); largestBrush = getResources().getInteger(R.integer.largest_size); } /** * Initialize the buttons */ private void initButtons() { //erase button eraseBtn = (ImageButton) findViewById(R.id.erase_btn); eraseBtn.setOnClickListener(this); //new button newBtn = (ImageButton) findViewById(R.id.new_btn); newBtn.setOnClickListener(this); //save button saveBtn = (ImageButton) findViewById(R.id.save_btn); saveBtn.setOnClickListener(this); } /** * Set erase to true on eraser click */ private void handleEraseButton() { drawView.setErase(true); } /** * Handle the new button click */ private void handleNewButton() { //new button AlertDialog.Builder newDialog = new AlertDialog.Builder(this); newDialog.setTitle("New drawing"); newDialog.setMessage("Start new drawing (you will lose the current " + "drawing)?"); newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { drawView.startNew(); dialog.dismiss(); } }); newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); newDialog.show(); } /** * Handle the save button click */ private void handleSaveButton() { CharSequence levels[] = new CharSequence[]{"Easy", "Medium", "Hard"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose difficulty:"); builder.setItems(levels, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { createJigsaw(which); } }); builder.show(); } /** * Create jigsaw and give user feedback */ private void createJigsaw(int which) { drawView.setDrawingCacheEnabled(true); Bitmap bitmap = drawView.getDrawingCache(); JigsawGenerator task = new JigsawGenerator(getApplicationContext(), getLevel(which)); toast(); task.execute(bitmap.copy(bitmap.getConfig(), true)); drawView.destroyDrawingCache(); } private Difficulty getLevel(int which) { switch (which) { case 0: return Difficulty.EASY; case 1: return Difficulty.MEDIUM; case 2: return Difficulty.HARD; default: throw new IllegalArgumentException("Unknown level"); } } /** * Get feedback if jigsaw is created or not * */ private void toast() { String feedback = "Loading jigsaw puzzle..."; Toast toast = Toast.makeText(getApplicationContext(), feedback, Toast.LENGTH_SHORT); toast.show(); } }
package com.malytic.altituden.classes; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.PolyUtil; import com.jjoe64.graphview.series.DataPoint; import com.malytic.altituden.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class PathData { private boolean isValid; public int length; public String encodedPolyline; public List<ElevationPoint> elevation; public List<LatLng> points; public int calories; private Context context; /** * Creates a new PathData object from a Google Directions response. * @param obj JSONObject containing directions data between two points. * @throws JSONException if provided JSONObject is invalid. */ public PathData(JSONObject obj) throws JSONException { isValid = false; encodedPolyline = extractEncodedPath(obj); elevation = null; points = PolyUtil.decode(encodedPolyline); length = extractPathLength(obj); isValid = true; calories = 0; } /** * Creates a new PathData object with all fields null. * Use to create an object when you don't have a directions * JSONObject yet. To check if the PathData object is valid * do yourObject.isValid(), returns true if it's valid, false otherwise. */ public PathData() { length = 0; encodedPolyline = null; elevation = null; points = null; isValid = false; } /** * Updates this objects path data. * @param obj Google Directions response JSONObject. * @throws JSONException if provided JSONObject is invalid. */ public void updatePath(JSONObject obj) throws JSONException { if(obj.getString("status").equals("OK")) { length = extractPathLength(obj); encodedPolyline = extractEncodedPath(obj); elevation = null; points = PolyUtil.decode(encodedPolyline); length = extractPathLength(obj); isValid = true; } } /** * Updates the objects elevation list and updates the calories. * @param obj JSONObject containing elevation information. * @throws JSONException if provided JSONObject is invalid. */ public void updateElevation(JSONObject obj, Context context) throws JSONException { elevation = extractElevation(obj); calories = calculateCalories(this, context); this.context = context; } /** * Updates the calorie count of this path. * @param context to get sharedPreferences. */ public void updateCalorieCount() { if(elevation != null && elevation.size() > 0 && context != null) calories = calculateCalories(this, context); } /** * Extracts the path length from a Google Directions response JSONObject. * @param obj Google Directions Response JSONObject. * @return Path length in meters. * @throws JSONException if provided JSONObject is invalid. */ public static int extractPathLength(JSONObject obj) throws JSONException { JSONArray routesArray; routesArray = obj.getJSONArray("routes"); JSONArray legsArray = null; for (int i = 0; i < routesArray.length(); i++) { JSONObject o = routesArray.getJSONObject(i); if (o != null) { legsArray = o.getJSONArray("legs"); } } int pathLength = 0; // extract the JSONObject with overview_polyline if (legsArray != null) { for (int i = 0; i < legsArray.length(); i++) { JSONObject o = legsArray.optJSONObject(i); if (o != null) { JSONObject distance = o.optJSONObject("distance"); pathLength = distance.getInt("value"); } } } return pathLength; } /** * Takes a JSONObject response from Google Directions API and * returns the encoded overview_polyline string. * @param obj Object containing Directions data. * @return String containing the overview_polyline. * @throws JSONException if provided JSONObject is invalid. */ public static String extractEncodedPath(JSONObject obj) throws JSONException { JSONArray routesArray; routesArray = obj.getJSONArray("routes"); String encodedOverviewPolyline = null; // extract the JSONObject with overview_polyline for(int i = 0; i < routesArray.length(); i++) { JSONObject o = routesArray.optJSONObject(i); if(o != null) { encodedOverviewPolyline = o.optJSONObject("overview_polyline").getString("points"); } } return encodedOverviewPolyline; } /** * Returns the validity of the PathData object. * @return true if valid, false otherwise. */ public boolean isValid() { return isValid; } /** * Builds a string request url to Google Elevation API from * an encoded overview_polyline string. * @param encodedPolyline encoded overview_polyline. * @param context Necessary to get the keys from android resources. * @return String request url to Google Elevation API. */ public static String getElevationUrl(String encodedPolyline, Context context) { String baseURL = "https://maps.googleapis.com/maps/api/elevation/json"; StringBuilder sb = new StringBuilder(); sb.append(baseURL); sb.append("?path=" + encodedPolyline); sb.append("&samples=" + 20); //TODO path_length/5 sb.append("&key=" + context.getResources().getString(R.string.google_server_key)); return sb.toString(); } /** * Takes a directions response JSONObject and returns a string * http-request URL for every point on the path provided. * @param obj JSONObject response from Doogle Directions API. * @param context needed to get the api-key from the android resources. * @return complete string URL for request to Google Elevation API * @throws JSONException if provided JSONObject is invalid. */ public static String getElevationUrl(JSONObject obj, Context context) throws JSONException { String baseURL = "https://maps.googleapis.com/maps/api/elevation/json"; StringBuilder sb = new StringBuilder(); sb.append(baseURL); sb.append("?path=enc:" + extractEncodedPath(obj)); //TODO split url into several requests when samples > 500 int samples = 512; sb.append("&samples=" + samples); sb.append("&key=" + context.getResources().getString(R.string.google_server_key)); return sb.toString(); } /** * Builds a string URL for a http-request to Google Directions API. * * @param context needed to get the api-key from the android resources. * @param origin LatLng point where the directions should start from. * @param dest LatLng point where the directions should end. * @return complete string URL for request to Google Directions API. */ public static String getDirectionsUrl(Context context, LatLng origin, LatLng dest) { StringBuilder sb = new StringBuilder(); sb.append("https://maps.googleapis.com/maps/api/directions/json?"); sb.append("origin=" + origin.latitude + "," + origin.longitude); sb.append("&destination=" + dest.latitude + "," + dest.longitude); sb.append("&mode=walking"); sb.append("&key=" + context.getResources().getString(R.string.google_server_key)); return sb.toString(); } /** * Extracts the elevation value from a response JSONObject. * @param obj JSONObject response from Google Elevation API * containing elevation data for one or more points. * @return List containing all the elevation points. * @throws JSONException when JSONObject does not contain * one of the fields. Probably due to passing an invalid * JSONObject (an object not from Google Elevation API). */ public static List<ElevationPoint> extractElevation(JSONObject obj) throws JSONException { ArrayList<ElevationPoint> result = new ArrayList<>(); JSONArray results = obj.getJSONArray("results"); for(int i = 0; i < results.length(); i ++) { JSONObject o = (JSONObject)results.get(i); if(o != null) { // create new ElevationPoint and add to result JSONObject location = o.getJSONObject("location"); LatLng point = new LatLng(location.getDouble("lat"), location.getDouble("lng")); ElevationPoint ePoint = new ElevationPoint(point, o.getDouble("elevation")); result.add(ePoint); } } return result; } /** * Parses and formats an encoded path of LatLngs and returns a string on the * form of "latitude1,longitude1|latitude2,longitude2|...". * @param encodedString string to parse * @return formatted string */ public static String formatPoints(String encodedString) { List<LatLng> points = PolyUtil.decode(encodedString); StringBuilder sb = new StringBuilder(); for(LatLng ll : points) { sb.append(ll.latitude + "," + ll.longitude + "|"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * Calculates the calories burned for a path. * Calories Burned = (((K1 x G) + K2) x WKG + TF) x DRK * where: G is angle in degrees, * WKG is weight in kilograms, * TF treadmill factor (air resistance), * DRK distance run in kilometers. * If the user is male the calories are multiplied by 0.08. * * The information about the user (weight, gender) is * acquired from SharedPreferences. * * @param pathData the path to calculate from * @return int total calories burned. */ public static int calculateCalories(PathData pathData, Context context) { //TODO calculate calories for path float calories = 0; int interpolationDistance = 100; float stepLength = ((float)pathData.length / (float)512); int step = (int)(interpolationDistance / stepLength); if(step >= 512) step = 511; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); int weight = sp.getInt("weight", -1); int gender = sp.getInt("gender", -1); boolean male = true; if(gender < 0) { male = false; } ElevationPoint start, end; boolean cond = true; double K1, K2; for(int i = 0; cond; i++) { int endStep = (i+1)*step; if(endStep >= 511) { endStep = 511; cond = false; } // find the angle between the points. double base = step*stepLength; start = pathData.elevation.get(i * step); end = pathData.elevation.get(endStep); double angle = Math.atan((base /(end.getElevation() - start.getElevation()))); base = Math.hypot(base, end.getElevation() - start.getElevation()); if(angle <= -15){ K1 = -.01; K2 = .5; } else if (angle > -15 && angle <= -10) { K1 = -.02; K2 = .35; } else if (angle > -10 && angle <= 0) { K1 = .04; K2 = .95; } else if (angle > 0 && angle <= 10) { K1 = .05; K2 = .95; } else if (angle > 10 && angle <= 15) { K1 = .07; K2 = .75; } else { K1 = .07; K2 = .75; } double pathCals = (((K1 * angle) + K2) * weight + 0.86) * base; calories += pathCals; } if(male) calories *= 1.08; return (int) calories / 1000; // per kilometer, not meter } }
package com.samourai.wallet.spend; import android.app.Activity; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SeekBar; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.BatchSendActivity; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.TxAnimUIActivity; import com.samourai.wallet.UTXOActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Activity; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.fragments.PaynymSelectModalFragment; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.ricochet.RicochetActivity; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SendParams; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.UTXOFactory; import com.samourai.wallet.spend.widgets.EntropyBar; import com.samourai.wallet.spend.widgets.SendTransactionDetailsView; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.SendAddressUtil; import com.yanzhenjie.zbar.Symbol; import org.apache.commons.lang3.tuple.Triple; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.script.Script; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Vector; public class SendActivity extends AppCompatActivity { private final static int SCAN_QR = 2012; private final static int RICOCHET = 2013; private static final String TAG = "SendActivity"; private SendTransactionDetailsView sendTransactionDetailsView; private ViewSwitcher amountViewSwitcher; private EditText toAddressEditText, btcEditText, satEditText; private TextView tvMaxAmount, tvReviewSpendAmount, tvTotalFee, tvToAddress, tvEstimatedBlockWait, tvSelectedFeeRate, tvSelectedFeeRateLayman, stoneWallDesc, stonewallOptionText, ricochetTitle, ricochetDesc; private Button btnReview, btnSend; private Switch ricochetHopsSwitch, stoneWallSwitch; private SeekBar feeSeekBar; private EntropyBar entropyBar; private long balance = 0L; private String strDestinationBTCAddress = null; private final static int FEE_LOW = 0; private final static int FEE_NORMAL = 1; private final static int FEE_PRIORITY = 2; private final static int FEE_CUSTOM = 3; private int FEE_TYPE = FEE_LOW; public final static int SPEND_SIMPLE = 0; public final static int SPEND_BOLTZMANN = 1; public final static int SPEND_RICOCHET = 2; private int SPEND_TYPE = SPEND_BOLTZMANN; private int selectedAccount = 0; private String strPCode = null; private long feeLow, feeMed, feeHigh; private String strPrivacyWarning; private ArrayList<UTXO> selectedUTXO; private long _change; private HashMap<String, BigInteger> receivers; private int changeType; private String address; private String message; private long amount; private int change_index; private String ricochetMessage; private JSONObject ricochetJsonObj = null; private int idxBIP44Internal = 0; private int idxBIP49Internal = 0; private int idxBIP84Internal = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); setSupportActionBar(findViewById(R.id.toolbar_send)); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); setTitle(""); //CustomView for showing and hiding body of th UI sendTransactionDetailsView = findViewById(R.id.sendTransactionDetailsView); //ViewSwitcher Element for toolbar section of the UI. //we can switch between Form and review screen with this element amountViewSwitcher = findViewById(R.id.toolbar_view_switcher); //Input elements from toolbar section of the UI toAddressEditText = findViewById(R.id.edt_send_to); btcEditText = findViewById(R.id.amountBTC); satEditText = findViewById(R.id.amountSat); tvToAddress = findViewById(R.id.to_address_review); tvReviewSpendAmount = findViewById(R.id.send_review_amount); tvMaxAmount = findViewById(R.id.totalBTC); //view elements from review segment and transaction segment can be access through respective //methods which returns root viewGroup entropyBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.entropyBar); btnReview = sendTransactionDetailsView.getTransactionView().findViewById(R.id.review_button); ricochetHopsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_hops_switch); ricochetTitle = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_desc); ricochetDesc = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_title); tvSelectedFeeRate = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate); tvSelectedFeeRateLayman = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate_in_layman); tvTotalFee = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_fee); btnSend = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.send_btn); feeSeekBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.fee_seekbar); tvEstimatedBlockWait = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.est_block_time); feeSeekBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.fee_seekbar); stoneWallSwitch = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.stone_wall_radio_btn); stonewallOptionText = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.textView_stonewall); stoneWallDesc = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.stonewall_desc); btcEditText.addTextChangedListener(BTCWatcher); satEditText.addTextChangedListener(satWatcher); btnReview.setOnClickListener(v -> review()); btnSend.setOnClickListener(v -> initiateSpend()); if (SamouraiWallet.getInstance().getShowTotalBalance()) { if (SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2) { selectedAccount = 1; } else { selectedAccount = 0; } } else { selectedAccount = 0; } View.OnClickListener clipboardCopy = view -> { ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = android.content.ClipData .newPlainText("Miner fee", tvTotalFee.getText()); if (cm != null) { cm.setPrimaryClip(clipData); Toast.makeText(this, getString(R.string.copied_to_clipboard), Toast.LENGTH_SHORT).show(); } }; tvTotalFee.setOnClickListener(clipboardCopy); tvSelectedFeeRate.setOnClickListener(clipboardCopy); SPEND_TYPE = SPEND_BOLTZMANN; saveChangeIndexes(); setUpRicochet(); setUpFee(); setBalance(); enableReviewButton(false); setUpBoltzman(); Bundle extras = getIntent().getExtras(); if (extras != null) { // bViaMenu = extras.getBoolean("via_menu", false); String strUri = extras.getString("uri"); strPCode = extras.getString("pcode"); if (strUri != null && strUri.length() > 0) { processScan(strUri); } if (strPCode != null && strPCode.length() > 0) { processPCode(strPCode, null); } } validateSpend(); } private void setUpBoltzman() { stonewallOptionText.setAlpha(1f); stoneWallSwitch.setAlpha(1f); stoneWallDesc.setAlpha(1f); stoneWallSwitch.setChecked(true); stoneWallSwitch.setEnabled(true); stoneWallSwitch.setOnCheckedChangeListener((compoundButton, checked) -> { SPEND_TYPE = checked ? SPEND_BOLTZMANN : SPEND_SIMPLE; //small delay for storing prefs. new Handler().postDelayed(() -> prepareSpend(), 100); }); } private void checkRicochetPossibility() { double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; return; } double dAmount = btc_amount; amount = Math.round(dAmount * 1e8); if (amount < (balance - (RicochetMeta.samouraiFeeAmountV2.add(BigInteger.valueOf(50000L))).longValue())) { ricochetDesc.setAlpha(1f); ricochetTitle.setAlpha(1f); ricochetHopsSwitch.setAlpha(1f); ricochetHopsSwitch.setEnabled(true); } else { ricochetDesc.setAlpha(.6f); ricochetTitle.setAlpha(.6f); ricochetHopsSwitch.setAlpha(.6f); ricochetHopsSwitch.setEnabled(false); } } private void enableReviewButton(boolean enable) { btnReview.setEnabled(enable); if (enable) { btnReview.setBackground(getDrawable(R.drawable.button_blue)); } else { btnReview.setBackground(getDrawable(R.drawable.disabled_grey_button)); } } private void setUpFee() { int multiplier = 10000; FEE_TYPE = PrefsUtil.getInstance(this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL); feeLow = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L; feeMed = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L; feeHigh = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L; float high = ((float) feeHigh / 2) + (float) feeHigh; int feeHighSliderValue = (int) (high * multiplier); int feeMedSliderValue = (int) (feeMed * multiplier); feeSeekBar.setMax(feeHighSliderValue - multiplier); if (feeLow == feeMed && feeMed == feeHigh) { feeLow = (long) ((double) feeMed * 0.85); feeHigh = (long) ((double) feeMed * 1.15); SuggestedFee lo_sf = new SuggestedFee(); lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L)); FeeUtil.getInstance().setLowFee(lo_sf); SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setHighFee(hi_sf); } else if (feeLow == feeMed || feeMed == feeMed) { feeMed = (feeLow + feeHigh) / 2L; SuggestedFee mi_sf = new SuggestedFee(); mi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setNormalFee(mi_sf); } else { ; } if (feeLow < 1L) { feeLow = 1L; SuggestedFee lo_sf = new SuggestedFee(); lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L)); FeeUtil.getInstance().setLowFee(lo_sf); } if (feeMed < 1L) { feeMed = 1L; SuggestedFee mi_sf = new SuggestedFee(); mi_sf.setDefaultPerKB(BigInteger.valueOf(feeMed * 1000L)); FeeUtil.getInstance().setNormalFee(mi_sf); } if (feeHigh < 1L) { feeHigh = 1L; SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setHighFee(hi_sf); } // tvEstimatedBlockWait.setText("6 blocks"); tvSelectedFeeRateLayman.setText(getString(R.string.normal)); FeeUtil.getInstance().sanitizeFee(); tvSelectedFeeRate.setText((String.valueOf((int) feeMed).concat(" sats/b"))); feeSeekBar.setProgress((feeMedSliderValue - multiplier) + 1); DecimalFormat decimalFormat = new DecimalFormat(" setFeeLabels(); feeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { double value = ((double) i + multiplier) / (double) multiplier; tvSelectedFeeRate.setText(String.valueOf(decimalFormat.format(value)).concat(" sats/b")); if (value == 0.0) { value = 1.0; } double pct = 0.0; int nbBlocks = 6; if (value <= (double) feeLow) { pct = ((double) feeLow / value); nbBlocks = ((Double) Math.ceil(pct * 24.0)).intValue(); } else if (value >= (double) feeHigh) { pct = ((double) feeHigh / value); nbBlocks = ((Double) Math.ceil(pct * 2.0)).intValue(); if (nbBlocks < 1) { nbBlocks = 1; } } else { pct = ((double) feeMed / value); nbBlocks = ((Double) Math.ceil(pct * 6.0)).intValue(); } tvEstimatedBlockWait.setText(nbBlocks + " blocks"); setFee(value); setFeeLabels(); restoreChangeIndexes(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { restoreChangeIndexes(); } }); switch (FEE_TYPE) { case FEE_LOW: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee()); FeeUtil.getInstance().sanitizeFee(); break; case FEE_PRIORITY: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); FeeUtil.getInstance().sanitizeFee(); break; default: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); FeeUtil.getInstance().sanitizeFee(); break; } } private void setFeeLabels() { float sliderValue = (((float) feeSeekBar.getProgress()) / feeSeekBar.getMax()); float sliderInPercentage = sliderValue * 100; if (sliderInPercentage < 33) { tvSelectedFeeRateLayman.setText(R.string.low); } else if (sliderInPercentage > 33 && sliderInPercentage < 66) { tvSelectedFeeRateLayman.setText(R.string.normal); } else if (sliderInPercentage > 66) { tvSelectedFeeRateLayman.setText(R.string.urgent); } } private void setFee(double fee) { double sanitySat = FeeUtil.getInstance().getHighFee().getDefaultPerKB().doubleValue() / 1000.0; final long sanityValue; if (sanitySat < 10.0) { sanityValue = 15L; } else { sanityValue = (long) (sanitySat * 1.5); } // String val = null; double d = FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0; NumberFormat decFormat = NumberFormat.getInstance(Locale.US); decFormat.setMaximumFractionDigits(3); decFormat.setMinimumFractionDigits(0); double customValue = 0.0; if (PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_TRUSTED_NODE, false)) { customValue = 0.0; } else { try { customValue = (double) fee; } catch (Exception e) { Toast.makeText(this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show(); return; } } SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long) (customValue * 1000.0))); FeeUtil.getInstance().setSuggestedFee(suggestedFee); prepareSpend(); } private void setUpRicochet() { ricochetHopsSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { SPEND_TYPE = SPEND_RICOCHET; PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, true); } else { SPEND_TYPE = stoneWallSwitch.isChecked() ? SPEND_BOLTZMANN : SPEND_SIMPLE; PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, false); } }); ricochetHopsSwitch.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_RICOCHET, false)); } private void setBalance() { try { balance = APIFactory.getInstance(SendActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(this).get().getAccount(selectedAccount).xpubstr()); } catch (IOException ioe) { ioe.printStackTrace(); balance = 0L; } catch (MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); balance = 0L; } catch (java.lang.NullPointerException npe) { npe.printStackTrace(); balance = 0L; } final String strAmount; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMaximumFractionDigits(8); nf.setMinimumFractionDigits(1); nf.setMinimumIntegerDigits(1); strAmount = nf.format(balance / 1e8); tvMaxAmount.setOnClickListener(view -> { btcEditText.setText(strAmount); }); tvMaxAmount.setText(strAmount + " " + getDisplayUnits()); } private TextWatcher BTCWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { satEditText.removeTextChangedListener(satWatcher); btcEditText.removeTextChangedListener(this); try { if (editable.toString().length() == 0) { satEditText.setText("0"); btcEditText.setText(""); satEditText.setSelection(satEditText.getText().length()); satEditText.addTextChangedListener(satWatcher); btcEditText.addTextChangedListener(this); return; } Double btc = Double.parseDouble(String.valueOf(editable)); if (btc > 21000000.0) { btcEditText.setText("0.00"); btcEditText.setSelection(btcEditText.getText().length()); satEditText.setText("0"); satEditText.setSelection(satEditText.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); String defaultSeparator = Character.toString(symbols.getDecimalSeparator()); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(max_len + 1); try { double d = NumberFormat.getInstance(Locale.US).parse(editable.toString()).doubleValue(); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { btcEditText.setText(s1.substring(0, s1.length() - 1)); btcEditText.setSelection(btcEditText.getText().length()); editable = btcEditText.getEditableText(); btc = Double.parseDouble(btcEditText.getText().toString()); } } } } catch (NumberFormatException nfe) { ; } catch (ParseException pe) { ; } Double sats = getSatValue(Double.valueOf(btc)); satEditText.setText(formattedSatValue(sats)); checkRicochetPossibility(); } } catch (NumberFormatException e) { e.printStackTrace(); } satEditText.addTextChangedListener(satWatcher); btcEditText.addTextChangedListener(this); validateSpend(); } }; private String formattedSatValue(Object number) { DecimalFormat decimalFormat = new DecimalFormat(" return decimalFormat.format(number).replace(",", " "); } private TextWatcher satWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { satEditText.removeTextChangedListener(this); btcEditText.removeTextChangedListener(BTCWatcher); try { if (editable.toString().length() == 0) { btcEditText.setText("0.00"); satEditText.setText(""); satEditText.addTextChangedListener(this); btcEditText.addTextChangedListener(BTCWatcher); return; } String cleared_space = editable.toString().replace(" ", ""); Double sats = Double.parseDouble(cleared_space); Double btc = getBtcValue(sats); String formatted = formattedSatValue(sats); satEditText.setText(formatted); satEditText.setSelection(formatted.length()); btcEditText.setText(String.format(Locale.ENGLISH, "%.8f", btc)); if (btc > 21000000.0) { btcEditText.setText("0.00"); btcEditText.setSelection(btcEditText.getText().length()); satEditText.setText("0"); satEditText.setSelection(satEditText.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } } catch (NumberFormatException e) { e.printStackTrace(); } satEditText.addTextChangedListener(this); btcEditText.addTextChangedListener(BTCWatcher); checkRicochetPossibility(); validateSpend(); } }; private void setToAddress(String string) { tvToAddress.setText(string); toAddressEditText.setText(string); } private String getToAddress() { if (toAddressEditText.getText().toString().trim().length() != 0) { return toAddressEditText.getText().toString(); } if (tvToAddress.getText().toString().length() != 0) { return tvToAddress.getText().toString(); } return ""; } private Double getBtcValue(Double sats) { return (double) (sats / 1e8); } private Double getSatValue(Double btc) { if (btc == 0) { return (double) 0; } return btc * 1e8; } private void review() { setUpBoltzman(); if (validateSpend() && prepareSpend()) { tvReviewSpendAmount.setText(btcEditText.getText().toString().concat(" BTC")); amountViewSwitcher.showNext(); hideKeyboard(); sendTransactionDetailsView.showReview(ricochetHopsSwitch.isChecked()); } } private void hideKeyboard() { InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(amountViewSwitcher.getWindowToken(), 0); } } private boolean prepareSpend() { restoreChangeIndexes(); double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount = btc_amount; amount = (long) (Math.round(dAmount * 1e8)); // Log.i("SendActivity", "amount:" + amount); address = strDestinationBTCAddress == null ? toAddressEditText.getText().toString().trim() : strDestinationBTCAddress; if ((FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) || PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false) { changeType = FormatsUtil.getInstance().isValidBech32(address) ? 84 : 49; } else { changeType = 44; } receivers = new HashMap<String, BigInteger>(); receivers.put(address, BigInteger.valueOf(amount)); if (changeType == 84) { change_index = idxBIP84Internal; } else if (changeType == 49) { change_index = idxBIP49Internal; } else { change_index = idxBIP44Internal; } // if possible, get UTXO by input 'type': p2pkh, p2sh-p2wpkh or p2wpkh, else get all UTXO long neededAmount = 0L; if (FormatsUtil.getInstance().isValidBech32(address)) { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, 0, UTXOFactory.getInstance().getCountP2WPKH(), 4).longValue(); // Log.d("SendActivity", "segwit:" + neededAmount); } else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, UTXOFactory.getInstance().getCountP2SH_P2WPKH(), 0, 4).longValue(); // Log.d("SendActivity", "segwit:" + neededAmount); } else { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(UTXOFactory.getInstance().getCountP2PKH(), 0, 4).longValue(); // Log.d("SendActivity", "p2pkh:" + neededAmount); } neededAmount += amount; neededAmount += SamouraiWallet.bDust.longValue(); // get all UTXO List<UTXO> utxos = SpendUtil.getUTXOS(SendActivity.this, address, neededAmount); List<UTXO> utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getP2WPKH().values()); List<UTXO> utxosP2SH_P2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getP2SH_P2WPKH().values()); List<UTXO> utxosP2PKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getP2PKH().values()); selectedUTXO = new ArrayList<UTXO>(); long totalValueSelected = 0L; long change = 0L; BigInteger fee = null; boolean canDoBoltzmann = true; // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "balance:" + balance); // insufficient funds if (amount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } // entire balance (can only be simple spend) else if (amount == balance) { // make sure we are using simple spend SPEND_TYPE = SPEND_SIMPLE; canDoBoltzmann = false; // Log.d("SendActivity", "amount == balance"); // take all utxos, deduct fee selectedUTXO.addAll(utxos); for (UTXO u : selectedUTXO) { totalValueSelected += u.getValue(); } // Log.d("SendActivity", "balance:" + balance); // Log.d("SendActivity", "total value selected:" + totalValueSelected); } else { ; } org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null; if (SPEND_TYPE == SPEND_RICOCHET) { boolean samouraiFeeViaBIP47 = false; if (BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) { samouraiFeeViaBIP47 = true; } ricochetJsonObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47); if (ricochetJsonObj != null) { try { long totalAmount = ricochetJsonObj.getLong("total_spend"); if (totalAmount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); ricochetHopsSwitch.setChecked(false); return false; } long hop0Fee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee"); long perHopFee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee_per_hop"); long ricochetFee = hop0Fee + (RicochetMeta.defaultNbHops * perHopFee); tvTotalFee.setText(Coin.valueOf(ricochetFee).toPlainString().concat(" BTC")); ricochetMessage = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) totalAmount))).concat(" BTC")); return true; } catch (JSONException je) { return false; } } return true; } else if (SPEND_TYPE == SPEND_BOLTZMANN) { Log.d("SendActivity", "needed amount:" + neededAmount); List<UTXO> _utxos1 = null; List<UTXO> _utxos2 = null; long valueP2WPKH = UTXOFactory.getInstance().getTotalP2WPKH(); long valueP2SH_P2WPKH = UTXOFactory.getInstance().getTotalP2SH_P2WPKH(); long valueP2PKH = UTXOFactory.getInstance().getTotalP2PKH(); Log.d("SendActivity", "value P2WPKH:" + valueP2WPKH); Log.d("SendActivity", "value P2SH_P2WPKH:" + valueP2SH_P2WPKH); Log.d("SendActivity", "value P2PKH:" + valueP2PKH); boolean selectedP2WPKH = false; boolean selectedP2SH_P2WPKH = false; boolean selectedP2PKH = false; if ((valueP2WPKH > (neededAmount * 2)) && FormatsUtil.getInstance().isValidBech32(address)) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2SH_P2WPKH > (neededAmount * 2)) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2PKH > (neededAmount * 2)) && !Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { Log.d("SendActivity", "set 1 P2PKH 2x"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else if (valueP2WPKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (valueP2SH_P2WPKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (valueP2PKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2PKH 2x"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else { ; } if (_utxos1 == null) { if (valueP2SH_P2WPKH > neededAmount) { Log.d("SendActivity", "set 1 P2SH_P2WPKH"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (valueP2WPKH > neededAmount) { Log.d("SendActivity", "set 1 P2WPKH"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (valueP2PKH > neededAmount) { Log.d("SendActivity", "set 1 P2PKH"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else { ; } } if (_utxos1 != null && _utxos2 == null) { if (!selectedP2SH_P2WPKH && valueP2SH_P2WPKH > neededAmount) { Log.d("SendActivity", "set 2 P2SH_P2WPKH"); _utxos2 = utxosP2SH_P2WPKH; } else if (!selectedP2WPKH && valueP2WPKH > neededAmount) { Log.d("SendActivity", "set 2 P2WPKH"); _utxos2 = utxosP2WPKH; } else if (!selectedP2PKH && valueP2PKH > neededAmount) { Log.d("SendActivity", "set 2 P2PKH"); _utxos2 = utxosP2PKH; } else { ; } } if (_utxos1 == null && _utxos2 == null) { // can't do boltzmann, revert to SPEND_SIMPLE canDoBoltzmann = false; SPEND_TYPE = SPEND_SIMPLE; } else { Log.d("SendActivity", "boltzmann spend"); Collections.shuffle(_utxos1); if (_utxos2 != null) { Collections.shuffle(_utxos2); } // boltzmann spend (STONEWALL) pair = SendFactory.getInstance(SendActivity.this).boltzmann(_utxos1, _utxos2, BigInteger.valueOf(amount), address); if (pair == null) { // can't do boltzmann, revert to SPEND_SIMPLE canDoBoltzmann = false; restoreChangeIndexes(); SPEND_TYPE = SPEND_SIMPLE; } else { canDoBoltzmann = true; } } } else { ; } if (SPEND_TYPE == SPEND_SIMPLE && amount == balance) { // do nothing, utxo selection handles above ; } // simple spend (less than balance) else if (SPEND_TYPE == SPEND_SIMPLE) { List<UTXO> _utxos = utxos; // sort in ascending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); Collections.reverse(_utxos); // get smallest 1 UTXO > than spend + fee + dust for (UTXO u : _utxos) { Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(u.getOutpoints())); if (u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2).longValue())) { selectedUTXO.add(u); totalValueSelected += u.getValue(); Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "single output"); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "value selected:" + u.getValue()); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size()); break; } } if (selectedUTXO.size() == 0) { // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); int selected = 0; int p2pkh = 0; int p2sh_p2wpkh = 0; int p2wpkh = 0; // get largest UTXOs > than spend + fee + dust for (UTXO u : _utxos) { selectedUTXO.add(u); totalValueSelected += u.getValue(); selected += u.getOutpoints().size(); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue())); Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector<MyTransactionOutPoint>(u.getOutpoints())); p2pkh += outpointTypes.getLeft(); p2sh_p2wpkh += outpointTypes.getMiddle(); p2wpkh += outpointTypes.getRight(); if (totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 2).longValue())) { Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "multiple outputs"); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "nb inputs:" + selected); break; } } } } else if (pair != null) { selectedUTXO.clear(); receivers.clear(); long inputAmount = 0L; long outputAmount = 0L; for (MyTransactionOutPoint outpoint : pair.getLeft()) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(outpoint); u.setOutpoints(outs); totalValueSelected += u.getValue(); selectedUTXO.add(u); inputAmount += u.getValue(); } for (TransactionOutput output : pair.getRight()) { try { Script script = new Script(output.getScriptBytes()); receivers.put(script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), BigInteger.valueOf(output.getValue().longValue())); outputAmount += output.getValue().longValue(); } catch (Exception e) { Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show(); return false; } } change = outputAmount - amount; fee = BigInteger.valueOf(inputAmount - outputAmount); } else { Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show(); return false; } // do spend here if (selectedUTXO.size() > 0) { // estimate fee for simple spend, already done if boltzmann if (SPEND_TYPE == SPEND_SIMPLE) { List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO utxo : selectedUTXO) { outpoints.addAll(utxo.getOutpoints()); } Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(outpoints)); if (amount == balance) { fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 1); amount -= fee.longValue(); receivers.clear(); receivers.put(address, BigInteger.valueOf(amount)); // fee sanity check restoreChangeIndexes(); Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(0, outpoints, receivers); tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx); byte[] serialized = tx.bitcoinSerialize(); Log.d("SendActivity", "size:" + serialized.length); Log.d("SendActivity", "vsize:" + tx.getVirtualTransactionSize()); Log.d("SendActivity", "fee:" + fee.longValue()); if ((tx.hasWitness() && (fee.longValue() < tx.getVirtualTransactionSize())) || (!tx.hasWitness() && (fee.longValue() < serialized.length))) { Toast.makeText(SendActivity.this, R.string.insufficient_fee, Toast.LENGTH_SHORT).show(); return false; } } else { fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2); } } Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "fee:" + fee.longValue()); Log.d("SendActivity", "nb inputs:" + selectedUTXO.size()); change = totalValueSelected - (amount + fee.longValue()); // Log.d("SendActivity", "change:" + change); if (change > 0L && change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) { AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.change_is_dust) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return false; } _change = change; final BigInteger _fee = fee; String dest = null; if (strPCode != null && strPCode.length() > 0) { dest = BIP47Meta.getInstance().getDisplayLabel(strPCode); } else { dest = address; } if (SendAddressUtil.getInstance().get(address) == 1) { strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n"; } else { strPrivacyWarning = ""; } if (!canDoBoltzmann) { restoreChangeIndexes(); stonewallOptionText.setAlpha(.6f); stoneWallSwitch.setAlpha(.6f); stoneWallDesc.setAlpha(.6f); stoneWallSwitch.setChecked(false); stoneWallSwitch.setEnabled(false); // strCannotDoBoltzmann = getString(R.string.boltzmann_cannot) + "\n\n"; } /* String strNoLikedTypeBoltzmann = null; if(canDoBoltzmann && PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_BOLTZMANN, true) == true && PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false) { strNoLikedTypeBoltzmann = getString(R.string.boltzmann_like_typed) + "\n\n"; } else { strNoLikedTypeBoltzmann = ""; } */ // String message = strCannotDoBoltzmann + strNoLikedTypeBoltzmann + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n"; message = strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n"; tvTotalFee.setText(Coin.valueOf(_fee.longValue()).toPlainString().concat(" BTC")); double value = Double.parseDouble(String.valueOf(_fee.add(BigInteger.valueOf(amount)))); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue(value))).concat(" BTC")); return true; } return false; } private void initiateSpend() { if (SPEND_TYPE == SPEND_RICOCHET) { ricochetSpend(); return; } AlertDialog.Builder builder = new AlertDialog.Builder(SendActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); final CheckBox cbShowAgain; if (strPrivacyWarning.length() > 0) { cbShowAgain = new CheckBox(SendActivity.this); cbShowAgain.setText(R.string.do_not_repeat_sent_to); cbShowAgain.setChecked(false); builder.setView(cbShowAgain); } else { cbShowAgain = null; } builder.setCancelable(false); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } // add change if (_change > 0L) { if (SPEND_TYPE == SPEND_SIMPLE) { if (changeType == 84) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 49) { String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else { try { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); receivers.put(change_address, BigInteger.valueOf(_change)); } catch (IOException ioe) { Toast.makeText(SendActivity.this, R.string.error_change_output, Toast.LENGTH_SHORT).show(); return; } catch (MnemonicException.MnemonicLengthException mle) { Toast.makeText(SendActivity.this, R.string.error_change_output, Toast.LENGTH_SHORT).show(); return; } } } else if (SPEND_TYPE == SPEND_BOLTZMANN) { // do nothing, change addresses included ; } else { ; } } SendParams.getInstance().setParams(outPoints, receivers, strPCode, SPEND_TYPE, _change, changeType, address, strPrivacyWarning.length() > 0, cbShowAgain != null ? cbShowAgain.isChecked() : false, amount, change_index ); Intent _intent = new Intent(SendActivity.this, TxAnimUIActivity.class); startActivity(_intent); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // btSend.setActivated(true); // btSend.setClickable(true); // dialog.dismiss(); } }); } }); AlertDialog alert = builder.create(); alert.show(); } private void ricochetSpend() { AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(ricochetMessage) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { RicochetMeta.getInstance(SendActivity.this).add(ricochetJsonObj); dialog.dismiss(); Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivityForResult(intent, RICOCHET); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } } private void backToTransactionView() { amountViewSwitcher.showPrevious(); sendTransactionDetailsView.showTransaction(); } @Override public void onBackPressed() { if (sendTransactionDetailsView.isReview()) { backToTransactionView(); } else { super.onBackPressed(); } } private void enableAmount(boolean enable) { btcEditText.setEnabled(enable); satEditText.setEnabled(enable); } private void processScan(String data) { if (data.contains("https://bitpay.com")) { AlertDialog.Builder dlg = new AlertDialog.Builder(this) .setTitle(R.string.app_name) .setMessage(R.string.no_bitpay) .setCancelable(false) .setPositiveButton(R.string.learn_more, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.samouraiwallet.com/post/169222582782/bitpay-qr-codes-are-no-longer-valid-important")); startActivity(intent); } }).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return; } if (FormatsUtil.getInstance().isValidPaymentCode(data)) { processPCode(data, null); return; } if (FormatsUtil.getInstance().isBitcoinUri(data)) { String address = FormatsUtil.getInstance().getBitcoinAddress(data); String amount = FormatsUtil.getInstance().getBitcoinAmount(data); setToAddress(address); if (amount != null) { try { NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(8); btcFormat.setMinimumFractionDigits(1); // setToAddress(btcFormat.format(Double.parseDouble(amount) / 1e8)); btcEditText.setText(btcFormat.format(Double.parseDouble(amount) / 1e8)); } catch (NumberFormatException nfe) { // setToAddress("0.0"); } } final String strAmount; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumIntegerDigits(1); nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(8); strAmount = nf.format(balance / 1e8); tvMaxAmount.setText(strAmount + " " + getDisplayUnits()); try { if (amount != null && Double.parseDouble(amount) != 0.0) { toAddressEditText.setEnabled(false); // selectPaynymBtn.setEnabled(false); // selectPaynymBtn.setAlpha(0.5f); // Toast.makeText(this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show(); enableAmount(false); } } catch (NumberFormatException nfe) { enableAmount(true); } } else if (FormatsUtil.getInstance().isValidBitcoinAddress(data)) { if (FormatsUtil.getInstance().isValidBech32(data)) { setToAddress(data.toLowerCase()); } else { setToAddress(data); } } else if (data.contains("?")) { String pcode = data.substring(0, data.indexOf("?")); // not valid BIP21 but seen often enough if (pcode.startsWith("bitcoin: pcode = pcode.substring(10); } if (pcode.startsWith("bitcoin:")) { pcode = pcode.substring(8); } if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) { processPCode(pcode, data.substring(data.indexOf("?"))); } } else { Toast.makeText(this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } validateSpend(); } public String getDisplayUnits() { return MonetaryUtil.getInstance().getBTCUnits(); } private void processPCode(String pcode, String meta) { if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) { try { PaymentCode _pcode = new PaymentCode(pcode); PaymentAddress paymentAddress = BIP47Util.getInstance(this).getSendAddress(_pcode, BIP47Meta.getInstance().getOutgoingIdx(pcode)); if (BIP47Meta.getInstance().getSegwit(pcode)) { SegwitAddress segwitAddress = new SegwitAddress(paymentAddress.getSendECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); strDestinationBTCAddress = segwitAddress.getBech32AsString(); } else { strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } strPCode = _pcode.toString(); setToAddress(BIP47Meta.getInstance().getDisplayLabel(strPCode)); toAddressEditText.setEnabled(false); validateSpend(); } catch (Exception e) { Toast.makeText(this, R.string.error_payment_code, Toast.LENGTH_SHORT).show(); } } else { // Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show(); if (meta != null && meta.startsWith("?") && meta.length() > 1) { meta = meta.substring(1); } Intent intent = new Intent(this, BIP47Activity.class); intent.putExtra("pcode", pcode); if (meta != null && meta.length() > 0) { intent.putExtra("meta", meta); } startActivity(intent); } } else { Toast.makeText(this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show(); } } private boolean validateSpend() { boolean isValid = false; boolean insufficientFunds = false; double btc_amount = 0.0; String strBTCAddress = getToAddress(); if (strBTCAddress.startsWith("bitcoin:")) { setToAddress(strBTCAddress.substring(8)); } setToAddress(strBTCAddress); try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } final double dAmount = btc_amount; // Log.i("SendFragment", "amount entered (converted):" + dAmount); final long amount = (long) (Math.round(dAmount * 1e8)); Log.i("SendFragment", "amount entered (converted to long):" + amount); Log.i("SendFragment", "balance:" + balance); if (amount > balance) { insufficientFunds = true; } // Log.i("SendFragment", "insufficient funds:" + insufficientFunds); if (amount >= SamouraiWallet.bDust.longValue() && FormatsUtil.getInstance().isValidBitcoinAddress(getToAddress())) { isValid = true; } else if (amount >= SamouraiWallet.bDust.longValue() && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress)) { isValid = true; } else { isValid = false; } if (insufficientFunds) { Toast.makeText(this, getString(R.string.insufficient_funds), Toast.LENGTH_SHORT).show(); } if (!isValid || insufficientFunds) { enableReviewButton(false); return false; } else { enableReviewButton(true); return true; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { strPCode = null; strDestinationBTCAddress = null; final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); processScan(strResult); } } else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else if (resultCode == Activity.RESULT_OK && requestCode == RICOCHET) { ; } else if (resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) { ; } else { ; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.send_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (item.getItemId() == android.R.id.home) { this.onBackPressed(); return true; } if (item.getItemId() == R.id.select_paynym) { PaynymSelectModalFragment paynymSelectModalFragment = PaynymSelectModalFragment.newInstance(code -> processPCode(code, null)); paynymSelectModalFragment.show(getSupportFragmentManager(), "paynym_select"); return true; } // noinspection SimplifiableIfStatement if (id == R.id.action_scan_qr) { doScan(); } else if (id == R.id.action_ricochet) { Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivity(intent); } else if (id == R.id.action_empty_ricochet) { emptyRicochetQueue(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_fees) { doFees(); } else if (id == R.id.action_batch) { doBatchSpend(); } else if (id == R.id.action_support) { doSupport(); } else { ; } return super.onOptionsItemSelected(item); } private void emptyRicochetQueue() { RicochetMeta.getInstance(this).setLastRicochet(null); RicochetMeta.getInstance(this).empty(); new Thread(new Runnable() { @Override public void run() { try { PayloadUtil.getInstance(SendActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(SendActivity.this).getGUID() + AccessFactory.getInstance(SendActivity.this).getPIN())); } catch (Exception e) { ; } } }).start(); } private void doScan() { Intent intent = new Intent(SendActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE}); startActivityForResult(intent, SCAN_QR); } private void doSupport() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/8-sending-bitcoin")); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(SendActivity.this, UTXOActivity.class); startActivity(intent); } private void doBatchSpend() { Intent intent = new Intent(SendActivity.this, BatchSendActivity.class); startActivity(intent); } private void doFees() { SuggestedFee highFee = FeeUtil.getInstance().getHighFee(); SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee(); SuggestedFee lowFee = FeeUtil.getInstance().getLowFee(); String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, (dialog, whichButton) -> dialog.dismiss()); if (!isFinishing()) { dlg.show(); } } private void saveChangeIndexes() { idxBIP84Internal = BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); idxBIP49Internal = BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); try { idxBIP44Internal = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx(); } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } private void restoreChangeIndexes() { BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP84Internal); BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP49Internal); try { HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(idxBIP44Internal); } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } }
package de.bitdroid.flooding.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.getbase.floatingactionbutton.FloatingActionButton; import com.github.brnunes.swipeablerecyclerview.SwipeableRecyclerViewTouchListener; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import de.bitdroid.flooding.R; import de.bitdroid.flooding.ceps.Alarm; import de.bitdroid.flooding.ceps.CepsManager; import de.bitdroid.flooding.network.AbstractErrorAction; import de.bitdroid.flooding.network.NetworkUtils; import de.bitdroid.flooding.ods.BodyOfWater; import de.bitdroid.flooding.ods.Station; import de.bitdroid.flooding.utils.StringUtils; import roboguice.inject.InjectView; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import timber.log.Timber; public class AlarmsFragment extends AbstractFragment { @Inject private NetworkUtils networkUtils; @Inject private CepsManager cepsManager; @InjectView(R.id.button_add) FloatingActionButton addButton; @InjectView(R.id.list) RecyclerView recyclerView; private AlarmsAdapter adapter; // flag indicating whether an alarm is currently being added. // required to update the list private boolean addingNewAlarm = false; public AlarmsFragment() { super(R.layout.fragment_alarms); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // setup list RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); adapter = new AlarmsAdapter(); recyclerView.setAdapter(adapter); // setup swipe to delete SwipeableRecyclerViewTouchListener swipeTouchListener = new SwipeableRecyclerViewTouchListener(recyclerView, new AlarmSwipeListener()); recyclerView.addOnItemTouchListener(swipeTouchListener); // setup add button addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addingNewAlarm = true; startActivity(new Intent(getActivity(), WaterSelectionActivity.class)); } }); // load items loadAlarms(); } @Override public void onResume() { super.onResume(); if (addingNewAlarm) loadAlarms(); } private void loadAlarms() { if (addingNewAlarm) addingNewAlarm = false; showSpinner(); cepsManager.getAlarms() .compose(networkUtils.<List<Alarm>>getDefaultTransformer()) .subscribe(new Action1<List<Alarm>>() { @Override public void call(List<Alarm> alarms) { hideSpinner(); adapter.setAlarms(alarms); } }, new AbstractErrorAction(AlarmsFragment.this) { @Override protected void doCall(Throwable throwable) { Timber.e(throwable, "failed to load data"); } }); } protected class AlarmsAdapter extends RecyclerView.Adapter<AlarmViewHolder> { private final List<Alarm> alarmList = new ArrayList<>(); @Override public void onBindViewHolder(AlarmViewHolder holder, int position) { holder.setItem(alarmList.get(position)); } @Override public int getItemCount() { return alarmList.size(); } public void setAlarms(List<Alarm> alarmList) { this.alarmList.clear(); this.alarmList.addAll(alarmList); notifyDataSetChanged(); } public List<Alarm> getAlarms() { return new ArrayList<>(alarmList); } @Override public AlarmViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_alarm, parent, false); return new AlarmViewHolder(view); } } protected class AlarmViewHolder extends RecyclerView.ViewHolder { private final View containerView; private final TextView stationView; private final TextView descriptionView; public AlarmViewHolder(View containerView) { super(containerView); this.containerView = containerView; this.stationView = (TextView) containerView.findViewById(R.id.alarm_title); this.descriptionView = (TextView) containerView.findViewById(R.id.alarm_description); } public void setItem(final Alarm alarm) { // setup on click containerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent stationIntent = new StationSelection(alarm.getStation().getBodyOfWater(), alarm.getStation()) .toIntent(getActivity(), StationInfoActivity.class); startActivity(stationIntent); } }); // setup content stationView.setText(StringUtils.toProperCase(alarm.getStation().getStationName()) + " - " + StringUtils.toProperCase(alarm.getStation().getBodyOfWater().getName())); String description; if (alarm.isAlarmWhenAboveLevel()) description = getString(R.string.alarms_description_above, alarm.getLevel()); else description = getString(R.string.alarms_description_below, alarm.getLevel()); descriptionView.setText(description); } } /** * Handles swipe to delete on alarm items */ protected class AlarmSwipeListener implements SwipeableRecyclerViewTouchListener.SwipeListener { @Override public boolean canSwipe(int position) { return true; } @Override public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) { removeItems(reverseSortedPositions); } @Override public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) { removeItems(reverseSortedPositions); } private void removeItems(int[] reverseSortedPositions) { List<Alarm> alarmsToRemove = new ArrayList<>(); List<Alarm> alarmsToKeep = adapter.getAlarms(); for (int position : reverseSortedPositions) { alarmsToRemove.add(alarmsToKeep.remove(position)); } adapter.setAlarms(alarmsToKeep); showSpinner(); Observable.from(alarmsToRemove) .flatMap(new Func1<Alarm, Observable<Void>>() { @Override public Observable<Void> call(Alarm alarm) { return cepsManager.removeAlarm(alarm); } }) .toList() .compose(networkUtils.<List<Void>>getDefaultTransformer()) .subscribe( new Action1<List<Void>>() { @Override public void call(List<Void> nothing) { loadAlarms(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable, "error removing alarms"); } }); } } /** * The glue that is necessary kick of the station selection process and show new {@link NewAlarmActivity} * when a station has been selected. */ public static class WaterSelectionActivity extends AbstractWaterSelectionActivity { @Override protected void onDataSelected(BodyOfWater water) { startActivity(new StationSelection(water).toIntent(this, StationSelectionActivity.class)); } @Override protected Class<? extends AbstractMapSelectionActivity> getMapSelectionClass() { return MapSelectionActivity.class; } } public static class StationSelectionActivity extends AbstractStationSelectionActivity { public StationSelectionActivity() { super(false); } @Override protected void onAllStationsSelected() { } @Override protected void onStationSelected(Station station) { AlarmsFragment.onStationSelected(this, station); } @Override protected Class<? extends AbstractMapSelectionActivity> getMapSelectionClass() { return MapSelectionActivity.class; } } public static class MapSelectionActivity extends AbstractMapSelectionActivity { @Override public void onStationClicked(Station station) { onStationSelected(this, station); } } private static void onStationSelected(Context context, Station station) { context.startActivity(new StationSelection(station.getBodyOfWater(), station).toIntent(context, NewAlarmActivity.class)); } }
package edu.umt.csci427.canary; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.DialogInterface; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link MonitorFragment.OnMonitorFragmentInteractionListener} interface * to handle interaction events. * Use the {@link MonitorFragment#newInstance} factory method to * create an instance of this fragment. */ public class MonitorFragment extends Fragment { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER public static final String ARG_PARAM1 = "title"; private static final String ARG_PARAM2 = "units"; private static final String ARG_PARAM3 = "value"; private static final String ARG_PARAM4 = "metric_id"; private static Monitor monitor; private OnMonitorFragmentInteractionListener mListener; private AlertService mService; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param title Title which will be displayed in the monitor. * @param units Units the value uses, if applicable. * @param metric_id Action of broadcasts that we should receive * @return A new instance of fragment MonitorFragment. */ public static MonitorFragment newInstance(String title, String units, String metric_id) { MonitorFragment fragment = new MonitorFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, title); args.putString(ARG_PARAM2, units); args.putString(ARG_PARAM4, metric_id); fragment.setArguments(args); return fragment; } public static MonitorFragment newInstance(Monitor factMonitor) { MonitorFragment fragment = new MonitorFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, factMonitor.getTitle()); args.putString(ARG_PARAM2, factMonitor.getUnits()); args.putString(ARG_PARAM4, factMonitor.getMetric_id()); fragment.setArguments(args); monitor = factMonitor; return fragment; } public MonitorFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { // Retain this fragment across configuration changes. setRetainInstance(true); mService.addListener(monitor.getMetric_id(),150,50); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_monitor, container, false); } @Override public void onStart() { super.onStart(); BroadcastReceiver receiver = new OpenICEIntentReceiver(this, (TextView)getView().findViewById(R.id.monitorValueTextView)); LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(receiver, new IntentFilter(monitor.getTitle())); TextView valTv; valTv = (TextView)getView().findViewById(R.id.monitorTitleTextView); valTv.setText(monitor.getTitle()); valTv.setOnClickListener(new monitorButtonShortListener()); valTv.setOnLongClickListener(new monitorButtonLongListener()); valTv = (TextView)getView().findViewById(R.id.monitorUnitsTextView); valTv.setText(monitor.getUnits()); valTv.setOnClickListener(new monitorButtonShortListener()); valTv.setOnLongClickListener(new monitorButtonLongListener()); valTv = (TextView)getView().findViewById(R.id.monitorValueTextView); valTv.setOnClickListener(new monitorButtonShortListener()); valTv.setOnLongClickListener(new monitorButtonLongListener()); } private class monitorButtonShortListener implements View.OnClickListener { @Override public void onClick(View V) { /* getFragmentManager().beginTransaction() .hide(getFragmentManager().findFragmentByTag(monitor.getTitle())); getFragmentManager().beginTransaction() .add(R.id.container, ThresholdFragment.newInstance("bogus1", "bogus2")) .commit(); }*/} } private class monitorButtonLongListener implements View.OnLongClickListener { @Override public boolean onLongClick(View v) { new AlertDialog.Builder(v.getContext()) .setTitle("Remove Fragment") .setMessage("Do you want to remove monitor?") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { getFragmentManager().beginTransaction() .remove(getFragmentManager().findFragmentByTag(monitor.getTitle())) .commit(); getFragmentManager().executePendingTransactions(); }}) .setNegativeButton(android.R.string.no, null).show(); return true; } } public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnMonitorFragmentInteractionListener) activity; mService = mListener.getAlertService(); } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * Override needed to fix crash when rotating screen **/ @Override public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); } public interface OnMonitorFragmentInteractionListener { public void onFragmentInteraction(); public void launchThresholdOnClick(); public AlertService getAlertService(); } @Override public void onDestroyView(){ super.onDestroyView(); } }
package io.pslab.fragment; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.github.anastr.speedviewlib.PointerSpeedometer; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import io.pslab.R; import io.pslab.activity.LuxMeterActivity; import io.pslab.communication.ScienceLab; import io.pslab.communication.peripherals.I2C; import io.pslab.communication.sensors.BH1750; import io.pslab.communication.sensors.TSL2561; import io.pslab.models.LuxData; import io.pslab.models.SensorDataBlock; import io.pslab.others.ScienceLabCommon; import static android.content.Context.SENSOR_SERVICE; public class LuxMeterDataFragment extends Fragment { private static int sensorType = 0; private static int highLimit = 2000; private static int updatePeriod = 100; private static int gain = 1; private long timeElapsed; private int count = 0, turns = 0; private float sum = 0; private boolean returningFromPause = false; private float luxValue = -1; private enum LUX_SENSOR {INBUILT_SENSOR, BH1750_SENSOR, TSL2561_SENSOR} @BindView(R.id.lux_max) TextView statMax; @BindView(R.id.lux_min) TextView statMin; @BindView(R.id.lux_avg) TextView statMean; @BindView(R.id.label_lux_sensor) TextView sensorLabel; @BindView(R.id.chart_lux_meter) LineChart mChart; @BindView(R.id.light_meter) PointerSpeedometer lightMeter; private Timer graphTimer; private SensorManager sensorManager; private Sensor sensor; private long startTime, block; private ArrayList<Entry> entries; private ArrayList<LuxData> recordedLuxArray; private LuxData sensorData; private float currentMin = 10000; private float currentMax = 0; private boolean playComplete = false; private YAxis y; private Unbinder unbinder; private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; private LuxMeterActivity luxSensor; public static LuxMeterDataFragment newInstance() { return new LuxMeterDataFragment(); } public static void setParameters(int highLimit, int updatePeriod, String type, String gain) { LuxMeterDataFragment.highLimit = highLimit; LuxMeterDataFragment.updatePeriod = updatePeriod; LuxMeterDataFragment.sensorType = Integer.valueOf(type); LuxMeterDataFragment.gain = Integer.valueOf(gain); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startTime = System.currentTimeMillis(); entries = new ArrayList<>(); luxSensor = (LuxMeterActivity) getActivity(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_lux_meter_data, container, false); unbinder = ButterKnife.bind(this, view); setupInstruments(); return view; } @Override public void onResume() { super.onResume(); if (luxSensor.playingData) { sensorLabel.setText(getResources().getString(R.string.recorder)); recordedLuxArray = new ArrayList<>(); resetInstrumentData(); playRecordedData(); } else if (!luxSensor.isRecording) { updateGraphs(); sum = 0; count = 0; currentMin = 10000; currentMax = 0; entries.clear(); mChart.clear(); mChart.invalidate(); initiateLuxSensor(sensorType); } else if (returningFromPause) { updateGraphs(); } } @Override public void onDestroyView() { super.onDestroyView(); if (graphTimer != null) { graphTimer.cancel(); } if (sensorManager != null) { sensorManager.unregisterListener(lightSensorEventListener); } unbinder.unbind(); } private void playRecordedData() { recordedLuxArray.addAll(luxSensor.recordedLuxData); try { if (recordedLuxArray.size() > 1) { LuxData i = recordedLuxArray.get(1); long timeGap = i.getTime() - i.getBlock(); processRecordedData(timeGap); } else { processRecordedData(0); } } catch (IllegalArgumentException e) { Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.no_data_fetched), Toast.LENGTH_SHORT).show(); } } private void processRecordedData(long timeGap) { final Handler handler = new Handler(); if (graphTimer != null) { graphTimer.cancel(); } else { graphTimer = new Timer(); } graphTimer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { try { playComplete = false; LuxData d = recordedLuxArray.get(turns); turns++; if (currentMax < d.getLux()) { currentMax = d.getLux(); statMax.setText(String.valueOf(d.getLux())); } if (currentMin > d.getLux()) { currentMin = d.getLux(); statMin.setText(String.valueOf(d.getLux())); } y.setAxisMaximum(currentMax); y.setAxisMinimum(currentMin); y.setLabelCount(10); lightMeter.setWithTremble(false); lightMeter.setSpeedAt(d.getLux()); Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getLux()); entries.add(entry); count++; sum += entry.getY(); statMean.setText(String.format(Locale.getDefault(), "%.2f", (sum / count))); LineDataSet dataSet = new LineDataSet(entries, getString(R.string.lux)); dataSet.setDrawCircles(false); dataSet.setDrawValues(false); dataSet.setLineWidth(2); LineData data = new LineData(dataSet); mChart.setData(data); mChart.notifyDataSetChanged(); mChart.setVisibleXRangeMaximum(80); mChart.moveViewToX(data.getEntryCount()); mChart.invalidate(); } catch (IndexOutOfBoundsException e) { graphTimer.cancel(); playComplete = true; } } }); } }, 0, timeGap); } public void saveGraph() { if (playComplete) { mChart.saveToGallery(luxSensor.dateFormat.format(recordedLuxArray.get(0).getTime()), 100); Toast.makeText(getActivity(), "Graph saved to gallery", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), "Wait until the play is complete", Toast.LENGTH_LONG).show(); } } private void setupInstruments() { lightMeter.setMaxSpeed(10000); XAxis x = mChart.getXAxis(); this.y = mChart.getAxisLeft(); YAxis y2 = mChart.getAxisRight(); mChart.setTouchEnabled(true); mChart.setHighlightPerDragEnabled(true); mChart.setDragEnabled(true); mChart.setScaleEnabled(true); mChart.setDrawGridBackground(false); mChart.setPinchZoom(true); mChart.setScaleYEnabled(true); mChart.setBackgroundColor(Color.BLACK); mChart.getDescription().setEnabled(false); LineData data = new LineData(); mChart.setData(data); Legend l = mChart.getLegend(); l.setForm(Legend.LegendForm.LINE); l.setTextColor(Color.WHITE); x.setTextColor(Color.WHITE); x.setDrawGridLines(true); x.setAvoidFirstLastClipping(true); y.setTextColor(Color.WHITE); y.setAxisMaximum(currentMax); y.setAxisMinimum(currentMin); y.setDrawGridLines(true); y.setLabelCount(10); y2.setDrawGridLines(false); } @Override public void onPause() { super.onPause(); if (graphTimer != null) { returningFromPause = true; graphTimer.cancel(); graphTimer = null; if (luxSensor.playingData) { luxSensor.finish(); } } } private void updateGraphs() { final Handler handler = new Handler(); if (graphTimer != null) { graphTimer.cancel(); } graphTimer = new Timer(); graphTimer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { try { visualizeData(); } catch (NullPointerException e) { /* Pass for another refresh round */ } } }); } }, 0, updatePeriod); } private void writeLogToFile(long timestamp, float sensorReading) { if (getActivity() != null && luxSensor.isRecording) { if (luxSensor.writeHeaderToFile) { luxSensor.csvLogger.prepareLogFile(); luxSensor.csvLogger.writeCSVFile("Timestamp,DateTime,Readings,Latitude,Longitude"); block = timestamp; luxSensor.recordSensorDataBlockID(new SensorDataBlock(timestamp, luxSensor.getSensorName())); luxSensor.writeHeaderToFile = !luxSensor.writeHeaderToFile; } if (luxSensor.addLocation && luxSensor.gpsLogger.isGPSEnabled()) { String dateTime = luxSensor.dateFormat.format(new Date(timestamp)); Location location = luxSensor.gpsLogger.getDeviceLocation(); luxSensor.csvLogger.writeCSVFile(timestamp + "," + dateTime + "," + sensorReading + "," + location.getLatitude() + "," + location.getLongitude()); sensorData = new LuxData(timestamp, block, luxValue, location.getLatitude(), location.getLongitude()); } else { String dateTime = luxSensor.dateFormat.format(new Date(timestamp)); luxSensor.csvLogger.writeCSVFile(timestamp + "," + dateTime + "," + sensorReading + ",0.0,0.0"); sensorData = new LuxData(timestamp, block, luxValue, 0.0, 0.0); } luxSensor.recordSensorData(sensorData); } else { luxSensor.writeHeaderToFile = true; } } private void visualizeData() { if (currentMax < luxValue) { currentMax = luxValue; statMax.setText(String.valueOf(luxValue)); } if (currentMin > luxValue) { currentMin = luxValue; statMin.setText(String.valueOf(luxValue)); } y.setAxisMaximum(currentMax); y.setAxisMinimum(currentMin); y.setLabelCount(10); if (luxValue >= 0) { lightMeter.setWithTremble(false); lightMeter.setSpeedAt(luxValue); if (luxValue > highLimit) lightMeter.setPointerColor(Color.RED); else lightMeter.setPointerColor(Color.WHITE); timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); if (timeElapsed != previousTimeElapsed) { previousTimeElapsed = timeElapsed; Entry entry = new Entry((float) timeElapsed, luxValue); Long currentTime = System.currentTimeMillis(); writeLogToFile(currentTime, luxValue); entries.add(entry); count++; sum += entry.getY(); statMean.setText(String.format(Locale.getDefault(), "%.2f", (sum / count))); LineDataSet dataSet = new LineDataSet(entries, getString(R.string.lux)); dataSet.setDrawCircles(false); dataSet.setDrawValues(false); dataSet.setLineWidth(2); LineData data = new LineData(dataSet); mChart.setData(data); mChart.notifyDataSetChanged(); mChart.setVisibleXRangeMaximum(80); mChart.moveViewToX(data.getEntryCount()); mChart.invalidate(); } } } private SensorEventListener lightSensorEventListener = new SensorEventListener() { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { luxValue = event.values[0]; } } }; private void resetInstrumentData() { luxValue = 0; count = 0; currentMin = 10000; currentMax = 0; sum = 0; sensor = null; if (sensorManager != null) { sensorManager.unregisterListener(lightSensorEventListener); } startTime = System.currentTimeMillis(); statMax.setText(getResources().getString(R.string.value_null)); statMin.setText(getResources().getString(R.string.value_null)); statMean.setText(getResources().getString(R.string.value_null)); lightMeter.setSpeedAt(0); lightMeter.setWithTremble(false); entries.clear(); } private void initiateLuxSensor(int type) { LUX_SENSOR s = LUX_SENSOR.values()[type]; resetInstrumentData(); ScienceLab scienceLab; switch (s) { case INBUILT_SENSOR: sensorLabel.setText(getResources().getStringArray(R.array.lux_sensors)[0]); sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); if (sensor == null) { Toast.makeText(getContext(), getResources().getString(R.string.no_lux_sensor), Toast.LENGTH_LONG).show(); } else { float max = sensor.getMaximumRange(); lightMeter.setMaxSpeed(max); sensorManager.registerListener(lightSensorEventListener, sensor, SensorManager.SENSOR_DELAY_FASTEST); } break; case BH1750_SENSOR: sensorLabel.setText(getResources().getStringArray(R.array.lux_sensors)[1]); scienceLab = ScienceLabCommon.scienceLab; if (scienceLab.isConnected()) { ArrayList<Integer> data; try { I2C i2c = scienceLab.i2c; data = i2c.scan(null); if (data.contains(0x23)) { BH1750 sensorBH1750 = new BH1750(i2c); sensorBH1750.setRange(String.valueOf(gain)); sensorType = 0; } else { Toast.makeText(getContext(), getResources().getText(R.string.sensor_not_connected_tls), Toast.LENGTH_SHORT).show(); sensorType = 0; } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } else { Toast.makeText(getContext(), getResources().getText(R.string.device_not_found), Toast.LENGTH_SHORT).show(); sensorType = 0; } break; case TSL2561_SENSOR: sensorLabel.setText(getResources().getStringArray(R.array.lux_sensors)[2]); scienceLab = ScienceLabCommon.scienceLab; if (scienceLab.isConnected()) { try { I2C i2c = scienceLab.i2c; ArrayList<Integer> data; data = i2c.scan(null); if (data.contains(0x39)) { TSL2561 sensorTSL2561 = new TSL2561(i2c, scienceLab); sensorTSL2561.setGain(String.valueOf(gain)); sensorType = 2; } else { Toast.makeText(getContext(), getResources().getText(R.string.sensor_not_connected_tls), Toast.LENGTH_SHORT).show(); sensorType = 0; } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } else { Toast.makeText(getContext(), getResources().getText(R.string.device_not_found), Toast.LENGTH_SHORT).show(); sensorType = 0; } break; default: break; } } }
package nickrout.lenslauncher.ui; import android.animation.Animator; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.widget.ImageView; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import nickrout.lenslauncher.R; public class AboutActivity extends BaseActivity { private static final String TAG = "AboutActivity"; @Bind(R.id.text_view_about) TextView mTextViewAbout; @Bind(R.id.backdrop) ImageView mImageAbout; @Bind(R.id.collapsing_toolbar) CollapsingToolbarLayout mCollapsingToolbar; @Bind(R.id.toolbar) Toolbar mToolbar; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); ButterKnife.bind(this); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mCollapsingToolbar.setExpandedTitleColor(ContextCompat.getColor(this, R.color.colorTransparent)); setupText(); mImageAbout.postDelayed(new Runnable() { @Override public void run() { circularRevealAboutImage(); } }, 150); } private void circularRevealAboutImage() { if (mImageAbout != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { int cx = mImageAbout.getWidth() / 2; int cy = mImageAbout.getHeight() / 2; float finalRadius = (float) Math.hypot(cx, cy); Animator anim = ViewAnimationUtils.createCircularReveal(mImageAbout, cx, cy, 0, finalRadius); mImageAbout.setVisibility(View.VISIBLE); anim.start(); } else { mImageAbout.setVisibility(View.VISIBLE); } } } private void setupText() { mTextViewAbout.setText(Html.fromHtml(getString(R.string.about))); mTextViewAbout.setMovementMethod(LinkMovementMethod.getInstance()); } @Override public void onBackPressed() { finish(); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
package phase3; import java.io.IOException; import java.util.Set; import java.util.TreeSet; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import subscriber.*; /** * The class implements the reducer for the last phase of the program. * @author Sameer Jagdale */ public class Phase3Reducer extends Reducer<Text, Text, Text, Text> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String str = ""; Set<ValueHolder> inputSet = new TreeSet<ValueHolder>(); // Read values into a Tree Set. This ensures values are sorted. // This provides ease while ranking the output. for (Text txt : values) { inputSet.add(ValueHolder.getValueHolderFromString(txt.toString())); } // Defines the number of records per day. int numRecords = inputSet.size(); long diff = Integer.MIN_VALUE; long rank = 0; // Count will hold the number of records having the same count. // This is required because the records having the same count // should have the same rank. However the rank of subsequent // records will have to incremented by the number of subscribers // with the count value. long count = 1; for (ValueHolder value : inputSet) { if (diff != (numRecords - value.getCount()) + 1) { diff = numRecords - value.getCount() + 1; rank += count; count = 1; } else { count++; } context.write(key, new Text(value.toString() + "\t" + rank + "/" + numRecords)); } } } /** * The class acts a placeholder for the values. Contains all the input fields * such as serviceName, subscriberId, serviceType and count. The compareTo method which * is overriden orders the objects first on count, followed by subscriberId, followed by * serviceName and finally serviceType. * @author Sameer Jagdale */ class ValueHolder implements Comparable<ValueHolder> { String serviceName; long subscriberId; String serviceType; long count; ValueHolder(String serviceName, long subscriberId, String serviceType, long count) { this.serviceName = serviceName; this.serviceType = serviceType; this.subscriberId = subscriberId; this.count = count; } public long getCount() { return count; } public String getServiceName() { return serviceName; } public String getServiceType() { return serviceType; } public long getSubscriberId() { return subscriberId; } public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof ValueHolder)) return false; ValueHolder other = (ValueHolder) obj; return serviceName.equals(other.getServiceName()) && serviceType.equals(other.getServiceType()) && subscriberId == other.getSubscriberId() && count == other.getCount(); } public String toString() { return serviceName + "\t" + subscriberId + "\t" + serviceType + "\t" + count; } @Override public int hashCode() { return ((new Long(subscriberId)).hashCode()) + serviceName.hashCode() + serviceType.hashCode() + (new Long(count)).hashCode(); } public int compareTo(ValueHolder other) { if ((int) (other.getCount() - count) == 0) { if ((int) (subscriberId - other.subscriberId) == 0) { if (serviceName.compareTo(other.getServiceName()) == 0) { return serviceType.compareTo(other.getServiceType()); } else { return serviceName.compareTo(other.getServiceName()); } } else { return (int) (subscriberId - other.subscriberId); } } else { return (int) (other.getCount() - count); } } public static ValueHolder getValueHolderFromString(String str) { String[] fields = (str.toString().split("[\t ]+")); return new ValueHolder(fields[0], Long.parseLong(fields[1]), fields[2], Long.parseLong(fields[3])); } }
package zero.zd.zquestionnaire; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LoadQnaActivity extends AppCompatActivity { private static final String TAG = LoadQnaActivity.class.getSimpleName(); public static Intent getStartIntent(Context context) { return new Intent(context, LoadQnaActivity.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load_qna); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
package com.kickstarter.services; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.kickstarter.factories.CategoryFactory; import com.kickstarter.factories.LocationFactory; import com.kickstarter.factories.ProjectFactory; import com.kickstarter.factories.UserFactory; import com.kickstarter.libs.Config; import com.kickstarter.models.Backing; import com.kickstarter.models.Category; import com.kickstarter.models.Comment; import com.kickstarter.models.Empty; import com.kickstarter.models.Location; import com.kickstarter.models.Notification; import com.kickstarter.models.Project; import com.kickstarter.models.Update; import com.kickstarter.models.User; import com.kickstarter.services.apiresponses.AccessTokenEnvelope; import com.kickstarter.services.apiresponses.ActivityEnvelope; import com.kickstarter.services.apiresponses.CommentsEnvelope; import com.kickstarter.services.apiresponses.DiscoverEnvelope; import java.util.List; import rx.Observable; public class MockApiClient implements ApiClientType { @Override public @NonNull Observable<Config> config() { return Observable.empty(); } @Override public @NonNull Observable<ActivityEnvelope> fetchActivities() { return Observable.empty(); } @Override public @NonNull Observable<ActivityEnvelope> fetchActivities(final @Nullable Integer count) { return Observable.empty(); } @Override public @NonNull Observable<ActivityEnvelope> fetchActivitiesWithPaginationPath(final @NonNull String paginationPath) { return Observable.empty(); } @Override public @NonNull Observable<List<Category>> fetchCategories() { return Observable.empty(); } @Override public @NonNull Observable<List<Notification>> fetchNotifications() { return Observable.empty(); } @Override public @NonNull Observable<Project> fetchProject(final @NonNull String param) { return Observable.just( ProjectFactory.project() .toBuilder() .slug(param) .build() ); } @Override public @NonNull Observable<Project> fetchProject(final @NonNull Project project) { return Observable.just(project); } @Override public @NonNull Observable<DiscoverEnvelope> fetchProjects(final @NonNull DiscoveryParams params) { return Observable.empty(); } @Override public @NonNull Observable<DiscoverEnvelope> fetchProjects(final @NonNull String paginationUrl) { return Observable.empty(); } @Override public @NonNull Observable<CommentsEnvelope> fetchProjectComments(final @NonNull Project project) { return Observable.empty(); } @Override public @NonNull Observable<CommentsEnvelope> fetchProjectComments(final @NonNull String paginationPath) { return Observable.empty(); } @Override public @NonNull Observable<Update> fetchUpdate(final @NonNull String projectParam, final @NonNull String updateParam) { return Observable.empty(); } @Override public @NonNull Observable<Update> fetchUpdate(final @NonNull Update update) { return Observable.empty(); } @Override public @NonNull Observable<AccessTokenEnvelope> loginWithFacebook(final @NonNull String accessToken) { return Observable.empty(); } @Override public @NonNull Observable<AccessTokenEnvelope> loginWithFacebook(final @NonNull String fbAccessToken, final @NonNull String code) { return Observable.empty(); } @Override public @NonNull Observable<AccessTokenEnvelope> registerWithFacebook(final @NonNull String fbAccessToken, final boolean sendNewsletters) { return Observable.empty(); } @Override public @NonNull Observable<Backing> fetchProjectBacking(final @NonNull Project project, final @NonNull User user) { return Observable.empty(); } @Override public @NonNull Observable<Category> fetchCategory(final @NonNull String param) { return Observable.just(CategoryFactory.musicCategory()); } @Override public @NonNull Observable<Category> fetchCategory(final @NonNull Category category) { return Observable.empty(); } @Override public @NonNull Observable<User> fetchCurrentUser() { return Observable.empty(); } @Override public @NonNull Observable<Location> fetchLocation(final @NonNull String param) { return Observable.just(LocationFactory.sydney()); } @Override public @NonNull Observable<AccessTokenEnvelope> login(final @NonNull String email, final @NonNull String password) { return Observable.empty(); } @Override public @NonNull Observable<AccessTokenEnvelope> login(final @NonNull String email, final @NonNull String password, final @NonNull String code) { return Observable.empty(); } @Override public @NonNull Observable<Comment> postProjectComment(final @NonNull Project project, final @NonNull String body) { return Observable.empty(); } @Override public @NonNull Observable<Empty> registerPushToken(final @NonNull String token) { return Observable.empty(); } @Override public @NonNull Observable<User> resetPassword(final @NonNull String email) { return Observable.just(UserFactory.user()); } @Override public @NonNull Observable<AccessTokenEnvelope> signup(final @NonNull String name, final @NonNull String email, final @NonNull String password, final @NonNull String passwordConfirmation, final boolean sendNewsletters) { return Observable.just( AccessTokenEnvelope.builder() .user(UserFactory.user() .toBuilder() .name(name) .build() ) .accessToken("deadbeef") .build() ); } @Override public @NonNull Observable<Project> starProject(final @NonNull Project project) { return Observable.just(project.toBuilder().isStarred(true).build()); } @Override public @NonNull Observable<Project> toggleProjectStar(final @NonNull Project project) { return Observable.just(project.toBuilder().isStarred(!project.isStarred()).build()); } @Override public @NonNull Observable<Notification> updateNotifications(final @NonNull Notification notification, final boolean checked) { return Observable.empty(); } @Override public @NonNull Observable<User> updateUserSettings(final @NonNull User user) { return Observable.just(user); } }
package org.wikipedia.csrf; import org.junit.Test; import org.wikipedia.test.MockRetrofitTest; public class CsrfTokenClientTest extends MockRetrofitTest { @Test public void testRequestSuccess() throws Throwable { String expected = "b6f7bd58c013ab30735cb19ecc0aa08258122cba+\\"; enqueueFromFile("csrf_token.json"); new CsrfTokenClient(wikiSite(), 1, getApiService()).getToken().test().await() .assertComplete().assertNoErrors() .assertValue(result -> result.equals(expected)); } @Test public void testRequestResponseApiError() throws Throwable { enqueueFromFile("api_error.json"); new CsrfTokenClient(wikiSite(), 1, getApiService()).getToken().test().await() .assertError(Exception.class); } @Test public void testRequestResponseFailure() throws Throwable { enqueue404(); new CsrfTokenClient(wikiSite(), 1, getApiService()).getToken().test().await() .assertError(Exception.class); } }
package jpt.app01.session; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.logging.Logger; import com.sun.net.httpserver.Filter; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import jpt.app01.CookieParser; import jpt.app01.RedirectResponder; /** * * @author avm */ public class SessionFilter extends Filter { private static final Logger LOG = Logger.getLogger(SessionFilter.class.getName()); private static final String SESSIONID_COOKIENAME = "SESSIONID"; private final SessionRegistry sessionRegistry; private final String redirectUrl; public SessionFilter(SessionRegistry sessionRegistry, String redirectUrl) { this.redirectUrl = redirectUrl; this.sessionRegistry = sessionRegistry; } @Override public void doFilter(HttpExchange exchange, Chain chain) throws IOException { final List<String> cookiesAttribute = exchange.getRequestHeaders().get("Cookie"); if (null==cookiesAttribute) { RedirectResponder.respond(exchange, redirectUrl, "login", Optional.of("Not yet logged in.")); return; // no doFilter since we abort here } final Optional<String> sessionId = cookiesAttribute.stream(). map(h -> CookieParser.getCookie(h, SESSIONID_COOKIENAME)). filter(oc -> oc.isPresent()).map(oc -> oc.get()). findFirst(); if (!sessionId.isPresent()) { RedirectResponder.respond(exchange, redirectUrl, "login", Optional.of("Session id not found in cookie.")); return; // no doFilter since we abort here } LOG.info(() -> "Retrieved session " + sessionId.get()); Session session = sessionRegistry.get(sessionId.get()); exchange.setAttribute(SESSION_ATTNAME, session); chain.doFilter(exchange); } private static final String SESSION_ATTNAME = "SESSION"; @Override public String description() { return "Retrieve session from Map and store it in ThreadLocal, redirect to login if session not found."; } public static void setCookie(Headers responseHeaders, Session session) { responseHeaders.set("Set-Cookie", String.format("%s=%s; path=/", SESSIONID_COOKIENAME, session.getId())); } public static Session getSession(HttpExchange exchange) { return (Session) exchange.getAttribute(SESSION_ATTNAME); } }
package com.axelor.web; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.ws.rs.Path; import org.apache.shiro.guice.web.GuiceShiroFilter; import org.reflections.Reflections; import org.reflections.scanners.TypeAnnotationsScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.axelor.auth.AuthModule; import com.axelor.db.JpaModule; import com.axelor.db.Translations; import com.axelor.meta.service.MetaTranslations; import com.axelor.rpc.Response; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; import com.google.inject.persist.PersistFilter; import com.google.inject.servlet.ServletModule; import com.sun.jersey.api.container.filter.GZIPContentEncodingFilter; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.guice.JerseyServletModule; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; * the web services on <i>/ws/*</i>. * */ public class AppServletModule extends JerseyServletModule { private static final String DEFAULT_PERSISTANCE_UNIT = "persistenceUnit"; private Logger log = LoggerFactory.getLogger(getClass()); private String jpaUnit; public AppServletModule() { this(DEFAULT_PERSISTANCE_UNIT); } public AppServletModule(String jpaUnit) { this.jpaUnit = jpaUnit; } @Override protected void configureServlets() { // load application settings bind(AppSettings.class).asEagerSingleton(); AppSettings settings = AppSettings.get(); StringBuilder builder = new StringBuilder("Starting application:"); builder.append("\n ").append("Name: ").append(settings.get("application.name")); builder.append("\n ").append("Version: ").append(settings.get("application.version")); log.info(builder.toString()); // initialize JPA Properties properties = new Properties(); properties.put("hibernate.ejb.interceptor", "com.axelor.auth.db.AuditInterceptor"); install(new JpaModule(jpaUnit, true, false).properties(properties)); // trick to ensure PersistFilter is registered before anything else install(new ServletModule() { @Override protected void configureServlets() { // order is important, PersistFilter must be the first filter filter("*").through(PersistFilter.class); filter("*").through(LocaleFilter.class); filter("*").through(GuiceShiroFilter.class); } }); // bind LDAP configuration bind(Properties.class).annotatedWith(Names.named("auth.ldap.config")) .toInstance(settings.getProperties()); // install the auth module install(new AuthModule(getServletContext())); // bind to translations provider bind(Translations.class).toProvider(MetaTranslations.class); // no-cache filter if ("dev".equals(settings.get("application.mode", "dev"))) { filter("*").through(NoCacheFilter.class); } // intercept all response methods bindInterceptor(Matchers.any(), Matchers.returns(Matchers.subclassesOf(Response.class)), new ResponseInterceptor()); // bind all the web service resources Reflections reflections = new Reflections("com.axelor.web", new TypeAnnotationsScanner()); for(Class<?> type : reflections.getTypesAnnotatedWith(Path.class)) { bind(type); } // register the session listener getServletContext().addListener(new AppSessionListener(settings)); Map<String, String> params = new HashMap<String, String>(); params.put(ResourceConfig.FEATURE_REDIRECT, "true"); params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.axelor;"); // enable GZIP encoding filter params.put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, GZIPContentEncodingFilter.class.getName()); params.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, GZIPContentEncodingFilter.class.getName()); serve("_init").with(InitServlet.class);
package bndtools.refactor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.resources.IResourceProxyVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.CompositeChange; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.ltk.core.refactoring.TextFileChange; import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; import org.eclipse.ltk.core.refactoring.participants.RenameArguments; import org.eclipse.ltk.core.refactoring.participants.RenameParticipant; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import bndtools.Plugin; import bndtools.utils.FileUtils; public class PkgRenameParticipant extends RenameParticipant { private IPackageFragment pkgFragment; private String changeTitle = null; @Override protected boolean initialize(Object element) { this.pkgFragment = (IPackageFragment) element; RenameArguments args = getArguments(); StringBuilder sb = new StringBuilder(256); sb.append("Bndtools: rename package '"); sb.append(pkgFragment.getElementName()); sb.append("' "); if (((RenamePackageProcessor) this.getProcessor()).getRenameSubpackages()) sb.append("and subpackages "); sb.append("to '"); sb.append(args.getNewName()); sb.append("'"); changeTitle = sb.toString(); return true; } @Override public String getName() { return "Bndtools Package Rename Participant"; } @Override public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) throws OperationCanceledException { return new RefactoringStatus(); } private static final String grammarSeparator = "[\\s,\"';]"; @Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { final Map<IFile, TextChange> fileChanges = new HashMap<IFile, TextChange>(); IResourceProxyVisitor visitor = new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if ((proxy.getType() == IResource.FOLDER) || (proxy.getType() == IResource.PROJECT)) { return true; } if (!((proxy.getType() == IResource.FILE) && proxy.getName().toLowerCase().endsWith(".bnd"))) { return false; } /* we're dealing with a *.bnd file */ /* get the proxied file */ IFile resource = (IFile) proxy.requestResource(); /* read the file as a single string */ String bndFileText = null; try { bndFileText = FileUtils.readFully(resource).get(); } catch (Exception e) { String str = "Could not read file " + proxy.getName(); Plugin.logError(str, e); throw new OperationCanceledException(str); } /* * get the previous change for this file if it exists, or * otherwise create a new change for it */ TextChange fileChange = getTextChange(resource); TextEdit rootEdit = null; if (fileChange == null) { fileChange = new TextFileChange(proxy.getName(), resource); rootEdit = new MultiTextEdit(); fileChange.setEdit(rootEdit); fileChanges.put(resource, fileChange); } else { rootEdit = fileChange.getEdit(); } final String oldName = pkgFragment.getElementName(); final String newName = getArguments().getNewName(); final Pattern pattern = Pattern.compile( /* match start boundary */"(^|" + grammarSeparator + ")" + /* match itself / package name */"(" + Pattern.quote(oldName) + ")" + /* match end boundary */"(" + grammarSeparator + "|" + Pattern.quote(".*") + "|" + Pattern.quote("\\") + "|$)"); /* see if there are matches, if not: return */ Matcher matcher = pattern.matcher(bndFileText); if (!matcher.find()) { return false; } /* find all matches to replace and add them to the root edit */ matcher.reset(); while (matcher.find()) { rootEdit.addChild(new ReplaceEdit(matcher.start(2), matcher.group(2).length(), newName)); } return false; } }; /* determine which projects have to be visited */ Set<IProject> projectsToVisit = new HashSet<IProject>(); projectsToVisit.add(pkgFragment.getResource().getProject()); for (IProject projectToVisit : pkgFragment.getResource().getProject().getReferencingProjects()) { projectsToVisit.add(projectToVisit); } for (IProject projectToVisit : pkgFragment.getResource().getProject().getReferencedProjects()) { projectsToVisit.add(projectToVisit); } /* visit the projects */ for (IProject projectToVisit : projectsToVisit) { projectToVisit.accept(visitor, IContainer.NONE); } if (fileChanges.isEmpty()) { /* no changes at all */ return null; } /* build a composite change with all changes */ CompositeChange cs = new CompositeChange(changeTitle); for (TextChange fileChange : fileChanges.values()) { cs.add(fileChange); } return cs; } }
package bndtools.refactor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.resources.IResourceProxyVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.CompositeChange; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.ltk.core.refactoring.TextFileChange; import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; import org.eclipse.ltk.core.refactoring.participants.RenameArguments; import org.eclipse.ltk.core.refactoring.participants.RenameParticipant; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import bndtools.Plugin; import bndtools.utils.FileUtils; public class PkgRenameParticipant extends RenameParticipant { private IPackageFragment pkgFragment; private String changeTitle = null; @Override protected boolean initialize(Object element) { this.pkgFragment = (IPackageFragment) element; RenameArguments args = getArguments(); StringBuilder sb = new StringBuilder(256); sb.append("Bndtools: rename package '"); sb.append(pkgFragment.getElementName()); sb.append("' "); if (((RenamePackageProcessor) this.getProcessor()).getRenameSubpackages()) sb.append("and subpackages "); sb.append("to '"); sb.append(args.getNewName()); sb.append("'"); changeTitle = sb.toString(); return true; } @Override public String getName() { return "Bndtools Package Rename Participant"; } @Override public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) throws OperationCanceledException { return new RefactoringStatus(); } private static final String grammarSeparator = "[\\s,\"';]"; @Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { final String oldName = pkgFragment.getElementName(); final String newName = getArguments().getNewName(); final Pattern pattern = Pattern.compile( /* match start boundary */"(^|" + grammarSeparator + ")" + /* match itself / package name */"(" + Pattern.quote(oldName) + ")" + /* match end boundary */"(" + grammarSeparator + "|" + Pattern.quote(".*") + "|" + Pattern.quote("\\") + "|$)"); final Map<IFile, TextChange> fileChanges = new HashMap<IFile, TextChange>(); IResourceProxyVisitor visitor = new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if ((proxy.getType() == IResource.FOLDER) || (proxy.getType() == IResource.PROJECT)) { return true; } if (!((proxy.getType() == IResource.FILE) && proxy.getName().toLowerCase().endsWith(".bnd"))) { return false; } /* we're dealing with a *.bnd file */ /* get the proxied file */ IFile resource = (IFile) proxy.requestResource(); /* read the file as a single string */ String bndFileText = null; try { bndFileText = FileUtils.readFully(resource).get(); } catch (Exception e) { String str = "Could not read file " + proxy.getName(); Plugin.logError(str, e); throw new OperationCanceledException(str); } /* see if there are matches, if not: return */ Matcher matcher = pattern.matcher(bndFileText); if (!matcher.find()) { return false; } /* * get the previous change for this file if it exists, or * otherwise create a new change for it */ TextChange fileChange = getTextChange(resource); TextEdit rootEdit = null; if (fileChange == null) { fileChange = new TextFileChange(proxy.getName(), resource); rootEdit = new MultiTextEdit(); fileChange.setEdit(rootEdit); fileChanges.put(resource, fileChange); } else { rootEdit = fileChange.getEdit(); } /* find all matches to replace and add them to the root edit */ matcher.reset(); while (matcher.find()) { rootEdit.addChild(new ReplaceEdit(matcher.start(2), matcher.group(2).length(), newName)); } return false; } }; Set<IProject> visitedProjects = new HashSet<IProject>(); IProject containingProject = pkgFragment.getResource().getProject(); containingProject.accept(visitor, IContainer.NONE); visitedProjects.add(containingProject); for (IProject project : pkgFragment.getResource().getProject().getReferencingProjects()) { project.accept(visitor, IContainer.NONE); visitedProjects.add(project); } for (IProject project : pkgFragment.getResource().getProject().getReferencedProjects()) { if (!visitedProjects.contains(project)) { project.accept(visitor, IContainer.NONE); visitedProjects.add(project); } } if (fileChanges.isEmpty()) { /* no changes at all */ return null; } /* build a composite change with all changes */ CompositeChange cs = new CompositeChange(changeTitle); for (TextChange fileChange : fileChanges.values()) { cs.add(fileChange); } return cs; } }
package ru.job4j.start; import ru.job4j.models.*; import java.util.Date; /**. * Chapter_002 * It programm for ready apps tracker * * @author Anton Vasilyuk * @version 1.0 * @since 0.1 */ public class StartUI { /**. * @input input its object for interaction */ private Input input; /**. * @tracker tracker its object for interaction */ private Tracker tracker; /**. * It's constructor for this class * @param input input parametr object * @param tracker parametr object */ public StartUI(Input input, Tracker tracker) { this.input = input; this.tracker = tracker; } /**. * method for intaraction with apps tracker */ public void init() { MenuTracker menu = new MenuTracker(this.input, this.tracker); int[] ranges = menu.getArrayNumber(); menu.fillActions(); // UserAction deleteAction = new UserAction() { // public int key() { // return 3; // public void execute(Input input, Tracker tracker) { // tam tam // public String info() { // return "3. Delete"; //menu.addAction(deleteAction); do { menu.show(); int key = Integer.valueOf(input.ask("Select:", ranges)); menu.select(key); } while(!"y".equals(this.input.ask("Exit?(y):"))); } /**. * It's main method * @param args args */ public static void main(String[] args) { Input input = new ValidateInput(); Tracker tracker = new Tracker(); new StartUI(input, tracker).init(); } }
package org.chromium; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import org.apache.cordova.AndroidWebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaActivity; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.LinearLayoutSoftKeyboardDetect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class BackgroundActivity extends CordovaActivity { private static final String LOG_TAG = "BackgroundActivity"; private static BackgroundActivity activityInstance; private static Intent activityIntent; DelegatingCordovaInterface delegatingCordovaInterface; @Override public void onCreate(Bundle savedInstanceState) { Log.d(LOG_TAG, "Background Activity onCreate()"); moveTaskToBack(true); delegatingCordovaInterface = new DelegatingCordovaInterface(this); activityInstance = this; activityIntent = null; super.onCreate(savedInstanceState); loadUrl(launchUrl); } @Override protected void createViews() { // No-op so as to not call setContentView(). } // Method is same as super class except we use the delegatingCordovaInterface and getApplicationContext(). @Override protected CordovaWebView makeWebView() { String r = preferences.getString("webView", null); CordovaWebView ret = null; if (r != null) { try { Class<?> webViewClass = Class.forName(r); Constructor<?> constructor = webViewClass.getConstructor(Context.class); ret = (CordovaWebView) constructor.newInstance((Context)this.getApplicationContext()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } if (ret == null) { // If all else fails, return a default WebView ret = new AndroidWebView(this); } ret.init(delegatingCordovaInterface, pluginEntries, internalWhitelist, externalWhitelist, preferences); return ret; } // Allow apps to define their own Background Activity if they want. private static ComponentName getBackgroundActivityComponent(Context context) { PackageManager pm = context.getPackageManager(); PackageInfo packageInfo = null; try { packageInfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("No package info for " + context.getPackageName(), e); } for (ActivityInfo activityInfo : packageInfo.activities) { if (activityInfo.name.contains("Background")) { return new ComponentName(packageInfo.packageName, activityInfo.name); } } return new ComponentName(BackgroundActivity.class.getPackage().toString(), BackgroundActivity.class.getName()); } private static ComponentName findMainActivityComponentName(Context context) { PackageManager pm = context.getPackageManager(); PackageInfo packageInfo = null; try { packageInfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("No package info for " + context.getPackageName(), e); } for (ActivityInfo activityInfo : packageInfo.activities) { if ((activityInfo.flags & ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS) == 0) { return new ComponentName(packageInfo.packageName, activityInfo.name); } } return new ComponentName(BackgroundActivity.class.getPackage().toString(), BackgroundActivity.class.getName()); } // Same as Intent.makeMainActivity(), but we avoid this for Gingerbread compatibility. private static Intent makeMainActivityIntent(ComponentName componentName) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setComponent(componentName); intent.addCategory(Intent.CATEGORY_LAUNCHER); return intent; } public static void launchBackground(Context context) { if (activityIntent != null) { return; // Activity is already scheduled to start. } ComponentName backgroundActivityComponent = getBackgroundActivityComponent(context); activityIntent = makeMainActivityIntent(backgroundActivityComponent); activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND); context.startActivity(activityIntent); } public static void launchForeground(Context context) { ComponentName foregroundActivityComponent = findMainActivityComponentName(context); Intent launchIntent = makeMainActivityIntent(foregroundActivityComponent); launchIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); // Use the application context to start this activity // - Using activity.startActivity() doesn't work (error seen in logcat) // - A semi-random activity will be shown instead context.getApplicationContext().startActivity(launchIntent); } public static CordovaWebView stealWebView(CordovaActivity newCordovaActivity) { if (activityInstance == null) { return null; } activityInstance.delegatingCordovaInterface.underlying = newCordovaActivity; activityInstance.delegatingCordovaInterface.allowStartActivityForResult = true; CordovaWebView ret = activityInstance.appView; activityInstance.appView = null; activityInstance.finish(); activityInstance = null; return ret; } private class DelegatingCordovaInterface implements CordovaInterface { CordovaInterface underlying; boolean allowStartActivityForResult; DelegatingCordovaInterface(CordovaInterface underlying) { this.underlying = underlying; } @Override public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) { if (!allowStartActivityForResult) { // Reason for this is that the hosting activity might change during the intent. // Might look at enabling this if there's a real need, but work-around is to just // start the real activity first. throw new IllegalStateException("Cannot fire intents while app is backgrounded."); } underlying.startActivityForResult(command, intent, requestCode); } @Override public void setActivityResultCallback(CordovaPlugin plugin) { underlying.setActivityResultCallback(plugin); } @Override public Activity getActivity() { return underlying.getActivity(); } @Override public Object onMessage(String id, Object data) { return underlying.onMessage(id, data); } @Override public ExecutorService getThreadPool() { return underlying.getThreadPool(); } } }
package ch.elexis.core.data.activator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.UUID; import org.eclipse.core.runtime.Platform; import org.eclipse.equinox.internal.app.CommandLineArgs; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.Desk; import ch.elexis.admin.AccessControl; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.data.constants.ElexisSystemPropertyConstants; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.events.Heartbeat; import ch.elexis.core.data.events.Heartbeat.HeartListener; import ch.elexis.core.data.events.PatientEventListener; import ch.elexis.core.data.extension.CoreOperationExtensionPoint; import ch.elexis.core.data.interfaces.ShutdownJob; import ch.elexis.core.data.interfaces.events.MessageEvent; import ch.elexis.core.data.interfaces.scripting.Interpreter; import ch.elexis.core.data.preferences.CorePreferenceInitializer; import ch.elexis.core.data.util.PlatformHelper; import ch.elexis.data.Anwender; import ch.elexis.data.Kontakt; import ch.elexis.data.Mandant; import ch.elexis.data.PersistentObject; import ch.elexis.data.PersistentObjectFactory; import ch.elexis.data.Query; import ch.rgw.io.LockFile; import ch.rgw.io.Settings; import ch.rgw.io.SqlSettings; import ch.rgw.io.SysSettings; import ch.rgw.tools.Log; import ch.rgw.tools.StringTool; import ch.rgw.tools.VersionInfo; /** * @since 3.0.0 */ public class CoreHub implements BundleActivator { public static final String PLUGIN_ID = "ch.elexis.core.data"; /* * This version is needed to compare the DB */ public static String Version = "3.1.0.qualifier"; //$NON-NLS-1$ public static final String APPLICATION_NAME = "Elexis Core"; //$NON-NLS-1$ static final String neededJRE = "1.7.0"; //$NON-NLS-1$ public static final String DBVersion = "3.1.0"; //$NON-NLS-1$ protected static Logger log = LoggerFactory.getLogger(CoreHub.class.getName()); private static String LocalCfgFile = null; private BundleContext context; /** Das Singleton-Objekt dieser Klasse */ public static CoreHub plugin; private static List<ShutdownJob> shutdownJobs = new LinkedList<ShutdownJob>(); public static final PersistentObjectFactory poFactory = new PersistentObjectFactory(); /** Heartbeat */ public static Heartbeat heart; static File userDir; /** Globale Einstellungen (Werden in der Datenbank gespeichert) */ public static Settings globalCfg; /** Lokale Einstellungen (Werden in der Registry bzw. ~/.java gespeichert) */ public static Settings localCfg; /** Anwenderspezifische Einstellungen (Werden in der Datenbank gespeichert) */ public static Settings userCfg; /** Mandantspezifische EInstellungen (Werden in der Datenbank gespeichert) */ public static Settings mandantCfg; public static Anwender actUser; // TODO set /** * @deprecated please use {@link ElexisEventDispatcher#getSelected(Mandant.class)} to retrieve * current mandator */ public static Mandant actMandant; public static final CorePreferenceInitializer pin = new CorePreferenceInitializer(); /** Die zentrale Zugriffskontrolle */ public static final AccessControl acl = new AccessControl(); /** * The listener for patient events */ private final PatientEventListener eeli_pat = new PatientEventListener(); /** * get the base directory of this currently running elexis application * * @return the topmost directory of this application or null if this information could not be * retrieved */ public static String getBasePath(){ return PlatformHelper.getBasePath(PLUGIN_ID); } /** * Return a directory suitable for temporary files. Most probably this will be a default tempdir * provided by the os. If none such exists, it will be the user dir. * * @return always a valid and writable directory. */ public static File getTempDir(){ File ret = null; String temp = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$ if (!StringTool.isNothing(temp)) { ret = new File(temp); if (ret.exists() && ret.isDirectory()) { return ret; } else { if (ret.mkdirs()) { return ret; } } } return getWritableUserDir(); } /** * return a directory suitable for plugin specific configuration data. If no such dir exists, it * will be created. If it could not be created, the application will refuse to start. * * @return a directory that exists always and is always writable and readable for plugins of the * currently running elexis instance. Caution: this directory is not necessarily shared * among different OS-Users. In Windows it is normally %USERPROFILE%\elexis, in Linux * ~./elexis */ public static File getWritableUserDir(){ if (userDir == null) { String userhome = null; if (localCfg != null) { userhome = localCfg.get("elexis-userDir", null); //$NON-NLS-1$ } if (userhome == null) { userhome = System.getProperty("user.home"); //$NON-NLS-1$ } if (StringTool.isNothing(userhome)) { userhome = System.getProperty("java.io.tempdir"); //$NON-NLS-1$ } userDir = new File(userhome, "elexis"); //$NON-NLS-1$ } if (!userDir.exists()) { if (!userDir.mkdirs()) { System.err.print("fatal: could not create Userdir"); //$NON-NLS-1$ MessageEvent.fireLoggedError("Panic exit", "could not create userdir " + userDir.getAbsolutePath()); System.exit(-5); } } return userDir; } @Override public void start(BundleContext context) throws Exception{ this.context = context; log.debug("Starting " + CoreHub.class.getName()); plugin = this; startUpBundle(); setUserDir(userDir); heart = Heartbeat.getInstance(); ElexisEventDispatcher.getInstance().addListeners(eeli_pat); // add core ClassLoader to default Script Interpreter Interpreter.classLoaders.add(CoreHub.class.getClassLoader()); if (!ElexisSystemPropertyConstants.RUN_MODE_FROM_SCRATCH.equals(System .getProperty(ElexisSystemPropertyConstants.RUN_MODE))) Runtime.getRuntime().addShutdownHook(new Thread() { public void run(){ SysSettings localCfg = (SysSettings) CoreHub.localCfg; localCfg.write_xml(LocalCfgFile); } }); } public static String readElexisBuildVersion(){ Properties prop = new Properties(); String elexis_version = "Developer"; String url_name = "platform:/plugin/ch.elexis.core.data/version.properties"; try { URL url; url = new URL(url_name); InputStream inputStream = url.openConnection().getInputStream(); if (inputStream != null) { prop.load(inputStream); elexis_version = prop.getProperty("elexis.version"); } } catch (IOException e) { log.warn("Error reading build version information from " + url_name); } return elexis_version.replace("-SNAPSHOT", ""); } @Override public void stop(BundleContext context) throws Exception{ log.debug("Stopping " + CoreHub.class.getName()); if (CoreHub.actUser != null) { Anwender.logoff(); } PersistentObject.disconnect(); ElexisEventDispatcher.getInstance().removeListeners(eeli_pat); ElexisEventDispatcher.getInstance().dump(); globalCfg = null; heart.stop(); plugin = null; this.context = null; } private void startUpBundle(){ String[] args = CommandLineArgs.getApplicationArgs(); String config = "default"; //$NON-NLS-1$ for (String s : args) { if (s.startsWith("--use-config=")) { //$NON-NLS-1$ String[] c = s.split("="); //$NON-NLS-1$ config = c[1]; } } if (ElexisSystemPropertyConstants.RUN_MODE_FROM_SCRATCH.equals(System .getProperty(ElexisSystemPropertyConstants.RUN_MODE))) { config = UUID.randomUUID().toString(); } loadLocalCfg(config); // Damit Anfragen auf userCfg und mandantCfg bei nicht eingeloggtem User // keine NPE werfen userCfg = localCfg; mandantCfg = localCfg; VersionInfo vI = new VersionInfo(System.getProperty("java.version", "0.0.0")); //$NON-NLS-1$ //$NON-NLS-2$ log.info(getId() + "; Java: " + vI.version() + "\nencoding: " + System.getProperty("file.encoding")); if (vI.isOlder(neededJRE)) { MessageEvent.fireLoggedError("Invalid Java version", "Your Java version is older than " + neededJRE + ", please update."); } log.info("Basepath: " + getBasePath()); pin.initializeDefaultPreferences(); heart = Heartbeat.getInstance(); initializeLock(); } private static void initializeLock(){ final int timeoutSeconds = 600; try { final LockFile lockfile = new LockFile(userDir, "elexislock", 4, timeoutSeconds); //$NON-NLS-1$ final int n = lockfile.lock(); if (n == 0) { MessageEvent.fireLoggedError("Too many instances", "Too many concurrent instances of Elexis running. Will exit."); log.error("Too many concurent instances. Check elexis.lock files in " + userDir); System.exit(2); } else { HeartListener lockListener = new HeartListener() { long timeSet; public void heartbeat(){ long now = System.currentTimeMillis(); if ((now - timeSet) > timeoutSeconds) { lockfile.updateLock(n); timeSet = now; } } }; heart.addListener(lockListener, Heartbeat.FREQUENCY_LOW); } } catch (IOException ex) { log.error("Can not aquire lock file in " + userDir + "; " + ex.getMessage()); //$NON-NLS-1$ } } public static String getId(){ StringBuilder sb = new StringBuilder(); sb.append(APPLICATION_NAME).append(" v.").append(Version).append("\n") .append(CoreHubHelper.getRevision(true, plugin)).append("\n") .append(System.getProperty("os.name")).append(StringConstants.SLASH) .append(System.getProperty("os.version")).append(StringConstants.SLASH) .append(System.getProperty("os.arch")); //$NON-NLS-1$ return sb.toString(); } private void loadLocalCfg(String branch){ LocalCfgFile = CoreHubHelper.getWritableUserDir() + "/localCfg_" + branch + ".xml"; String msg = "loadLocalCfg: Loading branch " + branch + " from " + LocalCfgFile; System.out.println(msg); log.debug(msg); SysSettings cfg = new SysSettings(SysSettings.USER_SETTINGS, Desk.class); cfg.read_xml(LocalCfgFile); CoreHub.localCfg = cfg; } public static void setMandant(Mandant newMandant){ if (actMandant != null && mandantCfg != null) { mandantCfg.flush(); } if (newMandant == null) { mandantCfg = userCfg; } else { mandantCfg = getUserSetting(newMandant); } actMandant = newMandant; ElexisEventDispatcher.getInstance().fire( new ElexisEvent(newMandant, Mandant.class, ElexisEvent.EVENT_MANDATOR_CHANGED)); } public static Settings getUserSetting(Kontakt user){ if (StringConstants.ONE.equals(user.get(Kontakt.FLD_IS_USER))) { Settings settings = new SqlSettings(PersistentObject.getConnection(), "USERCONFIG", "Param", "Value", "UserID=" + user.getWrappedId()); return settings; } return null; } public Bundle getBundle(){ return context.getBundle(); } /** * get a list of all mandators known to this system */ public static List<Mandant> getMandantenList(){ Query<Mandant> qbe = new Query<Mandant>(Mandant.class); return qbe.execute(); } /** * get a list of all users known to this system */ public static List<Anwender> getUserList(){ Query<Anwender> qbe = new Query<Anwender>(Anwender.class); return qbe.execute(); } /** * Return the name of a config instance, the user chose. This is just the valuie of the * -Dconfig=xx runtime value or "default" if no -Dconfig was set */ public static String getCfgVariant(){ String config = System.getProperty("config"); return config == null ? "default" : config; } public void setUserDir(File dir){ userDir = dir; localCfg.set("elexis-userDir", dir.getAbsolutePath()); //$NON-NLS-1$ } /** * Add a ShutdownJob to the list of jobs that has to be done after the Elexis workbench was shut * down. * * @param job */ public static void addShutdownJob(final ShutdownJob job){ if (!shutdownJobs.contains(job)) { shutdownJobs.add(job); } } public static int getSystemLogLevel(){ return localCfg.get(Preferences.ABL_LOGLEVEL, Log.ERRORS); } }
package ch.elexis.core.ui.actions; import static ch.elexis.admin.AccessControlDefaults.AC_ABOUT; import static ch.elexis.admin.AccessControlDefaults.AC_CHANGEMANDANT; import static ch.elexis.admin.AccessControlDefaults.AC_CONNECT; import static ch.elexis.admin.AccessControlDefaults.AC_EXIT; import static ch.elexis.admin.AccessControlDefaults.AC_HELP; import static ch.elexis.admin.AccessControlDefaults.AC_IMORT; import static ch.elexis.admin.AccessControlDefaults.AC_LOGIN; import static ch.elexis.admin.AccessControlDefaults.AC_NEWWINDOW; import static ch.elexis.admin.AccessControlDefaults.AC_PREFS; import static ch.elexis.admin.AccessControlDefaults.AC_SHOWPERSPECTIVE; import static ch.elexis.admin.AccessControlDefaults.AC_SHOWVIEW; import static ch.elexis.core.ui.text.TextTemplateRequirement.TT_ADDRESS_LABEL; import static ch.elexis.core.ui.text.TextTemplateRequirement.TT_KG_COVER_SHEET; import static ch.elexis.core.ui.text.TextTemplateRequirement.TT_PATIENT_LABEL; import static ch.elexis.core.ui.text.TextTemplateRequirement.TT_PATIENT_LABEL_ORDER; import static ch.elexis.core.ui.text.TextTemplateRequirement.TT_XRAY; import java.io.File; import java.util.ArrayList; import java.util.List; import org.eclipse.core.commands.IHandler; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.printing.PrintDialog; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.printing.PrinterData; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.help.IWorkbenchHelpSystem; import org.eclipse.ui.part.ViewPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.admin.ACE; import ch.elexis.admin.AccessControlDefaults; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.util.ResultAdapter; import ch.elexis.core.model.IPersistentObject; import ch.elexis.core.ui.Hub; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.constants.ExtensionPointConstantsUi; import ch.elexis.core.ui.constants.UiResourceConstants; import ch.elexis.core.ui.dialogs.DateSelectorDialog; import ch.elexis.core.ui.dialogs.EtiketteDruckenDialog; import ch.elexis.core.ui.dialogs.LoginDialog; import ch.elexis.core.ui.dialogs.NeuerFallDialog; import ch.elexis.core.ui.dialogs.SelectFallDialog; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.locks.LockedAction; import ch.elexis.core.ui.locks.LockedRestrictedAction; import ch.elexis.core.ui.util.Importer; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.core.ui.util.TemplateDrucker; import ch.elexis.core.ui.views.FallDetailView; import ch.elexis.core.ui.views.TemplatePrintView; import ch.elexis.core.ui.wizards.DBConnectWizard; import ch.elexis.data.Fall; import ch.elexis.data.Konsultation; import ch.elexis.data.Kontakt; import ch.elexis.data.Mandant; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.elexis.data.Query; import ch.elexis.data.Rechnung; import ch.rgw.tools.ExHandler; import ch.rgw.tools.Result; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; /** * Diese Klasse definiert alle statischen Actions, die global gelten sollen. */ public class GlobalActions { // globally used command ids (for key bindings / actions) public static final String RENAME_COMMAND = "org.eclipse.ui.edit.rename"; //$NON-NLS-1$ public static final String DELETE_COMMAND = "org.eclipse.ui.edit.delete"; //$NON-NLS-1$ public static final String PROPERTIES_COMMAND = "org.eclipse.ui.file.properties"; //$NON-NLS-1$ public static final String DEFAULTPERSPECTIVECFG = "/default_perspective"; //$NON-NLS-1$ public static IWorkbenchAction exitAction, newWindowAction, copyAction, cutAction, pasteAction; public static IAction loginAction, importAction, aboutAction, helpAction, prefsAction; public static IAction connectWizardAction, changeMandantAction, savePerspectiveAction, savePerspectiveAsAction; public static IAction savePerspectiveAsDefaultAction, resetPerspectiveAction, homeAction, fixLayoutAction; public static IAction printEtikette, printBlatt, printAdresse, printVersionedEtikette, showBlatt; public static IAction printRoeBlatt; public static IAction openFallaction, filterAction, makeBillAction, planeRechnungAction; public static RestrictedAction delKonsAction, delFallAction, reopenFallAction, neueKonsAction; public static LockedAction moveBehandlungAction, redateAction; public static IAction neuerFallAction; public static MenuManager perspectiveMenu, viewMenu; public static IContributionItem perspectiveList, viewList; public IWorkbenchWindow mainWindow; public static Action printKontaktEtikette; private static IWorkbenchHelpSystem help; private static Logger logger; public GlobalActions(final IWorkbenchWindow window){ if (Hub.mainActions != null) { return; } logger = LoggerFactory.getLogger(this.getClass()); mainWindow = window; help = Hub.plugin.getWorkbench().getHelpSystem(); exitAction = ActionFactory.QUIT.create(window); exitAction.setText(Messages.GlobalActions_MenuExit); //$NON-NLS-1$ newWindowAction = ActionFactory.OPEN_NEW_WINDOW.create(window); newWindowAction.setText(Messages.GlobalActions_NewWindow); //$NON-NLS-1$ copyAction = ActionFactory.COPY.create(window); copyAction.setText(Messages.GlobalActions_Copy); //$NON-NLS-1$ cutAction = ActionFactory.CUT.create(window); cutAction.setText(Messages.GlobalActions_Cut); //$NON-NLS-1$ pasteAction = ActionFactory.PASTE.create(window); pasteAction.setText(Messages.GlobalActions_Paste); //$NON-NLS-1$ aboutAction = ActionFactory.ABOUT.create(window); aboutAction.setText(Messages.GlobalActions_MenuAbout); //$NON-NLS-1$ // helpAction=ActionFactory.HELP_CONTENTS.create(window); // helpAction.setText(Messages.getString("GlobalActions.HelpIndex")); //$NON-NLS-1$ prefsAction = ActionFactory.PREFERENCES.create(window); prefsAction.setText(Messages.GlobalActions_Preferences); //$NON-NLS-1$ savePerspectiveAction = new Action(Messages.GlobalActions_SavePerspective) { //$NON-NLS-1$ { setId("savePerspektive"); //$NON-NLS-1$ // setActionDefinitionId(Hub.COMMAND_PREFIX+"savePerspektive"); //$NON-NLS-1$ setToolTipText(Messages.GlobalActions_SavePerspectiveToolTip); //$NON-NLS-1$ setImageDescriptor(Images.IMG_DISK.getImageDescriptor()); //$NON-NLS-1$ } @Override public void run(){ IWorkbenchPage page = mainWindow.getActivePage(); if (page != null && page.getPerspective() != null) { page.savePerspectiveAs(page.getPerspective()); } } }; helpAction = new Action(Messages.GlobalActions_ac_handbook) { //$NON-NLS-1$ { setImageDescriptor(Images.IMG_BOOK.getImageDescriptor()); setToolTipText(Messages.GlobalActions_ac_openhandbook); //$NON-NLS-1$ } @Override public void run(){ File book = new File(Platform.getInstallLocation().getURL().getPath() + "elexis.pdf"); //$NON-NLS-1$ Program proggie = Program.findProgram(".pdf"); //$NON-NLS-1$ if (proggie != null) { logger .info("will open handbook: " + book.toString() + " using: " + proggie); proggie.execute(book.toString()); } else { logger.info("will launch handbook: " + book.toString()); if (Program.launch(book.toString()) == false) { try { logger.info("will exec handbook: " + book.toString()); Runtime.getRuntime().exec(book.toString()); } catch (Exception e) { ExHandler.handle(e); } } } } }; savePerspectiveAsAction = ActionFactory.SAVE_PERSPECTIVE.create(window); // ActionFactory.SAVE_PERSPECTIVE.create(window); resetPerspectiveAction = ActionFactory.RESET_PERSPECTIVE.create(window); resetPerspectiveAction.setImageDescriptor(Images.IMG_REFRESH.getImageDescriptor()); homeAction = new Action(Messages.GlobalActions_Home) { //$NON-NLS-1$ { setId("home"); //$NON-NLS-1$ setActionDefinitionId(Hub.COMMAND_PREFIX + "home"); //$NON-NLS-1$ setImageDescriptor(Images.IMG_HOME.getImageDescriptor()); setToolTipText(Messages.GlobalActions_HomeToolTip); //$NON-NLS-1$ help.setHelp(this, "ch.elexis.globalactions.homeAction"); //$NON-NLS-1$ } @Override public void run(){ // String // perspektive=CoreHub.actUser.getInfoString("StartPerspektive"); String perspektive = CoreHub.localCfg.get(CoreHub.actUser + DEFAULTPERSPECTIVECFG, null); if (StringTool.isNothing(perspektive)) { perspektive = UiResourceConstants.PatientPerspektive_ID; } try { IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); PlatformUI.getWorkbench().showPerspective(perspektive, win); // Hub.heart.resume(true); } catch (Exception ex) { ExHandler.handle(ex); } } }; savePerspectiveAsDefaultAction = new Action(Messages.GlobalActions_saveasstartperspective) { //$NON-NLS-1$ { setId("start"); //$NON-NLS-1$ // setActionDefinitionId(Hub.COMMAND_PREFIX+"startPerspective"); } @Override public void run(){ IPerspectiveDescriptor p = mainWindow.getActivePage().getPerspective(); CoreHub.localCfg.set(CoreHub.actUser + DEFAULTPERSPECTIVECFG, p.getId()); // CoreHub.actUser.setInfoElement("StartPerspektive",p.getId()); } }; loginAction = new Action(Messages.GlobalActions_Login) { //$NON-NLS-1$ { setId("login"); //$NON-NLS-1$ setActionDefinitionId(Hub.COMMAND_PREFIX + "login");} //$NON-NLS-1$ @Override public void run(){ try { IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchWindow[] wins = PlatformUI.getWorkbench().getWorkbenchWindows(); for (IWorkbenchWindow w : wins) { if (!w.equals(win)) { w.close(); } } CoreHub.logoffAnwender(); LoginDialog dlg = new LoginDialog(win.getShell()); dlg.create(); dlg.setTitle(Messages.GlobalActions_LoginDialogTitle); //$NON-NLS-1$ dlg.setMessage(Messages.GlobalActions_LoginDialogMessage); //$NON-NLS-1$ // dlg.getButton(IDialogConstants.CANCEL_ID).setText("Beenden"); dlg.getShell().setText(Messages.GlobalActions_LoginDialogShelltext); //$NON-NLS-1$ if (dlg.open() == Dialog.CANCEL) { exitAction.run(); } adaptForUser(); } catch (Exception ex) { ExHandler.handle(ex); } System.out.println("login"); //$NON-NLS-1$ } }; importAction = new Action(Messages.GlobalActions_Import) { //$NON-NLS-1$ { setId("import"); //$NON-NLS-1$ setActionDefinitionId(Hub.COMMAND_PREFIX + "import");} //$NON-NLS-1$ @Override public void run(){ // cnv.open(); Importer imp = new Importer(mainWindow.getShell(), ExtensionPointConstantsUi.FREMDDATENIMPORT); imp.create(); imp.setMessage(Messages.GlobalActions_ImportDlgMessage); //$NON-NLS-1$ imp.getShell().setText(Messages.GlobalActions_ImportDlgShelltext); //$NON-NLS-1$ imp.setTitle(Messages.GlobalActions_ImportDlgTitle); //$NON-NLS-1$ imp.open(); } }; connectWizardAction = new Action(Messages.GlobalActions_Connection) { //$NON-NLS-1$ { setId("connectWizard"); //$NON-NLS-1$ setActionDefinitionId(Hub.COMMAND_PREFIX + "connectWizard"); //$NON-NLS-1$ } @Override public void run(){ WizardDialog wd = new WizardDialog(mainWindow.getShell(), new DBConnectWizard()); wd.open(); } }; changeMandantAction = new Action(Messages.GlobalActions_Mandator) { //$NON-NLS-1$ { setId("changeMandant"); //$NON-NLS-1$ // setActionDefinitionId(Hub.COMMAND_PREFIX+"changeMandant"); //$NON-NLS-1$ } @Override public void run(){ ChangeMandantDialog cmd = new ChangeMandantDialog(); if (cmd.open() == org.eclipse.jface.dialogs.Dialog.OK) { Mandant n = cmd.result; if (n != null) { Hub.setMandant(n); } } } }; printKontaktEtikette = new Action(Messages.GlobalActions_PrintContactLabel) { //$NON-NLS-1$ { setToolTipText(Messages.GlobalActions_PrintContactLabelToolTip); //$NON-NLS-1$ setImageDescriptor(Images.IMG_ADRESSETIKETTE.getImageDescriptor()); } @Override public void run(){ Kontakt kontakt = (Kontakt) ElexisEventDispatcher.getSelected(Kontakt.class); if (kontakt == null) { SWTHelper.showInfo("Kein Kontakt ausgewählt", "Bitte wählen Sie vor dem Drucken einen Kontakt!"); return; } EtiketteDruckenDialog dlg = new EtiketteDruckenDialog(mainWindow.getShell(), kontakt, TT_ADDRESS_LABEL); dlg.setTitle(Messages.GlobalActions_PrintContactLabel); dlg.setMessage(Messages.GlobalActions_PrintContactLabelToolTip); if (isDirectPrint()) { dlg.setBlockOnOpen(false); dlg.open(); if (dlg.doPrint()) { dlg.close(); } else { SWTHelper .alert("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten. Bitte überprüfen Sie die Einstellungen."); } } else { dlg.setBlockOnOpen(true); dlg.open(); } } }; printAdresse = new Action(Messages.GlobalActions_PrintAddressLabel) { //$NON-NLS-1$ { setImageDescriptor(Images.IMG_ADRESSETIKETTE.getImageDescriptor()); setToolTipText(Messages.GlobalActions_PrintAddressLabelToolTip); //$NON-NLS-1$ } @Override public void run(){ Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (actPatient == null) { SWTHelper.showInfo("Kein Patient ausgewählt", "Bitte wählen Sie vor dem Drucken einen Patient!"); return; } EtiketteDruckenDialog dlg = new EtiketteDruckenDialog(mainWindow.getShell(), actPatient, TT_ADDRESS_LABEL); dlg.setTitle(Messages.GlobalActions_PrintAddressLabel); dlg.setMessage(Messages.GlobalActions_PrintAddressLabelToolTip); if (isDirectPrint()) { dlg.setBlockOnOpen(false); dlg.open(); if (dlg.doPrint()) { dlg.close(); } else { SWTHelper .alert("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten. Bitte überprüfen Sie die Einstellungen."); } } else { dlg.setBlockOnOpen(true); dlg.open(); } } }; printVersionedEtikette = new Action(Messages.GlobalActions_PrintVersionedLabel) { //$NON-NLS-1$ { setToolTipText(Messages.GlobalActions_PrintVersionedLabelToolTip); //$NON-NLS-1$ setImageDescriptor(Images.IMG_VERSIONEDETIKETTE.getImageDescriptor()); } @Override public void run(){ Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (actPatient == null) { SWTHelper.showInfo("Kein Patient ausgewählt", "Bitte wählen Sie vor dem Drucken einen Patient!"); return; } EtiketteDruckenDialog dlg = new EtiketteDruckenDialog(mainWindow.getShell(), actPatient, TT_PATIENT_LABEL_ORDER); dlg.setTitle(Messages.GlobalActions_PrintVersionedLabel); dlg.setMessage(Messages.GlobalActions_PrintVersionedLabelToolTip); if (isDirectPrint()) { dlg.setBlockOnOpen(false); dlg.open(); if (dlg.doPrint()) { dlg.close(); } else { SWTHelper .alert("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten. Bitte überprüfen Sie die Einstellungen."); } } else { dlg.setBlockOnOpen(true); dlg.open(); } } }; printEtikette = new Action(Messages.GlobalActions_PrintLabel) { //$NON-NLS-1$ { setImageDescriptor(Images.IMG_PATIENTETIKETTE.getImageDescriptor()); setToolTipText(Messages.GlobalActions_PrintLabelToolTip); //$NON-NLS-1$ } @Override public void run(){ Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (actPatient == null) { SWTHelper.showInfo("Kein Patient ausgewählt", "Bitte wählen Sie vor dem Drucken einen Patient!"); return; } EtiketteDruckenDialog dlg = new EtiketteDruckenDialog(mainWindow.getShell(), actPatient, TT_PATIENT_LABEL); dlg.setTitle(Messages.GlobalActions_PrintLabel); dlg.setMessage(Messages.GlobalActions_PrintLabelToolTip); if (isDirectPrint()) { dlg.setBlockOnOpen(false); dlg.open(); if (dlg.doPrint()) { dlg.close(); } else { SWTHelper .alert("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten. Bitte überprüfen Sie die Einstellungen."); } } else { dlg.setBlockOnOpen(true); dlg.open(); } } }; printBlatt = new Action(Messages.GlobalActions_PrintEMR) { //$NON-NLS-1$ @Override public void run(){ Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class); String printer = CoreHub.localCfg.get("Drucker/Einzelblatt/Name", null); //$NON-NLS-1$ String tray = CoreHub.localCfg.get("Drucker/Einzelblatt/Schacht", null); //$NON-NLS-1$ new TemplateDrucker(TT_KG_COVER_SHEET, printer, tray).doPrint(actPatient); //$NON-NLS-1$ } }; showBlatt = new Action(Messages.GlobalActions_ShowEMR) { //$NON-NLS-1$ @Override public void run(){ Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class); try { TemplatePrintView tpw = (TemplatePrintView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().showView(TemplatePrintView.ID); tpw.doShow(actPatient, TT_KG_COVER_SHEET); } catch (PartInitException e) { MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Fehler", "Konnte View nicht öffnen"); LoggerFactory.getLogger(getClass()) .error("Error showing " + TemplatePrintView.ID, e); } } }; printRoeBlatt = new Action(Messages.GlobalActions_PrintXRay) { //$NON-NLS-1$ @Override public void run(){ Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class); String printer = CoreHub.localCfg.get("Drucker/A4/Name", null); //$NON-NLS-1$ String tray = CoreHub.localCfg.get("Drucker/A4/Schacht", null); //$NON-NLS-1$ new TemplateDrucker(TT_XRAY, printer, tray).doPrint(actPatient); //$NON-NLS-1$ } }; fixLayoutAction = new Action(Messages.GlobalActions_LockPerspectives, Action.AS_CHECK_BOX) { //$NON-NLS-1$ { setToolTipText(Messages.GlobalActions_LockPerspectivesToolTip); //$NON-NLS-1$ } @Override public void run(){ // store the current value in the user's configuration CoreHub.userCfg.set(Preferences.USR_FIX_LAYOUT, fixLayoutAction.isChecked()); } }; makeBillAction = new Action(Messages.GlobalActions_MakeBill) { //$NON-NLS-1$ @Override public void run(){ Fall actFall = (Fall) ElexisEventDispatcher.getSelected(Fall.class); Mandant mnd = ElexisEventDispatcher.getSelectedMandator(); if (actFall != null && mnd != null) { String rsId = mnd.getRechnungssteller().getId(); Konsultation[] bhdl = actFall.getBehandlungen(false); ArrayList<Konsultation> lBehdl = new ArrayList<Konsultation>(bhdl.length); for (Konsultation b : bhdl) { Rechnung rn = b.getRechnung(); if (rn == null) { if (b.getMandant().getRechnungssteller().getId().equals(rsId)) { lBehdl.add(b); } } } Result<Rechnung> res = Rechnung.build(lBehdl); if (!res.isOK()) { ErrorDialog.openError(mainWindow.getShell(), Messages.GlobalActions_Error, Messages //$NON-NLS-1$ .GlobalActions_BillErrorMessage, ResultAdapter //$NON-NLS-1$ .getResultAsStatus(res)); // Rechnung rn=(Rechnung)res.get(); // rn.storno(true); // rn.delete(); } } // setFall(actFall,null); } }; moveBehandlungAction = new LockedAction<Konsultation>(Messages.GlobalActions_AssignCase) { @Override public Konsultation getTargetedObject() { return (Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class); } @Override public void doRun(Konsultation element) { // TODO do we need to lock the fall? SelectFallDialog dlg = new SelectFallDialog(mainWindow.getShell()); if (dlg.open() == Dialog.OK) { Fall f = dlg.result; if (f != null) { element.setFall(f); ElexisEventDispatcher.fireSelectionEvent(f); } } } }; redateAction = new LockedAction<Konsultation>(Messages.GlobalActions_Redate) { @Override public Konsultation getTargetedObject() { return (Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class); } @Override public void doRun(Konsultation element) { DateSelectorDialog dlg = new DateSelectorDialog(mainWindow.getShell()); if (dlg.open() == Dialog.OK) { TimeTool date = dlg.getSelectedDate(); element.setDatum(date.toString(TimeTool.DATE_GER), false); // notify listeners about change ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(element, Konsultation.class, ElexisEvent.EVENT_UPDATE)); ElexisEventDispatcher.fireSelectionEvent(element); } } }; delFallAction = new LockedRestrictedAction<Fall>(AccessControlDefaults.DELETE_CASE, Messages.GlobalActions_DeleteCase) { @Override public void doRun(Fall element) { if ((element.delete(false) == false)) { SWTHelper.alert(Messages.GlobalActions_CouldntDeleteCaseMessage, Messages.GlobalActions_CouldntDeleteCaseExplanation); } ElexisEventDispatcher.reload(Fall.class); } @Override public Fall getTargetedObject() { return (Fall) ElexisEventDispatcher.getSelected(Fall.class); } }; delKonsAction = new LockedRestrictedAction<Konsultation>(AccessControlDefaults.KONS_DELETE, Messages.GlobalActions_DeleteKons) { @Override public void doRun(Konsultation element) { if (element.delete(false) == false) { SWTHelper.alert(Messages.GlobalActions_CouldntDeleteKons, // $NON-NLS-1$ Messages.GlobalActions_CouldntDeleteKonsExplanation + // $NON-NLS-1$ Messages.GlobalActions_97); // $NON-NLS-1$ } ElexisEventDispatcher.clearSelection(Konsultation.class); ElexisEventDispatcher.fireSelectionEvent(element.getFall()); } @Override public Konsultation getTargetedObject() { return (Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class); } }; openFallaction = new Action(Messages.GlobalActions_EditCase) { //$NON-NLS-1$ @Override public void run(){ try { Hub.plugin.getWorkbench().getActiveWorkbenchWindow().getActivePage() .showView(FallDetailView.ID); // getViewSite().getPage().showView(FallDetailView.ID); } catch (Exception ex) { ExHandler.handle(ex); } } }; reopenFallAction = new LockedRestrictedAction<Fall>(AccessControlDefaults.CASE_REOPEN, Messages.GlobalActions_ReopenCase) { @Override public void doRun(Fall element) { element.setEndDatum(StringConstants.EMPTY); } @Override public Fall getTargetedObject() { return (Fall) ElexisEventDispatcher.getSelected(Fall.class); } }; neueKonsAction = new RestrictedAction(AccessControlDefaults.KONS_CREATE, Messages.GlobalActions_NewKons) { { setImageDescriptor(Images.IMG_NEW.getImageDescriptor()); setToolTipText(Messages.GlobalActions_NewKonsToolTip); //$NON-NLS-1$ } @Override public void doRun(){ Konsultation.neueKons(null); IPersistentObject kons = ElexisEventDispatcher.getSelected(Konsultation.class); if (kons != null && kons.exists()) { CoreHub.getLocalLockService().acquireLock(kons); CoreHub.getLocalLockService().releaseLock(kons); } } }; neuerFallAction = new Action(Messages.GlobalActions_NewCase) { //$NON-NLS-1$ { setImageDescriptor(Images.IMG_NEW.getImageDescriptor()); setToolTipText(Messages.GlobalActions_NewCaseToolTip); //$NON-NLS-1$ } @Override public void run(){ Patient pat = ElexisEventDispatcher.getSelectedPatient(); if (pat != null) { NeuerFallDialog nfd = new NeuerFallDialog(mainWindow.getShell(), null); if (nfd.open() == Dialog.OK) { } } } }; planeRechnungAction = new Action(Messages.GlobalActions_plaBill) { //$NON-NLS-1$ public void run(){ } }; } protected void printPatient(final Patient patient){ PrinterData pd = getPrinterData("Etiketten"); //$NON-NLS-1$ if (pd != null) { // 25.01.2010 patch tschaller: page orientation of printer // driver is not handled correctly (we always get porttrait // even when the printer settings have landscape stored) Integer iOrientation = -1; String sOrientation = CoreHub.localCfg.get("Drucker/Etiketten/Ausrichtung", null); //$NON-NLS-1$ try { iOrientation = Integer.parseInt(sOrientation); } catch (NumberFormatException ex) {} if (iOrientation != -1) pd.orientation = iOrientation; Printer prn = new Printer(pd); if (prn.startJob(Messages.GlobalActions_PrintLabelJobName) == true) { //$NON-NLS-1$ GC gc = new GC(prn); int y = 0; prn.startPage(); gc.drawString(Messages.GlobalActions_PatientIDLabelText + patient.getPatCode(), 0, 0); //$NON-NLS-1$ FontMetrics fmt = gc.getFontMetrics(); y += fmt.getHeight(); String pers = patient.getPersonalia(); gc.drawString(pers, 0, y); y += fmt.getHeight(); gc.drawString(patient.getAnschrift().getEtikette(false, false), 0, y); y += fmt.getHeight(); StringBuilder tel = new StringBuilder(); tel.append(Messages.GlobalActions_PhoneHomeLabelText) .append(patient.get("Telefon1")) //$NON-NLS-1$ //$NON-NLS-2$ .append(Messages.GlobalActions_PhoneWorkLabelText) .append(patient.get("Telefon2")) //$NON-NLS-1$ //$NON-NLS-2$ .append(Messages.GlobalActions_PhoneMobileLabelText) .append(patient.get("Natel")); //$NON-NLS-1$ //$NON-NLS-2$ gc.drawString(tel.toString(), 0, y); gc.dispose(); prn.endPage(); prn.endJob(); prn.dispose(); } else { MessageDialog.openError(mainWindow.getShell(), Messages.GlobalActions_PrinterErrorTitle, Messages.GlobalActions_PrinterErrorMessage); //$NON-NLS-1$ //$NON-NLS-2$ } } } protected void printPatientAuftragsnummer(final Patient patient){ PrinterData pd = getPrinterData("Etiketten"); //$NON-NLS-1$ if (pd != null) { // 25.01.2010 patch tschaller: page orientation of printer // driver is not handled correctly (we always get porttrait // even when the printer settings have landscape stored) Integer iOrientation = -1; String sOrientation = CoreHub.localCfg.get("Drucker/Etiketten/Ausrichtung", null); //$NON-NLS-1$ try { iOrientation = Integer.parseInt(sOrientation); } catch (NumberFormatException ex) {} if (iOrientation != -1) pd.orientation = iOrientation; Printer prn = new Printer(pd); if (prn.startJob(Messages.GlobalActions_PrintLabelJobName) == true) { //$NON-NLS-1$ GC gc = new GC(prn); int y = 0; prn.startPage(); String pid = StringTool.addModulo10(patient.getPatCode()) + "-" //$NON-NLS-1$ + new TimeTool().toString(TimeTool.TIME_COMPACT); gc.drawString(Messages.GlobalActions_OrderID + ": " + pid, 0, 0); //$NON-NLS-1$ //$NON-NLS-2$ FontMetrics fmt = gc.getFontMetrics(); y += fmt.getHeight(); String pers = patient.getPersonalia(); gc.drawString(pers, 0, y); y += fmt.getHeight(); gc.drawString(patient.getAnschrift().getEtikette(false, false), 0, y); y += fmt.getHeight(); StringBuilder tel = new StringBuilder(); tel.append(Messages.GlobalActions_PhoneHomeLabelText) .append(patient.get("Telefon1")) //$NON-NLS-1$ //$NON-NLS-2$ .append(Messages.GlobalActions_PhoneWorkLabelText) .append(patient.get("Telefon2")) //$NON-NLS-1$ //$NON-NLS-2$ .append(Messages.GlobalActions_PhoneMobileLabelText) .append(patient.get("Natel")); //$NON-NLS-1$ //$NON-NLS-2$ gc.drawString(tel.toString(), 0, y); gc.dispose(); prn.endPage(); prn.endJob(); prn.dispose(); } else { MessageDialog.openError(mainWindow.getShell(), Messages.GlobalActions_PrinterErrorTitle, Messages.GlobalActions_PrinterErrorMessage); //$NON-NLS-1$ //$NON-NLS-2$ } } } protected void printAdr(final Kontakt k){ // 25.01.2010 patch tschaller: there was always the printer selection // dialog. With printEtikette it wasn't so I copied the hardcoded string // from there //PrinterData pd = getPrinterData(Messages.getString("GlobalActions.printersticker")); //$NON-NLS-1$ PrinterData pd = getPrinterData("Etiketten"); //$NON-NLS-1$ if (pd != null) { // 25.01.2010 patch tschaller: page orientation of printer driver is // not handled correctly (we always get porttrait even when the // printer settings have landscape stored) Integer iOrientation = -1; String sOrientation = CoreHub.localCfg.get("Drucker/Etiketten/Ausrichtung", null); //$NON-NLS-1$ try { iOrientation = Integer.parseInt(sOrientation); } catch (NumberFormatException ex) {} if (iOrientation != -1) pd.orientation = iOrientation; Printer prn = new Printer(pd); if (prn.startJob("Etikette drucken") == true) { //$NON-NLS-1$ GC gc = new GC(prn); int y = 0; prn.startPage(); FontMetrics fmt = gc.getFontMetrics(); String pers = k.getPostAnschrift(true); String[] lines = pers.split("\n"); //$NON-NLS-1$ for (String line : lines) { gc.drawString(line, 0, y); y += fmt.getHeight(); } gc.dispose(); prn.endPage(); prn.endJob(); prn.dispose(); } else { MessageDialog.openError(mainWindow.getShell(), Messages.GlobalActions_PrinterErrorTitle, Messages.GlobalActions_PrinterErrorMessage); //$NON-NLS-1$ //$NON-NLS-2$ } } } /** * Return a PrinterData object according to the given type (e. g. "Etiketten") and the user * settings. Shows a printer selection dialog if required. * * @param type * the printer type according to the printer settings * @return a PrinterData object describing the selected printer */ private PrinterData getPrinterData(final String type){ String cfgPrefix = "Drucker/" + type + "/"; //$NON-NLS-1$ //$NON-NLS-2$ $NON-NLS-2$ PrinterData pd = null; String printer = CoreHub.localCfg.get(cfgPrefix + "Name", null); //$NON-NLS-1$ String driver = CoreHub.localCfg.get(cfgPrefix + "Driver", null); //$NON-NLS-1$ boolean choose = CoreHub.localCfg.get(cfgPrefix + "Choose", false); //$NON-NLS-1$ if (choose || StringTool.isNothing(printer) || StringTool.isNothing(driver)) { Shell shell = UiDesk.getTopShell(); PrintDialog pdlg = new PrintDialog(shell); pd = pdlg.open(); } else { pd = new PrinterData(driver, printer); } return pd; } /** * Return true if direct printing on defined printer. If false, the user has to choose the * printer and print himself */ private boolean isDirectPrint(){ return !CoreHub.localCfg.get("Drucker/Etiketten/Choose", true); } public void adaptForUser(){ setMenuForUser(AC_EXIT, exitAction); // setMenuForUser(AC_UPDATE,updateAction); //$NON-NLS-1$ setMenuForUser(AC_NEWWINDOW, newWindowAction); setMenuForUser(AC_LOGIN, loginAction); setMenuForUser(AC_IMORT, importAction); setMenuForUser(AC_ABOUT, aboutAction); setMenuForUser(AC_HELP, helpAction); setMenuForUser(AC_PREFS, prefsAction); setMenuForUser(AC_CHANGEMANDANT, changeMandantAction); // setMenuForUser("importTarmedAction",importTarmedAction); setMenuForUser(AC_CONNECT, connectWizardAction); if (CoreHub.acl.request(AC_SHOWPERSPECTIVE) == true) { perspectiveList.setVisible(true); } else { perspectiveList.setVisible(false); } if (CoreHub.acl.request(AC_SHOWVIEW) == true) { viewList.setVisible(true); } else { viewList.setVisible(false); } // restore menue settings if (CoreHub.actUser != null) { boolean fixLayoutChecked = CoreHub.userCfg.get(Preferences.USR_FIX_LAYOUT, Preferences.USR_FIX_LAYOUT_DEFAULT); fixLayoutAction.setChecked(fixLayoutChecked); // System.err.println("fixLayoutAction: set to " + // fixLayoutChecked); } else { fixLayoutAction.setChecked(Preferences.USR_FIX_LAYOUT_DEFAULT); // System.err.println("fixLayoutAction: reset to false"); } } private void setMenuForUser(final ACE ace, final IAction action){ if (CoreHub.acl.request(ace) == true) { action.setEnabled(true); } else { action.setEnabled(false); } } /** * Creates an ActionHandler for the given IAction and registers it to the Site's HandlerService, * i. e. binds the action to the command so that key bindings get activated. You need to set the * action's actionDefinitionId to the command id. * * @param action * the action to activate. The action's actionDefinitionId must have been set to the * command's id (using <code>setActionDefinitionId()</code>) * @param part * the view this action should be registered for */ public static void registerActionHandler(final ViewPart part, final IAction action){ String commandId = action.getActionDefinitionId(); if (!StringTool.isNothing(commandId)) { IHandlerService handlerService = (IHandlerService) part.getSite().getService(IHandlerService.class); IHandler handler = new ActionHandler(action); handlerService.activateHandler(commandId, handler); } } class ChangeMandantDialog extends TitleAreaDialog { List<Mandant> lMandant; org.eclipse.swt.widgets.List lbMandant; Mandant result; ChangeMandantDialog(){ super(mainWindow.getShell()); } @Override public Control createDialogArea(final Composite parent){ lbMandant = new org.eclipse.swt.widgets.List(parent, SWT.BORDER | SWT.SINGLE); lbMandant.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); Query<Mandant> qbe = new Query<Mandant>(Mandant.class); lMandant = qbe.execute(); for (PersistentObject m : lMandant) { lbMandant.add(m.getLabel()); } return lbMandant; } @Override protected void okPressed(){ int idx = lbMandant.getSelectionIndex(); if (idx > -1) { result = lMandant.get(idx); } super.okPressed(); } @Override public void create(){ super.create(); setTitle(Messages.GlobalActions_ChangeMandator); //$NON-NLS-1$ setMessage(Messages.GlobalActions_ChangeMandatorMessage); //$NON-NLS-1$ } }; }
// TagSoup is distributed in the hope that it will be useful, but // unless required by applicable law or agreed to in writing, TagSoup // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. package org.ccil.cowan.tagsoup; import java.io.*; import org.xml.sax.SAXException; import org.xml.sax.Locator; /** This class implements a table-driven scanner for HTML, allowing for lots of defects. It implements the Scanner interface, which accepts a Reader object to fetch characters from and a ScanHandler object to report lexical events to. */ public class HTMLScanner implements Scanner, Locator { // Start of state table @@STATE_TABLE@@ // End of state table private String thePublicid; // Locator state private String theSystemid; private int theLastLine; private int theLastColumn; private int theCurrentLine; private int theCurrentColumn; int theState; // Current state int theNextState; // Next state char[] theOutputBuffer = new char[200]; // Output buffer int theSize; // Current buffer size int[] theWinMap = { // Windows chars map 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0x017D, 0xFFFD, 0xFFFD, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0x017E, 0x0178}; // Compensate for bug in PushbackReader that allows // pushing back EOF. private void unread(PushbackReader r, int c) throws IOException { if (c != -1) r.unread(c); } // Locator implementation public int getLineNumber() { return theLastLine; } public int getColumnNumber() { return theLastColumn; } public String getPublicId() { return thePublicid; } public String getSystemId() { return theSystemid; } // Scanner implementation /** Reset document locator, supplying systemid and publicid. @param systemid System id @param publicid Public id */ public void resetDocumentLocator(String publicid, String systemid) { thePublicid = publicid; theSystemid = systemid; theLastLine = theLastColumn = theCurrentLine = theCurrentColumn = 0; } /** Scan HTML source, reporting lexical events. @param r0 Reader that provides characters @param h ScanHandler that accepts lexical events. */ public void scan(Reader r0, ScanHandler h) throws IOException, SAXException { theState = S_PCDATA; PushbackReader r = new PushbackReader(new BufferedReader(r0), 2); int firstChar = r.read(); // Remove any leading BOM if (firstChar != '\uFEFF') unread(r, firstChar); while (theState != S_DONE) { int ch = r.read(); // Process control characters if (ch >= 0x80 && ch <= 0x9F) ch = theWinMap[ch-0x80]; if (ch == '\r') { ch = r.read(); // expect LF next if (ch != '\n') { unread(r, ch); // nope ch = '\n'; } } if (ch == '\n') { theCurrentLine++; theCurrentColumn = 0; } else { theCurrentColumn++; } if (!(ch >= 0x20 || ch == '\n' || ch == '\t' || ch == -1)) continue; // Search state table int action = 0; for (int i = 0; i < statetable.length; i += 4) { if (theState != statetable[i]) { if (action != 0) break; continue; } if (statetable[i+1] == 0) { action = statetable[i+2]; theNextState = statetable[i+3]; } else if (statetable[i+1] == ch) { action = statetable[i+2]; theNextState = statetable[i+3]; break; } } // System.err.println("In " + debug_statenames[theState] + " got " + nicechar(ch) + " doing " + debug_actionnames[action] + " then " + debug_statenames[theNextState]); switch (action) { case 0: throw new Error( "HTMLScanner can't cope with " + Integer.toString(ch) + " in state " + Integer.toString(theState)); case A_ADUP: h.adup(theOutputBuffer, 0, theSize); theSize = 0; break; case A_ADUP_SAVE: h.adup(theOutputBuffer, 0, theSize); theSize = 0; save(ch, h); break; case A_ADUP_STAGC: h.adup(theOutputBuffer, 0, theSize); theSize = 0; h.stagc(theOutputBuffer, 0, theSize); break; case A_ANAME: h.aname(theOutputBuffer, 0, theSize); theSize = 0; break; case A_ANAME_ADUP: h.aname(theOutputBuffer, 0, theSize); theSize = 0; h.adup(theOutputBuffer, 0, theSize); break; case A_ANAME_ADUP_STAGC: h.aname(theOutputBuffer, 0, theSize); theSize = 0; h.adup(theOutputBuffer, 0, theSize); h.stagc(theOutputBuffer, 0, theSize); break; case A_AVAL: h.aval(theOutputBuffer, 0, theSize); theSize = 0; break; case A_AVAL_STAGC: h.aval(theOutputBuffer, 0, theSize); theSize = 0; h.stagc(theOutputBuffer, 0, theSize); break; case A_CDATA: mark(); // suppress the final "]]" in the buffer if (theSize > 1) theSize -= 2; h.pcdata(theOutputBuffer, 0, theSize); theSize = 0; break; case A_ENTITY_START: h.pcdata(theOutputBuffer, 0, theSize); theSize = 0; save(ch, h); break; case A_ENTITY: mark(); char ch1 = (char)ch; // System.out.println("Got " + ch1 + " in state " + ((theState == S_ENT) ? "S_ENT" : ((theState == S_NCR) ? "S_NCR" : "UNK"))); if (theState == S_ENT && ch1 == ' theNextState = S_NCR; save(ch, h); break; } else if (theState == S_NCR && (ch1 == 'x' || ch1 == 'X')) { theNextState = S_XNCR; save(ch, h); break; } else if (theState == S_ENT && Character.isLetterOrDigit(ch1)) { save(ch, h); break; } else if (theState == S_NCR && Character.isDigit(ch1)) { save(ch, h); break; } else if (theState == S_XNCR && (Character.isDigit(ch1) || "abcdefABCDEF".indexOf(ch1) != -1)) { save(ch, h); break; } // The whole entity reference has been collected // System.err.println("%%" + new String(theOutputBuffer, 0, theSize)); h.entity(theOutputBuffer, 1, theSize - 1); int ent = h.getEntity(); // System.err.println("%% value = " + ent); if (ent != 0) { theSize = 0; if (ent >= 0x80 && ent <= 0x9F) { ent = theWinMap[ent-0x80]; } if (ent < 0x20) { // Control becomes space ent = 0x20; } else if (ent >= 0xD800 && ent <= 0xDFFF) { // Surrogates get dropped ent = 0; } else if (ent <= 0xFFFF) { // BMP character save(ent, h); } else { // Astral converted to two surrogates ent -= 0x10000; save((ent>>10) + 0xD800, h); save((ent&0x3FF) + 0xDC00, h); } if (ch != ';') { unread(r, ch); theCurrentColumn } } else { unread(r, ch); theCurrentColumn } theNextState = S_PCDATA; break; case A_ETAG: h.etag(theOutputBuffer, 0, theSize); theSize = 0; break; case A_DECL: h.decl(theOutputBuffer, 0, theSize); theSize = 0; break; case A_GI: h.gi(theOutputBuffer, 0, theSize); theSize = 0; break; case A_GI_STAGC: h.gi(theOutputBuffer, 0, theSize); theSize = 0; h.stagc(theOutputBuffer, 0, theSize); break; case A_LT: mark(); save('<', h); save(ch, h); break; case A_LT_PCDATA: mark(); save('<', h); h.pcdata(theOutputBuffer, 0, theSize); theSize = 0; break; case A_PCDATA: mark(); h.pcdata(theOutputBuffer, 0, theSize); theSize = 0; break; case A_CMNT: mark(); h.cmnt(theOutputBuffer, 0, theSize); theSize = 0; break; case A_MINUS3: save('-', h); save(' ', h); break; case A_MINUS2: save('-', h); save(' ', h); // fall through into A_MINUS case A_MINUS: save('-', h); save(ch, h); break; case A_PI: mark(); h.pi(theOutputBuffer, 0, theSize); theSize = 0; break; case A_PITARGET: h.pitarget(theOutputBuffer, 0, theSize); theSize = 0; break; case A_PITARGET_PI: h.pitarget(theOutputBuffer, 0, theSize); theSize = 0; h.pi(theOutputBuffer, 0, theSize); break; case A_SAVE: save(ch, h); break; case A_SKIP: break; case A_SP: save(' ', h); break; case A_STAGC: h.stagc(theOutputBuffer, 0, theSize); theSize = 0; break; case A_EMPTYTAG: mark(); // System.err.println("%%% Empty tag seen"); if (theSize > 0) h.gi(theOutputBuffer, 0, theSize); theSize = 0; h.stage(theOutputBuffer, 0, theSize); break; case A_UNGET: unread(r, ch); theCurrentColumn break; case A_UNSAVE_PCDATA: if (theSize > 0) theSize h.pcdata(theOutputBuffer, 0, theSize); theSize = 0; break; default: throw new Error("Can't process state " + action); } theState = theNextState; } h.eof(theOutputBuffer, 0, 0); } /** * Mark the current scan position as a "point of interest" - start of a tag, * cdata, processing instruction etc. */ private void mark() { theLastColumn = theCurrentColumn; theLastLine = theCurrentLine; } /** A callback for the ScanHandler that allows it to force the lexer state to CDATA content (no markup is recognized except the end of element. */ public void startCDATA() { theNextState = S_CDATA; } private void save(int ch, ScanHandler h) throws IOException, SAXException { if (theSize >= theOutputBuffer.length - 20) { if (theState == S_PCDATA || theState == S_CDATA) { // Return a buffer-sized chunk of PCDATA h.pcdata(theOutputBuffer, 0, theSize); theSize = 0; } else { // Grow the buffer size char[] newOutputBuffer = new char[theOutputBuffer.length * 2]; System.arraycopy(theOutputBuffer, 0, newOutputBuffer, 0, theSize+1); theOutputBuffer = newOutputBuffer; } } theOutputBuffer[theSize++] = (char)ch; } /** Test procedure. Reads HTML from the standard input and writes PYX to the standard output. */ public static void main(String[] argv) throws IOException, SAXException { Scanner s = new HTMLScanner(); Reader r = new InputStreamReader(System.in, "UTF-8"); Writer w = new OutputStreamWriter(System.out, "UTF-8"); PYXWriter pw = new PYXWriter(w); s.scan(r, pw); w.close(); } private static String nicechar(int in) { if (in == '\n') return "\\n"; if (in < 32) return "0x"+Integer.toHexString(in); return "'"+((char)in)+"'"; } }
package com.chaincloud.chaincloudv.api; import com.chaincloud.chaincloudv.BuildConfig; import com.chaincloud.chaincloudv.GlobalParams; import com.chaincloud.chaincloudv.R; import com.chaincloud.chaincloudv.api.service.ChainCloudColdReceiveService; import com.chaincloud.chaincloudv.api.service.ChainCloudHotSendService; import com.chaincloud.chaincloudv.api.service.VWebService; import com.chaincloud.chaincloudv.api.type.DateTypeAdapter; import com.chaincloud.chaincloudv.util.Coin; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Date; import retrofit.RestAdapter; import retrofit.android.AndroidLog; import retrofit.converter.GsonConverter; public class Api { public enum ServerType { ChainCloudHotSend(0), ChainCloudColdReceive(2), VTest(3); private int value; ServerType(int value) { this.value = value; } public int value() { return value; } public int nameRes(){ switch (this){ case ChainCloudHotSend: return R.string.setting_network_hs_name; case ChainCloudColdReceive: return R.string.setting_network_cr_name; case VTest: return R.string.setting_network_vtest_name; } return R.string.setting_network_hs_name; } } public static final String ChainCloudHotSendDomain = "https://chaincloud-api.getcai.com"; public static final String ChainCloudColdReceiveDomain = "https://chaincloud-api.getcai.com"; public static final String ChainCloudHotSendAltDomain = "https://chaincloud-api-alt.getcai.com"; public static final String ChainCloudColdReceiveAltDomain = "https://chaincloud-api-alt.getcai.com"; public static final String ChainCloudHotSendApiRootPath = "/api/v1/"; public static final String ChainCloudColdReiceveApiRootPath = "/api/v1/"; public static final String ChainCloudHotSendAltApiRootPath = "/api/v1/"; public static final String ChainCloudColdReiceveAltApiRootPath = "/api/v1/"; public static final String ChainCloudHotSendApiEndpoint = ChainCloudHotSendDomain + ChainCloudHotSendApiRootPath; public static final String ChainCloudColdReceiveApiEndpoint = ChainCloudColdReceiveDomain + ChainCloudColdReiceveApiRootPath; public static final String ChainCloudHotSendAltApiEndpoint = ChainCloudHotSendAltDomain + ChainCloudHotSendAltApiRootPath; public static final String ChainCloudColdReceiveAltApiEndpoint = ChainCloudColdReceiveAltDomain + ChainCloudColdReiceveAltApiRootPath; // public static String VTestDomain; public static final String VTestApiRootPath = "/api/v1/"; // public static String VTestApiEndpoint; private static final String LogTag = "API"; private static final RestAdapter.LogLevel LogLevel = BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE; public static final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy .LOWER_CASE_WITH_UNDERSCORES).registerTypeAdapter(Date.class, new DateTypeAdapter()) .create(); public static ChainCloudHotSendService chainCloudHotSendService, chainCloudHotSendAltService; public static ChainCloudColdReceiveService chainCloudColdReceiveService, chainCloudColdReceiveAltService; public static VWebService vWebService; public static <T> T apiService(Class<T> service) { return apiServiceAlt(service, !GlobalParams.coinCode.equals(Coin.BTC.getCode())); } public static <T> T apiServiceAlt(Class<T> service, boolean isAlt) { if (service == VWebService.class){ return (T) vWebService; } if (!isAlt){ if (service == ChainCloudHotSendService.class){ if (chainCloudHotSendService == null){ chainCloudHotSendService = (ChainCloudHotSendService) constructService(service, isAlt); } return (T) chainCloudHotSendService; }else if (service == ChainCloudColdReceiveService.class){ if (chainCloudColdReceiveService == null){ chainCloudColdReceiveService = (ChainCloudColdReceiveService) constructService(service, isAlt); } return (T) chainCloudColdReceiveService; } }else { if (service == ChainCloudHotSendService.class){ if (chainCloudHotSendAltService == null){ chainCloudHotSendAltService = (ChainCloudHotSendService) constructService(service, isAlt); } return (T) chainCloudHotSendAltService; }else if (service == ChainCloudColdReceiveService.class){ if (chainCloudColdReceiveAltService == null){ chainCloudColdReceiveAltService = (ChainCloudColdReceiveService) constructService(service, isAlt); } return (T) chainCloudColdReceiveAltService; } } return null; } public static void setVWebDomain(String domain){ String VTestApiEndpoint = domain + VTestApiRootPath; RestAdapter adapter = getBaseBuilder() .setEndpoint(VTestApiEndpoint) .setRequestInterceptor(VWebApiInterceptor.instance()) .build(); vWebService = adapter.create(VWebService.class); } private static <T> T constructService(Class<T> service, boolean isAlt){ if (service == ChainCloudHotSendService.class){ RestAdapter adapter; if (!isAlt){ adapter = getBaseBuilder() .setEndpoint(ChainCloudHotSendApiEndpoint) .setRequestInterceptor(ChainCloudHotSendApiInterceptor.instance()) .build(); }else { adapter = getBaseBuilder() .setEndpoint(ChainCloudHotSendAltApiEndpoint) .setRequestInterceptor(ChainCloudHotSendAltApiInterceptor.instance()) .build(); } return adapter.create(service); }else if (service == ChainCloudColdReceiveService.class){ RestAdapter adapter; if (!isAlt){ adapter = getBaseBuilder() .setEndpoint(ChainCloudColdReceiveApiEndpoint) .setRequestInterceptor(ChainCloudColdReceiveApiInterceptor.instance()) .build(); }else { adapter = getBaseBuilder() .setEndpoint(ChainCloudColdReceiveAltApiEndpoint) .setRequestInterceptor(ChainCloudColdReceiveAltApiInterceptor.instance()) .build(); } return adapter.create(service); }else if (service == VWebService.class){ return (T) vWebService; }else { return null; } } private static RestAdapter.Builder getBaseBuilder(){ return new RestAdapter.Builder() .setLog(new AndroidLog(LogTag)) .setLogLevel(LogLevel) .setConverter(new GsonConverter(gson)) .setErrorHandler(ApiErrorHandler.instance()); } }
package ch.bind.philib.lang; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.CountDownLatch; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class ThreadUtilTest { @Test public void normal() throws Exception { RestartTestRunnable r = new RestartTestRunnable(false, false); Runnable wrapped = new ThreadUtil.ForeverRunner(r); wrapped.run(); assertEquals(r.numStarts, 1); } @Test public void exception() throws Exception { RestartTestRunnable r = new RestartTestRunnable(true, false); Runnable wrapped = new ThreadUtil.ForeverRunner(r); wrapped.run(); assertEquals(r.numStarts, 2); } @Test public void error() throws Exception { RestartTestRunnable r = new RestartTestRunnable(false, true); Runnable wrapped = new ThreadUtil.ForeverRunner(r); wrapped.run(); assertEquals(r.numStarts, 2); } @Test public void exceptionThenError() throws Exception { RestartTestRunnable r = new RestartTestRunnable(true, true); Runnable wrapped = new ThreadUtil.ForeverRunner(r); wrapped.run(); assertEquals(r.numStarts, 3); } @Test(timeOut = 1000) public void interruptAndJoinWontStopOnFirstInterrupt() throws Exception { final CountDownLatch started = new CountDownLatch(1); final CountDownLatch stopped = new CountDownLatch(1); Thread t = new Thread(new InterruptTestRunnable(started, stopped, 1)); t.start(); started.await(); // give the other thread some time to enter sleep Thread.sleep(50); assertFalse(ThreadUtil.interruptAndJoin(t, 50)); assertTrue(ThreadUtil.interruptAndJoin(t, 50)); // the thread is no longer alive, successive calls must always return true assertFalse(t.isAlive()); for (int i = 0; i < 10; i++) { assertTrue(ThreadUtil.interruptAndJoin(t)); } } @Test public void interruptAndJoinTrueOnNull() throws Exception { assertTrue(ThreadUtil.interruptAndJoin(null)); assertTrue(ThreadUtil.interruptAndJoin(null, 100)); } @Test public void interruptAndJoinThreadsTrueOnNull() throws Exception { assertTrue(ThreadUtil.interruptAndJoinThreads((Thread[]) null)); assertTrue(ThreadUtil.interruptAndJoinThreads((Thread[]) null, 100)); assertTrue(ThreadUtil.interruptAndJoinThreads((Collection<Thread>) null)); assertTrue(ThreadUtil.interruptAndJoinThreads((Collection<Thread>) null, 100)); } @Test public void interruptAndJoinThreads() throws Exception { final int N = 10; final CountDownLatch started = new CountDownLatch(N); final CountDownLatch stopped = new CountDownLatch(N); List<Thread> ts = new ArrayList<>(); for (int i = 0; i < N; i++) { Thread t = new Thread(new InterruptTestRunnable(started, stopped, 1)); ts.add(t); } ThreadUtil.startThreads(ts); started.await(); // give the other threads some time to enter sleep Thread.sleep(50); assertFalse(ThreadUtil.interruptAndJoinThreads(ts, 25)); assertTrue(ThreadUtil.interruptAndJoinThreads(ts, 25)); for (Thread t : ts) { assertFalse(t.isAlive()); } } private static final class InterruptTestRunnable implements Runnable { private final CountDownLatch started; private final CountDownLatch stopped; private final int numIgnoreInterrupt; public InterruptTestRunnable(CountDownLatch started, CountDownLatch stopped, int numIgnoreInterrupt) { this.started = started; this.stopped = stopped; this.numIgnoreInterrupt = numIgnoreInterrupt; } @Override public void run() { started.countDown(); int ignoredInterrupts = 0; while (true) { try { Thread.sleep(100000); } catch (InterruptedException e) { if (ignoredInterrupts >= numIgnoreInterrupt) { break; } ignoredInterrupts++; } } stopped.countDown(); } } private static final class RestartTestRunnable implements Runnable { private boolean throwException; private boolean throwError; private int numStarts; RestartTestRunnable(boolean throwException, boolean throwError) { this.throwException = throwException; this.throwError = throwError; } @Override public void run() { numStarts++; if (throwException) { throwException = false; // forever-runner must restart this runnable throw new RuntimeException(); } if (throwError) { throwError = false; // forever-runner must not restart this runnable throw new Error(); } } } @Test public void sleepUntilMsIntoThePast() throws InterruptedException { // 1000 times no sleep at all long tStart = System.nanoTime(); for (int i = 0; i < 1000; i++) { long tms = System.currentTimeMillis(); ThreadUtil.sleepUntilMs(tms - 10); // noop } long elapsed = (System.nanoTime() - tStart); // this should finish within a few hundred microseconds // but that would make the test very flaky due to os-specific scheduling assertTrue(elapsed < 25_000_1000); // 25ms } @Test public void sleepUntilRegular() throws InterruptedException { long start = System.currentTimeMillis(); for (int i = 1; i <= 100; i++) { ThreadUtil.sleepUntilMs(start + i); } long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed >= 100); // this is probably also flaky as hell due to different scheduling behaviour of different platforms. lets see how well it does. assertTrue(elapsed <= 125); } }
package com.sdicons.json.mapper; import com.sdicons.json.model.JSONValue; import junit.framework.Assert; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import java.util.Vector; public class MapperTest extends TestCase { public static class TestBean { private Boolean booleanMbr; private String stringMbr; private Integer integerMbr; private int intMbr; private Short shortMbr; private Byte byteMbr; private Long longMbr; private Float floatMbr; private Double doubleMbr; private BigInteger bigIntMbr; private BigDecimal bigDecimalMbr; private Character charMbr; private Date date; private Boolean true1; private Boolean true2; private Boolean true3; private Boolean false1; private Boolean false2; private Boolean false3; private LinkedList<String> linkedList; private ArrayList<Date> arrayList; private LinkedHashMap<String, Date> linkedMap; public Integer getIntegerMbr() { return integerMbr; } public void setIntegerMbr(Integer integerMbr) { this.integerMbr = integerMbr; } public Short getShortMbr() { return shortMbr; } public void setShortMbr(Short shortMbr) { this.shortMbr = shortMbr; } public String getStringMbr() { return stringMbr; } public void setStringMbr(String stringMbr) { this.stringMbr = stringMbr; } public Boolean getBooleanMbr() { return booleanMbr; } public void setBooleanMbr(Boolean booleanMbr) { this.booleanMbr = booleanMbr; } public Byte getByteMbr() { return byteMbr; } public void setByteMbr(Byte byteMbr) { this.byteMbr = byteMbr; } public long getLongMbr() { return longMbr; } public void setLongMbr(Long longMbr) { this.longMbr = longMbr; } public Double getDoubleMbr() { return doubleMbr; } public void setDoubleMbr(Double doubleMbr) { this.doubleMbr = doubleMbr; } public Float getFloatMbr() { return floatMbr; } public void setFloatMbr(Float floatMbr) { this.floatMbr = floatMbr; } public BigDecimal getBigDecimalMbr() { return bigDecimalMbr; } public void setBigDecimalMbr(BigDecimal bigDecimalMbr) { this.bigDecimalMbr = bigDecimalMbr; } public BigInteger getBigIntMbr() { return bigIntMbr; } public void setBigIntMbr(BigInteger bigIntMbr) { this.bigIntMbr = bigIntMbr; } public Character getCharMbr() { return charMbr; } public void setCharMbr(Character charMbr) { this.charMbr = charMbr; } public int getIntMbr() { return intMbr; } public void setIntMbr(int intMbr) { this.intMbr = intMbr; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public ArrayList<Date> getArrayList() { return arrayList; } public void setArrayList(ArrayList<Date> lArrayList) { this.arrayList = lArrayList; } public LinkedList<String> getLinkedList() { return linkedList; } public void setLinkedList(LinkedList<String> lLinkedList) { this.linkedList = lLinkedList; } public LinkedHashMap<String, Date> getLinkedMap() { return linkedMap; } public void setLinkedMap(LinkedHashMap<String, Date> linkedMap) { this.linkedMap = linkedMap; } public Boolean getFalse1() { return false1; } public void setFalse1(Boolean false1) { this.false1 = false1; } public Boolean getFalse2() { return false2; } public void setFalse2(Boolean false2) { this.false2 = false2; } public Boolean getFalse3() { return false3; } public void setFalse3(Boolean false3) { this.false3 = false3; } public Boolean getTrue1() { return true1; } public void setTrue1(Boolean true1) { this.true1 = true1; } public Boolean getTrue2() { return true2; } public void setTrue2(Boolean true2) { this.true2 = true2; } public Boolean getTrue3() { return true3; } public void setTrue3(Boolean true3) { this.true3 = true3; } } public MapperTest(String lName) { super(lName); } public void testIt() { try { MapperTest.TestBean lDuupje = new MapperTest.TestBean(); lDuupje.setIntegerMbr(new Integer(13)); lDuupje.setIntMbr(17); lDuupje.setShortMbr(new Short((short) 17)); lDuupje.setStringMbr("It is not fair!"); lDuupje.setBooleanMbr(true); lDuupje.setByteMbr((byte) 32); lDuupje.setLongMbr(12345l); lDuupje.setFloatMbr(123.12f); lDuupje.setDoubleMbr(987.89); lDuupje.setBigIntMbr(new BigInteger("123654789555")); lDuupje.setBigDecimalMbr(new BigDecimal("1111111465465.676476545")); lDuupje.setCharMbr('A'); lDuupje.setDate(new Date()); Boolean trueBoolean=new Boolean(true); Boolean falseBoolean=new Boolean(false); lDuupje.setTrue1(trueBoolean); lDuupje.setTrue2(trueBoolean); lDuupje.setTrue3(trueBoolean); lDuupje.setFalse1(falseBoolean); lDuupje.setFalse2(falseBoolean); lDuupje.setFalse3(falseBoolean); LinkedList lLinkedList = new LinkedList(); lLinkedList.add("uno"); lLinkedList.add("duo"); lDuupje.setLinkedList(lLinkedList); ArrayList<Date> lArrayList = new ArrayList<Date>(); lArrayList.add(new Date()); lArrayList.add(new Date()); lDuupje.setArrayList(lArrayList); LinkedHashMap<String, Date> lMap = new LinkedHashMap<String, Date>(); lMap.put("uno", new Date()); lMap.put("duo", new Date()); lDuupje.setLinkedMap(lMap); JSONValue lObj = JSONMapper.toJSON(lDuupje); System.out.println(lObj.render(true)); MapperTest.TestBean lLitmus = (MapperTest.TestBean) JSONMapper.toJava(lObj, TestBean.class); Assert.assertNotNull(lLitmus); } catch(Exception e) { e.printStackTrace(System.out); Assert.fail(); } } public static class Graph{ private HashMap<String, ArrayList<Integer>> nodes; private ArrayList edges; private Collection<HashMap<String,String>> col; public ArrayList getEdges() { return edges; } public void setEdges(ArrayList edges) { this.edges = edges; } public HashMap<String, ArrayList<Integer>> getNodes() { return nodes; } public void setNodes(HashMap<String, ArrayList<Integer>> nodes) { this.nodes = nodes; } public Collection<HashMap<String, String>> getCol() { return col; } public void setCol(Collection<HashMap<String, String>> col) { this.col = col; } } public void test2(){ HashMap<String, ArrayList<Integer>> nodes = new HashMap<String, ArrayList<Integer>>(); ArrayList<Integer> nodeInfo = new ArrayList<Integer>(); nodeInfo.add(new Integer(270)); nodeInfo.add(new Integer(360)); nodes.put("uniqueNodeId1", nodeInfo); Collection<HashMap<String,String>> collection=new Vector<HashMap<String,String>>(); HashMap<String,String> hashMap=new HashMap<String, String>(); hashMap.put("index1","value1"); collection.add(hashMap); Graph graph = new Graph(); graph.setNodes(nodes); graph.setEdges(new ArrayList()); graph.setCol(collection); JSONValue lObj = null; try { lObj = JSONMapper.toJSON(graph); } catch (MapperException e) { e.printStackTrace(); } System.out.println(lObj.render(true)); // works Object javaObj = null; try { javaObj = JSONMapper.toJava(lObj, graph.getClass()); Graph graph2=(Graph)javaObj; HashMap<String, ArrayList<Integer>> nodes2=graph2.getNodes(); ArrayList<Integer> nodeInfo2=nodes2.get("uniqueNodeId1"); Iterator<Integer> iterator=nodeInfo2.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } catch (Exception e) { e.printStackTrace(); } System.out.println(javaObj); } public void test3(){ String[] strings={"abc","bcd","def"}; System.out.println("String[] class:"+strings.getClass()); JSONValue lObj = null; try { lObj = JSONMapper.toJSON(strings); }catch (MapperException e) { e.printStackTrace(); } System.out.println(lObj.render(true)); Object javaObj = null; try { javaObj = JSONMapper.toJava(lObj, strings.getClass()); String[] strings2=(String[])javaObj; System.out.println(strings2[0]+strings2[1]+strings2[2]); } catch (Exception e) { e.printStackTrace(); } } public static class TestBean4 { private String myString; public TestBean4(){ this.myString=""; } public TestBean4(String myString) { super(); this.myString = myString; } public String getMyString() { return myString; } public void setMyString(String myString) { this.myString = myString; } } public void test4(){ TestBean4[] bean4s={new TestBean4("abc"),new TestBean4("bcd"),new TestBean4("def")}; JSONValue lObj = null; try { lObj = JSONMapper.toJSON(bean4s); }catch (MapperException e) { e.printStackTrace(); } System.out.println(lObj.render(true)); Object javaObj = null; try { javaObj = JSONMapper.toJava(lObj, bean4s.getClass()); TestBean4[] beans=(TestBean4[])javaObj; System.out.println(beans[0].getMyString()+beans[1].getMyString()+beans[2].getMyString()); } catch (Exception e) { e.printStackTrace(); } } public void test5(){ String[][] strings={{"abc","bcd","def"},{"abc","bcd","def"}}; System.out.println("String[] class:"+strings.getClass()); JSONValue lObj = null; try { lObj = JSONMapper.toJSON(strings); }catch (MapperException e) { e.printStackTrace(); } System.out.println(lObj.render(true)); Object javaObj = null; try { javaObj = JSONMapper.toJava(lObj, strings.getClass()); String[][] strings2=(String[][])javaObj; System.out.println(strings2[0][0]+strings2[0][1]+strings2[0][2]); } catch (Exception e) { e.printStackTrace(); } } public static class SetAndListBean{ private Set<String> stringSet; private List<String> stringList; public List<String> getStringList() { return stringList; } public void setStringList(List<String> stringList) { this.stringList = stringList; } public Set<String> getStringSet() { return stringSet; } public void setStringSet(Set<String> stringSet) { this.stringSet = stringSet; } } public void testSetAndList(){ SetAndListBean setAndListBean=new SetAndListBean(); Set<String> stringSet=new HashSet<String>(); stringSet.add("abc"); stringSet.add("bcd"); List<String> stringList=new Vector<String>(); stringList.add("abc"); stringList.add("bcd"); setAndListBean.setStringSet(stringSet); setAndListBean.setStringList(stringList); try{ JSONValue jsonValue=JSONMapper.toJSON(setAndListBean); System.out.println(jsonValue.render(true)); Object object=JSONMapper.toJava(jsonValue,setAndListBean.getClass()); SetAndListBean setAndListBean2=(SetAndListBean)object; Iterator<String> iterator=setAndListBean2.getStringList().iterator(); System.out.println(iterator.next()); System.out.println(iterator.next()); iterator=setAndListBean2.getStringSet().iterator(); System.out.println(iterator.next()); System.out.println(iterator.next()); }catch(Exception e){ e.printStackTrace(); } } }
package brooklyn.util.text; import static org.testng.Assert.*; import org.testng.annotations.Test; import brooklyn.util.MutableMap; @Test public class StringsTest { public void isBlankOrEmpty() { assertTrue(Strings.isEmpty(null)); assertTrue(Strings.isEmpty("")); assertFalse(Strings.isEmpty(" \t ")); assertFalse(Strings.isEmpty("abc")); assertFalse(Strings.isEmpty(" abc ")); assertFalse(Strings.isNonEmpty(null)); assertFalse(Strings.isNonEmpty("")); assertTrue(Strings.isNonEmpty(" \t ")); assertTrue(Strings.isNonEmpty("abc")); assertTrue(Strings.isNonEmpty(" abc ")); assertTrue(Strings.isBlank(null)); assertTrue(Strings.isBlank("")); assertTrue(Strings.isBlank(" \t ")); assertFalse(Strings.isBlank("abc")); assertFalse(Strings.isBlank(" abc ")); assertFalse(Strings.isNonBlank(null)); assertFalse(Strings.isNonBlank("")); assertFalse(Strings.isNonBlank(" \t ")); assertTrue(Strings.isNonBlank("abc")); assertTrue(Strings.isNonBlank(" abc ")); } public void testMakeValidFilename() { assertEquals("abcdef", Strings.makeValidFilename("abcdef")); assertEquals("abc_def", Strings.makeValidFilename("abc$$$def")); assertEquals("abc_def", Strings.makeValidFilename("$$$abc$$$def$$$")); assertEquals("a_b_c", Strings.makeValidFilename("a b c")); assertEquals("a.b.c", Strings.makeValidFilename("a.b.c")); } @Test(expectedExceptions = { NullPointerException.class }) public void testMakeValidFilenameNull() { Strings.makeValidFilename(null); } @Test(expectedExceptions = { IllegalArgumentException.class }) public void testMakeValidFilenameEmpty() { Strings.makeValidFilename(""); } @Test(expectedExceptions = { IllegalArgumentException.class }) public void testMakeValidFilenameBlank() { Strings.makeValidFilename(" \t "); } public void makeValidJavaName() { assertEquals("__null", Strings.makeValidJavaName(null)); assertEquals("__empty", Strings.makeValidJavaName("")); assertEquals("abcdef", Strings.makeValidJavaName("abcdef")); assertEquals("abcdef", Strings.makeValidJavaName("a'b'c'd'e'f")); assertEquals("_12345", Strings.makeValidJavaName("12345")); } public void makeValidUniqueJavaName() { assertEquals("__null", Strings.makeValidUniqueJavaName(null)); assertEquals("__empty", Strings.makeValidUniqueJavaName("")); assertEquals("abcdef", Strings.makeValidUniqueJavaName("abcdef")); assertEquals("_12345", Strings.makeValidUniqueJavaName("12345")); } public void testRemoveFromEnd() { assertEquals("", Strings.removeFromEnd("", "bar")); assertEquals(null, Strings.removeFromEnd(null, "bar")); assertEquals("foo", Strings.removeFromEnd("foobar", "bar")); assertEquals("foo", Strings.removeFromEnd("foo", "bar")); assertEquals("foo", Strings.removeFromEnd("foobar", "foo", "bar")); // test they are applied in order assertEquals("foob", Strings.removeFromEnd("foobar", "ar", "bar", "b")); } public void testRemoveAllFromEnd() { assertEquals("", Strings.removeAllFromEnd("", "bar")); assertEquals(null, Strings.removeAllFromEnd(null, "bar")); assertEquals("", Strings.removeAllFromEnd("foobar", "foo", "bar")); assertEquals("f", Strings.removeAllFromEnd("foobar", "ar", "car", "b", "o")); // test they are applied in order assertEquals("foo", Strings.removeAllFromEnd("foobar", "ar", "car", "b", "ob")); assertEquals("foobar", Strings.removeAllFromEnd("foobar", "zz", "x")); } public void testRemoveFromStart() { assertEquals("", Strings.removeFromStart("", "foo")); assertEquals(null, Strings.removeFromStart(null, "foo")); assertEquals("bar", Strings.removeFromStart("foobar", "foo")); assertEquals("foo", Strings.removeFromStart("foo", "bar")); assertEquals("bar", Strings.removeFromStart("foobar", "foo", "bar")); assertEquals("obar", Strings.removeFromStart("foobar", "ob", "fo", "foo", "o")); } public void testRemoveAllFromStart() { assertEquals("", Strings.removeAllFromStart("", "foo")); assertEquals(null, Strings.removeAllFromStart(null, "foo")); assertEquals("bar", Strings.removeAllFromStart("foobar", "foo")); assertEquals("foo", Strings.removeAllFromStart("foo", "bar")); assertEquals("", Strings.removeAllFromStart("foobar", "foo", "bar")); assertEquals("ar", Strings.removeAllFromStart("foobar", "fo", "ob", "o")); assertEquals("ar", Strings.removeAllFromStart("foobar", "ob", "fo", "o")); // test they are applied in order, "ob" doesn't match because "o" eats the o assertEquals("bar", Strings.removeAllFromStart("foobar", "o", "fo", "ob")); } public void testRemoveFromStart2() { assertEquals(Strings.removeFromStart("xyz", "x"), "yz"); assertEquals(Strings.removeFromStart("xyz", "."), "xyz"); assertEquals(Strings.removeFromStart("http: } public void testRemoveFromEnd2() { assertEquals(Strings.removeFromEnd("xyz", "z"), "xy"); assertEquals(Strings.removeFromEnd("xyz", "."), "xyz"); assertEquals(Strings.removeFromEnd("http: } public void testReplaceAll() { assertEquals(Strings.replaceAll("xyz", "x", ""), "yz"); assertEquals(Strings.replaceAll("xyz", ".", ""), "xyz"); assertEquals(Strings.replaceAll("http://foo.com/", "/", ""), "http:foo.com"); assertEquals(Strings.replaceAll("http: } public void testReplaceAllNonRegex() { assertEquals(Strings.replaceAllNonRegex("xyz", "x", ""), "yz"); assertEquals(Strings.replaceAllNonRegex("xyz", ".", ""), "xyz"); assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "/", ""), "http:foo.com"); assertEquals(Strings.replaceAllNonRegex("http: } public void testReplaceAllRegex() { assertEquals(Strings.replaceAllRegex("xyz", "x", ""), "yz"); assertEquals(Strings.replaceAllRegex("xyz", ".", ""), ""); assertEquals(Strings.replaceAllRegex("http://foo.com/", "/", ""), "http:foo.com"); assertEquals(Strings.replaceAllRegex("http: } public void testReplaceMap() { assertEquals(Strings.replaceAll("xyz", MutableMap.builder().put("x","a").put("y","").build()), "az"); } public void testContainsLiteral() { assertTrue(Strings.containsLiteral("hello", "ell")); assertTrue(Strings.containsLiteral("hello", "h")); assertFalse(Strings.containsLiteral("hello", "H")); assertFalse(Strings.containsLiteral("hello", "O")); assertFalse(Strings.containsLiteral("hello", "x")); assertFalse(Strings.containsLiteral("hello", "ELL")); assertTrue(Strings.containsLiteral("hello", "hello")); assertTrue(Strings.containsLiteral("hELlo", "ELl")); assertFalse(Strings.containsLiteral("hello", "!")); } public void testContainsLiteralIgnoreCase() { assertTrue(Strings.containsLiteralIgnoreCase("hello", "ell")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "H")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "O")); assertFalse(Strings.containsLiteralIgnoreCase("hello", "X")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "ELL")); assertTrue(Strings.containsLiteralIgnoreCase("hello", "hello")); assertTrue(Strings.containsLiteralIgnoreCase("hELlo", "Hello")); assertFalse(Strings.containsLiteralIgnoreCase("hello", "!")); } public void testSizeString() { assertEquals(Strings.makeSizeString(0), "0b"); assertEquals(Strings.makeSizeString(999), "999b"); assertEquals(Strings.makeSizeString(1234), "1.23kb"); assertEquals(Strings.makeSizeString(23456789), "23.5mb"); assertEquals(Strings.makeSizeString(23456789012L), "23.5gb"); assertEquals(Strings.makeSizeString(23456789012345L), "2.35E4gb"); } }
package com.seleniumtests.tests; import static com.seleniumtests.core.CustomAssertion.*; import com.seleniumtests.core.SeleniumTestPlan; import static org.hamcrest.CoreMatchers.*; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.testng.annotations.Test; /** * Using Matchers */ public class RetryTest2 extends SeleniumTestPlan { /** * Will not retry as test would never fail */ @Test(groups="retryTest2", description = "Will retry failed assertions in this test") public void retryFailedTest() { assertThat("1 is always equal to 1", 1==1); // This won't fail assertThat("1 can not be equal to 2", 1, is(2)); assertThat("2 is always equal to 2", 2, equalTo(2)); // This won't fail assertThat("2 is always equal to 2", 2, is(equalTo(2))); // Same as previous statement assertThat("2 can not be equal to 3", 2, is(3)); MatcherAssert.assertThat("Hello", allOf(equalTo("Hello1"), equalTo("Hello"))); } }
package fm.audiobox.tests.models; import com.google.api.client.http.apache.ApacheHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.integralblue.httpresponsecache.HttpResponseCache; import fm.audiobox.core.Client; import fm.audiobox.core.config.Configuration; import fm.audiobox.core.exceptions.AudioBoxException; import fm.audiobox.core.models.*; import fm.audiobox.core.utils.ModelUtil; import fm.audiobox.tests.AudioBoxTests; import fm.audiobox.tests.mocks.AudioBoxMockHttpTransportFactory; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import javax.naming.ConfigurationException; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import static org.junit.Assert.*; public class UserTests extends AudioBoxTests { @Before public void setUp() { super.setUp(); try { final long httpCacheSize = 10 * 1024 * 1024; // 10 MiB final File httpCacheDir = CACHE_DIR; HttpResponseCache.install( httpCacheDir, httpCacheSize ); Configuration config = new Configuration( Configuration.Env.development ); config.setDataStoreFactory( new FileDataStoreFactory( DATA_STORE_DIR ) ); config.setApiKey( fixtures.getString( "authentication.client_id" ) ); config.setApiSecret( fixtures.getString( "authentication.client_secret" ) ); config.setHttpTransport( new NetHttpTransport() ); JacksonFactory jf = new JacksonFactory(); config.setJsonFactory( jf ); c = new Client( config ); } catch ( IOException | ConfigurationException e ) { fail( e.getMessage() ); } } /** * Test all user keys are well parsed. * * @throws AudioBoxException the audio box exception * @throws ParseException the parse exception */ @Test public void testAllUserKeysAreWellParsed() throws AudioBoxException, ParseException { c.getConf().setHttpTransport( AudioBoxMockHttpTransportFactory.getRightUserHttpTransport() ); User user = c.getUser(); assertNotNull( user ); assertEquals( 3, user.getId() ); assertEquals( "2013-08-29T18:25:52.079Z", user.getCreatedAt() ); long millisCreated = ModelUtil.toUnixTime( new SimpleDateFormat( ModelUtil.AUDIOBOX_DATE_FORMAT ), user.getCreatedAt() ); assertEquals( 1377800752079L, millisCreated ); assertEquals( "2014-01-21T21:48:58.850Z", user.getUpdatedAt() ); long millisUpdated = ModelUtil.toUnixTime( new SimpleDateFormat( ModelUtil.AUDIOBOX_DATE_FORMAT ), user.getUpdatedAt() ); assertEquals( 1390340938850L, millisUpdated ); assertEquals( "Real Name", user.getRealName() ); assertEquals( "test@test.com", user.getEmail() ); assertEquals( "4u770k3n", user.getAuthToken() ); assertEquals( 60, user.getMediaFilesCount() ); assertEquals( 13, user.getPlaylistsCount() ); assertEquals( 5, user.getTotalPlayCount() ); assertEquals( StringUtils.EMPTY, user.getCountry() ); assertEquals( "UTC", user.getTimeZone() ); assertEquals( "aac,mp3,m4a,flac,mp4,flv,webm", user.getAcceptedExtensions() ); assertEquals( "audio/aac,audio/mpeg,audio/mp4,audio/flac,video/mp4,video/x-flv,video/webm", user.getAcceptedFormats() ); assertEquals( "private-abc", user.getCometChannel() ); assertEquals( "active", user.getSubscriptionState() ); assertEquals( "audiobox_50", user.getPlan() ); assertEquals( "000_offline", user.getOfflinePlaylist() ); Permissions perms = user.getPermissions(); assertNotNull( perms ); assertTrue( perms.hasPlayer() ); assertTrue( perms.hasLocal() ); assertTrue( perms.hasCloud() ); assertTrue( perms.hasDropbox() ); assertTrue( perms.hasGdrive() ); assertTrue( perms.hasSkydrive() ); assertTrue( perms.hasUbuntu() ); assertTrue( perms.hasBox() ); assertTrue( perms.hasSoundcloud() ); assertTrue( perms.hasYoutube() ); assertTrue( perms.hasLastfm() ); assertTrue( perms.hasTwitchtv() ); assertTrue( perms.hasFacebook() ); assertTrue( perms.hasTwitter() ); assertTrue( perms.hasLyrics() ); assertTrue( perms.hasSongkick() ); ExternalTokens tks = user.getExternalTokens(); assertNotNull( tks ); assertFalse( tks.isDropboxEnabled() ); assertTrue( tks.isGdriveEnabled() ); assertTrue( tks.isSkydriveEnabled() ); assertFalse( tks.isUbuntuEnabled() ); assertFalse( tks.isSoundcloudEnabled() ); assertTrue( tks.isYoutubeEnabled() ); assertTrue( tks.isBoxEnabled() ); assertFalse( tks.isLastfmEnabled() ); assertFalse( tks.isTwitchtvEnabled() ); assertFalse( tks.isFacebookEnabled() ); assertFalse( tks.isTwitterEnabled() ); Stats stats = user.getStats(); assertNotNull( stats ); assertEquals( 5, stats.getTotalPlayCount() ); assertEquals( 777662290, stats.getDataServedOverall() ); assertEquals( 777662290, stats.getDataServedThisMonth() ); assertEquals( 5533908, stats.getBoxDataStoredOverall() ); assertEquals( 0, stats.getCloudDataStoredOverall() ); assertEquals( 0, stats.getLocalDataStoredOverall() ); assertEquals( 5533908, stats.getBoxDataStoredThisMonth() ); assertEquals( 170368034, stats.getGdriveDataStoredOverall() ); assertEquals( 0, stats.getUbuntuDataStoredOverall() ); assertEquals( 110981727, stats.getDropboxDataStoredOverall() ); assertEquals( 1500, stats.getYoutubeDataStoredOverall() ); assertEquals( 2175615, stats.getCloudDataStoredThisMonth() ); assertEquals( 0, stats.getLocalDataStoredThisMonth() ); assertEquals( 95088577, stats.getSkydriveDataStoredOverall() ); assertEquals( 170368034, stats.getGdriveDataStoredThisMonth() ); assertEquals( 0, stats.getUbuntuDataStoredThisMonth() ); assertEquals( 110981727, stats.getDropboxDataStoredThisMonth() ); assertEquals( 0, stats.getSoundcloudDataStoredOverall() ); assertEquals( 1500, stats.getYoutubeDataStoredThisMonth() ); assertEquals( 95088577, stats.getSkydriveDataStoredThisMonth() ); assertEquals( 0, stats.getSoundcloudDataStoredThisMonth() ); Preferences prefs = user.getPreferences(); assertNotNull( prefs ); assertEquals( "audiobox-fm-blue", prefs.getColor() ); assertTrue( prefs.isRepeatEnabled() ); assertFalse( prefs.isShuffleEnabled() ); assertFalse( prefs.isAutoplayEnabled() ); assertTrue( prefs.isPrebufferEnabled() ); assertFalse( prefs.isJsDemuxerEnabled() ); assertEquals( "default", prefs.getTopBarBg() ); assertEquals( "50", prefs.getVolumeLevel() ); assertTrue( prefs.doesAcceptsEmails() ); assertFalse( prefs.areTooltipsHidden() ); } /** * Test user update. * * @throws AudioBoxException the audio box exception */ @Test public void testUserUpdate() throws IOException { c.getConf().setHttpTransport( AudioBoxMockHttpTransportFactory.getRightUserHttpTransport() ); User u = c.getUser(); assertNotNull( u ); assertNotNull( u.getPreferences() ); u.getPreferences().setVolumeLevel( "100" ); c.getConf().setHttpTransport( AudioBoxMockHttpTransportFactory.getTwoOFourHttpTransport() ); assertNotNull( u.savePreferences( c ) ); } }
package org.pocketcampus.plugin.positioning; import org.pocketcampus.plugin.positioning.utils.Matrix; import org.pocketcampus.shared.plugin.map.Position; public class Taylor { //private Cercle c1_,c2_,c3_,c4_; private AccessPoint ap1_,ap2_,ap3_,ap4_; private double D1_,D2_,D3_,D4_; private Matrix matrix_; private Matrix vetcor_; private Position position_; public Taylor (AccessPoint ap1,AccessPoint ap2,AccessPoint ap3,AccessPoint ap4){ this.ap1_ = ap1; this.ap2_ = ap2; this.ap3_ = ap3; this.ap4_ = ap4; this.matrix_ = matrixA(ap1_,ap2_,ap3_,ap4_); this.vetcor_ = matrixB(ap1_,ap2_,ap3_,ap4_); this.position_ = taylorEquation(); } private Matrix matrixB(AccessPoint ap1,AccessPoint ap2,AccessPoint ap3,AccessPoint ap4) { double b1,b2,b3; double x1,x2,x3,x4; double y1,y2,y3,y4; double D1,D2,D3,D4; x1 = ap1.position().getLatitude(); x2 = ap2.position().getLatitude(); x3 = ap3.position().getLatitude(); x4 = ap4.position().getLatitude(); y1 = ap1.position().getLongitude(); y2 = ap2.position().getLongitude(); y3 = ap3.position().getLongitude(); y4 = ap4.position().getLongitude(); D1 = ap1.getDistance(); D2 = ap2.getDistance(); D3 = ap3.getDistance(); D4 = ap4.getDistance(); return null; } private Matrix matrixA(AccessPoint ap1,AccessPoint ap2,AccessPoint ap3,AccessPoint ap4) { Matrix matrix; double arrayA[][]; double a1,a2; double b1,b2; double c1,c2; double x1,x2,x3,x4; double y1,y2,y3,y4; x1 = ap1.position().getLatitude(); x2 = ap2.position().getLatitude(); x3 = ap3.position().getLatitude(); x4 = ap4.position().getLatitude(); y1 = ap1.position().getLongitude(); y2 = ap2.position().getLongitude(); y3 = ap3.position().getLongitude(); y4 = ap4.position().getLongitude(); a1 = x1-x2; a2 = y1-y2; b1 = x1-x3; b2 = y1-y3; c1 = x1-x4; c2 = y1-y4; arrayA = new double[3][2]; matrix = new Matrix(arrayA); return null; } private Position taylorEquation() { return null; } }
package guitests.guihandles; import java.util.List; import java.util.stream.Collectors; import guitests.GuiRobot; import javafx.scene.Node; import javafx.scene.control.Labeled; import javafx.scene.layout.Region; import javafx.stage.Stage; import seedu.address.model.tag.UniqueTagList; import seedu.address.model.task.ReadOnlyTask; /** * Provides a handle to a task card in the task list panel. */ public class TaskCardHandle extends GuiHandle { private static final String NAME_FIELD_ID = "#name"; private static final String DEADLINE_FIELD_ID = "#deadline"; private static final String DESCRIPTION_FIELD_ID = "#description"; private static final String ID_FIELD_ID = " private static final String TAGS_FIELD_ID = "#tags"; private Node node; public TaskCardHandle(GuiRobot guiRobot, Stage primaryStage, Node node) { super(guiRobot, primaryStage, null); this.node = node; } protected String getTextFromLabel(String fieldId) { return getTextFromLabel(fieldId, node); } public String getName() { return getTextFromLabel(NAME_FIELD_ID); } public String getDeadline() { return getTextFromLabel(DEADLINE_FIELD_ID); } public String getDescription() { return getTextFromLabel(DESCRIPTION_FIELD_ID); } public String getID() { return getTextFromLabel(ID_FIELD_ID); } public List<String> getTags() { return getTags(getTagsContainer()); } private List<String> getTags(Region tagsContainer) { return tagsContainer .getChildrenUnmodifiable() .stream() .map(node -> ((Labeled) node).getText()) .collect(Collectors.toList()); } private List<String> getTags(UniqueTagList tags) { return tags .asObservableList() .stream() .map(tag -> tag.tagName) .collect(Collectors.toList()); } private Region getTagsContainer() { return guiRobot.from(node).lookup(TAGS_FIELD_ID).query(); } public boolean isSameTask(ReadOnlyTask task) { return getName().equals(task.getName().toString()) && getDeadline().equals(task.getDeadline().toString()) && getDescription().equals(task.getDescription().toString()) && getID().equals(task.getID().toString()) && getTags().equals(getTags(task.getTags())); } @Override public boolean equals(Object obj) { if (obj instanceof TaskCardHandle) { TaskCardHandle handle = (TaskCardHandle) obj; return getName().equals(handle.getName()) && getDeadline().equals(handle.getDeadline()) && getDescription().equals(handle.getDescription()) && getID().equals(handle.getID()) && getTags().equals(handle.getTags()); } return super.equals(obj); } @Override public String toString() { return getName() + " " + getID(); } }
package io.redlink.sdk; import com.google.code.tempusfugit.concurrency.ConcurrentRule; import com.google.code.tempusfugit.concurrency.RepeatingRule; import com.google.code.tempusfugit.concurrency.annotations.Concurrent; import com.google.code.tempusfugit.concurrency.annotations.Repeating; import org.apache.commons.lang3.RandomStringUtils; import org.junit.*; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.openrdf.model.*; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.TreeModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.rio.RDFHandlerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.MalformedURLException; import java.util.*; /** * Add file description here! * * @author Sebastian Schaffert (sschaffert@apache.org) */ public class DataConcurrencyTest extends GenericTest { private static final String TEST_DATASET = "test"; private RedLink.Data redlink; @Rule public ConcurrentRule crule = new ConcurrentRule(); @Rule public RepeatingRule rrule = new RepeatingRule(); protected static Random rnd; private static long runs = 0; private static Logger log = LoggerFactory.getLogger(DataConcurrencyTest.class); private List<URI> resources = new ArrayList<>(); private List<Value> objects = new ArrayList<>(); private Set<Statement> allAddedTriples = new HashSet<>(); @Rule public TestWatcher watchman = new TestWatcher() { /** * Invoked when a test is about to start */ @Override protected void starting(Description description) { log.info("{} being run...", description.getMethodName()); } /** * Invoked when a test method finishes (whether passing or failing) */ @Override protected void finished(Description description) { log.info("{}: {} added triples, {} removed triples, {} resources reused, {} objects reused", new Object[] { description.getMethodName(), tripleAddCount, tripleRemoveCount, resourcesReused, objectsReused}); } }; long tripleAddCount = 0; long tripleRemoveCount = 0; long resourcesReused = 0; long objectsReused = 0; private ValueFactory valueFactory; @Before public void setupTest() throws MalformedURLException { Credentials credentials = buildCredentials(DataTest.class); redlink = RedLinkFactory.createDataClient(credentials); valueFactory = new ValueFactoryImpl(); rnd = new Random(); } @BeforeClass @AfterClass public static void cleanUp() throws Exception { Credentials credentials = buildCredentials(DataTest.class); Assume.assumeNotNull(credentials); Assume.assumeNotNull(credentials.getVersion()); Assume.assumeTrue(credentials.verify()); RedLink.Data redlink = RedLinkFactory.createDataClient(credentials); Assume.assumeTrue(redlink.cleanDataset(TEST_DATASET)); } @Test @Concurrent(count = 5) @Repeating(repetition = 10) public void testConcurrently() throws IOException, RDFHandlerException, InterruptedException { try { Model model = new TreeModel(); // create random triples for(int i=0; i < rnd.nextInt(100) + 1; i++) { model.add(new StatementImpl(randomURI(), randomURI(), randomObject())); } log.debug("created {} random triples", model.size()); redlink.importDataset(model, TEST_DATASET); Model exported = redlink.exportDataset(TEST_DATASET); Assert.assertFalse(exported.isEmpty()); for(Statement stmt : model) { Assert.assertTrue("triple "+stmt+" not contained in exported data", exported.contains(stmt)); } for(Resource r : model.subjects()) { redlink.deleteResource(r.stringValue(), TEST_DATASET); } Model deleted = redlink.exportDataset(TEST_DATASET); for(Statement stmt : model) { Assert.assertFalse("triple "+stmt+" still contained in exported data", deleted.contains(stmt)); } } catch (RuntimeException ex) { log.error("exception: ",ex); Assert.fail(ex.getMessage()); } } /** * Return a random URI, with a 10% chance of returning a URI that has already been used. * @return */ protected URI randomURI() { return getValueFactory().createURI("http://localhost/"+ RandomStringUtils.randomAlphanumeric(16)); } /** * Return a random RDF value, either a reused object (10% chance) or of any other kind. * @return */ protected Value randomObject() { Value object; switch(rnd.nextInt(6)) { case 0: object = getValueFactory().createURI("http://data.redlink.io/"+ RandomStringUtils.randomAlphanumeric(8)); break; case 2: object = getValueFactory().createLiteral(RandomStringUtils.randomAscii(40)); break; case 3: object = getValueFactory().createLiteral(rnd.nextInt()); break; case 4: object = getValueFactory().createLiteral(rnd.nextDouble()); break; case 5: object = getValueFactory().createLiteral(rnd.nextBoolean()); break; default: object = getValueFactory().createURI("http://data.redlink.io/"+ RandomStringUtils.randomAlphanumeric(8)); break; } return object; } protected ValueFactory getValueFactory() { return valueFactory; } }