Search Results

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

Page 5/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Setting the a caret in an JEditor Pane causes an exception.

    - by Elliott
    I have a JeditorPane which has some text in HTML format. When I execute the following command int len = editorPane.getText().length(); The value for len is 7473. But then I try to do the following: editorPane.setCaretPosition(4995); And I get the following exception: java.lang.IllegalArgumentException: bad position: 4995 My understanding is that I should only get this exception if the position at which I'm trying to set the caret is less than 0 or greater than the text length. It is neither. How can this be. Thank you, Elliott

    Read the article

  • How to work with varargs and reflection

    - by PeterMmm
    Simple question, how make this code working ? public class T { public static void main(String[] args) throws Exception { new T().m(); } public // as mentioned by Bozho void foo(String... s) { System.err.println(s[0]); } void m() throws Exception { String[] a = new String[]{"hello", "kitty"}; System.err.println(a.getClass()); Method m = getClass().getMethod("foo", a.getClass()); m.invoke(this, (Object[]) a); } } Output: class [Ljava.lang.String; Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments 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)

    Read the article

  • Throwing exception vs returning null value with switch statement

    - by Greg
    So I have function that formats a date to coerce to given enum DateType{CURRENT, START, END} what would be the best way to handling return value with cases that use switch statement public static String format(Date date, DateType datetype) { ..validation checks switch(datetype){ case CURRENT:{ return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss"); } ... default:throw new ("Something strange happend"); } } OR throw excpetion at the end public static String format(Date date, DateType datetype) { ..validation checks switch(datetype){ case CURRENT:{ return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss"); } ... } //It will never reach here, just to make compiler happy throw new IllegalArgumentException("Something strange happend"); } OR return null public static String format(Date date, DateType datetype) { ..validation checks switch(datetype){ case CURRENT:{ return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss"); } ... } return null; } What would be the best practice here ? Also all the enum values will be handled in the case statement

    Read the article

  • NullPointerException when linking to Service that uses ContentProvider

    - by Danny Chia
    H.i everyone, this is my first post here! Anyways, I'm trying to write a "todo list" application. It stores the data in a ContentProvider, which is accessed via a Service. However, my app crashes at launch. My code is below: Manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.examples.todolist" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="True"> <activity android:name=".ToDoList" android:label="@string/app_name" android:theme="@style/ToDoTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="TodoService"/> <provider android:name="TodoProvider" android:authorities="com.examples.provider.todolist" /> </application> <uses-sdk android:minSdkVersion="7" /> </manifest> ToDoList.java: package com.examples.todolist; import com.examples.todolist.TodoService.LocalBinder; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.ContextMenu; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class ToDoList extends Activity { static final private int ADD_NEW_TODO = Menu.FIRST; static final private int REMOVE_TODO = Menu.FIRST + 1; private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY"; private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY"; private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY"; private boolean addingNew = false; private ArrayList<ToDoItem> todoItems; private ListView myListView; private EditText myEditText; private ToDoItemAdapter aa; int entries = 0; int notifs = 0; //ToDoDBAdapter toDoDBAdapter; Cursor toDoListCursor; TodoService mService; boolean mBound = false; /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myListView = (ListView)findViewById(R.id.myListView); myEditText = (EditText)findViewById(R.id.myEditText); todoItems = new ArrayList<ToDoItem>(); int resID = R.layout.todolist_item; aa = new ToDoItemAdapter(this, resID, todoItems); myListView.setAdapter(aa); myEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { ToDoItem newItem = new ToDoItem(myEditText.getText().toString(), 0); mService.insertTask(newItem); updateArray(); myEditText.setText(""); entries++; Toast.makeText(ToDoList.this, "Entry added", Toast.LENGTH_SHORT).show(); aa.notifyDataSetChanged(); cancelAdd(); return true; } return false; } }); registerForContextMenu(myListView); restoreUIState(); populateTodoList(); } private void populateTodoList() { // Get all the todo list items from the database. toDoListCursor = mService. getAllToDoItemsCursor(); startManagingCursor(toDoListCursor); // Update the array. updateArray(); Toast.makeText(this, "Todo list retrieved", Toast.LENGTH_SHORT).show(); } private void updateArray() { toDoListCursor.requery(); todoItems.clear(); if (toDoListCursor.moveToFirst()) do { String task = toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_TASK)); long created = toDoListCursor.getLong(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_CREATION_DATE)); int taskid = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_ID)); ToDoItem newItem = new ToDoItem(task, new Date(created), taskid); todoItems.add(0, newItem); } while(toDoListCursor.moveToNext()); aa.notifyDataSetChanged(); } private void restoreUIState() { // Get the activity preferences object. SharedPreferences settings = getPreferences(0); // Read the UI state values, specifying default values. String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); // Restore the UI to the previous state. if (adding) { addNewItem(); myEditText.setText(text); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition()); super.onSaveInstanceState(outState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { int pos = -1; if (savedInstanceState != null) if (savedInstanceState.containsKey(SELECTED_INDEX_KEY)) pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1); myListView.setSelection(pos); } @Override protected void onPause() { super.onPause(); // Get the activity preferences object. SharedPreferences uiState = getPreferences(0); // Get the preferences editor. SharedPreferences.Editor editor = uiState.edit(); // Add the UI state preference values. editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString()); editor.putBoolean(ADDING_ITEM_KEY, addingNew); // Commit the preferences. editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Create and add new menu items. MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new); MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); // Assign icons itemAdd.setIcon(R.drawable.add_new_item); itemRem.setIcon(R.drawable.remove_item); // Allocate shortcuts to each of them. itemAdd.setShortcut('0', 'a'); itemRem.setShortcut('1', 'r'); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); int idx = myListView.getSelectedItemPosition(); String removeTitle = getString(addingNew ? R.string.cancel : R.string.remove); MenuItem removeItem = menu.findItem(REMOVE_TODO); removeItem.setTitle(removeTitle); removeItem.setVisible(addingNew || idx > -1); return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Selected To Do Item"); menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int index = myListView.getSelectedItemPosition(); switch (item.getItemId()) { case (REMOVE_TODO): { if (addingNew) { cancelAdd(); } else { removeItem(index); } return true; } case (ADD_NEW_TODO): { addNewItem(); return true; } } return false; } @Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); switch (item.getItemId()) { case (REMOVE_TODO): { AdapterView.AdapterContextMenuInfo menuInfo; menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int index = menuInfo.position; removeItem(index); return true; } } return false; } @Override public void onDestroy() { super.onDestroy(); } private void cancelAdd() { addingNew = false; myEditText.setVisibility(View.GONE); } private void addNewItem() { addingNew = true; myEditText.setVisibility(View.VISIBLE); myEditText.requestFocus(); } private void removeItem(int _index) { // Items are added to the listview in reverse order, so invert the index. //toDoDBAdapter.removeTask(todoItems.size()-_index); ToDoItem item = todoItems.get(_index); final long selectedId = item.getTaskId(); mService.removeTask(selectedId); entries--; Toast.makeText(this, "Entry deleted", Toast.LENGTH_SHORT).show(); updateArray(); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, TodoService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; public class TimedToast extends AsyncTask<Long, Integer, Integer> { @Override protected Integer doInBackground(Long... arg0) { if (notifs < 15) { try { Toast.makeText(ToDoList.this, entries + " entries left", Toast.LENGTH_SHORT).show(); notifs++; Thread.sleep(20000); } catch (InterruptedException e) { } } return 0; } } } TodoService.java: package com.examples.todolist; import android.app.Service; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Binder; import android.os.IBinder; public class TodoService extends Service { private final IBinder mBinder = new LocalBinder(); @Override public IBinder onBind(Intent arg0) { return mBinder; } public class LocalBinder extends Binder { TodoService getService() { return TodoService.this; } } public void insertTask(ToDoItem _task) { ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_CREATION_DATE, _task.getCreated().getTime()); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.insert(TodoProvider.CONTENT_URI, values); } public void updateTask(ToDoItem _task) { long tid = _task.getTaskId(); ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.update(TodoProvider.CONTENT_URI, values, TodoProvider.KEY_ID + "=" + tid, null); } public void removeTask(long tid) { ContentResolver cr = getContentResolver(); cr.delete(TodoProvider.CONTENT_URI, TodoProvider.KEY_ID + "=" + tid, null); } public Cursor getAllToDoItemsCursor() { ContentResolver cr = getContentResolver(); return cr.query(TodoProvider.CONTENT_URI, null, null, null, null); } } TodoProvider.java: package com.examples.todolist; import android.content.*; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; import android.text.TextUtils; import android.util.Log; public class TodoProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.examples.provider.todolist/todo"); @Override public boolean onCreate() { Context context = getContext(); todoHelper dbHelper = new todoHelper(context, DATABASE_NAME, null, DATABASE_VERSION); todoDB = dbHelper.getWritableDatabase(); return (todoDB == null) ? false : true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder tb = new SQLiteQueryBuilder(); tb.setTables(TODO_TABLE); // If this is a row query, limit the result set to the passed in row. switch (uriMatcher.match(uri)) { case TASK_ID: tb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); break; default: break; } // If no sort order is specified sort by date / time String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = KEY_ID; } else { orderBy = sort; } // Apply the query to the underlying database. Cursor c = tb.query(todoDB, projection, selection, selectionArgs, null, null, orderBy); // Register the contexts ContentResolver to be notified if // the cursor result set changes. c.setNotificationUri(getContext().getContentResolver(), uri); // Return a cursor to the query result. return c; } @Override public Uri insert(Uri _uri, ContentValues _initialValues) { // Insert the new row, will return the row number if // successful. long rowID = todoDB.insert(TODO_TABLE, "task", _initialValues); // Return a URI to the newly inserted row on success. if (rowID > 0) { Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(uri, null); return uri; } throw new SQLException("Failed to insert row into " + _uri); } @Override public int delete(Uri uri, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.delete(TODO_TABLE, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.delete(TODO_TABLE, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.update(TODO_TABLE, values, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.update(TODO_TABLE, values, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case TASKS: return "vnd.android.cursor.dir/vnd.examples.task"; case TASK_ID: return "vnd.android.cursor.item/vnd.examples.task"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Create the constants used to differentiate between the different URI // requests. private static final int TASKS = 1; private static final int TASK_ID = 2; private static final UriMatcher uriMatcher; // Allocate the UriMatcher object, where a URI ending in 'tasks' will // correspond to a request for all tasks, and 'tasks' with a // trailing '/[rowID]' will represent a single task row. static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("com.examples.provider.Todolist", "tasks", TASKS); uriMatcher.addURI("com.examples.provider.Todolist", "tasks/#", TASK_ID); } //The underlying database private SQLiteDatabase todoDB; private static final String TAG = "TodoProvider"; private static final String DATABASE_NAME = "todolist.db"; private static final int DATABASE_VERSION = 1; private static final String TODO_TABLE = "todolist"; // Column Names public static final String KEY_ID = "_id"; public static final String KEY_TASK = "task"; public static final String KEY_CREATION_DATE = "date"; public long insertTask(ToDoItem _task) { // Create a new row of values to insert. ContentValues newTaskValues = new ContentValues(); // Assign values for each row. newTaskValues.put(KEY_TASK, _task.getTask()); newTaskValues.put(KEY_CREATION_DATE, _task.getCreated().getTime()); // Insert the row. return todoDB.insert(TODO_TABLE, null, newTaskValues); } public boolean updateTask(long _rowIndex, String _task) { ContentValues newValue = new ContentValues(); newValue.put(KEY_TASK, _task); return todoDB.update(TODO_TABLE, newValue, KEY_ID + "=" + _rowIndex, null) > 0; } public boolean removeTask(long _rowIndex) { return todoDB.delete(TODO_TABLE, KEY_ID + "=" + _rowIndex, null) > 0; } // Helper class for opening, creating, and managing database version control private static class todoHelper extends SQLiteOpenHelper { private static final String DATABASE_CREATE = "create table " + TODO_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_TASK + " TEXT, " + KEY_CREATION_DATE + " INTEGER);"; public todoHelper(Context cn, String name, CursorFactory cf, int ver) { super(cn, name, cf, ver); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE); onCreate(db); } } } I've omitted the other files as I'm sure they are correct. When I run the program, LogCat shows that the NullPointerException occurs in populateTodoList(), at toDoListCursor = mService.getAllToDoItemsCursor(). mService is the Cursor object returned by TodoService. I've added the service to the Manifest file, but I still cannot find out why it's causing an exception. Thanks in advance.

    Read the article

  • Problem of reading OWL/XML

    - by Mikae Combarado
    Hello, I have a problem reading OWL/XML files from Java using Jena. I have no problem reading RDF/XML files, but whenever I create a OWL/XML file from Protege and try to read it, Java gives this error below : WARN [main] (RDFDefaultErrorHandler.java:36) Exception in thread "main" java.lang.NullPointerException at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.endElement(XMLHandler.java:143) The code that I use to retrieve RDF/XML is below : OntModel ontModel = ModelFactory.createOntologyModel(); InputStream in = FileManager.get().open(inputFileName); if (in == null) { throw new IllegalArgumentException( "File: " + inputFileName + " not found"); } ontModel.read(in, ""); This code works with RDF/XML perfectly. However, I cannot read an OWL/XML. I looked at Internet and I couldn't find anything. I would really appreciate, if someone shows me a way. Many thanks

    Read the article

  • augment the factory pattern in java

    - by TP
    I am trying to use a factory pattern to create a QuestionTypeFactory where the instantiated classes will be like MultipleChoice, TrueFalseQuestion etc. The factory code looks something like this class QuestionFactory { public enum QuestionType { TrueFalse, MultipleChoice, Essay } public static Question createQuestion(QuestionType quesType) { switch (quesType) { case TrueFalse: return new TrueFalseQuestion(); case MultipleChoice: return new MultipleChoiceQuestion(); case Essay: return new EssayQuestion(); } throw new IllegalArgumentException("Not recognized."); } } This works ok for now. If I want to add another question type I will need to modify the factory class and I do not want to do that. How can I set it up so that each question class registers itself with the Factory so that when I add a new question type, I do not have to change the code for the factory? I am a bit new to java and am not sure how to do this.

    Read the article

  • Play wave file using AudioFormat in java

    - by angelina
    Dear all, I m getting following exception while running my code on linux operating system.This code works fine on windows operating system.below is the exception and code used. java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian is supported. AudioFormat format = sourceaudio.getFormat(); format = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); AudioFileFormat.Type targettype = AudioFileFormat.Type.WAVE; AudioInputStream targetaudiostream = AudioSystem.getAudioInputStream(format, sourceaudio); sourceaudio.close(); targetaudiostream.close(); System.out.println("55555555"); URL url = new URL("http://localhost:8084/newvideo/PCMfile.wav"); Clip clip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(url); clip.open(ais); System.out.println("seconds: " + (clip.getMicrosecondLength() / 1000000));

    Read the article

  • How do encrypt a long or int using the Bouncy Castle crypto routines for BlackBerry?

    - by DanG
    How do encrypt/decrypt a long or int using the Bouncy Castle crypto routines for BlackBerry? I know how to encrypt/decrypt a String. I can encrypt a long but can't get a long to decrypt properly. Some of this is poorly done, but I'm just trying stuff out at the moment. I've included my entire crypto engine here: import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; public class CryptoEngine { // Global Variables // Global Objects private static AESFastEngine engine; private static BufferedBlockCipher cipher; private static KeyParameter key; public static boolean setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); keyText = HelperMethods.cleanUpNullString(keyText); byte[] keyBytes = keyText.getBytes(); key = new KeyParameter(keyBytes); engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); // just for now return true; } public static String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); String cipherString = new String(cipherBytes); return cipherString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } public static String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes, decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } private static byte[] convertLongToByteArray(long longToConvert) { return new byte[] { (byte) (longToConvert >>> 56), (byte) (longToConvert >>> 48), (byte) (longToConvert >>> 40), (byte) (longToConvert >>> 32), (byte) (longToConvert >>> 24), (byte) (longToConvert >>> 16), (byte) (longToConvert >>> 8), (byte) (longToConvert) }; } private static long convertByteArrayToLong(byte[] byteArrayToConvert) { long returnable = 0; for (int counter = 0; counter < byteArrayToConvert.length; counter++) { returnable += ((byteArrayToConvert[byteArrayToConvert.length - counter - 1] & 0xFF) << counter * 8); } if (returnable < 0) { returnable++; } return returnable; } public static long encryptLong(long plainLong) { try { String plainString = String.valueOf(plainLong); String cipherString = encryptString(plainString); byte[] cipherBytes = cipherString.getBytes(); long returnable = convertByteArrayToLong(cipherBytes); return returnable; } catch (Exception e) { Logger.logToConsole(e); } // else return Integer.MIN_VALUE;// default bad value } public static long decryptLong(long encryptedLong) { byte[] cipherBytes = convertLongToByteArray(encryptedLong); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipherBytes.length; try { cipher.doFinal(decryptedBytes, decryptedLength); } catch (DataLengthException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidCipherTextException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } long plainLong = convertByteArrayToLong(decryptedBytes); return plainLong; } public static boolean encryptBoolean(int plainBoolean) { return false; } public static boolean decryptBoolean(int encryptedBoolean) { return false; } public static boolean testLongToByteArrayConversion() { boolean returnable = true; // fails out of the bounds of an integer, the conversion to long from byte // array does not hold, need to figure out a better solution for (long counter = -1000000; counter < 1000000; counter++) { long test = counter; byte[] bytes = convertLongToByteArray(test); long result = convertByteArrayToLong(bytes); if (result != test) { returnable = false; Logger.logToConsole("long conversion failed"); Logger.logToConsole("test = " + test + "\n result = " + result); } // regardless } // the end Logger.logToConsole("final returnable result = " + returnable); return returnable; } }

    Read the article

  • JSF hiding exceptions?

    - by bshacklett
    I have a managed bean for a JSF page which is doing JPA calls in the constructor to populate fields in the bean. I'm having a bit of trouble with another call to persist an entity (to populate data for testing). I'm expecting it to throw some sort of exception since it's not working, but I'm not getting anything. Just of the heck of it I tried the following: Query newQuery = em.createQuery("Bad Syntax"); List newList = newQuery.getResultList(); I'd expect an IllegalArgumentException here since the query string is completely invalid, but the page still loads and I don't see any exceptions anywhere. Am I right in expecting this exception? If so, why am I not seeing it?

    Read the article

  • Not able to update contact name in emulator 2.1

    - by Rishabh
    Hi, I am tring to update name of existing contact in android 2.1 emulator with the following code but always getting "java.lang.IllegalArgumentException: Emplty values" Exception. ContentValues contactValues = new ContentValues(); contactValues.put(People.NAME, "rishabh"); getContentResolver().update(UpdateContactUri, contactValues, null, null); UpdateContactUri is the uri of existing contact with id 4. It is working on emulator 1.6 but not on 2.1. One more thing i need to ask how can i access indivisual fields of Name(first, middle, last) and Address(Street, city, state, zip, country) in 2.1

    Read the article

  • Load data from CSV to mySQL database Java+hibernate+spring

    - by mona
    I am trying to load a CSV file in to mySQL database using Java+Hibernate+Spring. I am using the following query in the DAO to help me load in to the database: entityManager.createQuery("LOAD DATA INFILE :fileName INTO TABLE test").setParameter("fileName", "C:\\samples\\test\\abcd.csv").executeUpdate(); I got some idea to use this from http://dev.mysql.com/doc/refman/5.1/en/load-data.html and how to import a csv file into a mysql from an hibernate+spring application? But I am getting the error: java.lang.IllegalArgumentException: node to traverse cannot be null! Please help! Thanks

    Read the article

  • Problems with Tomcat server and JSP web application

    - by CitadelCSCadet
    I am running a JSP/Servlet Web application and out of nowhere we experienced some random problems that don't make any sense. I checked the catalina.out file to check the log files, and I noticed it contained some of the following messages SEVERE: Error starting static Resources java.lang.IllegalArgumentException: Invalid or unreadable WAR file : error in opening zip file INFO: validateJarFile(/home/weremo/appservers/ apache-tomcat-6.0.26/webapps /WMA/WEB-INF/lib/ servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class I am aware of what this message means, but am in the dark as to what could have caused it, or what effects it could have on the application.

    Read the article

  • how can i get proper Uri of a particular contact in android 2.1

    - by Rishabh
    I have written an application and added 2 contacts on emulator, but i am not able to update their names on android 2.1, code is working on android 1.6 platform with the following code. ContentValues contactValues = new ContentValues(); contactValues.put(Contacts.People.NAME, firstName+" "+lastName); getContentResolver().update(UpdateContactUri, contactValues, null, null); In android 1.6 i am getting Uri for those two contacts are "content:// contacts/people/1" and "content://contacts/people/2". but in 2.1 I am getting these values are "content://contacts/people/8" and "content://contacts/people/9" and while updating its giving "java.IllegalArgumentException, Empty values" exception. When i tried to put a static Uri like "content://contacts/people/1", code was debugged sucessfully but contact was not updated. How can i resolve it, why i am not getting uri like 1.6 platform ? Thanks in advance...

    Read the article

  • What's the best practice to "look up" Java Enums?

    - by Marcus
    We have a REST API where clients can supply parameters representing values defined on the server in Java Enums. So we can provide a descriptive error, we add this lookup method to each Enum. Seems like we're just copying code (bad). Is there a better practice? public enum MyEnum { A, B, C, D; public static MyEnum lookup(String id) { try { return MyEnum.valueOf(id); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalid value for my enum blah blah: " + id); } } } Update: The default error message provided by valueOf(..) would be No enum const class a.b.c.MyEnum.BadValue. I would like to provide a more descriptive error from the API.

    Read the article

  • Documenting logic in javadoc

    - by smayers81
    I have a question about where to document logic in javadocs. For example, I have the following method signature in an interface: public int getTotalAssociationsAsParent(Long id, Long type); The method returns associations where the given ID is the parent and the association is of type 'type'. ID is required, but if type passed in is NULL, then I will return ALL associations where the ID is the parent. My question is where should this type of logic be documented? I hesitate putting it in the javadoc of the interface because that sort of constrains all implementing classes to adhere to that logic. Maybe in the future, I'll have an Impl class that throws an IllegalArgumentException if type is NULL. However, if I put it in non-javadoc in the Impl class, then consumers of this method won't know how the method behaves with a NULL type.

    Read the article

  • Working with EnumSet class in GWT

    - by zenmonkey
    I am having trouble using EnumSet on the client side. I get this runtime error message: java.util.EnumSet.EnumSetImpl is not default instantiable (it must have a zero-argument constructor or no constructors at all) and has no custom serializer. Is this is a known issue? Here is what I am doing (basically a hello world app) Service: String echo (EnumSet<Names> name) throws IllegalArgumentException; Client: echoServ.echo (EnumSet.of(Names.JOHN), new AsyncCallback<String>() { ....... }); Shared enum class enum Names { JOHN, NUMAN, OBAMA }

    Read the article

  • Create Java method from a string?

    - by drozzy
    Is it possible in Java, to declare a method with a string instead of an identifier? For example can I do something like the following: class Car{ new Method("getFoo", { return 1+1; }); } //Use it Car car = new Car(); car.getFoo(); EDIT: I am adding a Purpose WHY I need this. In order to not hardcode method names when using Jersey and it's UriBuilder, which requires a method name: https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/core/UriBuilder.html See path() method with signature: public abstract UriBuilder path(java.lang.Class resource, java.lang.String method) throws java.lang.IllegalArgumentException I hope my question is clear, if not - let me know and I can clarify it.

    Read the article

  • New/strange Java "try()" syntax?

    - by Ali
    While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I say code as follows: /** * 'try-with-resources' */ class Example { void foo() { try (FileReader reader1 = new FileReader("file1"); FileReader reader2 = new FileReader("file2")) { } } } I've never seen try used like this and I've been coding in Java for 9 years! Does any one know why you would do this? What is a possible use-case / benefit of doing this? An other pieces of code I saw, I thought was a very useful shorthand so I'm sharing it here as well, it's pretty obvious what it does: /** * 'multi-catch' */ class Example { void foo() { try { } catch (IllegalArgumentException | NullPointerException | ClassCastException e) { e.printStackTrace(); } } }

    Read the article

  • Should I use implicit conversions to enforce preconditions?

    - by Malvolio
    It occurs to me that I could use use implicit conversions to both announce and enforce preconditions. Consider this: object NonNegativeDouble { implicit def int2nnd(d : Double) : NonNegativeDouble = new NonNegativeDouble(d) implicit def nnd2int(d : NonNegativeDouble) : Double = d.v def sqrt(n : NonNegativeDouble) : NonNegativeDouble = scala.math.sqrt(n) } class NonNegativeDouble(val v : Double ) { if (v < 0) { throw new IllegalArgumentException("negative value") } } object Test { def t1 = { val d : Double = NonNegativeDouble.sqrt(3.0); printf("%f\n", d); val n : Double = NonNegativeDouble.sqrt(-3.0); } } Ignore for the moment the actual vacuity of the example: my point is, the subclass NonNegativeDouble expresses the notion that a function only takes a subset of the entire range of the class's values. First is this: A good idea, a bad idea, or an obvious idea everybody else already knows about Second, this would be most useful with basic types, like Int and String. Those classes are final, of course, so is there a good way to not only use the restricted type in functions (that's what the second implicit is for) but also delegate to all methods on the underlying value (short of hand-implementing every delegation)?

    Read the article

  • StreamTokenizer Iterator Adapter help

    - by alpdog14
    I have this StreamTokenizer Iterator Adapter that is suppose to create a Tokenizer Iterator Index Builder then build the index from a STIA wrapped around a StreamTokenizer. I am having trouble implementing the hasNext and Next for my STIA, can anyone help me, here is my class: public class StreamTokenizerIteratorAdapter implements Iterator<Token> { DefaultIndexImpl index; StreamTokenizer source; public StreamTokenizerIteratorAdapter(final StreamTokenizer source) { if (source == null) throw new IllegalArgumentException("source == null"); } @Override public boolean hasNext() { return !index.isEmpty(); } public Token next() { if(!index.isEmpty()) return next(); else return null; } @Override public void remove() { throw new UnsupportedOperationException(); } } Should I be using the source element in the hasNext() and next()?

    Read the article

  • Is it possible to cast the Elapsed Time function to Integer?

    - by nuvio
    I have the following function: (def elapsedtime (with-out-str (time (run-my-function)))) and I was wondering if is possible to store only the integer value of the time, as I can only store a String at the moment.... Any suggestion? Thanks a lot UPDATE So I did use this: (defmacro nsecs [expr] `(let [start# (. System (nanoTime))] ~expr (- (. System (nanoTime)) start#))) And then modified this: (def elapsedtime (nsecs (run-my-function argument1 argument2))) but doesn't work, what am I doing wrong? "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Wrong number of args (1) passed to: main$fn--105$nsecs"

    Read the article

  • BeanUtils getPropertyOfMapBean

    - by dx-cp
    Hi, Im wondering if it is possible to get data from property which is map cotaining pairs Key-StringArray (Map) in BeanUtils library. I just simply need to access one of array elements by calling propertyName=string[0]. Current version (1.8.3) does not support indexed properties. If you look into their code you will find in class PropertyUtilsBean in method getPropertyOfMapBean: if (resolver.isIndexed(propertyName) || resolver.isMapped(propertyName)) { throw new IllegalArgumentException( "Indexed or mapped properties are not supported on" + " objects of type Map: " + propertyName); } way too bad:-( Have any of you any tip how to do it somehow differently?

    Read the article

  • Best tool for monitoring Coldfusion interoperability with .Net web service

    - by John Galt
    Is there a tool to see the message sent to webservice hosted on an IIS server? I have a webservice written in .Net and our ColdFusion people are having trouble building a "complex" parameter. This problem is described from a ColdFusion perspective at: adobe forum question It runs when called from a .net client. While hosted on a server inside our LAN, I put it out on a public server so the WSDL could be viewed: please take a quick look at this WSDL here When the CF developer runs her code, she gets: java.lang.IllegalArgumentException: argument type mismatch ...and I am wondering if there is a tool I could run on the server that hosts my webservice to see if it is even entering the WS or is being rejected by Java code that CF uses and is not really even getting to my webservice.

    Read the article

  • Why is 1942/4/3 00:00:00 an illegal date in java.util.Calendar?

    - by Aleksi
    Is there something special in the date 3rd of April 1942? For some reason the the hour of day 0 (12:00 am) is illegal for this specific date. The date is accepted when a lenient calendar is used but the hour of day is incremented to 1 (1:00 am). Relevant code java.util.Calendar calendar = java.util.Calendar.getInstance(); calendar.clear(); calendar.setLenient(false); calendar.set(1942, 3, 3, 0, 0, 0); calendar.getTimeInMillis(); Exception java.lang.IllegalArgumentException: HOUR_OF_DAY at java.util.GregorianCalendar.computeTime(Unknown Source) at java.util.Calendar.updateTime(Unknown Source) at java.util.Calendar.getTimeInMillis(Unknown Source) I'd really prefer is the dates were not lenient as I don't want to accept impossible dates.

    Read the article

  • How can I force the text go to the button of the panel?

    - by Roman
    At the moment I have the following code which works fine. label = new JLabel(panelLabel,SwingConstants.CENTER); outputPanel.add(label,BorderLayout.CENTER); I get the text in the center of the panel (in terms of the left-right position as well as in terms of the top-bottom). Now I want to set the position to the bottom (and center in terms of "left-right"). I tried to use SOUTH instead of the CENTER in the first line. Compiler does not complains but during the execution i get IllegalArgumentException: HorizontalAlignment. What is that?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >