Search Results

Search found 1459 results on 59 pages for 'arraylist'.

Page 18/59 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Nhibernate Exception - Return types of SQL query were not specified

    - by Muhammad Akhtar
    I am executing SQL in hibernate and getting exception Return types of SQL query were not specified public ArrayList get(string Release, int DocId) { string query = string.Format("select ti.Id, (' Defect ' + cast(ti.onTimeId as varchar) + ' - ' + ti.Name) as Name from TrackingItems ti inner join DocumentTrackingItems dti on ti.Id = dti.ItemStepId inner join Documents doc on dti.DocumentId = doc.Id where ti.ReleaseId = '{0}' AND doc.TypeId = {1} and Doc.Name is null AND ti.Type = 'Defect'", Release, DocId); ISession session = NHibernateHelper.GetCurrentSession(); ArrayList arList = (ArrayList)session.CreateSQLQuery(query).List(); return arList; } When I run this query in SQL, it working fine. any idea what could be the issue? -------- Thanks.........

    Read the article

  • How to instantiate a FormFile Object ?

    - by Mercer
    Hello, i have a String with a path of my file and i want to instancie a new FormFile with this String. It's possible ..? My code: public ArrayList<FormFile> getFilesFromFolder(String path) { File file = new File(path); ArrayList<FormFile> vFiles = new ArrayList<FormFile>(); if (file.exists()) { File[] files = file.listFiles(); int i; for (i = 0; i < files.length; i++) { if (files[i].isFile()) { vFiles.add((FormFile) files[i]); } } } else { vFiles = null; } return vFiles; } but i have an error in this line vFiles.add((FormFile) files[i]);

    Read the article

  • .NET Hashtable clone

    - by thelost
    Given the following code: Hashtable main = new Hashtable(); Hashtable inner = new Hashtable(); ArrayList innerList = new ArrayList(); innerList.Add(1); inner.Add("list", innerList); main.Add("inner", inner); Hashtable second = (Hashtable)main.Clone(); ((ArrayList)((Hashtable)second["inner"])["list"])[0] = 2; Why does the value within the array change from 1 to 2 in the "main" Hashtable, as the change was made on a clone ?

    Read the article

  • Recreating a Dictionary from an IEnumerable

    - by learnerplates
    But some of the callers is the Dictionary's TryGetValue and ContainsKey and so require the result of the method to be a Dictionary, how can I convert the IEnumerable into a Dictionary so that I can use TryGetValue ? I've a method which at present returns an IEnumerable. I want to make it more generic by making it return an IEnumerable. method: public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents() { // ... yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation); } caller: Dictionary<string, ArrayList> actual = target.GetComponents(); actual.ContainsKey("something");

    Read the article

  • Android EditText within a ListView

    - by metalideath
    I have created a custom Array Adapter to bind a custom row that contains some static text and an editable EditText. I am trying to register to be notified when the user changes the text within the edit text and when notified to determine which ArrayList row the modified EditText corresponds to. In the past with other types of views such as a Spinner I could simply put a reference to the parent view and the row number into the tag for the Spinner view. And then when I was notified that the value changed I read the tag to determine how to correlate it back to the master ArrayList. The problem with registering to be notifed with an EditText change is that you do not get back a view but instead get a TextWatcher and I have no way to correlate back to the parent view or ArrayList row. What is the technique that you need to use in this circumstance?

    Read the article

  • Why people are so afraid of using clone() (on collection and JDK classes) ?

    - by Bozho
    A number of times I've argued that using clone() isn't such a bad practice. Yes, I know the arguments. Bloch said it's bad. He indeed did, but he said that implementing clone() is bad. Using clone on the other hand, especially if it is implemented correctly by a trusted library, such as the JDK, is OK. Just yesterday I had a discussion about an answer of mine that merely suggests that using clone() for ArrayList is OK (and got no upvotes for that reason, I guess). If we look at the @author of ArrayList, we can see a familiar name - Josh Bloch. So clone() on ArrayList (and other collections) is perfectly fine. (Just look at the implementation). Same goes for Calendar and perhaps most of the java.lang and java.util classes. So, give me a reason why not to use clone() with JDK classes?

    Read the article

  • Android Multiple objects in SimpleAdapter

    - by Adam Sherratt
    I have a need (unless you can think of a better way) of passing multiple objects to a custom list adapter. I know that I'm barking up the wrong tree here, and would appreciate someone setting me on the right course! Thanks playlistadapter = new MyPlaylistAdapter(MyApplication.getAppContext(), songsList, retained_songsList, folderMode, R.layout.file_view, new String[] { "songTitle","songAlbum", "songPath" }, new int[] { R.id.checkTextView, R.id.text2, R.id.text3 }); And my adapter class: public class MyPlaylistAdapter extends SimpleAdapter{ private ArrayList <Song> songsList = new ArrayList<Song>(); private ArrayList <Song> retained_songsList = new ArrayList<Song>(); private ArrayList<Song> playlistcheck = new ArrayList<Song>(); private String folderMode; private String TAG = "AndroidMediaCenter"; public MyPlaylistAdapter(Context context,List<Song> SongsList, List<Song> Retained_songsList, String FolderMode,int resource, String[] from, int[] to) { super(context, null, resource, from, to); songsList.clear(); songsList.addAll(SongsList); Log.i(TAG, "MyPlayListAdapter Songslist = " + songsList.size()); retained_songsList.clear(); retained_songsList.addAll(Retained_songsList); folderMode = FolderMode; } public View getView(int position, View convertView, ViewGroup parent) { //PlayListViewHolder holder; CheckedTextView checkTextView; TextView text2; TextView text3; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) MyApplication.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); //LayoutInflater inflater=getLayoutInflater(); convertView=inflater.inflate(R.layout.file_view, parent, false); //convertView.setBackgroundColor(0xFF00FF00 ); //holder = new PlayListViewHolder(); checkTextView = (CheckedTextView) convertView.findViewById(R.id.checkTextView); text2 = (TextView) convertView.findViewById(R.id.text2); text3 = (TextView) convertView.findViewById(R.id.text3); //convertView.setTag(holder); } else { //holder = (PlayListViewHolder) convertView.getTag(); } //put something into textviews String tracks = null; String tracks_Details = null; String trackspath = null; tracks = songsList.get(position).getSongTitle(); tracks_Details = songsList.get(position).getAlbum() + " (" + songsList.get(position).getArtist() + ")"; trackspath = songsList.get(position).getSongPath(); checkTextView = (CheckedTextView) convertView.findViewById(R.id.checkTextView); text2 = (TextView) convertView.findViewById(R.id.text2); text3 = (TextView) convertView.findViewById(R.id.text3); checkTextView.setText(tracks); if(folderMode.equals("Playlists")){ checkTextView.setBackgroundColor(Color.GREEN); checkTextView.setChecked(false); try { int listsize_rs = retained_songsList.size(); for (int j = 0; j<listsize_rs;j++){ if((retained_songsList.get(j).getSongPath()).equals(songsList.get(position).getSongPath())){ checkTextView.setBackgroundColor(Color.TRANSPARENT); //Need to check here whether the checkedtextview is ticked or not checkTextView.setChecked(true); playlistcheck.add(songsList.get(position)); break; } } } catch (Exception e) { e.printStackTrace(); } }else { //Need to check here whether the checkedtextview is ticked or not try { if (songsList.get(position).getSongCheckedStatus()==true){ checkTextView.setChecked(true); }else{ checkTextView.setChecked(false); } } catch (Exception e) { e.printStackTrace(); } } text2.setText(tracks_Details); text3.setText(trackspath); Log.i(TAG, "MyPlayListAdapter Songslist = " + songsList.size()); return convertView; } } However, this doesn't inflate, throwing the following errors: 10-26 23:11:09.464: E/AndroidRuntime(2826): FATAL EXCEPTION: main 10-26 23:11:09.464: E/AndroidRuntime(2826): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.GetMusicComplete flg=0x10 } in com.Nmidia.AMC.MusicActivity$18@414c5770 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:765) 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.os.Handler.handleCallback(Handler.java:615) 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.os.Handler.dispatchMessage(Handler.java:92) 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.os.Looper.loop(Looper.java:137) 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.app.ActivityThread.main(ActivityThread.java:4745) 10-26 23:11:09.464: E/AndroidRuntime(2826): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 23:11:09.464: E/AndroidRuntime(2826): at java.lang.reflect.Method.invoke(Method.java:511) 10-26 23:11:09.464: E/AndroidRuntime(2826): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 10-26 23:11:09.464: E/AndroidRuntime(2826): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-26 23:11:09.464: E/AndroidRuntime(2826): at dalvik.system.NativeStart.main(Native Method) 10-26 23:11:09.464: E/AndroidRuntime(2826): Caused by: java.lang.NullPointerException 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93) 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.widget.ListView.setAdapter(ListView.java:460) 10-26 23:11:09.464: E/AndroidRuntime(2826): at com.Nmidia.AMC.MusicActivity.setFilterMusic(MusicActivity.java:1230) 10-26 23:11:09.464: E/AndroidRuntime(2826): at com.Nmidia.AMC.MusicActivity$18.onReceive(MusicActivity.java:996) 10-26 23:11:09.464: E/AndroidRuntime(2826): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:755) 10-26 23:11:09.464: E/AndroidRuntime(2826): ... 9 more

    Read the article

  • How do I correctly use generics?

    - by ninjasense
    I basically am making webrequests and recieving a JSON response. Depending on the request, I am parsing JSON request into objects I have created. The parsing is pretty much the same no matter what the object Im parsing into looks like. So I have a bunch of methods doing the same work only with different objects, I was wondering how I could accomplish this with generics? Here is an example public static ArrayList<Contact> parseContacts(String responseData) { ArrayList<Contact> Contacts = new ArrayList<Contact>(); try { JSONArray jsonContacts = new JSONArray(responseData); if (!jsonContacts.isNull(0)) { for (int i = 0; i < jsonContacts.length(); i++) { Contacts.add(new Contact(jsonContacts.getJSONObject(i))); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { } return Contacts; }

    Read the article

  • Warning vs. error

    - by Samuel
    I had an annoying issue, getting a "Possible loss of precision" error when compiling my Java program on BlueJ (But from what i read this isn't connected to a specific IDE). I was surprised by the fact that the compiler told me there is a possible loss of precision and wouldnt let me compile/run the program. Why is this an error and not a warning saying you might loose precision here, if you don't want that change your code? The program runs just fine when i drop the float values, it wouldn't matter since there is no point (e.g [143.08, 475.015]) on my screen. On the other hand when i loop through an ArrayList and in this loop i have an if clause removing elements from the ArrayList it runs fine, just throws an error and doesn't display the ArrayList [used for drawing circles] for a fraction of a second. This appears to me as a severe error but doesn't cause (hardly) any troubles, while i wouldn't want to have such a thing in my code at all. What's the boundary?

    Read the article

  • Serialization java to c#

    - by tom
    Hi, I have manged to serialize an arraylist in java using xstream, send it to my c# application via http and then write that to file (just for now). The serialized data was an arraylist in java. I want to try and re form this arraylist in c# from the xml i have. I have been looking at http://code.google.com/p/xstream-dot-net/ to do this. Does anyone know if that is the right way to go or is there a better way of reforming the serialized data in c#?

    Read the article

  • How do you search through a map?

    - by Jack Null
    I have a map: Map<String, String> ht = new HashMap(); and I would like to know how to search through it and find anything matching a particular string. And if it is a match store it into an arraylist. The map contains strings like this: 1,2,3,4,5,5,5 and the matching string would be 5. So for I have this: String match = "5"; ArrayList<String> result = new ArrayList<String>(); Enumeration num= ht.keys(); while (num.hasMoreElements()) { String number = (String) num.nextElement(); if(number.equals(match)) { result.add(number); } }

    Read the article

  • SQL To Filter A SubSet Of Data

    - by Nick LaMarca
    I have an arraylist that holds a subset of names found in my database. I need to write a query to get a count of the people in the arraylist for certain sections i.e. There is a field "City" in my database from the people in the arraylist of names I want to know how many of them live in Chicago, how many live in New York etc. Can someone help me how I might set up an sql statement to handle this. I think somehow I have to pass the subset of names to sql somehow.

    Read the article

  • permute data for a HashMap in Java

    - by tuxou
    hi i have a linkedhashmap and i need to permute (change the key of the values) between 2 random values example : key 1 value 123 key 2 value 456 key 3 value 789 after random permutation of 2 values key 1 value 123 key 2 value 789 key 3 value 456 so here I permuted values between key 2 and key 3 thank you; sample of the code of my map : Map map = new LinkedHashMap(); map =myMap.getLinkedHashMap(); Set key = map.keySet(); for(Iterator it = cles.iterator(); it.hasNext();) { Integer cle = it.next(); ArrayList values = (ArrayList)map.get(cle);//an arrayList of integers int i = 0; while(i < values.size()) { //i donno what to do here i++; } }

    Read the article

  • Help choosing the right data structure

    - by devoured elysium
    I need a data structure with the following requirements: Needs to be able to get elements by index (like a List). I will always just add / remove elements from the end of the structure. I am inclined to use an ArrayList. In this situation, it seems to be O(1) both to read elements (they always are?), remove elements (I only need to remove them at the end of the list) and to add(I only add to the end of the list). There is only the problem that time to time the ArrayList will have a performance penalty when it's completly full and I need to add more elements to it. Is there any other better idea? I don't think of a data structure that'd beat the ArrayList here. Thanks

    Read the article

  • Get application names with specific permission

    - by rolling.stones
    I want list of all applications installed on the device which use a specific permission like INTERNET. i am using this code , but not able to retrieve results , please help . private ArrayList<String> getInstalledApps(Context context) { ArrayList<String> results = new ArrayList<String>(); PackageManager packageManager = context.getPackageManager(); List<PackageInfo> applist = packageManager.getInstalledPackages(0); Iterator<PackageInfo> it = applist.iterator(); while (it.hasNext()) { PackageInfo pk = (PackageInfo) it.next(); if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(Manifest.permission.INTERNET, pk.packageName)) results.add("" + pk.applicationInfo.loadLabel(packageManager)); } for (int i = 0; i <= results.size(); i++) { Log.v("app using internet = ", results.toString()); } return results; } Thanks in advance. Any help accepted :)

    Read the article

  • Java - Optimize finding a string in a list

    - by Mark
    I have an ArrayList of objects where each object contains a string 'word' and a date. I need to check to see if the date has passed for a list of 500 words. The ArrayList could contain up to a million words and dates. The dates I store as integers, so the problem I have is attempting to find the word I am looking for in the ArrayList. Is there a way to make this faster? In python I have a dict and mWords['foo'] is a simple lookup without looping through the whole 1 million items in the mWords array. Is there something like this in java? for (int i = 0; i < mWords.size(); i++) { if ( word == mWords.get(i).word ) { mLastFindIndex = i; return mWords.get(i); } }

    Read the article

  • LWJGL SlickUtil Texture Binding

    - by Matthew Dockerty
    I am making a 3D game using LWJGL and I have a texture class with static variables so that I only need to load textures once, even if I need to use them more than once. I am using Slick Util for this. When I bind a texture it works fine, but then when I try to render something else after I have rendered the model with the texture, the texture is still being bound. How do I unbind the texture and set the rendermode to the one that was in use before any textures were bound? Some of my code is below. The problem I am having is the player texture is being used in the box drawn around the player after it the model has been rendered. Model.java public class Model { public List<Vector3f> vertices = new ArrayList<Vector3f>(); public List<Vector3f> normals = new ArrayList<Vector3f>(); public ArrayList<Vector2f> textureCoords = new ArrayList<Vector2f>(); public List<Face> faces = new ArrayList<Face>(); public static Model TREE; public static Model PLAYER; public static void loadModels() { try { TREE = OBJLoader.loadModel(new File("assets/model/tree_pine_0.obj")); PLAYER = OBJLoader.loadModel(new File("assets/model/player.obj")); } catch (Exception e) { e.printStackTrace(); } } public void render(Vector3f position, Vector3f scale, Vector3f rotation, Texture texture, float shinyness) { glPushMatrix(); { texture.bind(); glColor3f(1, 1, 1); glTranslatef(position.x, position.y, position.z); glScalef(scale.x, scale.y, scale.z); glRotatef(rotation.x, 1, 0, 0); glRotatef(rotation.y, 0, 1, 0); glRotatef(rotation.z, 0, 0, 1); glMaterialf(GL_FRONT, GL_SHININESS, shinyness); glBegin(GL_TRIANGLES); { for (Face face : faces) { Vector2f t1 = textureCoords.get((int) face.textureCoords.x - 1); glTexCoord2f(t1.x, t1.y); Vector3f n1 = normals.get((int) face.normal.x - 1); glNormal3f(n1.x, n1.y, n1.z); Vector3f v1 = vertices.get((int) face.vertex.x - 1); glVertex3f(v1.x, v1.y, v1.z); Vector2f t2 = textureCoords.get((int) face.textureCoords.y - 1); glTexCoord2f(t2.x, t2.y); Vector3f n2 = normals.get((int) face.normal.y - 1); glNormal3f(n2.x, n2.y, n2.z); Vector3f v2 = vertices.get((int) face.vertex.y - 1); glVertex3f(v2.x, v2.y, v2.z); Vector2f t3 = textureCoords.get((int) face.textureCoords.z - 1); glTexCoord2f(t3.x, t3.y); Vector3f n3 = normals.get((int) face.normal.z - 1); glNormal3f(n3.x, n3.y, n3.z); Vector3f v3 = vertices.get((int) face.vertex.z - 1); glVertex3f(v3.x, v3.y, v3.z); } texture.release(); } glEnd(); } glPopMatrix(); } } Textures.java public class Textures { public static Texture FLOOR; public static Texture PLAYER; public static Texture SKYBOX_TOP; public static Texture SKYBOX_BOTTOM; public static Texture SKYBOX_FRONT; public static Texture SKYBOX_BACK; public static Texture SKYBOX_LEFT; public static Texture SKYBOX_RIGHT; public static void loadTextures() { try { FLOOR = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/model/floor.png"))); FLOOR.setTextureFilter(GL11.GL_NEAREST); PLAYER = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/model/tree_pine_0.png"))); PLAYER.setTextureFilter(GL11.GL_NEAREST); SKYBOX_TOP = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_top.png"))); SKYBOX_TOP.setTextureFilter(GL11.GL_NEAREST); SKYBOX_BOTTOM = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_bottom.png"))); SKYBOX_BOTTOM.setTextureFilter(GL11.GL_NEAREST); SKYBOX_FRONT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_front.png"))); SKYBOX_FRONT.setTextureFilter(GL11.GL_NEAREST); SKYBOX_BACK = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_back.png"))); SKYBOX_BACK.setTextureFilter(GL11.GL_NEAREST); SKYBOX_LEFT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_left.png"))); SKYBOX_LEFT.setTextureFilter(GL11.GL_NEAREST); SKYBOX_RIGHT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_right.png"))); SKYBOX_RIGHT.setTextureFilter(GL11.GL_NEAREST); } catch (Exception e) { e.printStackTrace(); } } } Player.java public class Player { private Vector3f position; private float yaw; private float moveSpeed; public Player(float x, float y, float z, float yaw, float moveSpeed) { this.position = new Vector3f(x, y, z); this.yaw = yaw; this.moveSpeed = moveSpeed; } public void update() { if (Keyboard.isKeyDown(Keyboard.KEY_W)) walkForward(moveSpeed); if (Keyboard.isKeyDown(Keyboard.KEY_S)) walkBackwards(moveSpeed); if (Keyboard.isKeyDown(Keyboard.KEY_A)) strafeLeft(moveSpeed); if (Keyboard.isKeyDown(Keyboard.KEY_D)) strafeRight(moveSpeed); if (Mouse.isButtonDown(0)) yaw += Mouse.getDX(); LowPolyRPG.getInstance().getCamera().setPosition(-position.x, -position.y, -position.z); LowPolyRPG.getInstance().getCamera().setYaw(yaw); } public void walkForward(float distance) { position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw))); position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw))); } public void walkBackwards(float distance) { position.setX(position.getX() - distance * (float) Math.sin(Math.toRadians(yaw))); position.setZ(position.getZ() + distance * (float) Math.cos(Math.toRadians(yaw))); } public void strafeLeft(float distance) { position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw - 90))); position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw - 90))); } public void strafeRight(float distance) { position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw + 90))); position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw + 90))); } public void render() { Model.PLAYER.render(new Vector3f(position.x, position.y + 12, position.z), new Vector3f(3, 3, 3), new Vector3f(0, -yaw + 90, 0), Textures.PLAYER, 128); GL11.glPushMatrix(); GL11.glTranslatef(position.getX(), position.getY(), position.getZ()); GL11.glRotatef(-yaw, 0, 1, 0); GL11.glScalef(5.8f, 21, 2.2f); GL11.glDisable(GL11.GL_LIGHTING); GL11.glLineWidth(3); GL11.glBegin(GL11.GL_LINE_STRIP); GL11.glColor3f(1, 1, 1); glVertex3f(1f, 0f, -1f); glVertex3f(-1f, 0f, -1f); glVertex3f(-1f, 1f, -1f); glVertex3f(1f, 1f, -1f); glVertex3f(-1f, 0f, 1f); glVertex3f(1f, 0f, 1f); glVertex3f(1f, 1f, 1f); glVertex3f(-1f, 1f, 1f); glVertex3f(1f, 1f, -1f); glVertex3f(-1f, 1f, -1f); glVertex3f(-1f, 1f, 1f); glVertex3f(1f, 1f, 1f); glVertex3f(1f, 0f, 1f); glVertex3f(-1f, 0f, 1f); glVertex3f(-1f, 0f, -1f); glVertex3f(1f, 0f, -1f); glVertex3f(1f, 0f, 1f); glVertex3f(1f, 0f, -1f); glVertex3f(1f, 1f, -1f); glVertex3f(1f, 1f, 1f); glVertex3f(-1f, 0f, -1f); glVertex3f(-1f, 0f, 1f); glVertex3f(-1f, 1f, 1f); glVertex3f(-1f, 1f, -1f); GL11.glEnd(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glPopMatrix(); } public Vector3f getPosition() { return new Vector3f(-position.x, -position.y, -position.z); } public float getX() { return position.getX(); } public float getY() { return position.getY(); } public float getZ() { return position.getZ(); } public void setPosition(Vector3f position) { this.position = position; } public void setPosition(float x, float y, float z) { this.position.setX(x); this.position.setY(y); this.position.setZ(z); } } Thanks for the help.

    Read the article

  • C#/.NET Little Wonders: Use Cast() and TypeOf() to Change Sequence Type

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. We’ve seen how the Select() extension method lets you project a sequence from one type to a new type which is handy for getting just parts of items, or building new items.  But what happens when the items in the sequence are already the type you want, but the sequence itself is typed to an interface or super-type instead of the sub-type you need? For example, you may have a sequence of Rectangle stored in an IEnumerable<Shape> and want to consider it an IEnumerable<Rectangle> sequence instead.  Today we’ll look at two handy extension methods, Cast<TResult>() and OfType<TResult>() which help you with this task. Cast<TResult>() – Attempt to cast all items to type TResult So, the first thing we can do would be to attempt to create a sequence of TResult from every item in the source sequence.  Typically we’d do this if we had an IEnumerable<T> where we knew that every item was actually a TResult where TResult inherits/implements T. For example, assume the typical Shape example classes: 1: // abstract base class 2: public abstract class Shape { } 3:  4: // a basic rectangle 5: public class Rectangle : Shape 6: { 7: public int Widtgh { get; set; } 8: public int Height { get; set; } 9: } And let’s assume we have a sequence of Shape where every Shape is a Rectangle… 1: var shapes = new List<Shape> 2: { 3: new Rectangle { Width = 3, Height = 5 }, 4: new Rectangle { Width = 10, Height = 13 }, 5: // ... 6: }; To get the sequence of Shape as a sequence of Rectangle, of course, we could use a Select() clause, such as: 1: // select each Shape, cast it to Rectangle 2: var rectangles = shapes 3: .Select(s => (Rectangle)s) 4: .ToList(); But that’s a bit verbose, and fortunately there is already a facility built in and ready to use in the form of the Cast<TResult>() extension method: 1: // cast each item to Rectangle and store in a List<Rectangle> 2: var rectangles = shapes 3: .Cast<Rectangle>() 4: .ToList(); However, we should note that if anything in the list cannot be cast to a Rectangle, you will get an InvalidCastException thrown at runtime.  Thus, if our Shape sequence had a Circle in it, the call to Cast<Rectangle>() would have failed.  As such, you should only do this when you are reasonably sure of what the sequence actually contains (or are willing to handle an exception if you’re wrong). Another handy use of Cast<TResult>() is using it to convert an IEnumerable to an IEnumerable<T>.  If you look at the signature, you’ll see that the Cast<TResult>() extension method actually extends the older, object-based IEnumerable interface instead of the newer, generic IEnumerable<T>.  This is your gateway method for being able to use LINQ on older, non-generic sequences.  For example, consider the following: 1: // the older, non-generic collections are sequence of object 2: var shapes = new ArrayList 3: { 4: new Rectangle { Width = 3, Height = 13 }, 5: new Rectangle { Width = 10, Height = 20 }, 6: // ... 7: }; Since this is an older, object based collection, we cannot use the LINQ extension methods on it directly.  For example, if I wanted to query the Shape sequence for only those Rectangles whose Width is > 5, I can’t do this: 1: // compiler error, Where() operates on IEnumerable<T>, not IEnumerable 2: var bigRectangles = shapes.Where(r => r.Width > 5); However, I can use Cast<Rectangle>() to treat my ArrayList as an IEnumerable<Rectangle> and then do the query! 1: // ah, that’s better! 2: var bigRectangles = shapes.Cast<Rectangle>().Where(r => r.Width > 5); Or, if you prefer, in LINQ query expression syntax: 1: var bigRectangles = from s in shapes.Cast<Rectangle>() 2: where s.Width > 5 3: select s; One quick warning: Cast<TResult>() only attempts to cast, it won’t perform a cast conversion.  That is, consider this: 1: var intList = new List<int> { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; 2:  3: // casting ints to longs, this should work, right? 4: var asLong = intList.Cast<long>().ToList(); Will the code above work?  No, you’ll get a InvalidCastException. Remember that Cast<TResult>() is an extension of IEnumerable, thus it is a sequence of object, which means that it will box every int as an object as it enumerates over it, and there is no cast conversion from object to long, and thus the cast fails.  In other words, a cast from int to long will succeed because there is a conversion from int to long.  But a cast from int to object to long will not, because you can only unbox an item by casting it to its exact type. For more information on why cast-converting boxed values doesn’t work, see this post on The Dangers of Casting Boxed Values (here). OfType<TResult>() – Filter sequence to only items of type TResult So, we’ve seen how we can use Cast<TResult>() to change the type of our sequence, when we expect all the items of the sequence to be of a specific type.  But what do we do when a sequence contains many different types, and we are only concerned with a subset of a given type? For example, what if a sequence of Shape contains Rectangle and Circle instances, and we just want to select all of the Rectangle instances?  Well, let’s say we had this sequence of Shape: 1: var shapes = new List<Shape> 2: { 3: new Rectangle { Width = 3, Height = 5 }, 4: new Rectangle { Width = 10, Height = 13 }, 5: new Circle { Radius = 10 }, 6: new Square { Side = 13 }, 7: // ... 8: }; Well, we could get the rectangles using Select(), like: 1: var onlyRectangles = shapes.Where(s => s is Rectangle).ToList(); But fortunately, an easier way has already been written for us in the form of the OfType<T>() extension method: 1: // returns only a sequence of the shapes that are Rectangles 2: var onlyRectangles = shapes.OfType<Rectangle>().ToList(); Now we have a sequence of only the Rectangles in the original sequence, we can also use this to chain other queries that depend on Rectangles, such as: 1: // select only Rectangles, then filter to only those more than 2: // 5 units wide... 3: var onlyBigRectangles = shapes.OfType<Rectangle>() 4: .Where(r => r.Width > 5) 5: .ToList(); The OfType<Rectangle>() will filter the sequence to only the items that are of type Rectangle (or a subclass of it), and that results in an IEnumerable<Rectangle>, we can then apply the other LINQ extension methods to query that list further. Just as Cast<TResult>() is an extension method on IEnumerable (and not IEnumerable<T>), the same is true for OfType<T>().  This means that you can use OfType<TResult>() on object-based collections as well. For example, given an ArrayList containing Shapes, as below: 1: // object-based collections are a sequence of object 2: var shapes = new ArrayList 3: { 4: new Rectangle { Width = 3, Height = 5 }, 5: new Rectangle { Width = 10, Height = 13 }, 6: new Circle { Radius = 10 }, 7: new Square { Side = 13 }, 8: // ... 9: }; We can use OfType<Rectangle> to filter the sequence to only Rectangle items (and subclasses), and then chain other LINQ expressions, since we will then be of type IEnumerable<Rectangle>: 1: // OfType() converts the sequence of object to a new sequence 2: // containing only Rectangle or sub-types of Rectangle. 3: var onlyBigRectangles = shapes.OfType<Rectangle>() 4: .Where(r => r.Width > 5) 5: .ToList(); Summary So now we’ve seen two different ways to get a sequence of a superclass or interface down to a more specific sequence of a subclass or implementation.  The Cast<TResult>() method casts every item in the source sequence to type TResult, and the OfType<TResult>() method selects only those items in the source sequence that are of type TResult. You can use these to downcast sequences, or adapt older types and sequences that only implement IEnumerable (such as DataTable, ArrayList, etc.). Technorati Tags: C#,CSharp,.NET,LINQ,Little Wonders,TypeOf,Cast,IEnumerable<T>

    Read the article

  • How-to populate different select list content per table row

    - by frank.nimphius
    Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} A frequent requirement posted on the OTN forum is to render cells of a table column using instances of af:selectOneChoices with each af:selectOneChoice instance showing different list values. To implement this use case, the select list of the table column is populated dynamically from a managed bean for each row. The table's current rendered row object is accessible in the managed bean using the #{row} expression, where "row" is the value added to the table's var property. <af:table var="row">   ...   <af:column ...>     <af:selectOneChoice ...>         <f:selectItems value="#{browseBean.items}"/>     </af:selectOneChoice>   </af:column </af:table> The browseBean managed bean referenced in the code snippet above has a setItems and getItems method defined that is accessible from EL using the #{browseBean.items} expression. When the table renders, then the var property variable - the #{row} reference - is filled with the data object displayed in the current rendered table row. The managed bean getItems method returns a List<SelectItem>, which is the model format expected by the f:selectItems tag to populate the af:selectOneChoice list. public void setItems(ArrayList<SelectItem> items) {} //this method is executed for each table row public ArrayList<SelectItem> getItems() {   FacesContext fctx = FacesContext.getCurrentInstance();   ELContext elctx = fctx.getELContext();   ExpressionFactory efactory =          fctx.getApplication().getExpressionFactory();          ValueExpression ve =          efactory.createValueExpression(elctx, "#{row}", Object.class);      Row rw = (Row) ve.getValue(elctx);         //use one of the row attributes to determine which list to query and   //show in the current af:selectOneChoice list  // ...  ArrayList<SelectItem> alsi = new ArrayList<SelectItem>();  for( ... ){      SelectItem item = new SelectItem();        item.setLabel(...);        item.setValue(...);        alsi.add(item);   }   return alsi;} For better performance, the ADF Faces table stamps it data rows. Stamping means that the cell renderer component - af:selectOneChoice in this example - is instantiated once for the column and then repeatedly used to display the cell data for individual table rows. This however means that you cannot refresh a single select one choice component in a table to change its list values. Instead the whole table needs to be refreshed, rerunning the managed bean list query. Be aware that having individual list values per table row is an expensive operation that should be used only on small tables for Business Services with low latency data fetching (e.g. ADF Business Components and EJB) and with server side caching strategies for the queried data (e.g. storing queried list data in a managed bean in session scope).

    Read the article

  • c# display DB table structure

    - by user3529643
    I have a question. My code is the following : public partial class Form1 : Form { public OleDbConnection datCon; public string MyDataFile; public ArrayList tblArray; public ArrayList fldArray; public Form1() { InitializeComponent(); lvData.Clear(); lvData.View = View.Details; lvData.LabelEdit = false; lvData.FullRowSelect = true; lvData.GridLines = true; } private void DataConnection() { MyDataFile = Application.StartupPath + @"\studenti.mdb"; string MyCon = @"provider=microsoft.jet.oledb.4.0;data source=" + MyDataFile; try { datCon = new OleDbConnection(MyCon); } catch (Exception ex) { MessageBox.Show(ex.Message); } FillTreeView(); } private void GetTables(OleDbConnection cnn) { try { cnn.Open(); DataTable schTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }); tblArray = new ArrayList(); foreach (DataRow datrow in schTable.Rows) { tblArray.Add(datrow["TABLE_NAME"].ToString()); } cnn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void GetFields(OleDbConnection cnn, string tabNode) { string tabName; try { tabName = tabNode; cnn.Open(); DataTable schTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, tabName }); fldArray = new ArrayList(); foreach (DataRow datRow in schTable.Rows) { fldArray.Add(datRow["COLUMN_NAME"].ToString()); } cnn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void FillTreeView() { tvData.Nodes.Clear(); tvData.Nodes.Add("Database"); tvData.Nodes[0].Tag = "RootDB"; GetTables(datCon); // add table node for (int i = 0; i < tblArray.Count; i++) { tvData.Nodes[0].Nodes.Add(tblArray[i].ToString()); tvData.Nodes[0].Nodes[i].Tag = "Tables"; } // add field node for (int i = 0; i < tblArray.Count; i++) { GetFields(datCon, tblArray[i].ToString()); for (int j = 0; j < fldArray.Count; j++) { tvData.Nodes[0].Nodes[i].Nodes.Add(fldArray[j].ToString()); tvData.Nodes[0].Nodes[i].Nodes[j].Tag = "Fields"; } } this.tvData.ContextMenuStrip = contextMenuStrip1; contextMenuStrip1.ItemClicked +=contextMenuStrip1_ItemClicked; } public void FillListView(OleDbConnection cnn, string tabName) { OleDbCommand cmdRead; OleDbDataReader datReader; string strField; lblTableName.Text = tabName; strField = "SELECT * FROM [" + tabName + "]"; // Initi cmdRead obiect cmdRead = new OleDbCommand(strField, cnn); cnn.Open(); datReader = cmdRead.ExecuteReader(); // fill ListView while (datReader.Read()) { ListViewItem objListItem = new ListViewItem(datReader.GetValue(0).ToString()); for (int c = 1; c < datReader.FieldCount; c++) { objListItem.SubItems.Add(datReader.GetValue(c).ToString()); } lvData.Items.Add(objListItem); } datReader.Close(); cnn.Close(); } private void ViewToolStripMenuItem_Click(object sender, EventArgs e) { DataConnection(); } public void tvData_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e) { string tabName; int fldCount; if (e.Node.Tag.ToString() == "Tables") { fldCount = e.Node.GetNodeCount(false); //column headers. int n = lvData.Width; double wid = n / fldCount; // width columnn for (int c = 0; c < fldCount; c++) { lvData.Columns.Add(e.Node.Nodes[c].Text, (int)wid, HorizontalAlignment.Left); } // gett table name tabName = e.Node.Text; FillListView(datCon, tabName); } } public void button1_Click(object sender, EventArgs e) { //TO DO?? } } I have a treeview populated with tables (nodes) from my database, and a listview which is populated with the data from my tables when I click on a table. As you can see I have a button1 on my form. When I click it I want it to display to me the structure of the table I selected in my treeview (a treeview node). Not too many details, just the name of the columns in my table, type of columns, primary keys. I've tried to follow many tutorials but I can t seem to manage it.

    Read the article

  • Collision disturbing the jumping mechanic in java 2D game [on hold]

    - by user50931
    So I have been working on a 2D Java game recently and everything was going smoothly, until I reached a problem to do with the players jumping mechanic. So far I've got the player to jump a fixed rate and fall due to gravity. Hers my code for my Player class. public class Player extends GameObject { public Player(int x, int y, int width, int height, ObjectId id) { super(x, y, width, height, id); } @Override public void tick(ArrayList<GameObject> object) { if(go){ x+=vx; y+=vy; } if(vx <0){ facing =-1; }else if(vx >0) facing =1; checkCollision(object); checkStance(); } private void checkStance() { if(falling){ //gravity jumping = false; vy = speed/2; } if(jumping){ // Calculates how high jump should be vy = -speed*2; if(jumpY - y >= maxJumpHeight) falling =true; } } private void checkCollision(ArrayList<GameObject> object) { for(int i=0; i< object.size(); i++ ){ GameObject tempObject = object.get(i); if(tempObject.getId() == ObjectId.Ledge){ if(getBoundsTop().intersects(tempObject.getBoundsAll())){ //Top y = tempObject.getY() + tempObject.getBoundsAll().height; falling =true; } if(getBoundsRight().intersects(tempObject.getBoundsAll())){ // Right x = tempObject.getX() -width ; } if(getBoundsLeft().intersects(tempObject.getBoundsAll())){ //Left x = tempObject.getX() + tempObject.getWidth(); } if(getBoundsBottom().intersects(tempObject.getBoundsAll())){ //Bottom y = tempObject.getY() - height; falling =false; vy=0; }else{ falling =true; } } } } @Override public void render(Graphics g) { g.setColor(Color.BLACK); g.fillRect((int)x, (int)y, width, height); } @Override public Rectangle getBoundsAll() { return new Rectangle((int)x, (int)y,width,height); } public Rectangle getBoundsTop() { return new Rectangle((int) x , (int)y ,width,height/15); } public Rectangle getBoundsBottom() { return new Rectangle( (int)x , (int) y +height -(height /15),width,height/15); } public Rectangle getBoundsLeft() { return new Rectangle( (int) x , (int) y + height /10 ,width/8,height - (height /5)); } public Rectangle getBoundsRight() { return new Rectangle((int) x + width - (width/8) ,(int) y + height /10 ,width/8,height - height/5); } } My problem is when I add: else{ falling =true; } during the loop of the ArrayList to check collision, it stops the player from jumping and keeps him on the ground. I've tried to find a way around this but haven't had any luck. Any suggestions?

    Read the article

  • Dynamic Strategy Pattern [migrated]

    - by Karl Barker
    So I'm writing a web service architecture which includes FunctionProvider classes which do the actual processing of requests, and a main Endpoint class which receives and delegates requests to the proper FunctionProvider. I don't know exactly the FunctionProviders available at runtime, so I need to be able to 'register' (if that's the right word) them with my main Endpoint class, and query them to see if they match an incoming request. public class MyFunc implements FunctionProvider{ static { MyEndpoint.register(MyFunc); } public Boolean matchesRequest(Request req){...} public void processRequest(Request req){...} } public class MyEndpoint{ private static ArrayList<FunctionProvider> functions = new ArrayList<FunctionProvider>(); public void register(Class clz){ functions.add(clz); } public void doPost(Request request){ //find the FunctionProvider in functions //matching the request } } I've really not done much reflective Java like this (and the above is likely wrong, but hopefully demonstrates my intentions). What's the nicest way to implement this without getting hacky?

    Read the article

  • Player position triggering teleports

    - by jSherz
    I'm developing a Minecraft plugin (bukkit) in which a server admin can create 'portals' - a small region that will teleport any players who enter it. I have the teleportation sorted and I know how I could define areas that the player's position could be tested against. This would involve an ArrayList containing the zones and then hooking the PlayerMoveEvent so that the ArrayList is searched each time for a matching portal region. Although this method would work, I doubt that it would be very efficient when 100+ players are all moving around at the same time. Is there a better way of checking a player position against a set of 'zones' / regions?

    Read the article

  • Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException

    - by Dheeraj kumar
    Hi, I have to read xls file in java.I used poi-3.6 to read xls file in Eclipse.But i m getting this ERROR"Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException at ReadExcel2.main(ReadExcel2.java:38)". I have added following jars 1)poi-3.6-20091214.jar 2)poi-contrib-3.6-20091214.jar 3)poi-examples-3.6-20091214.jar 4)poi-ooxml-3.6-20091214.jar 5)poi-ooxml-schemas-3.6-20091214.jar 6)poi-scratchpad-3.6-20091214.jar Below is the code which i m using: import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.ArrayList; public class ReadExcel { public static void main(String[] args) throws Exception { // // An excel file name. You can create a file name with a full path // information. // String filename = "C:\\myExcel.xl"; // // Create an ArrayList to store the data read from excel sheet. // List sheetData = new ArrayList(); FileInputStream fis = null; try { // // Create a FileInputStream that will be use to read the excel file. // fis = new FileInputStream(filename); // // Create an excel workbook from the file system. // // HSSFWorkbook workbook = new HSSFWorkbook(fis); Workbook workbook = new XSSFWorkbook(fis); // // Get the first sheet on the workbook. // Sheet sheet = workbook.getSheetAt(0); // // When we have a sheet object in hand we can iterator on each // sheet's rows and on each row's cells. We store the data read // on an ArrayList so that we can printed the content of the excel // to the console. // Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { Row row = (XSSFRow) rows.next(); Iterator cells = row.cellIterator(); List data = new ArrayList(); while (cells.hasNext()) { Cell cell = (XSSFCell) cells.next(); data.add(cell); } sheetData.add(data); } } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { fis.close(); } } showExelData(sheetData); } private static void showExelData(List sheetData) { // // Iterates the data and print it out to the console. // for (int i = 0; i < sheetData.size(); i++) { List list = (List) sheetData.get(i); for (int j = 0; j < list.size(); j++) { Cell cell = (XSSFCell) list.get(j); System.out.print(cell.getRichStringCellValue().getString()); if (j < list.size() - 1) { System.out.print(", "); } } System.out.println(""); } } } Please help. thanks in anticipation, Regards, Dheeraj!

    Read the article

  • HTTP error code 405: tomcat Url mapping issue

    - by Andrew
    I am having trouble POSTing to my java HTTPServlet. I am getting "HTTP Status 405 - HTTP method GET is not supported by this URL" from my tomcat server". When I debug the servlet the login method is never called. I think it's a url mapping issue within tomcat... web.xml <servlet-mapping> <servlet-name>faxcom</servlet-name> <url-pattern>/faxcom/*</url-pattern> </servlet-mapping> FaxcomService.java @Path("/rest") public class FaxcomService extends HttpServlet{ private FAXCOM_x0020_ServiceLocator service; private FAXCOM_x0020_ServiceSoap port; @GET @Produces("application/json") public String testGet() { return "{ \"got here\":true }"; } @POST @Path("/login") @Consumes("application/json") // @Produces("application/json") public Response login(LoginBean login) { ArrayList<ResultMessageBean> rm = new ArrayList<ResultMessageBean>(10); try { service = new FAXCOM_x0020_ServiceLocator(); service.setFAXCOM_x0020_ServiceSoapEndpointAddress("http://cd-faxserver/faxcom_ws/faxcomservice.asmx"); service.setMaintainSession(true); // enable sessions support port = service.getFAXCOM_x0020_ServiceSoap(); rm.add(new ResultMessageBean(port.logOn( "\\\\CD-Faxserver\\FaxcomQ_API", /* path to the queue */ login.getUserName(), /* username */ login.getPassword(), /* password */ login.getUserType() /* 2 = user conf user */ ))); } catch (RemoteException e) { e.printStackTrace(); } catch (ServiceException e) { e.printStackTrace(); } // return rm; return Response.status(201).entity(rm).build(); } @POST @Path("/newFaxMessage") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ArrayList<ResultMessageBean> newFaxMessage(FaxBean fax) { ArrayList<ResultMessageBean> rm = new ArrayList<ResultMessageBean>(); try { rm.add(new ResultMessageBean(port.newFaxMessage( fax.getPriority(), /* priority: 0 - low, 1 - normal, 2 - high, 3 - urgent */ fax.getSendTime(), /* send time */ /* "0.0" - immediate */ /* "1.0" - offpeak */ /* "9/14/2007 5:12:11 PM" - to set specific time */ fax.getResolution(), /* resolution: 0 - low res, 1 - high res */ fax.getSubject(), /* subject */ fax.getCoverpage(), /* cover page: "" – default, “(none)� – no cover page */ fax.getMemo(), /* memo */ fax.getSenderName(), /* sender's name */ fax.getSenderFaxNumber(), /* sender's fax */ fax.getRecipients().get(0).getName(), /* recipient's name */ fax.getRecipients().get(0).getCompany(), /* recipient's company */ fax.getRecipients().get(0).getFaxNumber(), /* destination fax number */ fax.getRecipients().get(0).getVoiceNumber(), /* recipient's phone number */ fax.getRecipients().get(0).getAccountNumber() /* recipient's account number */ ))); if (fax.getRecipients().size() > 1) { for (int i = 1; i < fax.getRecipients().size(); i++) rm.addAll(addRecipient(fax.getRecipients().get(i))); } } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rm; } } Main.java private static void main(String[] args) { try { URL url = new URL("https://andrew-vm/faxcom/rest/login"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); FileInputStream jsonDemo = new FileInputStream("login.txt"); OutputStream os = (OutputStream) conn.getOutputStream(); os.write(IOUtils.toByteArray(jsonDemo)); os.flush(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } // Don't want to disconnect - servletInstance will be destroyed // conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } I am working from this tutorial: http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >