Search Results

Search found 255 results on 11 pages for 'instanceof'.

Page 9/11 | < Previous Page | 5 6 7 8 9 10 11  | Next Page >

  • Constructors from extended class in Java

    - by Crystal
    I'm having some trouble with a hw assignment. In one assignment, we had to create a Person class. Mine was: public class Person { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return 7 * firstName.hashCode() + 11 * lastName.hashCode() + 13 * telephone.hashCode() + 15 * email.hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } } Now we have to extend that class and use that class in our constructor. The function protoype is: public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) I'm confused on how I use the Person constructor from the superclass. I cannot necessarily do super(client); in my constructor which is what the book did with some primitive types in their example. Not sure what the correct thing to do is... Any thoughts? Thanks!

    Read the article

  • Java collision detection and player movement: tips

    - by Loris
    I have read a short guide for game develompent (java, without external libraries). I'm facing with collision detection and player (and bullets) movements. Now i put the code. Most of it is taken from the guide (should i link this guide?). I'm just trying to expand and complete it. This is the class that take care of updates movements and firing mechanism (and collision detection): public class ArenaController { private Arena arena; /** selected cell for movement */ private float targetX, targetY; /** true if droid is moving */ private boolean moving = false; /** true if droid is shooting to enemy */ private boolean shooting = false; private DroidController droidController; public ArenaController(Arena arena) { this.arena = arena; this.droidController = new DroidController(arena); } public void update(float delta) { Droid droid = arena.getDroid(); //droid movements if (moving) { droidController.moveDroid(delta, targetX, targetY); //check if arrived if (droid.getX() == targetX && droid.getY() == targetY) moving = false; } //firing mechanism if(shooting) { //stop shot if there aren't bullets if(arena.getBullets().isEmpty()) { shooting = false; } for(int i = 0; i < arena.getBullets().size(); i++) { //current bullet Bullet bullet = arena.getBullets().get(i); System.out.println(bullet.getBounds()); //angle calculation double angle = Math.atan2(bullet.getEnemyY() - bullet.getY(), bullet.getEnemyX() - bullet.getX()); //increments x and y bullet.setX((float) (bullet.getX() + (Math.cos(angle) * bullet.getSpeed() * delta))); bullet.setY((float) (bullet.getY() + (Math.sin(angle) * bullet.getSpeed() * delta))); //collision with obstacles for(int j = 0; j < arena.getObstacles().size(); j++) { Obstacle obs = arena.getObstacles().get(j); if(bullet.getBounds().intersects(obs.getBounds())) { System.out.println("Collision detect!"); arena.removeBullet(bullet); } } //collisions with enemies for(int j = 0; j < arena.getEnemies().size(); j++) { Enemy ene = arena.getEnemies().get(j); if(bullet.getBounds().intersects(ene.getBounds())) { System.out.println("Collision detect!"); arena.removeBullet(bullet); } } } } } public boolean onClick(int x, int y) { //click on empty cell if(arena.getGrid()[(int)(y / Arena.TILE)][(int)(x / Arena.TILE)] == null) { //coordinates targetX = x / Arena.TILE; targetY = y / Arena.TILE; //enables movement moving = true; return true; } //click on enemy: fire if(arena.getGrid()[(int)(y / Arena.TILE)][(int)(x / Arena.TILE)] instanceof Enemy) { //coordinates float enemyX = x / Arena.TILE; float enemyY = y / Arena.TILE; //new bullet Bullet bullet = new Bullet(); //start coordinates bullet.setX(arena.getDroid().getX()); bullet.setY(arena.getDroid().getY()); //end coordinates (enemie) bullet.setEnemyX(enemyX); bullet.setEnemyY(enemyY); //adds bullet to arena arena.addBullet(bullet); //enables shooting shooting = true; return true; } return false; } As you can see for collision detection i'm trying to use Rectangle object. Droid example: import java.awt.geom.Rectangle2D; public class Droid { private float x; private float y; private float speed = 20f; private float rotation = 0f; private float damage = 2f; public static final int DIAMETER = 32; private Rectangle2D rectangle; public Droid() { rectangle = new Rectangle2D.Float(x, y, DIAMETER, DIAMETER); } public float getX() { return x; } public void setX(float x) { this.x = x; //rectangle update rectangle.setRect(x, y, DIAMETER, DIAMETER); } public float getY() { return y; } public void setY(float y) { this.y = y; //rectangle update rectangle.setRect(x, y, DIAMETER, DIAMETER); } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public float getRotation() { return rotation; } public void setRotation(float rotation) { this.rotation = rotation; } public float getDamage() { return damage; } public void setDamage(float damage) { this.damage = damage; } public Rectangle2D getRectangle() { return rectangle; } } For now, if i start the application and i try to shot to an enemy, is immediately detected a collision and the bullet is removed! Can you help me with this? If the bullet hit an enemy or an obstacle in his way, it must disappear. Ps: i know that the movements of the bullets should be managed in another class. This code is temporary. update I realized what happens, but not why. With those for loops (which checks collisions) the movements of the bullets are instantaneous instead of gradual. In addition to this, if i add the collision detection to the Droid, the method intersects returns true ALWAYS while the droid is moving! public void moveDroid(float delta, float x, float y) { Droid droid = arena.getDroid(); int bearing = 1; if (droid.getX() > x) { bearing = -1; } if (droid.getX() != x) { droid.setX(droid.getX() + bearing * droid.getSpeed() * delta); //obstacles collision detection for(Obstacle obs : arena.getObstacles()) { if(obs.getRectangle().intersects(droid.getRectangle())) { System.out.println("Collision detected"); //ALWAYS HERE } } //controlla se è arrivato if ((droid.getX() < x && bearing == -1) || (droid.getX() > x && bearing == 1)) droid.setX(x); } bearing = 1; if (droid.getY() > y) { bearing = -1; } if (droid.getY() != y) { droid.setY(droid.getY() + bearing * droid.getSpeed() * delta); if ((droid.getY() < y && bearing == -1) || (droid.getY() > y && bearing == 1)) droid.setY(y); } }

    Read the article

  • Key Promoter for NetBeans

    - by Geertjan
    Whenever a menu item or toolbar button is clicked, it would be handy if NetBeans were to tell you 'hey, did you know, you can actually do this via the following keyboard shortcut', if a keyboard shortcut exists for the invoked action. After all, ultimately, a lot of developers would like to do everything with the keyboard and a key promoter feature of this kind is a helpful tool in learning the keyboard shortcuts related to the menu items and toolbar buttons you're clicking with your mouse. Above, you see the balloon message that appears for each menu item and toolbar button that you click and, below, you can see a list of all the actions that have been logged in the Notifications window. That happens automatically when an action is invoked (assuming the plugin described in this blog entry is installed), showing the display name of the action, together with the keyboard shortcut, which is presented as a hyperlink which, when clicked, re-invokes the action (which might not always be relevant, especially for context-sensitive actions, though for others it is quite useful, e.g., reopen the New Project wizard). And here's all the code. Notice that I'm hooking into the 'uigestures' functionality, which was suggested by Tim Boudreau, and I have added my own handler, which was suggested by Jaroslav Tulach, which gets a specific parameter from each new log entry handled by the 'org.netbeans.ui.actions' logger, makes sure that the parameter actually is an action, and then gets the relevant info from the action, if the relevant info exists: @OnShowingpublic class Startable implements Runnable {    @Override    public void run() {        Logger logger = Logger.getLogger("org.netbeans.ui.actions");        logger.addHandler(new StreamHandler() {            @Override            public void publish(LogRecord record) {                Object[] parameters = record.getParameters();                if (parameters[2] instanceof Action) {                    Action a = (Action) parameters[2];                    JMenuItem menu = new JMenuItem();                    Mnemonics.setLocalizedText(                            menu,                             a.getValue(Action.NAME).toString());                    String name = menu.getText();                    if (a.getValue(Action.ACCELERATOR_KEY) != null) {                        String accelerator = a.getValue(Action.ACCELERATOR_KEY).toString();                        NotificationDisplayer.getDefault().notify(                                name,                                 new ImageIcon("/org/nb/kp/car.png"),                                 accelerator,                                 new ActionListener() {                            @Override                            public void actionPerformed(ActionEvent e) {                                a.actionPerformed(e);                            }                        });                    }                }            }        });    }} Indeed, inspired by the Key Promoter in IntelliJ IDEA. Interested in trying it out? If there's interest in it, I'll put it in the NetBeans Plugin Portal.

    Read the article

  • JMS messaging implementation

    - by Gandalf StormCrow
    I've been struggling with this "simple" task for more expirienced people, I'm stuck for 2 days now need help. I've changed things arround like zillion times now, finally I stumbled upon this spring JMS tutorial. What I want to do, Send a message and receive it. I've been also reading this book chapter 8 on messaging. It really nicely explains 2 type of messaging and there is nice example for publish-and-subscribe type but now example for point-to-point messaging( this is the one I need). I'm able to send message to the queue on my own, but don't have a clue how to receive thats why I tried with this spring tutorial here is what I've got so far : SENDER : package quartz.spring.com.example; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.Session; import org.springframework.jms.core.MessageCreator; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.JmsTemplate102; import org.springframework.jms.core.MessagePostProcessor; public class JmsQueueSender { private JmsTemplate jmsTemplate; private Queue queue; public void setConnectionFactory(ConnectionFactory cf) { this.jmsTemplate = new JmsTemplate102(cf, false); } public void setQueue(Queue queue) { this.queue = queue; } public void simpleSend() { this.jmsTemplate.send(this.queue, new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage("hello queue world"); } }); } public void sendWithConversion() { Map map = new HashMap(); map.put("Name", "Mark"); map.put("Age", new Integer(47)); jmsTemplate.convertAndSend("testQueue", map, new MessagePostProcessor() { public Message postProcessMessage(Message message) throws JMSException { message.setIntProperty("AccountID", 1234); message.setJMSCorrelationID("123-00001"); return message; } }); } } RECEIVER : package quartz.spring.com.example; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; public class ExampleListener implements MessageListener { public void onMessage(Message message) { if (message instanceof TextMessage) { try { System.out.println(((TextMessage) message).getText()); } catch (JMSException ex) { throw new RuntimeException(ex); } } else { throw new IllegalArgumentException("Message must be of type TextMessage"); } } } applicationcontext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd"> <bean id="sender" class="quartz.spring.com.example.JmsQueueSender" init-method="sendWithConversion" /> <bean id="receiver" class="quartz.spring.com.example.ExampleListener" init-method="onMessage" /> </beans> Didn't really know that learning curve for this is so long, I mean the idea is very simple: Send message to the destination queue Receive message from the destination queue To receive messages, you do the following(so does book say): 1 Locate a ConnectionFactory, typically using JNDI. 2 Use the ConnectionFactory to create a Connection. 3 Use the Connection to create a Session. 4 Locate a Destination, typically using JNDI. 5 Use the Session to create a MessageConsumer for that Destination. Once you’ve done this, methods on the MessageConsumer enable you to either query the Destination for messages or to register for message notification. Can somebody please direct me towards right direction, is there a tutorial which explains in details how to receive message from the queue?I have the working send message code, didn't post it here because this post is too long as it is.

    Read the article

  • JSF: Cannot catch ViewExpiredException

    - by ifischer
    I'm developing a JSF 2.0 application on Glassfish v3 and i'm trying to handle the ViewExpiredException. But whatever i do, i always get a Glassfish error report instead of my own error page. To simulate the occurrence of the VEE, i inserted the following function into my backing bean, which fires the VEE. I'm triggering this function from my JSF page through a commandLink. The Code: @Named public class PersonHome { (...) public void throwVEE() { throw new ViewExpiredException(); } } At first i tried it by simply adding an error-page to my web.xml: <error-page> <exception-type>javax.faces.application.ViewExpiredException</exception-type> <location>/error.xhtml</location> </error-page> But this doesn't work, i'm not redirected to error but i'm shown the Glassfish errorpage, which shows a HTTP Status 500 page with the following content: description:The server encountered an internal error () that prevented it from fulfilling this request. exception: javax.servlet.ServletException: javax.faces.application.ViewExpiredException root cause: javax.faces.el.EvaluationException:javax.faces.application.ViewExpiredException root cause:javax.faces.application.ViewExpiredException Next thing i tried was to write ExceptionHandlerFactory and a CustomExceptionHandler, as described in JavaServerFaces 2.0 - The Complete Reference. So i inserted the following tag into faces-config.xml: <factory> <exception-handler-factory> exceptions.ExceptionHandlerFactory </exception-handler-factory> </factory> And added these classes: The factory: package exceptions; import javax.faces.context.ExceptionHandler; public class ExceptionHandlerFactory extends javax.faces.context.ExceptionHandlerFactory { private javax.faces.context.ExceptionHandlerFactory parent; public ExceptionHandlerFactory(javax.faces.context.ExceptionHandlerFactory parent) { this.parent = parent; } @Override public ExceptionHandler getExceptionHandler() { ExceptionHandler result = parent.getExceptionHandler(); result = new CustomExceptionHandler(result); return result; } } The custom exception handler: package exceptions; import java.util.Iterator; import javax.faces.FacesException; import javax.faces.application.NavigationHandler; import javax.faces.application.ViewExpiredException; import javax.faces.context.ExceptionHandler; import javax.faces.context.ExceptionHandlerWrapper; import javax.faces.context.FacesContext; import javax.faces.event.ExceptionQueuedEvent; import javax.faces.event.ExceptionQueuedEventContext; class CustomExceptionHandler extends ExceptionHandlerWrapper { private ExceptionHandler parent; public CustomExceptionHandler(ExceptionHandler parent) { this.parent = parent; } @Override public ExceptionHandler getWrapped() { return this.parent; } @Override public void handle() throws FacesException { for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) { ExceptionQueuedEvent event = i.next(); System.out.println("Iterating over ExceptionQueuedEvents. Current:" + event.toString()); ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource(); Throwable t = context.getException(); if (t instanceof ViewExpiredException) { ViewExpiredException vee = (ViewExpiredException) t; FacesContext fc = FacesContext.getCurrentInstance(); NavigationHandler nav = fc.getApplication().getNavigationHandler(); try { // Push some useful stuff to the flash scope for // use in the page fc.getExternalContext().getFlash().put("expiredViewId", vee.getViewId()); nav.handleNavigation(fc, null, "/login?faces-redirect=true"); fc.renderResponse(); } finally { i.remove(); } } } // At this point, the queue will not contain any ViewExpiredEvents. // Therefore, let the parent handle them. getWrapped().handle(); } } But STILL i'm NOT redirected to my error page - i'm getting the same HTTP 500 error like above. What am i doing wrong, what could be missing in my implementation so that the exception is handled correctly?

    Read the article

  • Placing component on Glass Pane

    - by Chris Lieb
    I have a subclass of JLabel that forms a component of my GUI. I have implemented the ability to drag and drop the component from one container to another, but without any visual effects. I want to have this JLabel follow the cursor during the drag of the item from one container to another. I figured that I could just create a glass pane and draw it on there. However, even after I add the component to the glass pane, set the component visible, and set the glass pane visible, and set the glass pane as opaque, I still so not see the component. I know the component works because I can add it to the content pane and have it show up. How do I add a component to the glass pane? package wpics509s10t7.view; import javax.swing.*; import wpics509s10t7.model.Tile; import java.awt.*; import java.awt.dnd.DragSource; import java.awt.event.AWTEventListener; import java.awt.event.MouseEvent; /** * GlassPane tutorial * "A well-behaved GlassPane" * http://weblogs.java.net/blog/alexfromsun/ * <p/> * This is the final version of the GlassPane * it is transparent for MouseEvents, * and respects underneath component's cursors by default, * it is also friedly for other users, * if someone adds a mouseListener to this GlassPane * or set a new cursor it will respect them * * @author Alexander Potochkin */ public class GlassPane extends JPanel implements AWTEventListener { private static final long serialVersionUID = 1L; private final JFrame frame; private TileView tv; // subclass of JLabel private Point point; private WordStealApp wsa; public GlassPane(JFrame frame, WordStealApp wsa) { super(null); this.wsa = wsa; this.frame = frame; setOpaque(true); setLayout(null); setVisible(true); composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); } public void beginDrag(Tile t, Point p) { this.tv = new TileView(t, null, this.wsa, true); this.add(this.tv); System.out.println("Starting point: x=" + p.getX() + ",y=" + p.getY()); this.tv.setLocation((int)p.getX(), (int)p.getY()); this.tv.setVisible(true); } public void endDrag(Point p) { System.out.println("Ending point: x=" + p.getX() + ",y=" + p.getY()); this.remove(this.tv); this.tv.setVisible(false); this.tv = null; } public void eventDispatched(AWTEvent event) { if (event instanceof MouseEvent) { MouseEvent me = (MouseEvent) event; if (!SwingUtilities.isDescendingFrom(me.getComponent(), frame)) { return; } if (me.getID() == MouseEvent.MOUSE_EXITED && me.getComponent() == frame) { if (tv != null) { tv.setVisible(false); } point = null; } else { MouseEvent converted = SwingUtilities.convertMouseEvent(me.getComponent(), me, frame.getGlassPane()); point = converted.getPoint(); } repaint(); } } /** * If someone adds a mouseListener to the GlassPane or set a new cursor * we expect that he knows what he is doing * and return the super.contains(x, y) * otherwise we return false to respect the cursors * for the underneath components */ @Override public boolean contains(int x, int y) { if (getMouseListeners().length == 0 && getMouseMotionListeners().length == 0 && getMouseWheelListeners().length == 0 && getCursor() == Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)) { return false; } return super.contains(x, y); } }

    Read the article

  • Using UUIDs for cheap equals() and hashCode()

    - by Tom McIntyre
    I have an immutable class, TokenList, which consists of a list of Token objects, which are also immutable: @Immutable public final class TokenList { private final List<Token> tokens; public TokenList(List<Token> tokens) { this.tokens = Collections.unmodifiableList(new ArrayList(tokens)); } public List<Token> getTokens() { return tokens; } } I do several operations on these TokenLists that take multiple TokenLists as inputs and return a single TokenList as the output. There can be arbitrarily many TokenLists going in, and each can have arbitrarily many Tokens. These operations are expensive, and there is a good chance that the same operation (ie the same inputs) will be performed multiple times, so I would like to cache the outputs. However, performance is critical, and I am worried about the expense of performing hashCode() and equals() on these objects that may contain arbitrarily many elements (as they are immutable then hashCode could be cached, but equals will still be expensive). This led me to wondering whether I could use a UUID to provide equals() and hashCode() simply and cheaply by making the following updates to TokenList: @Immutable public final class TokenList { private final List<Token> tokens; private final UUID uuid; public TokenList(List<Token> tokens) { this.tokens = Collections.unmodifiableList(new ArrayList(tokens)); this.uuid = UUID.randomUUID(); } public List<Token> getTokens() { return tokens; } public UUID getUuid() { return uuid; } } And something like this to act as a cache key: @Immutable public final class TopicListCacheKey { private final UUID[] uuids; public TopicListCacheKey(TopicList... topicLists) { uuids = new UUID[topicLists.length]; for (int i = 0; i < uuids.length; i++) { uuids[i] = topicLists[i].getUuid(); } } @Override public int hashCode() { return Arrays.hashCode(uuids); } @Override public boolean equals(Object other) { if (other == this) return true; if (other instanceof TopicListCacheKey) return Arrays.equals(uuids, ((TopicListCacheKey) other).uuids); return false; } } I figure that there are 2^128 different UUIDs and I will probably have at most around 1,000,000 TokenList objects active in the application at any time. Given this, and the fact that the UUIDs are used combinatorially in cache keys, it seems that the chances of this producing the wrong result are vanishingly small. Nevertheless, I feel uneasy about going ahead with it as it just feels 'dirty'. Are there any reasons I should not use this system? Will the performance costs of the SecureRandom used by UUID.randomUUID() outweigh the gains (especially since I expect multiple threads to be doing this at the same time)? Are collisions going to be more likely than I think? Basically, is there anything wrong with doing it this way?? Thanks.

    Read the article

  • My Dijit DateTimeCombo widget doesn't send selected value on form submission

    - by david bessire
    i need to create a Dojo widget that lets users specify date & time. i found a sample implementation attached to an entry in the Dojo bug tracker. It looks nice and mostly works, but when i submit the form, the value sent by the client is not the user-selected value but the value sent from the server. What changes do i need to make to get the widget to submit the date & time value? Sample usage is to render a JSP with basic HTML tags (form & input), then dojo.addOnLoad a function which selects the basic elements by ID, adds dojoType attribute, and dojo.parser.parse()-es the page. Thanks in advance. The widget is implemented in two files. The application uses Dojo 1.3. File 1: DateTimeCombo.js dojo.provide("dojox.form.DateTimeCombo"); dojo.require("dojox.form._DateTimeCombo"); dojo.require("dijit.form._DateTimeTextBox"); dojo.declare( "dojox.form.DateTimeCombo", dijit.form._DateTimeTextBox, { baseClass: "dojoxformDateTimeCombo dijitTextBox", popupClass: "dojox.form._DateTimeCombo", pickerPostOpen: "pickerPostOpen_fn", _selector: 'date', constructor: function (argv) {}, postMixInProperties: function() { dojo.mixin(this.constraints, { /* datePattern: 'MM/dd/yyyy HH:mm:ss', timePattern: 'HH:mm:ss', */ datePattern: 'MM/dd/yyyy HH:mm', timePattern: 'HH:mm', clickableIncrement:'T00:15:00', visibleIncrement:'T00:15:00', visibleRange:'T01:00:00' }); this.inherited(arguments); }, _open: function () { this.inherited(arguments); if (this._picker!==null && (this.pickerPostOpen!==null && this.pickerPostOpen!=="")) { if (this._picker.pickerPostOpen_fn!==null) { this._picker.pickerPostOpen_fn(this); } } } } ); File 2: _DateTimeCombo.js dojo.provide("dojox.form._DateTimeCombo"); dojo.require("dojo.date.stamp"); dojo.require("dijit._Widget"); dojo.require("dijit._Templated"); dojo.require("dijit._Calendar"); dojo.require("dijit.form.TimeTextBox"); dojo.require("dijit.form.Button"); dojo.declare("dojox.form._DateTimeCombo", [dijit._Widget, dijit._Templated], { // invoked only if time picker is empty defaultTime: function () { var res= new Date(); res.setHours(0,0,0); return res; }, // id of this table below is the same as this.id templateString: " <table class=\"dojoxDateTimeCombo\" waiRole=\"presentation\">\ <tr class=\"dojoxTDComboCalendarContainer\">\ <td>\ <center><input dojoAttachPoint=\"calendar\" dojoType=\"dijit._Calendar\"></input></center>\ </td>\ </tr>\ <tr class=\"dojoxTDComboTimeTextBoxContainer\">\ <td>\ <center><input dojoAttachPoint=\"timePicker\" dojoType=\"dijit.form.TimeTextBox\"></input></center>\ </td>\ </tr>\ <tr><td><center><button dojoAttachPoint=\"ctButton\" dojoType=\"dijit.form.Button\">Ok</button></center></td></tr>\ </table>\ ", widgetsInTemplate: true, constructor: function(arg) {}, postMixInProperties: function() { this.inherited(arguments); }, postCreate: function() { this.inherited(arguments); this.connect(this.ctButton, "onClick", "_onValueSelected"); }, // initialize pickers to calendar value pickerPostOpen_fn: function (parent_inst) { var parent_value = parent_inst.attr('value'); if (parent_value !== null) { this.setValue(parent_value); } }, // expects a valid date object setValue: function(value) { if (value!==null) { this.calendar.attr('value', value); this.timePicker.attr('value', value); } }, // return a Date constructed date in calendar & time in time picker. getValue: function() { var value = this.calendar.attr('value'); var result=value; if (this.timePicker.value !== null) { if ((this.timePicker.value instanceof Date) === true) { result.setHours(this.timePicker.value.getHours(), this.timePicker.value.getMinutes(), this.timePicker.value.getSeconds()); return result; } } else { var defTime=this.defaultTime(); result.setHours(defTime.getHours(), defTime.getMinutes(), defTime.getSeconds()); return result; } }, _onValueSelected: function() { var value = this.getValue(); this.onValueSelected(value); }, onValueSelected: function(value) {} });

    Read the article

  • getting base64 content string of an image from a mimepart in Java

    - by Bas van den Broek
    Hello, I am trying to get the base64 content of a MimePart in a MimeMultiPart, but I'm struggling with the Javamail package. I simply want the base64 encoded String of a certain inline image, there doesn't seem to be an easy way to do this though. I wrote a method that will take the mime content (as a string) and an image name as a parameter, and searches for the part that contains the base64 content of that image name, and in the end returns this base64 string (as well as the content type but that is irrelevant for this question) Here is the relevant code: private static String[] getBase64Content(String imageName, String mimeString) throws MessagingException, IOException { System.out.println("image name: " + imageName + "\n\n"); System.out.println("mime string: " + mimeString); String[] base64Content = new String[2]; base64Content[0] = ""; base64Content[1] = "image/jpeg"; //some default value DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(mimeString.getBytes()), "multipart/mixed"); MimeMultipart mp = new MimeMultipart(source); for (int i = 0; i < mp.getCount(); i++) { MimePart part = (MimePart) mp.getBodyPart(i); String disposition = part.getDisposition(); if (disposition != null && disposition.equals(Part.INLINE)) { if (part.getContentID() != null && part.getContentID().indexOf(imageName) > -1) //check if this is the right part { if (part.getContent() instanceof BASE64DecoderStream) { BASE64DecoderStream base64DecoderStream = (BASE64DecoderStream) part.getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(base64DecoderStream, writer); String base64decodedString = writer.toString(); byte[] encodedMimeByteArray = Base64.encodeBase64(base64decodedString.getBytes()); String encodedMimeString = new String(encodedMimeByteArray); System.out.println("encoded mime string: " + encodedMimeString); base64Content[0] = encodedMimeString; base64Content[1] = getContentTypeString(part); } } } } return base64Content; } I cannot paste all of the output as the post would be too long, but this is some of it: image name: [email protected] This is a part of the mimeString input, it does find this (correct) part with the image name: --_004_225726A14AF9134CB538EE7BD44373A04D9E3F3940menexch2007ex_ Content-Type: image/gif; name="image001.gif" Content-Description: image001.gif Content-Disposition: inline; filename="image001.gif"; size=1070; creation-date="Fri, 02 Apr 2010 16:19:43 GMT"; modification-date="Fri, 02 Apr 2010 16:19:43 GMT" Content-ID: <[email protected]> Content-Transfer-Encoding: base64 R0lGODlhEAAQAPcAABxuHJzSlDymHGy2XHTKbITCdNTu1FyqTHTCXJTKhLTarCSKHEy2JHy6bJza lITKfFzCPEyWPHS+XHzCbJzSjFS+NLTirBx6HHzKdOz27GzCZJTOjCyWHKzWpHy2ZJTGhHS+VLzi (more base64 string here that I'm not going to paste) But when it finally prints the encoded mime string, this is a different string than I was expecting: encoded mime string: R0lGODlhEAAQAO+/vQAAHG4c77+90pQ877+9HGzvv71cdO+/vWzvv73vv71077+977+977+9XO+/vUx077+9XO+/vcqE77+92qwk77+9HEzvv70kfO+/vWzvv73alO+ Clearly different from the one that has its output in the part above. I'm not even sure what I'm looking at here, but when I try to load this as an image in a html page, it won't work. This is fairly frustrating for me, since all I want is a piece of the text that I'm already printing, but I'd rather not have to search through the mime string myself for the correct part, introducing all kinds of bugs.So I'd really prefer to use the Javamail library but could use some help on how to actually get that correct mime string.

    Read the article

  • FolderClosed Exception in Javamail

    - by SikhWarrior
    Im trying to create a simple mail client in android, and I have the android version of javamail compiling and running in my app. However, whenever I try to connect and receive mail, I get a Folder Closed exception seen below. 10-23 12:12:13.484: W/System.err(6660): javax.mail.FolderClosedException 10-23 12:12:13.484: W/System.err(6660): at com.sun.mail.imap.IMAPMessage.getProtocol(IMAPMessage.java:149) 10-23 12:12:13.484: W/System.err(6660): at com.sun.mail.imap.IMAPMessage.loadBODYSTRUCTURE(IMAPMessage.java:1262) 10-23 12:12:13.484: W/System.err(6660): at com.sun.mail.imap.IMAPMessage.getDataHandler(IMAPMessage.java:616) 10-23 12:12:13.484: W/System.err(6660): at javax.mail.internet.MimeMessage.getContent(MimeMessage.java:1398) 10-23 12:12:13.484: W/System.err(6660): at com.teamzeta.sfu.Util.MailHelper.getMessageHTML(MailHelper.java:60) 10-23 12:12:13.484: W/System.err(6660): at com.teamzeta.sfu.GetAsyncEmails.onPostExecute(EmailActivity.java:31) 10-23 12:12:13.484: W/System.err(6660): at com.teamzeta.sfu.GetAsyncEmails.onPostExecute(EmailActivity.java:1) 10-23 12:12:13.484: W/System.err(6660): at android.os.AsyncTask.finish(AsyncTask.java:631) 10-23 12:12:13.484: W/System.err(6660): at android.os.AsyncTask.access$600(AsyncTask.java:177) 10-23 12:12:13.484: W/System.err(6660): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 10-23 12:12:13.484: W/System.err(6660): at android.os.Handler.dispatchMessage(Handler.java:99) 10-23 12:12:13.484: W/System.err(6660): at android.os.Looper.loop(Looper.java:137) 10-23 12:12:13.484: W/System.err(6660): at android.app.ActivityThread.main(ActivityThread.java:5227) 10-23 12:12:13.484: W/System.err(6660): at java.lang.reflect.Method.invokeNative(Native Method) 10-23 12:12:13.484: W/System.err(6660): at java.lang.reflect.Method.invoke(Method.java:511) 10-23 12:12:13.484: W/System.err(6660): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 10-23 12:12:13.484: W/System.err(6660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 10-23 12:12:13.494: W/System.err(6660): at dalvik.system.NativeStart.main(Native Method) My code is as follows: public static Message[] getAllMail(String user, String pwd){ String host = "imap.sfu.ca"; final Message[] NO_MESSAGES = {}; Properties properties = System.getProperties(); properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.imap.socketFactory.port", "993"); Session session = Session.getDefaultInstance(properties); try { Store store = session.getStore("imap"); store.connect(host, user, pwd); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); folder.close(true); store.close(); Log.d("####TEAM ZETA DEBUG####", "Content: " + messages.length); return messages; } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("####TEAM ZETA DEBUG####", "Returning NO_MESSAGES"); return NO_MESSAGES; } public static String getMessageHTML(Message message){ Object msgContent; try { msgContent = message.getContent(); if (msgContent instanceof Multipart) { Multipart mp = (Multipart) msgContent; for (int i = 0; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); if (Pattern .compile(Pattern.quote("text/html"), Pattern.CASE_INSENSITIVE) .matcher(bp.getContentType()).find()) { // found html part return (String) bp.getContent(); } else { // some other bodypart... } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Something went wrong"; } I couldn't find anything helpful on the web, does anyone have an ideas why this is happening?? This is called in class GetAsyncEmails extends AsyncTask<String, Integer, Message[]>{ @Override protected Message[] doInBackground(String... args) { // TODO Auto-generated method stub Message[] messages = MailHelper.getAllMail(args[0], args[1]); return messages; } protected void onPostExecute(Message[] result){ if(result.length > 1){ Message message = result[0]; String content = MailHelper.getMessageHTML(message); System.out.println("####TEAM ZETA DEBUG####" + content); } } }

    Read the article

  • How to represent a Board Panel in Java for a game ? [+code]

    - by FILIaS
    I wanna fix a 2D board for a game. I've already fixed other panels for the Gui and everything goes well. But the panel for the board cant be printed on the window. I'm a bit confused about it as i think i've followed the same ideas as for the others panels i need. Here's what i've done: EDIT:*EDIT* what i'm trying to do is fix a board panel for the game according to the dimensions of the it,hold every square in an array in order to use it after wherever it;s needed. I draw each little square of it with the method draw and put it back to the panel. So, each square on the board is a panel. This is the idea. But as u can see. There are troubles/errors on it. EDIT: code updated. just found a part of the problem. i thought first that i had set background to squared, but i didnt. with this one it appears on the panel a wide black "column". Unfortunately,still none squares. :( One More EDIT: Also,i realized that draw method is never called. when i put the draw method in the following method i can see the squares but they remain small. I redefine them with setSize but still no change. /** *Method used to construct the square in the area of the *gui's grid. In this stage a GUISquare array is being constructed, * used in the whole game as *a mean of changing a square graphical state. *@param squares is the squares array from whom the gui grid will be *constructed. *@see getSquare about the correspondance beetween a squareModel and * a GUISquare. */ private void initBoardPanel(SquareModel[][] squares){ BoardPanel.setLayout(new GridLayout(height ,width )); //set layout SquareRenderer[][] Squares; JPanel[][] grid; Squares=new GUISquare[height][width()]; grid=new JPanel[height()][width()]; for (int i=0; i<height(); i++){ for (int j=0; j<width() ; j++){ grid[i][j] = new JPanel( ); SquareRenderer kout=new SquareRenderer(i,j); koutaki.setSquare(myGame.getSquares()[i][j]); if (myGame.getSquares()[i][j] instanceof SimpleSquareModel){ kout.draw(i,j,"");} else { kout.draw(i,j); } kout.setVisible(true); kout.setBackground(Color.BLACK); kout.setSize(50,50); Squares[i][j]= kout; grid[i][j].setSize(50,50); grid[i][j].setVisible(true); grid[i][j].setBackground(Color.BLACK); BoardPanel.add(kout); BoardPanel.setVisible(true); BoardPanel.setBackground(Color.WHITE); } } this.add(BoardPanel,BorderLayout.WEST); // this.pack(); //sets appropriate size for frame this.setVisible(true); //makes frame visible } IMPLEMENTED BY SQUARERENDERER: /** * Transformer for Snake/Ladder * <br>This method is used to display a square on the screen. */ public void draw(int i,int j) { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JLabel label1 = new JLabel("Move To"+myGame.getSquares()[i][j].getGoTo()); JLabel label2 = new JLabel(""+myGame.getSquares()[i][j].getSquare()); JSeparator CellSeparator = new JSeparator(orientation); panel.add(CellSeparator); panel.setForeground(Color.ORANGE); panel.add(label2, BorderLayout.NORTH); panel.add(label1, BorderLayout.CENTER); }

    Read the article

  • Generics and Performance question.

    - by Tarmon
    Hey Everyone, I was wondering if anyone could look over a class I wrote, I am receiving generic warnings in Eclipse and I am just wondering if it could be cleaned up at all. All of the warnings I received are surrounded in ** in my code below. The class takes a list of strings in the form of (hh:mm AM/PM) and converts them into HourMinute objects in order to find the first time in the list that comes after the current time. I am also curious about if there are more efficient ways to do this. This works fine but the student in me just wants to find out how I could do this better. public class FindTime { private String[] hourMinuteStringArray; public FindTime(String[] hourMinuteStringArray){ this.hourMinuteStringArray = hourMinuteStringArray; } public int findTime(){ HourMinuteList hourMinuteList = convertHMStringArrayToHMArray(hourMinuteStringArray); Calendar calendar = new GregorianCalendar(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); HourMinute now = new HourMinute(hour,minute); int nearestTimeIndex = findNearestTimeIndex(hourMinuteList, now); return nearestTimeIndex; } private int findNearestTimeIndex(HourMinuteList hourMinuteList, HourMinute now){ HourMinute current; int position = 0; Iterator<HourMinute> iterator = **hourMinuteList.iterator()**; while(iterator.hasNext()){ current = (HourMinute) iterator.next(); if(now.compareTo(current) == -1){ return position; } position++; } return position; } private static HourMinuteList convertHMStringArrayToHMArray(String[] times){ FindTime s = new FindTime(new String[1]); HourMinuteList list = s.new HourMinuteList(); String[] splitTime = new String[3]; for(String time : times ){ String[] tempFirst = time.split(":"); String[] tempSecond = tempFirst[1].split(" "); splitTime[0] = tempFirst[0]; splitTime[1] = tempSecond[0]; splitTime[2] = tempSecond[1]; int hour = Integer.parseInt(splitTime[0]); int minute = Integer.parseInt(splitTime[1]); HourMinute hm; if(splitTime[2] == "AM"){ hm = s.new HourMinute(hour,minute); } else if((splitTime[2].equals("PM")) && (hour < 12)){ hm = s.new HourMinute(hour + 12,minute); } else{ hm = s.new HourMinute(hour,minute); } **list.add(hm);** } return list; } class **HourMinuteList** extends **ArrayList** implements RandomAccess{ } class HourMinute implements **Comparable** { int hour; int minute; public HourMinute(int hour, int minute) { setHour(hour); setMinute(minute); } int getMinute() { return this.minute; } String getMinuteString(){ if(this.minute < 10){ return "0" + this.minute; }else{ return "" + this.minute; } } int getHour() { return this.hour; } void setHour(int hour) { this.hour = hour; } void setMinute(int minute) { this.minute = minute; } @Override public int compareTo(Object aThat) { if (aThat instanceof HourMinute) { HourMinute that = (HourMinute) aThat; if (this.getHour() == that.getHour()) { if (this.getMinute() > that.getMinute()) { return 1; } else if (this.getMinute() < that.getMinute()) { return -1; } else { return 0; } } else if (this.getHour() > that.getHour()) { return 1; } else if (this.getHour() < that.getHour()) { return -1; } else { return 0; } } return 0; } } If you have any questions let me know. Thanks, Rob

    Read the article

  • JUnit testing, exception in threa main

    - by Crystal
    I am new to JUnit and am trying to follow my prof's example. I have a Person class and a PersonTest class. When I try to compile PersonTest.java, I get the following error: Exception in thread "main" java.lang.NoSuchMethodError: main I am not really sure why since I followed his example. Person.java public class Person implements Comparable { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int compareTo(Object o) { String s1 = this.lastName + this.firstName; String s2 = ((Person) o).lastName + ((Person) o).firstName; return s1.compareTo(s2); } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return this.email.toLowerCase().hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } } PersonTest.java import org.junit.Test; // JDK 5.0 annotation support import static org.junit.Assert.assertTrue; // Using JDK 5.0 static imports import static org.junit.Assert.assertFalse; // Using JDK 5.0 static imports import junit.framework.JUnit4TestAdapter; // Need this to be compatible with old test driver public class PersonTest { /** A test to verify equals method. */ @Test public void checkEquals() { Person p1 = new Person("jj", "aa", "[email protected]", "1112223333"); assertTrue(p1.equals(p1)); // first check in equals method assertFalse(p1.equals(null)); // second check in equals method assertFalse(p1.equals(new Object())); // third chk in equals method Person p2 = new Person("jj", "aa", "[email protected]", "1112223333"); assertTrue(p1.equals(p2)); // check for deep comparison p1 = new Person("jj", "aa", "[email protected]", "1112223333"); p2 = new Person("kk", "aa", "[email protected]", "1112223333"); assertFalse(p1.equals(p2)); // check for deep comkparison } }

    Read the article

  • How to make a jQuery plugin (the right way)?

    - by macek
    I know there are jQuery cookie plugins out there, but I wanted to write one for the sake of better learning the jQuery plugin pattern. I like the separation of "work" in small, manageable functions, but I feel like I'm passing name, value, and options arguments around too much. Is there a way this can be refactored? I'm looking for snippets of code to help illustrate examples provided with in answers. Any help is appreciated. Thanks :) example usage $.cookie('foo', 'bar', {expires:7}); $.cookie('foo'); //=> bar $.cookie('foo', null); $.cookie('foo'); //=> undefined Edit: I did a little bit of work on this. You can view the revision history to see where this has come from. It still feels like more refactoring can be done to optimize the flow a bit. Any ideas? the plugin (function($){ $.cookie = function(name, value, options) { if (typeof value == 'undefined') { return get(name); } else { options = $.extend({}, $.cookie.defaults, options || {}); return (value != null) ? set(name, value, options) : unset(name, options); } }; $.cookie.defaults = { expires: null, path: '/', domain: null, secure: false }; var set = function(name, value, options){ console.log(options); return document.cookie = options_string(name, value, options); }; var get = function(name){ var cookies = {}; $.map(document.cookie.split(';'), function(pair){ var c = $.trim(pair).split('='); cookies[c[0]] = c[1]; }); return decodeURIComponent(cookies[name]); }; var unset = function(name, options){ value = ''; options.expires = -1; set(name, value, options); }; var options_string = function(name, value, options){ var pairs = [param.name(name, value)]; $.each(options, function(k,v){ pairs.push(param[k](v)); }); return $.map(pairs, function(p){ return p === null ? null : p; }).join(';'); }; var param = { name: function(name, value){ return name + "=" + encodeURIComponent(value); }, expires: function(value){ // no expiry if(value === null){ return null; } // number of days else if(typeof value == "number"){ d = new Date(); d.setTime(d.getTime() + (value * 24 * 60 * 60 * 1000)); } // date object else if(typeof value == "object" && value instanceof "Date") { d = value; } return "expires=" + d.toUTCString(); }, path: function(value){ return "path="+value; }, domain: function(value){ return value === null ? null : "domain=" + value; }, secure: function(bool){ return bool ? "secure" : null; } }; })(jQuery);

    Read the article

  • How perform USort() on an Array of Objects class definition as a method?

    - by user558724
    class Contact{ public $name; public $bgcolor; public $lgcolor; public $email; public $element; public function __construct($name, $bgcolor, $lgcolor, $email, $element) { $this->name = $name; $this->bgcolor = $bgcolor; $this->lgcolor = $lgcolor; $this->email = $email; $this->element = $element; } public static function sortByName(Contact $p1, Contact $p2) { return strcmp($p1->name, $p2->name); } } class ContactList implements Iterator, ArrayAccess { protected $_label; protected $_contacts = array(); public function __construct($label) { $this->_label = $label; } public function getLabel() { return $this->_label; } public function addContact(Contact $contact) { $this->_contacts[] = $contact; } public function current() { return current($this->_contacts); } public function key() { return key($this->_contacts); } public function next() { return next($this->_contacts); } public function rewind() { return reset($this->_contacts); } public function valid() { return current($this->_contacts); } public function offsetGet($offset) { return $this->_contacts[$offset]; } public function offsetSet($offset, $data) { if (!$data instanceof Contact) throw new InvalidArgumentException('Only Contact objects allowed in a ContactList'); if ($offset == '') { $this->_contacts[] = $data; } else { $this->_contacts[$offset] = $data; } } public function offsetUnset($offset) { unset($this->_contacts[$offset]); } public function offsetExists($offset) { return isset($this->_contacts[$offset]); } public function sort($attribute = 'name') { $sortFct = 'sortBy' . ucfirst(strtolower($attribute)); if (!in_array($sortFct, get_class_methods('Contact'))) { throw new Exception('contact->sort(): Can\'t sort by ' . $attribute); } usort($this->contact, 'ContactList::' . $sortFct); } } public function Sort($property, $asc=true) { // this is where sorting logic takes place $_pd = $this->_contact->getProperty($property); if ($_pd == null) { user_error('Property '.$property.' does not exist in class '.$this->_contact->getName(), E_WARNING); return; } // set sortDescriptor ContactList::$sortProperty = $_pd; // and apply sorting usort($this->_array, array('ContactList', ($asc?'USortAsc':'USortDesc'))); } function getItems(){ return $this->_array; } class SortableItem extends ContactList { static public $sortProperty; static function USortAsc($a, $b) { /*@var $_pd ReflectionProperty*/ /* $_pd = self::$sortProperty; if ($_pd !== null) { if ($_pd->getValue($a) === $_pd->getValue($b)) return 0; else return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1); } return 0; } static function USortDesc($a, $b) { return -(self::USortAsc($a,$b)); } } This approach keeps giving me PHP Warnings: usort() [function.usort]: of all kinds which I can provide later as needed to comment out those methods and definitions in order to test and fix some minor bugs of our program. **$billy parameters are already defined. $all -> addContact($billy); // --> ended up adding each contact manually above $all->Sort('name',true); $items = $all->getItems(); foreach($items as $contact) { echo $contact->__toString(); } $all->sort(); The reason for using usort is to re-arrange the order alphabetically by name but somehow is either stating that the function comparison needs to be an array or another errors which obviously I have seemed to pass. Any help would be greatly appreciated, thanks in advance.

    Read the article

  • Using Comparable to compare objects and sorting them in a TreeMap

    - by arjacsoh
    II cannot understand how should the natural ordering of class be "consistent with equals" when implementing the Comparable interface. I deteted a flaw in my program and therefore I deteced that in the documentantion of the interface Comparable. My problem is that although two Objects are considered as distinct on the base of equals method, the TreeMap structure treats them as equal and consequently does not accept the second insert. The sample code is: public class Car implements Comparable<Car> { int weight; String name; public Car(int w, String n) { weight=w; name=n; } public boolean equals(Object o){ if(o instanceof Car){ Car d = (Car)o; return ((d.name.equals(name)) && (d.weight==weight)); } return false; } public int hashCode(){ return weight/2 + 17; } public String toString(){ return "I am " +name+ " !!!"; } public int compareTo(Car d){ if(this.weight>d.weight) return 1; else if(this.weight<d.weight) return -1; else return 0; } /*public int compareTo(Car d){ return this.name.compareTo(d.name); }*/ } public static void main(String[] args) { Car d1 = new Car(100, "a"); Car d2 = new Car(110, "b"); Car d3 = new Car(110, "c"); Car d4 = new Car(100, "a"); Map<Car, Integer> m = new HashMap<Car, Integer>(); m.put(d1, 1); m.put(d2, 2); m.put(d3, 3); m.put(d4, 16); for(Map.Entry<Car, Integer> me : m.entrySet()) System.out.println(me.getKey().toString() + " " +me.getValue()); TreeMap<Car, Integer> tm = new TreeMap<Car, Integer>(m); System.out.println("After Sorting: "); for(Map.Entry<Car, Integer> me : tm.entrySet()) System.out.println(me.getKey().toString() + " " +me.getValue()); } The output is : I am a !!! 16 I am c !!! 3 I am b !!! 2 After Sorting: I am a !!! 16 I am c !!! 2 That is, that the object c has replaced (somewhat) object b. If I comment the original equals method and uncomment the second equals method, which compares the objects according name, the output is the expected: I am a !!! 16 I am c !!! 3 I am b !!! 2 After Sorting: I am a !!! 16 I am b !!! 2 I am c !!! 3 Why does it come around in this way and what should I alter in order to insert and sort different objects with some attributes of equal value in a TreeMap?

    Read the article

  • Hibernate - strange order of native SQL parameters

    - by Xorty
    Hello, I am trying to use native MySQL's MD5 crypto func, so I defined custom insert in my mapping file. <hibernate-mapping package="tutorial"> <class name="com.xorty.mailclient.client.domain.User" table="user"> <id name="login" type="string" column="login"></id> <property name="password"> <column name="password" /> </property> <sql-insert>INSERT INTO user (login,password) VALUES ( ?, MD5(?) )</sql-insert> </class> </hibernate-mapping> Then I create User (pretty simple POJO with just 2 Strings - login and password) and try to persist it. session.beginTransaction(); // we have no such user in here yet User junitUser = (User) session.load(User.class, "junit_user"); assert (null == junitUser); // insert new user junitUser = new User(); junitUser.setLogin("junit_user"); junitUser.setPassword("junitpass"); session.save(junitUser); session.getTransaction().commit(); What actually happens? User is created, but with reversed parameters order. He has login "junitpass" and "junit_user" is MD5 encrypted and stored as password. What did I wrong? Thanks EDIT: ADDING POJO class package com.xorty.mailclient.client.domain; import java.io.Serializable; /** * POJO class representing user. * @author MisoV * @version 0.1 */ public class User implements Serializable { /** * Generated UID */ private static final long serialVersionUID = -969127095912324468L; private String login; private String password; /** * @return login */ public String getLogin() { return login; } /** * @return password */ public String getPassword() { return password; } /** * @param login the login to set */ public void setLogin(String login) { this.login = login; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @see java.lang.Object#toString() * @return login */ @Override public String toString() { return login; } /** * Creates new User. * @param login User's login. * @param password User's password. */ public User(String login, String password) { setLogin(login); setPassword(password); } /** * Default constructor */ public User() { } /** * @return hashCode * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((null == login) ? 0 : login.hashCode()); result = prime * result + ((null == password) ? 0 : password.hashCode()); return result; } /** * @param obj Compared object * @return True, if objects are same. Else false. * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof User)) { return false; } User other = (User) obj; if (login == null) { if (other.login != null) { return false; } } else if (!login.equals(other.login)) { return false; } if (password == null) { if (other.password != null) { return false; } } else if (!password.equals(other.password)) { return false; } return true; } }

    Read the article

  • Javascript and Twitter API rate limitation? (Changing variable values in a loop)

    - by Pablo
    Hello, I have adapted an script from an example of http://github.com/remy/twitterlib. It´s a script that makes one query each 10 seconds to my Twitter timeline, to get only the messages that begin with a musical notation. It´s already working, but I don´t know it is the better way to do this... The Twitter API has a rate limit of 150 IP access per hour (queries from the same user). At this time, my Twitter API is blocked at 25 minutes because the 10 seconds frecuency between posts. If I set up a frecuency of 25 seconds between post, I am below the rate limit per hour, but the first 10 posts are shown so slowly. I think this way I can guarantee to be below the Twitter API rate limit and show the first 10 posts at normal speed: For the first 10 posts, I would like to set a frecuency of 5 seconds between queries. For the rest of the posts, I would like to set a frecuency of 25 seconds between queries. I think if making somewhere in the code a loop with the previous sentences, setting the "frecuency" value from 5000 to 25000 after the 10th query (or after 50 seconds, it´s the same), that´s it... Can you help me on modify this code below to make it work? Thank you in advance. var Queue = function (delay, callback) { var q = [], timer = null, processed = {}, empty = null, ignoreRT = twitterlib.filter.format('-"RT @"'); function process() { var item = null; if (q.length) { callback(q.shift()); } else { this.stop(); setTimeout(empty, 5000); } return this; } return { push: function (item) { var green = [], i; if (!(item instanceof Array)) { item = [item]; } if (timer == null && q.length == 0) { this.start(); } for (i = 0; i < item.length; i++) { if (!processed[item[i].id] && twitterlib.filter.match(item[i], ignoreRT)) { processed[item[i].id] = true; q.push(item[i]); } } q = q.sort(function (a, b) { return a.id > b.id; }); return this; }, start: function () { if (timer == null) { timer = setInterval(process, delay); } return this; }, stop: function () { clearInterval(timer); timer = null; return this; }, empty: function (fn) { empty = fn; return this; }, q: q, next: process }; }; $.extend($.expr[':'], { below: function (a, i, m) { var y = m[3]; return $(a).offset().top y; } }); function renderTweet(data) { var html = ''; html += ''; html += twitterlib.ify.clean(data.text); html += ''; since_id = data.id; return html; } function passToQueue(data) { if (data.length) { twitterQueue.push(data.reverse()); } } var frecuency = 10000; // The lapse between each new Queue var since_id = 1; var run = function () { twitterlib .timeline('twitteruser', { filter : "'?'", limit: 10 }, passToQueue) }; var twitterQueue = new Queue(frecuency, function (item) { var tweet = $(renderTweet(item)); var tweetClone = tweet.clone().hide().css({ visibility: 'hidden' }).prependTo('#tweets').slideDown(1000); tweet.css({ top: -200, position: 'absolute' }).prependTo('#tweets').animate({ top: 0 }, 1000, function () { tweetClone.css({ visibility: 'visible' }); $(this).remove(); }); $('#tweets p:below(' + window.innerHeight + ')').remove(); }).empty(run); run();

    Read the article

  • Using Dynamic Proxies to centralize JPA code

    - by Daziplqa
    Hi All, Actually, This is not a question but really I need your opinions in a matter... I put his post here because I know you always active, so please don't consider this a bad question and share me your opinions. I've used Java dynamic proxies to Centralize The code of JPA that I used in a standalone mode, and Here's the dynamic proxy code: package com.forat.service; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.forat.service.exceptions.DAOException; /** * Example of usage : * <pre> * OnlineFromService onfromService = * (OnlineFromService) DAOProxy.newInstance(new OnlineFormServiceImpl()); * try { * Student s = new Student(); * s.setName("Mohammed"); * s.setNationalNumber("123456"); * onfromService.addStudent(s); * }catch (Exception ex) { * System.out.println(ex.getMessage()); * } *</pre> * @author mohammed hewedy * */ public class DAOProxy implements InvocationHandler{ private Object object; private Logger logger = Logger.getLogger(this.getClass().getSimpleName()); private DAOProxy(Object object) { this.object = object; } public static Object newInstance(Object object) { return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new DAOProxy(object)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { EntityManagerFactory emf = null; EntityManager em = null; EntityTransaction et = null; Object result = null; try { emf = Persistence.createEntityManagerFactory(Constants.UNIT_NAME); em = emf.createEntityManager();; Method entityManagerSetter = object.getClass(). getDeclaredMethod(Constants.ENTITY_MANAGER_SETTER_METHOD, EntityManager.class); entityManagerSetter.invoke(object, em); et = em.getTransaction(); et.begin(); result = method.invoke(object, args); et.commit(); return result; }catch (Exception ex) { et.rollback(); Throwable cause = ex.getCause(); logger.log(Level.SEVERE, cause.getMessage()); if (cause instanceof DAOException) throw new DAOException(cause.getMessage(), cause); else throw new RuntimeException(cause.getMessage(), cause); }finally { em.close(); emf.close(); } } } And here's the link that contains more info (http://m-hewedy.blogspot.com/2010/04/using-dynamic-proxies-to-centralize-jpa.html) (plz don't consider this as adds, as I can copy and past the entire topic here if you want that) So, Please give me your opinions. Thanks.

    Read the article

  • If I use a facade class with generic methods to access the JPA API, how should I provide additional processing for specific types?

    - by Shaun
    Let's say I'm making a fairly simple web application using JAVA EE specs (I've heard this is possible). In this app, I only have about 10 domain/data objects, and these are represented by JPA Entities. Architecturally, I would consider the JPA API to perform the role of a DAO. Of course, I don't want to use the EntityManager directly in my UI (JSF) and I need to manage transactions, so I delegate these tasks to the so-called service layer. More specifically, I would like to be able to handle these tasks in a single DataService class (often also called CrudService) with generic methods. See this article by Adam Bien for an example interface: http://www.adam-bien.com/roller/abien/entry/generic_crud_service_aka_dao My project differs from that article in that I can't use EJBs, so my service classes are essentially just named beans and I handle transactions manually. Regardless, what I want is a single interface for simple CRUD operations on my data objects because having a different class for each data type would lead to a lot of duplicate and/or unnecessary code. Ideally, my views would be able to use a method such as public <T> List<T> findAll(Class<T> type) { ... } to retrieve data. Using JSF, it might look something like this: <h:dataTable value="#{dataService.findAll(data.class)}" var="d"> ... </h:dataTable> Similarly, after validating forms, my controller could submit the data with a method such as: public <T> void add(T entity) { ... } Granted, you'd probably actually want to return something useful to the caller. In any case, this works well if your data can be treated as homogenous in this manner. Alas, it breaks down when you need to perform additional processing on certain objects before passing them on to JPA. For example, let's say I'm dealing with Books and Authors which have a many-to-many relationship. Each Book has a set of IDs referring to its authors, and each Author has a set of IDs referring to their books. Normally, JPA can manage this kind of relationship for you, but in some cases it can't (for example, the google app engine JPA provider doesn't support this). Thus, when I persist a new book for example, I may need to update the corresponding author entities. My question, then, is if there's an elegant way to handle this or if I should reconsider the sanity of my whole design. Here's a couple ways I see of dealing with it: The instanceof operator. I could use this to target certain classes when special processing is needed. Perhaps maintainability suffers and it isn't beautiful code, but if there's only 10 or so domain objects it can't be all that bad... could it? Make a different service for each entity type (ie, BookService and AuthorService). All services would inherit from a generic DataService base class and override methods if special processing is needed. At this point, you could probably also just call them DAOs instead. As always, I appreciate the help. Let me know if any clarifications are needed, as I left out many smaller details.

    Read the article

  • JMS Step 3 - Using the QueueReceive.java Sample Program to Read a Message from a JMS Queue

    - by John-Brown.Evans
    JMS Step 3 - Using the QueueReceive.java Sample Program to Read a Message from a JMS Queue ol{margin:0;padding:0} .c18_3{vertical-align:top;width:487.3pt;border-style:solid;background-color:#f3f3f3;border-color:#000000;border-width:1pt;padding:0pt 5pt 0pt 5pt} .c20_3{vertical-align:top;width:487.3pt;border-style:solid;border-color:#ffffff;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c19_3{background-color:#ffffff} .c17_3{list-style-type:circle;margin:0;padding:0} .c12_3{list-style-type:disc;margin:0;padding:0} .c6_3{font-style:italic;font-weight:bold} .c10_3{color:inherit;text-decoration:inherit} .c1_3{font-size:10pt;font-family:"Courier New"} .c2_3{line-height:1.0;direction:ltr} .c9_3{padding-left:0pt;margin-left:72pt} .c15_3{padding-left:0pt;margin-left:36pt} .c3_3{color:#1155cc;text-decoration:underline} .c5_3{height:11pt} .c14_3{border-collapse:collapse} .c7_3{font-family:"Courier New"} .c0_3{background-color:#ffff00} .c16_3{font-size:18pt} .c8_3{font-weight:bold} .c11_3{font-size:24pt} .c13_3{font-style:italic} .c4_3{direction:ltr} .title{padding-top:24pt;line-height:1.15;text-align:left;color:#000000;font-size:36pt;font-family:"Arial";font-weight:bold;padding-bottom:6pt}.subtitle{padding-top:18pt;line-height:1.15;text-align:left;color:#666666;font-style:italic;font-size:24pt;font-family:"Georgia";padding-bottom:4pt} li{color:#000000;font-size:10pt;font-family:"Arial"} p{color:#000000;font-size:10pt;margin:0;font-family:"Arial"} h1{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:24pt;font-family:"Arial";font-weight:normal} h2{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:18pt;font-family:"Arial";font-weight:normal} h3{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:14pt;font-family:"Arial";font-weight:normal} h4{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:12pt;font-family:"Arial";font-weight:normal} h5{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:11pt;font-family:"Arial";font-weight:normal} h6{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:10pt;font-family:"Arial";font-weight:normal} This post continues the series of JMS articles which demonstrate how to use JMS queues in a SOA context. In the first post, JMS Step 1 - How to Create a Simple JMS Queue in Weblogic Server 11g we looked at how to create a JMS queue and its dependent objects in WebLogic Server. In the previous post, JMS Step 2 - Using the QueueSend.java Sample Program to Send a Message to a JMS Queue I showed how to write a message to that JMS queue using the QueueSend.java sample program. In this article, we will use a similar sample, the QueueReceive.java program to read the message from that queue. Please review the previous posts if you have not already done so, as they contain prerequisites for executing the sample in this article. 1. Source code The following java code will be used to read the message(s) from the JMS queue. As with the previous example, it is based on a sample program shipped with the WebLogic Server installation. The sample is not installed by default, but needs to be installed manually using the WebLogic Server Custom Installation option, together with many, other useful samples. You can either copy-paste the following code into your editor, or install all the samples. The knowledge base article in My Oracle Support: How To Install WebLogic Server and JMS Samples in WLS 10.3.x (Doc ID 1499719.1) describes how to install the samples. QueueReceive.java package examples.jms.queue; import java.util.Hashtable; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * This example shows how to establish a connection to * and receive messages from a JMS queue. The classes in this * package operate on the same JMS queue. Run the classes together to * witness messages being sent and received, and to browse the queue * for messages. This class is used to receive and remove messages * from the queue. * * @author Copyright (c) 1999-2005 by BEA Systems, Inc. All Rights Reserved. */ public class QueueReceive implements MessageListener { // Defines the JNDI context factory. public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory"; // Defines the JMS connection factory for the queue. public final static String JMS_FACTORY="jms/TestConnectionFactory"; // Defines the queue. public final static String QUEUE="jms/TestJMSQueue"; private QueueConnectionFactory qconFactory; private QueueConnection qcon; private QueueSession qsession; private QueueReceiver qreceiver; private Queue queue; private boolean quit = false; /** * Message listener interface. * @param msg message */ public void onMessage(Message msg) { try { String msgText; if (msg instanceof TextMessage) { msgText = ((TextMessage)msg).getText(); } else { msgText = msg.toString(); } System.out.println("Message Received: "+ msgText ); if (msgText.equalsIgnoreCase("quit")) { synchronized(this) { quit = true; this.notifyAll(); // Notify main thread to quit } } } catch (JMSException jmse) { System.err.println("An exception occurred: "+jmse.getMessage()); } } /** * Creates all the necessary objects for receiving * messages from a JMS queue. * * @param ctx JNDI initial context * @param queueName name of queue * @exception NamingException if operation cannot be performed * @exception JMSException if JMS fails to initialize due to internal error */ public void init(Context ctx, String queueName) throws NamingException, JMSException { qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qcon = qconFactory.createQueueConnection(); qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (Queue) ctx.lookup(queueName); qreceiver = qsession.createReceiver(queue); qreceiver.setMessageListener(this); qcon.start(); } /** * Closes JMS objects. * @exception JMSException if JMS fails to close objects due to internal error */ public void close()throws JMSException { qreceiver.close(); qsession.close(); qcon.close(); } /** * main() method. * * @param args WebLogic Server URL * @exception Exception if execution fails */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: java examples.jms.queue.QueueReceive WebLogicURL"); return; } InitialContext ic = getInitialContext(args[0]); QueueReceive qr = new QueueReceive(); qr.init(ic, QUEUE); System.out.println( "JMS Ready To Receive Messages (To quit, send a \"quit\" message)."); // Wait until a "quit" message has been received. synchronized(qr) { while (! qr.quit) { try { qr.wait(); } catch (InterruptedException ie) {} } } qr.close(); } private static InitialContext getInitialContext(String url) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); env.put(Context.PROVIDER_URL, url); return new InitialContext(env); } } 2. How to Use This Class 2.1 From the file system on Linux This section describes how to use the class from the file system of a WebLogic Server installation. Log in to a machine with a WebLogic Server installation and create a directory to contain the source and code matching the package name, e.g. span$HOME/examples/jms/queue. Copy the above QueueReceive.java file to this directory. Set the CLASSPATH and environment to match the WebLogic server environment. Go to $MIDDLEWARE_HOME/user_projects/domains/base_domain/bin  and execute . ./setDomainEnv.sh Collect the following information required to run the script: The JNDI name of the JMS queue to use In the WebLogic server console > Services > Messaging > JMS Modules > Module name, (e.g. TestJMSModule) > JMS queue name, (e.g. TestJMSQueue) select the queue and note its JNDI name, e.g. jms/TestJMSQueue The JNDI name of the connection factory to use to connect to the queue Follow the same path as above to get the connection factory for the above queue, e.g. TestConnectionFactory and its JNDI name e.g. jms/TestConnectionFactory The URL and port of the WebLogic server running the above queue Check the JMS server for the above queue and the managed server it is targeted to, for example soa_server1. Now find the port this managed server is listening on, by looking at its entry under Environment > Servers in the WLS console, e.g. 8001 The URL for the server to be passed to the QueueReceive program will therefore be t3://host.domain:8001 e.g. t3://jbevans-lx.de.oracle.com:8001 Edit Queue Receive .java and enter the above queue name and connection factory respectively under ... public final static String JMS_FACTORY="jms/TestConnectionFactory"; ... public final static String QUEUE="jms/TestJMSQueue"; ... Compile Queue Receive .java using javac Queue Receive .java Go to the source’s top-level directory and execute it using java examples.jms.queue.Queue Receive   t3://jbevans-lx.de.oracle.com:8001 This will print a message that it is ready to receive messages or to send a “quit” message to end. The program will read all messages in the queue and print them to the standard output until it receives a message with the payload “quit”. 2.2 From JDeveloper The steps from JDeveloper are the same as those used for the previous program QueueSend.java, which is used to send a message to the queue. So we won't repeat them here. Please see the previous blog post at JMS Step 2 - Using the QueueSend.java Sample Program to Send a Message to a JMS Queue and apply the same steps in that example to the QueueReceive.java program. This concludes the example. In the following post we will create a BPEL process which writes a message based on an XML schema to the queue.

    Read the article

  • Rotating a NetBeans Visual Library Widget

    - by Geertjan
    Trying to create a widget which, when clicked, rotates slightly further on each subsequent click: Above, the bird where the mouse is visible has been clicked a few times and so has rotated a bit further on each click. The code isn't quite right yet and I'm hoping someone will take this code, try it out, and help with a nice solution! public class BirdScene extends Scene {     public BirdScene() {         addChild(new LayerWidget(this));         getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() {             public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) {                 Image dragImage = getImageFromTransferable(transferable);                 if (dragImage != null) {                     JComponent view = getView();                     Graphics2D g2 = (Graphics2D) view.getGraphics();                     Rectangle visRect = view.getVisibleRect();                     view.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);                     g2.drawImage(dragImage,                             AffineTransform.getTranslateInstance(point.getLocation().getX(),                             point.getLocation().getY()),                             null);                     return ConnectorState.ACCEPT;                 } else {                     return ConnectorState.REJECT;                 }             }             public void accept(Widget widget, final Point point, Transferable transferable) {                 addChild(new BirdWidget(getScene(), getImageFromTransferable(transferable), point));             }         }));     }     private Image getImageFromTransferable(Transferable transferable) {         Object o = null;         try {             o = transferable.getTransferData(DataFlavor.imageFlavor);         } catch (IOException ex) {         } catch (UnsupportedFlavorException ex) {         }         return o instanceof Image ? (Image) o : null;     }     private class BirdWidget extends IconNodeWidget {         private int theta = 0;         public BirdWidget(Scene scene, Image imageFromTransferable, Point point) {             super(scene);             setImage(imageFromTransferable);             setPreferredLocation(point);             setCheckClipping(true);             getActions().addAction(ActionFactory.createMoveAction());             getActions().addAction(ActionFactory.createSelectAction(new SelectProvider() {                 public boolean isAimingAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public boolean isSelectionAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public void select(final Widget widget, Point localLocation, boolean invertSelection) {                     theta = (theta + 100) % 360;                     repaint();                     getScene().validate();                 }             }));         }         @Override         public void paintWidget() {             final Image image = getImageWidget().getImage();             Graphics2D g = getGraphics();             g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             Rectangle bounds = getClientArea();             AffineTransform newXform = g.getTransform();             int xRot = image.getWidth(null) / 2;             int yRot = image.getWidth(null) / 2;             newXform.rotate(theta * Math.PI / 180, xRot, yRot);             g.setTransform(newXform);             g.drawImage(image, bounds.x, bounds.y, null);         }     } } The problem relates to refreshing the scene after the rotation. But it would help if someone would just take the code above, add it to their own application, try it out, see the problem for yourself, and develop it a bit further!

    Read the article

  • Java Program help [migrated]

    - by georgetheevilman
    Okay I have a really annoying error. Its coming from my retainAll method. The problem is that I am outputting 1,3,5 in ints at the end, but I need 1,3,5,7,9. Here is the code below for the MySet and driver classes public class MySetTester { public static void main(String[]args) { MySet<String> strings = new MySet<String>(); strings.add("Hey!"); strings.add("Hey!"); strings.add("Hey!"); strings.add("Hey!"); strings.add("Hey!"); strings.add("Listen!"); strings.add("Listen!"); strings.add("Sorry, I couldn't resist."); strings.add("Sorry, I couldn't resist."); strings.add("(you know you would if you could)"); System.out.println("Testing add:\n"); System.out.println("Your size: " + strings.size() + ", contains(Sorry): " + strings.contains("Sorry, I couldn't resist.")); System.out.println("Exp. size: 4, contains(Sorry): true\n"); MySet<String> moreStrings = new MySet<String>(); moreStrings.add("Sorry, I couldn't resist."); moreStrings.add("(you know you would if you could)"); strings.removeAll(moreStrings); System.out.println("Testing remove and removeAll:\n"); System.out.println("Your size: " + strings.size() + ", contains(Sorry): " + strings.contains("Sorry, I couldn't resist.")); System.out.println("Exp. size: 2, contains(Sorry): false\n"); MySet<Integer> ints = new MySet<Integer>(); for (int i = 0; i < 100; i++) { ints.add(i); } System.out.println("Your size: " + ints.size()); System.out.println("Exp. size: 100\n"); for (int i = 0; i < 100; i += 2) { ints.remove(i); } System.out.println("Your size: " + ints.size()); System.out.println("Exp. size: 50\n"); MySet<Integer> zeroThroughNine = new MySet<Integer>(); for (int i = 0; i < 10; i++) { zeroThroughNine.add(i); } ints.retainAll(zeroThroughNine); System.out.println("ints should now only retain odd numbers" + " 0 through 10\n"); System.out.println("Testing your iterator:\n"); for (Integer i : ints) { System.out.println(i); } System.out.println("\nExpected: \n\n1 \n3 \n5 \n7 \n9\n"); System.out.println("Yours:"); for (String s : strings) { System.out.println(s); } System.out.println("\nExpected: \nHey! \nListen!"); strings.clear(); System.out.println("\nClearing your set...\n"); System.out.println("Your set is empty: " + strings.isEmpty()); System.out.println("Exp. set is empty: true"); } } And here is the main code. But still read the top part because that's where my examples are. import java.util.Set; import java.util.Collection; import java.lang.Iterable; import java.util.Iterator; import java.util.Arrays; import java.lang.reflect.Array; public class MySet implements Set, Iterable { // instance variables - replace the example below with your own private E[] backingArray; private int numElements; /** * Constructor for objects of class MySet */ public MySet() { backingArray=(E[]) new Object[5]; numElements=0; } public boolean add(E e){ for(Object elem:backingArray){ if (elem==null ? e==null : elem.equals(e)){ return false; } } if(numElements==backingArray.length){ E[] newArray=Arrays.copyOf(backingArray,backingArray.length*2); newArray[numElements]=e; numElements=numElements+1; backingArray=newArray; return true; } else{ backingArray[numElements]=e; numElements=numElements+1; return true; } } public boolean addAll(Collection<? extends E> c){ for(E elem:c){ this.add(elem); } return true; } public void clear(){ E[] newArray=(E[])new Object[backingArray.length]; numElements=0; backingArray=newArray; } public boolean equals(Object o){ if(o instanceof Set &&(((Set)o).size()==numElements)){ for(E elem:(Set<E>)o){ if (this.contains(o)==false){ return false; } return true; } } return false; } public boolean contains(Object o){ for(E backingElem:backingArray){ if (o!=null && o.equals(backingElem)){ return true; } } return false; } public boolean containsAll(Collection<?> c){ for(E elem:(Set<E>)c){ if(!(this.contains(elem))){ return false; } } return true; } public int hashCode(){ int sum=0; for(E elem:backingArray){ if(elem!=null){ sum=sum+elem.hashCode(); } } return sum; } public boolean isEmpty(){ if(numElements==0){ return true; } else{ return false; } } public boolean remove(Object o){ int i=0; for(Object elem:backingArray){ if(o!=null && o.equals(elem)){ backingArray[i]=null; numElements=numElements-1; E[] newArray=Arrays.copyOf(backingArray,backingArray.length-1); return true; } i=i+1; } return false; } public boolean removeAll(Collection<?> c){ for(Object elem:c){ this.remove(elem); } return true; } public boolean retainAll(Collection<?> c){ MySet<E> removalArray=new MySet<E>(); for(E arrayElem:backingArray){ if(arrayElem!= null && !(c.contains(arrayElem))){ this.remove(arrayElem); } } return false; } public int size(){ return numElements; } public <T> T[] toArray(T[] a) throws ArrayStoreException,NullPointerException{ for(int i=0;i<numElements;i++){ a[i]=(T)backingArray[i]; } for(int j=numElements;j<a.length;j++){ a[j]=null; } return a; } public Object[] toArray(){ Object[] newArray=new Object[numElements]; for(int i=0;i<numElements;i++){ newArray[i]=backingArray[i]; } return newArray; } public Iterator<E> iterator(){ setIterator iterator=new setIterator(); return iterator; } private class setIterator implements Iterator<E>{ private int currIndex; private E lastElement; public setIterator(){ currIndex=0; lastElement=null; } public boolean hasNext(){ while(currIndex<=numElements && backingArray[currIndex]==null){ currIndex=currIndex+1; } if (currIndex<=numElements){ return true; } return false; } public E next(){ E element=backingArray[currIndex]; currIndex=currIndex+1; lastElement=element; return element; } public void remove() throws UnsupportedOperationException,IllegalStateException{ if(lastElement!=null){ MySet.this.remove((Object)lastElement); numElements=numElements-1; } else{ throw new IllegalStateException(); } } } } I've been able to reduce the problems, but otherwise this thing is still causing problems.

    Read the article

  • Using Oracle Proxy Authentication with JPA (eclipselink-Style)

    - by olaf.heimburger
    Security is a very intriguing topic. You will find it everywhere and you need to implement it everywhere. Yes, you need. Unfortunately, one can easily forget it while implementing the last mile. The Last Mile In a multi-tier application it is a common practice to use connection pools between the business layer and the database layer. Connection pools are quite useful to speed database connection creation and to split the load. Another very common practice is to use a specific, often called technical, user to connect to the database. This user has authentication and authorization rules that apply to all application users. Imagine you've put every effort to define roles for different types of users that use your application. These roles are necessary to differentiate between normal users, premium users, and administrators (I bet you will find or already have more roles in your application). While these user roles are pretty well used within your application, once the flow of execution enters the database everything is gone. Each and every user just has one role and is the same database user. Issues? What Issues? As long as things go well, this is not a real issue. However, things do not go well all the time. Once your application becomes famous performance decreases in certain situations or, more importantly, current and upcoming regulations and laws require that your application must be able to apply different security measures on a per user role basis at every stage of your application. If you only have a bunch of users with the same name and role you are not able to find the application usage profile that causes the performance issue, or which user has accessed data that he/she is not allowed to. Another thread to your role concept is that databases tend to be used by different applications and tools. These tools can be developer tools like SQL*Plus, SQL Developer, etc. or end user applications like BI Publisher, Oracle Forms and so on. These tools have no idea of your applications role concept and access the database the way they think is appropriate. A big oversight for your perfect role model and a big nightmare for your Chief Security Officer. Speaking of the CSO, brings up another issue: Password management. Once your technical user account is compromised, every user is able to do things that he/she is not expected to do from the design of your application. Counter Measures In the Oracle world a common counter measure is to use Virtual Private Database (VPD). This restricts the values a database user can see to the allowed minimum. However, it doesn't help in regard of a connection pool user, because this one is still not the real user. Oracle Proxy Authentication Another feature of the Oracle database is Proxy Authentication. First introduced with version 9i it is a quite useful feature for nearly every situation. The main idea behind Proxy Authentication is, to create a crippled database user who has only connect rights. Even if this user is compromised the risks are well understood and fairly limited. This user can be used in every situation in which you need to connect to the database, no matter which tool or application (see above) you use.The proxy user is perfect for multi-tier connection pools. CREATE USER app_user IDENTIFIED BY abcd1234; GRANT CREATE SESSION TO app_user; But what if you need to access real data? Well, this is the primary use case, isn't it? Now is the time to bring the application's role concept into play. You define database roles that define the grants for your identified user groups. Once you have these groups you grant access through the proxy user with the application role to the specific user. CREATE ROLE app_role_a; GRANT app_role_a TO scott; ALTER USER scott GRANT CONNECT THROUGH app_user WITH ROLE app_role_a; Now, hr has permission to connect to the database through the proxy user. Through the role you can restrict the hr's rights the are needed for the application only. If hr connects to the database directly all assigned role and permissions apply. Testing the Setup To test the setup you can use SQL*Plus and connect to your database: $ sqlplus app_user[hr]/abcd1234 Java Persistence API The Java Persistence API (JPA) is a fairly easy means to build applications that retrieve data from the database and put it into Java objects. You use plain old Java objects (POJOs) and mixin some Java annotations that define how the attributes of the object are used for storing data from the database into the Java object. Here is a sample for objects from the HR sample schema EMPLOYEES table. When using Java annotations you only specify what can not be deduced from the code. If your Java class name is Employee but the table name is EMPLOYEES, you need to specify the table name, otherwise it will fail. package demo.proxy.ejb; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @NamedQueries({ @NamedQuery(name = "Employee.findAll", query = "select o from Employee o") }) @Table(name = "EMPLOYEES") public class Employee implements Serializable { @Column(name="COMMISSION_PCT") private Double commissionPct; @Column(name="DEPARTMENT_ID") private Long departmentId; @Column(nullable = false, unique = true, length = 25) private String email; @Id @Column(name="EMPLOYEE_ID", nullable = false) private Long employeeId; @Column(name="FIRST_NAME", length = 20) private String firstName; @Column(name="HIRE_DATE", nullable = false) private Timestamp hireDate; @Column(name="JOB_ID", nullable = false, length = 10) private String jobId; @Column(name="LAST_NAME", nullable = false, length = 25) private String lastName; @Column(name="PHONE_NUMBER", length = 20) private String phoneNumber; private Double salary; @ManyToOne @JoinColumn(name = "MANAGER_ID") private Employee employee; @OneToMany(mappedBy = "employee") private List employeeList; public Employee() { } public Employee(Double commissionPct, Long departmentId, String email, Long employeeId, String firstName, Timestamp hireDate, String jobId, String lastName, Employee employee, String phoneNumber, Double salary) { this.commissionPct = commissionPct; this.departmentId = departmentId; this.email = email; this.employeeId = employeeId; this.firstName = firstName; this.hireDate = hireDate; this.jobId = jobId; this.lastName = lastName; this.employee = employee; this.phoneNumber = phoneNumber; this.salary = salary; } public Double getCommissionPct() { return commissionPct; } public void setCommissionPct(Double commissionPct) { this.commissionPct = commissionPct; } public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Timestamp getHireDate() { return hireDate; } public void setHireDate(Timestamp hireDate) { this.hireDate = hireDate; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public List getEmployeeList() { return employeeList; } public void setEmployeeList(List employeeList) { this.employeeList = employeeList; } public Employee addEmployee(Employee employee) { getEmployeeList().add(employee); employee.setEmployee(this); return employee; } public Employee removeEmployee(Employee employee) { getEmployeeList().remove(employee); employee.setEmployee(null); return employee; } } JPA could be used in standalone applications and Java EE containers. In both worlds you normally create a Facade to retrieve or store the values of the Entities to or from the database. The Facade does this via an EntityManager which will be injected by the Java EE container. Here is sample Facade Session Bean for a Java EE container. package demo.proxy.ejb; import java.util.HashMap; import java.util.List; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; import oracle.jdbc.driver.OracleConnection; import org.eclipse.persistence.config.EntityManagerProperties; import org.eclipse.persistence.internal.jpa.EntityManagerImpl; @Stateless(name = "DataFacade", mappedName = "ProxyUser-TestEJB-DataFacade") @Remote @Local public class DataFacadeBean implements DataFacade, DataFacadeLocal { @PersistenceContext(unitName = "TestEJB") private EntityManager em; private String username; public Object queryByRange(String jpqlStmt, int firstResult, int maxResults) { // setSessionUser(); Query query = em.createQuery(jpqlStmt); if (firstResult 0) { query = query.setFirstResult(firstResult); } if (maxResults 0) { query = query.setMaxResults(maxResults); } return query.getResultList(); } public Employee persistEmployee(Employee employee) { // setSessionUser(); em.persist(employee); return employee; } public Employee mergeEmployee(Employee employee) { // setSessionUser(); return em.merge(employee); } public void removeEmployee(Employee employee) { // setSessionUser(); employee = em.find(Employee.class, employee.getEmployeeId()); em.remove(employee); } /** select o from Employee o */ public List getEmployeeFindAll() { Query q = em.createNamedQuery("Employee.findAll"); return q.getResultList(); } Putting Both Together To use Proxy Authentication with JPA and within a Java EE container you have to take care of the additional requirements: Use an OCI JDBC driver Provide the user name that connects through the proxy user Use an OCI JDBC driver To use the OCI JDBC driver you need to set up your JDBC data source file to use the correct JDBC URL. hr jdbc:oracle:oci8:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE))) oracle.jdbc.OracleDriver user app_user 62C32F70E98297522AD97E15439FAC0E SQL SELECT 1 FROM DUAL jdbc/hrDS Application Additionally you need to make sure that the version of the shared libraries of the OCI driver match the version of the JDBC driver in your Java EE container or Java application and are within your PATH (on Windows) or LD_LIBRARY_PATH (on most Unix-based systems). Installing the Oracle Database Instance Client software works perfectly. Provide the user name that connects through the proxy user This part needs some modification of your application software and session facade. Session Facade Changes In the Session Facade we must ensure that every call that goes through the EntityManager must be prepared correctly and uniquely assigned to this session. The second is really important, as the EntityManager works with a connection pool and can not guarantee that we set the proxy user on the connection that will be used for the database activities. To avoid changing every method call of the Session Facade we provide a method to set the username of the user that connects through the proxy user. This method needs to be called by the Facade client bfore doing anything else. public void setUsername(String name) { username = name; } Next we provide a means to instruct the TopLink EntityManager Delegate to use Oracle Proxy Authentication. (I love small helper methods to hide the nitty-gritty details and avoid repeating myself.) private void setSessionUser() { setSessionUser(username); } private void setSessionUser(String user) { if (user != null && !user.isEmpty()) { EntityManagerImpl emDelegate = ((EntityManagerImpl)em.getDelegate()); emDelegate.setProperty(EntityManagerProperties.ORACLE_PROXY_TYPE, OracleConnection.PROXYTYPE_USER_NAME); emDelegate.setProperty(OracleConnection.PROXY_USER_NAME, user); emDelegate.setProperty(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, "Always"); } } The final step is use the EJB 3.0 AroundInvoke interceptor. This interceptor will be called around every method invocation. We therefore check whether the Facade methods will be called or not. If so, we set the user for proxy authentication and the normal method flow continues. @AroundInvoke public Object proxyInterceptor(InvocationContext invocationCtx) throws Exception { if (invocationCtx.getTarget() instanceof DataFacadeBean) { setSessionUser(); } return invocationCtx.proceed(); } Benefits Using Oracle Proxy Authentification has a number of additional benefits appart from implementing the role model of your application: Fine grained access control for temporary users of the account, without compromising the original password. Enabling database auditing and logging. Better identification of performance bottlenecks. References Effective Oracle Database 10g Security by Design, David Knox TopLink Developer's Guide, Chapter 98

    Read the article

  • Remove box2d bodies after collision deduction android?

    - by jubin
    Can any one explain me how to destroy box2d body when collide i have tried but my application crashed.First i have checked al collisions then add all the bodies in array who i want to destroy.I am trying to learning this tutorial My all the bodies are falling i want these bodies should destroy when these bodies will collide my actor monkey but when it collide it destroy but my aplication crashed.I have googled and from google i got the application crash reasons we should not destroy body in step funtion but i am removing body in the last of tick method. could any one help me or provide me code aur check my code why i am getting this prblem or how can i destroy box2d bodies. This is my code what i am doing. Please could any one check my code and tell me what is i am doing wrong for removing bodies. The code is for multiple box2d objects falling on my actor monkey it should be destroy when it will fall on the monkey.It is destroing but my application crahes. static class Box2DLayer extends CCLayer { protected static final float PTM_RATIO = 32.0f; protected static final float WALK_FACTOR = 3.0f; protected static final float MAX_WALK_IMPULSE = 0.2f; protected static final float ANIM_SPEED = 0.3f; int isLeft=0; String dir=""; int x =0; float direction; CCColorLayer objectHint; // protected static final float PTM_RATIO = 32.0f; protected World _world; protected static Body spriteBody; CGSize winSize = CCDirector.sharedDirector().winSize(); private static int count = 200; protected static Body monkey_body; private static Body bodies; CCSprite monkey; float animDelay; int animPhase; CCSpriteSheet danceSheet = CCSpriteSheet.spriteSheet("phases.png"); CCSprite _block; List<Body> toDestroy = new ArrayList<Body>(); //CCSpriteSheet _spriteSheet; private static MyContactListener _contactListener = new MyContactListener(); public Box2DLayer() { this.setIsAccelerometerEnabled(true); CCSprite bg = CCSprite.sprite("jungle.png"); addChild(bg,0); bg.setAnchorPoint(0,0); bg.setPosition(0,0); CGSize s = CCDirector.sharedDirector().winSize(); // Use scaled width and height so that our boundaries always match the current screen float scaledWidth = s.width/PTM_RATIO; float scaledHeight = s.height/PTM_RATIO; Vector2 gravity = new Vector2(0.0f, -30.0f); boolean doSleep = false; _world = new World(gravity, doSleep); // Create edges around the entire screen // Define the ground body. BodyDef bxGroundBodyDef = new BodyDef(); bxGroundBodyDef.position.set(0.0f, 0.0f); // The body is also added to the world. Body groundBody = _world.createBody(bxGroundBodyDef); // Register our contact listener // Define the ground box shape. PolygonShape groundBox = new PolygonShape(); Vector2 bottomLeft = new Vector2(0f,0f); Vector2 topLeft = new Vector2(0f,scaledHeight); Vector2 topRight = new Vector2(scaledWidth,scaledHeight); Vector2 bottomRight = new Vector2(scaledWidth,0f); // bottom groundBox.setAsEdge(bottomLeft, bottomRight); groundBody.createFixture(groundBox,0); // top groundBox.setAsEdge(topLeft, topRight); groundBody.createFixture(groundBox,0); // left groundBox.setAsEdge(topLeft, bottomLeft); groundBody.createFixture(groundBox,0); // right groundBox.setAsEdge(topRight, bottomRight); groundBody.createFixture(groundBox,0); CCSprite floorbg = CCSprite.sprite("grassbehind.png"); addChild(floorbg,1); floorbg.setAnchorPoint(0,0); floorbg.setPosition(0,0); CCSprite floorfront = CCSprite.sprite("grassfront.png"); floorfront.setTag(2); this.addBoxBodyForSprite(floorfront); addChild(floorfront,3); floorfront.setAnchorPoint(0,0); floorfront.setPosition(0,0); addChild(danceSheet); //CCSprite monkey = CCSprite.sprite(danceSheet, CGRect.make(0, 0, 48, 73)); //addChild(danceSprite); monkey = CCSprite.sprite("arms_up.png"); monkey.setTag(2); monkey.setPosition(200,100); BodyDef spriteBodyDef = new BodyDef(); spriteBodyDef.type = BodyType.DynamicBody; spriteBodyDef.bullet=true; spriteBodyDef.position.set(200 / PTM_RATIO, 300 / PTM_RATIO); monkey_body = _world.createBody(spriteBodyDef); monkey_body.setUserData(monkey); PolygonShape spriteShape = new PolygonShape(); spriteShape.setAsBox(monkey.getContentSize().width/PTM_RATIO/2, monkey.getContentSize().height/PTM_RATIO/2); FixtureDef spriteShapeDef = new FixtureDef(); spriteShapeDef.shape = spriteShape; spriteShapeDef.density = 2.0f; spriteShapeDef.friction = 0.70f; spriteShapeDef.restitution = 0.0f; monkey_body.createFixture(spriteShapeDef); //Vector2 force = new Vector2(10, 10); //monkey_body.applyLinearImpulse(force, spriteBodyDef.position); addChild(monkey,10000); this.schedule(tickCallback); this.schedule(createobjects, 2.0f); objectHint = CCColorLayer.node(ccColor4B.ccc4(255,0,0,128), 200f, 100f); addChild(objectHint, 15000); objectHint.setVisible(false); _world.setContactListener(_contactListener); } private UpdateCallback tickCallback = new UpdateCallback() { public void update(float d) { tick(d); } }; private UpdateCallback createobjects = new UpdateCallback() { public void update(float d) { secondUpdate(d); } }; private void secondUpdate(float dt) { this.addNewSprite(); } public void addBoxBodyForSprite(CCSprite sprite) { BodyDef spriteBodyDef = new BodyDef(); spriteBodyDef.type = BodyType.StaticBody; //spriteBodyDef.bullet=true; spriteBodyDef.position.set(sprite.getPosition().x / PTM_RATIO, sprite.getPosition().y / PTM_RATIO); spriteBody = _world.createBody(spriteBodyDef); spriteBody.setUserData(sprite); Vector2 verts[] = { new Vector2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO), new Vector2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO), new Vector2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO), new Vector2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO), new Vector2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO), new Vector2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO), new Vector2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO) }; PolygonShape spriteShape = new PolygonShape(); spriteShape.set(verts); //spriteShape.setAsBox(sprite.getContentSize().width/PTM_RATIO/2, //sprite.getContentSize().height/PTM_RATIO/2); FixtureDef spriteShapeDef = new FixtureDef(); spriteShapeDef.shape = spriteShape; spriteShapeDef.density = 2.0f; spriteShapeDef.friction = 0.70f; spriteShapeDef.restitution = 0.0f; spriteShapeDef.isSensor=true; spriteBody.createFixture(spriteShapeDef); } public void addNewSprite() { count=0; Random rand = new Random(); int Number = rand.nextInt(10); switch(Number) { case 0: _block = CCSprite.sprite("banana.png"); break; case 1: _block = CCSprite.sprite("backpack.png");break; case 2: _block = CCSprite.sprite("statue.png");break; case 3: _block = CCSprite.sprite("pineapple.png");break; case 4: _block = CCSprite.sprite("bananabunch.png");break; case 5: _block = CCSprite.sprite("hat.png");break; case 6: _block = CCSprite.sprite("canteen.png");break; case 7: _block = CCSprite.sprite("banana.png");break; case 8: _block = CCSprite.sprite("statue.png");break; case 9: _block = CCSprite.sprite("hat.png");break; } int padding=20; //_block.setPosition(CGPoint.make(100, 100)); // Determine where to spawn the target along the Y axis CGSize winSize = CCDirector.sharedDirector().displaySize(); int minY = (int)(_block.getContentSize().width / 2.0f); int maxY = (int)(winSize.width - _block.getContentSize().width / 2.0f); int rangeY = maxY - minY; int actualY = rand.nextInt(rangeY) + minY; // Create block and add it to the layer float xOffset = padding+_block.getContentSize().width/2+((_block.getContentSize().width+padding)*count); _block.setPosition(CGPoint.make(actualY, 750)); _block.setTag(1); float w = _block.getContentSize().width; objectHint.setVisible(true); objectHint.changeWidth(w); objectHint.setPosition(actualY-w/2, 460); this.addChild(_block,10000); // Create ball body and shape BodyDef ballBodyDef1 = new BodyDef(); ballBodyDef1.type = BodyType.DynamicBody; ballBodyDef1.position.set(actualY/PTM_RATIO, 480/PTM_RATIO); bodies = _world.createBody(ballBodyDef1); bodies.setUserData(_block); PolygonShape circle1 = new PolygonShape(); Vector2 verts[] = { new Vector2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO), new Vector2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO), new Vector2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO), new Vector2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO), new Vector2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO), new Vector2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO), new Vector2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO) }; circle1.set(verts); FixtureDef ballShapeDef1 = new FixtureDef(); ballShapeDef1.shape = circle1; ballShapeDef1.density = 10.0f; ballShapeDef1.friction = 0.0f; ballShapeDef1.restitution = 0.1f; bodies.createFixture(ballShapeDef1); count++; //Remove(); } @Override public void ccAccelerometerChanged(float accelX, float accelY, float accelZ) { //Apply the directional impulse /*float impulse = monkey_body.getMass()*accelY*WALK_FACTOR; Vector2 force = new Vector2(impulse, 0); monkey_body.applyLinearImpulse(force, monkey_body.getWorldCenter());*/ walk(accelY); //Remove(); } private void walk(float accelY) { // TODO Auto-generated method stub direction = accelY; } private void Remove() { for (Iterator<MyContact> it1 = _contactListener.mContacts.iterator(); it1.hasNext();) { MyContact contact = it1.next(); Body bodyA = contact.fixtureA.getBody(); Body bodyB = contact.fixtureB.getBody(); // See if there's any user data attached to the Box2D body // There should be, since we set it in addBoxBodyForSprite if (bodyA.getUserData() != null && bodyB.getUserData() != null) { CCSprite spriteA = (CCSprite) bodyA.getUserData(); CCSprite spriteB = (CCSprite) bodyB.getUserData(); // Is sprite A a cat and sprite B a car? If so, push the cat // on a list to be destroyed... if (spriteA.getTag() == 1 && spriteB.getTag() == 2) { //Log.v("dsfds", "dsfsd"+bodyA); //_world.destroyBody(bodyA); // removeChild(spriteA, true); toDestroy.add(bodyA); } // Is sprite A a car and sprite B a cat? If so, push the cat // on a list to be destroyed... else if (spriteA.getTag() == 2 && spriteB.getTag() == 1) { //Log.v("dsfds", "dsfsd"+bodyB); toDestroy.add(bodyB); } } } // Loop through all of the box2d bodies we want to destroy... for (Iterator<Body> it1 = toDestroy.iterator(); it1.hasNext();) { Body body = it1.next(); // See if there's any user data attached to the Box2D body // There should be, since we set it in addBoxBodyForSprite if (body.getUserData() != null) { // We know that the user data is a sprite since we set // it that way, so cast it... CCSprite sprite = (CCSprite) body.getUserData(); // Remove the sprite from the scene _world.destroyBody(body); removeChild(sprite, true); } // Destroy the Box2D body as well // _contactListener.mContacts.remove(0); } } public synchronized void tick(float delta) { synchronized (_world) { _world.step(delta, 8, 3); //_world.clearForces(); //addNewSprite(); } CCAnimation danceAnimation = CCAnimation.animation("dance", 1.0f); // Iterate over the bodies in the physics world Iterator<Body> it = _world.getBodies(); while(it.hasNext()) { Body b = it.next(); Object userData = b.getUserData(); if (userData != null && userData instanceof CCSprite) { //Synchronize the Sprites position and rotation with the corresponding body CCSprite sprite = (CCSprite)userData; if(sprite.getTag()==1) { //b.applyLinearImpulse(force, pos); sprite.setPosition(b.getPosition().x * PTM_RATIO, b.getPosition().y * PTM_RATIO); sprite.setRotation(-1.0f * ccMacros.CC_RADIANS_TO_DEGREES(b.getAngle())); } else { //Apply the directional impulse float impulse = monkey_body.getMass()*direction*WALK_FACTOR; Vector2 force = new Vector2(impulse, 0); b.applyLinearImpulse(force, b.getWorldCenter()); sprite.setPosition(b.getPosition().x * PTM_RATIO, b.getPosition().y * PTM_RATIO); animDelay -= 1.0f/60.0f; if(animDelay <= 0) { animDelay = ANIM_SPEED; animPhase++; if(animPhase > 2) { animPhase = 1; } } if(direction < 0 ) { isLeft=1; } else { isLeft=0; } if(isLeft==1) { dir = "left"; } else { dir = "right"; } float standingLimit = (float) 0.1f; float vX = monkey_body.getLinearVelocity().x; if((vX > -standingLimit)&& (vX < standingLimit)) { // Log.v("sasd", "standing"); } else { } } } } Remove(); } } Sorry for my english. Thanks in advance.

    Read the article

< Previous Page | 5 6 7 8 9 10 11  | Next Page >