code
stringlengths
3
1.18M
language
stringclasses
1 value
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for Component. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Component implements Serializable, HasLabels { private static final AccElementType ELEMENT_TYPE = AccElementType.COMPONENT; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long componentId; @Persistent private long parentProjectId; @Persistent private String name; @Persistent private String description; /** * Ordering hint for views displaying Attributes. Lower values should be put higher in the list. * Note that value is NOT guaranteed to be unique or greater than zero. */ @Persistent private Long displayOrder = 0 - System.currentTimeMillis(); @NotPersistent private List<AccLabel> accLabels = new ArrayList<AccLabel>(); public Component() { } public Component(long parentProjectId) { this.parentProjectId = parentProjectId; } public Long getComponentId() { return componentId; } @Override public Long getId() { return getComponentId(); } @Override public AccElementType getElementType() { return ELEMENT_TYPE; } public void setComponentId(long componentId) { this.componentId = componentId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public long getParentProjectId() { return parentProjectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setDisplayOrder(long displayOrder) { this.displayOrder = displayOrder; } public long getDisplayOrder() { return displayOrder; } @Override public List<AccLabel> getAccLabels() { return accLabels; } public AccLabel getAccLabel(String accLabelId) { for (AccLabel l : accLabels) { if (accLabelId.equals(l.getId())) { return l; } } return null; } @Override public void setAccLabels(List<AccLabel> labels) { this.accLabels = labels; } public void addLabel(String labelText) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(componentId); label.setElementType(ELEMENT_TYPE); label.setLabelText(labelText); accLabels.add(label); } public void addLabel(String name, String value) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(componentId); label.setElementType(ELEMENT_TYPE); label.setName(name); label.setValue(value); accLabels.add(label); } @Override public void addLabel(AccLabel label) { accLabels.add(label); } public void removeLabel(AccLabel label) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (label.getId() != null) { if (label.getId().equals(l.getId())) { i.remove(); } } else { if (label.getLabelText().equals(l.getLabelText())) { i.remove(); } } } } public void removeLabel(String labelText) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (labelText.equals(l.getLabelText())) { i.remove(); } } } public void removeLabel(String name, String value) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (name.equals(l.getName()) && value.equals(l.getValue())) { i.remove(); } } } public void updateLabel(String oldLabelText, String newLabelText) { for (AccLabel l : accLabels) { if (oldLabelText.equals(l.getLabelText())) { l.setLabelText(newLabelText); } } } public void setDescription(String description) { this.description = description; } public String getDescription() { return description == null ? "" : description; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Enumeration for storing potential failure rates. * * @author chrsmith@google.com (Chris Smith) */ public enum FailureRate { NA (-2, "n/a"), VERY_RARELY (0, "Rarely"), SELDOM (1, "Seldom"), OCCASIONALLY (2, "Occasionally"), OFTEN (3, "Often"); private final int ordinal; private final String description; private FailureRate(int ordinal, String description) { this.ordinal = ordinal; this.description = description; } public int getOrdinal() { return ordinal; } public String getDescription() { return description; } /** * Convert FailureRate.getDescription() into the original FailureRate instance. Enum.getValue * cannot be used because that requires the "ALL_CAPS" form of the value, rather than * the "User Friendly" getName version. */ public static FailureRate fromDescription(String name) { for (FailureRate rate : FailureRate.values()) { if (rate.getDescription().equals(name)) { return rate; } } return null; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.testing; import com.google.gwt.user.client.rpc.AsyncCallback; import org.easymock.EasyMock; import org.easymock.IAnswer; /** * Utility class for simplifying Easy Mock unit tests. * * @author chrsmith@google.com (Chris Smith) */ public abstract class EasyMockUtils { private EasyMockUtils() {} /** Sets the return value for the last call to EasyMock. */ public static <T> void setLastReturnValue(final T result) { EasyMock.expectLastCall().andReturn(result); } /** * Gets the {@link AsyncCallback} (last parameter of the previous function call) and ensures that * the onSuccess method gets called with the given result. This is needed because GWT's async RPC * calls return their value as part of an {@link AsyncCallback}, which is difficult to mock. */ public static <T> void setLastAsyncCallbackSuccessWithResult(final T result) { EasyMock.expectLastCall().andAnswer(new IAnswer<T>() { @SuppressWarnings("unchecked") @Override public T answer() throws Throwable { final Object[] arguments = EasyMock.getCurrentArguments(); AsyncCallback<T> callback = (AsyncCallback<T>) arguments[arguments.length - 1]; callback.onSuccess(result); return null; } }); } /** * Gets the {@link AsyncCallback} (last parameter of the previous function call) and ensures that * the onFailure method gets called with the given {@code Throwable}. */ public static <T> void setLastAsyncCallbackFailure(final Throwable exception) { EasyMock.expectLastCall().andAnswer(new IAnswer<T>() { @SuppressWarnings("unchecked") @Override public T answer() throws Throwable { final Object[] arguments = EasyMock.getCurrentArguments(); AsyncCallback<T> callback = (AsyncCallback<T>) arguments[arguments.length - 1]; callback.onFailure(exception); return null; } }); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview; import com.google.scrollview.events.SVEvent; import com.google.scrollview.ui.SVImageHandler; import com.google.scrollview.ui.SVWindow; import org.piccolo2d.nodes.PImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.regex.Pattern; /** * The ScrollView class is the main class which gets started from the command * line. It sets up LUA and handles the network processing. * @author wanke@google.com */ public class ScrollView { /** The port our server listens at. */ public static int SERVER_PORT = 8461; /** * All SVWindow objects share the same connection stream. The socket is needed * to detect when the connection got closed, in/out are used to send and * receive messages. */ private static Socket socket; private static PrintStream out; public static BufferedReader in; public static float polylineXCoords[]; // The coords being received. public static float polylineYCoords[]; // The coords being received. public static int polylineSize; // The size of the coords arrays. public static int polylineScanned; // The size read so far. private static ArrayList<SVWindow> windows; // The id to SVWindow map. private static Pattern intPattern; // For checking integer arguments. private static Pattern floatPattern; // For checking float arguments. /** Keeps track of the number of messages received. */ static int nrInputLines = 0; /** Prints all received messages to the console if true. */ static boolean debugViewNetworkTraffic = false; /** Add a new message to the outgoing queue */ public static void addMessage(SVEvent e) { if (debugViewNetworkTraffic) { System.out.println("(S->c) " + e.toString()); } String str = e.toString(); // Send the whole thing as UTF8. try { byte [] utf8 = str.getBytes("UTF8"); out.write(utf8, 0, utf8.length); } catch (java.io.UnsupportedEncodingException ex) { System.out.println("Oops... can't encode to UTF8... Exiting"); System.exit(0); } out.println(); // Flush the output and check for errors. boolean error = out.checkError(); if (error) { System.out.println("Connection error. Quitting ScrollView Server..."); System.exit(0); } } /** Read one message from client (assuming there are any). */ public static String receiveMessage() throws IOException { return in.readLine(); } /** * The main program loop. Basically loops trough receiving messages and * processing them and then sending messages (if there are any). */ private static void IOLoop() { String inputLine; try { while (!socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown() && socket.isConnected() && socket.isBound()) { inputLine = receiveMessage(); nrInputLines++; if (debugViewNetworkTraffic) { System.out.println("(c->S," + nrInputLines + ")" + inputLine); } if (polylineSize > polylineScanned) { // We are processing a polyline. // Read pairs of coordinates separated by commas. boolean first = true; for (String coordStr : inputLine.split(",")) { int coord = Integer.parseInt(coordStr); if (first) { polylineXCoords[polylineScanned] = coord; } else { polylineYCoords[polylineScanned++] = coord; } first = !first; } assert first; } else { // Process this normally. processInput(inputLine); } } } // Some connection error catch (IOException e) { System.out.println("Connection error. Quitting ScrollView Server..."); } System.exit(0); } // Parse a comma-separated list of arguments into ArrayLists of the // possible types. Each type is stored in order, but the order // distinction between types is lost. // Note that the format is highly constrained to what the client used // to send to LUA: // Quoted string -> String. // true or false -> Boolean. // %f format number -> Float (no %e allowed) // Sequence of digits -> Integer // Nothing else allowed. private static void parseArguments(String argList, ArrayList<Integer> intList, ArrayList<Float> floatList, ArrayList<String> stringList, ArrayList<Boolean> boolList) { // str is only non-null if an argument starts with a single or double // quote. str is set back to null on completion of the string with a // matching quote. If the string contains a comma then str will stay // non-null across multiple argStr values until a matching closing quote. // Backslash escaped quotes do not count as terminating the string. String str = null; for (String argStr : argList.split(",")) { if (str != null) { // Last string was incomplete. Append argStr to it and restore comma. // Execute str += "," + argStr in Java. int length = str.length() + 1 + argStr.length(); StringBuilder appended = new StringBuilder(length); appended.append(str); appended.append(","); appended.append(argStr); str = appended.toString(); } else if (argStr.length() == 0) { continue; } else { char quote = argStr.charAt(0); // If it begins with a quote then it is a string, but may not // end this time if it contained a comma. if (quote == '\'' || quote == '"') { str = argStr; } } if (str != null) { // It began with a quote. Check that it still does. assert str.charAt(0) == '\'' || str.charAt(0) == '"'; int len = str.length(); if (len > 1 && str.charAt(len - 1) == str.charAt(0)) { // We have an ending quote of the right type. Now check that // it is not escaped. Must have an even number of slashes before. int slash = len - 1; while (slash > 0 && str.charAt(slash - 1) == '\\') --slash; if ((len - 1 - slash) % 2 == 0) { // It is now complete. Chop off the quotes and save. // TODO(rays) remove the first backslash of each pair. stringList.add(str.substring(1, len - 1)); str = null; } } // If str is not null here, then we have a string with a comma in it. // Append , and the next argument at the next iteration, but check // that str is null after the loop terminates in case it was an // unterminated string. } else if (floatPattern.matcher(argStr).matches()) { // It is a float. floatList.add(Float.parseFloat(argStr)); } else if (argStr.equals("true")) { boolList.add(true); } else if (argStr.equals("false")) { boolList.add(false); } else if (intPattern.matcher(argStr).matches()) { // Only contains digits so must be an int. intList.add(Integer.parseInt(argStr)); } // else ignore all incompatible arguments for forward compatibility. } // All strings must have been terminated. assert str == null; } /** Executes the LUA command parsed as parameter. */ private static void processInput(String inputLine) { if (inputLine == null) { return; } // Execute a function encoded as a LUA statement! Yuk! if (inputLine.charAt(0) == 'w') { // This is a method call on a window. Parse it. String noWLine = inputLine.substring(1); String[] idStrs = noWLine.split("[ :]", 2); int windowID = Integer.parseInt(idStrs[0]); // Find the parentheses. int start = inputLine.indexOf('('); int end = inputLine.lastIndexOf(')'); // Parse the args. ArrayList<Integer> intList = new ArrayList<Integer>(4); ArrayList<Float> floatList = new ArrayList<Float>(2); ArrayList<String> stringList = new ArrayList<String>(4); ArrayList<Boolean> boolList = new ArrayList<Boolean>(3); parseArguments(inputLine.substring(start + 1, end), intList, floatList, stringList, boolList); int colon = inputLine.indexOf(':'); if (colon > 1 && colon < start) { // This is a regular function call. Look for the name and call it. String func = inputLine.substring(colon + 1, start); if (func.equals("drawLine")) { windows.get(windowID).drawLine(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("createPolyline")) { windows.get(windowID).createPolyline(intList.get(0)); } else if (func.equals("drawPolyline")) { windows.get(windowID).drawPolyline(); } else if (func.equals("drawRectangle")) { windows.get(windowID).drawRectangle(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("setVisible")) { windows.get(windowID).setVisible(boolList.get(0)); } else if (func.equals("setAlwaysOnTop")) { windows.get(windowID).setAlwaysOnTop(boolList.get(0)); } else if (func.equals("addMessage")) { windows.get(windowID).addMessage(stringList.get(0)); } else if (func.equals("addMessageBox")) { windows.get(windowID).addMessageBox(); } else if (func.equals("clear")) { windows.get(windowID).clear(); } else if (func.equals("setStrokeWidth")) { windows.get(windowID).setStrokeWidth(floatList.get(0)); } else if (func.equals("drawEllipse")) { windows.get(windowID).drawEllipse(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("pen")) { if (intList.size() == 4) { windows.get(windowID).pen(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else { windows.get(windowID).pen(intList.get(0), intList.get(1), intList.get(2)); } } else if (func.equals("brush")) { if (intList.size() == 4) { windows.get(windowID).brush(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else { windows.get(windowID).brush(intList.get(0), intList.get(1), intList.get(2)); } } else if (func.equals("textAttributes")) { windows.get(windowID).textAttributes(stringList.get(0), intList.get(0), boolList.get(0), boolList.get(1), boolList.get(2)); } else if (func.equals("drawText")) { windows.get(windowID).drawText(intList.get(0), intList.get(1), stringList.get(0)); } else if (func.equals("addMenuBarItem")) { if (boolList.size() > 0) { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1), intList.get(0), boolList.get(0)); } else if (intList.size() > 0) { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1), intList.get(0)); } else { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1)); } } else if (func.equals("addPopupMenuItem")) { if (stringList.size() == 4) { windows.get(windowID).addPopupMenuItem(stringList.get(0), stringList.get(1), intList.get(0), stringList.get(2), stringList.get(3)); } else { windows.get(windowID).addPopupMenuItem(stringList.get(0), stringList.get(1)); } } else if (func.equals("update")) { windows.get(windowID).update(); } else if (func.equals("showInputDialog")) { windows.get(windowID).showInputDialog(stringList.get(0)); } else if (func.equals("showYesNoDialog")) { windows.get(windowID).showYesNoDialog(stringList.get(0)); } else if (func.equals("zoomRectangle")) { windows.get(windowID).zoomRectangle(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("readImage")) { PImage image = SVImageHandler.readImage(intList.get(2), in); windows.get(windowID).drawImage(image, intList.get(0), intList.get(1)); } else if (func.equals("drawImage")) { PImage image = new PImage(stringList.get(0)); windows.get(windowID).drawImage(image, intList.get(0), intList.get(1)); } else if (func.equals("destroy")) { windows.get(windowID).destroy(); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } else { // No colon. Check for create window. if (idStrs[1].startsWith("= luajava.newInstance")) { while (windows.size() <= windowID) { windows.add(null); } windows.set(windowID, new SVWindow(stringList.get(1), intList.get(0), intList.get(1), intList.get(2), intList.get(3), intList.get(4), intList.get(5), intList.get(6))); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } } else if (inputLine.startsWith("svmain")) { // Startup or end. Startup is a lua bind, which is now a no-op. if (inputLine.startsWith("svmain:exit")) { exit(); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } /** Called from the client to make the server exit. */ public static void exit() { System.exit(0); } /** * The main function. Sets up LUA and the server connection and then calls the * IOLoop. */ public static void main(String[] args) { if (args.length > 0) { SERVER_PORT = Integer.parseInt(args[0]); } windows = new ArrayList<SVWindow>(100); intPattern = Pattern.compile("[0-9-][0-9]*"); floatPattern = Pattern.compile("[0-9-][0-9]*\\.[0-9]*"); try { // Open a socket to listen on. ServerSocket serverSocket = new ServerSocket(SERVER_PORT); System.out.println("Socket started on port " + SERVER_PORT); // Wait (blocking) for an incoming connection socket = serverSocket.accept(); System.out.println("Client connected"); // Setup the streams out = new PrintStream(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8")); } catch (IOException e) { // Something went wrong and we were unable to set up a connection. This is // pretty // much a fatal error. // Note: The server does not get restarted automatically if this happens. e.printStackTrace(); System.exit(1); } // Enter the main program loop. IOLoop(); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.events; /** * These are the defined events which can happen in ScrollView and be * transferred to the client. They are same events as on the client side part of * ScrollView (defined in ScrollView.h). * * @author wanke@google.com */ public enum SVEventType { SVET_DESTROY, // Window has been destroyed by user. SVET_EXIT, // User has destroyed the last window by clicking on the 'X' SVET_CLICK, // Any button pressed thats not a popup trigger. SVET_SELECTION, // Left button selection. SVET_INPUT, // Any kind of input SVET_MOUSE, // The mouse has moved with a button pressed. SVET_MOTION, // The mouse has moved with no button pressed. SVET_HOVER, // The mouse has stayed still for a second. SVET_POPUP, // A command selected through a popup menu SVET_MENU; // A command selected through the menubar }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.events; import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVWindow; import org.piccolo2d.PCamera; import org.piccolo2d.PNode; import org.piccolo2d.event.PBasicInputEventHandler; import org.piccolo2d.event.PInputEvent; import org.piccolo2d.nodes.PPath; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.Timer; /** * The ScrollViewEventHandler takes care of any events which might happen on the * canvas and converts them to an according SVEvent, which is (using the * processEvent method) then added to a message queue. All events from the * message queue get sent gradually * * @author wanke@google.com */ public class SVEventHandler extends PBasicInputEventHandler implements ActionListener, KeyListener, WindowListener { /** Necessary to wait for a defined period of time (for SVET_HOVER). */ public Timer timer; /** The window which the event corresponds to. */ private SVWindow svWindow; /** These are used to determine a selection size (for SVET_SELECTION). */ private int lastX = 0; private int lastY = 0; /** * These are used in case we want to transmit our position, but do not get it * because it was no MouseEvent, in particular SVET_HOVER and SVET_INPUT. */ private int lastXMove = 0; private int lastYMove = 0; /** For Drawing a rubber-band rectangle for selection */ private int startX = 0; private int startY = 0; private float rubberBandTransparency = 0.5f; private PNode selection = null; /** The string entered since the last enter. Since the client * end eats all newlines, we can't use the newline * character, so use ! for now, as it cannot be entered * directly anyway and therefore can never show up for real. */ private String keyStr = "!"; /** Setup the timer. */ public SVEventHandler(SVWindow wdw) { timer = new Timer(1000, this); svWindow = wdw; } /** * Store the newest x,y values, add the message to the queue and restart the * timer. */ private void processEvent(SVEvent e) { lastXMove = e.x; lastYMove = e.y; ScrollView.addMessage(e); timer.restart(); } /** Show the associated popup menu at (x,y) (relative position of the window). */ private void showPopup(PInputEvent e) { double x = e.getCanvasPosition().getX(); double y = e.getCanvasPosition().getY(); if (svWindow.svPuMenu != null) { svWindow.svPuMenu.show(svWindow, (int) x, (int) y); } } /** The mouse is clicked - create an SVET_CLICK event. */ @Override public void mouseClicked(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { processEvent(new SVEvent(SVEventType.SVET_CLICK, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), 0, 0, null)); } } /** * The mouse key is pressed (and keeps getting pressed). * Depending on the OS, show a popup menu (if the button pressed is associated * with popup menus, like the RMB under windows&linux) or otherwise save the * position (in case it is a selection). */ @Override public void mousePressed(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { lastX = (int) e.getPosition().getX(); lastY = (int) e.getPosition().getY(); timer.restart(); } } /** The mouse is getting dragged - create an SVET_MOUSE event. */ @Override public void mouseDragged(PInputEvent e) { processEvent(new SVEvent(SVEventType.SVET_MOUSE, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), (int) e .getPosition().getX() - lastX, (int) e.getPosition().getY() - lastY, null)); // Paint a selection rectangle. if (selection == null) { startX = (int) e.getPosition().getX(); startY = (int) e.getPosition().getY(); selection = PPath.createRectangle(startX, startY, 1, 1); selection.setTransparency(rubberBandTransparency); svWindow.canvas.getLayer().addChild(selection); } else { int right = Math.max(startX, (int) e.getPosition().getX()); int left = Math.min(startX, (int) e.getPosition().getX()); int bottom = Math.max(startY, (int) e.getPosition().getY()); int top = Math.min(startY, (int) e.getPosition().getY()); svWindow.canvas.getLayer().removeChild(selection); selection = PPath.createRectangle(left, top, right - left, bottom - top); selection.setPaint(Color.YELLOW); selection.setTransparency(rubberBandTransparency); svWindow.canvas.getLayer().addChild(selection); } } /** * The mouse was released. * Depending on the OS, show a popup menu (if the button pressed is associated * with popup menus, like the RMB under windows&linux) or otherwise create an * SVET_SELECTION event. */ @Override public void mouseReleased(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { processEvent(new SVEvent(SVEventType.SVET_SELECTION, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), (int) e .getPosition().getX() - lastX, (int) e.getPosition().getY() - lastY, null)); } if (selection != null) { svWindow.canvas.getLayer().removeChild(selection); selection = null; } } /** * The mouse wheel is used to zoom in and out of the viewport and center on * the (x,y) position the mouse is currently on. */ @Override public void mouseWheelRotated(PInputEvent e) { PCamera lc = svWindow.canvas.getCamera(); double sf = SVWindow.SCALING_FACTOR; if (e.getWheelRotation() < 0) { sf = 1 / sf; } lc.scaleViewAboutPoint(lc.getScale() / sf, e.getPosition().getX(), e .getPosition().getY()); } /** * The mouse was moved - create an SVET_MOTION event. NOTE: This obviously * creates a lot of traffic and, depending on the type of application, could * quite possibly be disabled. */ @Override public void mouseMoved(PInputEvent e) { processEvent(new SVEvent(SVEventType.SVET_MOTION, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), 0, 0, null)); } /** * The mouse entered the window. * Start the timer, which will then emit SVET_HOVER events every X ms. */ @Override public void mouseEntered(PInputEvent e) { timer.restart(); } /** * The mouse exited the window * Stop the timer, so no more SVET_HOVER events will emit. */ @Override public void mouseExited(PInputEvent e) { timer.stop(); } /** * The only associated object with this is the timer, so we use it to send a * SVET_HOVER event. */ public void actionPerformed(ActionEvent e) { processEvent(new SVEvent(SVEventType.SVET_HOVER, svWindow, lastXMove, lastYMove, 0, 0, null)); } /** * A key was pressed - create an SVET_INPUT event. * * NOTE: Might be useful to specify hotkeys. * * Implementation note: The keyListener provided by Piccolo seems to be * broken, so we use the AWT listener directly. * There are never any keyTyped events received either so we are * stuck with physical keys, which is very ugly. */ public void keyPressed(KeyEvent e) { char keyCh = e.getKeyChar(); if (keyCh == '\r' || keyCh == '\n' || keyCh == '\0' || keyCh == '?') { processEvent(new SVEvent(SVEventType.SVET_INPUT, svWindow, lastXMove, lastYMove, 0, 0, keyStr)); // Send newline characters as '!' as '!' can never be a keypressed // and the client eats all newline characters. keyStr = "!"; } else { processEvent(new SVEvent(SVEventType.SVET_INPUT, svWindow, lastXMove, lastYMove, 0, 0, String.valueOf(keyCh))); keyStr += keyCh; } } /** * A window is closed (by the 'x') - create an SVET_DESTROY event. If it was * the last open Window, also send an SVET_EXIT event (but do not exit unless * the client says so). */ public void windowClosing(WindowEvent e) { processEvent(new SVEvent(SVEventType.SVET_DESTROY, svWindow, lastXMove, lastYMove, 0, 0, null)); e.getWindow().dispose(); SVWindow.nrWindows--; if (SVWindow.nrWindows == 0) { processEvent(new SVEvent(SVEventType.SVET_EXIT, svWindow, lastXMove, lastYMove, 0, 0, null)); } } /** These are all events we do not care about and throw away */ public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.events; import com.google.scrollview.ui.SVWindow; /** * The SVEvent is a structure which holds the actual values of a message to be * transmitted. It corresponds to the client structure defined in scrollview.h * * @author wanke@google.com */ public class SVEvent { SVEventType type; // What kind of event. SVWindow window; // Window event relates to. int x; // Coords of click or selection. int y; int xSize; // Size of selection. int ySize; int commandId; String parameter; // Any string that might have been passed as argument. /** * A "normal" SVEvent. * * @param t The type of the event as specified in SVEventType (e.g. * SVET_CLICK) * @param w The window the event corresponds to * @param x1 X position of the mouse at the time of the event * @param y1 Y position of the mouse at the time of the event * @param x2 X selection size at the time of the event * @param y2 Y selection size at the time of the event * @param p A parameter associated with the event (e.g. keyboard input) */ public SVEvent(SVEventType t, SVWindow w, int x1, int y1, int x2, int y2, String p) { type = t; window = w; x = x1; y = y1; xSize = x2; ySize = y2; commandId = 0; parameter = p; } /** * An event which issues a command (like clicking on a item in the menubar). * * @param eventtype The type of the event as specified in SVEventType * (usually SVET_MENU or SVET_POPUP) * @param svWindow The window the event corresponds to * @param commandid The associated id with the command (given by the client * on construction of the item) * @param value A parameter associated with the event (e.g. keyboard input) */ public SVEvent(SVEventType eventtype, SVWindow svWindow, int commandid, String value) { type = eventtype; window = svWindow; parameter = value; x = 0; y = 0; xSize = 0; ySize = 0; commandId = commandid; } /** * This is the string representation of the message, which is what will * actually be transferred over the network. */ @Override public String toString() { return (window.hash + "," + type.ordinal() + "," + x + "," + y + "," + xSize + "," + ySize + "," + commandId + "," + parameter); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventHandler; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVMenuBar; import com.google.scrollview.ui.SVPopupMenu; import org.piccolo2d.PCamera; import org.piccolo2d.PCanvas; import org.piccolo2d.PLayer; import org.piccolo2d.extras.swing.PScrollPane; import org.piccolo2d.nodes.PImage; import org.piccolo2d.nodes.PPath; import org.piccolo2d.nodes.PText; import org.piccolo2d.util.PPaintContext; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.TextArea; import java.awt.geom.IllegalPathStateException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; /** * The SVWindow is the top-level ui class. It should get instantiated whenever * the user intends to create a new window. It contains helper functions to draw * on the canvas, add new menu items, show modal dialogs etc. * * @author wanke@google.com */ public class SVWindow extends JFrame { /** * Constants defining the maximum initial size of the window. */ private static final int MAX_WINDOW_X = 1000; private static final int MAX_WINDOW_Y = 800; /* Constant defining the (approx) height of the default message box*/ private static final int DEF_MESSAGEBOX_HEIGHT = 200; /** Constant defining the "speed" at which to zoom in and out. */ public static final double SCALING_FACTOR = 2; /** The top level layer we add our PNodes to (root node). */ PLayer layer; /** The current color of the pen. It is used to draw edges, text, etc. */ Color currentPenColor; /** * The current color of the brush. It is used to draw the interior of * primitives. */ Color currentBrushColor; /** The system name of the current font we are using (e.g. * "Times New Roman"). */ Font currentFont; /** The stroke width to be used. */ // This really needs to be a fixed width stroke as the basic stroke is // anti-aliased and gets too faint, but the piccolo fixed width stroke // is too buggy and generates missing initial moveto in path definition // errors with a IllegalPathStateException that cannot be caught because // it is in the automatic repaint function. If we can fix the exceptions // in piccolo, then we can use the following instead of BasicStroke: // import edu.umd.cs.piccolox.util.PFixedWidthStroke; // PFixedWidthStroke stroke = new PFixedWidthStroke(0.5f); // Instead we use the BasicStroke and turn off anti-aliasing. BasicStroke stroke = new BasicStroke(0.5f); /** * A unique representation for the window, also known by the client. It is * used when sending messages from server to client to identify him. */ public int hash; /** * The total number of created Windows. If this ever reaches 0 (apart from the * beginning), quit the server. */ public static int nrWindows = 0; /** * The Canvas, MessageBox, EventHandler, Menubar and Popupmenu associated with * this window. */ private SVEventHandler svEventHandler = null; private SVMenuBar svMenuBar = null; private TextArea ta = null; public SVPopupMenu svPuMenu = null; public PCanvas canvas; private int winSizeX; private int winSizeY; /** Set the brush to an RGB color */ public void brush(int red, int green, int blue) { brush(red, green, blue, 255); } /** Set the brush to an RGBA color */ public void brush(int red, int green, int blue, int alpha) { // If alpha is zero, use a null brush to save rendering time. if (alpha == 0) { currentBrushColor = null; } else { currentBrushColor = new Color(red, green, blue, alpha); } } /** Erase all content from the window, but do not destroy it. */ public void clear() { // Manipulation of Piccolo's scene graph should be done from Swings // event dispatch thread since Piccolo is not thread safe. This code calls // removeAllChildren() from that thread and releases the latch. final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); SwingUtilities.invokeLater(new Runnable() { public void run() { layer.removeAllChildren(); repaint(); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { } } /** * Start setting up a new polyline. The server will now expect * polyline data until the polyline is complete. * * @param length number of coordinate pairs */ public void createPolyline(int length) { ScrollView.polylineXCoords = new float[length]; ScrollView.polylineYCoords = new float[length]; ScrollView.polylineSize = length; ScrollView.polylineScanned = 0; } /** * Draw the now complete polyline. */ public void drawPolyline() { int numCoords = ScrollView.polylineXCoords.length; if (numCoords < 2) { return; } PPath pn = PPath.createLine(ScrollView.polylineXCoords[0], ScrollView.polylineYCoords[0], ScrollView.polylineXCoords[1], ScrollView.polylineYCoords[1]); pn.reset(); pn.moveTo(ScrollView.polylineXCoords[0], ScrollView.polylineYCoords[0]); for (int p = 1; p < numCoords; ++p) { pn.lineTo(ScrollView.polylineXCoords[p], ScrollView.polylineYCoords[p]); } pn.closePath(); ScrollView.polylineSize = 0; pn.setStrokePaint(currentPenColor); pn.setPaint(null); // Don't fill the polygon - this is just a polyline. pn.setStroke(stroke); layer.addChild(pn); } /** * Construct a new SVWindow and set it visible. * * @param name Title of the window. * @param hash Unique internal representation. This has to be the same as * defined by the client, as they use this to refer to the windows. * @param posX X position of where to draw the window (upper left). * @param posY Y position of where to draw the window (upper left). * @param sizeX The width of the window. * @param sizeY The height of the window. * @param canvasSizeX The canvas width of the window. * @param canvasSizeY The canvas height of the window. */ public SVWindow(String name, int hash, int posX, int posY, int sizeX, int sizeY, int canvasSizeX, int canvasSizeY) { super(name); // Provide defaults for sizes. if (sizeX == 0) sizeX = canvasSizeX; if (sizeY == 0) sizeY = canvasSizeY; if (canvasSizeX == 0) canvasSizeX = sizeX; if (canvasSizeY == 0) canvasSizeY = sizeY; // Initialize variables nrWindows++; this.hash = hash; this.svEventHandler = new SVEventHandler(this); this.currentPenColor = Color.BLACK; this.currentBrushColor = Color.BLACK; this.currentFont = new Font("Times New Roman", Font.PLAIN, 12); // Determine the initial size and zoom factor of the window. // If the window is too big, rescale it and zoom out. int shrinkfactor = 1; if (sizeX > MAX_WINDOW_X) { shrinkfactor = (sizeX + MAX_WINDOW_X - 1) / MAX_WINDOW_X; } if (sizeY / shrinkfactor > MAX_WINDOW_Y) { shrinkfactor = (sizeY + MAX_WINDOW_Y - 1) / MAX_WINDOW_Y; } winSizeX = sizeX / shrinkfactor; winSizeY = sizeY / shrinkfactor; double initialScalingfactor = 1.0 / shrinkfactor; if (winSizeX > canvasSizeX || winSizeY > canvasSizeY) { initialScalingfactor = Math.min(1.0 * winSizeX / canvasSizeX, 1.0 * winSizeY / canvasSizeY); } // Setup the actual window (its size, camera, title, etc.) if (canvas == null) { canvas = new PCanvas(); getContentPane().add(canvas, BorderLayout.CENTER); } layer = canvas.getLayer(); canvas.setBackground(Color.BLACK); // Disable anitaliasing to make the lines more visible. canvas.setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); validate(); canvas.requestFocus(); // Manipulation of Piccolo's scene graph should be done from Swings // event dispatch thread since Piccolo is not thread safe. This code calls // initialize() from that thread once the PFrame is initialized, so you are // safe to start working with Piccolo in the initialize() method. SwingUtilities.invokeLater(new Runnable() { public void run() { repaint(); } }); setSize(winSizeX, winSizeY); setLocation(posX, posY); setTitle(name); // Add a Scrollpane to be able to scroll within the canvas PScrollPane scrollPane = new PScrollPane(canvas); getContentPane().add(scrollPane); scrollPane.setWheelScrollingEnabled(false); PCamera lc = canvas.getCamera(); lc.scaleViewAboutPoint(initialScalingfactor, 0, 0); // Disable the default event handlers and add our own. addWindowListener(svEventHandler); canvas.removeInputEventListener(canvas.getPanEventHandler()); canvas.removeInputEventListener(canvas.getZoomEventHandler()); canvas.addInputEventListener(svEventHandler); canvas.addKeyListener(svEventHandler); // Make the window visible. validate(); setVisible(true); } /** * Convenience function to add a message box to the window which can be used * to output debug information. */ public void addMessageBox() { if (ta == null) { ta = new TextArea(); ta.setEditable(false); getContentPane().add(ta, BorderLayout.SOUTH); } // We need to make the window bigger to accomodate the message box. winSizeY += DEF_MESSAGEBOX_HEIGHT; setSize(winSizeX, winSizeY); } /** * Allows you to specify the thickness with which to draw lines, recantgles * and ellipses. * @param width The new thickness. */ public void setStrokeWidth(float width) { // If this worked we wouldn't need the antialiased rendering off. // stroke = new PFixedWidthStroke(width); stroke = new BasicStroke(width); } /** * Draw an ellipse at (x,y) with given width and height, using the * current stroke, the current brush color to fill it and the * current pen color for the outline. */ public void drawEllipse(int x, int y, int width, int height) { PPath pn = PPath.createEllipse(x, y, width, height); pn.setStrokePaint(currentPenColor); pn.setStroke(stroke); pn.setPaint(currentBrushColor); layer.addChild(pn); } /** * Draw the image with the given name at (x,y). Any image loaded stays in * memory, so if you intend to redraw an image, you do not have to use * createImage again. */ public void drawImage(PImage img, int xPos, int yPos) { img.setX(xPos); img.setY(yPos); layer.addChild(img); } /** * Draw a line from (x1,y1) to (x2,y2) using the current pen color and stroke. */ public void drawLine(int x1, int y1, int x2, int y2) { PPath pn = PPath.createLine(x1, y1, x2, y2); pn.setStrokePaint(currentPenColor); pn.setPaint(null); // Null paint may render faster than the default. pn.setStroke(stroke); pn.moveTo(x1, y1); pn.lineTo(x2, y2); layer.addChild(pn); } /** * Draw a rectangle given the two points (x1,y1) and (x2,y2) using the current * stroke, pen color for the border and the brush to fill the * interior. */ public void drawRectangle(int x1, int y1, int x2, int y2) { if (x1 > x2) { int t = x1; x1 = x2; x2 = t; } if (y1 > y2) { int t = y1; y1 = y2; y2 = t; } PPath pn = PPath.createRectangle(x1, y1, x2 - x1, y2 - y1); pn.setStrokePaint(currentPenColor); pn.setStroke(stroke); pn.setPaint(currentBrushColor); layer.addChild(pn); } /** * Draw some text at (x,y) using the current pen color and text attributes. If * the current font does NOT support at least one character, it tries to find * a font which is capable of displaying it and use that to render the text. * Note: If the font says it can render a glyph, but in reality it turns out * to be crap, there is nothing we can do about it. */ public void drawText(int x, int y, String text) { int unreadableCharAt = -1; char[] chars = text.toCharArray(); PText pt = new PText(text); pt.setTextPaint(currentPenColor); pt.setFont(currentFont); // Check to see if every character can be displayed by the current font. for (int i = 0; i < chars.length; i++) { if (!currentFont.canDisplay(chars[i])) { // Set to the first not displayable character. unreadableCharAt = i; break; } } // Have to find some working font and use it for this text entry. if (unreadableCharAt != -1) { Font[] allfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (int j = 0; j < allfonts.length; j++) { if (allfonts[j].canDisplay(chars[unreadableCharAt])) { Font tempFont = new Font(allfonts[j].getFontName(), currentFont.getStyle(), currentFont.getSize()); pt.setFont(tempFont); break; } } } pt.setX(x); pt.setY(y); layer.addChild(pt); } /** Set the pen color to an RGB value */ public void pen(int red, int green, int blue) { pen(red, green, blue, 255); } /** Set the pen color to an RGBA value */ public void pen(int red, int green, int blue, int alpha) { currentPenColor = new Color(red, green, blue, alpha); } /** * Define how to display text. Note: underlined is not currently not supported */ public void textAttributes(String font, int pixelSize, boolean bold, boolean italic, boolean underlined) { // For legacy reasons convert "Times" to "Times New Roman" if (font.equals("Times")) { font = "Times New Roman"; } int style = Font.PLAIN; if (bold) { style += Font.BOLD; } if (italic) { style += Font.ITALIC; } currentFont = new Font(font, style, pixelSize); } /** * Zoom the window to the rectangle given the two points (x1,y1) * and (x2,y2), which must be greater than (x1,y1). */ public void zoomRectangle(int x1, int y1, int x2, int y2) { if (x2 > x1 && y2 > y1) { winSizeX = getWidth(); winSizeY = getHeight(); int width = x2 - x1; int height = y2 - y1; // Since piccolo doesn't do this well either, pad with a margin // all the way around. int wmargin = width / 2; int hmargin = height / 2; double scalefactor = Math.min(winSizeX / (2.0 * wmargin + width), winSizeY / (2.0 * hmargin + height)); PCamera lc = canvas.getCamera(); lc.scaleView(scalefactor / lc.getViewScale()); lc.animateViewToPanToBounds(new Rectangle(x1 - hmargin, y1 - hmargin, 2 * wmargin + width, 2 * hmargin + height), 0); } } /** * Flush buffers and update display. * * Only actually reacts if there are no more messages in the stack, to prevent * the canvas from flickering. */ public void update() { // TODO(rays) fix bugs in piccolo or use something else. // The repaint function generates many // exceptions for no good reason. We catch and ignore as many as we // can here, but most of them are generated by the system repaints // caused by resizing/exposing parts of the window etc, and they // generate unwanted stack traces that have to be piped to /dev/null // (on linux). try { repaint(); } catch (NullPointerException e) { // Do nothing so the output isn't full of stack traces. } catch (IllegalPathStateException e) { // Do nothing so the output isn't full of stack traces. } } /** Adds a checkbox entry to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name, int id, boolean checked) { svMenuBar.add(parent, name, id, checked); } /** Adds a submenu to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name) { addMenuBarItem(parent, name, -1); } /** Adds a new entry to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name, int id) { if (svMenuBar == null) { svMenuBar = new SVMenuBar(this); } svMenuBar.add(parent, name, id); } /** Add a message to the message box. */ public void addMessage(String message) { if (ta != null) { ta.append(message + "\n"); } else { System.out.println(message + "\n"); } } /** * This method converts a string which might contain hexadecimal values to a * string which contains the respective unicode counterparts. * * For example, Hall0x0094chen returns Hall<o umlaut>chen * encoded as utf8. * * @param input The original string, containing 0x values * @return The converted string which has the replaced unicode symbols */ private static String convertIntegerStringToUnicodeString(String input) { StringBuffer sb = new StringBuffer(input); Pattern numbers = Pattern.compile("0x[0-9a-fA-F]{4}"); Matcher matcher = numbers.matcher(sb); while (matcher.find()) { // Find the next match which resembles a hexadecimal value and convert it // to // its char value char a = (char) (Integer.decode(matcher.group()).intValue()); // Replace the original with the new character sb.replace(matcher.start(), matcher.end(), String.valueOf(a)); // Start again, since our positions have switched matcher.reset(); } return sb.toString(); } /** * Show a modal input dialog. The answer by the dialog is then send to the * client, together with the associated menu id, as SVET_POPUP * * @param msg The text that is displayed in the dialog. * @param def The default value of the dialog. * @param id The associated commandId * @param evtype The event this is associated with (usually SVET_MENU * or SVET_POPUP) */ public void showInputDialog(String msg, String def, int id, SVEventType evtype) { svEventHandler.timer.stop(); String tmp = (String) JOptionPane.showInputDialog(this, msg, "", JOptionPane.QUESTION_MESSAGE, null, null, def); if (tmp != null) { tmp = convertIntegerStringToUnicodeString(tmp); SVEvent res = new SVEvent(evtype, this, id, tmp); ScrollView.addMessage(res); } svEventHandler.timer.restart(); } /** * Shows a modal input dialog to the user. The return value is automatically * sent to the client as SVET_INPUT event (with command id -1). * * @param msg The text of the dialog. */ public void showInputDialog(String msg) { showInputDialog(msg, null, -1, SVEventType.SVET_INPUT); } /** * Shows a dialog presenting "Yes" and "No" as answers and returns either a * "y" or "n" to the client. * * @param msg The text that is displayed in the dialog. */ public void showYesNoDialog(String msg) { // res returns 0 on yes, 1 on no. Seems to be a bit counterintuitive int res = JOptionPane.showOptionDialog(this, msg, "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); SVEvent e = null; if (res == 0) { e = new SVEvent(SVEventType.SVET_INPUT, this, 0, 0, 0, 0, "y"); } else if (res == 1) { e = new SVEvent(SVEventType.SVET_INPUT, this, 0, 0, 0, 0, "n"); } ScrollView.addMessage(e); } /** Adds a submenu to the popup menu, c.f. SVPopupMenu.add(...) */ public void addPopupMenuItem(String parent, String name) { if (svPuMenu == null) { svPuMenu = new SVPopupMenu(this); } svPuMenu.add(parent, name, -1); } /** Adds a new menu entry to the popup menu, c.f. SVPopupMenu.add(...) */ public void addPopupMenuItem(String parent, String name, int cmdEvent, String value, String desc) { if (svPuMenu == null) { svPuMenu = new SVPopupMenu(this); } svPuMenu.add(parent, name, cmdEvent, value, desc); } /** Destroys a window. */ public void destroy() { ScrollView.addMessage(new SVEvent(SVEventType.SVET_DESTROY, this, 0, "SVET_DESTROY")); setVisible(false); // dispose(); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import javax.swing.JCheckBoxMenuItem; /** * Constructs a new menulistitem which possesses a flag that can be toggled. */ class SVCheckboxMenuItem extends SVAbstractMenuItem { public String value = null; public String desc = null; public boolean bvalue; SVCheckboxMenuItem(int id, String name, boolean val) { super(id, name, new JCheckBoxMenuItem(name, val)); bvalue = val; } /** What to do when user clicks on this item. */ @Override public void performAction(SVWindow window, SVEventType eventType) { // Checkbox entry - trigger and send event. if (bvalue) { bvalue = false; } else { bvalue = true; } SVEvent svme = new SVEvent(eventType, window, id, getValue()); ScrollView.addMessage(svme); } /** Returns the actual value of the MenuListItem. */ @Override public String getValue() { return Boolean.toString(bvalue); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVWindow; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JMenu; import javax.swing.JMenuBar; /** * The SVMenuBar class provides the functionality to add a menubar to * ScrollView. Each menubar item gets associated with a (client-defined) * command-id, which SVMenuBar will return upon clicking it. * * @author wanke@google.com * */ public class SVMenuBar implements ActionListener { /** The root entry to add items to. */ private JMenuBar root; /** Contains a map of item name to its actual entry. */ private HashMap<String, SVAbstractMenuItem> items; /** The window the menubar belongs to. */ private SVWindow svWindow; /** * Create a new SVMenuBar and place it at the top of the ScrollView window. * * @param scrollView The window our menubar belongs to. */ public SVMenuBar(SVWindow scrollView) { root = new JMenuBar(); svWindow = scrollView; items = new HashMap<String, SVAbstractMenuItem>(); svWindow.setJMenuBar(root); } /** * A click on one of the items in our menubar has occured. Forward it * to the item itself to let it decide what happens. */ public void actionPerformed(ActionEvent e) { // Get the corresponding menuitem. SVAbstractMenuItem svm = items.get(e.getActionCommand()); svm.performAction(svWindow, SVEventType.SVET_MENU); } /** * Add a new entry to the menubar. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. */ public void add(String parent, String name, int id) { // A duplicate entry - we just throw it away, since its already in. if (items.get(name) != null) { return; } // A new submenu at the top-level if (parent.equals("")) { JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); root.add(jli); } // A new sub-submenu else if (id == -1) { SVAbstractMenuItem jmi = items.get(parent); JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); jmi.add(jli); } // A new child entry. Add to appropriate parent. else { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVEmptyMenuItem(id, name); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } } /** * Add a new checkbox entry to the menubar. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. * @param b Whether the entry is initally flagged. * */ public void add(String parent, String name, int id, boolean b) { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVCheckboxMenuItem(id, name, b); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.events.SVEventType; import javax.swing.JMenu; import javax.swing.JMenuItem; abstract class SVAbstractMenuItem { JMenuItem mi; public String name; public int id; /** * Sets the basic attributes for name, id and the corresponding swing item */ SVAbstractMenuItem(int id, String name, JMenuItem jmi) { this.mi = jmi; this.name = name; this.id = id; } /** Returns the actual value of the MenuListItem. */ public String getValue() { return null; } /** Adds a child entry to the submenu. */ public void add(SVAbstractMenuItem mli) { } /** Adds a child menu to the submenu (or root node). */ public void add(JMenu jli) { } /** * What to do when user clicks on this item. * @param window The window the event happened. * @param eventType What kind of event will be associated * (usually SVET_POPUP or SVET_MENU). */ public void performAction(SVWindow window, SVEventType eventType) {} }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVMenuItem; import com.google.scrollview.ui.SVWindow; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JMenu; import javax.swing.JPopupMenu; /** * The SVPopupMenu class provides the functionality to add a popup menu to * ScrollView. Each popup menu item gets associated with a (client-defined) * command-id, which SVPopupMenu will return upon clicking it. * * @author wanke@google.com * */ public class SVPopupMenu implements ActionListener { /** The root entry to add items to. */ private JPopupMenu root; /** Contains a map of item name to its actual entry. */ private HashMap<String, SVAbstractMenuItem> items; /** The window the menubar belongs to. */ private SVWindow svWindow; /** * Create a new SVPopupMenu and associate it with a ScrollView window. * * @param sv The window our popup menu belongs to. */ SVPopupMenu(SVWindow sv) { root = new JPopupMenu(); svWindow = sv; items = new HashMap<String, SVAbstractMenuItem>(); } /** * Add a new entry to the menubar. For these items, the server will poll the * client to ask what to do. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. */ public void add(String parent, String name, int id) { // A duplicate entry - we just throw it away, since its already in. if (items.get(name) != null) { return; } // A new submenu at the top-level if (parent.equals("")) { JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); root.add(jli); } // A new sub-submenu else if (id == -1) { SVAbstractMenuItem jmi = items.get(parent); JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); jmi.add(jli); } // A new child entry. Add to appropriate parent. else { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVEmptyMenuItem(id, name); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } } /** * Add a new entry to the menubar. In this case, we also know its value and * possibly even have a description. For these items, the server will not poll * the client to ask what to do, but just show an input dialog and send a * message with the new value. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. * @param value The value of the new entry. * @param desc The description of the new entry. */ public void add(String parent, String name, int id, String value, String desc) { SVAbstractMenuItem jmi = items.get(parent); SVMenuItem mli = new SVMenuItem(id, name, value, desc); mli.mi.addActionListener(this); items.put(name, mli); if (jmi == null) { // add to root root.add(mli.mi); } else { // add to parent jmi.add(mli); } } /** * A click on one of the items in our menubar has occured. Forward it * to the item itself to let it decide what happens. */ public void actionPerformed(ActionEvent e) { // Get the corresponding menuitem SVAbstractMenuItem svm = items.get(e.getActionCommand()); svm.performAction(svWindow, SVEventType.SVET_POPUP); } /** * Gets called by the SVEventHandler of the window to actually show the * content of the popup menu. */ public void show(Component Invoker, int x, int y) { root.show(Invoker, x, y); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import javax.swing.JMenu; /** Constructs a new submenu which can hold other entries. */ class SVSubMenuItem extends SVAbstractMenuItem { public SVSubMenuItem(String name, JMenu jli) { super(-1, name, jli); } /** Adds a child entry to the submenu. */ @Override public void add(SVAbstractMenuItem mli) { mi.add(mli.mi); } /** Adds a child menu to the submenu (or root node). */ @Override public void add(JMenu jli) { mi.add(jli); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.events.SVEventType; import javax.swing.JMenuItem; /** * Constructs a new menulistitem which also has a value and a description. For * these, we will not have to ask the server what the value is when the user * wants to change it, but can just call the client with the new value. */ class SVMenuItem extends SVAbstractMenuItem { public String value = null; public String desc = null; SVMenuItem(int id, String name, String v, String d) { super(id, name, new JMenuItem(name)); value = v; desc = d; } /** * Ask the user for new input for a variable and send it. * Depending on whether there is a description given for the entry, show * the description in the dialog or just show the name. */ @Override public void performAction(SVWindow window, SVEventType eventType) { if (desc != null) { window.showInputDialog(desc, value, id, eventType); } else { window.showInputDialog(name, value, id, eventType); } } /** Returns the actual value of the MenuListItem. */ @Override public String getValue() { return value; } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import javax.swing.JMenuItem; /** * Constructs a new menulistitem which just has an ID and a name attached to * it. In this case, we will have to ask for the value of the item and its * description if it gets called. */ class SVEmptyMenuItem extends SVAbstractMenuItem { SVEmptyMenuItem(int id, String name) { super(id, name, new JMenuItem(name)); } /** What to do when user clicks on this item. */ @Override public void performAction(SVWindow window, SVEventType eventType) { // Send an event indicating that someone clicked on an entry. // Value will be null here. SVEvent svme = new SVEvent(eventType, window, id, getValue()); ScrollView.addMessage(svme); } }
Java
// Copyright 2007 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); You may not // use this file except in compliance with the License. You may obtain a copy of // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. package com.google.scrollview.ui; import org.piccolo2d.nodes.PImage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; /** * The ScrollViewImageHandler is a helper class which takes care of image * processing. It is used to construct an Image from the message-stream and * basically consists of a number of utility functions to process the input * stream. * * @author wanke@google.com */ public class SVImageHandler { /* All methods are static, so we forbid to construct SVImageHandler objects */ private SVImageHandler() { } /** * Reads size bytes from the stream in and interprets it as an image file, * encoded as png, and then text-encoded as base 64, returning the decoded * bitmap. * * @param size The size of the image file. * @param in The input stream from which to read the bytes. */ public static PImage readImage(int size, BufferedReader in) { char[] charbuffer = new char[size]; int numRead = 0; while (numRead < size) { int newRead = -1; try { newRead = in.read(charbuffer, numRead, size - numRead); } catch (IOException e) { System.out.println("Failed to read image data from socket:" + e.getMessage()); return null; } if (newRead < 0) { return null; } numRead += newRead; } if (numRead != size) { System.out.println("Failed to read image data from socket"); return null; } // Convert the character data to binary. byte[] binarydata = DatatypeConverter.parseBase64Binary(new String(charbuffer)); // Convert the binary data to a byte stream and parse to image. ByteArrayInputStream byteStream = new ByteArrayInputStream(binarydata); try { PImage img = new PImage(ImageIO.read(byteStream)); return img; } catch (IOException e) { System.out.println("Failed to decode image data from socket" + e.getMessage()); } return null; } }
Java
package org.oryxeditor.buildapps.sscompress; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.json.JSONArray; import org.json.JSONObject; import org.apache.commons.codec.binary.Base64; public class SSCompressor { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { if(args.length < 1) throw new Exception("Missing argument! Usage: java SSCompressor <SSDirectory>"); //get stencil set directory from arguments String ssDirString = args[0]; //get stencil set configuration file File ssConf = new File(ssDirString + "/stencilsets.json"); if(!ssConf.exists()) throw new Exception("File " + ssDirString + "/stencilsets.json does not exist."); //read stencil set configuration StringBuffer jsonObjStr = readFile(ssConf); JSONArray jsonObj = new JSONArray(jsonObjStr.toString()); //iterate all stencil set configurations for(int i = 0; i < jsonObj.length(); i++) { JSONObject ssObj = jsonObj.getJSONObject(i); //get stencil set location if(ssObj.has("uri")) { String ssUri = ssObj.getString("uri"); File ssFile = new File(ssDirString + ssUri); if(!ssFile.exists()) throw new Exception("Stencil set " + ssDirString + ssUri + " that is referenced in stencil set configuration file does not exist."); String ssDir = ssFile.getParent(); //read stencil set file StringBuffer ssString = readFile(ssFile); // store copy of original stencilset file (w/o SVG includes) with postfix '-nosvg' int pIdx = ssUri.lastIndexOf('.'); File ssNoSvgFile = new File(ssDirString + ssUri.substring(0, pIdx) + "-nosvg" + ssUri.substring(pIdx)); writeFile(ssNoSvgFile, ssString.toString()); //***include svg files*** //get view property Pattern pattern = Pattern.compile("[\"\']view[\"\']\\s*:\\s*[\"\']\\S+[\"\']"); Matcher matcher = pattern.matcher(ssString); StringBuffer tempSS = new StringBuffer(); int lastIndex = 0; //iterate all view properties while(matcher.find()) { tempSS.append(ssString.substring(lastIndex, matcher.start())); lastIndex = matcher.end(); //get svg file name String filename = matcher.group().replaceFirst("[\"\']view[\"\']\\s*:\\s*[\"\']", ""); filename = filename.substring(0, filename.length()-1); //get svg file File svgFile = new File(ssDir + "/view/" + filename); if(!svgFile.exists()) throw new Exception("SVG File " + svgFile.getPath() + " does not exists!. Compressing stencil sets aborted!"); StringBuffer svgString = readFile(svgFile); //check, if svgString is a valid xml file /*try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder document = builder.newDocumentBuilder(); document.parse(svgString.toString()); } catch(Exception e) { throw new Exception("File " + svgFile.getCanonicalPath() + " is not a valid XML file: " + e.getMessage()); }*/ //append file content to output json file (replacing existing json file) tempSS.append("\"view\":\""); tempSS.append(svgString.toString().replaceAll("[\\t\\n\\x0B\\f\\r]", " ").replaceAll("\"", "\\\\\"")); //newSS.append(filename); tempSS.append("\""); } tempSS.append(ssString.substring(lastIndex)); //***end include svg files*** /* * BAD IDEA, BECAUSE IT INCREASES THROUGHPUT //***include png files //get icon property pattern = Pattern.compile("[\"\']icon[\"\']\\s*:\\s*[\"\']\\S+[\"\']"); matcher = pattern.matcher(tempSS); StringBuffer finalSS = new StringBuffer(); lastIndex = 0; //iterate all icon properties while(matcher.find()) { finalSS.append(tempSS.substring(lastIndex, matcher.start())); lastIndex = matcher.end(); //get icon file name String filename = matcher.group().replaceFirst("[\"\']icon[\"\']\\s*:\\s*[\"\']", ""); filename = filename.substring(0, filename.length()-1); //get icon file File pngFile = new File(ssDir + "/icons/" + filename); if(!pngFile.exists()) throw new Exception("SVG File " + pngFile.getPath() + " does not exists!. Compressing stencil sets aborted!"); StringBuffer pngString = readFile(pngFile); //append file content to output json file (replacing existing json file) finalSS.append("\"icon\":\"javascript:"); finalSS.append(encodeBase64(pngString.toString())); finalSS.append("\""); } finalSS.append(tempSS.substring(lastIndex)); //***end include png files */ //write compressed stencil set file writeFile(ssFile, tempSS.toString()); System.out.println("Compressed stencil set file " + ssFile.getCanonicalPath()); } } } private static StringBuffer readFile(File file) throws Exception { FileInputStream fin = new FileInputStream(file); StringBuffer result = new StringBuffer(); String thisLine = ""; BufferedReader myInput = new BufferedReader(new InputStreamReader(fin, "utf-8")); while ((thisLine = myInput.readLine()) != null) { result.append(thisLine); result.append("\n"); } myInput.close(); fin.close(); return result; } private static void writeFile(File file, String text) throws Exception { FileOutputStream fos = new FileOutputStream(file); BufferedWriter myOutput = new BufferedWriter(new OutputStreamWriter(fos, "utf-8")); myOutput.write(text); myOutput.flush(); myOutput.close(); fos.close(); } /*private static String encodeBase64(String text) { byte[] encoded = Base64.encodeBase64(text.getBytes()); return new String(encoded); }*/ }
Java
package org.oryxeditor.buildapps; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.util.FileCopyUtils; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.yahoo.platform.yui.compressor.JavaScriptCompressor; /** * @author Philipp Berger * */ public class ProfileCreator { /** * @param args * path to plugin dir and output dir * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws JSONException */ public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, JSONException { if (args.length != 2) { System.err.println("Wrong Number of Arguments!"); System.err.println(usage()); return; } String pluginDirPath = args[0]; ; String pluginXMLPath = pluginDirPath + "/plugins.xml";// args[0]; String profilePath = pluginDirPath + "/profiles.xml";// ; String outputPath = args[1]; File outDir = new File(outputPath); outDir.mkdir(); HashMap<String, String> nameSrc = new HashMap<String, String>(); HashMap<String, ArrayList<String>> profilName = new HashMap<String, ArrayList<String>>(); ArrayList<String> coreNames = new ArrayList<String>(); extractPluginData(pluginXMLPath, nameSrc, coreNames); extractProfileData(profilePath, profilName); for (String key : profilName.keySet()) { ArrayList<String> pluginNames = profilName.get(key); //add core plugins to each profile pluginNames.addAll(coreNames); writeProfileJS(pluginDirPath, outputPath, nameSrc, key, pluginNames); writeProfileXML(pluginXMLPath, profilePath, outputPath, key, pluginNames); } } /** * Create the profileName.js by reading all path out of the nameSrc Hashmap, the required names * are given * @param pluginDirPath * @param outputPath * @param nameSrc * plugin name to js source file * @param profileName * name of the profile, serve as name for the js file * @param pluginNames * all plugins for this profile * @throws IOException * @throws FileNotFoundException */ private static void writeProfileJS(String pluginDirPath, String outputPath, HashMap<String, String> nameSrc, String profileName, ArrayList<String> pluginNames) throws IOException, FileNotFoundException { HashSet<String> pluginNameSet = new HashSet<String>(); pluginNameSet.addAll(pluginNames); File profileFile = new File(outputPath + File.separator + profileName +"Uncompressed.js"); profileFile.createNewFile(); FileWriter writer = new FileWriter(profileFile); for (String name : pluginNameSet) { String source = nameSrc.get(name); if(source==null) throw new IllegalArgumentException("In profile '"+profileName+"' an unknown plugin is referenced named '"+ name+"'"); FileReader reader = new FileReader(pluginDirPath + File.separator + source); writer.append(FileCopyUtils.copyToString(reader)); } writer.close(); File compressOut=new File(outputPath + File.separator + profileName +".js"); FileReader reader = new FileReader(profileFile); FileWriter writer2 = new FileWriter(compressOut); try{ com.yahoo.platform.yui.compressor.JavaScriptCompressor x= new JavaScriptCompressor(reader, null); x.compress(writer2, 1, true, false, false, false); writer2.close(); reader.close(); }catch (Exception e) { /* * Fallback if yui compression fails */ System.err.println("Profile Compression failed! profile: "+compressOut.getAbsolutePath()+ " uncompressed version is used, please ensure javascript correctness and compatibility of YUI compressor with your system"); e.printStackTrace(); writer2.close(); reader.close(); FileWriter writer3 = new FileWriter(new File(outputPath + File.separator + profileName +".js")); FileReader reader1 = new FileReader(profileFile); FileCopyUtils.copy(reader1, writer3); reader1.close(); writer3.close(); } } /** * @param pluginDirPath * @param outputPath * @param ProfileName * name of the profile, serve as name for the js file * @param pluginNames * all plugins for this profile * @throws IOException * @throws FileNotFoundException * @throws JSONException */ private static void writeProfileXML(String pluginXMLPath, String profileXMLPath, String outputPath, String ProfileName, ArrayList<String> pluginNames) throws IOException, FileNotFoundException, JSONException { FileCopyUtils.copy(new FileInputStream(pluginXMLPath), new FileOutputStream(outputPath + File.separator + ProfileName + ".xml")); InputStream reader = new FileInputStream(outputPath + File.separator + ProfileName + ".xml"); DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { builder = factory.newDocumentBuilder(); Document outProfileXMLdocument = builder.parse(reader); reader = new FileInputStream(profileXMLPath); builder = factory.newDocumentBuilder(); Document profilesXMLdocument = builder.parse(reader); NodeList pluginNodeList = outProfileXMLdocument .getElementsByTagName("plugin"); Node profileNode = getProfileNodeFromDocument(ProfileName, profilesXMLdocument); if (profileNode == null) throw new IllegalArgumentException( "profile not defined in profile xml"); NamedNodeMap attr = profileNode.getAttributes(); JSONObject config=new JSONObject(); for(int i=0;i<attr.getLength();i++){ config.put(attr.item(i).getNodeName(), attr.item(i).getNodeValue()); } for (int profilePluginNodeIndex = 0; profilePluginNodeIndex < profileNode .getChildNodes().getLength(); profilePluginNodeIndex++) { Node tmpNode = profileNode.getChildNodes().item(profilePluginNodeIndex); if("plugin".equals(tmpNode.getNodeName()) || tmpNode==null) continue; JSONObject nodeObject = new JSONObject(); NamedNodeMap attr1 = tmpNode.getAttributes(); if(attr1==null) continue; for(int i=0;i<attr1.getLength();i++){ nodeObject.put(attr1.item(i).getNodeName(), attr1.item(i).getNodeValue()); } if(config.has(tmpNode.getNodeName())){ config.getJSONArray(tmpNode.getNodeName()).put(nodeObject); }else{ config.put(tmpNode.getNodeName(), new JSONArray().put(nodeObject)); } } FileCopyUtils.copy(config.toString(), new FileWriter(outputPath + File.separator+ProfileName+".conf")); // for each plugin in the copied plugin.xml for (int i = 0; i < pluginNodeList.getLength(); i++) { Node pluginNode = pluginNodeList.item(i); String pluginName = pluginNode.getAttributes().getNamedItem( "name").getNodeValue(); // if plugin is in the current profile if (pluginNames.contains(pluginName)) { // mark plugin as active ((Element) pluginNode).setAttribute("engaged", "true"); // throw new // IllegalArgumentException("profile not defined in profile xml"); // plugin defintion found copy or replace properties Node profilePluginNode = getLastPluginNode(profileNode, pluginName); if(profilePluginNode==null){ //System.out.println("Plugin: "+pluginName+" assumed to be core"); break;} saveOrUpdateProperties(pluginNode, profilePluginNode); }else{ ((Element) pluginNode).setAttribute("engaged", "false"); } } writeXMLToFile(outProfileXMLdocument, outputPath + File.separator + ProfileName + ".xml"); } catch (DOMException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } private static Node getLastPluginNode(Node profileNode, String pluginName) { Node profilePluginNode = null; // search plugin definition in profile xml for (int profilePluginNodeIndex = 0; profilePluginNodeIndex < profileNode .getChildNodes().getLength(); profilePluginNodeIndex++) { Node tmpNode = profileNode.getChildNodes().item( profilePluginNodeIndex); if (tmpNode.getAttributes() != null && tmpNode.getAttributes().getNamedItem("name") != null && tmpNode.getAttributes().getNamedItem("name") .getNodeValue().equals(pluginName)) profilePluginNode = tmpNode; } if (profilePluginNode == null) { String[] dependsOnProfiles = getDependencies(profileNode); if (dependsOnProfiles==null ||dependsOnProfiles.length == 0) { return profilePluginNode; } for (String dependsProfile : dependsOnProfiles) { profilePluginNode = getLastPluginNode( getProfileNodeFromDocument(dependsProfile, profileNode .getOwnerDocument()), pluginName); if (profilePluginNode != null) break; } // plugin definition not found, plugin defined in depended profiles // TODO handle recursive property search } ; return profilePluginNode; }; /** * @param outProfileXMLdocument * @param xmlFileName * @throws FileNotFoundException */ private static void writeXMLToFile(Document outProfileXMLdocument, String xmlFileName) throws FileNotFoundException { // ---- Use a XSLT transformer for writing the new XML file ---- try { Transformer transformer = TransformerFactory.newInstance() .newTransformer(); DOMSource source = new DOMSource(outProfileXMLdocument); FileOutputStream os = new FileOutputStream(new File(xmlFileName)); StreamResult result = new StreamResult(os); transformer.transform(source, result); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } /** * * @param pluginNode * @param profilePluginNode * @throws DOMException */ private static void saveOrUpdateProperties(Node pluginNode, Node profilePluginNode) throws DOMException { // for(String dependent:getDependencies(profilePluginNode.getParentNode())){ // saveOrUpdateProperties(pluginNode,getProfileNodeFromDocument(dependent, profilePluginNode.getOwnerDocument())); // }; // for each child node in the profile xml for (int index = 0; index < profilePluginNode.getChildNodes() .getLength(); index++) { Node profilePluginChildNode = profilePluginNode.getChildNodes() .item(index); // check if property if (profilePluginChildNode.getNodeName() == "property") { boolean found = false; // search for old definitions for (int childIndex = 0; childIndex < pluginNode .getChildNodes().getLength(); childIndex++) { Node pluginChildNode = pluginNode.getChildNodes().item( childIndex); if (pluginChildNode.getNodeName() == "property") { NamedNodeMap propertyAttributes = profilePluginChildNode .getAttributes(); for (int attrIndex = 0; attrIndex < propertyAttributes .getLength(); attrIndex++) { String newPropertyName = profilePluginChildNode .getAttributes().item(attrIndex) .getNodeName(); Node oldPropertyNode = pluginChildNode .getAttributes().getNamedItem( newPropertyName); if (oldPropertyNode != null) { // old definition found replace value found = true; String newValue = profilePluginChildNode .getAttributes().item(attrIndex).getNodeValue(); oldPropertyNode.setNodeValue(newValue); } } } } if (!found) { // no definition found add some Node property = pluginNode.getOwnerDocument() .createElement("property"); ((Element) property).setAttribute("name", profilePluginChildNode.getAttributes() .getNamedItem("name").getNodeValue()); ((Element) property).setAttribute("value", profilePluginChildNode.getAttributes() .getNamedItem("value").getNodeValue()); pluginNode.appendChild(property); } } } } /** * @param ProfileName * @param profilesXMLdocument * @throws DOMException */ private static Node getProfileNodeFromDocument(String ProfileName, Document profilesXMLdocument) throws DOMException { Node profileNode = null; NodeList profileNodes = profilesXMLdocument .getElementsByTagName("profile"); for (int i = 0; i < profileNodes.getLength(); i++) { if (profileNodes.item(i).getAttributes().getNamedItem("name") .getNodeValue().equals(ProfileName)) { profileNode = profileNodes.item(i); break; } } return profileNode; } /** * @param profilePath * @param profilName * @throws FileNotFoundException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws DOMException */ private static void extractProfileData(String profilePath, HashMap<String, ArrayList<String>> profilName) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException, DOMException { InputStream reader = new FileInputStream(profilePath); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document = factory.newDocumentBuilder().parse(reader); NodeList profiles = document.getElementsByTagName("profile"); for (int i = 0; i < profiles.getLength(); i++) { Node profile = profiles.item(i); String name = profile.getAttributes().getNamedItem("name") .getNodeValue(); profilName.put(name, new ArrayList<String>()); for (int q = 0; q < profile.getChildNodes().getLength(); q++) { if (profile.getChildNodes().item(q).getNodeName() .equalsIgnoreCase("plugin")) { profilName.get(name).add( profile.getChildNodes().item(q).getAttributes() .getNamedItem("name").getNodeValue()); } ; } } resolveDependencies(profilName, profiles); } /** * @param profilName * @param profiles * @throws DOMException */ private static void resolveDependencies( HashMap<String, ArrayList<String>> profilName, NodeList profiles) throws DOMException { HashMap<String, String[]> profileDepends = new HashMap<String, String[]>(); for (int i = 0; i < profiles.getLength(); i++) { Node profile = profiles.item(i); String name = profile.getAttributes().getNamedItem("name") .getNodeValue(); profileDepends.put(name, getDependencies(profile)); } ArrayList<String> completedProfiles = new ArrayList<String>(); for (String key : profileDepends.keySet()) { if (profileDepends.get(key) == null) { completedProfiles.add(key); } } for (String cur : completedProfiles) profileDepends.remove(cur); while (!profileDepends.isEmpty()) { for (String key : profileDepends.keySet()) { boolean allIn = true; for (String name : profileDepends.get(key)) { if (!completedProfiles.contains(name)) { allIn = false; break; } } if (allIn) { for (String name : profileDepends.get(key)) { profilName.get(key).addAll(profilName.get(name)); completedProfiles.add(key); } } } for (String cur : completedProfiles) profileDepends.remove(cur); } } /** * @param profile * DocumentNode containing a profile * @throws DOMException */ private static String[] getDependencies(Node profil) throws DOMException { String[] dependencies = null; if (profil.getAttributes().getNamedItem("depends") != null) { dependencies = profil.getAttributes().getNamedItem("depends") .getNodeValue().split(","); } return dependencies; } /** * @param pluginXMLPath * @param nameSrc * HashMap links Pluginnames and Sourcefiles * @param coreNames * ArrayList containing Names of all core plugins * @throws FileNotFoundException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws DOMException */ private static void extractPluginData(String pluginXMLPath, HashMap<String, String> nameSrc, ArrayList<String> coreNames) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException, DOMException { InputStream reader = new FileInputStream(pluginXMLPath); DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); Document document = builder.parse(reader); NodeList plugins = document.getElementsByTagName("plugin"); for (int i = 0; i < plugins.getLength(); i++) { String name = plugins.item(i).getAttributes().getNamedItem("name") .getNodeValue(); String src = plugins.item(i).getAttributes().getNamedItem("source") .getNodeValue(); assert (src!=null); nameSrc.put(name, src); if (plugins.item(i).getAttributes().getNamedItem("core") != null) { if (plugins.item(i).getAttributes().getNamedItem("core") .getNodeValue().equalsIgnoreCase("true")) { coreNames.add(name); } } } } public static String usage() { String use = "Profiles Creator\n" + "Use to parse the profiles.xml and creates\n" + "for each profile an .js-source. Therefore additional\n" + "information from the plugins.xml is required.\n" + "usage:\n" + "java ProfileCreator pluginPath outputDir"; return use; } }
Java
package com.example.Sorteando; import java.util.Collections; import java.util.List; public class Embaralhar { public List <String> embra(List<String> lists){ Collections.shuffle(lists); return lists; } }
Java
package com.example.Sorteando; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; public class LoadingTask extends AsyncTask<String, Integer, Integer> { public interface LoadingTaskFinishedListener { void onTaskFinished(); // If you want to pass something back to the listener add a param to this method } // This is the progress bar you want to update while the task is in progress private final ProgressBar progressBar; // This is the listener that will be told when this task is finished private final LoadingTaskFinishedListener finishedListener; /** * A Loading task that will load some resources that are necessary for the app to start * @param progressBar - the progress bar you want to update while the task is in progress * @param finishedListener - the listener that will be told when this task is finished */ public LoadingTask(ProgressBar progressBar, LoadingTaskFinishedListener finishedListener) { this.progressBar = progressBar; this.finishedListener = finishedListener; } protected Integer doInBackground(String... params) { Log.i("Tutorial", "Starting task with url: "+params[0]); if(resourcesDontAlreadyExist()){ downloadResources(); } // Perhaps you want to return something to your post execute return 1234; } private boolean resourcesDontAlreadyExist() { // Here you would query your app's internal state to see if this download had been performed before // Perhaps once checked save this in a shared preference for speed of access next time return true; // returning true so we show the splash every time } private void downloadResources() { // We are just imitating some process thats takes a bit of time (loading of resources / downloading) int count = 10; for (int i = 0; i < count; i++) { // Update the progress bar after every step int progress = (int) ((i / (float) count) * 100); publishProgress(progress); // Do some long loading things try { Thread.sleep(1000); } catch (InterruptedException ignore) {} } } protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressBar.setProgress(values[0]); // This is ran on the UI thread so it is ok to update our progress bar ( a UI view ) here } protected void onPostExecute(Integer result) { super.onPostExecute(result); finishedListener.onTaskFinished(); // Tell whoever was listening we have finished } }
Java
package com.example.Sorteando; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Window; import android.widget.ProgressBar; import com.example.Sorteando.LoadingTask.LoadingTaskFinishedListener; public class inicoactivity extends Activity implements LoadingTaskFinishedListener{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); // Show the splash screen setContentView(R.layout.inicioactivity); // Find the progress bar ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1); // Start your loading new LoadingTask(progressBar, this).execute("http://tecksoft.com.br/"); // Pass in whatever you need a url is just an example we don't use it in this tutorial } // This is the callback for when your async task has finished @Override public void onTaskFinished() { completeSplash(); } private void completeSplash(){ startApp(); finish(); // Don't forget to finish this Splash Activity so the user can't return to it! } private void startApp() { Intent intent = new Intent(inicoactivity.this, add_activity.class); startActivity(intent); } }
Java
package foundation.data; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import com.mysport.ui.R; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.DatabaseTableConfig; import com.j256.ormlite.table.DatabaseTableConfigLoader; import com.j256.ormlite.table.TableUtils; /** * * @author 福建师范大学软件学院 陈贝、刘大刚 * */ public class DataHelper extends OrmLiteSqliteOpenHelper { private static final int DATABASE_VERSION = 1; private Context context; public DataHelper(Context context,String dataFileName) { super(context, dataFileName, null, DATABASE_VERSION, R.raw.ormlite_config); this.context = context; } @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { // create database this.createTable(db, connectionSource); } @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int arg2, int arg3) { // update database this.updateTable(db, connectionSource); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); Log.d("DataHelper", "database is opened"); } @Override public void close() { super.close(); Log.d("DataHelper", "database is closed"); } private void createTable(SQLiteDatabase db,ConnectionSource connectionSource) { try { Log.d("DataHelper", "create database"); InputStream is = this.context.getResources().openRawResource( R.raw.ormlite_config); InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr, 4096); List<DatabaseTableConfig<?>> tableConfigs = DatabaseTableConfigLoader .loadDatabaseConfigFromReader(reader); for (DatabaseTableConfig<?> databaseTableConfig : tableConfigs) { TableUtils.createTableIfNotExists(connectionSource, databaseTableConfig); } is.close(); isr.close(); reader.close(); } catch (Exception e) { Log.e(DataHelper.class.getName(), "创建数据库失败" + e.getCause()); e.printStackTrace(); } } private void updateTable(SQLiteDatabase db, ConnectionSource connectionSource) { try { Log.d("DataHelper", "Update Database"); InputStream is = this.context.getResources().openRawResource( R.raw.ormlite_config); InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr, 4096); List<DatabaseTableConfig<?>> tableConfigs = DatabaseTableConfigLoader .loadDatabaseConfigFromReader(reader); for (DatabaseTableConfig<?> databaseTableConfig : tableConfigs) { TableUtils.dropTable(connectionSource, databaseTableConfig, true); } is.close(); isr.close(); reader.close(); onCreate(db, connectionSource); } catch (Exception e) { Log.e(DataHelper.class.getName(), "更新数据库失败" + e.getMessage()); e.printStackTrace(); } } }
Java
package foundation.data; import java.sql.SQLException; import java.util.List; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.PreparedDelete; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; /** * * @author 福建师范大学软件学院 陈贝、刘大刚 * */ public interface IDataContext { // 增加 public abstract <T, ID> void add(T item, Class<T> dataClass, Class<ID> idClass) throws SQLException; // 删除 public abstract <T, ID> void delete(T item, Class<T> dataClass, Class<ID> idClass) throws SQLException; //通用删除 public abstract <T,ID> void delete(Class<T> dataClass, Class<ID> idClass,PreparedDelete<T> preparedDelete) throws SQLException; // 更新 public abstract <T, ID> void update(T item, Class<T> dataClass, Class<ID> idClass) throws SQLException; // 根据ID查询 public abstract <T, ID, K extends ID> T queryById(Class<T> dataClass, Class<K> idClass, ID id) throws SQLException; // 查询全部 public abstract <T, ID> List<T> queryForAll(Class<T> dataClass, Class<ID> idClass) throws SQLException; // 根据条件查询 public abstract <T, ID> List<String[]> queryBySql(Class<T> dataClass, Class<ID> idClass, String query) throws SQLException; // 获取全部记录数 public abstract <T, ID> long countof(Class<T> dataClass, Class<ID> idClass) throws SQLException; // 获取符合条件的记录数 public abstract <T, ID> long countof(Class<T> dataClass, Class<ID> idClass, PreparedQuery<T> query) throws SQLException; // 按id删除记录 public abstract <T, ID, K extends ID> void deleteById(ID id, Class<T> dataClass, Class<K> idClass) throws SQLException; //删除所有记录 public abstract <T, ID> void deleteAll(Class<T> dataClass, Class<ID> idClass) throws SQLException ; /** * 通用查询 * * @param <T> * @param <ID> * @param dataClass * @param idClass * @param query * @return * @throws SQLException */ public abstract <T, ID> List<T> query(Class<T> dataClass, Class<ID> idClass, PreparedQuery<T> query) throws SQLException; /** * 获取QueryBuilder * * @param <T> * @param <ID> * @param dataClass * @param idClass * @return * @throws SQLException */ public abstract <T, ID> QueryBuilder<T, ID> getQueryBuilder( Class<T> dataClass, Class<ID> idClass) throws SQLException; /** * 获取DeleteBuilder * @param dataClass * @param idClass * @return * @throws SQLException */ public abstract <T, ID> DeleteBuilder<T, ID> getDeleteBuilder( Class<T> dataClass, Class<ID> idClass) throws SQLException; /** * 开始事务 */ public abstract void beginTransaction(); // 提交事务 public abstract void commit(); // 回滚事务 public abstract void rollback(); }
Java
package foundation.data; import java.sql.SQLException; import java.util.List; import android.database.sqlite.SQLiteDatabase; import app.MyApplication; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.PreparedDelete; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.support.ConnectionSource; /** * * @author 福建师范大学软件学院 陈贝、刘大刚 * */ public class DataContext implements IDataContext { private ConnectionSource connectionSource;//数据库连接 private SQLiteDatabase db; // 事务管理 public DataContext() { connectionSource = MyApplication.DATAHELPER.getConnectionSource(); db = MyApplication.DATAHELPER.getWritableDatabase(); } // 增加 public <T, ID> void add(T item, Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); dao.create(item); } // 删除 public <T, ID> void delete(T item, Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); dao.delete(item); } //删除所有记录 public <T, ID> void deleteAll(Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); List<T> list=dao.queryForAll(); dao.delete(list); } // 按ID删除 public <T, ID, K extends ID> void deleteById(ID id, Class<T> dataClass, Class<K> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); dao.deleteById(id); } //删除BUilder public <T, ID> DeleteBuilder<T, ID> getDeleteBuilder(Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.deleteBuilder(); } //通用删除 public <T, ID> void delete(Class<T> dataClass, Class<ID> idClass, PreparedDelete<T> preparedDelete) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); dao.delete(preparedDelete); } // 更新 public <T, ID> void update(T item, Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); dao.update(item); } // 根据ID查询 public <T, ID, K extends ID> T queryById(Class<T> dataClass, Class<K> idClass, ID id) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.queryForId(id); } // 查询所有记录 public <T, ID> List<T> queryForAll(Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.queryForAll(); } // 根据SQL语句查询 public <T, ID> List<String[]> queryBySql(Class<T> dataClass, Class<ID> idClass, String sql) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); GenericRawResults<String[]> rawResults = dao.queryRaw(sql); List<String[]> list = rawResults.getResults(); return list; } // 通用查询 public <T, ID> List<T> query(Class<T> dataClass, Class<ID> idClass, PreparedQuery<T> query) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.query(query); } // 获取所有记录数 public <T, ID> long countof(Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.countOf(); } // 获取指定条件的记录数 public <T, ID> long countof(Class<T> dataClass, Class<ID> idClass, PreparedQuery<T> query) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.countOf(query); } // 获取QueryBuilder public <T, ID> QueryBuilder<T, ID> getQueryBuilder(Class<T> dataClass, Class<ID> idClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dao.queryBuilder(); } // 开始事务 public void beginTransaction() { db.beginTransaction(); } // 提交事务 public void commit() { db.setTransactionSuccessful(); } // 回滚事务 public void rollback() { db.endTransaction(); } }
Java
package foundation.webservice; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; public class WeatherService { //定义Web Service 的命名空间 static final String SERVICE_NS = "http://WebXml.com.cn/"; //定义Web Service提供服务的URL static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx"; //调用远程Web Service获取省份列表 public static List<String> getProviceList() { //调用的方法 final String methodName = "getRegionProvince"; //创建HttpTransportSE传输对象 final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL); ht.debug = true; //使用SOAP1.1协议创建Envelop 对象 final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); //实例化SoapObject对象 SoapObject soapObject = new SoapObject(SERVICE_NS,methodName); envelope.bodyOut = soapObject; //设置与。net提供的Web Service 保持较好的兼容性 envelope.dotNet = true; FutureTask<List<String>> task = new FutureTask<List<String>>( new Callable<List<String>>() { @Override public List<String> call() throws Exception { //调用Web Service ht.call(SERVICE_NS + methodName,envelope); if(envelope.getResponse() != null) { //获取服务器响应返回的SOAP消息 SoapObject result = (SoapObject) envelope.bodyIn; SoapObject detail = (SoapObject) result.getProperty(methodName + "Result"); //解析服务器响应的SOAP消息 return parseProvinceOrCity(detail); } return null; } }); new Thread(task).start(); try { return task.get(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } //根据省份获取城市列表 public static List<String> getCityListByProvince(String province) { //调用方法 final String methodName = "getSupportCityString"; //创建HttpTransportSE传输对象 final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL); ht.debug = true; //实例化SoapObject对象 SoapObject soapObject = new SoapObject(SERVICE_NS,methodName); //添加一个请求参数 soapObject.addProperty("theRegionCode", province); //使用SOAP1.1协议创建Envelop对象 final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = soapObject; //设置与。net提供的Web Service 保持较好的兼容性 envelope.dotNet = true;// FutureTask<List<String>> task = new FutureTask<List<String>>( new Callable<List<String>>() { @Override public List<String> call() throws Exception { //调用Web service ht.call(SERVICE_NS + methodName, envelope); if(envelope.getResponse() != null) { //获取服务器响应返回的SOAP消息 SoapObject result = (SoapObject) envelope.bodyIn; SoapObject detail = (SoapObject) result.getProperty(methodName + "Result"); //解析服务器响应的SOAP消息 return parseProvinceOrCity(detail); } return null; } }); new Thread(task).start(); try { return task.get(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } private static List<String> parseProvinceOrCity(SoapObject detail) { // TODO 自动生成的方法存根 ArrayList<String> result = new ArrayList<String>(); for(int i=0; i<detail.getPropertyCount(); i++) { //解析出每个省份 result.add(detail.getProperty(i).toString().split(",")[0]); } return result; } public static SoapObject getWeatherByCity(String cityName) { final String methodName = "getWeather"; final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL); ht.debug = true; final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); SoapObject soapObject = new SoapObject(SERVICE_NS,methodName); soapObject.addProperty("theCityCode",cityName); envelope.bodyOut = soapObject; //设置与。net提供的Web Service保持较好的兼容性 envelope.dotNet = true; FutureTask<SoapObject> task = new FutureTask<SoapObject>( new Callable<SoapObject>(){ @Override public SoapObject call() throws Exception { ht.call(SERVICE_NS + methodName, envelope); SoapObject result = (SoapObject) envelope.bodyIn; SoapObject detail = (SoapObject) result.getProperty(methodName + "Result"); return detail; } }); new Thread(task).start(); try { return task.get(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } }
Java
package foundation.webservice; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class GeocodeService { public static JSONObject geocodeAddr(double lat, double lng) { String urlString = "http://maps.google.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true&language=zh-CN"; StringBuilder sTotalString = new StringBuilder(); try { URL url = new URL(urlString); URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; InputStream urlStream = httpConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlStream)); String sCurrentLine = ""; while ((sCurrentLine = bufferedReader.readLine()) != null) { sTotalString.append(sCurrentLine); System.out.println(); } //System.out.println(sTotalString); bufferedReader.close(); httpConnection.disconnect(); // 关闭http连接 } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(sTotalString.toString()); } catch (JSONException e) { e.printStackTrace(); } return jsonObject; } /** * * @param lat * @param lng * @param i 0街道,1区,2市,3国家 * @return */ public static String getAddressByLatLng(double lat, double lng, int i) { String address = null; JSONObject jsonObject = geocodeAddr(lat, lng); try { JSONArray placemarks = jsonObject.getJSONArray("results"); JSONObject place = placemarks.getJSONObject(0); JSONArray detail = place.getJSONArray("address_components"); JSONObject add = detail.getJSONObject(i); address = add.getString("long_name"); } catch (Exception e) { e.printStackTrace(); } return address; } }
Java
package tool.data; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import android.os.Bundle; import domain.businessEntity.gps.ClimbData; public class ClimbDataUtil { /** * @param args */ private static final String startAltitude = null; private static final String stopAltitude = null; private static final String startTime = null; private static final String stopTime = null; private static final String longitude =null; private static final String latitude =null; private static Date date1; private static Date date2; public static Bundle writeCardtoBundle(ClimbData climbdat){ Bundle bundle = new Bundle(); bundle.putInt("startAltitude", climbdat.getStartAltitude()); bundle.putInt("stopAltitude", climbdat.getStopAltitude()); bundle.putString("startTime", climbdat.getStartTime().toString()); bundle.putString("stopTime", climbdat.getStopTime().toString()); bundle.putDouble("longitude", climbdat.getLongitude()); bundle.putDouble("latitude", climbdat.getLatitude()); return bundle; } public static ClimbData readCardFromBundle(Bundle bundle){ ClimbData climbdat = new ClimbData(); climbdat.setStartAltitude(bundle.getInt("startAltitude")); climbdat.setStopAltitude(bundle.getInt("stopAltitude")); SimpleDateFormat sdf = new SimpleDateFormat("HH:MI:SS"); try { date1 = sdf.parse(bundle.getString("startTime")); date2 = sdf.parse(bundle.getString("stopTime")); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } climbdat.setStartTime(date1); climbdat.setStopTime(date2); climbdat.setLongitude(bundle.getDouble("longitude")); climbdat.setLatitude(bundle.getDouble("latitude")); return climbdat; } }
Java
package tool.data; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import android.os.Environment; import com.j256.ormlite.android.apptools.OrmLiteConfigUtil; /** * 生成ORM映射文件 * * @author 福建师范大学软件学院 陈贝、刘大刚 * @since 2012-6-8 * */ public class DatabaseConfigUtil extends OrmLiteConfigUtil { public static String BUSINESSENTITYPKGNAME = "domain.businessEntity"; public static void main(String[] args) throws Exception { Set<Class<?>> clses = getClasses(BUSINESSENTITYPKGNAME); if (clses == null) { return; } int len = clses.size(); Class<?>[] classes = new Class<?>[len]; int i = 0; for (Class<?> cls : clses) { classes[i] = cls; i++; } writeConfigFile("ormlite_config.txt", classes); } public static Set<Class<?>> getClasses(String pack) { // 第一个class类的集合 Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); // 是否循环迭代 boolean recursive = true; // 获取包的名字 并进行替换 String packageName = pack; String packageDirName = packageName.replace('.', '/'); // 定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader() .getResources(packageDirName); while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } }// 循环迭代下去 } catch (IOException e) { e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * * @param packageName * @param packagePath * @param recursive * @param classes */ public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile( packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 classes.add(Thread.currentThread().getContextClassLoader() .loadClass(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log.error("添加用户类错误,找不到此类的.class文件"); e.printStackTrace(); } } } } }
Java
package tool.SunriseSunset; /****************************************************************************** * * SunriseSunset.java * ******************************************************************************* * * Java Class: SunriseSunset * * This Java class is part of a collection of classes developed for the * reading and processing of oceanographic and meterological data collected * since 1970 by environmental buoys and stations. This dataset is * maintained by the National Oceanographic Data Center and is publicly * available. These Java classes were written for the US Environmental * Protection Agency's National Exposure Research Laboratory under Contract * No. GS-10F-0073K with Neptune and Company of Los Alamos, New Mexico. * * Purpose: * * This Java class performs calculations to determine the time of * sunrise and sunset given lat, long, and date. * * Inputs: * * Latitude, longitude, date/time, and time zone. * * Outputs: * * Local time of sunrise and sunset as calculated by the * program. * If no sunrise or no sunset occurs, or if the sun is up all day * or down all day, appropriate boolean values are set. * A boolean is provided to identify if the time provided is during the day. * * The above values are accessed by the following methods: * * Date getSunrise() returns date/time of sunrise * Date getSunset() returns date/time of sunset * boolean isSunrise() returns true if there was a sunrise, else false * boolean isSunset() returns true if there was a sunset, else false * boolean isSunUp() returns true if sun is up all day, else false * boolean isSunDown() returns true if sun is down all day, else false * boolean isDaytime() returns true if sun is up at the time * specified, else false * * Required classes from the Java library: * * java.util.Date * java.text.SimpleDateFormat * java.text.ParseException; * java.math.BigDecimal; * * Package of which this class is a member: * * default * * Known limitations: * * It is assumed that the data provided are within valie ranges * (i.e. latitude between -90 and +90, longitude between 0 and 360, * a valid date, and time zone between -14 and +14. * * Compatibility: * * Java 1.1.8 * * References: * * The mathematical algorithms used in this program are patterned * after those debveloped by Roger Sinnott in his BASIC program, * SUNUP.BAS, published in Sky & Telescope magazine: * Sinnott, Roger W. "Sunrise and Sunset: A Challenge" * Sky & Telescope, August, 1994 p.84-85 * * The following is a cross-index of variables used in SUNUP.BAS. * A single definition from multiple reuse of variable names in * SUNUP.BAS was clarified with various definitions in this program. * * SUNUP.BAS this class * * A dfA * A(2) dfAA1, dfAA2 * A0 dfA0 * A2 dfA2 * A5 dfA5 * AZ Not used * C dfCosLat * C0 dfC0 * D iDay * D(2) dfDD1, dfDD2 * D0 dfD0 * D1 dfD1 * D2 dfD2 * D5 dfD5 * D7 Not used * DA dfDA * DD dfDD * G bGregorian, dfGG * H dfTimeZone * H0 dfH0 * H1 dfH1 * H2 dfH2 * H3 dfHourRise, dfHourSet * H7 Not used * J dfJ * J3 dfJ3 * K1 dfK1 * L dfLL * L0 dfL0 * L2 dfL2 * L5 dfLon * M iMonth * M3 dfMinRise, dfMinSet * N7 Not used * P dfP * S iSign, dfSinLat, dfSS * T dfT * T0 dfT0 * T3 not used * TT dfTT * U dfUU * V dfVV * V0 dfV0 * V1 dfV1 * V2 dfV2 * W dfWW * Y iYear * Z dfZenith * Z0 dfTimeZone * * * Author/Company: * * JDT: John Tauxe, Neptune and Company * JMG: Jo Marie Green * * Change log: * * date ver by description of change * _________ _____ ___ ______________________________________________ * 5 Jan 01 0.006 JDT Excised from ssapp.java v. 0.005. * 11 Jan 01 0.007 JDT Minor modifications to comments based on * material from Sinnott, 1994. * 7 Feb 01 0.008 JDT Fixed backwards time zone. The standard is that * local time zone is specified in hours EAST of * Greenwich, so that EST would be -5, for example. * For some reason, SUNUP.BAS does this backwards * (probably an americocentric perspective) and * SunriseSunset adopted that convention. Oops. * So the sign in the math is changed. * 7 Feb 01 0.009 JDT Well, that threw off the azimuth calculation... * Removed the azimuth calculations. * 14 Feb 01 0.010 JDT Added ability to accept a time (HH:mm) in * dateInput, and decide if that time is daytime * or nighttime. * 27 Feb 01 0.011 JDT Added accessor methods in place of having public * variables to get results. * 28 Feb 01 0.012 JDT Cleaned up list of imported classes. * 28 Mar 01 1.10 JDT Final version accompanying deliverable 1b. * 4 Apr 01 1.11 JDT Moved logic supporting .isDaytime into method. * Moved calculations out of constructor. * 01 May 01 1.12 JMG Added 'GMT' designation and testing lines. * 16 May 01 1.13 JDT Added setLenient( false ) and setTimeZone( tz ) * to dfmtDay, dfmtMonth, and dfmtYear in * doCalculations. * 27 Jun 01 1.14 JDT Removed reliance on StationConstants (GMT). * 13 Aug 01 1.20 JDT Final version accompanying deliverable 1c. * 6 Sep 01 1.21 JDT Thorough code and comment review. * 21 Sep 01 1.30 JDT Final version accompanying deliverable 2. * 17 Dec 01 1.40 JDT Version accompanying final deliverable. * *----------------------------------------------------------------------------*/ // Import required classes and packages import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; import java.math.BigDecimal; import java.util.TimeZone; /****************************************************************************** * class: SunriseSunset class ******************************************************************************* * * This Java class performs calculations to determine the time of * sunrise and sunset given lat, long, and date. * * It is assumed that the data provided are within valie ranges * (i.e. latitude between -90 and +90, longitude between 0 and 360, * a valid date, and time zone between -14 and +14. * *----------------------------------------------------------------------------*/ public class SunriseSunset { // Declare and initialize variables private double dfLat; // latitude from user private double dfLon; // latitude from user private Date dateInput; // date/time from user private double dfTimeZone; // time zone from user private Date dateSunrise; // date and time of sunrise private Date dateSunset; // date and time of sunset private boolean bSunriseToday = false; // flag for sunrise on this date private boolean bSunsetToday = false; // flag for sunset on this date private boolean bSunUpAllDay = false; // flag for sun up all day private boolean bSunDownAllDay = false; // flag for sun down all day private boolean bDaytime = false; // flag for daytime, given // hour and min in dateInput private boolean bSunrise = false; // sunrise during hour checked private boolean bSunset = false; // sunset during hour checked private boolean bGregorian = false; // flag for Gregorian calendar private int iJulian; // Julian day private int iYear; // year of date of interest private int iMonth; // month of date of interest private int iDay; // day of date of interest private int iCount; // a simple counter private int iSign; // SUNUP.BAS: S private double dfHourRise, dfHourSet; // hour of event: SUNUP.BAS H3 private double dfMinRise, dfMinSet; // minute of event: SUNUP.BAS M3 private double dfSinLat, dfCosLat; // sin and cos of latitude private double dfZenith; // SUNUP.BAS Z: Zenith private SimpleDateFormat dfmtDate; // formatting for date alone private SimpleDateFormat dfmtDateTime; // formatting for date and time private SimpleDateFormat dfmtYear; // formatting for year private SimpleDateFormat dfmtMonth; // formatting for month private SimpleDateFormat dfmtDay; // formatting for day // Many variables in SUNUP.BAS have undocumented meanings, // and so are translated rather directly to avoid confusion: private double dfAA1 = 0, dfAA2 = 0; // SUNUP.BAS A(2) private double dfDD1 = 0, dfDD2 = 0; // SUNUP.BAS D(2) private double dfC0; // SUNUP.BAS C0 private double dfK1; // SUNUP.BAS K1 private double dfP; // SUNUP.BAS P private double dfJ; // SUNUP.BAS J private double dfJ3; // SUNUP.BAS J3 private double dfA; // SUNUP.BAS A private double dfA0, dfA2, dfA5; // SUNUP.BAS A0, A2, A5 private double dfD0, dfD1, dfD2, dfD5; // SUNUP.BAS D0, D1, D2, D5 private double dfDA, dfDD; // SUNUP.BAS DA, DD private double dfH0, dfH1, dfH2; // SUNUP.BAS H0, H1, H2 private double dfL0, dfL2; // SUNUP.BAS L0, L2 private double dfT, dfT0, dfTT; // SUNUP.BAS T, T0, TT private double dfV0, dfV1, dfV2; // SUNUP.BAS V0, V1, V2 private TimeZone tz = TimeZone.getTimeZone( "GMT" ); /****************************************************************************** * method: SunriseSunset ******************************************************************************* * * Constructor for SunriseSunset class. * *----------------------------------------------------------------------------*/ public SunriseSunset( double dfLatIn, // latitude double dfLonIn, // longitude Date dateInputIn, // date double dfTimeZoneIn // time zone ) { // Copy values supplied as agruments to local variables. dfLat = dfLatIn; dfLon = dfLonIn; dateInput = dateInputIn; dfTimeZone = dfTimeZoneIn; // Call the method to do the calculations. doCalculations(); } // end of class constructor /****************************************************************************** * method: doCalculations ******************************************************************************* * * Method for performing the calculations done in SUNUP.BAS. * *----------------------------------------------------------------------------*/ private void doCalculations() { try { // Break out day, month, and year from date provided. // (This is necesary for the math algorithms.) dfmtYear = new SimpleDateFormat( "yyyy" ); dfmtYear.setLenient( false ); dfmtYear.setTimeZone( tz ); dfmtMonth = new SimpleDateFormat( "M" ); dfmtMonth.setLenient( false ); dfmtMonth.setTimeZone( tz ); dfmtDay = new SimpleDateFormat( "d" ); dfmtDay.setLenient( false ); dfmtDay.setTimeZone( tz ); iYear = Integer.parseInt( dfmtYear.format( dateInput ) ); iMonth = Integer.parseInt( dfmtMonth.format( dateInput ) ); iDay = Integer.parseInt( dfmtDay.format( dateInput ) ); // Convert time zone hours to decimal days (SUNUP.BAS line 50) dfTimeZone = dfTimeZone / 24.0; // NOTE: (7 Feb 2001) Here is a non-standard part of SUNUP.BAS: // It (and this algorithm) assumes that the time zone is // positive west, instead of the standard negative west. // Classes calling SunriseSunset will be assuming that // times zones are specified in negative west, so here the // sign is changed so that the SUNUP algorithm works: dfTimeZone = -dfTimeZone; // Convert longitude to fraction (SUNUP.BAS line 50) dfLon = dfLon / 360.0; // Convert calendar date to Julian date: // Check to see if it's later than 1583: Gregorian calendar // When declared, bGregorian is initialized to false. // ** Consider making a separate class of this function. ** if( iYear >= 1583 ) bGregorian = true; // SUNUP.BAS 1210 dfJ = -Math.floor( 7.0 // SUNUP used INT, not floor * ( Math.floor( ( iMonth + 9.0 ) / 12.0 ) + iYear ) / 4.0 ) // add SUNUP.BAS 1240 and 1250 for G = 0 + Math.floor( iMonth * 275.0 / 9.0 ) + iDay + 1721027.0 + iYear * 367.0; if ( bGregorian ) { // SUNUP.BAS 1230 if ( ( iMonth - 9.0 ) < 0.0 ) iSign = -1; else iSign = 1; dfA = Math.abs( iMonth - 9.0 ); // SUNUP.BAS 1240 and 1250 dfJ3 = -Math.floor( ( Math.floor( Math.floor( iYear + (double)iSign * Math.floor( dfA / 7.0 ) ) / 100.0 ) + 1.0 ) * 0.75 ); // correct dfJ as in SUNUP.BAS 1240 and 1250 for G = 1 dfJ = dfJ + dfJ3 + 2.0; } // SUNUP.BAS 1290 iJulian = (int)dfJ - 1; // SUNUP.BAS 60 and 70 (see also line 1290) dfT = (double)iJulian - 2451545.0 + 0.5; dfTT = dfT / 36525.0 + 1.0; // centuries since 1900 // Calculate local sidereal time at 0h in zone time // SUNUP.BAS 410 through 460 dfT0 = ( dfT * 8640184.813 / 36525.0 + 24110.5 + dfTimeZone * 86636.6 + dfLon * 86400.0 ) / 86400.0; dfT0 = dfT0 - Math.floor( dfT0 ); // NOTE: SUNUP.BAS uses INT() dfT0 = dfT0 * 2.0 * Math.PI; // SUNUP.BAS 90 dfT = dfT + dfTimeZone; // SUNUP.BAS 110: Get Sun's position for( iCount=0; iCount<=1; iCount++ ) // Loop thru only twice { // Calculate Sun's right ascension and declination // at the start and end of each day. // SUNUP.BAS 910 - 1160: Fundamental arguments // from van Flandern and Pulkkinen, 1979 // declare local temporary doubles for calculations double dfGG; // SUNUP.BAS G double dfLL; // SUNUP.BAS L double dfSS; // SUNUP.BAS S double dfUU; // SUNUP.BAS U double dfVV; // SUNUP.BAS V double dfWW; // SUNUP.BAS W dfLL = 0.779072 + 0.00273790931 * dfT; dfLL = dfLL - Math.floor( dfLL ); dfLL = dfLL * 2.0 * Math.PI; dfGG = 0.993126 + 0.0027377785 * dfT; dfGG = dfGG - Math.floor( dfGG ); dfGG = dfGG * 2.0 * Math.PI; dfVV = 0.39785 * Math.sin( dfLL ) - 0.01000 * Math.sin( dfLL - dfGG ) + 0.00333 * Math.sin( dfLL + dfGG ) - 0.00021 * Math.sin( dfLL ) * dfTT; dfUU = 1 - 0.03349 * Math.cos( dfGG ) - 0.00014 * Math.cos( dfLL * 2.0 ) + 0.00008 * Math.cos( dfLL ); dfWW = - 0.00010 - 0.04129 * Math.sin( dfLL * 2.0 ) + 0.03211 * Math.sin( dfGG ) - 0.00104 * Math.sin( 2.0 * dfLL - dfGG ) - 0.00035 * Math.sin( 2.0 * dfLL + dfGG ) - 0.00008 * Math.sin( dfGG ) * dfTT; // Compute Sun's RA and Dec; SUNUP.BAS 1120 - 1140 dfSS = dfWW / Math.sqrt( dfUU - dfVV * dfVV ); dfA5 = dfLL + Math.atan( dfSS / Math.sqrt( 1.0 - dfSS * dfSS )); dfSS = dfVV / Math.sqrt( dfUU ); dfD5 = Math.atan( dfSS / Math.sqrt( 1 - dfSS * dfSS )); // Set values and increment t if ( iCount == 0 ) // SUNUP.BAS 125 { dfAA1 = dfA5; dfDD1 = dfD5; } else // SUNUP.BAS 145 { dfAA2 = dfA5; dfDD2 = dfD5; } dfT = dfT + 1.0; // SUNUP.BAS 130 } // end of Get Sun's Position for loop if ( dfAA2 < dfAA1 ) dfAA2 = dfAA2 + 2.0 * Math.PI; // SUNUP.BAS 150 dfZenith = Math.PI * 90.833 / 180.0; // SUNUP.BAS 160 dfSinLat = Math.sin( dfLat * Math.PI / 180.0 ); // SUNUP.BAS 170 dfCosLat = Math.cos( dfLat * Math.PI / 180.0 ); // SUNUP.BAS 170 dfA0 = dfAA1; // SUNUP.BAS 190 dfD0 = dfDD1; // SUNUP.BAS 190 dfDA = dfAA2 - dfAA1; // SUNUP.BAS 200 dfDD = dfDD2 - dfDD1; // SUNUP.BAS 200 dfK1 = 15.0 * 1.0027379 * Math.PI / 180.0; // SUNUP.BAS 330 // Initialize sunrise and sunset times, and other variables // hr and min are set to impossible times to make errors obvious dfHourRise = 99.0; dfMinRise = 99.0; dfHourSet = 99.0; dfMinSet = 99.0; dfV0 = 0.0; // initialization implied by absence in SUNUP.BAS dfV2 = 0.0; // initialization implied by absence in SUNUP.BAS // Test each hour to see if the Sun crosses the horizon // and which way it is heading. for( iCount=0; iCount<24; iCount++ ) // SUNUP.BAS 210 { double tempA; // SUNUP.BAS A double tempB; // SUNUP.BAS B double tempD; // SUNUP.BAS D double tempE; // SUNUP.BAS E dfC0 = (double)iCount; dfP = ( dfC0 + 1.0 ) / 24.0; // SUNUP.BAS 220 dfA2 = dfAA1 + dfP * dfDA; // SUNUP.BAS 230 dfD2 = dfDD1 + dfP * dfDD; // SUNUP.BAS 230 dfL0 = dfT0 + dfC0 * dfK1; // SUNUP.BAS 500 dfL2 = dfL0 + dfK1; // SUNUP.BAS 500 dfH0 = dfL0 - dfA0; // SUNUP.BAS 510 dfH2 = dfL2 - dfA2; // SUNUP.BAS 510 // hour angle at half hour dfH1 = ( dfH2 + dfH0 ) / 2.0; // SUNUP.BAS 520 // declination at half hour dfD1 = ( dfD2 + dfD0 ) / 2.0; // SUNUP.BAS 530 // Set value of dfV0 only if this is the first hour, // otherwise, it will get set to the last dfV2 (SUNUP.BAS 250) if ( iCount == 0 ) // SUNUP.BAS 550 { dfV0 = dfSinLat * Math.sin( dfD0 ) + dfCosLat * Math.cos( dfD0 ) * Math.cos( dfH0 ) - Math.cos( dfZenith ); // SUNUP.BAS 560 } else dfV0 = dfV2; // That is, dfV2 from the previous hour. dfV2 = dfSinLat * Math.sin( dfD2 ) + dfCosLat * Math.cos( dfD2 ) * Math.cos( dfH2 ) - Math.cos( dfZenith ); // SUNUP.BAS 570 // if dfV0 and dfV2 have the same sign, then proceed to next hr if ( ( dfV0 >= 0.0 && dfV2 >= 0.0 ) // both are positive || // or ( dfV0 < 0.0 && dfV2 < 0.0 ) // both are negative ) { // Break iteration and proceed to test next hour dfA0 = dfA2; // SUNUP.BAS 250 dfD0 = dfD2; // SUNUP.BAS 250 continue; // SUNUP.BAS 610 } dfV1 = dfSinLat * Math.sin( dfD1 ) + dfCosLat * Math.cos( dfD1 ) * Math.cos( dfH1 ) - Math.cos( dfZenith ); // SUNUP.BAS 590 tempA = 2.0 * dfV2 - 4.0 * dfV1 + 2.0 * dfV0; // SUNUP.BAS 600 tempB = 4.0 * dfV1 - 3.0 * dfV0 - dfV2; // SUNUP.BAS 600 tempD = tempB * tempB - 4.0 * tempA * dfV0; // SUNUP.BAS 610 if ( tempD < 0.0 ) { // Break iteration and proceed to test next hour dfA0 = dfA2; // SUNUP.BAS 250 dfD0 = dfD2; // SUNUP.BAS 250 continue; // SUNUP.BAS 610 } tempD = Math.sqrt( tempD ); // SUNUP.BAS 620 // Determine occurence of sunrise or sunset. // Flags to identify occurrence during this day are // bSunriseToday and bSunsetToday, and are initialized false. // These are set true only if sunrise or sunset occurs // at any point in the hourly loop. Never set to false. // Flags to identify occurrence during this hour: bSunrise = false; // reset before test bSunset = false; // reset before test if ( dfV0 < 0.0 && dfV2 > 0.0 ) // sunrise occurs this hour { bSunrise = true; // SUNUP.BAS 640 bSunriseToday = true; // sunrise occurred today } if ( dfV0 > 0.0 && dfV2 < 0.0 ) // sunset occurs this hour { bSunset = true; // SUNUP.BAS 660 bSunsetToday = true; // sunset occurred today } tempE = ( tempD - tempB ) / ( 2.0 * tempA ); if ( tempE > 1.0 || tempE < 0.0 ) // SUNUP.BAS 670, 680 tempE = ( -tempD - tempB ) / ( 2.0 * tempA ); // Set values of hour and minute of sunset or sunrise // only if sunrise/set occurred this hour. if ( bSunrise ) { dfHourRise = Math.floor( dfC0 + tempE + 1.0/120.0 ); dfMinRise = Math.floor( ( dfC0 + tempE + 1.0/120.0 - dfHourRise ) * 60.0 ); } if ( bSunset ) { dfHourSet = Math.floor( dfC0 + tempE + 1.0/120.0 ); dfMinSet = Math.floor( ( dfC0 + tempE + 1.0/120.0 - dfHourSet ) * 60.0 ); } // Change settings of variables for next loop dfA0 = dfA2; // SUNUP.BAS 250 dfD0 = dfD2; // SUNUP.BAS 250 } // end of loop testing each hour for an event // After having checked all hours, set flags if no rise or set // bSunUpAllDay and bSundownAllDay are initialized as false if ( !bSunriseToday && !bSunsetToday ) { if ( dfV2 < 0.0 ) bSunDownAllDay = true; else bSunUpAllDay = true; } // Load dateSunrise with data dfmtDateTime = new SimpleDateFormat( "d M yyyy HH:mm z" ); if( bSunriseToday ) { dateSunrise = dfmtDateTime.parse( iDay + " " + iMonth + " " + iYear + " " + (int)dfHourRise + ":" + (int)dfMinRise + " GMT" ); } // Load dateSunset with data if( bSunsetToday ) { dateSunset = dfmtDateTime.parse( iDay + " " + iMonth + " " + iYear + " " + (int)dfHourSet + ":" + (int)dfMinSet + " GMT" ); } } // end of try // Catch errors catch( ParseException e ) { System.out.println( "\nCannot parse date" ); System.out.println( e ); System.exit( 1 ); } // end of catch } /****************************************************************************** * method: getSunrise() ******************************************************************************* * * Gets the date and time of sunrise. If there is no sunrise, returns null. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public Date getSunrise() { if ( bSunriseToday ) return( dateSunrise ); else return( null ); } /****************************************************************************** * method: getSunset() ******************************************************************************* * * Gets the date and time of sunset. If there is no sunset, returns null. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public Date getSunset() { if ( bSunsetToday ) return( dateSunset ); else return( null ); } /****************************************************************************** * method: isSunrise() ******************************************************************************* * * Returns a boolean identifying if there was a sunrise. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunrise() { return( bSunriseToday ); } /****************************************************************************** * method: isSunset() ******************************************************************************* * * Returns a boolean identifying if there was a sunset. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunset() { return( bSunsetToday ); } /****************************************************************************** * method: isSunUp() ******************************************************************************* * * Returns a boolean identifying if the sun is up all day. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunUp() { return( bSunUpAllDay ); } /****************************************************************************** * method: isSunDown() ******************************************************************************* * * Returns a boolean identifying if the sun is down all day. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunDown() { return( bSunDownAllDay ); } /****************************************************************************** * method: isDaytime() ******************************************************************************* * * Returns a boolean identifying if it is daytime at the hour contained in * the Date object passed to SunriseSunset on construction. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isDaytime() { // Determine if it is daytime (at sunrise or later) // or nighttime (at sunset or later) at the location of interest // but expressed in the time zone requested. if ( bSunriseToday && bSunsetToday ) // sunrise and sunset { if ( dateSunrise.before( dateSunset ) ) // sunrise < sunset { if ( ( dateInput.after( dateSunrise ) || dateInput.equals( dateSunrise ) ) && dateInput.before( dateSunset ) ) bDaytime = true; else bDaytime = false; } else // sunrise comes after sunset (in opposite time zones) { if ( ( dateInput.after( dateSunrise ) || dateInput.equals( dateSunrise ) ) || // use OR rather than AND dateInput.before( dateSunset ) ) bDaytime = true; else bDaytime = false; } } else if ( bSunUpAllDay ) // sun is up all day bDaytime = true; else if ( bSunDownAllDay ) // sun is down all day bDaytime = false; else if ( bSunriseToday ) // sunrise but no sunset { if ( dateInput.before( dateSunrise ) ) bDaytime = false; else bDaytime = true; } else if ( bSunsetToday ) // sunset but no sunrise { if ( dateInput.before( dateSunset ) ) bDaytime = true; else bDaytime = false; } else bDaytime = false; // this should never execute return( bDaytime ); } } // end of class /*----------------------------------------------------------------------------- * end of class *----------------------------------------------------------------------------*/
Java
package app; import ui.viewModel.ViewModel; import foundation.data.DataHelper; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public class MyApplication extends Application { // 数据库助手 public static DataHelper DATAHELPER; // 数据库名 public static String DATAFILENAME = "myApp.db"; // 登录用户 // Activity跳转广播接收器 public static ViewFwdRcv VWFWDRCV; @Override public void onCreate() { super.onCreate(); // 初始化全局变量 DATAHELPER = new DataHelper(getApplicationContext(), DATAFILENAME); VWFWDRCV = new ViewFwdRcv(); } // Activity跳转广播接收器类的定义 public class ViewFwdRcv extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { // 获取源源Activity和目标源Activity的名字 String frmActClsNm = arg1.getStringExtra("frmActClsNm"); String toActClsNm = arg1.getStringExtra("toActClsNm"); if (frmActClsNm.equals(toActClsNm) || frmActClsNm == null || toActClsNm == null) { return; } // 源Activity的ViewModel对象 ViewModel ObjOfFrmActVM = null; // 目标Activity的ViewModel对象 ViewModel ObjOfToActVM = null; // 源Activity中ViewModel对象的打包对象 Bundle bdlOfFrmAct = arg1.getExtras(); // 目标Activity中ViewModel对象的打包对象 Bundle bdlOfToAct = null; if (bdlOfFrmAct != null) { // 获取源Activity的ViewModel对象 ObjOfFrmActVM = ViewModel.readFromBundle(bdlOfFrmAct); } // 依据源Activity的ViewModel对象,变换生成目标Activity的ViewModel对象 ObjOfToActVM = ViewModelTansformation(frmActClsNm, ObjOfFrmActVM, toActClsNm); // 打包目标Activity的ViewModel对象 if (ObjOfToActVM != null) { bdlOfToAct = ObjOfToActVM.writeToBundle(); } Class<?> clsOfToAct = null; try { clsOfToAct = Class.forName(toActClsNm); Intent toActIntent = new Intent(MyApplication.this, clsOfToAct); if (bdlOfToAct != null) { toActIntent.putExtras(bdlOfToAct); } toActIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(toActIntent); } catch (ClassNotFoundException e) { Log.e(toActClsNm, "目标Activity的类找不到"); } } } protected ViewModel ViewModelTansformation(String frmActClsNm, ViewModel objOfFrmActVM, String toActClsNm) { ViewModel resultVMofToAct = null; /* * if (frmActClsNm.equals(Activity1.class.getName()) && * toActClsNm.equals(Aoivtity2.class.getName())){ // 强制类型转换 if * (objOfFrmActVM != null) { ViewModelX objOfVMX = (ViewModelX) * objOfFrmActVM; ViewModelY objOfVMY = new ViewModelY(); * * //视图模型变换 objOfVMY.setAge2(objOfVMX.getAge() + 1); resultVMofToAct = * objOfVMY; } } */ return resultVMofToAct; } }
Java
package app; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.view.Window; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import com.mysport.ui.R; /** * * @author GreamTeam 沈志鹏 郑运春 * */ public class MainActivity extends TabActivity implements OnCheckedChangeListener{ public static final String TAB_GPS = "tabGps"; public static final String TAB_MAP = "tabMap"; public static final String TAB_WEATHER = "tabWeather"; public static final String TAB_TERRAIN = "tabTerrain"; private RadioGroup radioderGroup; private TabHost tabHost; protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_tab); tabHost=this.getTabHost(); //添加选项卡 tabHost.addTab(tabHost.newTabSpec("TAB_GPS").setIndicator("TAB_GPS") .setContent(new Intent(this, ui.activity.gps.GpsObtainActivity.class))); tabHost.addTab(tabHost.newTabSpec("TAB_MAP").setIndicator("TAB_MAP") .setContent(new Intent(this,ui.activity.GoogleMap.GMapActivity.class))); tabHost.addTab(tabHost.newTabSpec("TAB_WEATHER").setIndicator("TAB_WEATHER") .setContent(new Intent(this,ui.activity.weather.WeatherActivity.class))); // tabHost.addTab(tabHost.newTabSpec("TAB_TERRAIN").setIndicator("TAB_TERRAIN") // .setContent(new Intent(this,ui.activity.GoogleMap.GoogleMapActivity.class))); radioderGroup = (RadioGroup) findViewById(R.id.main_radio); radioderGroup.setOnCheckedChangeListener(this); this.tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { // TODO Auto-generated method stub } }); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub switch(checkedId){ case R.id.radio_button0: tabHost.setCurrentTabByTag("TAB_GPS"); break; case R.id.radio_button1: tabHost.setCurrentTabByTag("TAB_MAP"); break; case R.id.radio_button2: tabHost.setCurrentTabByTag("TAB_WEATHER"); break; case R.id.radio_button3: tabHost.setCurrentTabByTag("TAB_TERRAIN"); break; } } }
Java
/** * Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved */ package socialShare.wxapi; import android.os.Bundle; import com.baidu.sharesdk.weixin.WXEventHandlerActivity; /** * 处理微信回调 * @author chenhetong(chenhetong@baidu.com) * */ public class WXEntryActivity extends WXEventHandlerActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); finish(); } }
Java
package socialShare; public class SocialShareConfig { public final static String mbApiKey = "OYt9Ios9cy7vM09e64AIIjFE"; // online // env public static final String SINA_SSO_APP_KEY = "319137445"; public static final String QQ_SSO_APP_KEY = "100358052"; public static final String wxApp = "wxa2f5dc38baa66b9d"; }
Java
package domain.businessService.gps; import java.util.List; import domain.businessEntity.gps.ClimbData; public interface IClimbDataService { //添加登山记录 public boolean addClimbData(ClimbData data); //删除登山记录 public boolean deleteCilmbDataByID(int climbId); //删除全部记录 public boolean deleteAll(); //获取登山记录 public List<ClimbData> getClimbData(); //根据ID获取登山记录 public ClimbData getClimbDataById(int climbId); }
Java
package domain.businessService.gps; import java.util.Date; import java.util.List; import domain.businessEntity.gps.LatLngData; public interface ILatLngDataService { public boolean addLatLngData(LatLngData data); public boolean deleteAll(); public boolean deleteByDate(String time); public List<LatLngData> getLatLngDataByTime(String time); }
Java
package domain.businessService.gps; import java.util.List; import domain.businessEntity.gps.AltitudeData; public interface IAltitudeDataService { public boolean addAltitudeData(AltitudeData data); public boolean deleteAltitudeData(String time); public List<AltitudeData> getAltitudeData(String time); }
Java
package domain.businessService.gps; import java.sql.SQLException; import java.util.List; import ui.viewModel.gps.RecDetailViewModel; import com.j256.ormlite.stmt.QueryBuilder; import android.util.Log; import domain.businessEntity.gps.ClimbData; import foundation.data.DataContext; import foundation.data.IDataContext; public class ClimbDataService implements IClimbDataService { private static String Tag="GpsDataService"; private RecDetailViewModel viewModel; private IDataContext ctx=null; public ClimbDataService(){ ctx= new DataContext(); } //添加数据 @Override public boolean addClimbData(ClimbData data) { try { ctx.add(data, ClimbData.class, int.class); return true; } catch (SQLException e) { Log.e(Tag, e.toString()); } return false; } //根据ID删除数据 @Override public boolean deleteCilmbDataByID(int climbId) { // TODO Auto-generated method stub try { ctx.deleteById(climbId, ClimbData.class, int.class); } catch (SQLException e) { // TODO Auto-generated catch block Log.e(Tag, e.toString()); } return false; } //删除所有数据 @Override public boolean deleteAll() { try { ctx.deleteAll(ClimbData.class, int.class); return true; } catch (SQLException e) { // TODO Auto-generated catch block Log.e(Tag, e.toString()); } return false; } //获取数据 @Override public List<ClimbData> getClimbData() { // TODO Auto-generated method stub try { List<ClimbData> dateList=ctx.queryForAll(ClimbData.class, int.class); return dateList; } catch (SQLException e) { // TODO Auto-generated catch block Log.e(Tag, e.toString()); } return null; } //根据ID获取数据 public ClimbData getClimbDataById(int climbId) { // TODO Auto-generated method stub ClimbData climbdata = new ClimbData(); try{ climbdata = ctx.queryById(ClimbData.class, int.class, climbId); return climbdata; }catch (Exception e) { // TODO: handle exception Log.e(Tag, e.toString()); } return null; } /* public boolean getClimbDataById(int climbId) { // TODO Auto-generated method stub ClimbData climbdata=null; try{ climbdata = new ClimbData(); climbdata = ctx.queryById(ClimbData.class, int.class, climbId); viewModel.setClimbdata(climbdata); // viewModel.fireOnUpdated(); return true; }catch (Exception e) { // TODO: handle exception Log.e(Tag, e.toString()); } return false; } */ }
Java
package domain.businessService.gps; import java.sql.SQLException; import java.util.List; import android.util.Log; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.QueryBuilder; import domain.businessEntity.gps.AltitudeData; import domain.businessEntity.gps.LatLngData; import foundation.data.DataContext; import foundation.data.IDataContext; public class AltitudeDataService implements IAltitudeDataService { private static String tag="AltitudeDataService"; private IDataContext ctx = null; public AltitudeDataService(){ ctx = new DataContext(); } @Override public boolean addAltitudeData(AltitudeData data) { try { ctx.add(data, AltitudeData.class, Integer.class); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override public boolean deleteAltitudeData(String time) { DeleteBuilder<AltitudeData, Integer> db; try { db = ctx.getDeleteBuilder(AltitudeData.class, int.class); db.where().eq("time", time); ctx.delete(AltitudeData.class, int.class, db.prepare()); } catch (SQLException e) { Log.e(tag, e.toString()); } return false; } @Override public List<AltitudeData> getAltitudeData(String time) { try { QueryBuilder<AltitudeData,Integer> qb = ctx.getQueryBuilder(AltitudeData.class, int.class); qb.where().eq("time", time); List<AltitudeData> qbDataList = ctx.query(AltitudeData.class, int.class, qb.prepare()); return qbDataList; } catch (SQLException e) { Log.e(tag,e.toString()); } return null; } }
Java
package domain.businessService.gps; import java.sql.SQLException; import java.util.Date; import java.util.List; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.QueryBuilder; import android.util.Log; import domain.businessEntity.gps.LatLngData; import foundation.data.DataContext; import foundation.data.IDataContext; public class LatLngDataService implements ILatLngDataService{ private static String tag="LatLngDataService"; private IDataContext ctx = null; public LatLngDataService(){ ctx = new DataContext(); } @Override public boolean addLatLngData(LatLngData data) { try { ctx.add(data, LatLngData.class, Integer.class); return true; } catch (SQLException e) { Log.e(tag, e.toString()); } return false; } @Override public boolean deleteAll() { try { ctx.deleteAll(LatLngData.class, Integer.class); return true; } catch (SQLException e) { Log.e(tag,e.toString()); } return false; } @Override public boolean deleteByDate(String time) { DeleteBuilder<LatLngData, Integer> db; try { db = ctx.getDeleteBuilder(LatLngData.class, int.class); db.where().eq("time", time); ctx.delete(LatLngData.class, int.class, db.prepare()); } catch (SQLException e) { Log.e(tag, e.toString()); } return false; } @Override public List<LatLngData> getLatLngDataByTime(String time) { try { QueryBuilder<LatLngData,Integer> qb = ctx.getQueryBuilder(LatLngData.class, int.class); qb.where().eq("time", time); List<LatLngData> qbDataList = ctx.query(LatLngData.class, int.class, qb.prepare()); return qbDataList; } catch (SQLException e) { Log.e(tag,e.toString()); } return null; } }
Java
package domain.businessEntity.gps; import java.util.Date; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "T_ClimbData") public class ClimbData { public ClimbData(){} //ID号 设置主键 @DatabaseField(generatedId = true) private int climbID; //设置登山记录名称 @DatabaseField(canBeNull = false) private String climbName; //开始高度 @DatabaseField(canBeNull = true) private int startAltitude; //结束高度 @DatabaseField(canBeNull = true) private int stopAltitude; //开始时间 @DatabaseField(canBeNull = true) private Date startTime; //结束时间 @DatabaseField(canBeNull = true) private Date stopTime; //经度 @DatabaseField(canBeNull = true) private Double longitude; //纬度 @DatabaseField(canBeNull = true) private Double latitude; public int getStartAltitude() { return startAltitude; } public void setStartAltitude(int startAltitude) { this.startAltitude = startAltitude; } public int getStopAltitude() { return stopAltitude; } public void setStopAltitude(int stopAltitude) { this.stopAltitude = stopAltitude; } public int getClimbID() { return climbID; } public void setClimbID(int climbID) { this.climbID = climbID; } public String getClimbName() { return climbName; } public void setClimbName(String climbName) { this.climbName = climbName; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getStopTime() { return stopTime; } public void setStopTime(Date stopTime) { this.stopTime = stopTime; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } }
Java
package domain.businessEntity.gps; import java.util.Date; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "T_LatLngData") public class LatLngData { public LatLngData(){} //设置ID为主键 @DatabaseField(generatedId = true) private int dataID; //设置开始记录时间作为标识 @DatabaseField(canBeNull = false) private String time; //纬度 @DatabaseField(canBeNull = true) private double lat; //经度 @DatabaseField(canBeNull = true) private double lng; public int getDataID() { return dataID; } public void setDataID(int dataID) { this.dataID = dataID; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public String getStartTime() { return time; } public void setStartTime(String time) { this.time = time; } }
Java
package domain.businessEntity.gps; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "T_AltitudeData") public class AltitudeData { @DatabaseField(generatedId = true) private int dataID; @DatabaseField(canBeNull = false) private int Altitude; @DatabaseField(canBeNull = false) private String time; public AltitudeData(){ } public int getDateID() { return dataID; } public void setDateID(int dataID) { this.dataID = dataID; } public int getAltitude() { return Altitude; } public void setAltitude(int altitude) { Altitude = altitude; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
Java
package ui.activity.gps; import java.io.ByteArrayOutputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.renderer.XYSeriesRenderer; import android.R.integer; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.GestureDetector.OnGestureListener; import android.view.Display; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.baidu.sharesdk.BaiduShareException; import com.baidu.sharesdk.BaiduSocialShare; import com.baidu.sharesdk.ShareContent; import com.baidu.sharesdk.ShareListener; import com.baidu.sharesdk.SocialShareLogger; import com.baidu.sharesdk.Utility; import com.baidu.sharesdk.ui.BaiduSocialShareUserInterface; import com.mysport.ui.R; import domain.businessEntity.gps.ClimbData; import domain.businessService.gps.ClimbDataService; import domain.businessService.gps.IClimbDataService; import domain.businessService.gps.ILatLngDataService; import domain.businessService.gps.LatLngDataService; import socialShare.SocialShareConfig; import tool.data.ClimbDataUtil; import ui.activity.ActivityOfAF4Ad; import ui.activity.GoogleMap.GMapActivity; import ui.activity.GoogleMap.GoogleMapActivity; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; import ui.viewModel.gps.RecDetailViewModel; public class RecDetailsActivity extends ActivityOfAF4Ad implements OnTouchListener, OnGestureListener { private IClimbDataService dateService; private ILatLngDataService latLngService; // 记录名 private TextView tv_Name = null; // 当前日期 private TextView tv_Date = null; // 开始时间 private TextView tv_startTime = null; // 结束时间 private TextView tv_stopTime = null; // 平均海拔 private TextView tv_altitudeDiff = null; // 经度 private TextView tv_lat = null; // 纬度 private TextView tv_lon = null; // 返回上一个界面 private ImageView iv_back = null; private ImageView iv_delete = null; private ImageView iv_location; private int id = -1; private int maxId = -1; // 经纬度全局变量方便传值 private double lat; private double lon; private String Name; private String strTime;// 全局变量方便取值 GestureDetector mGestureDetector = null; // 定义手势监听对象 private int verticalMinDistance = 10; // 最小触摸滑动距离 private int minVelocity = 0; // 最小水平移动速度 private RelativeLayout detailLayout; private ImageView iv_share; /********************** 社会化分享组件定义 ***********************************/ private BaiduSocialShare socialShare; private BaiduSocialShareUserInterface socialShareUi; private final static String appKey = SocialShareConfig.mbApiKey; private final static String wxAppKey = SocialShareConfig.wxApp; private ShareContent picContent; private final Handler handler = new Handler(Looper.getMainLooper()); /*******************************************************************/ /*********************** 图表 *****************************************/ private XYMultipleSeriesDataset ds; private XYMultipleSeriesRenderer render; private XYSeries series; private GraphicalView gv; private XYSeriesRenderer xyRender; /*******************************************************************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); // 初始化社会化主件 socialShare = BaiduSocialShare.getInstance(this, appKey); // socialShare.supportWeiBoSso(BaiduSocialShareConfig.SINA_SSO_APP_KEY); socialShare.supportWeixin(wxAppKey); socialShareUi = socialShare.getSocialShareUserInterfaceInstance(); SocialShareLogger.on(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_rec_details, menu); return true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("dataset", ds); outState.putSerializable("renderer", render); outState.putSerializable("current_series", series); outState.putSerializable("current_renderer", xyRender); } @Override protected void onRestoreInstanceState(Bundle savedState) { super.onRestoreInstanceState(savedState); ds = (XYMultipleSeriesDataset) savedState.getSerializable("dataset"); render = (XYMultipleSeriesRenderer) savedState .getSerializable("renderer"); series = (XYSeries) savedState.getSerializable("current_series"); xyRender = (XYSeriesRenderer) savedState .getSerializable("current_renderer"); } @Override protected void onResume() { super.onResume(); if (ds == null) getDataset(); if (render == null) getRenderer(); if (gv == null) { LinearLayout layout = (LinearLayout) findViewById(R.id.chart); gv = ChartFactory.getLineChartView(this, ds, render); layout.addView(gv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } else { // 绘制图形 gv.repaint(); } } private XYMultipleSeriesDataset getDataset() { ds = new XYMultipleSeriesDataset(); // 新建一个系列(线条) series = new XYSeries("高度走势"); series.add(10,30); series.add(20,50); series.add(30,71); series.add(40,85); series.add(50,90); // 把添加了点的折线放入dataset ds.addSeries(series); return ds; } public XYMultipleSeriesRenderer getRenderer() { // 新建一个xymultipleseries render = new XYMultipleSeriesRenderer(); render.setAxisTitleTextSize(16); // 设置坐标轴标题文本大小 render.setChartTitleTextSize(20); // 设置图表标题文本大小 render.setLabelsTextSize(15); // 设置轴标签文本大小 render.setLegendTextSize(15); // 设置图例文本大小 render.setMargins(new int[] {20, 30, 15,0}); // 设置4边留白 render.setPanEnabled(false, false); // 设置x,y坐标轴不会因用户划动屏幕而移动 // 设置4边留白透明 render.setMarginsColor(Color.argb(0,0xff, 0, 0)); render.setBackgroundColor(Color.TRANSPARENT); // 设置背景色透明 render.setApplyBackgroundColor(true); // 使背景色生效 render.setXTitle("持续时间"); render.setYTitle("海拔高度"); // 设置一个系列的颜色为蓝色 xyRender = new XYSeriesRenderer(); xyRender.setColor(Color.BLUE); // 往xymultiplerender中增加一个系列 render.addSeriesRenderer(xyRender); return render; } @Override protected void initControlsAndRegEvent() { tv_Date = (TextView) findViewById(R.id.tv_Date); tv_startTime = (TextView) findViewById(R.id.tv_startTime); tv_stopTime = (TextView) findViewById(R.id.tv_stopTime); tv_altitudeDiff = (TextView) findViewById(R.id.tv_altitudeDiff); tv_Name = (TextView) findViewById(R.id.tv_recName); iv_back = (ImageView) findViewById(R.id.iv_back); iv_delete = (ImageView) findViewById(R.id.iv_delete); iv_location = (ImageView) findViewById(R.id.iv_loc); //iv_back.setOnClickListener(new BackToRecord()); iv_share = (ImageView) findViewById(R.id.iv_share); mGestureDetector = new GestureDetector((OnGestureListener) this); detailLayout = (RelativeLayout) findViewById(R.id.detail_layout); detailLayout.setOnTouchListener(this); detailLayout.setLongClickable(true); dateService = new ClimbDataService(); latLngService = new LatLngDataService(); Intent intent = getIntent(); ClimbData climbdata; if (intent != null) { Bundle bundle = intent.getExtras(); id = bundle.getInt("id"); maxId = bundle.getInt("count"); climbdata = dateService.getClimbDataById(id); } else { throw new RuntimeException("查看信息出错"); } showActivity(climbdata); // 设置分享内容 picContent = new ShareContent(); picContent.setContent("MyClimb:我刚刚登上了" + climbdata.getClimbName() + "!" + "这是我的行程记录"); picContent.setTitle("MyClimb"); picContent.setUrl("http://weibo.com/lovelss310"); // 设置删除键监听事件 iv_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dateService.deleteCilmbDataByID(id); latLngService.deleteByDate(strTime); Intent intent = new Intent(RecDetailsActivity.this, RecordActivity.class); startActivity(intent); RecDetailsActivity.this.finish(); } }); // 设置定位键监听事件 iv_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(RecDetailsActivity.this, GMapActivity.class); Bundle bundle = new Bundle(); bundle.putString("time", strTime); bundle.putString("Marker", Name); intent.putExtras(bundle); startActivity(intent); } }); iv_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(RecDetailsActivity.this, RecordActivity.class); RecDetailsActivity.this.startActivity(intent); RecDetailsActivity.this.finish(); } }); // 分享按钮监听事件 iv_share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { printscreen_share(); } }); } class BackToRecord implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub // Intent intent = new Intent(); // intent.setClass(RecDetailsActivity.this, RecordActivity.class); // RecDetailsActivity.this.startActivity(intent); overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right); } } // public void showActivity(ClimbData climbdata) { if (climbdata != null) { Name = climbdata.getClimbName(); tv_Name.setText(Name); Double longitude = climbdata.getLongitude(); Double latitude = climbdata.getLatitude(); lat = longitude; lon = latitude; // tv_lat.setText(longitude.toString()); // // tv_lon.setText(latitude.toString()); Date startTime = climbdata.getStartTime(); Date stopTime = climbdata.getStopTime(); tv_Date.setText(DateFormat.getDateInstance().format(startTime)); SimpleDateFormat tmp = new SimpleDateFormat("yyyy-MM-dd"); strTime = tmp.format(startTime); SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss"); String date1 = sdf.format(startTime); String date2 = sdf.format(stopTime); tv_startTime.setText(date1); tv_stopTime.setText(date2); int startAltitude = climbdata.getStartAltitude(); int stopAltitude = climbdata.getStopAltitude(); int altitudeDiff = stopAltitude - startAltitude; tv_altitudeDiff.setText(altitudeDiff + ""); } } @Override protected ViewModel initModel() { return null; } @Override protected void upDateView(ViewModel aVM) { // TODO Auto-generated method stub } @Override protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM, String errMsg) { // TODO Auto-generated method stub } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity && (--id) >= 1) { Animation translateAnimationoOut = AnimationUtils.loadAnimation( detailLayout.getContext(), R.anim.out_to_right); detailLayout.startAnimation(translateAnimationoOut); ClimbData climbdata = dateService.getClimbDataById(id); showActivity(climbdata); Animation translateAnimationIn = AnimationUtils.loadAnimation( detailLayout.getContext(), R.anim.in_from_left); detailLayout.startAnimation(translateAnimationIn); } if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity && (++id) <= maxId) { Toast toast = Toast.makeText(RecDetailsActivity.this, id + "", Toast.LENGTH_SHORT); toast.show(); ClimbData climbdata = dateService.getClimbDataById(id); Animation translateAnimationOut = AnimationUtils.loadAnimation( detailLayout.getContext(), R.anim.out_to_left); detailLayout.startAnimation(translateAnimationOut); showActivity(climbdata); Animation translateAnimationIn = AnimationUtils.loadAnimation( detailLayout.getContext(), R.anim.in_from_right); detailLayout.startAnimation(translateAnimationIn); } return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(event); } /*************** 截屏分享 **************/ public void printscreen_share() { View view1 = getWindow().getDecorView(); Display display = getWindowManager().getDefaultDisplay(); view1.layout(0, 0, display.getWidth(), display.getHeight()); view1.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view1.getDrawingCache()); picContent.setImageUrl(null); picContent.addImageByContent(Bitmap2Bytes(bitmap)); socialShareUi.showShareMenu(this, picContent, Utility.SHARE_THEME_STYLE, new ShareListener() { @Override public void onAuthComplete(Bundle values) { // TODO Auto-generated method stub } @Override public void onApiComplete(String responses) { // TODO Auto-generated method stub handler.post(new Runnable() { @Override public void run() { Utility.showAlert(RecDetailsActivity.this, "分享成功"); } }); } @Override public void onError(BaiduShareException e) { handler.post(new Runnable() { @Override public void run() { Utility.showAlert(RecDetailsActivity.this, "分享失败"); } }); } }); } // 把Bitmap 转成 Byte public static byte[] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK ) { Intent intent = new Intent(this, RecordActivity.class); startActivity(intent); this.finish(); } return true; } }
Java
package ui.activity.gps; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import ui.activity.ActivityOfAF4Ad; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; import android.content.Intent; import android.os.Bundle; import android.view.GestureDetector; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.GestureDetector.OnGestureListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.mysport.ui.R; import domain.businessEntity.gps.ClimbData; import domain.businessService.gps.ClimbDataService; import domain.businessService.gps.IClimbDataService; /** * @uml.annotations * uml_usage="mmi:///#jsrctype^name=BackToRecord[jsrctype^name=RecDetailsActivity[jcu^name=RecDetailsActivity.java[jpack^name=ui.activity.gps[jsrcroot^srcfolder=src[project^id=MyClimb]]]]]$uml.Class" * @author DreamTeam 郑宇 */ public class RecordActivity extends ActivityOfAF4Ad implements OnTouchListener,OnGestureListener { private IClimbDataService dateService; private ListView recList; private TextView tv_id; private TextView tv_name; List<Map<String,String>> data; List<ClimbData> list; Date date=new Date(); GestureDetector mGestureDetector=null; //定义手势监听对象 private int verticalMinDistance = 10; //最小触摸滑动距离 private int minVelocity = 0; //最小水平移动速度 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_record); dateService=new ClimbDataService(); list=dateService.getClimbData(); data=convertDateToMap(list); recList=(ListView)findViewById(R.id.recList); mGestureDetector=new GestureDetector((OnGestureListener)this); RelativeLayout recordlayout=(RelativeLayout)findViewById(R.id.record_layout); recordlayout.setOnTouchListener(this); recordlayout.setLongClickable(true); recList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent=new Intent(RecordActivity.this, RecDetailsActivity.class); Bundle bundle=new Bundle(); bundle.putInt("id", list.get(arg2).getClimbID()); bundle.putInt("count", list.size()); intent.putExtras(bundle); startActivity(intent); } }); SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.activity_reclist2, new String[] {"name","date"}, new int[]{R.id.recName3,R.id.recDate3}); recList.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_record, menu); return true; } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); this.finish(); } @Override protected void initControlsAndRegEvent() { } private List<Map<String, String>> convertDateToMap(List<ClimbData> climbData) { // TODO Auto-generated method stub List<Map<String,String>> mapList=new ArrayList<Map<String, String>>();; if(climbData!=null) { int len=climbData.size(),i=0; for(;i<len;i++) { Map<String,String> map=new HashMap<String, String>(); //map.put("id",climbData.get(i).getClimbID()+""); map.put("name", climbData.get(i).getClimbName()); Date date=climbData.get(i).getStartTime(); map.put("date", DateFormat.getDateInstance().format(date)); mapList.add(map); } } return mapList; } @Override protected ViewModel initModel() { // TODO Auto-generated method stub return null; } @Override protected void upDateView(ViewModel aVM) { // TODO Auto-generated method stub } @Override protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM, String errMsg) { // TODO Auto-generated method stub } @Override public boolean onDown(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub if(arg1.getX()-arg0.getX()>verticalMinDistance && Math.abs(arg2)>minVelocity) { //Intent intent=new Intent(RecordActivity.this, GpsObtainActivity.class); //startActivity(intent); RecordActivity.this.finish(); overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right); } return false; } @Override public void onLongPress(MotionEvent arg0) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent arg0) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(event); } }
Java
package ui.activity.gps; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import ui.activity.ActivityOfAF4Ad; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.os.SystemClock; import android.text.InputType; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.RotateAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.Chronometer; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import com.mysport.ui.R; import domain.businessEntity.gps.ClimbData; import domain.businessEntity.gps.LatLngData; import domain.businessService.gps.ClimbDataService; import domain.businessService.gps.IClimbDataService; import foundation.webservice.GeocodeService; /** * @author DreamTeam 沈志鹏 */ public class GpsObtainActivity extends ActivityOfAF4Ad implements OnTouchListener, OnGestureListener { private TextView tv_altitude;// 高度显示控件 private TextView tv_direction;// 方向显示控件 private TextView tv_speed;// 速度显示控件 private TextView tv_longitude;// 经度显示控件 private TextView tv_latitude;// 纬度显示控件 private ImageButton bt_startAndStop;// 开始结束按钮 private Builder builder; private EditText editor;// 对话框文本输入控件 private LocationManager locManager;// 定义LocationManager对象 private String cliName;// 行程名称 private Chronometer timer;// 定义计时器 private Date startTime;// 记录开始时间 private Date stopTime;// 记录结束时间 private int startAltitude;// 开始海拔 private int stopAltitude;// 结束海拔 private SimpleDateFormat sDateFormat; boolean flag = false;// 设置开始结束按钮标志 private int currentAltitude;// 获取当前高度 private SensorManager mSensorManager;// 定义SensorManager对象 private double stopLon;// 结束时经度 private double stopLat;// 结束时纬度 private double currentLon;// 当前经度 private double currentLat;// 当前纬度 private IClimbDataService climbDataService;// 定义登山数据服务对象 GestureDetector mGestureDetector = null; // 定义手势监听对象 private int verticalMinDistance = 10; // 最小触摸滑动距离 private int minVelocity = 0; // 最小水平移动速度 private ImageView iv_compass; private float predegree = 0f; private ImageView compassNeedle;//指南针 private String city; private boolean isExit = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gps); mGestureDetector = new GestureDetector((OnGestureListener) this); LinearLayout mainlayout = (LinearLayout) findViewById(R.id.gps_main_layout); mainlayout.setOnTouchListener(this); mainlayout.setLongClickable(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_obtain_gps, menu); return true; } @Override protected void initControlsAndRegEvent() { // 获取相应控件id bt_startAndStop = (ImageButton) findViewById(R.id.bt_startAndStop); tv_altitude = (TextView) findViewById(R.id.tv_altitude); tv_direction = (TextView) findViewById(R.id.tv_direction); tv_speed = (TextView) findViewById(R.id.tv_speed); tv_longitude = (TextView) findViewById(R.id.tv_longitude); tv_latitude = (TextView) findViewById(R.id.tv_latitude); timer = (Chronometer) findViewById(R.id.timer); compassNeedle=(ImageView)findViewById(R.id.iv_compassNeedle); climbDataService = new ClimbDataService(); // 构建对话框输入控件对象 editor = new EditText(this); builder = new AlertDialog.Builder(this); // 设置计时器显示格式 timer.setFormat("%s"); if (flag == true) { bt_startAndStop.setImageDrawable(getResources().getDrawable( R.drawable.pause)); } else bt_startAndStop.setImageDrawable(getResources().getDrawable( R.drawable.play)); // 启动GPS startGps(); // 获取方向传感器服务 mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // 开始和停止按钮监听事件 bt_startAndStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (flag == false) { builder.setTitle("请输入行程名称"); builder.setView(editor); RequireAddressAsyncTask asyncTask = new RequireAddressAsyncTask( editor); asyncTask.execute(); // 点击自动EditText自动全选 editor.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { editor.selectAll(); ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)) .showSoftInput(v, 0); return true; } }); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { initControlsAndRegEvent(); } }); // 设置对话框 builder.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 获取输入 cliName = editor.getText().toString(); // 计时器重置 timer.setBase(SystemClock.elapsedRealtime()); // 开始计时 timer.start(); // 获取开始时间 startTime = new java.util.Date(); // 记录开始高度值 startAltitude = currentAltitude; flag = true; sendStartStatusToGMap(); initControlsAndRegEvent(); } }); builder.create().show(); } else { flag = false; timer.stop(); // 记录结束是时间 stopTime = new java.util.Date(); // 记录结束时高度 stopAltitude = currentAltitude; // 记录结束是经度 stopLon = currentLon; // 记录结束是纬度 stopLat = currentLat; sendStopStatusToGMap(); writeDataToSqlite(); initControlsAndRegEvent(); } } }); } // 发送开始状态广播给GoogleMap public void sendStartStatusToGMap() { Intent intent = new Intent(); intent.setAction("status"); intent.putExtra("status", true); sendBroadcast(intent); } // 发送结束状态广播给GoogleMap public void sendStopStatusToGMap() { Intent intent = new Intent(); intent.setAction("status"); intent.putExtra("status", false); sendBroadcast(intent); } // 跳转到记录界面 public void toRecActivity() { toActivity(this, RecordActivity.class); } // 开启GPS功能 public void startGps() { locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); // Location // location=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); updateGpsView(location); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { updateGpsView(locManager.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { updateGpsView(null); } @Override public void onLocationChanged(Location location) { updateGpsView(location); } }); } // 动态更新GPS数据 public void updateGpsView(Location newLocation) { int altitude; float speed; double lat; double lon; if (newLocation != null) { currentAltitude = altitude = (int) newLocation.getAltitude(); speed = newLocation.getSpeed(); currentLat = lat = newLocation.getLatitude(); currentLon = lon = newLocation.getLongitude(); sendBroadcastToWeather(); tv_altitude.setText(Integer.toString(altitude)); tv_speed.setText(new DecimalFormat("#0.0").format(speed)); tv_latitude.setText(Double.toString(lat)); tv_longitude.setText(Double.toString(lon)); } else { tv_altitude.setText("0"); tv_speed.setText("0"); tv_latitude.setText("0"); tv_longitude.setText("0"); } } // 设置方向传感器监听类 SensorEventListener mSersorEventListener = new SensorEventListener() { // 传感器值改变 @Override public void onSensorChanged(SensorEvent event) { float[] values = event.values; if (values[0] >= 0 && values[0] < 30) tv_direction.setText("北"); if (values[0] >= 30 && values[0] < 60) tv_direction.setText("东北"); if (values[0] >= 60 && values[0] < 120) tv_direction.setText("东"); if (values[0] >= 120 && values[0] < 150) tv_direction.setText("东南"); if (values[0] >= 150 && values[0] < 210) tv_direction.setText("南"); if (values[0] >= 210 && values[0] < 240) tv_direction.setText("西南"); if (values[0] >= 240 && values[0] < 300) tv_direction.setText("西"); if (values[0] >= 300 && values[0] < 330) tv_direction.setText("西北"); if (values[0] >= 300 && values[0] <= 360) tv_direction.setText("北"); RotateAnimation animation = new RotateAnimation(predegree, -values[0], Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f); animation.setDuration(200); compassNeedle.startAnimation(animation); predegree=-values[0]; } // 传感器精度改变 @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; @Override protected void onResume() { super.onResume(); // 方向传感器注册监听器 mSensorManager.registerListener(mSersorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onStop() { // 程序停止时注销监听器 mSensorManager.unregisterListener(mSersorEventListener); super.onStop(); } @Override protected void onPause() { // 程序暂停时注销监听器 mSensorManager.unregisterListener(mSersorEventListener); super.onStop(); } // 数据写入数据库操作 public void writeDataToSqlite() { ClimbData climbData = new ClimbData(); climbData.setClimbName(cliName); climbData.setLatitude(stopLat); climbData.setLongitude(stopLon); climbData.setStartAltitude(startAltitude); climbData.setStopAltitude(stopAltitude); climbData.setStartTime(startTime); climbData.setStopTime(stopTime); climbDataService.addClimbData(climbData); } @Override protected ViewModel initModel() { // TODO Auto-generated method stub return null; } @Override protected void upDateView(ViewModel aVM) { // TODO Auto-generated method stub } @Override protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM, String errMsg) { // TODO Auto-generated method stub } @Override public boolean onDown(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub if (arg0.getX() - arg1.getX() > verticalMinDistance && Math.abs(arg2) > minVelocity) { Intent intent = new Intent(GpsObtainActivity.this, RecordActivity.class); startActivity(intent); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); } return false; } @Override public void onLongPress(MotionEvent arg0) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent arg0) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onTouch(View arg0, MotionEvent arg1) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(arg1); } /** * * 使用多线性异步使用访问网络,进行地址反向解析查询 * */ class RequireAddressAsyncTask extends AsyncTask<Void, Void, String> { private EditText editor; public RequireAddressAsyncTask(EditText editor) { this.editor = editor; } @Override protected String doInBackground(Void... params) { String result = null; result = GeocodeService.getAddressByLatLng(currentLat, currentLon, 1); return result; } @Override protected void onPostExecute(String result) { editor.setText(result); } } public void sendBroadcastToWeather(){ Intent intent = new Intent(); intent.setAction("LatLng"); intent.putExtra("Lat", currentLat); intent.putExtra("Lng", currentLon); sendBroadcast(intent); } }
Java
package ui.activity.GoogleMap; /** * @author DreamTeam 郑运春 */ import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE; import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID; import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL; import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.content.Context; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.mysport.ui.R; import domain.businessEntity.gps.LatLngData; import domain.businessService.gps.ILatLngDataService; import domain.businessService.gps.LatLngDataService; public class GMapActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener{ private Polyline mMutablePolyline; //经纬度 private double latitude; private double longitude; private int flag = 0; private LatLngData data; private String strTime; private LocationClient mLocationClient; private List<String> titles; //标题栏 private List<List<String>> item_names; //选项名称 private List<List<Integer>> item_images; //选项图标 private MyDefinedMenu myMenu; //弹出菜单 private ILatLngDataService latLngDataService = null; private List<LatLng> points = new ArrayList<LatLng>(); private List<LatLngData> dataList = new ArrayList<LatLngData>(); private boolean status;//监听第一个界面广播过来的开始或结束的状态 true为开始,false为停止 private boolean traffic_status = false; private GoogleMap mMap; private UiSettings mUiSettings; private static final LocationRequest REQUEST = LocationRequest.create() .setInterval(50000) // 50 seconds .setFastestInterval(20) // 16ms = 60fps .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_googlemap); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapGoogle); if (savedInstanceState == null) { // 第一次得到该 activity. mapFragment.setRetainInstance(true); } else { // 当重启该Activity 时候,不需要要在重新实例化 就可以得到之前的activity mMap = mapFragment.getMap(); } latLngDataService = new LatLngDataService(); setUpMapIfNeeded(); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(29,113),2)); setRecRoute(); initPopupWindow(); } public void initPopupWindow(){ //弹出菜单标题栏 titles = addItems(new String[]{"图层菜单"}); //选项图标 item_images = new ArrayList<List<Integer>>(); item_images.add(addItems(new Integer[]{R.drawable.pop_normalmap, R.drawable.pop_earth,R.drawable.pop_terrin, R.drawable.pop_traffic})); //选项名称 item_names = new ArrayList<List<String>>(); item_names.add(addItems(new String[]{"平面地图", "卫星地图", "地形", "实时路况"})); //创建弹出菜单对象 myMenu = new MyDefinedMenu(this, titles, item_names,item_images, new ItemClickEventGmap()); } //菜单选项点击事件 public class ItemClickEventGmap implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if(arg2 == 0) mMap.setMapType(MAP_TYPE_NORMAL); if(arg2 == 1) mMap.setMapType(MAP_TYPE_SATELLITE); if(arg2 == 2) mMap.setMapType(MAP_TYPE_TERRAIN); if(arg3 == 3){ mMap.setTrafficEnabled(traffic_status); setUi(); if(traffic_status) traffic_status = false; else traffic_status = true; } myMenu.dismiss(); //菜单消失 myMenu.currentState = 1; //标记状态,已消失 } } // 转换为List<String> private List<String> addItems(String[] values) { List<String> list = new ArrayList<String>(); for (String var : values) { list.add(var); } return list; } //转换为List<Integer> private List<Integer> addItems(Integer[] values) { List<Integer> list = new ArrayList<Integer>(); for (Integer var : values) { list.add(var); } return list; } public boolean onCreateOptionsMenu(){ return false; } public boolean onCreateOptionsMenu(Menu menu){ if(0 == myMenu.currentState && myMenu.isShowing()) { myMenu.dismiss(); //对话框消失 myMenu.currentState = 1; //标记状态,已消失 } else { myMenu.showAtLocation(findViewById(R.id.mapGoogle), Gravity.BOTTOM, 0,0); myMenu.currentState = 0; //标记状态,显示中 } return false; // true--显示系统自带菜单;false--不显示。 } @Override public void closeOptionsMenu() { // TODO Auto-generated method stub super.closeOptionsMenu(); } @Override public void onOptionsMenuClosed(Menu menu) { // TODO Auto-generated method stub super.onOptionsMenuClosed(menu); } public void setRecRoute(){ //获取由RecDetailsActivity传过来的位置信息 Bundle bundle = getIntent().getExtras(); if(bundle != null) { strTime = bundle.getString("time"); dataList = latLngDataService.getLatLngDataByTime(strTime); Iterator<LatLngData> it = dataList.iterator(); if(!it.hasNext()){ Toast toast = Toast.makeText(this, "当前记录无轨迹!", Toast.LENGTH_SHORT); toast.show(); return; } PolylineOptions RecOptions = new PolylineOptions(); mMap.addMarker(new MarkerOptions() .position(new LatLng(it.next().getLat(),it.next().getLng())) .title("开始")); //LatLngData data; while(it.hasNext()){ data = it.next(); RecOptions.add(new LatLng(data.getLat(),data.getLng())); } mMap.addMarker(new MarkerOptions() .position(new LatLng(data.getLat(),data.getLng())) .title("结束")); mMutablePolyline = mMap.addPolyline(RecOptions .color(Color.GREEN) .width(2) .geodesic(true)); } } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); if (mMap != null) { setUi(); mMap.setMapType(MAP_TYPE_SATELLITE); } status = StatusReceiver.getStatus(); setUpLocationClientIfNeeded(); mLocationClient.connect(); } @Override public void onPause() { super.onPause(); if (mLocationClient != null) { mLocationClient.disconnect(); } } private void setUpLocationClientIfNeeded() { if (mLocationClient == null) { mLocationClient = new LocationClient( getApplicationContext(), this, // ConnectionCallbacks this); // OnConnectionFailedListener } } //添加经纬度点 private void addLatLngPoint(double longitude,double latitude){ double lat = latitude; double lon = longitude; points.add(new LatLng(lon,lat)); } private void setUi(){ mUiSettings.setZoomControlsEnabled(true); mUiSettings.setCompassEnabled(true); mUiSettings.setMyLocationButtonEnabled(true); mMap.setMyLocationEnabled(true); mUiSettings.setScrollGesturesEnabled(true); mUiSettings.setZoomGesturesEnabled(true); mUiSettings.setTiltGesturesEnabled(true); mUiSettings.setRotateGesturesEnabled(true); } private void setUpMapIfNeeded() { if (mMap == null) { mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapGoogle)) .getMap(); if (mMap != null) { setUpMap(); } } } private void setUpMap() { mMap.setMyLocationEnabled(true); mUiSettings = mMap.getUiSettings(); } private void drawRouteOnMap(){ if(points.size() >= 2) { PolylineOptions options = new PolylineOptions(); options.addAll(points); mMutablePolyline = mMap.addPolyline(options .color(Color.RED) .width(2) .geodesic(true)); } } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub if(status){ latitude = location.getLatitude(); longitude = location.getLongitude(); if(flag == 0 ){ mMap.addMarker(new MarkerOptions() .position(new LatLng(latitude,longitude)) .title("开始")); flag = 1; } addLatLngPoint(latitude,longitude); //划线 drawRouteOnMap(); //将记录下的点存入数据库 SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); String time = sf.format(new java.util.Date()); LatLngData data = new LatLngData(); data.setLat(latitude); data.setLng(longitude); data.setStartTime(time); latLngDataService.addLatLngData(data); }else{ if(flag == 1){ mMap.addMarker(new MarkerOptions() .position(new LatLng(latitude,longitude)) .title("结束")); flag = 2; } } } @Override public void onConnectionFailed(ConnectionResult arg0) { // TODO Auto-generated method stub0 } @Override public void onConnected(Bundle connectionHint) { mLocationClient.requestLocationUpdates( REQUEST, this); // LocationListener } @Override public void onDisconnected() { // TODO Auto-generated method stub } }
Java
package ui.activity.GoogleMap; import java.util.List; import android.content.Context; import android.graphics.Color; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.TextView; /** * * @author DreamTeam 郑运春 * */ public class TitleAdatper extends BaseAdapter { private List<String> titles; private Context context; private final TextView[] tv_titels; public TitleAdatper(Context context, List<String> titles) { this.context = context; this.titles = titles; tv_titels = new TextView[titles.size()]; } @Override public int getCount() { // TODO Auto-generated method stub return titles.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public void setFocus(int position) { for (int i = 0; i < titles.size(); i++) { tv_titels[i].setBackgroundColor(Color.WHITE); } tv_titels[position].setBackgroundColor(Color.BLUE); } @Override public View getView(int position, View convertView, ViewGroup parent) { tv_titels[position] = new TextView(context); tv_titels[position].setGravity(Gravity.CENTER); tv_titels[position].setText(titles.get(position)); tv_titels[position].setTextSize(18); tv_titels[position].setLayoutParams(new GridView.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); return tv_titels[position]; } }
Java
package ui.activity.GoogleMap; /** * @author DreamTeam 郑运春 */ import java.util.List; import ui.activity.GoogleMap.GMapActivity.ItemClickEventGmap; import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Toast; public class MyDefinedMenu extends PopupWindow { private LinearLayout layout; private GridView gv_title; private GridView gv_body; private BodyAdatper[] bodyAdapter; private TitleAdatper titleAdapter; private Context context; private int titleIndex; public int currentState; public MyDefinedMenu(Context context, List<String> titles, List<List<String>> item_names, List<List<Integer>> item_images, ItemClickEventGmap itemClickEvent) { super(context); this.context = context; currentState = 1; layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); titleIndex = 0; gv_title = new GridView(context); titleAdapter = new TitleAdatper(context, titles); gv_title.setAdapter(titleAdapter); gv_title.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); gv_title.setNumColumns(titles.size()); //gv_title.setBackgroundColor(Color.WHITE); gv_title.setBackgroundColor(Color.GRAY); bodyAdapter = new BodyAdatper[item_names.size()]; for (int i = 0; i < item_names.size(); i++) { bodyAdapter[i] = new BodyAdatper(context, item_names.get(i), item_images.get(i)); } gv_body = new GridView(context); gv_body.setNumColumns(4); //设置背景为半透明 //gv_body.setBackgroundColor(Color.TRANSPARENT); gv_body.setBackgroundColor(Color.WHITE); gv_body.setAdapter(bodyAdapter[0]); gv_title.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { titleIndex = arg2; titleAdapter.setFocus(arg2); gv_body.setAdapter(bodyAdapter[arg2]); } }); gv_body.setOnItemClickListener(itemClickEvent); layout.addView(gv_title); layout.addView(gv_body); this.setContentView(layout); this.setWidth(LayoutParams.FILL_PARENT); this.setHeight(LayoutParams.WRAP_CONTENT); this.setFocusable(true); } public int getTitleIndex() { return titleIndex; } }
Java
package ui.activity.GoogleMap; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class StatusReceiver extends BroadcastReceiver { private static boolean status; @Override public void onReceive(Context context, Intent intent) { status = intent.getExtras().getBoolean("status"); } public static boolean getStatus(){ return status; } }
Java
package ui.activity.GoogleMap; import java.io.IOException; import java.text.DecimalFormat; import java.util.List; import java.util.Locale; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.mysport.ui.R; import android.app.Activity; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN; public class GoogleMapActivity extends FragmentActivity { private GoogleMap mMap; private UiSettings mUiSettings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_googlemap); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); mMap.setMapType(MAP_TYPE_TERRAIN); mMap.setMyLocationEnabled(true); mUiSettings=mMap.getUiSettings(); //设置地图显示指南针 mUiSettings.setCompassEnabled(true); //倾斜手势操作 mUiSettings.setTiltGesturesEnabled(true); } private void setUpMapIfNeeded() { if (mMap == null) { mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapGoogle)) .getMap(); } } }
Java
package ui.activity.GoogleMap; import java.util.List; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; /** * @author Dreamteam 郑运春 */ public class BodyAdatper extends BaseAdapter { private List<String> item_names; private List<Integer> item_images; private Context context; public BodyAdatper(Context context, List<String> item_names, List<Integer> item_images) { this.context = context; this.item_names = item_names; this.item_images = item_images; } @Override public int getCount() { // TODO Auto-generated method stub return item_images.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LinearLayout layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); layout.setGravity(Gravity.CENTER); TextView tv_item = new TextView(context); tv_item.setGravity(Gravity.CENTER); tv_item.setLayoutParams(new GridView.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tv_item.setText(item_names.get(position)); ImageView img_item = new ImageView(context); img_item.setLayoutParams(new LayoutParams(50, 50)); img_item.setImageResource(item_images.get(position)); layout.addView(img_item); layout.addView(tv_item); return layout; } }
Java
package ui.activity; import java.util.List; import ui.viewModel.IOnViewModelUpated; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import app.MyApplication; import com.mysport.ui.*; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public abstract class ActivityOfAF4Ad extends Activity { // tag标记,用于输出调试信息 static String tag = "MyApplication"; // 视图模型 protected ViewModel vm; public ViewModel getVm() { return vm; } public void setVm(ViewModel aVM) { if (this.vm != aVM) { this.vm = aVM; // 触发视图模型更新事件 if (vm != null) { vm.fireOnUpdted(); } } } // 视图模型更新的监听器 private OnViewModelUpdated listener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 加载视图 setContentView(R.layout.activity_af4ad); // 初始化视图模型 this.vm = null; // 考虑Activity跳转时,获取从MyApplication转发过来的ViewModel Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { this.vm = ViewModel.readFromBundle(bundle); } // 构造监听器 setListener(new OnViewModelUpdated()); Log.d(tag, "in OnCreate..."); } @Override protected void onPostCreate(android.os.Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Log.d(tag, "in onPostCreate..."); // 获取初始视图模型 if (vm == null) { vm = initModel(); } Log.d(tag, "vm intialized..."); // 获取操作控件并注册控件事件 initControlsAndRegEvent(); Log.d(tag, "controls obtained...."); // 注册视图模型的监听者 if (vm != null) { int position = vm.findListener(getListener()); Log.d(tag, "finding listener..."); // 是否已加入过 if (position == -1) { // 注册视图模型的监听者 vm.addListener(getListener()); Log.d(tag, "listener added"); } } // 更新视图 if (vm != null) { upDateView(vm); } } @Override protected void onDestroy() { if (vm != null) { int position = vm.findListener(getListener()); if (position > -1) { vm.removeListener(getListener()); } } super.onDestroy(); } // 获取操作控件并注册控件事件 protected abstract void initControlsAndRegEvent(); // 获取初始的视图模型 protected abstract ViewModel initModel(); // 更新视图 protected abstract void upDateView(ViewModel aVM); /** * 处理视图模型错误 * @param errsOfVM:第一个参数给出了出错的属性名和出错消息, * @param errMsg:按每个属性出错误一行的格式给出错误消息 */ protected abstract void processViewModelErrorMsg( List<ModelErrorInfo> errsOfVM, String errMsg); /** * 视图模型更新的监听器类 **/ /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ private class OnViewModelUpdated implements IOnViewModelUpated { @Override // 视图模型更新后的回调方法 public void onUpdated(ViewModel vm) { upDateView(vm); } @Override // 发现视图模型错误时的回调方法 public void onViewModelInError(List<ModelErrorInfo> errsOfVM) { String errTxt = ""; for (int i = 0; i < errsOfVM.size(); i++) { errTxt += errsOfVM.get(i).getErrMsg() + "\n"; } //调用子类的处理视图模型错误方法 processViewModelErrorMsg(errsOfVM, errTxt); } } /** * 跳转至其它Activity * @param frmActObj:源Activity对象 * @param toActCls:目标Activity类的描述对象可用ActivityX.class */ protected void toActivity(Activity frmActObj, Class<?> toActCls) { //设定Activity跳转广播 Intent toAppIntent = new Intent("ViewForwardBroadcast"); String frmActClsName=frmActObj.getClass().getName(); String toActClsName=toActCls.getName(); toAppIntent.putExtra("frmActClsNm", frmActClsName); toAppIntent.putExtra("toActClsNm", toActClsName); //将源Activity的ViewMode打包 if (this.vm != null) { Bundle bdlOfFrmAct = new Bundle(); bdlOfFrmAct = vm.writeToBundle(); toAppIntent.putExtras(bdlOfFrmAct); } //设定接收广播对象 IntentFilter filter = new IntentFilter("ViewForwardBroadcast"); registerReceiver(MyApplication.VWFWDRCV, filter); //发送广播 sendBroadcast(toAppIntent); } public OnViewModelUpdated getListener() { return listener; } public void setListener(OnViewModelUpdated listener) { this.listener = listener; } }
Java
package ui.activity.weather; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.ksoap2.serialization.SoapObject; import android.os.AsyncTask; import android.os.Bundle; import android.view.GestureDetector; import android.view.Menu; import android.view.GestureDetector.OnGestureListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.mysport.ui.R; import foundation.webservice.GeocodeService; import foundation.webservice.WeatherService; import tool.SunriseSunset.SunriseSunset; import ui.activity.ActivityOfAF4Ad; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; public class WeatherActivity extends ActivityOfAF4Ad { private ImageView todayWhIcon = null; private TextView tv_todaydate = null; private TextView tv_currentTemperature = null; private TextView tv_today_Temp = null; private TextView tv_today_windspeed = null; private ImageView tomorrowWhIcon = null; private TextView tv_tomorrowdate = null; private TextView tv_tomorrow_Temp = null; private TextView tv_tomorrow_windspeed = null; private TextView today_sunrisetime = null;// private TextView today_sunsettime = null;// protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); SunriseAndSetAsyncTask calculate = new SunriseAndSetAsyncTask(); RequireWeatherAsyncTask require = new RequireWeatherAsyncTask(); require.execute(); calculate.execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_weather, menu); return true; } @Override protected void initControlsAndRegEvent() { todayWhIcon = (ImageView) findViewById(R.id.todayWhIcon); tv_todaydate = (TextView) findViewById(R.id.tv_todaydate); tv_currentTemperature = (TextView) findViewById(R.id.tv_currentTemperature); tv_today_Temp = (TextView) findViewById(R.id.tv_today_Temp); tv_today_windspeed = (TextView) findViewById(R.id.tv_today_windspeed); tomorrowWhIcon = (ImageView) findViewById(R.id.tomorrowWhIcon); tv_tomorrowdate = (TextView) findViewById(R.id.tv_tomorrowdate); // tv_currentTemperature = (TextView) // findViewById(R.id.tv_currentTemperature); // tv_tomorrow_Temp = (TextView) findViewById(R.id.tv_tomorrow_Temp); tv_tomorrow_windspeed = (TextView) findViewById(R.id.tv_tomorrow_windspeed); tv_tomorrow_Temp = (TextView) findViewById(R.id.tv_tomorrow_Temp); today_sunrisetime = (TextView) findViewById(R.id.today_sunrisetime); today_sunsettime = (TextView) findViewById(R.id.today_sunsettime); } @Override protected ViewModel initModel() { // TODO Auto-generated method stub return null; } @Override protected void upDateView(ViewModel aVM) { // TODO Auto-generated method stub } @Override protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM, String errMsg) { // TODO Auto-generated method stub } // 多线程实现天气查询 class RequireWeatherAsyncTask extends AsyncTask<Void, Void, SoapObject> { @Override protected SoapObject doInBackground(Void... arg0) { String city; city = GeocodeService.getAddressByLatLng(LatLngReceiver.getLat(), LatLngReceiver.getLng(), 2); return WeatherService.getWeatherByCity(city); } @Override protected void onPostExecute(SoapObject detail) { // TODO Auto-generated method stub showWeather(detail); } } private void showWeather(SoapObject detail) { if (detail == null) { initModel(); return; } String weatherToday = null; String weatherTomorrow = null; String weatherCurrent = null; int iconToday; int iconTomorrow; // int iconAfterday[] = new int[2]; // 获取天气实况 weatherCurrent = detail.getProperty(4).toString().substring(10, 13); tv_currentTemperature.setText(weatherCurrent); // 解析今天的天气情况 String date = detail.getProperty(7).toString(); weatherToday = "今天:" + date.split(" ")[0]; weatherToday = weatherToday + " " + date.split(" ")[1]; tv_todaydate.setText(weatherToday); weatherToday = detail.getProperty(8).toString();// 今日气温范围 tv_today_Temp.setText(weatherToday); weatherToday = detail.getProperty(9).toString(); tv_today_windspeed.setText(weatherToday); iconToday = parseIcon(detail.getProperty(10).toString()); todayWhIcon.setImageResource(iconToday); // iconToday[1] = parseIcon(detail.getProperty(11).toString()); // 解析明天的天气情况 date = detail.getProperty(12).toString(); weatherTomorrow = "明天:" + date.split(" ")[0]; weatherTomorrow = weatherTomorrow + " " + date.split(" ")[1]; tv_tomorrowdate.setText(weatherTomorrow); weatherTomorrow = detail.getProperty(13).toString(); tv_tomorrow_Temp.setText(weatherTomorrow); weatherTomorrow = detail.getProperty(14).toString(); tv_tomorrow_windspeed.setText(weatherTomorrow); iconTomorrow = parseIcon(detail.getProperty(15).toString()); tomorrowWhIcon.setImageResource(iconTomorrow); // iconTomorrow[1] = parseIcon(detail.getProperty(16).toString()); } // 工具方法,该方法负责把返回的天气图标字符串。转换为程序的图片资源ID private int parseIcon(String strIcon) { // TODO 自动生成的方法存根 // 根据字符串解析天气图标的代码 if (strIcon == null) return -1; if ("0.gif".equals(strIcon)) return R.drawable.a_0; if ("1.gif".equals(strIcon)) return R.drawable.a_1; if ("2.gif".equals(strIcon)) return R.drawable.a_2; if ("3.gif".equals(strIcon)) return R.drawable.a_3; if ("4.gif".equals(strIcon)) return R.drawable.a_4; if ("5.gif".equals(strIcon)) return R.drawable.a_5; if ("6.gif".equals(strIcon)) return R.drawable.a_6; if ("7.gif".equals(strIcon)) return R.drawable.a_7; if ("8.gif".equals(strIcon)) return R.drawable.a_8; if ("9.gif".equals(strIcon)) return R.drawable.a_9; if ("10.gif".equals(strIcon)) return R.drawable.a_10; if ("11.gif".equals(strIcon)) return R.drawable.a_11; if ("12.gif".equals(strIcon)) return R.drawable.a_12; if ("13.gif".equals(strIcon)) return R.drawable.a_13; if ("14.gif".equals(strIcon)) return R.drawable.a_14; if ("15.gif".equals(strIcon)) return R.drawable.a_15; if ("16.gif".equals(strIcon)) return R.drawable.a_16; if ("17.gif".equals(strIcon)) return R.drawable.a_17; if ("18.gif".equals(strIcon)) return R.drawable.a_18; if ("19.gif".equals(strIcon)) return R.drawable.a_19; if ("20.gif".equals(strIcon)) return R.drawable.a_20; if ("21.gif".equals(strIcon)) return R.drawable.a_21; if ("22.gif".equals(strIcon)) return R.drawable.a_22; if ("23.gif".equals(strIcon)) return R.drawable.a_23; if ("24.gif".equals(strIcon)) return R.drawable.a_24; if ("25.gif".equals(strIcon)) return R.drawable.a_25; if ("26.gif".equals(strIcon)) return R.drawable.a_26; if ("27.gif".equals(strIcon)) return R.drawable.a_27; if ("28.gif".equals(strIcon)) return R.drawable.a_28; if ("29.gif".equals(strIcon)) return R.drawable.a_29; if ("30.gif".equals(strIcon)) return R.drawable.a_30; if ("31.gif".equals(strIcon)) return R.drawable.a_31; return 0; } class SunriseAndSetAsyncTask extends AsyncTask<Void,Void,Date[]>{ private double lat; private double lng; @Override protected Date[] doInBackground(Void... params) { lat = LatLngReceiver.getLat(); lng = LatLngReceiver.getLng(); Date now = new Date(); Date[] riseSet = new Date[2]; SunriseSunset sunriseSunset = new SunriseSunset(lat, lng, now, 0); riseSet[0]=sunriseSunset.getSunrise(); riseSet[1]=sunriseSunset.getSunset(); return riseSet; } @Override protected void onPostExecute(Date[] result) { SimpleDateFormat sf = new SimpleDateFormat("hh:mm:ss"); today_sunrisetime.setText(sf.format(result[0])); today_sunsettime.setText(sf.format(result[1])); } } }
Java
package ui.activity.weather; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class LatLngReceiver extends BroadcastReceiver { private static double lat; private static double lng; @Override public void onReceive(Context context, Intent intent) { lat = intent.getExtras().getDouble("Lat"); lng = intent.getExtras().getDouble("Lng"); } public static double getLat(){ return lat; } public static double getLng(){ return lng; } }
Java
package ui.activity.app; import com.mysport.ui.R; import com.mysport.ui.R.layout; import com.mysport.ui.R.menu; import android.os.Bundle; import android.app.Activity; import android.view.Menu; //该Activity为测试用,可刪去 public class DefaultActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_default); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_default, menu); return true; } }
Java
package ui.viewModel; import java.util.List; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public interface IOnViewModelUpated { //视图模型更新后的回调方法 public void onUpdated(ViewModel vm); //发现视图模型错误时的回调方法 public void onViewModelInError(List<ModelErrorInfo> errsOfVM); }
Java
package ui.viewModel.gps; import java.util.Date; import java.util.List; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; public class RecordViewModel extends ViewModel { private String ClimbName; private Date starTime; public String getClimbName() { return ClimbName; } public void setClimbName(String climbName) { ClimbName = climbName; } public Date getStarTime() { return starTime; } public void setStarTime(Date starTime) { this.starTime = starTime; } @Override public List<ModelErrorInfo> verifyModel() { // TODO Auto-generated method stub return null; } }
Java
package ui.viewModel.gps; import java.util.Date; import java.util.List; import domain.businessEntity.gps.ClimbData; import ui.viewModel.ModelErrorInfo; import ui.viewModel.ViewModel; public class RecDetailViewModel extends ViewModel { private String ClimbName; private int startAltitude; private int stopAltitude; private Date startTime; private Date stopTime; private String longitude; private String latitude; private ClimbData climbdata; public ClimbData getClimbdata() { return climbdata; } public void setClimbdata(ClimbData climbdata) { this.climbdata = climbdata; } public int getStartAltitude() { return startAltitude; } public void setStartAltitude(int startAltitude) { this.startAltitude = startAltitude; } public int getStopAltitude() { return stopAltitude; } public void setStopAltitude(int stopAltitude) { this.stopAltitude = stopAltitude; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getStopTime() { return stopTime; } public void setStopTime(Date stopTime) { this.stopTime = stopTime; } public String getClimbName() { return ClimbName; } public void setClimbName(String climbName) { ClimbName = climbName; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } @Override public List<ModelErrorInfo> verifyModel() { // TODO Auto-generated method stub return null; } }
Java
package ui.viewModel.attributeReflection; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public class AttributeReflection { /** * Android平台下可以直接打包的类(int,char等可直接打包,如发现遗漏可以再添加) */ static String[] CANPARCELABLECALSSNAMES = { "java.lang.String", "java.util.Date", "Integer", "Float", "Boolean", "Double", "Character", "Byte", "Short", "Long" }; /** * 目前只考虑集合类List,后期可再添加其它集合类 */ static String[] CANPROCESSSETNAMES = { "java.util.List" }; public enum FieldKind { /** * 可直接打包的原子类型(其包括CANPARCELABLECALSSNAMES中的类和 Java中的原子类型如int,char等)的属性 */ ParcelableAtomicField, /** * 可直接打包的集合类型(目前仅考虑List)的属性 如List<int>或List<String> */ ParcelableCollectionField, /** * 不可直接打包的集合类型(目前仅考虑List)的属性 * */ CantParceCollectionField, /** * 用户自定义类型的属性,不可直接打包 * */ ClassUserDefinedField; } /** * 根据给定的对象获取该对象所有属性名称、类型和值, 并存放在AttInfo列表中 * * @param obj * :输入的任意一个对象 * @return:输入对象的属性信息列表,空对象则返回null * @throws ClassNotFoundException * :该对象对应类定义未发现 * @throws IllegalArgumentException * :参数异常 * @throws IllegalAccessException * :私有属性不允许访问 * @throws InstantiationException * :实例化对象异常 */ public static List<AttInfo> getAttInfosFromObject(Object obj) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException { List<AttInfo> attInfos = null; if (obj == null) return attInfos; Class<?> aClass = Class.forName(obj.getClass().getName()); Field[] flds = aClass.getDeclaredFields(); int len = flds.length; attInfos = new ArrayList<AttInfo>(); // 根据对象类中每个属性 for (int i = 0; i < len; i++) { Field fld = flds[i]; fld.setAccessible(true); String attName = fld.getName(); String typeName = fld.getType().getName(); AttInfo info = new AttInfo(); info.setAttName(attName); info.setTypeName(typeName); Object value = fld.get(obj); FieldKind fldKind = getFieldKind(fld); // 可打包原子类型或是可打包的集合List类型的属性 if (fldKind == FieldKind.ParcelableAtomicField || fldKind == FieldKind.ParcelableCollectionField) { info.setValue(value); info.setComplexAtt(null); } else { if (fldKind == FieldKind.ClassUserDefinedField) { // 用户自定义类 info.setValue(null); // 自定义类中所有子对象的属性信息存放在AttInfosOfDefinedClass List<AttInfo> AttInfosOfDefinedClass = getAttInfosFromObject(value); info.setComplexAtt(AttInfosOfDefinedClass); } else { info.setValue(null); List<AttInfo> attInfosInSet = getAttInfosFromCantParceSetField( fld, value); info.setComplexAtt(attInfosInSet); } } attInfos.add(info); } return attInfos; } /** * 类名和属性信息列表中,构建出对象 * * @param className * :类名 * @param attInfos * :类对象所对应的属性信息 * @return:根据属性信息构造出的对象 * @throws ClassNotFoundException * :类名对应的类未发现 * @throws InstantiationException * :实例化异常 * @throws IllegalAccessException * :私有属性不允许访问 * @throws NoSuchFieldException * :属性找不到 */ public static Object getOjectFromAttInfos(String className, List<AttInfo> attInfos) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException { Object obj = null; if (className == null || attInfos == null) { return obj; } Class<?> cls = Class.forName(className); obj = cls.newInstance(); int len = attInfos.size(); Class<?> cls2 = obj.getClass(); for (int i = 0; i < len; i++) { AttInfo att = attInfos.get(i); String attName = att.getAttName(); String typeName = att.getTypeName(); Object value = att.getValue(); Field fld = cls2.getDeclaredField(attName); fld.setAccessible(true); if (value != null) {// 可直接打包类型 fld.set(obj, value); } else {// 是集合类型或自定义类型 boolean isCollectionType = false; for (String name : CANPROCESSSETNAMES) { if (typeName.equals(name)) { isCollectionType = true; } } if (isCollectionType) {// 是集合类型 List<Object> subObjs = getSubObjectsFormListField(att); fld.set(obj, subObjs); } else {// 是自定类型 Object subObj = getOjectFromAttInfos(typeName, att.getComplexAtt()); fld.set(obj, subObj); } } } return obj; } /** * 判断一个类的属性Field,在Android下是否可直接打包, 目前只考虑基本类型、自定义类型和List集合三种属性Field * * @param Field * :属性 * @return true:是可直接打包的Field,false:不可直接打包的Field */ private static boolean isParcelableBasicTypeField(final Field fld) { boolean result = false; Class<?> fldType = fld.getType(); String fldTypeName = fldType.getName(); if (fldType.isPrimitive()) {// 是否是基本类型 result = true; } else {// 是否是可直接打包类型 for (String typeName : CANPARCELABLECALSSNAMES) { if (fldTypeName.equals(typeName)) { result = true; break; } } } return result; } /** * * @param fld * :属性 * @return:属性的种类(可直接打包的原子类型属性ParcelableAtomicField、 * 不可直接打包的集合类型属性CantParceCollectionField * 、 * 可直接打包的集合类型属性ParcelableCollectionField * 、 用户自定义类型的属性 * @throws ClassNotFoundException * :fld对应类未发现 */ private static FieldKind getFieldKind(Field fld) throws ClassNotFoundException { FieldKind kind = FieldKind.CantParceCollectionField; boolean isCollectionType = false; String fldTypeName = fld.getType().getName(); // 判断是否是集合类型 for (String name : CANPROCESSSETNAMES) { if (fldTypeName.equals(name)) { isCollectionType = true; } } // 是否集合类型,则判定其kind if (isCollectionType) { // 得到参数类名(List<T>中T的名字) Type fldGenericType = fld.getGenericType(); String parameterizedTypeName = ""; Type[] types = ((ParameterizedType) fldGenericType) .getActualTypeArguments(); String str = types[0].toString(); int len = str.length(); parameterizedTypeName = str.substring(6, len); // 获取参数类的属性 Class<?> typeClss; typeClss = Class.forName(parameterizedTypeName); Field[] flds = typeClss.getDeclaredFields(); // 判断List<T>中T是不是基本类型,并进一步判断T是否可直接打包, // 如可则List<T>也可直接打包 if (flds.length == 1) { if (isParcelableBasicTypeField(flds[0])) { kind = FieldKind.ParcelableCollectionField; } } } else {// 不考虑其它情况,只剩下基本类型和自定义类型 if (isParcelableBasicTypeField(fld)) { kind = FieldKind.ParcelableAtomicField; } else { kind = FieldKind.ClassUserDefinedField; } } return kind; } /** * * @param listfld * :List类型属性 * @param value * :该属性的值 * @return:该属性下的所有子对象的属性信息列表 * @throws ClassNotFoundException * :找不到子对象对应的类 * @throws InstantiationException * :实例化子对象 * @throws IllegalAccessException * :访问属性异常 */ public static List<AttInfo> getAttInfosFromCantParceSetField(Field listfld, Object value) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // 不可打包的集合类型 List<AttInfo> AttInfosInSetField = null; if (value == null) { return AttInfosInSetField; } // 获取参数类的名称 Type fldGenericType = listfld.getGenericType(); String parameterizedTypeName = ""; Type[] types = ((ParameterizedType) fldGenericType) .getActualTypeArguments(); String str = types[0].toString(); int len2 = str.length(); parameterizedTypeName = str.substring(6, len2); Class<?> ParameterizedClass = Class.forName(parameterizedTypeName); List<Object> subObjs = (List<Object>) value; int numOfSubOj = subObjs.size(); AttInfosInSetField = new ArrayList<AttInfo>(); // 对每个子对象进行递归 for (int k = 0; k < numOfSubOj; k++) { Object subObj = ParameterizedClass.newInstance(); subObj = subObjs.get(k); // 一个子象中的属性信息 AttInfo subAttInfo = new AttInfo(); subAttInfo.setAttName(Integer.toString(k)); subAttInfo.setTypeName(parameterizedTypeName); subAttInfo.setValue(null); List<AttInfo> AttInfosInSubOject = getAttInfosFromObject(subObj); subAttInfo.setComplexAtt(AttInfosInSubOject); AttInfosInSetField.add(subAttInfo); } return AttInfosInSetField; } public static List<Object> getSubObjectsFormListField(AttInfo att) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException { List<Object> subObjs = null; List<AttInfo> subAttInfos = att.getComplexAtt(); if (subAttInfos == null) { return subObjs; } int numOfSubObjs = subAttInfos.size(); if (numOfSubObjs >= 1) { subObjs = new ArrayList<Object>(); } for (int j = 0; j < numOfSubObjs; j++) { String subClassName = subAttInfos.get(j).getTypeName(); List<AttInfo> AttInfosInThisSubObj = subAttInfos.get(j) .getComplexAtt(); Object subObj = getOjectFromAttInfos(subClassName, AttInfosInThisSubObj); subObjs.add(subObj); } return subObjs; } }
Java
package ui.viewModel.attributeReflection; import java.util.List; import android.os.Parcel; import android.os.Parcelable; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public class AttInfo implements Parcelable { // 属性名 private String attName; // 属性的类型名 private String typeName; // 属性值,如属性是Android下不可直接打包的类,则此值为空 private Object value; // 属性信息列表,仅在属性的类型为不可直接打包类时使用 private List<AttInfo> complexAtt; public String getAttName() { return attName; } public void setAttName(String attName) { this.attName = attName; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public List<AttInfo> getComplexAtt() { return complexAtt; } public void setComplexAtt(List<AttInfo> complexAtt) { this.complexAtt = complexAtt; } /** * 将属性信息对象写到Parcel中,实现Parcelable接口中方法 */ @Override public int describeContents() { return 0; } /** * 实现Parcelable接口中Parcel的构造类 */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(attName); dest.writeString(typeName); if (complexAtt == null) { dest.writeValue(value); } else { dest.writeValue(null); int len = complexAtt.size(); for (int i = 0; i < len; i++) { AttInfo subAtt = complexAtt.get(i); subAtt.writeToParcel(dest, flags); } } } /** * 实现Parcelable接口中Parcel的构造类 */ public static final Parcelable.Creator<AttInfo> CREATOR = new Parcelable.Creator<AttInfo>() { // 从Parcel中构造出属性信息对象 public AttInfo createFromParcel(Parcel in) { AttInfo attInfo = new AttInfo(); attInfo.attName = in.readString(); attInfo.typeName = in.readString(); attInfo.value = in.readValue(null); if (attInfo.value != null) {// 简单属性 attInfo.complexAtt = null; } else {// 含子属性列表 Parcel subParcel = (Parcel) in.readValue(null); createFromParcel(subParcel); } return attInfo; } /** * 生成属性信息对象数组,实现Parcelable接口中方法 */ public AttInfo[] newArray(int size) { return new AttInfo[size]; } }; }
Java
package ui.viewModel; import java.util.ArrayList; import java.util.List; import ui.viewModel.attributeReflection.AttInfo; import ui.viewModel.attributeReflection.AttributeReflection; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public abstract class ViewModel { static String tag = "ViewModel"; /** * 定义两个常量用ViewModel对象打包使用 CLASSNAME表示类名,FIELDLIST属性列表 */ public static String CLASSNAME = "ClassName"; public static String FIELDLIST = "FieldList"; // 监听者列表 List<IOnViewModelUpated> listeners = null; // 触发视图模型更新事件 public void fireOnUpdted() { List<ModelErrorInfo> errs = verifyModel(); // 检验视图模型是否正确 if (errs == null) {//视图模型正确 // 回调每一个监听者的onUpdated方法 for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onUpdated(this); } } else {//视图模型不正确; // 回调每一个监听者的onViewModelInError方法 for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onViewModelInError(errs); } } } /* *检验模型,将出错属性及对应的错误消息构造ModelErrorInfo对象, 形成列表返回, 如果模型正确则返回null */ public abstract List<ModelErrorInfo> verifyModel(); // 增加一个监听者 public void addListener(IOnViewModelUpated aListener) { listeners.add(aListener); } // 删除一个监听者 public Boolean removeListener(IOnViewModelUpated aListener) { return listeners.remove(aListener); } // 查找一个监听者 public int findListener(IOnViewModelUpated aListener) { return listeners.indexOf(aListener); } public ViewModel() { this.listeners = new ArrayList<IOnViewModelUpated>(); } /** * 将ViewMode对象的每个属性,形成attInfo对象(可能含子对象), 写入Bundle进行保存 * * @return: 返回ViewModel对象的打包,异常时返回null */ public Bundle writeToBundle() { Bundle bdl = null; List<AttInfo> attInfos = null; try { // 获取ViewModel对象对应的属性信息列表 attInfos = AttributeReflection.getAttInfosFromObject(this); if (attInfos == null) { return bdl; } int len = attInfos.size(); if (len > 0) { bdl = new Bundle(); AttInfo[] arrayOfAttInfo=new AttInfo[len]; for(int j=0;j<len;j++){ arrayOfAttInfo[j]=attInfos.get(j); } bdl.putString(CLASSNAME, this.getClass().getName()); bdl.putParcelableArray(FIELDLIST, arrayOfAttInfo); } } catch (InstantiationException e) { Log.e(tag, e.getMessage()); } catch (IllegalArgumentException e) { Log.e(tag, e.getMessage()); } catch (ClassNotFoundException e) { Log.e(tag, e.getMessage()); } catch (IllegalAccessException e) { Log.e(tag, e.getMessage()); } return bdl; } /** * 从Pacel创建VieModel对象 * * @param in * :ViewModel对象的属性打包对象 * @return:返回解包后的ViewModel对象 * */ public static ViewModel readFromBundle(Bundle in) { ViewModel vm = null; if(in==null){ return vm; } String clsName = in.getString(CLASSNAME); Parcelable[] arrayOfField = in.getParcelableArray(FIELDLIST); if (clsName != null && arrayOfField!=null) { int len = arrayOfField.length; List<AttInfo> viewModelFields = new ArrayList<AttInfo>(); for (int i = 0; i < len; i++) { viewModelFields.add((AttInfo) arrayOfField[i]); } try { vm = (ViewModel) AttributeReflection.getOjectFromAttInfos(clsName, viewModelFields); } catch (ClassNotFoundException e) { Log.e(tag, e.getMessage()); } catch (InstantiationException e) { Log.e(tag, e.getMessage()); } catch (IllegalAccessException e) { Log.e(tag, e.getMessage()); } catch (NoSuchFieldException e) { Log.e(tag, e.getMessage()); } } return vm; }; }
Java
package ui.viewModel; /** * * @author 福建师范大学软件学院 倪友聪、赵康 * */ public class ModelErrorInfo { //错误属性名称 private String errAttName; //错误消息 private String errMsg; //获取属性名称 public String getAttName() { return this.errAttName; } //设置属性名称 public void setErrAttName(String aErrAttName){ this.errAttName=aErrAttName; } //获取错误消息 public String getErrMsg(){ return this.errMsg; } //设置错误消息 public void setErrMsg(String aErrMsg){ this.errMsg=aErrMsg; } public ModelErrorInfo(){ } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sv; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author PC-PC */ @WebServlet(name = "AddSinhVien", urlPatterns = {"/AddSinhVien"}) public class AddSinhVien extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String username = null; String password = null; String firstname = null; String lastname = null; String email = null; username = request.getParameter("username"); password = request.getParameter("passid"); firstname = request.getParameter("firstname"); lastname = request.getParameter("lastname"); email = request.getParameter("email"); //chen vao co so du lieu if (insertUser(username, password, firstname, lastname, email)) { session.setAttribute("UserName", username); session.setAttribute("Access", "member"); //gan sesssion cho UserId RequestDispatcher rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else { RequestDispatcher rd = request.getRequestDispatcher("registerMember.jsp"); request.setAttribute("addMemberInvalid", false); rd.forward(request, response); } } public static boolean insertUser(String username, String password, String firstname, String lastname, String email) { boolean isInsert = false; //ket noi voi co so du lieu Connection conn = getConnection(); //chuyen password thanh ma md5 String hashtest = convertMD5(password); //chuyen du lieu ve kieu ngay String call = "{call sp_Insert_Member(?,?,?,?,?,?,?,?,?)}"; try { CallableStatement callbleStatememt = conn.prepareCall(call); callbleStatememt.setString(1, username); callbleStatememt.setString(2, password); callbleStatememt.setString(3, firstname); callbleStatememt.setString(4, lastname); callbleStatememt.setString(5, password); callbleStatememt.executeUpdate(); isInsert = true; System.out.println("them thanh cong"); } catch (SQLException e) { System.out.println("loi insert co so du lieu"); e.printStackTrace(); } finally { System.out.println("dong ket noi"); try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return isInsert; } public static String convertMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digit = md.digest(); BigInteger bigInt = new BigInteger(1, digit); String hashtext = bigInt.toString(16); return hashtext; } catch (NoSuchAlgorithmException e) { } catch (NullPointerException ex) { System.out.println(ex); } return null; } public static Connection getConnection() { Connection con = null; try { // ket noi vs Microsoft sql server Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://PC\\SQLEXPRESSt:1433;" + "databaseName=StudentManagement;"; con = DriverManager.getConnection(url, "sa", "123456"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { System.out.println("Loi Ket Noi!"); } return con; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mahoamd5; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author PC-PC */ public class MahoaMD5 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } public boolean isValidAccount(String userName, String password) { String hashtext = convertMD5(password); System.out.println("password MD5: " + hashtext); // if (checkMember(userName, hashtext) > 0) { // return true; // } return false; } public static String convertMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digit = md.digest(); BigInteger bigInt = new BigInteger(1, digit); String hashtext = bigInt.toString(16); return hashtext; } catch (NoSuchAlgorithmException e) { } catch (NullPointerException ex) { System.out.println(ex); } return null; } }
Java
package org.esgl3d.spatial; import java.util.ArrayList; import org.esgl3d.rendering.RenderQueue; import org.esgl3d.scene.CameraNode; import org.esgl3d.scene.Scene; import org.esgl3d.scene.SceneNode; public class NoneSpatialStructure implements SpatialStructure { private final Scene attachedScene; public NoneSpatialStructure(Scene scene) { attachedScene = scene; } @Override public void getVisibleNodes(CameraNode cam, RenderQueue queue) { for (SceneNode curNode : attachedScene.getChildren()) renderNode(queue, curNode); } private void renderNode(RenderQueue queue, SceneNode node) { queue.add(node); if (node.hasChildren()) { ArrayList<SceneNode> childs = node.getChildren(); for(SceneNode curNode : childs) { renderNode(queue, curNode); } } } @Override public void rebuild() { // TODO Auto-generated method stub } @Override public void update(SceneNode node) { // TODO Auto-generated method stub } }
Java
package org.esgl3d.spatial; import org.esgl3d.rendering.RenderQueue; import org.esgl3d.scene.CameraNode; import org.esgl3d.scene.SceneNode; /** * Basic interface for any kind of spartial tree. * @author michael * */ public interface SpatialStructure { /** * Performs a full rebuild of the internal structure */ public void rebuild(); /** * Updates information of a single scene node. * * @param node Node to update in the graph. */ public void update(SceneNode node); /** * Iterates the structure and adds visible nodes into the * rendering queue. * * @param cam The currently active camera. * @param queue The queue in which visible nodes are added. */ public void getVisibleNodes(CameraNode cam, RenderQueue queue); }
Java
package org.esgl3d.rendering; import java.util.ArrayList; import org.esgl3d.scene.SceneNode; public class RenderQueue { public enum RenderBucket { Solid, Transparent, } private ArrayList<SceneNode> nodesToRender = new ArrayList<SceneNode>(); public void reset() { nodesToRender.clear(); } public void add(SceneNode node) { nodesToRender.add(node); } public ArrayList<SceneNode> getNodesToRender() { return nodesToRender; } }
Java
package org.esgl3d.rendering; /** * @author michael * This class represents options which specify how a vertex container is created. */ public class VertexContainerOptions { private final boolean forceVertexArray; public boolean isVertexArrayForced() { return forceVertexArray; } public VertexContainerOptions(boolean setVertexArray) { forceVertexArray = setVertexArray; } public static final VertexContainerOptions STATIC = new VertexContainerOptions(false); public static final VertexContainerOptions DYNAMIC = new VertexContainerOptions(false); public static final VertexContainerOptions FULL_DYNAMIC = new VertexContainerOptions(true); }
Java
package org.esgl3d.rendering; import java.util.logging.Level; import java.util.logging.Logger; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; class VertexBuffer extends VertexContainer { private static Logger logger = Logger.getLogger(VertexBuffer.class.getName()); private final int vertexBufferId; private final GL11 gl; public VertexBuffer(int sizeInBytes, VertexFormat type, GL11 gl) { super(sizeInBytes, type); this.gl = gl; int[] buffer = new int[1]; gl.glGenBuffers(1, buffer, 0); vertexBufferId = buffer[0]; if (logger.isLoggable(Level.FINEST)) logger.finest(String.format("VBO-Id: %d", vertexBufferId)); } void bind() { gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexBufferId); } void unbind() { gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); } @Override public void draw(PrimitiveType type, int startVerticeIndex, int numberOfVertices) { int glType = GL11.GL_TRIANGLES; switch (type) { case Line: glType = GL11.GL_LINES; break; case Point: glType = GL11.GL_POINTS; break; case TriangleStrip: glType = GL11.GL_TRIANGLE_STRIP; break; case Triangle: break; } bind(); if (format.components[VertexFormat.COLOR] > 0) { gl.glEnableClientState(GL11.GL_COLOR_ARRAY); if (structure == BufferStructure.Stacked) gl.glColorPointer(format.components[VertexFormat.COLOR], GL11.GL_FLOAT, 0, format.offsets[VertexFormat.COLOR] * numberOfVertices*4); else gl.glColorPointer(format.components[VertexFormat.COLOR], GL11.GL_FLOAT, format.totalFloats*4, format.offsets[VertexFormat.COLOR]*4); } else gl.glDisableClientState(GL11.GL_COLOR_ARRAY); if (format.components[VertexFormat.NORMAL] > 0) { gl.glEnableClientState(GL11.GL_NORMAL_ARRAY); if (structure == BufferStructure.Stacked) gl.glNormalPointer(GL11.GL_FLOAT, 0, format.offsets[VertexFormat.NORMAL] * numberOfVertices*4); else gl.glNormalPointer(GL11.GL_FLOAT, format.totalFloats*4, format.offsets[VertexFormat.NORMAL] *4); } else gl.glDisableClientState(GL11.GL_NORMAL_ARRAY); if (format.components[VertexFormat.TEXTURE] > 0) { gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); if (structure == BufferStructure.Stacked) gl.glTexCoordPointer(format.components[VertexFormat.TEXTURE], GL11.GL_FLOAT, 0, format.offsets[VertexFormat.TEXTURE] * numberOfVertices*4); else gl.glTexCoordPointer(format.components[VertexFormat.TEXTURE], GL11.GL_FLOAT, format.totalFloats*4, format.offsets[VertexFormat.TEXTURE] *4); } else gl.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); if (format.components[VertexFormat.POSITION] > 0) { gl.glEnableClientState(GL11.GL_VERTEX_ARRAY); if (structure == BufferStructure.Stacked) gl.glVertexPointer(format.components[VertexFormat.POSITION], GL11.GL_FLOAT, 0, format.offsets[VertexFormat.POSITION] * numberOfVertices*4); else gl.glVertexPointer(format.components[VertexFormat.POSITION], GL11.GL_FLOAT, format.totalFloats*4, format.offsets[VertexFormat.POSITION] *4); } else gl.glDisableClientState(GL11.GL_VERTEX_ARRAY); gl.glDrawArrays(glType, startVerticeIndex, numberOfVertices); unbind(); } @Override public void synchronize() { bind(); buffer.position(0); gl.glBufferData(GL11.GL_ARRAY_BUFFER, buffer.capacity()*4, buffer, GL11.GL_STATIC_DRAW); } }
Java
package org.esgl3d.rendering; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; import android.opengl.GLUtils; public class TextureManager { private GL10 gl; public void setGl(GL10 value) { gl = value; } public Texture addImage(Bitmap bitmap, boolean mipmaps) { IntBuffer texturesBuffer = IntBuffer.allocate(1); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glGenTextures(1, texturesBuffer); gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesBuffer.get(0)); int textuteMode = GL10.GL_LINEAR; // setup texture parameters if (mipmaps) textuteMode = GL10.GL_LINEAR_MIPMAP_LINEAR; gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, textuteMode); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, textuteMode); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); if (mipmaps) buildMipmap(gl, bitmap, 32); else buildMipmap(gl, bitmap, 1); Texture result = new Texture(texturesBuffer.get(0), bitmap.getWidth(), bitmap.getHeight()); return result; } void buildMipmap(GL10 gl, Bitmap bitmap, int count) { // int level = 0; // int height = bitmap.getHeight(); int width = bitmap.getWidth(); while ( (height >= 1 || width >= 1) && (count > 0) ) { // First of all, generate the texture from our bitmap and set it to // the according level GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); // if (height == 1 || width == 1) { break; } // Increase the mipmap level level++; // height /= 2; width /= 2; Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); // Clean up bitmap.recycle(); bitmap = bitmap2; count--; } } }
Java
package org.esgl3d.rendering; import java.nio.FloatBuffer; import org.esgl3d.rendering.VertexContainer.BufferStructure; /** * Acts as a wrapper for legacy opengl commands. Handles internal state * of color and texture coordinates. * * @author michael * */ public class LegacyGLWrapper { FloatBuffer buffer; private float a; private float r; private float g; private float b; private float u; private float v; private VertexFormat type; private int number; private int numberOfVertices; private VertexContainer container; public LegacyGLWrapper(FloatBuffer setBuffer, VertexFormat format, VertexContainer setContainer) { buffer = setBuffer; type = format; numberOfVertices = setContainer.getNumberOfVertices(); container = setContainer; } public void glBegin() { number = 0; } public void glVertex2f(float x, float y) { glVertex3f(x, y, 0); } public void glVertex3f(float x, float y, float z) { if (container.structure == BufferStructure.Stacked) { // write color parts if (type.components[VertexFormat.COLOR] > 0) { buffer.position(type.offsets[VertexFormat.COLOR]*numberOfVertices + number*type.components[VertexFormat.COLOR]); buffer.put(r); buffer.put(g); buffer.put(b); buffer.put(a); } // write texture parts if (type.components[VertexFormat.TEXTURE] > 0) { buffer.position(type.offsets[VertexFormat.TEXTURE]*numberOfVertices + number*type.components[VertexFormat.TEXTURE]); buffer.put(u); buffer.put(v); } // write vertex parts if (type.components[VertexFormat.POSITION] == 2) { buffer.position(type.offsets[VertexFormat.POSITION]*numberOfVertices + number*type.components[VertexFormat.POSITION]); buffer.put(x); buffer.put(y); } else if (type.components[VertexFormat.POSITION] == 3) { buffer.position(type.offsets[VertexFormat.POSITION]*numberOfVertices + number*type.components[VertexFormat.POSITION]); buffer.put(x); buffer.put(y); buffer.put(z); } } else { buffer.position(type.totalFloats * number); // write color parts if (type.components[VertexFormat.COLOR] > 0) { buffer.put(r); buffer.put(g); buffer.put(b); buffer.put(a); } // write texture parts if (type.components[VertexFormat.TEXTURE] > 0) { buffer.put(u); buffer.put(v); } // write vertex parts if (type.components[VertexFormat.POSITION] == 2) { buffer.put(x); buffer.put(y); } else if (type.components[VertexFormat.POSITION] == 3) { buffer.put(x); buffer.put(y); buffer.put(z); } } number ++; } public void glTexCoord2f(float u, float v) { this.u = u; this.v = v; } public void glColor4f(float r, float g, float b,float a) { this.a = a; this.r = r; this.g = g; this.b = b; } public void glEnd() { // does nothing } }
Java
package org.esgl3d.rendering; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import android.R.integer; public abstract class VertexContainer { public enum PrimitiveType { Triangle, TriangleStrip, Line, Quad, Point } /** * Type of Buffer * @author michael */ public enum BufferStructure { Stacked, Interleaved, } protected final FloatBuffer buffer; protected final int numberOfVertices; protected final VertexFormat format; protected final BufferStructure structure; VertexContainer(int setNumberOfVertices, VertexFormat ftype) { buffer = ByteBuffer.allocateDirect(setNumberOfVertices * (ftype.totalFloats*4)) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); numberOfVertices = setNumberOfVertices; format = ftype; structure = BufferStructure.Interleaved; } public abstract void draw(PrimitiveType type, int startingVertice, int numberOfVertices); /** * Synchronizes the buffer with the one in video memory. */ public abstract void synchronize(); private void putValues(int index, int type, float... data) { if (format.components[type]== 0) return; if (structure == BufferStructure.Stacked) buffer.position(format.offsets[type] * numberOfVertices + format.components[type] * index); else buffer.position(format.totalFloats * index + format.offsets[type]); buffer.put(data[0]); buffer.put(data[1]); if (format.components[type]==3) buffer.put(data[2]); if (format.components[type]==4) buffer.put(data[3]); } /** * Sets positional data at the specified index * @param index * @param data */ public void setPosition(int index, float... data) { putValues(index, VertexFormat.POSITION, data); } /** * Sets texture u/v coordinates at the specified index * @param index * @param data */ public void setTexture(int index, float... data) { putValues(index, VertexFormat.TEXTURE, data); } /** * Sets color information at the specified index * @param index * @param data */ public void setColor(int index, float... data) { putValues(index, VertexFormat.COLOR, data); } /** * Returns a new legacy wrapper. * @return a new wrapper object which wraps this container */ public LegacyGLWrapper getLegacyGLInterface() { return new LegacyGLWrapper(buffer,format, this); } /** * @return number of vertices in this container */ public int getNumberOfVertices() { return numberOfVertices; } /** * releases the buffer */ public void release() { // TODO Auto-generated method stub } }
Java
package org.esgl3d.rendering; import android.R.integer; public class VertexFormat { static final int COLOR = 0; static final int NORMAL = 1; static final int TEXTURE = 2; static final int POSITION = 3; final int[] components = new int[4]; final int[] offsets = new int[4]; final int totalFloats; final boolean isInterleaved; private VertexFormat(int setColorComp, int setTextureComp, int setPositionComp, boolean setInterleaved) { components[COLOR] = setColorComp; components[NORMAL] = 0; components[TEXTURE] = setTextureComp; components[POSITION] = setPositionComp; int total = 0; for (int i=0;i<4;i++) { offsets[i] = 0; for (int x=0;x<i;x++) offsets[i] += components[x]; total += components[i]; } totalFloats = total; isInterleaved = setInterleaved; } // color, normal, textureX, position public static final VertexFormat F_4Color_3Position = new VertexFormat(4, 0, 3,false); public static final VertexFormat F_2Texture_3Position = new VertexFormat(0, 2, 3, false); public static final VertexFormat F_2Texture_2Position = new VertexFormat(0, 2, 2, false); }
Java
package org.esgl3d.rendering; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; import android.opengl.GLUtils; public class Texture { private final int textureId; private final int width; private final int height; public int getHeight() { return height; } public int getWidth() { return width; } public int getTextureId() { return textureId; } public void bind(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); } Texture(int id, int setWidth, int setHeight) { textureId = id; width = setWidth; height = setHeight; } }
Java
package org.esgl3d.rendering; import java.lang.ref.Reference; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.esgl3d.Mesh; import org.esgl3d.Mesh.Format; import org.esgl3d.math.Matrix; import org.esgl3d.primitives.Pyramid; import org.esgl3d.rendering.VertexContainer.PrimitiveType; import org.esgl3d.scene.MeshNode; import org.esgl3d.scene.Scene; import org.esgl3d.scene.SceneNode; import org.esgl3d.util.FpsCounter; import org.esgl3d.util.HighPerformanceCounter; import android.opengl.GLSurfaceView; import android.opengl.GLU; public class Renderer implements GLSurfaceView.Renderer { private static Logger logger = Logger.getLogger(Renderer.class.getName()); public enum MatrixType { Projection, ModelView } private RenderCaps caps; private GL10 gl; private SceneNode p; private RenderQueue queue = new RenderQueue(); private HighPerformanceCounter timeForRendering = new HighPerformanceCounter("Rendering"); private TextureManager textureManager = null; private Scene sceneToRender = null; private final RenderActivity renderActivity; private final FpsCounter fpsCounter; public Renderer(RenderActivity renderActivity) { this.renderActivity = renderActivity; textureManager = new TextureManager(); fpsCounter = new FpsCounter(); } public void setScene(Scene value) { sceneToRender = value; } public TextureManager getTextureManager() { return textureManager; } public FpsCounter getFpsCounter() { return fpsCounter; } @Override public void onDrawFrame(GL10 arg0) { fpsCounter.next(); setPerspectiveProjection(); gl.glClearColor(0, 0, 0, 1); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); gl.glTranslatef(0.0f,0.0f,-32.0f); render(this); renderActivity.updateScenegraph(); } @Override public void onSurfaceChanged(GL10 arg0, int width, int height) { gl.glViewport(0, 0, width, height); // Reset The Current Viewport And Perspective Transformation gl.glMatrixMode(GL10.GL_PROJECTION); // Select The Projection Matrix gl.glLoadIdentity(); // Reset The Projection Matrix GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f); // Calculate The Aspect Ratio Of The Window gl.glMatrixMode(GL10.GL_MODELVIEW); // Select The Modelview Matrix gl.glLoadIdentity(); // Reset The ModalView Matrix } @Override public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) { gl = arg0; caps = new RenderCaps(); caps.initialize(gl); textureManager.setGl(gl); //gl.glShadeModel(GL10.GL_SMOOTH); //Enables Smooth Color Shading gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //This Will Clear The Background Color To Black gl.glClearDepthf((float) 1.0); //Enables Clearing Of The Depth Buffer gl.glEnable(GL10.GL_DEPTH_TEST); //Enables Depth Testing gl.glDepthFunc(GL10.GL_LEQUAL); //The Type Of Depth Test To Do //gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // Really Nice Perspective Calculations gl.glEnable(GL10.GL_TEXTURE_2D); gl.glEnable(GL10.GL_CULL_FACE); // which is the front? the one which is drawn counter clockwise gl.glFrontFace(GL10.GL_CCW); // which one should NOT be drawn /*gl.glEnable(GL10.GL_COLOR_MATERIAL); gl.glCullFace(GL10.GL_BACK); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA,GL10.GL_ONE_MINUS_SRC_ALPHA);*/ renderActivity.setupScenegraph(); } /** * Creates a vertex container to be used by the application. The renderer * decides whether it is implemented as a vertex array or vbo. * * @param format Vertex format * @param numberOfVertices The total number of vertices * @return a newly created vertex container */ public VertexContainer createVertexContainer(VertexFormat format, int numberOfVertices) { return createVertexContainer(format, numberOfVertices, VertexContainerOptions.DYNAMIC); } /** * Creates a vertex container to be used by the application. The renderer * decides whether it is implemented as a vertex array or vbo. * * @param format Vertex format * @param numberOfVertices The total number of vertices * @param options Options to further specify the usage * @return a newly created vertex container */ public VertexContainer createVertexContainer(VertexFormat format, int numberOfVertices, VertexContainerOptions options) { if (!caps.isVboSupported() || options.isVertexArrayForced()) { if (logger.isLoggable(Level.FINE)) logger.fine( String.format("Using Vertex Array (%d vertices)", numberOfVertices)); return new VertexArray(numberOfVertices, format, gl); } else { if (logger.isLoggable(Level.FINE)) logger.fine( String.format("Using Vertex Buffer Object (%d vertices)", numberOfVertices)); //return new VertexArray(numberOfVertices, format, gl); return new VertexBuffer(numberOfVertices, format, (GL11)gl); } } public void activeMatrixModel(MatrixType type) { if (type == MatrixType.ModelView) gl.glMatrixMode(GL10.GL_MODELVIEW); else gl.glMatrixMode(GL10.GL_PROJECTION); } public void loadMatrix(Matrix m) { gl.glLoadMatrixf(m.buffer); } public void pushMatrix() { gl.glPushMatrix(); } public void popMatrix() { gl.glPopMatrix(); } public void mulMatrix(Matrix m) { gl.glMultMatrixf(m.buffer); } public void setPerspectiveProjection() { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluPerspective(gl, 45, 320.0f/480.0f, 0.1f, 1000); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); } public void setOrthographicProjection() { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluOrtho2D(gl, 0, 20, 30, 0); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); } private int currentlyBoundTexture = 0; private boolean texturingEnabled = false; /** * Sets the appropriate opengl states for textures * * @param toBind texture to bind or null to unbind */ public void bindTexture(Texture toBind) { if (toBind != null) { if (!texturingEnabled) { gl.glEnable(GL10.GL_TEXTURE_2D); texturingEnabled = true; } if (currentlyBoundTexture != toBind.getTextureId()) { gl.glBindTexture(GL10.GL_TEXTURE_2D, toBind.getTextureId()); currentlyBoundTexture = toBind.getTextureId(); } } else { if (texturingEnabled) { gl.glDisable(GL10.GL_TEXTURE_2D); gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); currentlyBoundTexture = 0; texturingEnabled = false; } } } public GL10 getGl() { return gl; } public void render(Renderer renderer) { timeForRendering.start(); queue.reset(); if (sceneToRender != null) sceneToRender.getSpatialStructure().getVisibleNodes(null, queue); renderer.activeMatrixModel(MatrixType.ModelView); for (SceneNode curNode : queue.getNodesToRender()) { if (curNode instanceof MeshNode) { MeshNode cur = (MeshNode)curNode; Mesh geometry = cur.getGeometry(); int count = cur.getGeometry().getNumberOfVertices(); bindTexture(geometry.getTexture()); renderer.pushMatrix(); renderer.mulMatrix(cur.getWorldTransformation()); Format format = geometry.getFormat(); if (format == Format.Triangle) { geometry.getVertices().draw(PrimitiveType.Triangle, 0, count); } else { geometry.getVertices().draw(PrimitiveType.TriangleStrip, 0, count); } renderer.popMatrix(); } } timeForRendering.stop(); if (timeForRendering.getCounterDurationMillis() > 5000) { if (logger.isLoggable(Level.INFO)) logger.info(timeForRendering.getStatisticString()); timeForRendering.reset(); } } }
Java
package org.esgl3d.rendering; import java.util.logging.Level; import java.util.logging.Logger; import javax.microedition.khronos.opengles.GL10; /** * @author michael * */ public class RenderCaps { private static Logger log = Logger.getLogger(RenderCaps.class.getName()); private boolean isSoftwareRenderer = false; private boolean isVboSupported = false; private boolean isOpenGL10 = false; public boolean isSoftwareRenderer() { return isSoftwareRenderer; } public boolean isVboSupported() { return isVboSupported; } /** * Checks if opengl-es 1.0 is available. * @return true if available */ public boolean isOpenGL10() { return isOpenGL10; } /** * Checks if opengl-es 1.1 is available * @return true if available */ public boolean isOpenGL11() { return !isOpenGL10; } /** * Checks if opengl-es 2.0 is available * @return always false since opengl-es 2.0 is not supported */ public boolean isOpenGL20() { return false; } public void initialize(GL10 gl) { String extensions = gl.glGetString(GL10.GL_EXTENSIONS); String renderer = gl.glGetString(GL10.GL_RENDERER); String version = gl.glGetString(GL10.GL_VERSION); if (log.isLoggable(Level.INFO)) { log.info(extensions); log.info(renderer); log.info(version); } isSoftwareRenderer = renderer.contains("PixelFlinger"); isOpenGL10 = version.contains("1.0"); isVboSupported = !isSoftwareRenderer && (!isOpenGL10 || extensions.contains("vertex_buffer_object")); } }
Java
package org.esgl3d.rendering; public class Layer { }
Java
package org.esgl3d.rendering; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; class VertexArray extends VertexContainer { private final GL10 gl; public VertexArray(int sizeInBytes, VertexFormat type, GL10 gl) { super(sizeInBytes,type); this.gl = gl; } @Override public void draw(PrimitiveType type, int startVerticeIndex, int numberOfVertices) { int glType = GL10.GL_TRIANGLES; switch (type) { case Line: glType = GL10.GL_LINES; break; case Point: glType = GL10.GL_POINTS; break; case TriangleStrip: glType = GL10.GL_TRIANGLE_STRIP; break; case Triangle: break; } if (format.components[VertexFormat.COLOR] > 0) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); if (structure == BufferStructure.Stacked) gl.glColorPointer(format.components[VertexFormat.COLOR], GL10.GL_FLOAT, 0, buffer.position(format.offsets[VertexFormat.COLOR] * numberOfVertices)); else gl.glColorPointer(format.components[VertexFormat.COLOR], GL10.GL_FLOAT, format.totalFloats, buffer.position(format.offsets[VertexFormat.COLOR])); } else gl.glDisableClientState(GL10.GL_COLOR_ARRAY); if (format.components[VertexFormat.NORMAL] > 0) { gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); if (structure == BufferStructure.Stacked) gl.glNormalPointer(GL10.GL_FLOAT, 0, buffer.position(format.offsets[VertexFormat.NORMAL] * numberOfVertices)); else gl.glNormalPointer(GL10.GL_FLOAT, format.totalFloats, buffer.position(format.offsets[VertexFormat.NORMAL])); } else gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); if (format.components[VertexFormat.TEXTURE] > 0) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); if (structure == BufferStructure.Stacked) gl.glTexCoordPointer(format.components[VertexFormat.TEXTURE], GL10.GL_FLOAT, 0, buffer.position(format.offsets[VertexFormat.TEXTURE] * numberOfVertices)); else gl.glTexCoordPointer(format.components[VertexFormat.TEXTURE], GL10.GL_FLOAT, format.totalFloats, buffer.position(format.offsets[VertexFormat.TEXTURE])); } else gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); if (format.components[VertexFormat.POSITION] > 0) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (structure == BufferStructure.Stacked) gl.glVertexPointer(format.components[VertexFormat.POSITION], GL10.GL_FLOAT, 0, buffer.position(format.offsets[VertexFormat.POSITION] * numberOfVertices)); else gl.glVertexPointer(format.components[VertexFormat.POSITION], GL10.GL_FLOAT, format.totalFloats, buffer.position(format.offsets[VertexFormat.POSITION])); } else gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDrawArrays(glType, startVerticeIndex, numberOfVertices); } @Override public void synchronize() { // TODO Auto-generated method stub } }
Java
package org.esgl3d.util; public class HighPerformanceCounter { private long firstStart = 0; private long start = 0; private long lastElapsed = 0; private boolean isRunning = false; private long totalElapsed = 0; private long totalStops = 0; private final String name; public HighPerformanceCounter(String nameString) { name = nameString; } public void start() { start = System.nanoTime(); if (firstStart == 0) firstStart = start; isRunning = true; } public void stop() { lastElapsed = System.nanoTime() - start; isRunning = false; totalStops += 1; totalElapsed += lastElapsed; } public void reset() { totalElapsed = 0; totalStops = 0; lastElapsed = 0; firstStart = 0; start = 0; isRunning = false; } public long getTotalStops() { return totalStops; } public long getCounterDurationMillis() { if (firstStart > 0) { long duration = (System.nanoTime() - firstStart) / (1000*1000); return duration; } return 0; } public long getAverageTotalElapsedMillis() { if (totalStops > 0) { return (totalElapsed / totalStops) / (1000*1000); } return 0; } public String getStatisticString() { return String.format("%s: Cnt: %d Avg: %dms", name, getTotalStops(), getAverageTotalElapsedMillis()); } public long getElapsedMillis() { long total = lastElapsed; if (isRunning) total += (System.nanoTime() - start); long diffInMillis = total / (1000*1000); return diffInMillis; } }
Java
package org.esgl3d.util; public class FpsCounter { private int lastFps = 0; private int currentFps; private int lastDelta = 0; private long lastMillis = System.currentTimeMillis(); private long lastNextMillis = System.currentTimeMillis(); private String lastFpsString = ""; public int getLastFps() { return lastFps; } public int getLastDelta() { return lastDelta; } public void next() { currentFps++; if (System.currentTimeMillis() > lastMillis+1000) { if (lastFps != currentFps) lastFpsString = String.format("FPS: %d", currentFps); lastFps = currentFps; currentFps = 0; lastMillis = System.currentTimeMillis(); } lastDelta = (int)(System.currentTimeMillis() - lastNextMillis); lastNextMillis = System.currentTimeMillis(); } @Override public String toString() { return lastFpsString; } }
Java
package org.esgl3d.scene; import java.util.logging.Level; import java.util.logging.Logger; public class LightNode extends SceneNode { private static final Logger logger = Logger.getLogger(LightNode.class.getName()); @Override protected void onSceneSwitch(Scene from, Scene to) { if (from != null) { if (logger.isLoggable(Level.FINE)) logger.fine("Removing light from scene"); from.unregisterLightNode(this); } if (to != null) { if (logger.isLoggable(Level.FINE)) logger.fine("Adding light to scene"); to.registerLightNode(this); } } }
Java
package org.esgl3d.scene; import java.util.ArrayList; import org.esgl3d.Mesh; import org.esgl3d.math.Matrix; import org.esgl3d.primitives.Pyramid; import org.esgl3d.rendering.Renderer; import com.sun.org.apache.xpath.internal.axes.ChildIterator; /** * SceneNode represents a single node of a scene graph. SceneNode can have * any number of children attached to it. * * @author michael */ public class SceneNode { private Matrix localTransformation = new Matrix(); private Matrix worldTransformation = new Matrix(); private boolean isDirty = false; private SceneNode parentNode; private Scene owner; private ArrayList<SceneNode> childNodes = new ArrayList<SceneNode>(); void setScene(Scene newScene) { if (owner != newScene) onSceneSwitch(owner, newScene); owner = newScene; } /** * Called when a scene node switches from one scene to another * @param from Old scene * @param to New scene */ protected void onSceneSwitch(Scene from, Scene to) { } public Scene getScene() { return owner; } /** * @return true if this scene node (or any of its parent) has been moved */ public boolean isDirty() { return isDirty; } /** * resets the dirty flag to 'false' */ public void unsetDirtyFlag() { isDirty = false; } /** * Return the local transformation relative to the parent * * @return Matrix (local tranformation) */ public Matrix getLocalTransformation() { return localTransformation; } /** * Calculates and returns the world transformation * * @return Matrix (world transformation) */ public Matrix getWorldTransformation() { // quick and dirty... Matrix.assign(worldTransformation.v, localTransformation.v); SceneNode next = parentNode; while (next != null) { Matrix.preMultiplyMM(worldTransformation.v, next.localTransformation.v); next = next.parentNode; } return worldTransformation; } /** * Translates (moves) this scene node * * @param x * @param y * @param z */ public void translate(float x, float y, float z) { Matrix.translateM(localTransformation.v, 0, x, y, z); isDirty = true; } /** * Rotates this scene node around its center * * @param deg * @param x * @param y * @param z */ public void rotate(float deg, float x, float y, float z) { Matrix.rotateM(localTransformation.v, 0, deg, x, y, z); } /** * Checks if this node has any children * * @return true if there are children, otherwise false */ public boolean hasChildren() { return childNodes.size()>0; } public ArrayList<SceneNode> getChildren() { return childNodes; } public boolean checkCulling() { // currently always visible return true; } private void setParentNode(SceneNode newParent) { parentNode = newParent; Scene newScene = null; if (newParent != null) newScene = newParent.owner; if (newScene != owner) setOwningSceneRecursively(newScene); } void setOwningSceneRecursively(Scene set) { setScene(set); for (SceneNode curNode : childNodes) { curNode.setOwningSceneRecursively(set); } } /** * Detaches this node from its parent. */ public void detach() { if (parentNode != null) { parentNode.detachChild(this); } else { owner.removeChild(this); } } /** * Attaches this node to a new parent. * @param newParent */ public void attachTo(SceneNode newParent) { newParent.attachChild(this); } /** * Attaches a node as child. Detaches it if it has already a parent. * @param node */ public void attachChild(SceneNode node) { if (node.parentNode != null) node.parentNode.detachChild(node); node.setParentNode(this); childNodes.add(node); } /** * Detaches a specific child. * @param child */ public void detachChild(SceneNode child) { if (childNodes.contains(child)) { child.parentNode = null; childNodes.remove(child); } } }
Java
package org.esgl3d.scene; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.esgl3d.rendering.RenderQueue; import org.esgl3d.rendering.Renderer; import org.esgl3d.rendering.Renderer.MatrixType; import org.esgl3d.rendering.VertexContainer.PrimitiveType; import org.esgl3d.spatial.NoneSpatialStructure; import org.esgl3d.spatial.SpatialStructure; import org.esgl3d.util.HighPerformanceCounter; public class Scene { private static final Logger logger = Logger.getLogger(Scene.class.getName()); private ArrayList<SceneNode> childNodes = new ArrayList<SceneNode>(); private ArrayList<LightNode> lightNodes = new ArrayList<LightNode>(); private SpatialStructure spatialSeperator = null; public SpatialStructure getSpatialStructure() { return spatialSeperator; } public Scene() { spatialSeperator = new NoneSpatialStructure(this); } public void addChild(SceneNode node) { childNodes.add(node); node.setOwningSceneRecursively(this); } public void removeChild(SceneNode node) { childNodes.remove(node); node.setOwningSceneRecursively(null); } public ArrayList<SceneNode> getChildren() { return childNodes; } public void registerLightNode(LightNode node) { if (!lightNodes.contains(node)) lightNodes.add(node); } public void unregisterLightNode(LightNode node) { if (lightNodes.contains(node)) lightNodes.remove(node); } }
Java
package org.esgl3d.scene; import org.esgl3d.Mesh; import org.esgl3d.rendering.Texture; public class MeshNode extends SceneNode { private Mesh geometry; public Mesh getGeometry() { return geometry; } public void setGeometry(Mesh value) { geometry = value; } }
Java
package org.esgl3d.scene; public class CameraNode extends SceneNode { }
Java
package org.esgl3d.math; public class Vector3d { private static final Vector3d ORIGIN = new Vector3d(0f, 0f, 0f); public float x; public float y; public float z; public Vector3d(final Vector3d other) { x = other.x; y = other.y; z = other.z; } public Vector3d(float xComp, float yComp, float zComp) { x = xComp; y = yComp; z = zComp; } public Vector3d plus(float xComp, float yComp, float zComp) { return new Vector3d(x + xComp, y + yComp, z + zComp); } public Vector3d minus(float xComp, float yComp, float zComp) { return new Vector3d(x - xComp, y - yComp, z - zComp); } public String toString() { return "["+x+","+y+","+z+"]"; } public Vector3d times(float comp) { return times(comp, comp, comp); } public Vector3d times(float xComp, float yComp, float zComp) { return new Vector3d(x * xComp, y * yComp, z * zComp); } public Vector3d scale(float scaleValue) { return new Vector3d(x * scaleValue, y * scaleValue, z * scaleValue); } public Vector3d divide(float comp) { return new Vector3d(x / comp, y / comp, z / comp); } public float length() { return (float) Math.sqrt((x*x)+(y*y)+(z*z)); } public Vector3d normalize() { float len = length(); return new Vector3d(x / len, y / len, z / len); } public Vector3d times(Vector3d other) { return this.times(other.x, other.y, other.z); } public Vector3d plus(Vector3d other) { return this.plus(other.x, other.y, other.z); } public Vector3d minus(Vector3d other) { return this.minus(other.x, other.y, other.z); } public Vector3d cross(Vector3d other) { float newX = y * other.z - other.y * z; float newY = z * other.x - other.z * x; float newZ = x * other.y - other.x * y; return new Vector3d(newX, newY, newZ); } public float dot(Vector3d other) { return x * other.x + y * other.y + z * other.z; } public Vector3d negative() { return new Vector3d(-x, -y, -z); } public void normalizeMutable() { float len = length(); x = x / len; y = y / len; z = z / len; } }
Java
package org.esgl3d.math; import java.nio.FloatBuffer; import android.R.integer; /** * This class is straight from android sources with some modifications */ /** * Matrix math utilities. These methods operate on OpenGL ES format * matrices and vectors stored in float arrays. * * Matrices are 4 x 4 column-vector matrices stored in column-major * order: * <pre> * m[offset + 0] m[offset + 4] m[offset + 8] m[offset + 12] * m[offset + 1] m[offset + 5] m[offset + 9] m[offset + 13] * m[offset + 2] m[offset + 6] m[offset + 10] m[offset + 14] * m[offset + 3] m[offset + 7] m[offset + 11] m[offset + 15] * </pre> * * Vectors are 4 row x 1 column column-vectors stored in order: * <pre> * v[offset + 0] * v[offset + 1] * v[offset + 2] * v[offset + 3] * </pre> * */ public class Matrix { public volatile float[] v =null; public volatile FloatBuffer buffer = null; /** * Multiply two 4x4 matrices together and store the result in a third 4x4 * matrix. In matrix notation: result = lhs x rhs. Due to the way * matrix multiplication works, the result matrix will have the same * effect as first multiplying by the rhs matrix, then multiplying by * the lhs matrix. This is the opposite of what you might expect. * * The same float array may be passed for result, lhs, and/or rhs. However, * the result element values are undefined if the result elements overlap * either the lhs or rhs elements. * * @param result The float array that holds the result. * @param resultOffset The offset into the result array where the result is * stored. * @param lhs The float array that holds the left-hand-side matrix. * @param lhsOffset The offset into the lhs array where the lhs is stored * @param rhs The float array that holds the right-hand-side matrix. * @param rhsOffset The offset into the rhs array where the rhs is stored. * * @throws IllegalArgumentException if result, lhs, or rhs are null, or if * resultOffset + 16 > result.length or lhsOffset + 16 > lhs.length or * rhsOffset + 16 > rhs.length. */ public Matrix() { v = new float[16]; buffer = FloatBuffer.wrap(v); Matrix.setIdentityM(v, 0); } public static void multiplyMM(float[] result, int resultOffset, float[] lhs, int lhsOffset, float[] rhs, int rhsOffset) { int i, j, k; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) { int tmpIdx = 4*j+i; result[tmpIdx+resultOffset] = 0.0f; for (k = 0; k < 4; k++) { result[tmpIdx+resultOffset] += lhs[4*k+i+lhsOffset] * rhs[4*j+k+rhsOffset]; } } // assign(dst, tmp); } public static void multiplyMM(float[] lhs, int lhsOffset, float[] rhs, int rhsOffset) { float[] result = new float[16]; int i, j, k; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) { int tmpIdx = 4*j+i; result[tmpIdx] = 0.0f; for (k = 0; k < 4; k++) { result[tmpIdx] += lhs[4*k+i+lhsOffset] * rhs[4*j+k+rhsOffset]; } } lhs = result; } /** * Multiply a 4 element vector by a 4x4 matrix and store the result in a 4 * element column vector. In matrix notation: result = lhs x rhs * * The same float array may be passed for resultVec, lhsMat, and/or rhsVec. * However, the resultVec element values are undefined if the resultVec * elements overlap either the lhsMat or rhsVec elements. * * @param resultVec The float array that holds the result vector. * @param resultVecOffset The offset into the result array where the result * vector is stored. * @param lhsMat The float array that holds the left-hand-side matrix. * @param lhsMatOffset The offset into the lhs array where the lhs is stored * @param rhsVec The float array that holds the right-hand-side vector. * @param rhsVecOffset The offset into the rhs vector where the rhs vector * is stored. * * @throws IllegalArgumentException if resultVec, lhsMat, * or rhsVec are null, or if resultVecOffset + 4 > resultVec.length * or lhsMatOffset + 16 > lhsMat.length or * rhsVecOffset + 4 > rhsVec.length. */ public static void multiplyMV(float[] resultVec, int resultVecOffset, float[] lhsMat, int lhsMatOffset, float[] rhsVec, int rhsVecOffset) { throw new RuntimeException("Not implemented."); } /** * Transposes a 4 x 4 matrix. * * @param mTrans the array that holds the output inverted matrix * @param mTransOffset an offset into mInv where the inverted matrix is * stored. * @param m the input array * @param mOffset an offset into m where the matrix is stored. */ public static void transposeM(float[] mTrans, int mTransOffset, float[] m, int mOffset) { for (int i = 0; i < 4; i++) { int mBase = i * 4 + mOffset; mTrans[i + mTransOffset] = m[mBase]; mTrans[i + 4 + mTransOffset] = m[mBase + 1]; mTrans[i + 8 + mTransOffset] = m[mBase + 2]; mTrans[i + 12 + mTransOffset] = m[mBase + 3]; } } /** * Inverts a 4 x 4 matrix. * * @param mInv the array that holds the output inverted matrix * @param mInvOffset an offset into mInv where the inverted matrix is * stored. * @param m the input array * @param mOffset an offset into m where the matrix is stored. * @return true if the matrix could be inverted, false if it could not. */ public static boolean invertM(float[] mInv, int mInvOffset, float[] m, int mOffset) { // Invert a 4 x 4 matrix using Cramer's Rule // array of transpose source matrix float[] src = new float[16]; // transpose matrix transposeM(src, 0, m, mOffset); // temp array for pairs float[] tmp = new float[12]; // calculate pairs for first 8 elements (cofactors) tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; // Holds the destination matrix while we're building it up. float[] dst = new float[16]; // calculate first 8 elements (cofactors) dst[0] = tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]; dst[0] -= tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]; dst[1] = tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]; dst[1] -= tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]; dst[2] = tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]; dst[2] -= tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]; dst[3] = tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]; dst[3] -= tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]; dst[4] = tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]; dst[4] -= tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]; dst[5] = tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]; dst[5] -= tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]; dst[6] = tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]; dst[6] -= tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]; dst[7] = tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]; dst[7] -= tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]; // calculate pairs for second 8 elements (cofactors) tmp[0] = src[2] * src[7]; tmp[1] = src[3] * src[6]; tmp[2] = src[1] * src[7]; tmp[3] = src[3] * src[5]; tmp[4] = src[1] * src[6]; tmp[5] = src[2] * src[5]; tmp[6] = src[0] * src[7]; tmp[7] = src[3] * src[4]; tmp[8] = src[0] * src[6]; tmp[9] = src[2] * src[4]; tmp[10] = src[0] * src[5]; tmp[11] = src[1] * src[4]; // calculate second 8 elements (cofactors) dst[8] = tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]; dst[8] -= tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]; dst[9] = tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]; dst[9] -= tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]; dst[10] = tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]; dst[10] -= tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]; dst[11] = tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]; dst[11] -= tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]; dst[12] = tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]; dst[12] -= tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]; dst[13] = tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]; dst[13] -= tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]; dst[14] = tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]; dst[14] -= tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]; dst[15] = tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]; dst[15] -= tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]; // calculate determinant float det = src[0] * dst[0] + src[1] * dst[1] + src[2] * dst[2] + src[3] * dst[3]; if (det == 0.0f) { } // calculate matrix inverse det = 1 / det; for (int j = 0; j < 16; j++) mInv[j + mInvOffset] = dst[j] * det; return true; } /** * Computes an orthographic projection matrix. * * @param m returns the result * @param mOffset * @param left * @param right * @param bottom * @param top * @param near * @param far */ public static void orthoM(float[] m, int mOffset, float left, float right, float bottom, float top, float near, float far) { if (left == right) { throw new IllegalArgumentException("left == right"); } if (bottom == top) { throw new IllegalArgumentException("bottom == top"); } if (near == far) { throw new IllegalArgumentException("near == far"); } final float r_width = 1.0f / (right - left); final float r_height = 1.0f / (top - bottom); final float r_depth = 1.0f / (far - near); final float x = 2.0f * (r_width); final float y = 2.0f * (r_height); final float z = -2.0f * (r_depth); final float tx = -(right + left) * r_width; final float ty = -(top + bottom) * r_height; final float tz = -(far + near) * r_depth; m[mOffset + 0] = x; m[mOffset + 5] = y; m[mOffset +10] = z; m[mOffset +12] = tx; m[mOffset +13] = ty; m[mOffset +14] = tz; m[mOffset +15] = 1.0f; m[mOffset + 1] = 0.0f; m[mOffset + 2] = 0.0f; m[mOffset + 3] = 0.0f; m[mOffset + 4] = 0.0f; m[mOffset + 6] = 0.0f; m[mOffset + 7] = 0.0f; m[mOffset + 8] = 0.0f; m[mOffset + 9] = 0.0f; m[mOffset + 11] = 0.0f; } /** * Define a projection matrix in terms of six clip planes * @param m the float array that holds the perspective matrix * @param offset the offset into float array m where the perspective * matrix data is written * @param left * @param right * @param bottom * @param top * @param near * @param far */ public static void frustumM(float[] m, int offset, float left, float right, float bottom, float top, float near, float far) { if (left == right) { throw new IllegalArgumentException("left == right"); } if (top == bottom) { throw new IllegalArgumentException("top == bottom"); } if (near == far) { throw new IllegalArgumentException("near == far"); } if (near <= 0.0f) { throw new IllegalArgumentException("near <= 0.0f"); } if (far <= 0.0f) { throw new IllegalArgumentException("far <= 0.0f"); } final float r_width = 1.0f / (right - left); final float r_height = 1.0f / (top - bottom); final float r_depth = 1.0f / (near - far); final float x = 2.0f * (near * r_width); final float y = 2.0f * (near * r_height); final float A = 2.0f * ((right + left) * r_width); final float B = (top + bottom) * r_height; final float C = (far + near) * r_depth; final float D = 2.0f * (far * near * r_depth); m[offset + 0] = x; m[offset + 5] = y; m[offset + 8] = A; m[offset + 9] = B; m[offset + 10] = C; m[offset + 14] = D; m[offset + 11] = -1.0f; m[offset + 1] = 0.0f; m[offset + 2] = 0.0f; m[offset + 3] = 0.0f; m[offset + 4] = 0.0f; m[offset + 6] = 0.0f; m[offset + 7] = 0.0f; m[offset + 12] = 0.0f; m[offset + 13] = 0.0f; m[offset + 15] = 0.0f; } /** * Computes the length of a vector * * @param x x coordinate of a vector * @param y y coordinate of a vector * @param z z coordinate of a vector * @return the length of a vector */ public static float length(float x, float y, float z) { return (float) Math.sqrt(x * x + y * y + z * z); } /** * Sets matrix m to the identity matrix. * @param sm returns the result * @param smOffset index into sm where the result matrix starts */ public static void setIdentityM(float[] sm, int smOffset) { for (int i=0 ; i<16 ; i++) { sm[smOffset + i] = 0; } for(int i = 0; i < 16; i += 5) { sm[smOffset + i] = 1.0f; } } /** * Scales matrix m by x, y, and z, putting the result in sm * @param sm returns the result * @param smOffset index into sm where the result matrix starts * @param m source matrix * @param mOffset index into m where the source matrix starts * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void scaleM(float[] sm, int smOffset, float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int smi = smOffset + i; int mi = mOffset + i; sm[ smi] = m[ mi] * x; sm[ 4 + smi] = m[ 4 + mi] * y; sm[ 8 + smi] = m[ 8 + mi] * z; sm[12 + smi] = m[12 + mi]; } } /** * Scales matrix m in place by sx, sy, and sz * @param m matrix to scale * @param mOffset index into m where the matrix starts * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void scaleM(float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int mi = mOffset + i; m[ mi] *= x; m[ 4 + mi] *= y; m[ 8 + mi] *= z; } } /** * Translates matrix m by x, y, and z, putting the result in tm * @param tm returns the result * @param tmOffset index into sm where the result matrix starts * @param m source matrix * @param mOffset index into m where the source matrix starts * @param x translation factor x * @param y translation factor y * @param z translation factor z */ public static void translateM(float[] tm, int tmOffset, float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<12 ; i++) { tm[tmOffset + i] = m[mOffset + i]; } for (int i=0 ; i<4 ; i++) { int tmi = tmOffset + i; int mi = mOffset + i; tm[12 + tmi] = m[mi] * x + m[4 + mi] * y + m[8 + mi] * z + m[12 + mi]; } } /** * Translates matrix m by x, y, and z in place. * @param m matrix * @param mOffset index into m where the matrix starts * @param x translation factor x * @param y translation factor y * @param z translation factor z */ public static void translateM( float[] m, int mOffset, float x, float y, float z) { for (int i=0 ; i<4 ; i++) { int mi = mOffset + i; m[12 + mi] += m[mi] * x + m[4 + mi] * y + m[8 + mi] * z; } } /** * Rotates matrix m by angle a (in degrees) around the axis (x, y, z) * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param m source matrix * @param mOffset index into m where the source matrix starts * @param a angle to rotate in degrees * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void rotateM(float[] rm, int rmOffset, float[] m, int mOffset, float a, float x, float y, float z) { float[] r = new float[16]; setRotateM(r, 0, a, x, y, z); multiplyMM(rm, rmOffset, m, mOffset, r, 0); } /** * Rotates matrix m in place by angle a (in degrees) * around the axis (x, y, z) * @param m source matrix * @param mOffset index into m where the matrix starts * @param a angle to rotate in degrees * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void rotateM(float[] m, int mOffset, float a, float x, float y, float z) { float[] temp = new float[32]; setRotateM(temp, 0, a, x, y, z); multiplyMM(temp, 16, m, mOffset, temp, 0); System.arraycopy(temp, 16, m, mOffset, 16); } /** * Rotates matrix m by angle a (in degrees) around the axis (x, y, z) * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param a angle to rotate in degrees * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void setRotateM(float[] rm, int rmOffset, float a, float x, float y, float z) { rm[rmOffset + 3] = 0; rm[rmOffset + 7] = 0; rm[rmOffset + 11]= 0; rm[rmOffset + 12]= 0; rm[rmOffset + 13]= 0; rm[rmOffset + 14]= 0; rm[rmOffset + 15]= 1; a *= (float) (Math.PI / 180.0f); float s = (float) Math.sin(a); float c = (float) Math.cos(a); if (1.0f == x && 0.0f == y && 0.0f == z) { rm[rmOffset + 5] = c; rm[rmOffset + 10]= c; rm[rmOffset + 6] = s; rm[rmOffset + 9] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 2] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 0] = 1; } else if (0.0f == x && 1.0f == y && 0.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 10]= c; rm[rmOffset + 8] = s; rm[rmOffset + 2] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 5] = 1; } else if (0.0f == x && 0.0f == y && 1.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 5] = c; rm[rmOffset + 1] = s; rm[rmOffset + 4] = -s; rm[rmOffset + 2] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 10]= 1; } else { float len = length(x, y, z); if (1.0f != len) { float recipLen = 1.0f / len; x *= recipLen; y *= recipLen; z *= recipLen; } float nc = 1.0f - c; float xy = x * y; float yz = y * z; float zx = z * x; float xs = x * s; float ys = y * s; float zs = z * s; rm[rmOffset + 0] = x*x*nc + c; rm[rmOffset + 4] = xy*nc - zs; rm[rmOffset + 8] = zx*nc + ys; rm[rmOffset + 1] = xy*nc + zs; rm[rmOffset + 5] = y*y*nc + c; rm[rmOffset + 9] = yz*nc - xs; rm[rmOffset + 2] = zx*nc - ys; rm[rmOffset + 6] = yz*nc + xs; rm[rmOffset + 10] = z*z*nc + c; } } /** * Converts Euler angles to a rotation matrix * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param x angle of rotation, in degrees * @param y angle of rotation, in degrees * @param z angle of rotation, in degrees */ public static void setRotateEulerM(float[] rm, int rmOffset, float x, float y, float z) { x *= (float) (Math.PI / 180.0f); y *= (float) (Math.PI / 180.0f); z *= (float) (Math.PI / 180.0f); float cx = (float) Math.cos(x); float sx = (float) Math.sin(x); float cy = (float) Math.cos(y); float sy = (float) Math.sin(y); float cz = (float) Math.cos(z); float sz = (float) Math.sin(z); float cxsy = cx * sy; float sxsy = sx * sy; rm[rmOffset + 0] = cy * cz; rm[rmOffset + 1] = -cy * sz; rm[rmOffset + 2] = sy; rm[rmOffset + 3] = 0.0f; rm[rmOffset + 4] = cxsy * cz + cx * sz; rm[rmOffset + 5] = -cxsy * sz + cx * cz; rm[rmOffset + 6] = -sx * cy; rm[rmOffset + 7] = 0.0f; rm[rmOffset + 8] = -sxsy * cz + sx * sz; rm[rmOffset + 9] = sxsy * sz + sx * cz; rm[rmOffset + 10] = cx * cy; rm[rmOffset + 11] = 0.0f; rm[rmOffset + 12] = 0.0f; rm[rmOffset + 13] = 0.0f; rm[rmOffset + 14] = 0.0f; rm[rmOffset + 15] = 1.0f; } public void rotate(float angle, float x, float y, float z) { Matrix.rotateM(v, 0, angle, x, y, z); } public void preMultiply(float[] src) { Matrix.preMultiplyMM(v, src); } public void preMultiply(Matrix src) { Matrix.preMultiplyMM(v, src.v); } public static void preMultiplyMMSlow(float[] dst, float[] src) { float[] tmp = new float[16]; int i, j, k; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) { int tmpIdx = 4*j+i; tmp[tmpIdx] = 0.0f; for (k = 0; k < 4; k++) { tmp[tmpIdx] += src[4*k+i] * dst[4*j+k]; } } assign(dst, tmp); } public static void preMultiplyMM(float[] dst, float[] src) { float[] tmp = new float[16]; tmp[4*0+0] = (src[0] * dst[4*0]) + (src[4+0] * dst[4*0+1]) + (src[8+0] * dst[4*0+2]) + (src[12+0] * dst[4*0+3]); tmp[4*1+0] = (src[0] * dst[4*1]) + (src[4+0] * dst[4*1+1]) + (src[8+0] * dst[4*1+2]) + (src[12+0] * dst[4*1+3]); tmp[4*2+0] = (src[0] * dst[4*2]) + (src[4+0] * dst[4*2+1]) + (src[8+0] * dst[4*2+2]) + (src[12+0] * dst[4*2+3]); tmp[4*3+0] = (src[0] * dst[4*3]) + (src[4+0] * dst[4*3+1]) + (src[8+0] * dst[4*3+2]) + (src[12+0] * dst[4*3+3]); tmp[4*0+1] = (src[1] * dst[4*0]) + (src[4+1] * dst[4*0+1]) + (src[8+1] * dst[4*0+2]) + (src[12+1] * dst[4*0+3]); tmp[4*1+1] = (src[1] * dst[4*1]) + (src[4+1] * dst[4*1+1]) + (src[8+1] * dst[4*1+2]) + (src[12+1] * dst[4*1+3]); tmp[4*2+1] = (src[1] * dst[4*2]) + (src[4+1] * dst[4*2+1]) + (src[8+1] * dst[4*2+2]) + (src[12+1] * dst[4*2+3]); tmp[4*3+1] = (src[1] * dst[4*3]) + (src[4+1] * dst[4*3+1]) + (src[8+1] * dst[4*3+2]) + (src[12+1] * dst[4*3+3]); tmp[4*0+2] = (src[2] * dst[4*0]) + (src[4+2] * dst[4*0+1]) + (src[8+2] * dst[4*0+2]) + (src[12+2] * dst[4*0+3]); tmp[4*1+2] = (src[2] * dst[4*1]) + (src[4+2] * dst[4*1+1]) + (src[8+2] * dst[4*1+2]) + (src[12+2] * dst[4*1+3]); tmp[4*2+2] = (src[2] * dst[4*2]) + (src[4+2] * dst[4*2+1]) + (src[8+2] * dst[4*2+2]) + (src[12+2] * dst[4*2+3]); tmp[4*3+2] = (src[2] * dst[4*3]) + (src[4+2] * dst[4*3+1]) + (src[8+2] * dst[4*3+2]) + (src[12+2] * dst[4*3+3]); tmp[4*0+3] = (src[3] * dst[4*0]) + (src[4+3] * dst[4*0+1]) + (src[8+3] * dst[4*0+2]) + (src[12+3] * dst[4*0+3]); tmp[4*1+3] = (src[3] * dst[4*1]) + (src[4+3] * dst[4*1+1]) + (src[8+3] * dst[4*1+2]) + (src[12+3] * dst[4*1+3]); tmp[4*2+3] = (src[3] * dst[4*2]) + (src[4+3] * dst[4*2+1]) + (src[8+3] * dst[4*2+2]) + (src[12+3] * dst[4*2+3]); tmp[4*3+3] = (src[3] * dst[4*3]) + (src[4+3] * dst[4*3+1]) + (src[8+3] * dst[4*3+2]) + (src[12+3] * dst[4*3+3]); dst[0] = tmp[0]; dst[1] = tmp[1]; dst[2] = tmp[2]; dst[3] = tmp[3]; dst[4] = tmp[4]; dst[5] = tmp[5]; dst[6] = tmp[6]; dst[7] = tmp[7]; dst[8] = tmp[8]; dst[9] = tmp[9]; dst[10] = tmp[10]; dst[11] = tmp[11]; dst[12] = tmp[12]; dst[13] = tmp[13]; dst[14] = tmp[14]; dst[15] = tmp[15]; } public static void assign(float[] dst, float[] src) { for (int i=0;i<16;i++) dst[i] = src[i]; } // column based matrix index //#define MIDX(i, j) (4 * j + i) }
Java
package org.esgl3d; import org.esgl3d.rendering.Texture; import org.esgl3d.rendering.VertexContainer; public class Mesh { public enum Format { Triangle, TriangleStrip, } private VertexContainer vertices; private int numberOfVertices; private Format meshFormat; private Texture texture = null; public int getNumberOfVertices() { return numberOfVertices; } public VertexContainer getVertices() { return vertices; } public Format getFormat() { return meshFormat; } public void setVertices(VertexContainer value, Format setMeshFormat) { vertices = value; numberOfVertices = value.getNumberOfVertices(); meshFormat = setMeshFormat; } public Texture getTexture() { return texture; } public void setTexture(Texture value) { texture = value; } }
Java
package org.esgl3d.loader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.ReadOnlyBufferException; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import org.esgl3d.Mesh; import org.esgl3d.Mesh.Format; import org.esgl3d.core.ResourceResolver; import org.esgl3d.math.Vector3d; import org.esgl3d.rendering.Renderer; import org.esgl3d.rendering.VertexContainer; import org.esgl3d.rendering.VertexFormat; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.FaceDetector.Face; import android.util.Log; public class ObjLoader { private static class Float3 { public float x; public float y; public float z; } private static class Face3 { public int[] idx = new int[3]; public int[] tex = new int[3]; public void parseIndex(int i, String line) { StringTokenizer tokenizer = new StringTokenizer(line, "/"); idx[i] = Integer.parseInt(tokenizer.nextToken()); if (tokenizer.hasMoreTokens()) tex[i]= Integer.parseInt(tokenizer.nextToken()); } } private static class Float2 { public float u; public float v; } private static class Material { public String name = ""; public ArrayList<Face3> faces = new ArrayList<Face3>(); } private static final Logger logger = Logger.getLogger(ObjLoader.class.getName()); private ResourceResolver resolver; private String resourceIdString; private final static String VERTEX = "v"; private final static String FACE = "f"; private final static String TEXCOORD = "vt"; private final static String NORMAL = "vn"; private final static String OBJECT = "o"; private final static String MATERIAL_LIB = "mtllib"; private final static String USE_MATERIAL = "usemtl"; private final static String NEW_MATERIAL = "newmtl"; private final static String DIFFUSE_TEX_MAP = "map_Kd"; private ArrayList<Float3> vertices = new ArrayList<ObjLoader.Float3>(); private ArrayList<Face3> faces = new ArrayList<ObjLoader.Face3>(); private ArrayList<Float2> texturecoords = new ArrayList<ObjLoader.Float2>(); private HashMap<String, Material> materials = new HashMap<String, Material>(); public ObjLoader(ResourceResolver res, String resourceId) { resolver = res; resourceIdString = resourceId; } public Mesh createMesh(Renderer r, InputStream stream) { BufferedReader buffer = new BufferedReader(new InputStreamReader(resolver.getResourceStream(resourceIdString ))); String line; Material current = null; try { while ((line = buffer.readLine()) != null) { StringTokenizer parts = new StringTokenizer(line, " "); int numTokens = parts.countTokens(); if (numTokens == 0) continue; String type = parts.nextToken(); if (type.equals(VERTEX)) { if (logger.isLoggable(Level.FINEST)) logger.finest("Vertex: "+line); Float3 f = new Float3(); f.x = Float.parseFloat(parts.nextToken()); f.y = Float.parseFloat(parts.nextToken()); f.z = Float.parseFloat(parts.nextToken()); vertices.add(f); } else if (type.equals(FACE)) { Face3 f = new Face3(); f.parseIndex(0,parts.nextToken()); f.parseIndex(1,parts.nextToken()); f.parseIndex(2,parts.nextToken()); faces.add(f); current.faces.add(f); } else if (type.equals(TEXCOORD)) { Float2 f = new Float2(); f.u = Float.parseFloat(parts.nextToken()); f.v = Float.parseFloat(parts.nextToken()); texturecoords.add(f); } else if (type.equals(MATERIAL_LIB)) { parseMaterial(resolver.getResourceStream(parts.nextToken())); } else if (type.equals(USE_MATERIAL)) { current = materials.get(parts.nextToken()); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Mesh result = new Mesh(); VertexContainer container = null; if (texturecoords.size() > 0) container = r.createVertexContainer(VertexFormat.F_2Texture_3Position, faces.size()*3); else container = r.createVertexContainer(VertexFormat.F_4Color_3Position, faces.size()*3); int num = 0; for (Material mat : materials.values()) { if (mat.name.length() > 0) { Bitmap loadedBitmap = BitmapFactory.decodeStream(resolver.getResourceStream(mat.name)); result.setTexture(r.getTextureManager().addImage(loadedBitmap, false )); } for (Face3 curFace : mat.faces) { if (logger.isLoggable(Level.FINEST)) logger.finest(String.format("Face: %d %d %d ", curFace.idx[0], curFace.idx[1], curFace.idx[2])); if (texturecoords.size() > 0) { foo(container, num, vertices.get(curFace.idx[0]-1), texturecoords.get(curFace.tex[0]-1)); foo(container, num+1, vertices.get(curFace.idx[1]-1),texturecoords.get(curFace.tex[1]-1)); foo(container, num+2, vertices.get(curFace.idx[2]-1),texturecoords.get(curFace.tex[2]-1)); } else { foo(container, num, vertices.get(curFace.idx[0]-1), null); foo(container, num+1, vertices.get(curFace.idx[1]-1),null); foo(container, num+2, vertices.get(curFace.idx[2]-1),null); } num += 3; } } container.synchronize(); result.setVertices(container, Format.Triangle); return result; } private void foo(VertexContainer c, int idx, Float3 bar, Float2 baz) { c.setColor(idx, 1,1,1,0.5f); c.setPosition(idx,bar.x/1,bar.y/1,bar.z/1 ); if (baz != null) c.setTexture(idx, baz.u, 1-baz.v); } private void parseMaterial(InputStream stream) { BufferedReader buffer = new BufferedReader(new InputStreamReader(stream)); Material current = null; String line; try { while ((line = buffer.readLine()) != null) { StringTokenizer parts = new StringTokenizer(line, " "); int numTokens = parts.countTokens(); if (numTokens == 0) continue; String type = parts.nextToken(); if (type.equals(NEW_MATERIAL)) { current = new Material(); materials.put(parts.nextToken(), current); } if (type.equals(DIFFUSE_TEX_MAP)) { current.name = parts.nextToken(); } } } catch (IOException e) { e.printStackTrace(); } } }
Java
package org.esgl3d.primitives; import org.esgl3d.Mesh; import org.esgl3d.Mesh.Format; import org.esgl3d.rendering.LegacyGLWrapper; import org.esgl3d.rendering.Renderer; import org.esgl3d.rendering.VertexContainer; import org.esgl3d.rendering.VertexFormat; public class Box { float box[] = new float[] { // FRONT 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, // BACK -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, // LEFT -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, // RIGHT 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // TOP -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, // BOTTOM -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, }; float texCoords[] = new float[] { // FRONT 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, // BACK 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // LEFT 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // RIGHT 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // TOP 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // BOTTOM 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; VertexContainer container = null; private Box(Renderer r) { container = r.createVertexContainer(VertexFormat.F_2Texture_3Position, box.length/3); //container = r.createVertexContainer(FormatType.F_4Color_3Position, box.length/3); LegacyGLWrapper gl = container.getLegacyGLInterface(); gl.glBegin(); for (int i =0;i<box.length/3;i++) { gl.glTexCoord2f(texCoords[i*2], texCoords[i*2+1]); gl.glVertex3f(box[i*3]*6, box[i*3+1]*6, box[i*3+2]*6); } gl.glEnd(); container.synchronize(); } public Mesh getMesh() { Mesh m = new Mesh(); m.setVertices(container, Format.TriangleStrip); return m; } public static Mesh createTexturedBox(Renderer r) { return new Box(r).getMesh(); } public static Mesh createTexturedBoxWithNormals(Renderer r) { return new Box(r).getMesh(); } }
Java
package org.esgl3d.primitives; import java.util.logging.Logger; import org.esgl3d.Mesh; import org.esgl3d.Mesh.Format; import org.esgl3d.rendering.LegacyGLWrapper; import org.esgl3d.rendering.Renderer; import org.esgl3d.rendering.VertexContainer; import org.esgl3d.rendering.VertexFormat; import org.esgl3d.rendering.VertexContainer.PrimitiveType; public class Pyramid { private static final Logger logger = Logger.getLogger(Pyramid.class.getName()); VertexContainer container = null; private Pyramid(Renderer r) { container = r.createVertexContainer(VertexFormat.F_4Color_3Position, 12); LegacyGLWrapper gl = container.getLegacyGLInterface(); gl.glBegin(); gl.glColor4f(1,1.0f,0.0f,0.0f); // Red gl.glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front) gl.glColor4f(1,0.0f,1.0f,0.0f); // Green gl.glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front) gl.glColor4f(1,0.0f,0.0f,1.0f); // Blue gl.glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front) gl.glColor4f(1,1.0f,0.0f,0.0f); // Red gl.glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right) gl.glColor4f(1,0.0f,0.0f,1.0f); // Blue gl.glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right) gl.glColor4f(1,0.0f,1.0f,0.0f); // Green gl.glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right) gl.glColor4f(1,1.0f,0.0f,0.0f); // Red gl.glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back) gl.glColor4f(1,0.0f,1.0f,0.0f); // Green gl.glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back) gl.glColor4f(1,0.0f,0.0f,1.0f); // Blue gl.glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back) gl.glColor4f(1,1.0f,0.0f,0.0f); // Red gl.glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left) gl.glColor4f(1,0.0f,0.0f,1.0f); // Blue gl.glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left) gl.glColor4f(1,0.0f,1.0f,0.0f); // Green gl.glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left) container.synchronize(); } public Mesh getMesh() { Mesh m = new Mesh(); m.setVertices(container, Format.Triangle); return m; } public static Pyramid createColoredPyramid(Renderer r) { return new Pyramid(r); } }
Java
package org.esgl3d.core; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import android.content.res.AssetManager; import android.content.res.Resources; public class AndroidResourceResolver implements ResourceResolver { private final static Logger logger = Logger.getLogger(AndroidResourceResolver.class.getName()); private final AssetManager manager; public AndroidResourceResolver(AssetManager setAssetManager) { manager = setAssetManager; } @Override public InputStream getResourceStream(String id) { InputStream in = null; if (logger.isLoggable(Level.FINE)) logger.fine("Trying resource "+id); try { in = manager.open(id); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return in; } }
Java
package org.esgl3d.core; import java.io.InputStream; public interface ResourceResolver { /** * Gets a resource stream for the given filename. * @param filename of the resource * @return null if not found otherwise a input stream */ InputStream getResourceStream(String filename); }
Java
package org.esgl3d.ui; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.esgl3d.rendering.Renderer; import org.esgl3d.rendering.VertexContainer; import org.esgl3d.rendering.VertexContainer.PrimitiveType; import org.esgl3d.rendering.VertexFormat; public class Label { private VertexContainer container = null; private String text = ""; private boolean isDirty = true; private BitmapFont bitmapFont = null; private int noOfVertices; private int noOfTriangle; private int color; private float[] colorValuesRGBA = new float[4]; private Renderer renderer; public Label(Renderer r) { renderer = r; container = renderer.createVertexContainer(VertexFormat.F_2Texture_2Position, 128); } public void setText(String value) { text = value; isDirty = true; } public String getText() { return text; } public void setBitmapFont(BitmapFont bitmapFont) { this.bitmapFont = bitmapFont; isDirty = true; } public BitmapFont getBitmapFont() { return bitmapFont; } //@ requires 0 <= \old(newColor); //@ assignable color; public void setColor(int newColor) { color = newColor; colorValuesRGBA[3] = (float)((newColor >> 24) & 0xff)/255; colorValuesRGBA[0] = (float)((newColor >> 16) & 0xff)/255; colorValuesRGBA[1] = (float)((newColor >> 8) & 0xff)/255; colorValuesRGBA[2] = (float)((newColor >> 0) & 0xff)/255; } public int getColor() { return color; } public void render(GL10 gl) { if (isDirty) { char[] chars = text.toCharArray(); // check if new buffer size would be different to old one boolean bufferResize = (chars.length*2 != noOfTriangle) || (container==null); noOfTriangle = chars.length * 2; noOfVertices = noOfTriangle * 3; if (bufferResize) { /*if (container != null) container.release(); container = renderer.createVertexContainer(VertexFormat.F_2Texture_2Position, 128);*/ } else { } bitmapFont.drawInBuffers(container, chars); container.synchronize(); isDirty = false; } bitmapFont.bindTexture(gl); container.draw(PrimitiveType.Triangle, 0, noOfVertices); } }
Java
package org.esgl3d.ui; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import org.esgl3d.rendering.Texture; import org.esgl3d.rendering.VertexContainer; import org.omg.CORBA.PRIVATE_MEMBER; import android.graphics.Bitmap; public class BitmapFont { Texture fontTexture; FloatBuffer fontTex; FloatBuffer face; public BitmapFont(Texture texture) { fontTexture = texture; float width = 1f/16f; float height = width; float[] fontTexCoords = new float[16*16*8]; int ix = 0; for (int row = 0; row < 16; ++row) { for(int col = 0; col < 16; ++col) { fontTexCoords[ix++] = col*width; fontTexCoords[ix++] = row*height + 0.01f; fontTexCoords[ix++] = col*width; fontTexCoords[ix++] = (row+1)*height - 0.01f; fontTexCoords[ix++] = (col+1)*width; fontTexCoords[ix++] = (row)*height + 0.01f; fontTexCoords[ix++] = (col+1)*width; fontTexCoords[ix++] = (row+1)*height - 0.01f; } } fontTex = makeFloatBuffer(fontTexCoords); float faceVerts[] = new float[] { -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, }; face = makeFloatBuffer(faceVerts); } public void bindTexture(GL10 gl) { fontTexture.bind(gl); } public void drawInBuffers(VertexContainer container, char[] chars) { for (int i = 0; i< chars.length; ++i) { // draw two triangles for each char // 0-2 2 // |/ /| // 1 0-1 //vertices.put(i); //vertices.put(0); container.setPosition(i*6+0, i,0); //vertices.put(i); //vertices.put(1); container.setPosition(i*6+1, i, 1); //vertices.put(i+1); //vertices.put(0); container.setPosition(i*6+2, i+1, 0); //vertices.put(i); //vertices.put(1); container.setPosition(i*6+3,i,1); //vertices.put(i+1); //vertices.put(1); container.setPosition(i*6+4,i+1,1); //vertices.put(i+1); //vertices.put(0); container.setPosition(i*6+5, i+1,0); fontTex.position(chars[i]*8); //texture.put(fontTex.get()); //texture.put(fontTex.get()); container.setTexture(i*6+0, fontTex.get(),fontTex.get()); //texture.put(fontTex.get()); //texture.put(fontTex.get()); container.setTexture(i*6+1, fontTex.get(),fontTex.get()); //texture.put(fontTex.get()); //texture.put(fontTex.get()); container.setTexture(i*6+2, fontTex.get(),fontTex.get()); fontTex.position(chars[i]*8+2); //texture.put(fontTex.get()); //texture.put(fontTex.get()); container.setTexture(i*6+3, fontTex.get(),fontTex.get()); fontTex.position(chars[i]*8+6); //texture.put(fontTex.get()); //texture.put(fontTex.get()); container.setTexture(i*6+4, fontTex.get(),fontTex.get()); fontTex.position(chars[i]*8+4); //texture.put(fontTex.get()); //texture.put(fontTex.get()); container.setTexture(i*6+5, fontTex.get(),fontTex.get()); } } /** * Make a direct NIO FloatBuffer from an array of floats * @param arr The array * @return The newly created FloatBuffer */ protected static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** * Make a direct NIO IntBuffer from an array of ints * @param arr The array * @return The newly created IntBuffer */ protected static IntBuffer makeFloatBuffer(int[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); IntBuffer ib = bb.asIntBuffer(); ib.put(arr); ib.position(0); return ib; } protected static ByteBuffer makeByteBuffer(Bitmap bmp) { ByteBuffer bb = ByteBuffer.allocateDirect(bmp.getHeight()*bmp.getWidth()*4); bb.order(ByteOrder.BIG_ENDIAN); IntBuffer ib = bb.asIntBuffer(); for (int y = 0; y < bmp.getHeight(); y++) for (int x=0;x<bmp.getWidth();x++) { int pix = bmp.getPixel(x, bmp.getHeight()-y-1); // Convert ARGB -> RGBA byte alpha = (byte)((pix >> 24)&0xFF); byte red = (byte)((pix >> 16)&0xFF); byte green = (byte)((pix >> 8)&0xFF); byte blue = (byte)((pix)&0xFF); ib.put(((red&0xFF) << 24) | ((green&0xFF) << 16) | ((blue&0xFF) << 8) | ((alpha&0xFF))); } ib.position(0); bb.position(0); return bb; } }
Java
package org.esgl3d; import java.util.ArrayList; import java.util.List; import org.esgl3d.core.AndroidResourceResolver; import org.esgl3d.loader.ObjLoader; import org.esgl3d.primitives.Pyramid; import org.esgl3d.rendering.RenderActivity; import org.esgl3d.rendering.Renderer; import org.esgl3d.scene.MeshNode; import org.esgl3d.scene.Scene; import org.esgl3d.ui.BitmapFont; import org.esgl3d.ui.Label; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory.Options; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Vibrator; import android.util.Log; import android.view.MotionEvent; public class ExAsteroidChaseActivity extends RenderActivity implements SensorEventListener { private static final int MAX_ASTEROIDS = 15; private MeshNode parentNode; private Label myLabel; private Renderer cur; private int oldFps; private ArrayList<MeshNode> asteroids = new ArrayList<MeshNode>(); private Mesh asteroidMesh; private Scene myScene; private ArrayList<MeshNode> kill = new ArrayList<MeshNode>(); private Mesh pyramid; private float deltaX = 0; private float deltaY = 0; private float centerX = 0; private float centerY = 30; private boolean centered = false; private Vibrator vibrator = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE); } @Override protected void onStart() { super.onStart(); SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); List<Sensor> sensorList = sm.getSensorList(Sensor.TYPE_ORIENTATION); sm.registerListener(this, sensorList.get(0) , SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); sm.unregisterListener(this); } @Override public void setupScenegraph() { cur = getRenderer(); myScene = new Scene(); // add our first pyramid parentNode = new MeshNode(); pyramid = Pyramid.createColoredPyramid(cur).getMesh(); parentNode.setGeometry(pyramid); parentNode.translate(0, 0, -10); parentNode.rotate(180, 0, 1, 0); //parentNode.rotate(90, 1, 0, 0); // create a second pyramid and attach it to the base with // a offset to the right (x) AndroidResourceResolver resolver = new AndroidResourceResolver(getAssets()); ObjLoader loader = new ObjLoader(resolver,"comet.obj"); asteroidMesh = loader.createMesh(cur, null); loader = new ObjLoader(resolver, "starship.obj"); Mesh starshipMesh = loader.createMesh(cur, null); parentNode.setGeometry(starshipMesh); // add the first node to our scene (obviously the child pyramid is // attached too) myScene.addChild(parentNode); // set our scene as the one to render cur.setScene(myScene); Options opt = new Options(); opt.inPreferredConfig = Config.RGB_565; Bitmap font = BitmapFactory.decodeStream(resolver.getResourceStream("font.png")); BitmapFont bmpFont = new BitmapFont(cur.getTextureManager().addImage(font, true)); myLabel = new Label(cur); myLabel.setBitmapFont(bmpFont); } @Override public void updateScenegraph() { // rotate the parent node //parentNode.rotate(0.50f, 0, 1, 0); cur.setOrthographicProjection(); if (cur.getFpsCounter().getLastFps() != oldFps) { oldFps = cur.getFpsCounter().getLastFps(); myLabel.setText(cur.getFpsCounter().toString() + " " + String.valueOf(asteroids.size())); } myLabel.setColor(Color.WHITE); myLabel.render(cur.getGl()); if ( (asteroids.size() < MAX_ASTEROIDS) && (Math.random() <= 0.05) ) { MeshNode childNode = new MeshNode(); childNode.setGeometry(asteroidMesh); childNode.translate((float)Math.random()*30-15, (float)Math.random()*30-15, -600); myScene.addChild(childNode); asteroids.add(childNode); } kill.clear(); for (MeshNode curAsteroid : asteroids) { curAsteroid.translate(0,0,125f * cur.getFpsCounter().getLastDelta() / 1000); org.esgl3d.math.Matrix local = curAsteroid.getLocalTransformation(); if ( (local.v[14] >= -15) && (local.v[14] <= -5) ) { float dx = local.v[12] - parentNode.getLocalTransformation().v[12]; float dy = local.v[13] - parentNode.getLocalTransformation().v[13]; //float dz = local.v[14] - parentNode.getLocalTransformation().v[14]; float distance = (float)Math.sqrt((dx*dx)+(dy*dy)); if (distance <= 5) vibrator.vibrate(100); } if (local.v[14] > 2) kill.add(curAsteroid); } for (MeshNode cur : kill) { myScene.removeChild(cur); asteroids.remove(cur); } if (centered) { final float max = 25; float dX = (deltaX-centerX); float dY = (deltaY-centerY); if (dX < -max) dX = -max; if (dX > max) dX = max; if (dY < -max) dY = -max; if (dY > max) dY = max; parentNode.translate(0.5f*dX*cur.getFpsCounter().getLastDelta()/1000, 0 ,0); parentNode.translate(0, 0.5f*dY*cur.getFpsCounter().getLastDelta()/1000,0); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } @Override public boolean onTouchEvent(MotionEvent event) { centerX = deltaX; centerY = deltaY; centered = true; return true; } @Override public void onSensorChanged(SensorEvent event) { //Log.d("sensor1", String.valueOf(event.values[1])); //Log.d("sensor2", String.valueOf(event.values[2])); deltaX = event.values[2]; deltaY = event.values[1]; } }
Java
package org.esgl3d; import java.io.IOException; import java.io.InputStream; import java.util.logging.LogManager; import android.app.Activity; import android.os.Bundle; import android.app.ListActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.util.Linkify; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; /** * Main menu activity * * @author Lee */ public class Startup extends ListActivity { private final int CONTEXTID_VIEWFILE = 0; private final int CONTEXTID_CANCEL = 1; private Class<?>[] classes = { ExMinimalActivity.class, ExTexturedBoxActivity.class, ExBitmapFontActivity.class, ExAsteroidChaseActivity.class, }; private String[] strings = { "Two spinning pyramids", "A textured box", "Simple bitmap font (displays fps)", "Asteroid chase (sample game)" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); InputStream logFile = getResources().openRawResource(R.raw.logging); try { LogManager.getLogManager().readConfiguration(logFile); LogCatHandler handler = new LogCatHandler(); handler.setLevel(java.util.logging.Level.ALL); LogManager.getLogManager().getLogger("").addHandler(handler); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings)); registerForContextMenu(getListView()); } @Override public void onListItemClick(ListView parent, View v, int position, long id) { this.startActivity( new Intent(this, classes[position] ) ); } }
Java
package org.esgl3d; import java.util.Date; import org.esgl3d.core.AndroidResourceResolver; import org.esgl3d.primitives.Box; import org.esgl3d.rendering.RenderActivity; import org.esgl3d.rendering.Renderer; import org.esgl3d.rendering.TextureManager; import org.esgl3d.scene.MeshNode; import org.esgl3d.scene.Scene; import org.esgl3d.ui.BitmapFont; import org.esgl3d.ui.Label; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory.Options; public class ExBitmapFontActivity extends RenderActivity { private Label myLabel = null; private Renderer cur; private MeshNode box = null; private final String dateTime; private int oldFps; public ExBitmapFontActivity() { dateTime = new Date().toLocaleString(); } @Override public void setupScenegraph() { cur = getRenderer(); // create a new scene Scene myScene = new Scene(); Mesh boxMesh = Box.createTexturedBox(cur); AndroidResourceResolver resolver = new AndroidResourceResolver(getAssets()); Bitmap font = BitmapFactory.decodeStream(resolver.getResourceStream("nehe_texture_crate.png")); // create a new box and set a texture box = new MeshNode(); box.setGeometry(boxMesh); boxMesh.setTexture(cur.getTextureManager().addImage(font, false)); // add the box to the scene myScene.addChild(box); // set the scene to be rendered cur.setScene(myScene); Options opt = new Options(); opt.inPreferredConfig = Config.RGB_565; font = BitmapFactory.decodeStream(resolver.getResourceStream("font.png")); BitmapFont bmpFont = new BitmapFont(cur.getTextureManager().addImage(font, true)); myLabel = new Label(cur); myLabel.setBitmapFont(bmpFont); } @Override public void updateScenegraph() { // rotate our box a little box.rotate(1, 0.25f, 1, 0); cur.setOrthographicProjection(); if (cur.getFpsCounter().getLastFps() != oldFps) { oldFps = cur.getFpsCounter().getLastFps(); } myLabel.setText(cur.getFpsCounter().toString()); myLabel.setColor(Color.WHITE); myLabel.render(cur.getGl()); } }
Java
package org.esgl3d; import org.esgl3d.primitives.Pyramid; import org.esgl3d.rendering.RenderActivity; import org.esgl3d.rendering.Renderer; import org.esgl3d.scene.MeshNode; import org.esgl3d.scene.Scene; import org.esgl3d.scene.SceneNode; import android.app.Activity; import android.os.Bundle; public class ExMinimalActivity extends RenderActivity { private MeshNode parentNode; private MeshNode childNode; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public void setupScenegraph() { // get our current renderer instance Renderer cur = getRenderer(); // create a new scene Scene myScene = new Scene(); // add our first pyramid parentNode = new MeshNode(); parentNode.setGeometry(Pyramid.createColoredPyramid(cur).getMesh()); // create a second pyramid and attach it to the base with // a offset to the right (x) childNode = new MeshNode(); childNode.setGeometry(Pyramid.createColoredPyramid(cur).getMesh()); childNode.translate(10, 0, 0); childNode.attachTo(parentNode); // add the first node to our scene (obviously the child pyramid is // attached too) myScene.addChild(parentNode); // set our scene as the one to render cur.setScene(myScene); } @Override public void updateScenegraph() { // rotate the parent node parentNode.rotate(1, 0, 1, 0); // rotate the child node // since this node is attached to the parent it gets rotated too childNode.rotate(1, 0, 0, 1); } }
Java
package org.esgl3d; import org.esgl3d.core.AndroidResourceResolver; import org.esgl3d.primitives.Box; import org.esgl3d.primitives.Pyramid; import org.esgl3d.rendering.RenderActivity; import org.esgl3d.rendering.Renderer; import org.esgl3d.scene.MeshNode; import org.esgl3d.scene.Scene; import org.esgl3d.ui.BitmapFont; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory.Options; import android.os.Bundle; public class ExTexturedBoxActivity extends RenderActivity { private MeshNode box; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public void setupScenegraph() { AndroidResourceResolver resolver = new AndroidResourceResolver(getAssets()); // get our renderer Renderer cur = getRenderer(); // load a bitmap (straightforward android code) Options opt = new Options(); opt.inPreferredConfig = Config.RGB_565; Bitmap font = BitmapFactory.decodeStream(resolver.getResourceStream("nehe_texture_crate.png")); // create a new scene Scene myScene = new Scene(); Mesh boxMesh = Box.createTexturedBox(cur); // create a new box and set a texture box = new MeshNode(); box.setGeometry(boxMesh); boxMesh.setTexture(cur.getTextureManager().addImage(font, false)); // add the box to the scene myScene.addChild(box); // set the scene to be rendered cur.setScene(myScene); } @Override public void updateScenegraph() { // rotate our box a little box.rotate(1, 0.25f, 1, 0); } }
Java