Search Results

Search found 243 results on 10 pages for 'illegalargumentexception'.

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

  • how to update an Android ListActivity on changing data of the connected SimpleCursorAdapter

    - by 4485670
    I have the following code. What I want to achieve is to update the shown list when I click an entry so I can traverse through the list. I found the two uncommented ways to do it here on stackoverflow, but neither works. I also got the advice to create a new ListActivity on the data update, but that sounds like wasting resources? EDIT: I found the solution myself. All you need to do is call "SimpleCursorAdapter.changeCursor(new Cursor);". No notifying, no things in UI-Thread or whatever. import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class MyActivity extends ListActivity { private DepartmentDbAdapter mDbHelper; private Cursor cursor; private String[] from = new String[] { DepartmentDbAdapter.KEY_NAME }; private int[] to = new int[] { R.id.text1 }; private SimpleCursorAdapter notes; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.departments_list); mDbHelper = new DepartmentDbAdapter(this); mDbHelper.open(); // Get all of the departments from the database and create the item list cursor = mDbHelper.fetchSubItemByParentId(1); this.startManagingCursor(cursor); // Now create an array adapter and set it to display using our row notes = new SimpleCursorAdapter(this, R.layout.department_row, cursor, from, to); this.setListAdapter(notes); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // get new data and update the list this.updateData(safeLongToInt(id)); } /** * update data for the list * * @param int departmentId id of the parent department */ private void updateData(int departmentId) { // close the old one, get a new one cursor.close(); cursor = mDbHelper.fetchSubItemByParentId(departmentId); // change the cursor of the adapter to the new one notes.changeCursor(cursor); } /** * safely convert long to in to save memory * * @param long l the long variable * * @return integer */ public static int safeLongToInt(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new IllegalArgumentException (l + " cannot be cast to int without changing its value."); } return (int) l; } }

    Read the article

  • how to invoke an activity of a library project from an android apps

    - by Austin
    I have an open source android code that I need to use in my android apps. It has all the source code as well as resource files, manifest files and class path. It can be compiled as a separate android apps. I have constraints for using the open source. 1. I can't change a single line of code. 2. I can't use it as a separate apps. These constraints are non negotiable. What I have done is I have compiled the open source as class library(in Eclipse: Project Properties-Android- Tick check box Is Library). This has resulted in generation of .class files(in bin) for the java files and resource files. This open source has an android activity that i want to open from my application. So I have linked the directory of these sets of class files in the source section of my java build path( in .classpath). I have declared the activity in my manifest file with proper action intent filters. Now when I am trying to call activity from my code, its not working. Cleaning and rebuilding doesn't help. However, if I build the open source project and my apps in the same workspace of eclipse and link the open source in my apps in exact same manner it works fine. I am not able to identify the difference. All settings seems to be same(all files are identical in both the cases). But only in the second case it works. I have tried it as jar file also. I have build the open source as project library and exported it into a jar file(excluding manifest file). But in that case I am getting the following error UNEXPECTED TOP-LEVEL EXCEPTION: java.lang.IllegalArgumentException: already added: .... Conversion to Dalvik format failed with error 1 This I guess is coming because the android library(2.2) has been included twice in my apps( one for building my apps & another for building the open source). I dont know how to avoid this. Cleaning the project doesn't help. What i require is to use the open source and invoking it's activities in my apps without violating the constraints. If i can use the open source as bunch of .class files then great, or else any other way will do fine. Please look into it and let me know. Thanks

    Read the article

  • JPA - Can I create an Entity class, using an @DiscriminatorValue, that doesn't have its own table?

    - by DaveyDaveDave
    Hi - this is potentially a bit complex, so I'll do my best to describe my situation - it's also my first post here, so please forgive formatting mistakes, etc! I'm using JPA with joined inheritance and a database structure that looks like: ACTION --------- ACTION_ID ACTION_MAPPING_ID ACTION_TYPE DELIVERY_CHANNEL_ACTION -------------------------- ACTION_ID CHANNEL_ID OVERRIDE_ADDRESS_ACTION -------------------------- ACTION_ID (various fields specific to this action type) So, in plain English, I have multiple different types of action, all share an ACTION_MAPPING, which is referenced from the 'parent' ACTION table. DELIVERY_CHANNEL_ACTION and OVERRIDE_ADDRESS_ACTION both have extra, supplementary data of their own, and are mapped to ACTION with a FK. Real-world, I also have a 'suppress' action, but this doesn't have any supplementary data of its own, so it doesn't have a corresponding table - all it needs is an ACTION_MAPPING, which is stored in the ACTION table. Hopefully you're with me so far... I'm creating a new project from scratch, so am pretty flexible in what I can do, but obviously would like to get it right from the outset! My current implementation, which works, has three entities loosely defined as follows: @Entity @Table(name="ACTION") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorValue("SUPPRESS") public class Action @Entity @Table(name="DELIVERY_CHANNEL_ACTION") @DiscriminatorValue("DELIVERY_CHANNEL") public class DeliveryChannelAction extends Action @Entity @Table(name="OVERRIDE_ADDRESS_ACTION") @DiscriminatorValue("OVERRIDE_ADDRESS") public class OverrideAddressAction extends Action That is - I have a concrete base class, Action, with a Joined inheritance strategy. DeliveryChannelAction and OverrideAddressAction both extend Action. What feels wrong here though, is that my Action class is the base class for these two actions, but also forms the concrete implementation for the suppress action. For the time being this works, but at some point more actions are likely to be added, and there's every chance that some of them will, like SUPPRESS, have no supplementary data, which will start to get difficult! So... what I would like to do, in the object model world, is to have Action be abstract, and create a SuppressAction class, which is empty apart from having a @DiscriminatorValue("SUPPRESS"). I've tried doing exactly what is described above, so, changing Action to: @Entity @Table(name="ACTION") @Inheritance(strategy=InheritanceType.JOINED) public abstract class Action and creating: @DiscriminatorValue("SUPPRESS") public class SuppressAction extends Action but no luck - it seems to work fine for DeliveryChannelAction and OverrideAddressAction, but when I try to create a SuppressAction and persist it, I get: java.lang.IllegalArgumentException: Object: com.mypackage.SuppressAction[actionId=null] is not a known entity type. at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4147) at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:368) at com.mypackage.test.util.EntityTestUtil.createSuppressAction(EntityTestUtil.java:672) at com.mypackage.entities.ActionTest.testCRUDAction(ActionTest.java:27) which I assume is down to the fact that SuppressAction isn't registered as an entity, but I don't know how I can do that, given that it doesn't have an associated table. Any pointers, either complete answers or hints for things to Google (I'm out of ideas!), most welcome :) EDIT: to correct my stacktrace.

    Read the article

  • How solve consumer/producer task using semaphores

    - by user1074896
    I have SimpleProducerConsumer class that illustrate consumer/producer problem (I am not sure that it's correct). public class SimpleProducerConsumer { private Stack<Object> stack = new Stack<Object>(); private static final int STACK_MAX_SIZE = 10; public static void main(String[] args) { SimpleProducerConsumer pc = new SimpleProducerConsumer(); new Thread(pc.new Producer(), "p1").start(); new Thread(pc.new Producer(), "p2").start(); new Thread(pc.new Consumer(), "c1").start(); new Thread(pc.new Consumer(), "c2").start(); new Thread(pc.new Consumer(), "c3").start(); } public synchronized void push(Object d) { while (stack.size() >= STACK_MAX_SIZE) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stack.push(new Object()); System.out.println("push " + Thread.currentThread().getName() + " " + stack.size()); notify(); } public synchronized Object pop() { while (stack.size() == 0) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } stack.pop(); System.out.println("pop " + Thread.currentThread().getName() + " " + stack.size()); notify(); return null; } class Consumer implements Runnable { @Override public void run() { while (true) { pop(); } } } class Producer implements Runnable { @Override public void run() { while (true) { push(new Object()); } } } } I found simple realization of semaphore(here:http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html I know that there is concurrency package) How I need to change code to exchange java objects monitors to my custom semaphore. (To illustrate C/P problem using semaphores) Semaphore: class Semaphore { private int counter; public Semaphore() { this(0); } public Semaphore(int i) { if (i < 0) throw new IllegalArgumentException(i + " < 0"); counter = i; } public synchronized void release() { if (counter == 0) { notify(); } counter++; } public synchronized void acquire() throws InterruptedException { while (counter == 0) { wait(); } counter--; } }

    Read the article

  • How to create a simple adf dashboard application with EJB 3.0

    - by Rodrigues, Raphael
    In this month's Oracle Magazine, Frank Nimphius wrote a very good article about an Oracle ADF Faces dashboard application to support persistent user personalization. You can read this entire article clicking here. The idea in this article is to extend the dashboard application. My idea here is to create a similar dashboard application, but instead ADF BC model layer, I'm intending to use EJB3.0. There are just a one small trick here and I'll show you. I'm using the HR usual oracle schema. The steps are: 1. Create a ADF Fusion Application with EJB as a layer model 2. Generate the entities from table (I'm using Department and Employees only) 3. Create a new Session Bean. I called it: HRSessionEJB 4. Create a new method like that: public List getAllDepartmentsHavingEmployees(){ JpaEntityManager jpaEntityManager = (JpaEntityManager)em.getDelegate(); Query query = jpaEntityManager.createNamedQuery("Departments.allDepartmentsHavingEmployees"); JavaBeanResult.setQueryResultClass(query, AggregatedDepartment.class); return query.getResultList(); } 5. In the Departments entity, create a new native query annotation: @Entity @NamedQueries( { @NamedQuery(name = "Departments.findAll", query = "select o from Departments o") }) @NamedNativeQueries({ @NamedNativeQuery(name="Departments.allDepartmentsHavingEmployees", query = "select e.department_id, d.department_name , sum(e.salary), avg(e.salary) , max(e.salary), min(e.salary) from departments d , employees e where d.department_id = e.department_id group by e.department_id, d.department_name")}) public class Departments implements Serializable {...} 6. Create a new POJO called AggregatedDepartment: package oramag.sample.dashboard.model; import java.io.Serializable; import java.math.BigDecimal; public class AggregatedDepartment implements Serializable{ @SuppressWarnings("compatibility:5167698678781240729") private static final long serialVersionUID = 1L; private BigDecimal departmentId; private String departmentName; private BigDecimal sum; private BigDecimal avg; private BigDecimal max; private BigDecimal min; public AggregatedDepartment() { super(); } public AggregatedDepartment(BigDecimal departmentId, String departmentName, BigDecimal sum, BigDecimal avg, BigDecimal max, BigDecimal min) { super(); this.departmentId = departmentId; this.departmentName = departmentName; this.sum = sum; this.avg = avg; this.max = max; this.min = min; } public void setDepartmentId(BigDecimal departmentId) { this.departmentId = departmentId; } public BigDecimal getDepartmentId() { return departmentId; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getDepartmentName() { return departmentName; } public void setSum(BigDecimal sum) { this.sum = sum; } public BigDecimal getSum() { return sum; } public void setAvg(BigDecimal avg) { this.avg = avg; } public BigDecimal getAvg() { return avg; } public void setMax(BigDecimal max) { this.max = max; } public BigDecimal getMax() { return max; } public void setMin(BigDecimal min) { this.min = min; } public BigDecimal getMin() { return min; } } 7. Create the util java class called JavaBeanResult. The function of this class is to configure a native SQL query to return POJOs in a single line of code using the utility class. Credits: http://onpersistence.blogspot.com.br/2010/07/eclipselink-jpa-native-constructor.html package oramag.sample.dashboard.model.util; /******************************************************************************* * Copyright (c) 2010 Oracle. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * @author shsmith ******************************************************************************/ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import org.eclipse.persistence.exceptions.ConversionException; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.jpa.JpaHelper; import org.eclipse.persistence.queries.DatabaseQuery; import org.eclipse.persistence.queries.QueryRedirector; import org.eclipse.persistence.sessions.Record; import org.eclipse.persistence.sessions.Session; /*** * This class is a simple query redirector that intercepts the result of a * native query and builds an instance of the specified JavaBean class from each * result row. The order of the selected columns musts match the JavaBean class * constructor arguments order. * * To configure a JavaBeanResult on a native SQL query use: * JavaBeanResult.setQueryResultClass(query, SomeBeanClass.class); * where query is either a JPA SQL Query or native EclipseLink DatabaseQuery. * * @author shsmith * */ public final class JavaBeanResult implements QueryRedirector { private static final long serialVersionUID = 3025874987115503731L; protected Class resultClass; public static void setQueryResultClass(Query query, Class resultClass) { JavaBeanResult javaBeanResult = new JavaBeanResult(resultClass); DatabaseQuery databaseQuery = JpaHelper.getDatabaseQuery(query); databaseQuery.setRedirector(javaBeanResult); } public static void setQueryResultClass(DatabaseQuery query, Class resultClass) { JavaBeanResult javaBeanResult = new JavaBeanResult(resultClass); query.setRedirector(javaBeanResult); } protected JavaBeanResult(Class resultClass) { this.resultClass = resultClass; } @SuppressWarnings("unchecked") public Object invokeQuery(DatabaseQuery query, Record arguments, Session session) { List results = new ArrayList(); try { Constructor[] constructors = resultClass.getDeclaredConstructors(); Constructor javaBeanClassConstructor = null; // (Constructor) resultClass.getDeclaredConstructors()[0]; Class[] constructorParameterTypes = null; // javaBeanClassConstructor.getParameterTypes(); List rows = (List) query.execute( (AbstractSession) session, (AbstractRecord) arguments); for (Object[] columns : rows) { boolean found = false; for (Constructor constructor : constructors) { javaBeanClassConstructor = constructor; constructorParameterTypes = javaBeanClassConstructor.getParameterTypes(); if (columns.length == constructorParameterTypes.length) { found = true; break; } // if (columns.length != constructorParameterTypes.length) { // throw new ColumnParameterNumberMismatchException( // resultClass); // } } if (!found) throw new ColumnParameterNumberMismatchException( resultClass); Object[] constructorArgs = new Object[constructorParameterTypes.length]; for (int j = 0; j < columns.length; j++) { Object columnValue = columns[j]; Class parameterType = constructorParameterTypes[j]; // convert the column value to the correct type--if possible constructorArgs[j] = ConversionManager.getDefaultManager() .convertObject(columnValue, parameterType); } results.add(javaBeanClassConstructor.newInstance(constructorArgs)); } } catch (ConversionException e) { throw new ColumnParameterMismatchException(e); } catch (IllegalArgumentException e) { throw new ColumnParameterMismatchException(e); } catch (InstantiationException e) { throw new ColumnParameterMismatchException(e); } catch (IllegalAccessException e) { throw new ColumnParameterMismatchException(e); } catch (InvocationTargetException e) { throw new ColumnParameterMismatchException(e); } return results; } public final class ColumnParameterMismatchException extends RuntimeException { private static final long serialVersionUID = 4752000720859502868L; public ColumnParameterMismatchException(Throwable t) { super( "Exception while processing query results-ensure column order matches constructor parameter order", t); } } public final class ColumnParameterNumberMismatchException extends RuntimeException { private static final long serialVersionUID = 1776794744797667755L; public ColumnParameterNumberMismatchException(Class clazz) { super( "Number of selected columns does not match number of constructor arguments for: " + clazz.getName()); } } } 8. Create the DataControl and a jsf or jspx page 9. Drag allDepartmentsHavingEmployees from DataControl and drop in your page 10. Choose Graph > Type: Bar (Normal) > any layout 11. In the wizard screen, Bars label, adds: sum, avg, max, min. In the X Axis label, adds: departmentName, and click in OK button 12. Run the page, the result is showed below: You can download the workspace here . It was using the latest jdeveloper version 11.1.2.2.

    Read the article

  • Twitter 2 for Android crash every time I try uploading multi photos [closed]

    - by Hazz
    Hello, I'm using the new Twitter 2 on Android 2.1. Whenever I hit the button which enables me to upload multiple photos in a single tweet, I always get the error "The application Camera (process com.sonyericsson.camera) has stopped unexpectidly. Please try again". However, uploading a single photo using the camera button in Twitter have no problem, it works. My phone is Sony Ericsson x10 mini pro. I tried signing out and back in, same result. Anything I can do to fix this? This is the log info I got using Log Collector: 02-23 15:05:57.328 I/ActivityManager( 1240): Starting activity: Intent { act=com.twitter.android.post.status cmp=com.twitter.android/.PostActivity } 02-23 15:05:57.338 D/PhoneWindow(15095): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@45726938 has no id. 02-23 15:05:57.688 I/ActivityManager( 1240): Displayed activity com.twitter.android/.PostActivity: 340 ms (total 340 ms) 02-23 15:05:59.018 I/ActivityManager( 1240): Starting activity: Intent { act=android.intent.action.PICK typ=vnd.android.cursor.dir/image cmp=com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity } 02-23 15:05:59.038 I/ActivityManager( 1240): Start proc com.sonyericsson.camera for activity com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity: pid=15113 uid=10057 gids={1006, 1015, 3003} 02-23 15:05:59.128 I/dalvikvm(15113): Debugger thread not active, ignoring DDM send (t=0x41504e4d l=38) 02-23 15:05:59.158 I/dalvikvm(15113): Debugger thread not active, ignoring DDM send (t=0x41504e4d l=50) 02-23 15:05:59.448 I/ActivityManager( 1240): Displayed activity com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity: 423 ms (total 423 ms) 02-23 15:05:59.458 W/dalvikvm(15113): threadid=15: thread exiting with uncaught exception (group=0x4001e160) 02-23 15:05:59.458 E/AndroidRuntime(15113): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception 02-23 15:05:59.468 E/AndroidRuntime(15113): java.lang.RuntimeException: An error occured while executing doInBackground() 02-23 15:05:59.468 E/AndroidRuntime(15113): at android.os.AsyncTask$3.done(AsyncTask.java:200) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.lang.Thread.run(Thread.java:1096) 02-23 15:05:59.468 E/AndroidRuntime(15113): Caused by: java.lang.IllegalArgumentException: Unsupported MIME type. 02-23 15:05:59.468 E/AndroidRuntime(15113): at com.sonyericsson.album.grid.GridActivity$AlbumTask.doInBackground(GridActivity.java:202) 02-23 15:05:59.468 E/AndroidRuntime(15113): at com.sonyericsson.album.grid.GridActivity$AlbumTask.doInBackground(GridActivity.java:124) 02-23 15:05:59.468 E/AndroidRuntime(15113): at android.os.AsyncTask$2.call(AsyncTask.java:185) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 02-23 15:05:59.468 E/AndroidRuntime(15113): ... 4 more 02-23 15:05:59.628 E/SemcCheckin(15113): Get crash dump level : java.io.FileNotFoundException: /data/semc-checkin/crashdump 02-23 15:05:59.628 W/ActivityManager( 1240): Unable to start service Intent { act=com.sonyericsson.android.jcrashcatcher.action.BUGREPORT_AUTO cmp=com.sonyericsson.android.jcrashcatcher/.JCrashCatcherService (has extras) }: not found 02-23 15:05:59.648 I/Process ( 1240): Sending signal. PID: 15113 SIG: 3 02-23 15:05:59.648 I/dalvikvm(15113): threadid=7: reacting to signal 3 02-23 15:05:59.778 I/dalvikvm(15113): Wrote stack trace to '/data/anr/traces.txt' 02-23 15:06:00.388 E/SemcCheckin( 1673): Get Crash Level : java.io.FileNotFoundException: /data/semc-checkin/crashdump 02-23 15:06:01.708 I/DumpStateReceiver( 1240): Added state dump to 1 crashes 02-23 15:06:02.008 D/iddd-events( 1117): Registering event com.sonyericsson.idd.probe.android.devicemonitor::ApplicationCrash with 4314 bytes payload. 02-23 15:06:06.968 D/dalvikvm( 1673): GC freed 661 objects / 126704 bytes in 124ms 02-23 15:06:11.928 D/dalvikvm( 1379): GC freed 19753 objects / 858832 bytes in 84ms 02-23 15:06:13.038 I/Process (15113): Sending signal. PID: 15113 SIG: 9 02-23 15:06:13.048 I/WindowManager( 1240): WIN DEATH: Window{4596ecc0 com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity paused=false} 02-23 15:06:13.048 I/ActivityManager( 1240): Process com.sonyericsson.camera (pid 15113) has died. 02-23 15:06:13.048 I/WindowManager( 1240): WIN DEATH: Window{459db5e8 com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity paused=false} 02-23 15:06:13.078 I/UsageStats( 1240): Unexpected resume of com.twitter.android while already resumed in com.sonyericsson.camera 02-23 15:06:13.098 W/InputManagerService( 1240): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@456e7168 02-23 15:06:21.278 D/dalvikvm( 1745): GC freed 2032 objects / 410848 bytes in 60ms

    Read the article

  • How do I resolve "Unable to resolve attribute [organizationType.id] against path" exception?

    - by Dave
    I'm using Spring 3.1.1.RELEASE, Hibernate 4.1.0.Final, JUnit 4.8, and JPA 2.0 (hibernate-jpa-2.0-api). I'm trying to write a query and search based on fields of member fields. What I mean is I have this entity … @GenericGenerator(name = "uuid-strategy", strategy = "uuid.hex") @Entity @Table(name = "cb_organization", uniqueConstraints = {@UniqueConstraint(columnNames={"organization_id"})}) public class Organization implements Serializable { @Id @NotNull @GeneratedValue(generator = "uuid-strategy") @Column(name = "id") /* the database id of the Organization */ private String id; @ManyToOne @JoinColumn(name = "state_id", nullable = true, updatable = false) /* the State for the organization */ private State state; @ManyToOne @JoinColumn(name = "country_id", nullable = false, updatable = false) /* The country the Organization is in */ private Country country; @ManyToOne(optional = false) @JoinColumn(name = "organization_type_id", nullable = false, updatable = false) /* The type of the Organization */ private OrganizationType organizationType; Notice the members "organizationType," "state," and "country," which are all objects. I wish to build a query based on their id fields. This code @Override public List<Organization> findByOrgTypesCountryAndState(Set<String> organizationTypes, String countryId, String stateId) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Organization> criteria = builder.createQuery(Organization.class); Root<Organization> org = criteria.from(Organization.class); criteria.select(org).where(builder.and(org.get("organizationType.id").in(organizationTypes), builder.equal(org.get("state.id"), stateId), builder.equal(org.get("country.id"), countryId))); return entityManager.createQuery(criteria).getResultList(); } is throwing the exception below. How do I heal the pain? java.lang.IllegalArgumentException: Unable to resolve attribute [organizationType.id] against path at org.hibernate.ejb.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:116) at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:221) at org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:192) at org.mainco.subco.organization.repo.OrganizationDaoImpl.findByOrgTypesCountryAndState(OrganizationDaoImpl.java:248) at org.mainco.subco.organization.repo.OrganizationDaoTest.testFindByOrgTypesCountryAndState(OrganizationDaoTest.java:55) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

    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

  • JPA thinks I'm deleting a detached object

    - by Steve
    So, I've got a DAO that I used to load and save my domain objects using JPA. I finally managed to get the transaction stuff working (with a bunch of help from the folks here...), now I've got another issue. In my test case, I call my DAO to load a domain object with a given id, check that it got loaded and then call the same DAO to delete the object I just loaded. When I do that I get the following: java.lang.IllegalArgumentException: Removing a detached instance mil.navy.ndms.conops.common.model.impl.jpa.Group#10 at org.hibernate.ejb.event.EJB3DeleteEventListener.performDetachedEntityDeletionCheck(EJB3DeleteEventListener.java:45) at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:108) at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:74) at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:794) at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:772) at org.hibernate.ejb.AbstractEntityManagerImpl.remove(AbstractEntityManagerImpl.java:253) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) at java.lang.reflect.Method.invoke(Method.java:600) at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:180) at $Proxy27.remove(Unknown Source) at mil.navy.ndms.conops.common.dao.impl.jpa.GroupDao.delete(GroupDao.java:499) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) at java.lang.reflect.Method.invoke(Method.java:600) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:304) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy28.delete(Unknown Source) at mil.navy.ndms.conops.common.dao.impl.jpa.GroupDaoTest.testGroupDaoSave(GroupDaoTest.java:89) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) at java.lang.reflect.Method.invoke(Method.java:600) at junit.framework.TestCase.runTest(TestCase.java:164) at junit.framework.TestCase.runBare(TestCase.java:130) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.runTest(TestSuite.java:230) at junit.framework.TestSuite.run(TestSuite.java:225) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) Now given that I'm using the same DAO instance, and I've not changed EntityManagers (unless Spring does so without letting me know), how can this be a detached object? My DAO code looks like this: public class GenericJPADao implements IWebDao, IDao, IDaoUtil { private static Logger logger = Logger.getLogger (GenericJPADao.class); protected Class voClass; @PersistenceContext(unitName = "CONOPS_PU") protected EntityManagerFactory emf; @PersistenceContext(unitName = "CONOPS_PU") protected EntityManager em; public GenericJPADao() { super ( ); ParameterizedType genericSuperclass = (ParameterizedType) getClass ( ).getGenericSuperclass ( ); this.voClass = (Class) genericSuperclass.getActualTypeArguments ( )[1]; } ... public void delete (INTFC modelObj, EntityManager em) { em.remove (modelObj); } @SuppressWarnings("unchecked") public INTFC findById (Long id) { return ((INTFC) em.find (voClass, id)); } } The test case code looks like: IGroup loadedGroup = dao.findById (group.getId ( )); assertNotNull (loadedGroup); assertEquals (group.getId ( ), loadedGroup.getId ( )); dao.delete (loadedGroup); // - This generates the above exception loadedGroup = dao.findById (group.getId ( )); assertNull(loadedGroup); Can anyone tell me what I'm doing wrong here? Thanks

    Read the article

  • class not found expection.

    - by theJava
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.lang.Class[]' for property 'annotatedClasses'; nested exception is java.lang.IllegalArgumentException: Cannot find class [com.vinoth.domain.User] org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:212) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879) org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689) java.lang.Thread.run(Unknown Source) I have the particular class in my source and here is my bean config and yet when i compile my application it throws me the error. <?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"/> <property name="username" value="monty"/> <property name="password" value="indian"/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="myDataSource" /> <property name="annotatedClasses"> <list> <value>com.vinoth.domain.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean> <bean id="myUserDAO" class="com.vinoth.dao.UserDAOImpl"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> <bean name="/user/*.htm" class="com.vinoth.web.UserController" > <property name="userDAO" ref="myUserDAO" /> </bean> </beans>

    Read the article

  • Managing highly repetitive code and documentation in Java

    - by polygenelubricants
    Highly repetitive code is generally a bad thing, and there are design patterns that can help minimize this. However, sometimes it's simply inevitable due to the constraints of the language itself. Take the following example from java.util.Arrays: /** * Assigns the specified long value to each element of the specified * range of the specified array of longs. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(long[] a, int fromIndex, int toIndex, long val) { rangeCheck(a.length, fromIndex, toIndex); for (int i=fromIndex; i<toIndex; i++) a[i] = val; } The above snippet appears in the source code 8 times, with very little variation in the documentation/method signature but exactly the same method body, one for each of the root array types int[], short[], char[], byte[], boolean[], double[], float[], and Object[]. I believe that unless one resorts to reflection (which is an entirely different subject in itself), this repetition is inevitable. I understand that as a utility class, such high concentration of repetitive Java code is highly atypical, but even with the best practice, repetition does happen! Refactoring doesn't always work because it's not always possible (the obvious case is when the repetition is in the documentation). Obviously maintaining this source code is a nightmare. A slight typo in the documentation, or a minor bug in the implementation, is multiplied by however many repetitions was made. In fact, the best example happens to involve this exact class: Google Research Blog - Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken (by Joshua Bloch, Software Engineer) The bug is a surprisingly subtle one, occurring in what many thought to be just a simple and straightforward algorithm. // int mid =(low + high) / 2; // the bug int mid = (low + high) >>> 1; // the fix The above line appears 11 times in the source code! So my questions are: How are these kinds of repetitive Java code/documentation handled in practice? How are they developed, maintained, and tested? Do you start with "the original", and make it as mature as possible, and then copy and paste as necessary and hope you didn't make a mistake? And if you did make a mistake in the original, then just fix it everywhere, unless you're comfortable with deleting the copies and repeating the whole replication process? And you apply this same process for the testing code as well? Would Java benefit from some sort of limited-use source code preprocessing for this kind of thing? Perhaps Sun has their own preprocessor to help write, maintain, document and test these kind of repetitive library code? A comment requested another example, so I pulled this one from Google Collections: com.google.common.base.Predicates lines 276-310 (AndPredicate) vs lines 312-346 (OrPredicate). The source for these two classes are identical, except for: AndPredicate vs OrPredicate (each appears 5 times in its class) "And(" vs Or(" (in the respective toString() methods) #and vs #or (in the @see Javadoc comments) true vs false (in apply; ! can be rewritten out of the expression) -1 /* all bits on */ vs 0 /* all bits off */ in hashCode() &= vs |= in hashCode()

    Read the article

  • How to do inclusive range queries when only half-open range is supported (ala SortedMap.subMap)

    - by polygenelubricants
    On SortedMap.subMap This is the API for SortedMap<K,V>.subMap: SortedMap<K,V> subMap(K fromKey, K toKey) : Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. This inclusive lower bound, exclusive upper bound combo ("half-open range") is something that is prevalent in Java, and while it does have its benefits, it also has its quirks, as we shall soon see. The following snippet illustrates a simple usage of subMap: static <K,V> SortedMap<K,V> someSortOfSortedMap() { return Collections.synchronizedSortedMap(new TreeMap<K,V>()); } //... SortedMap<Integer,String> map = someSortOfSortedMap(); map.put(1, "One"); map.put(3, "Three"); map.put(5, "Five"); map.put(7, "Seven"); map.put(9, "Nine"); System.out.println(map.subMap(0, 4)); // prints "{1=One, 3=Three}" System.out.println(map.subMap(3, 7)); // prints "{3=Three, 5=Five}" The last line is important: 7=Seven is excluded, due to the exclusive upper bound nature of subMap. Now suppose that we actually need an inclusive upper bound, then we could try to write a utility method like this: static <V> SortedMap<Integer,V> subMapInclusive(SortedMap<Integer,V> map, int from, int to) { return (to == Integer.MAX_VALUE) ? map.tailMap(from) : map.subMap(from, to + 1); } Then, continuing on with the above snippet, we get: System.out.println(subMapInclusive(map, 3, 7)); // prints "{3=Three, 5=Five, 7=Seven}" map.put(Integer.MAX_VALUE, "Infinity"); System.out.println(subMapInclusive(map, 5, Integer.MAX_VALUE)); // {5=Five, 7=Seven, 9=Nine, 2147483647=Infinity} A couple of key observations need to be made: The good news is that we don't care about the type of the values, but... subMapInclusive assumes Integer keys for to + 1 to work. A generic version that also takes e.g. Long keys is not possible (see related questions) Not to mention that for Long, we need to compare against Long.MAX_VALUE instead Overloads for the numeric primitive boxed types Byte, Character, etc, as keys, must all be written individually A special check need to be made for toInclusive == Integer.MAX_VALUE, because +1 would overflow, and subMap would throw IllegalArgumentException: fromKey > toKey This, generally speaking, is an overly ugly and overly specific solution What about String keys? Or some unknown type that may not even be Comparable<?>? So the question is: is it possible to write a general subMapInclusive method that takes a SortedMap<K,V>, and K fromKey, K toKey, and perform an inclusive-range subMap queries? Related questions Are upper bounds of indexed ranges always assumed to be exclusive? Is it possible to write a generic +1 method for numeric box types in Java? On NavigableMap It should be mentioned that there's a NavigableMap.subMap overload that takes two additional boolean variables to signify whether the bounds are inclusive or exclusive. Had this been made available in SortedMap, then none of the above would've even been asked. So working with a NavigableMap<K,V> for inclusive range queries would've been ideal, but while Collections provides utility methods for SortedMap (among other things), we aren't afforded the same luxury with NavigableMap. Related questions Writing a synchronized thread-safety wrapper for NavigableMap On API providing only exclusive upper bound range queries Does this highlight a problem with exclusive upper bound range queries? How were inclusive range queries done in the past when exclusive upper bound is the only available functionality?

    Read the article

  • LibreOffice UNO Java API: how to open a document, execute a macro and close it?

    - by MarcoS
    I'm working on LibreOffice server-side: on the server I run soffice --accept=... Then I use Java LibreOffice client API's to apply a macro on a document (calc or writer). The java execution does not give any error, but I do not get the job done (macro code is executed, but it's effects are not in the output file). More, after macro script is invoked, the Basic debugger window appears, apparently stopped on the first line of my macro; F5 does not restart it... This is the relevant code I'm using: try { XComponentContext xLocalContext = Bootstrap.createInitialComponentContext(null); System.out.println("xLocalContext"); XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); System.out.println("xLocalServiceManager"); Object urlResolver = xLocalServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", xLocalContext); System.out.println("urlResolver"); XUnoUrlResolver xUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, urlResolver); System.out.println("xUrlResolve"); try { String uno = "uno:" + unoMode + ",host=" + unoHost + ",port=" + unoPort + ";" + unoProtocol + ";" + unoObjectName; Object rInitialObject = xUrlResolver.resolve(uno); System.out.println("rInitialObject"); if (null != rInitialObject) { XMultiComponentFactory xOfficeFactory = (XMultiComponentFactory) UnoRuntime.queryInterface( XMultiComponentFactory.class, rInitialObject); System.out.println("xOfficeFactory"); Object desktop = xOfficeFactory.createInstanceWithContext("com.sun.star.frame.Desktop", xLocalContext); System.out.println("desktop"); XComponentLoader xComponentLoader = (XComponentLoader)UnoRuntime.queryInterface( XComponentLoader.class, desktop); System.out.println("xComponentLoader"); PropertyValue[] loadProps = new PropertyValue[3]; loadProps[0] = new PropertyValue(); loadProps[0].Name = "Hidden"; loadProps[0].Value = Boolean.TRUE; loadProps[1] = new PropertyValue(); loadProps[1].Name = "ReadOnly"; loadProps[1].Value = Boolean.FALSE; loadProps[2] = new PropertyValue(); loadProps[2].Name = "MacroExecutionMode"; loadProps[2].Value = new Short(com.sun.star.document.MacroExecMode.ALWAYS_EXECUTE_NO_WARN); try { XComponent xComponent = xComponentLoader.loadComponentFromURL("file:///" + inputFile, "_blank", 0, loadProps); System.out.println("xComponent from " + inputFile); String macroName = "Standard.Module1.MYMACRONAME?language=Basic&location=application"; Object[] aParams = null; XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent); XScriptProvider xScriptProvider = xScriptPS.getScriptProvider(); XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+macroName); short[][] aOutParamIndex = new short[1][1]; Object[][] aOutParam = new Object[1][1]; @SuppressWarnings("unused") Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam); System.out.println("xScript invoke macro" + macroName); XStorable xStore = (XStorable)UnoRuntime.queryInterface(XStorable.class, xComponent); System.out.println("xStore"); if (outputFileType.equalsIgnoreCase("pdf")) { System.out.println("writer_pdf_Export"); loadProps[0].Name = "FilterName"; loadProps[0].Value = "writer_pdf_Export"; } xStore.storeToURL("file:///" + outputFile, loadProps); System.out.println("storeToURL to file " + outputFile); xComponent.dispose(); xComponentLoader = null; rInitialObject = null; System.out.println("done."); System.exit(0); } catch(IllegalArgumentException e) { System.err.println("Error: Can't load component from url " + inputFile); } } else { System.err.println("Error: Unknown initial object name at server side"); } } catch(NoConnectException e) { System.err.println("Error: Server Connection refused: check server is listening..."); } } catch(java.lang.Exception e) { System.err.println("Error: Java exception:"); e.printStackTrace(); }

    Read the article

  • What is "read operations inside transactions can't allow failover" ?

    - by Kenyth
    From time to time I got the following exception message on GAE for my GAE/J app. I searched with Google, no relevant results were found. Does anyone know about this? Thanks in advance for any response! The exception message is as below: Nested in org.springframework.orm.jpa.JpaSystemException: Illegal argument; nested exception is javax.persistence.PersistenceException: Illegal argument: java.lang.IllegalArgumentException: read operations inside transactions can't allow failover at com.google.appengine.api.datastore.DatastoreApiHelper.translateError(DatastoreApiHelper.java: 34) at com.google.appengine.api.datastore.DatastoreApiHelper.makeSyncCall(DatastoreApiHelper.java: 67) at com.google.appengine.api.datastore.DatastoreServiceImpl $1.run(DatastoreServiceImpl.java:128) at com.google.appengine.api.datastore.TransactionRunner.runInTransaction(TransactionRunner.java: 30) at com.google.appengine.api.datastore.DatastoreServiceImpl.get(DatastoreServiceImpl.java: 111) at com.google.appengine.api.datastore.DatastoreServiceImpl.get(DatastoreServiceImpl.java: 84) at com.google.appengine.api.datastore.DatastoreServiceImpl.get(DatastoreServiceImpl.java: 77) at org.datanucleus.store.appengine.RuntimeExceptionWrappingDatastoreService.get(RuntimeExceptionWrappingDatastoreService.java: 53) at org.datanucleus.store.appengine.DatastorePersistenceHandler.get(DatastorePersistenceHandler.java: 94) at org.datanucleus.store.appengine.DatastorePersistenceHandler.get(DatastorePersistenceHandler.java: 106) at org.datanucleus.store.appengine.DatastorePersistenceHandler.fetchObject(DatastorePersistenceHandler.java: 464) at org.datanucleus.state.JDOStateManagerImpl.loadUnloadedFieldsInFetchPlan(JDOStateManagerImpl.java: 1627) at org.datanucleus.state.JDOStateManagerImpl.loadFieldsInFetchPlan(JDOStateManagerImpl.java: 1603) at org.datanucleus.ObjectManagerImpl.performDetachAllOnCommitPreparation(ObjectManagerImpl.java: 3192) at org.datanucleus.ObjectManagerImpl.preCommit(ObjectManagerImpl.java: 2931) at org.datanucleus.TransactionImpl.internalPreCommit(TransactionImpl.java: 369) at org.datanucleus.TransactionImpl.commit(TransactionImpl.java:256) at org.datanucleus.jpa.EntityTransactionImpl.commit(EntityTransactionImpl.java: 104) at org.datanucleus.store.appengine.jpa.DatastoreEntityTransactionImpl.commit(DatastoreEntityTransactionImpl.java: 55) at name.kenyth.playtweets.service.Tx.run(Tx.java:39) at name.kenyth.playtweets.web.controller.TwitterApiController.persistStatus(TwitterApiController.java: 309) at name.kenyth.playtweets.web.controller.TwitterApiController.processStatusesForWebCall(TwitterApiController.java: 271) at name.kenyth.playtweets.web.controller.TwitterApiController.getHomeTimelineUpdates_aroundBody0(TwitterApiController.java: 247) at name.kenyth.playtweets.web.controller.TwitterApiController $AjcClosure1.run(TwitterApiController.java:1) at name.kenyth.playtweets.web.refine.AuthenticationEnforcement.ajc $around$name_kenyth_playtweets_web_refine_AuthenticationEnforcement $2$439820b7proceed(AuthenticationEnforcement.aj:1) at name.kenyth.playtweets.web.refine.AuthenticationEnforcement.ajc $around$name_kenyth_playtweets_web_refine_AuthenticationEnforcement $2$439820b7(AuthenticationEnforcement.aj:168) at name.kenyth.playtweets.web.controller.TwitterApiController.getHomeTimelineUpdates(TwitterApiController.java: 129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Method.java:43) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java: 710) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java: 167) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java: 414) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java: 402) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java: 771) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java: 716) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java: 647) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java: 552) at javax.servlet.http.HttpServlet.service(HttpServlet.java:693) at javax.servlet.http.HttpServlet.service(HttpServlet.java:806) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java: 511) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java: 390) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java: 216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java: 182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java: 765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java: 418) at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:327) at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:126) at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java: 195) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java: 159) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java: 141) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java: 90) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java: 417) at org.mortbay.jetty.servlet.ServletHandler $CachedChain.doFilter(ServletHandler.java:1157) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java: 71) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java: 76) at org.mortbay.jetty.servlet.ServletHandler $CachedChain.doFilter(ServletHandler.java:1157) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java: 88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java: 76) at org.mortbay.jetty.servlet.ServletHandler $CachedChain.doFilter(ServletHandler.java:1157) at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java: 97) at org.mortbay.jetty.servlet.ServletHandler $CachedChain.doFilter(ServletHandler.java:1157) at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java: 35) at org.mortbay.jetty.servlet.ServletHandler $CachedChain.doFilter(ServletHandler.java:1157) at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java: 43) at org.mortbay.jetty.servlet.ServletHandler $CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java: 388) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java: 216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java: 182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java: 765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java: 418) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java: 238) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java: 152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java: 542) at org.mortbay.jetty.HttpConnection $RequestHandler.headerComplete(HttpConnection.java:923) at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java: 76) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java: 135) at com.google.apphosting.runtime.JavaRuntime.handleRequest(JavaRuntime.java: 250) at com.google.apphosting.base.RuntimePb$EvaluationRuntime $6.handleBlockingRequest(RuntimePb.java:5838) at com.google.apphosting.base.RuntimePb$EvaluationRuntime $6.handleBlockingRequest(RuntimePb.java:5836) at com.google.net.rpc.impl.BlockingApplicationHandler.handleRequest(BlockingApplicationHandler.java: 24) at com.google.net.rpc.impl.RpcUtil.runRpcInApplication

    Read the article

  • Forcing a transaction to rollback on validation errors in Seam

    - by Chris Williams
    Quick version: We're looking for a way to force a transaction to rollback when specific situations occur during the execution of a method on a backing bean but we'd like the rollback to happen without having to show the user a generic 500 error page. Instead, we'd like the user to see the form she just submitted and a FacesMessage that indicates what the problem was. Long version: We've got a few backing beans that use components to perform a few related operations in the database (using JPA/Hibernate). During the process, an error can occur after some of the database operations have happened. This could be for a few different reasons but for this question, let's assume there's been a validation error that is detected after some DB writes have happened that weren't detectible before the writes occurred. When this happens, we'd like to make sure all of the db changes up to this point will be rolled back. Seam can deal with this because if you throw a RuntimeException out of the current FacesRequest, Seam will rollback the current transaction. The problem with this is that the user is shown a generic error page. In our case, we'd actually like the user to be shown the page she was on with a descriptive message about what went wrong, and have the opportunity to correct the bad input that caused the problem. The solution we've come up with is to throw an Exception from the component that discovers the validation problem with the annotation: @ApplicationException( rollback = true ) Then our backing bean can catch this exception, assume the component that threw it has published the appropriate FacesMessage, and simply return null to take the user back to the input page with the error displayed. The ApplicationException annotation tells Seam to rollback the transaction and we're not showing the user a generic error page. This worked well for the first place we used it that happened to only be doing inserts. The second place we tried to use it, we have to delete something during the process. In this second case, everything works if there's no validation error. If a validation error does happen, the rollback Exception is thrown and the transaction is marked for rollback. Even if no database modifications have happened to be rolled back, when the user fixes the bad data and re-submits the page, we're getting: java.lang.IllegalArgumentException: Removing a detached instance The detached instance is lazily loaded from another object (there's a many to one relationship). That parent object is loaded when the backing bean is instantiated. Because the transaction was rolled back after the validation error, the object is now detached. Our next step was to change this page from conversation scope to page scope. When we did this, Seam can't even render the page after the validation error because our page has to hit the DB to render and the transaction has been marked for rollback. So my question is: how are other people dealing with handling errors cleanly and properly managing transactions at the same time? Better yet, I'd love to be able to use everything we have now if someone can spot something I'm doing wrong that would be relatively easy to fix. I've read the Seam Framework article on Unified error page and exception handling but this is geared more towards more generic errors your application might encounter.

    Read the article

  • Tomcat v7.0 failed to start on Eclipse

    - by Questions
    Whenever I am running a program on Eclipse, my tomcat is failing to start. I get a dialog box stating this message Server Tomcat v7.0 Server at localhost failed to start. In the console, I am getting this messages Nov 17, 2011 11:56:04 AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:/Program Files/Java/jre6/lib/i386;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Java\jdk1.6.0_01\bin;C:\Program Files\Java\jre1.6.0_01\bin;C:\ILOG\CPLEX_Studio_Preview122\opl\bin\x86_win32;C:\ILOG\CPLEX_Studio_Preview122\opl\oplide\;C:\ILOG\CPLEX_Studio_Preview122\cplex\bin\x86_win32;C:\ILOG\CPLEX_Studio_Preview122\cpoptimizer\bin\x86_win32;;D:\JSP_Setup\eclipse-jee-helios-SR2-win32\eclipse;;. Nov 17, 2011 11:56:04 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:servletConfigTest' did not find a matching property. Nov 17, 2011 11:56:04 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:BeerAdvice3' did not find a matching property. Nov 17, 2011 11:56:04 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:BeerAdvice1' did not find a matching property. Nov 17, 2011 11:56:05 AM org.apache.coyote.http11.Http11Protocol init INFO: Initializing Coyote HTTP/1.1 on http-8080 Nov 17, 2011 11:56:05 AM org.apache.coyote.ajp.AjpProtocol init INFO: Initializing Coyote AJP/1.3 on ajp-8009 Nov 17, 2011 11:56:05 AM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 682 ms Nov 17, 2011 11:56:05 AM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Nov 17, 2011 11:56:05 AM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.2 java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415) Caused by: java.lang.IllegalArgumentException: Invalid <url-pattern> entry_checking in servlet mapping at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:2823) at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:2799) at org.apache.catalina.deploy.WebXml.configureContext(WebXml.java:1278) at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1255) at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:313) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4667) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:988) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:771) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:988) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:427) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:649) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139) at org.apache.catalina.startup.Catalina.start(Catalina.java:585) ... 6 more I had run the code previously, but now it is giving this problems. Also, I went through this post http://forums.opensuse.org/applications/391114-tomcat6-eclipse-not-working.html But is not helping me. Please help at the earliest.

    Read the article

  • Spring Security and the Synchronizer Token J2EE pattern, problem when authentication fails.

    - by dfuse
    Hey, we are using Spring Security 2.0.4. We have a TransactionTokenBean which generates a unique token each POST, the bean is session scoped. The token is used for the duplicate form submission problem (and security). The TransactionTokenBean is called from a Servlet filter. Our problem is the following, after a session timeout occured, when you do a POST in the application Spring Security redirects to the logon page, saving the original request. After logging on again the TransactionTokenBean is created again, since it is session scoped, but then Spring forwards to the originally accessed url, also sending the token that was generated at that time. Since the TransactionTokenBean is created again, the tokens do not match and our filter throws an Exception. I don't quite know how to handle this elegantly, (or for that matter, I can't even fix it with a hack), any ideas? This is the code of the TransactionTokenBean: public class TransactionTokenBean implements Serializable { public static final int TOKEN_LENGTH = 8; private RandomizerBean randomizer; private transient Logger logger; private String expectedToken; public String getUniqueToken() { return expectedToken; } public void init() { resetUniqueToken(); } public final void verifyAndResetUniqueToken(String actualToken) { verifyUniqueToken(actualToken); resetUniqueToken(); } public void resetUniqueToken() { expectedToken = randomizer.getRandomString(TOKEN_LENGTH, RandomizerBean.ALPHANUMERICS); getLogger().debug("reset token to: " + expectedToken); } public void verifyUniqueToken(String actualToken) { if (getLogger().isDebugEnabled()) { getLogger().debug("verifying token. expected=" + expectedToken + ", actual=" + actualToken); } if (expectedToken == null || actualToken == null || !isValidToken(actualToken)) { throw new IllegalArgumentException("missing or invalid transaction token"); } if (!expectedToken.equals(actualToken)) { throw new InvalidTokenException(); } } private boolean isValidToken(String actualToken) { return StringUtils.isAlphanumeric(actualToken); } public void setRandomizer(RandomizerBean randomizer) { this.randomizer = randomizer; } private Logger getLogger() { if (logger == null) { logger = Logger.getLogger(TransactionTokenBean.class); } return logger; } } and this is the Servlet filter (ignore the Ajax stuff): public class SecurityFilter implements Filter { static final String AJAX_TOKEN_PARAM = "ATXTOKEN"; static final String TOKEN_PARAM = "TXTOKEN"; private WebApplicationContext webApplicationContext; private Logger logger = Logger.getLogger(SecurityFilter.class); public void init(FilterConfig config) { setWebApplicationContext(WebApplicationContextUtils.getWebApplicationContext(config.getServletContext())); } public void destroy() { } public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; if (isPostRequest(request)) { if (isAjaxRequest(request)) { log("verifying token for AJAX request " + request.getRequestURI()); getTransactionTokenBean(true).verifyUniqueToken(request.getParameter(AJAX_TOKEN_PARAM)); } else { log("verifying and resetting token for non-AJAX request " + request.getRequestURI()); getTransactionTokenBean(false).verifyAndResetUniqueToken(request.getParameter(TOKEN_PARAM)); } } chain.doFilter(request, response); } private void log(String line) { if (logger.isDebugEnabled()) { logger.debug(line); } } private boolean isPostRequest(HttpServletRequest request) { return "POST".equals(request.getMethod().toUpperCase()); } private boolean isAjaxRequest(HttpServletRequest request) { return request.getParameter("AJAXREQUEST") != null; } private TransactionTokenBean getTransactionTokenBean(boolean ajax) { return (TransactionTokenBean) webApplicationContext.getBean(ajax ? "ajaxTransactionTokenBean" : "transactionTokenBean"); } void setWebApplicationContext(WebApplicationContext context) { this.webApplicationContext = context; } }

    Read the article

  • Configurable Values in Enum

    - by Omer Akhter
    I often use this design in my code to maintain configurable values. Consider this code: public enum Options { REGEX_STRING("Some Regex"), REGEX_PATTERN(Pattern.compile(REGEX_STRING.getString()), false), THREAD_COUNT(2), OPTIONS_PATH("options.config", false), DEBUG(true), ALWAYS_SAVE_OPTIONS(true), THREAD_WAIT_MILLIS(1000); Object value; boolean saveValue = true; private Options(Object value) { this.value = value; } private Options(Object value, boolean saveValue) { this.value = value; this.saveValue = saveValue; } public void setValue(Object value) { this.value = value; } public Object getValue() { return value; } public String getString() { return value.toString(); } public boolean getBoolean() { Boolean booleanValue = (value instanceof Boolean) ? (Boolean) value : null; if (value == null) { try { booleanValue = Boolean.valueOf(value.toString()); } catch (Throwable t) { } } // We want a NullPointerException here return booleanValue.booleanValue(); } public int getInteger() { Integer integerValue = (value instanceof Number) ? ((Number) value).intValue() : null; if (integerValue == null) { try { integerValue = Integer.valueOf(value.toString()); } catch (Throwable t) { } } return integerValue.intValue(); } public float getFloat() { Float floatValue = (value instanceof Number) ? ((Number) value).floatValue() : null; if (floatValue == null) { try { floatValue = Float.valueOf(value.toString()); } catch (Throwable t) { } } return floatValue.floatValue(); } public static void saveToFile(String path) throws IOException { FileWriter fw = new FileWriter(path); Properties properties = new Properties(); for (Options option : Options.values()) { if (option.saveValue) { properties.setProperty(option.name(), option.getString()); } } if (DEBUG.getBoolean()) { properties.list(System.out); } properties.store(fw, null); } public static void loadFromFile(String path) throws IOException { FileReader fr = new FileReader(path); Properties properties = new Properties(); properties.load(fr); if (DEBUG.getBoolean()) { properties.list(System.out); } Object value = null; for (Options option : Options.values()) { if (option.saveValue) { Class<?> clazz = option.value.getClass(); try { if (String.class.equals(clazz)) { value = properties.getProperty(option.name()); } else { value = clazz.getConstructor(String.class).newInstance(properties.getProperty(option.name())); } } catch (NoSuchMethodException ex) { Debug.log(ex); } catch (InstantiationException ex) { Debug.log(ex); } catch (IllegalAccessException ex) { Debug.log(ex); } catch (IllegalArgumentException ex) { Debug.log(ex); } catch (InvocationTargetException ex) { Debug.log(ex); } if (value != null) { option.setValue(value); } } } } } This way, I can save and retrieve values from files easily. The problem is that I don't want to repeat this code everywhere. Like as we know, enums can't be extended; so wherever I use this, I have to put all these methods there. I want only to declare the values and that if they should be persisted. No method definitions each time; any ideas?

    Read the article

  • My IDE is showing "undeclared FileNotFoundException must be caught or thrown"

    - by Dan Czarnecki
    I am having the following issue above. I have tried actually putting a try-catch statement into the code as you will see below, but I can't get the compiler to get past that. import java.io.*; public class DirectoryStatistics extends DirectorySize { /* Dan Czarnecki October 24, 2013 Class variables: private File directory A File object that holds the pathname of the directory to look in private long sizeInBytes A variable of type long that holds the size of a file/directory (in bytes) private long fileCount A variable of type long that holds the number of files in a directory Constructors: public DirectoryStatistics(File startingDirectory) throws FileNotFoundException Creates a DirectoryStatistics object, given a pathname (inherited from DirectorySize class), and has 3 instance variables that hold the directory to search in, the size of each file (in bytes), and the number of files within the directory Modification history: October 24, 2013 Original version of class */ private File directory; private long sizeInBytes; private long fileCount; public DirectoryStatistics(File startingDirectory) throws FileNotFoundException { super(startingDirectory); try { if(directory == null) { throw new IllegalArgumentException("null input"); } if(directory.isDirectory() == false) { throw new FileNotFoundException("the following input is not a directory!"); } } catch(IOException ioe) { System.out.println("You have not entered a directory. Please try again."); } } public File getDirectory() { return this.directory; } public long getSizeInBytes() { return this.sizeInBytes; } public long getFileCount() { return this.fileCount; } public long setFileCount(long size) { fileCount = size; return size; } public long setSizeInBytes(long size) { sizeInBytes = size; return size; } public void incrementFileCount() { fileCount = fileCount + 1; } public void addToSizeInBytes(long addend) { sizeInBytes = sizeInBytes + addend; } public String toString() { return "Directory" + this.directory + "Size (in bytes) " + this.sizeInBytes + "Number of files: " + this.fileCount; } public int hashCode() { return this.directory.hashCode(); } public boolean equals(DirectoryStatistics other) { return this.equals(other); } } import java.io.*; import java.util.*; public class DirectorySize extends DirectoryProcessor { /* Dan Czarnecki October 17, 2013 Class variables: private Vector<Long> directorySizeList Variable of type Vector<Long> that holds the total file size of files in that directory as well as files within folders of that directory private Vector<File> currentFile Variable of type Vector<File> that holds the parent directory Constructors: public DirectorySize(File startingDirectory) throws FileNotFoundException Creates a DirectorySize object, takes in a pathname (inherited from DirectoryProcessor class, and has a single vector of a DirectoryStatistics object to hold the files and folders within a directory Modification History October 17, 2013 Original version of class Implemented run() and processFile() methods */ private Vector<DirectoryStatistics> directory; /* private Vector<Long> directorySizeList; private Vector<File> currentFile; */ public DirectorySize(File startingDirectory) throws FileNotFoundException { super(startingDirectory); directory = new Vector<DirectoryStatistics>(); } public void processFile(File file) { DirectoryStatistics parent; int index; File parentFile; System.out.println(file.getName()); System.out.println(file.getParent()); parentFile = file.getParentFile(); parent = new DirectoryStatistics(parentFile); System.out.println(parent); parent.equals(parent); index = directory.indexOf(parent); if(index == 0) { directory.elementAt(index).addToSizeInBytes(file.length()); directory.elementAt(index).incrementFileCount(); } if(index < 0) { directory.addElement(parent); directory.lastElement().setSizeInBytes(file.length()); directory.lastElement().incrementFileCount(); } Could someone tell me why I'm getting this issue?

    Read the article

  • Unable to edit a database row from JSF

    - by user1924104
    Hi guys i have a data table in JSF which displays all of the contents of my database table, it displays it fine, i also have a delete function that can successfully delete from the database fine and updates the data table fine however when i try to update the database i get the error java.lang.IllegalArgumentException: Cannot convert richard.test.User@129d62a7 of type class richard.test.User to long below is the code that i have been using to delete the rows in the database that is working fine : public void delete(long userID) { PreparedStatement ps = null; Connection con = null; if (userID != 0) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); String sql = "DELETE FROM user1 WHERE userId=" + userID; ps = con.prepareStatement(sql); int i = ps.executeUpdate(); if (i > 0) { System.out.println("Row deleted successfully"); } } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } } } i simply wanted to edit the above code so it would update the records instead of deleting them so i edited it to look like : public void editData(long userID) { PreparedStatement ps = null; Connection con = null; if (userID != 0) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); String sql = "UPDATE user1 set name = '"+name+"', email = '"+ email +"', address = '"+address+"' WHERE userId=" + userID; ps = con.prepareStatement(sql); int i = ps.executeUpdate(); if (i > 0) { System.out.println("Row updated successfully"); } } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } } } and the xhmtl is : <p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}" paginator="true" rows="10" editable="true" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15"> <p:column> <f:facet name="header"> User ID </f:facet> #{u.userID} </p:column> <p:column> <f:facet name="header"> Name </f:facet> #{u.name} </p:column> <p:column> <f:facet name="header"> Email </f:facet> #{u.email} </p:column> <p:column> <f:facet name="header"> Address </f:facet> #{u.address} </p:column> <p:column> <f:facet name="header"> Created Date </f:facet> #{u.created_date} </p:column> <p:column> <f:facet name="header"> Delete </f:facet> <h:commandButton value="Delete" action="#{user.delete(u.userID)}" /> </p:column> <p:column> <f:facet name="header"> Delete </f:facet> <h:commandButton value="Edit" action="#{user.editData(u)}" /> </p:column> currently when you press the edit button it will only update it with the same values as i haven't yet managed to get the datatable to be editable with the database, i have seen a few examples with an array list where the data table gets its values from but never a database so if you have any advice on this too it would be great thanks

    Read the article

  • sherlock actionbar menu

    - by user1647443
    I am trying to setup a menu programatically and my method gets com.actionbarsherlock.view.Menu menu as a parameter. As I want to change the styling of the menu item I am trying to setup a SpannableString spannable and pass it to add. menu.add(0, MENU_ABOUT, 0, spannable); This is causing a crash only in ICS when I cick that menu item. Any ideas if I am missing something. Thanks Here is the code I am trying and it crashes when I run the app and select "About Application". FYI, I am using SpannableString because I want to add some styling and color to the menu item. The crash does NOT happen if I use a regular string, but then I cant do styling public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) { SpannableString spannable = new SpannableString("About Application"); menu.add(0, MENU_ABOUT, 0, spannable); return true; } Here is the stack trace: 09-05 02:25:32.849: E/AndroidRuntime(684): FATAL EXCEPTION: main 09-05 02:25:32.849: E/AndroidRuntime(684): java.lang.IllegalArgumentException: Invalid payload item type 09-05 02:25:32.849: E/AndroidRuntime(684): at android.util.EventLog.writeEvent(Native Method) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.app.Activity.onMenuItemSelected(Activity.java:2501) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:351) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.widget.AdapterView.performItemClick(AdapterView.java:292) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.widget.AbsListView.performItemClick(AbsListView.java:1058) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.widget.AbsListView.onTouchEvent(AbsListView.java:3180) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.View.dispatchTouchEvent(View.java:5541) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1951) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1712) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1860) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.View.dispatchPointerEvent(View.java:5721) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:2890) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2466) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewRootImpl.processInputEvents(ViewRootImpl.java:845) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2475) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.os.Handler.dispatchMessage(Handler.java:99) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.os.Looper.loop(Looper.java:137) 09-05 02:25:32.849: E/AndroidRuntime(684): at android.app.ActivityThread.main(ActivityThread.java:4424) 09-05 02:25:32.849: E/AndroidRuntime(684): at java.lang.reflect.Method.invokeNative(Native Method) 09-05 02:25:32.849: E/AndroidRuntime(684): at java.lang.reflect.Method.invoke(Method.java:511) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 09-05 02:25:32.849: E/AndroidRuntime(684): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 09-05 02:25:32.849: E/AndroidRuntime(684): at dalvik.system.NativeStart.main(Native Method) Thanks

    Read the article

  • UndoRedo on Nodes

    - by Geertjan
    When a change is made to the property in the Properties Window, below, the undo/redo functionality becomes enabled: When undo/redo are invoked, e.g., via the buttons in the toolbar, the display name of the node changes accordingly. The only problem I have is that the buttons only become enabled when the Person Window is selected, not when the Properties Window is selected, which would be desirable. Here's the Person object: public class Person implements PropertyChangeListener {     private String name;     public static final String PROP_NAME = "name";     public Person(String name) {         this.name = name;     }     public String getName() {         return name;     }     public void setName(String name) {         String oldName = this.name;         this.name = name;         propertyChangeSupport.firePropertyChange(PROP_NAME, oldName, name);     }     private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);     public void addPropertyChangeListener(PropertyChangeListener listener) {         propertyChangeSupport.addPropertyChangeListener(listener);     }     public void removePropertyChangeListener(PropertyChangeListener listener) {         propertyChangeSupport.removePropertyChangeListener(listener);     }     @Override     public void propertyChange(PropertyChangeEvent evt) {         propertyChangeSupport.firePropertyChange(evt);     } } And here's the Node with UndoRedo enablement: public class PersonNode extends AbstractNode implements UndoRedo.Provider, PropertyChangeListener {     private UndoRedo.Manager manager = new UndoRedo.Manager();     private boolean undoRedoEvent;     public PersonNode(Person person) {         super(Children.LEAF, Lookups.singleton(person));         person.addPropertyChangeListener(this);         setDisplayName(person.getName());     }     @Override     protected Sheet createSheet() {         Sheet sheet = Sheet.createDefault();         Sheet.Set set = Sheet.createPropertiesSet();         set.put(new NameProperty(getLookup().lookup(Person.class)));         sheet.put(set);         return sheet;     }     @Override     public void propertyChange(PropertyChangeEvent evt) {         if (evt.getPropertyName().equals(Person.PROP_NAME)) {             firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());         }     }     public void fireUndoableEvent(String property, Person source, Object oldValue, Object newValue) {         manager.addEdit(new MyAbstractUndoableEdit(source, oldValue, newValue));     }     @Override     public UndoRedo getUndoRedo() {         return manager;     }     @Override     public String getDisplayName() {         Person p = getLookup().lookup(Person.class);         if (p != null) {             return p.getName();         }         return super.getDisplayName();     }     private class NameProperty extends PropertySupport.ReadWrite<String> {         private Person p;         public NameProperty(Person p) {             super("name", String.class, "Name", "Name of Person");             this.p = p;         }         @Override         public String getValue() throws IllegalAccessException, InvocationTargetException {             return p.getName();         }         @Override         public void setValue(String newValue) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {             String oldValue = p.getName();             p.setName(newValue);             if (!undoRedoEvent) {                 fireUndoableEvent("name", p, oldValue, newValue);                 fireDisplayNameChange(oldValue, newValue);             }         }     }     class MyAbstractUndoableEdit extends AbstractUndoableEdit {         private final String oldValue;         private final String newValue;         private final Person source;         private MyAbstractUndoableEdit(Person source, Object oldValue, Object newValue) {             this.oldValue = oldValue.toString();             this.newValue = newValue.toString();             this.source = source;         }         @Override         public boolean canRedo() {             return true;         }         @Override         public boolean canUndo() {             return true;         }         @Override         public void undo() throws CannotUndoException {             undoRedoEvent = true;             source.setName(oldValue.toString());             fireDisplayNameChange(oldValue, newValue);             undoRedoEvent = false;         }         @Override         public void redo() throws CannotUndoException {             undoRedoEvent = true;             source.setName(newValue.toString());             fireDisplayNameChange(oldValue, newValue);             undoRedoEvent = false;         }     } } Does anyone out there know how to have the Undo/Redo functionality enabled when the Properties Window is selected?

    Read the article

  • Java Animation Memory Overload [on hold]

    - by user2425429
    I need a way to reduce the memory usage of these programs while keeping the functionality. Every time I add 50 milliseconds or so to the set&display loop in AnimationTest1, it throws an out of memory error. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; //set&display loop while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Animation Color [on hold]

    - by user2425429
    I'm having problems in my java program for animation. I'm trying to draw a hexagon with a shape similar to that of a trapezoid. Then, I'm making it move to the right for a certain amount of time (DEMO_TIME). Animation and ScreenManager are "API" classes, and AnimationTest1 is a demo. In my test program, it runs with a black screen and white stroke color. I'd like to know why this happened and how to fix it. I'm a beginner, so I apologize for this question being stupid to all you game programmers. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • How to handle screen orientation change when progress dialog and background thread active?

    - by Heikki Toivonen
    My program does some network activity in a background thread. Before starting, it pops up a progress dialog. The dialog is dismissed on the handler. This all works fine, except when screen orientation changes while the dialog is up (and the background thread is going). At this point the app either crashes, or deadlocks, or gets into a weird stage where the app does not work at all until all the threads have been killed. How can I handle the screen orientation change gracefully? The sample code below matches roughly what my real program does: public class MyAct extends Activity implements Runnable { public ProgressDialog mProgress; // UI has a button that when pressed calls send public void send() { mProgress = ProgressDialog.show(this, "Please wait", "Please wait", true, true); Thread thread = new Thread(this); thread.start(); } public void run() { Thread.sleep(10000); Message msg = new Message(); mHandler.sendMessage(msg); } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgress.dismiss(); } }; } Stack: E/WindowManager( 244): Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here E/WindowManager( 244): android.view.WindowLeaked: Activity MyAct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@433b7150 that was originally added here E/WindowManager( 244): at android.view.ViewRoot.<init>(ViewRoot.java:178) E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:147) E/WindowManager( 244): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:90) E/WindowManager( 244): at android.view.Window$LocalWindowManager.addView(Window.java:393) E/WindowManager( 244): at android.app.Dialog.show(Dialog.java:212) E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:103) E/WindowManager( 244): at android.app.ProgressDialog.show(ProgressDialog.java:91) E/WindowManager( 244): at MyAct.send(MyAct.java:294) E/WindowManager( 244): at MyAct$4.onClick(MyAct.java:174) E/WindowManager( 244): at android.view.View.performClick(View.java:2129) E/WindowManager( 244): at android.view.View.onTouchEvent(View.java:3543) E/WindowManager( 244): at android.widget.TextView.onTouchEvent(TextView.java:4664) E/WindowManager( 244): at android.view.View.dispatchTouchEvent(View.java:3198) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857) E/WindowManager( 244): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1593) E/WindowManager( 244): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1089) E/WindowManager( 244): at android.app.Activity.dispatchTouchEvent(Activity.java:1871) E/WindowManager( 244): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1577) E/WindowManager( 244): at android.view.ViewRoot.handleMessage(ViewRoot.java:1140) E/WindowManager( 244): at android.os.Handler.dispatchMessage(Handler.java:88) E/WindowManager( 244): at android.os.Looper.loop(Looper.java:123) E/WindowManager( 244): at android.app.ActivityThread.main(ActivityThread.java:3739) E/WindowManager( 244): at java.lang.reflect.Method.invokeNative(Native Method) E/WindowManager( 244): at java.lang.reflect.Method.invoke(Method.java:515) E/WindowManager( 244): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) E/WindowManager( 244): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497) E/WindowManager( 244): at dalvik.system.NativeStart.main(Native Method) and: W/dalvikvm( 244): threadid=3: thread exiting with uncaught exception (group=0x4000fe68) E/AndroidRuntime( 244): Uncaught handler: thread main exiting due to uncaught exception E/AndroidRuntime( 244): java.lang.IllegalArgumentException: View not attached to window manager E/AndroidRuntime( 244): at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:331) E/AndroidRuntime( 244): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200) E/AndroidRuntime( 244): at android.view.Window$LocalWindowManager.removeView(Window.java:401) E/AndroidRuntime( 244): at android.app.Dialog.dismissDialog(Dialog.java:249) E/AndroidRuntime( 244): at android.app.Dialog.access$000(Dialog.java:59) E/AndroidRuntime( 244): at android.app.Dialog$1.run(Dialog.java:93) E/AndroidRuntime( 244): at android.app.Dialog.dismiss(Dialog.java:233) E/AndroidRuntime( 244): at MyAct$1.handleMessage(MyAct.java:321) E/AndroidRuntime( 244): at android.os.Handler.dispatchMessage(Handler.java:88) E/AndroidRuntime( 244): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime( 244): at android.app.ActivityThread.main(ActivityThread.java:3739) E/AndroidRuntime( 244): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 244): at java.lang.reflect.Method.invoke(Method.java:515) E/AndroidRuntime( 244): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) E/AndroidRuntime( 244): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497) E/AndroidRuntime( 244): at dalvik.system.NativeStart.main(Native Method) I/Process ( 46): Sending signal. PID: 244 SIG: 3 I/dalvikvm( 244): threadid=7: reacting to signal 3 I/dalvikvm( 244): Wrote stack trace to '/data/anr/traces.txt' I/Process ( 244): Sending signal. PID: 244 SIG: 9 I/ActivityManager( 46): Process MyAct (pid 244) has died. I have tried to dismiss the progress dialog in onSaveInstanceState, but that just prevents an immediate crash. The background thread is still going, and the UI is in partially drawn state. Need to kill the whole app before it starts working again.

    Read the article

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