Array of cfc object help

I just picked up coldfusion about a month ago, so my
coldfusion lingo sucks. I have been programming in C++ for over 5
years now and will be using a lot of C++ terminology to help avoid
any confusion. I am writing a cfc function that preforms web
servicing. This function needs to return an object/class that is
defined in another coldfusion function. I can do this without a
problem if I only need to return one instance of this object.
However, I cannot seem to return an array of this object (I need to
return multiple instances of this object, kind of like a query, but
for programming purposes it needs to stay as an object).
It seems that the webservicing function hates my return type.
If I try to make an array of the object, it does not like array or
the object as the return type. However, when I take this function
out of the cfc, and make it a cfm, it gets the array of objects
just fine. So, I think I am having issues with the return type on
the <cffunction> tag. So I came up with the idea of creating
another object which will hold an array of the first object and
using the second object as the return type. Here is some psuedo
code of the function I am working on:
<cffunction name="SelectGames" access="remote"
returntype="ArrayOfGames" output="false">
<!-- arguments --->
<!--- query --->
<cfobject component = "myArray" name>
<cfobject component="games" name="test">
<cfset counter = 0>
<cfloop query="getevents">
<cfset counter = counter + 1>
<cfset test.Game_id = event_id>
<cfset test.gameDate = eventdate>
<cfset test.Starttime = starttime>
<cfset test.Place = place>
<cfset test.Level = level>
<cfset test.Sport = sport>
<cfset test.Gender = division>
<cfset test.Opponent = opponent_id>
<cfset test.Type = type>
<cfset test.Link = spec_name>
<cfset myArray.gamesArray[counter] = test>
</cfloop>
<cfreturn myArray>
</cffunction>
It keeps telling me that it does not recognize the return
type.
Here are examples of the two objects I am using from the 2
dif. cfc files:
<cfcomponent>
<cfproperty name="gamesArray" type="array">
</cfcomponent>
<cfcomponent>
<cfproperty name="Game_id" type="numeric">
<cfproperty name="gameDate" type="date">
<cfproperty name="Starttime" type="string">
<cfproperty name="Place" type="string">
<cfproperty name="Level" type="string">
<cfproperty name="Sport" type="string">
<cfproperty name="Gender" type="string">
<cfproperty name="Opponent" type="string">
<cfproperty name="Type" type="string">
<cfproperty name="Link" type="string">
</cfcomponent>
Feel free to post any questions to clear anything up, I know
this is confusing and I probably did a poor job of explaining my
problem. Also, if I throw this code into a cfm and try to make an
array of games, it works, this is the code I got it to work with:
<cfset myArray = newArray(1)>
<cfloop query="getevents">
<cfset counter = counter + 1>
<cfset test.Game_id = event_id>
<cfset test.gameDate = eventdate>
<cfset test.Starttime = starttime>
<cfset test.Place = place>
<cfset test.Level = level>
<cfset test.Sport = sport>
<cfset test.Gender = division>
<cfset test.Opponent = opponent_id>
<cfset test.Type = type>
<cfset test.Link = spec_name>
<cfset myArray[counter] = test>
</cfloop>
I guess my problem is I do not know how to specify a type for
an array.

The return type of this FUNCTION would be returnType="array".
No matter
what kind of data the array contained.
That's what I get for fast proofing.
Ian Skinner wrote:
> I would have to play with your code more if this does
not clear it up
> for you, but lets start with this simple concept first.
>
> You mentioned "typing the array" several times.
ColdFusion is typeless,
> you don't type an array, it is just array. An array of
strings is the
> same as an array of integers which is the same as an
array of objects.
>
> So if you had a function something like this.
>
> <cffunction returnType="array" ...>
> <cfset theArray = arrayNew()>
>
> <cfloop ...>
> <cfset arrayAppend(theArray, newObject)>
> </cfloop>
>
> <cfreturn theArray>
> </cffunction>
>
> The return type of this function would be
returnType="array". No matter what
> kind of data the array contained.
>
> mwiley63 wrote:
>> I just picked up coldfusion about a month ago, so my
coldfusion lingo
>> sucks. I have been programming in C++ for over 5
years now and will
>> be using a lot of C++ terminology to help avoid any
confusion. I am
>> writing a cfc function that preforms web servicing.
This function
>> needs to return an object/class that is defined in
another coldfusion
>> function. I can do this without a problem if I only
need to return
>> one instance of this object. However, I cannot seem
to return an
>> array of this object (I need to return multiple
instances of this
>> object, kind of like a query, but for programming
purposes it needs to
>> stay as an object).
>> It seems that the webservicing function hates my
return type. If I
>> try to make an array of the object, it does not like
array or the
>> object as the return type. However, when I take this
function out of
>> the cfc, and make it a cfm, it gets the array of
objects just fine.
>> So, I think I am having issues with the return type
on the
>> <cffunction> tag. So I came up with the idea
of creating another
>> object which will hold an array of the first object
and using the
>> second object as the return type. Here is some
psuedo code of the
>> function I am working on:
>>
>> <cffunction name="SelectGames" access="remote"
>> returntype="ArrayOfGames" output="false">
>> <!-- arguments --->
>> <!--- query --->
>> <cfobject component = "myArray" name>
>> <cfobject component="games" name="test">
>> <cfset counter = 0>
>> <cfloop query="getevents">
>> <cfset counter = counter + 1>
>> <cfset test.Game_id = event_id>
>> <cfset test.gameDate = eventdate>
>> <cfset test.Starttime = starttime>
>> <cfset test.Place = place>
>> <cfset test.Level = level>
>> <cfset test.Sport = sport>
>> <cfset test.Gender = division>
>> <cfset test.Opponent = opponent_id>
>> <cfset test.Type = type>
>> <cfset test.Link = spec_name>
>> <cfset myArray.gamesArray[counter] = test>
>> </cfloop>
>> <cfreturn myArray>
>> </cffunction>
>>
>> It keeps telling me that it does not recognize the
return type.
>> Here are examples of the two objects I am using from
the 2 dif. cfc
>> files:
>> <cfcomponent>
>> <cfproperty name="gamesArray" type="array">
>> </cfcomponent>
>> <cfcomponent>
>> <cfproperty name="Game_id" type="numeric">
>> <cfproperty name="gameDate" type="date">
>> <cfproperty name="Starttime" type="string">
>> <cfproperty name="Place" type="string">
>> <cfproperty name="Level" type="string">
>> <cfproperty name="Sport" type="string">
>> <cfproperty name="Gender" type="string">
>> <cfproperty name="Opponent" type="string">
>> <cfproperty name="Type" type="string">
>> <cfproperty name="Link" type="string">
>> </cfcomponent>
>>
>> Feel free to post any questions to clear anything
up, I know this is
>> confusing and I probably did a poor job of
explaining my problem.
>> Also, if I throw this code into a cfm and try to
make an array of
>> games, it works, this is the code I got it to work
with:
>> <cfset myArray = newArray(1)>
>> <cfloop query="getevents">
>> <cfset counter = counter + 1>
>> <cfset test.Game_id = event_id>
>> <cfset test.gameDate = eventdate>
>> <cfset test.Starttime = starttime>
>> <cfset test.Place = place>
>> <cfset test.Level = level>
>> <cfset test.Sport = sport>
>> <cfset test.Gender = division>
>> <cfset test.Opponent = opponent_id>
>> <cfset test.Type = type>
>> <cfset test.Link = spec_name>
>> <cfset myArray[counter] = test>
>> </cfloop>
>>
>> I guess my problem is I do not know how to specify a
type for an array.
>>

Similar Messages

  • I want to create a 3*3 multidimensional array of label objects

    i want to initialize the array with label objects help me

    If this post answers your question or helps, please mark it as such.
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
      creationComplete="init();">
      <mx:Script>
        <![CDATA[
          import mx.controls.Label;
          private var arr:Array = new Array();
          private function init():void{
            for(var a:uint=0;a<10;a++){
              var inArr1:Array = new Array();
              for(var b:uint=0;b<10;b++){
                  var inArr2:Array = new Array();
                for(var c:uint=0;c<10;c++){
                  var lbl:Label = new Label();
                  lbl.text = "Label" + a + b + c;
                  inArr2.push(lbl);
                inArr1.push(inArr2);
              arr.push(inArr1);
            for each(var xArr:Array in arr){
              for each(var yArr:Array in xArr){
                for each(var lbl2:Label in yArr){
                  txt.text += lbl2.text + " ";
        ]]>
      </mx:Script>
      <mx:TextArea width="100%" height="100%" id="txt"/>
    </mx:Application>

  • Newbie - help needed with array and dictionary objects

    Hi all
    Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
    The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
    I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
    I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
    Any help again is very much appreciated.
    // Open the database connection and retrieve minimal information for all objects.
    - (void)initializeDatabase {
    NSMutableArray *authorArray = [[NSMutableArray alloc] init];
    self.authors = authorArray;
    [authorArray release];
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // Get the primary key for all books.
    const char *sql = "SELECT id, author FROM author";
    sqlite3_stmt *statement;
    // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
    // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
    if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
    // We "step" through the results - once for each row.
    // We start with Letter A...we're building an A - Z grouping
    NSString *letter = @"A";
    NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
    while (sqlite3_step(statement) == SQLITE_ROW) {
    author *author = [[author alloc] init];
    author.primaryKey = sqlite3columnint(statement, 0);
    author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
    // FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
    // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
    // autorelease is slightly more expensive than release. This design choice has nothing to do with
    // actual memory management - at the end of this block of code, all the book objects allocated
    // here will be in memory regardless of whether we use autorelease or release, because they are
    // retained by the books array.
    // if the author starts with the Letter we currently have, add it to the temp array
    if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
    [tempauthors addObject:author];
    } // if this is different letter, then we need to deal with that too...
    else {
    // create a dictionary to store the current tempauthors array in...
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    // add the dictionary to our appDelegate-level array
    [authors addObject:tempDictionary];
    // now prepare for the next loop...
    // set the new letter...
    letter = [author.title substringToIndex:1];
    // remove all of the previous authors so we don't duplicate...
    [tempauthors removeAllObjects];
    // add the current author as this was the one that didn't match the Letter and so
    // never went into the previous array...
    [tempauthors addObject:author];
    // release ready for the next loop...
    [author release];
    // clear up the remaining authors that weren't picked up and saved in the "else" statement above...
    if (tempauthors.count > 0){
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    [authors addObject:tempDictionary];
    else {
    printf("Failed preparing statement %s
    ", sqlite3_errmsg(database));
    // "Finalize" the statement - releases the resources associated with the statement.
    sqlite3_finalize(statement);
    } else {
    // Even though the open failed, call close to properly clean up resources.
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    // Additional error handling, as appropriate...
    Message was edited by: dotnetter

    Ok, so I know what the issue is now...I just don't know enough to be able to resolve it!
    it's the tempAuthors objects.
    It's an NSMutableArray which is create on the line before the start of the WHILE loop.
    Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
    Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
    Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
    I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
    Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
    Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
    I am continuing to read up on memory management etc but just not there yet.
    Regards
    Wayne

  • Array of CreditCard objects - PLEASE HELP!

    My situation is this: I need to create an array of CreditCard objects. The problem is that when I try to invoke the methods getName, getNumber, or getLimit, the compiler recognizes the array (cardholders) as a variable.
    My coding is this.
    for(int i=0;fileInput.hasNext();i++)
         CreditCard[] cardholders = new CreditCard[records];
         int cardNum = Integer.parseInt(fileInput.next());
         String cardName = fileInput.nextLine();
         double cardLimit = Double.parseDouble(fileInput.nextLine());
         cardholders[i] = new CreditCard(cardNum, cardName, cardLimit);
    But when I try to access a CreditCard object, through cardholders[4] (for example), the error cannot find symbol appears. PLEASE HELP ITS DRIVING ME CRAZY.
    THANKS

    You are lacking basic Java knowledge, micksabox. The following tutorial is on Arrays in Java. The one after on the Java Collections Framework, you might want to learn about as the better solution for working with sets and lists of objects in Java.
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
    http://java.sun.com/docs/books/tutorial/collections/index.html

  • Help, store an array of cd objects

    im doing a java project on creating a music cd database, i need to store an array of cd objects, each entry in the array will be a single object for a cd.
    The objects are: Artist, Album, No of tracks
    I need some help with this, thanks
    here's the code ive done so far:
    import javax.swing.JOptionPane;
    class Cd1
         public static void main (String[] args)
              int menu_choice;
              CdRecord one = new CdRecord();
              one.artist_name = JOptionPane.showInputDialog("Enter artist name.");
              one.album_name = JOptionPane.showInputDialog("Enter album name.");
              one.no_of_tracks =Integer.parseInt(JOptionPane.showInputDialog("Enter the number of tracks on the album"));
         one.printCdRecord();          
    class CdRecord
         public String artist_name;
         public String album_name;
         public int no_of_tracks;
    public CdRecord (String artist, String album, int tracks, int year)
         artist_name = artist;
         album_name = album;
         no_of_tracks = tracks;
    public CdRecord()
    artist_name = "A";
    album_name = "B";
    no_of_tracks = 0;
    public void printCdRecord ()
    String o = "Artist Name: " + artist_name + "\nAlbum Name: " album_name"\nNo. Of Tracks: " + no_of_tracks;;
    System.out.println(o);
    }

    where should i put this in my code?this part would normally be a class field, accessible from many parts of the class
    java.util.List<CdRecord> records;to it may look something like this
    class Cd1
      private java.util.List<CdRecord> records;//and use constructor to create
      //or
      private java.util.List<CdRecord> records = new java.util.ArrayList<CdRecord>();
      ...as is, the above will cause you a problem because you have most of your code in main() which is static.
    before you go much further, rethink your program design:
    - your class name is Cd1, which would indicate a single CD, but you're doing a CD database so call it CdInventory, CdCollection, etc
    - the only code you want in main() is to start the program, so that would be new CdInventory(), nothing more (unless creating a GUI)
    - how are you going to get new records - a GUI with buttons add/edit/delete, or the console.
    - are you going to save new/edited records to a file (the database), and read existing data back into the program at startup
    - basically how you go about the above determines what you have in the constructor of the program (and do not use main() for this)

  • Re: Beginner needs help using a array of class objects, and quick

    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
    I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
    Is there a way to discard and replace a post (with html source code) in the Sun forum ?
    Thanks for your help.
    Chavada

    chavada wrote:
    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
    [code]
    public class Foo() {
      * This is the bar method
      public void bar() {
        // do stuff
    }[/code]

  • HELP! "array required, but object found" :S

    Halo I'm new to Java and on one of my exercises I'm getting the following compile error and don't know why :S
    "array required but Deck found"
    Here is the code:
    //Card.java this defines the Card class and object
    public class Card {
    private final int rank;
    private final int suit;
    // Kinds of suits
    public final static int DIAMONDS = 1;
    public final static int CLUBS = 2;
    public final static int HEARTS = 3;
    public final static int SPADES = 4;
    // Kinds of ranks
    public final static int ACE = 1;
    public final static int DEUCE = 2;
    public final static int THREE = 3;
    public final static int FOUR = 4;
    public final static int FIVE = 5;
    public final static int SIX = 6;
    public final static int SEVEN = 7;
    public final static int EIGHT = 8;
    public final static int NINE = 9;
    public final static int TEN = 10;
    public final static int JACK = 11;
    public final static int QUEEN = 12;
    public final static int KING = 13;
    public Card(int rank, int suit) {
    assert isValidRank(rank);
    assert isValidSuit(suit);
    this.rank = rank;
    this.suit = suit;
    public int getSuit() {
    return suit;
    public int getRank() {
    return rank;
    public static boolean isValidRank(int rank) {
    return ACE <= rank && rank <= KING;
    public static boolean isValidSuit(int suit) {
    return DIAMONDS <= suit && suit <= SPADES;
    public static String rankToString(int rank) {
    switch (rank) {
    case ACE:
    return "Ace";
    case DEUCE:
    return "Deuce";
    case THREE:
    return "Three";
    case FOUR:
    return "Four";
    case FIVE:
    return "Five";
    case SIX:
    return "Six";
    case SEVEN:
    return "Seven";
    case EIGHT:
    return "Eight";
    case NINE:
    return "Nine";
    case TEN:
    return "Ten";
    case JACK:
    return "Jack";
    case QUEEN:
    return "Queen";
    case KING:
    return "King";
    default:
    return null;
    public static String suitToString(int suit) {
    switch (suit) {
    case DIAMONDS:
    return "Diamonds";
    case CLUBS:
    return "Clubs";
    case HEARTS:
    return "Hearts";
    case SPADES:
    return "Spades";
    default:
    return null;
    // Deck.java creates a deck of cards:P
    import java.util.*;
    public class Deck {
    public static int numSuits = 4;
    public static int numRanks = 13;
    public static int numCards = numSuits * numRanks;
    public Card[][] cards;
    public Deck() {
    cards = new Card[numSuits][numRanks];
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
    for (int rank = Card.ACE; rank <= Card.KING; rank++) {
    cards[suit-1][rank-1] = new Card(rank, suit);
    public Card getCard(int suit, int rank) {
    return cards[suit-1][rank-1];
    //AND finally, DisplayDeck.java that creates a deck of cards and display the cards of a deck:P
    import java.util.*;
    public class DisplayDeck {
    public static void main(String[] args) {
    Deck bobbysDeck = new Deck();
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
    for (int rank = Card.ACE; rank <= Card.KING; rank++) {
    System.out.format("%s of %s%n",
    Card.rankToString(bobbysDeck[suit-1][rank-1].getrank()), //<---here is where I get the error
    Card.suitToString(bobbysDeck[suit-1][rank-1].getsuit())); // <----and here too
    bobbysDeck is an array, so why is it giving me this compile error? Thank you very much for your help.

    For the benefit of others, here is Deck displayed with code tags:
    public class Deck
      public static int numSuits = 4;
      public static int numRanks = 13;
      public static int numCards = numSuits * numRanks;
      public Card[][] cards;
      public Deck()
        cards = new Card[numSuits][numRanks];
        for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
          for (int rank = Card.ACE; rank <= Card.KING; rank++)
            cards[suit - 1][rank - 1] = new Card(rank, suit);
      public Card getCard(int suit, int rank)
        return cards[suit - 1][rank - 1];
    }You'll see that Deck holds an array of Card objects in its cards field. You could if you desired directly access that field and use that as an array like so:
      public static void main(String[] args)
        Deck bobbysDeck = new Deck();
        for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
          for (int rank = Card.ACE; rank <= Card.KING; rank++)
            Card card = bobbysDeck.cards[suit - 1][rank - 1];
            System.out.format("%s of %s%n",
                Card.rankToString(card.getRank()),
                Card.suitToString(card.getSuit()));
      }but this allows outside classes to mess around with the innards of the Deck class in ways that we cannot control and can cause nasty bugs to appear that are very hard to identify and remove. Some class could for instance delete all the Card objects in cards. Much better and much safer is to make Deck's card variable a private variable and to only get the information through public methods, methods that allow the Deck class to control access. Notice that with this method, we can only get the card information; we can't delte or change it. So better is this:
      public static void main(String[] args)
        Deck bobbysDeck = new Deck();
        for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
          for (int rank = Card.ACE; rank <= Card.KING; rank++)
            Card card = bobbysDeck.getCard(suit, rank);
            System.out.format("%s of %s%n",
                Card.rankToString(card.getRank()),
                Card.suitToString(card.getSuit()));
      }

  • How can I send a mapping based CFC object?

    I got an exception on sending a CFC object through
    EventGateway for Flex Messaging. The result of SendGatewayMessage
    says
    FALSE: Error on server: java.rmi.UnmarshalException: error
    unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: coldfusion.runtime.Array (no
    security manager: RMI class loader disabled)
    If the CFC is under web root, it works... I changed
    eventgateway config (e.g. use-structs, use-accessors, adding
    use-mappings) and tried them. But it does not work at all.
    Is this a bug?

    Well the OO theory says that objects comunicate via messages, now that information must be taken as knowledge only, not for programming issues really. What you need to know is that when you need to pass any data from onw object to another you can send them via parameters of defined methods.
    For example you have an Object called R of a receiver class and that object needs to pass a String (text message) to another object. you can do it via a method.

  • I can't seem to get individual elements when comparing 2 arrays using Compare-Object

    My backup software keeps track of servers with issues using a 30 day rolling log, which it emails to me once a week in CSV format. What I want to do is create a master list of servers, then compare that master list against the new weekly lists to identify
    servers that are not in the master list, and vice versa. That way I know what servers are new problem and which ones are pre-existing and which ones dropped off the master list. At the bottom is the entire code for the project. I know it's a bit much
    but I want to provide all the information, hopefully making it easier for you to help me :)
    Right now the part I am working on is in the Compare-NewAgainstMaster function, beginning on line 93. After putting one more (fake) server in the master file, the output I get looks like this
    Total entries (arrMasterServers): 245
    Total entries (arrNewServers): 244
    Comparing new against master
    There are 1 differences.
    InputObject SideIndicator
    @{Agent= Virtual Server in vCenterServer; Backupse... <=
    What I am trying to get is just the name of the server, which should be $arrDifferent[0] or possibly $arrDifferent.Client. Once I have the name(s) of the servers that are different, then I can do stuff with that. So either I am not accessing the array
    right, building the array right, or using Compare-Object correctly.
    Thank you!
    Sample opening lines from the report
    " CommCells > myComCellServer (Reports) >"
    " myComCellServer -"
    " 30 day SLA"
    CommCell Details
    " Client"," Agent"," Instance"," Backupset"," Subclient"," Reason"," Last Job Id"," Last Job End"," Last Job Status"
    " myServerA"," vCenterServer"," VMware"," defaultBackupSet"," default"," No Job within SLA Period"," 496223"," Nov 17, 2014"," Killed"
    " myServerB"," Oracle Database"," myDataBase"," default"," default"," No Job within SLA Period"," 0"," N/A"," N/A"
    Entire script
    # things to add
    # what date was server entered in list
    # how many days has server been on list
    # add temp.status = pre-existing, new, removed from list
    # copy sla_master before making changes. Copy to archive folder, automate rolling 90 days?
    ## 20150114 Created script ##
    #declare global variables
    $global:arrNewServers = @()
    $global:arrMasterServers = @()
    $global:countNewServers = 1
    function Get-NewServers
    Param($path)
    Write-Host "Since we're skipping the 1st 6 lines, create test to check for opening lines of report from CommVault."
    write-host "If not original report, break out of script"
    Write-Host ""
    #skip 5 to include headers, 6 for no headers
    (Get-Content -path $path | Select-Object -Skip 6) | Set-Content $path
    $sourceNewServers = get-content -path $path
    $global:countNewServers = 1
    foreach ($line in $sourceNewServers)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0].Substring(2, $tempLine[0].Length-3)
    $temp.Agent = $tempLine[1].Substring(2, $tempLine[1].Length-3)
    $temp.Backupset = $tempLine[3].Substring(2, $tempLine[3].Length-3)
    $temp.Reason = $tempLine[5].Substring(2, $tempLine[5].Length-3)
    #write temp object to array
    $global:arrNewServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countNewServers ++
    Write-Host ""
    $exportYN = Read-Host "Do you want to export new servers to new master list?"
    $exportYN = $exportYN.ToUpper()
    if ($exportYN -eq "Y")
    $exportPath = Read-Host "Enter full path to export to"
    Write-Host "Exporting to $($exportPath)"
    foreach ($server in $arrNewServers)
    $newtext = $Server.Client + ", " + $Server.Agent + ", " + $Server.Backupset + ", " + $Server.Reason
    Add-Content -Path $exportPath -Value $newtext
    function Get-MasterServers
    Param($path)
    $sourceMaster = get-content -path $path
    $global:countMasterServers = 1
    foreach ($line in $sourceMaster)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0]
    $temp.Agent = $tempLine[1]
    $temp.Backupset = $tempLine[2]
    $temp.Reason = $tempLine[3]
    #write temp object to array
    $global:arrMasterServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countMasterServers ++
    function Compare-NewAgainstMaster
    Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    Write-Host "Total entries (arrNewServers): $($countNewServers)"
    Write-Host "Comparing new against master"
    #Compare-Object $arrMasterServers $arrNewServers
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Write-Host "There are $($arrDifferent.Count) differences."
    foreach ($item in $arrDifferent)
    $item
    ## BEGIN CODE ##
    cls
    $getMasterServersYN = Read-Host "Do you want to get master servers?"
    $getMasterServersYN = $getMasterServersYN.ToUpper()
    if ($getMasterServersYN -eq "Y")
    $filePathMaster = Read-Host "Enter full path and file name to master server list"
    $temp = Test-Path $filePathMaster
    if ($temp -eq $false)
    Read-Host "File not found ($($filePathMaster)), press any key to exit script"
    exit
    Get-MasterServers -path $filePathMaster
    $getNewServersYN = Read-Host "Do you want to get new servers?"
    $getNewServersYN = $getNewServersYN.ToUpper()
    if ($getNewServersYN -eq "Y")
    $filePathNewServers = Read-Host "Enter full path and file name to new server list"
    $temp = Test-Path $filePathNewServers
    if ($temp -eq $false)
    Read-Host "File not found ($($filePath)), press any key to exit script"
    exit
    Get-NewServers -path $filePathNewServers
    #$global:arrNewServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrNewServers): $($countNewServers)"
    #Write-Host ""
    #$global:arrMasterServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    #Write-Host ""
    Compare-NewAgainstMaster

    do not do this:
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Try this:
    $arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
    ¯\_(ツ)_/¯
    This is what made the difference. I guess you don't have to declare arrDifferent as an array, it is automatically created as an array when Compare-Object runs and fills it with the results of the compare operation. I'll look at that "pass thru" option
    in a little more detail. Thank you very much!
    Yes - this is the way PowerShell works.  You do not need to write so much code once you understand what PS can and is doing.
    ¯\_(ツ)_/¯

  • How to pass Array of Java objects to Callable statement

    Hi ,
    I need to know how can I pass an array of objects to PL/SQL stored procedure using callable statement.
    So I am having and array list of some object say xyz which has two attributes string and double type.
    Now I need to pass this to a PL/SQL Procedure as IN parameter.
    Now I have gone through some documentation for the same and found that we can use ArrayDescriptor tp create array (java.sql.ARRAY).
    And we will use a record type from SQL to map this to our array of java objects.
    So my question is how this mapping of java object's two attribute will be done to the TYPE in SQL? can we also pass this array as a package Table?
    Please help
    Thanks

    I seem to remember that that is in one of Oracle's online sample programs.
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/index.html

  • How to call a method using a array of that object?

    hey, another array question
    for example i have 2 classes one name class and a driver
    inside the name class i have method that gets the name
    public Name getName1( ) {return name1;}
    my question is if i created an array of Name objects in my driver with the following line
    Name [ ] n1 = new Name [ ] ;
    and i wanna call methods inside the name class using my array of Name that i created how do i do it?
    thanks in advance

    thanks for the reply Maxx
    another question regarding arrays
    for example if im doing an array of objects Name[ ] n1 = new Name [ ]
    and i have a method that removes the name if its the same as the user input
    if (n1[ i ].getName.equals(myName))
    / / if they equal it removes it,
    else,
    / / the n[ 1 ] stays the same
    ive search the forum for previous questions on this but their examples doesnt seems to work, can anyone help? also if end up using this remove method that checks the elements in n1 if it matches it will remove it what should i do to avoid nullpointerexceptions if i wanna shift it all down?
    thanks in advance

  • Passing Array of java objects to and from oracle database-Complete Example

    Hi all ,
    I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
    First thinsg first
    i) Create a Java Value Object which you want to pass .
    create or replace and compile java source named Person as
    import java.sql.*;
    import java.io.*;
    public class Person implements SQLData
    private String sql_type = "PERSON_T";
    public int person_id;
    public String person_name;
    public Person () {}
    public String getSQLTypeName() throws SQLException { return sql_type; }
    public void readSQL(SQLInput stream, String typeName) throws SQLException
    sql_type = typeName;
    person_id = stream.readInt();
    person_name = stream.readString();
    public void writeSQL(SQLOutput stream) throws SQLException
    stream.writeInt (person_id);
    stream.writeString (person_name);
    ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
    you should see a message called "Java created."
    iii) Now create your object Types
    CREATE TYPE person_t AS OBJECT
    EXTERNAL NAME 'Person' LANGUAGE JAVA
    USING SQLData (
    person_id NUMBER(9) EXTERNAL NAME 'person_id',
    person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
    iv) Now create a table of Objects
    CREATE TYPE person_tab IS TABLE OF person_t;
    v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
    create or replace
    procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
    as
    l_person_id Number;
    l_person_name Varchar2(200);
    l_person person_t;
    l_p_arrayout person_tab;
    errm Varchar2(2000);
    begin
         l_p_arrayout := person_tab();
    for i in 1 .. p_array.count
    loop
         l_p_arrayout.extend;
         insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
         l_person_id := p_array(i).person_id;
         l_person_name := p_array(i).person_name;
         l_person := person_t(null,null);
         l_person.person_id := l_person_id + 5;
         l_person.person_name := 'Out Record ' ||l_person_name ;
         l_p_arrayout(i) := l_person;
    end loop;
    p_arrayout := l_p_arrayout;
         l_person_id := p_arrayout.count;
    for i in 1 .. p_arrayout.count
    loop
    insert into person_test values(l_person_id, p_arrayout(i).person_name);
    end loop;
    commit;
    EXCEPTION WHEN OTHERS THEN
         errm := SQLERRM;
         insert into person_test values(-1, errm);
         commit;
    end;
    vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
    import java.util.Date;
    import java.io.*;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.driver.*;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    public class ArrayDemo
    public static void passArray() throws SQLException
    Connection conn = getConnection();
    ArrayDemo a = new ArrayDemo();
    Person pn1 = new Person();
    pn1.person_id = 1;
    pn1.person_name = "SunilKumar";
    Person pn2 = new Person();
    pn2.person_id = 2;
    pn2.person_name = "Superb";
    Person pn3 = new Person();
    pn3.person_id = 31;
    pn3.person_name = "Outstanding";
    Person[] P_arr = {pn1, pn2, pn3};
    Person[] P_arr_out = new Person[3];
    ArrayDescriptor descriptor =
    ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
    ARRAY array_to_pass =
    new ARRAY( descriptor, conn, P_arr);
    OracleCallableStatement ps =
    (OracleCallableStatement )conn.prepareCall
    ( "begin give_me_an_array(?,?); end;" );
    ps.setARRAY( 1, array_to_pass );
         ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
         ps.execute();
         oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
    Object[] personDetails = (Object[]) returnArray.getArray();
    Person person_record = new Person();
    for (int i = 0; i < personDetails.length; i++) {
              person_record = (Person)personDetails;
              System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
                        public static void main (String args[]){
         try
                             ArrayDemo tfc = new ArrayDemo();
                             tfc.passArray();
         catch(Exception e) {
                        e.printStackTrace();
              public static Connection getConnection() {
         try
                             Class.forName ("oracle.jdbc.OracleDriver");
                             return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
                             "username", "password");
         catch(Exception SQLe) {
                        System.out.println("IN EXCEPTION BLOCK ");
                        return null;
    and thats it. you are done.
    Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
    Thanks
    Sunil.s

    Hi Sunil,
    I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
    http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
    I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
    java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
                        at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
                        at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
                        at oracle.sql.ARRAY.<init>(ARRAY.java:152)
                        at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
    Here's a code snippet I used :
    Object optionVal[] =   {optionArr[0]};   // optionArr[0] is an Option object which has three properties
    oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
    ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
    I'll appreciate if you can provide some information.
    Regards,
    Shamik

  • Best way to perform the same task wih arrays of different Objects

    Hello all.
    This isn't an XPath question, it's a much lower-level Java Object question, but it involves XPath. I hope that doesn't distract from the question, or confuse anything.
    I have 4-5 different types of Objects (call them A, B, C, etc.) that each contain an array of other Objects (call them a[], b[], c[], etc.)
    a, b, c, etc., each have an Xpath object and and XPathExpression. When I create each XPath object I assign it a NamespaceContext object which contains the namespaces needed for that XPath.
    When I create, for example, an A object, I pass is constructor an array of a and an array of Namespaces. With each a object I need to:
    1. create a NamespaceContext object
    2. go through all the Namespace objects and if its route matches,
    (if Namespace.route == a.getRoute() )
    3. add that Namespace to the NamespaceContext Object,
    4. assign the NamespaceContext to the XPath object, and finally
    5. create the a object, passing it the XPath object
    My problem / question is: I also have to do the same thing with B and b[], C and c[], etc. It's not that long of a process, not that much code, but all the same, I was wondering what the best way to write this code once would be, and have it work for all the different types of Objects.
    In other words, I'd like to write a mehod, call it assignNamespaces(), that accepts an array of Objects(a[], b[], c[], etc.) and an array of Namespaces, creates the XPath Object for each a, b, c, etc., and that creates and returns an array of a[],b[],c[], etc., sending the XPath Object as a parameter.
    That way when I create for example an A Object, I call:
    class A
    ObjectsWithXpath[] objectsWithXPath;
    this..objectsWithXPath = assignNamespaces(objectsWithXPath,namespaces);
    Should the assgnNamespaces() method simply use Class.forName() to see what type of Object it is and do a cast accordingly, or is there some other, more elegant way of doing this?
    I hope I've explained myself, and haven't bored you ...
    Thanks in advance,
    Bob

    Thanks for your reply!
    I poked around a bit looking into Factory classes. I've used them a million times but never actually made one. At any rate, they seem like a good idea when you have a bunch of different classes that are similar but not equal.
    In my case my classes ONLY have the XPathExpression in common. Which means that I'd have to make a base abstract class with a bunch of methods of which only a percentage are defined by any class that extends it. In other words, if I had 3 classes -- a, b and c -- that extend the base abstract class, and each had 5 getters and setters, the base abstract class would have 15 methods, 5 only used by a, 5 only used by b and 5 only used by c.
    It seemed a bit ugly to me. Besides, I only have 3 classes. I decided to factor out the inner loop, which is about 70% of the code, stick it in a utility class, and call it from there. I am repeating some code still, but it isn't that bad, and it saves me having to define an interface, an abstract class, a Factory class, etc.
    It ain't perfect, but then nothing ever is.
    Thanks for all the help! Viva the Java community!
    Bob

  • Array of an Object

    I hope this is the right place to post this but here goes. I am trying to create an array of an object which I have created to store basic details of various people, I have declared the array like this people[] Person = new people[5]; //people is the name of the object but whenever i try to assign values to one of objects, for example Person[number].setName(textName.getText()); //number is predetermined array value to use it throws a null pointer exception. If I define a single instance such as people Person = new people(); it works fine but I specifically need and array. Any help would be greatly appreciated.

    I have to say thanks again, it is working now, all that's left is to change is the naming conventions <img class="emoticon" src="images/emoticons/happy.gif" border="0" alt="" />.

  • Help with arrays...Please Help

    Hello,
    Iam trying to make a library system. I have three classes, one for the GUI, User class, and Users class. User class instantiates an object with all the relevant data like, Name, Age, Address, etc. The Users class contains a array of User Objects.
    With this program I have to be able to create users, display users and delete users. The problem Iam having is displaying them. (I think I correctly store the User Objectsin the array, and Iam having problems retreiving them). The thing is when I run the program I don't get any exception errors, just nothing gets displayed!
    Here is part of my code:
    public class Users {
    //declaring variables
    public Users (){
    initialiseArray();
    public void initialiseArray(){
    userArray = new User [50];
    // This method first checks to see if there is enough room for a new
    // user object. If there is the object is added to the array, if there is'nt
    // Then method expandUserArray is called to make room for the user
    public void addUser( User user)
    if (userArraySize == userArray.length) {
    expandUserArray();
    userArray[userArraySize] = user;
    userArraySize++;
    // In this method first the user is searched for in the array, if found
    // Then method decreaseUserArray is called to delete the user
    public void deleteUser ( User user )
    location = 0;
    while (location < userArraySize && userArray[location] != user) {
    location++;
    if (userArray[location] == user) {
    decreaseUserArray(location);
    public void displayUsers( ){
    for (int i = 0; i < userArraySize; i++) {
    usersInformation += "\n" + (userArray.getUserName());
    usersInformation += "\t" + (userArray[i].getUserID());
    usersInformation += "\t" + (userArray[i].getUserAddress());
    public String getUserInformation(){
    //usersInformation = userInformation.toString();
    return usersInformation;
    // The User is deleted by shifting all the above users one place down
    private void decreaseUserArray(int loc)
    userArray[loc] = userArray[userArraySize - 1];
    userArray[userArraySize - 1] = null;
    userArraySize--;
    // This method increase the size of the array by 50%
    private void expandUserArray( )
    int newSize = (int) (userArray.length * increasePercentage);
    User newUserArray[] = new User[newSize];
    for (int i = 0; i < userArray.length; i++) {
    newUserArray[i] = userArray[i];
    userArray = newUserArray;
    Is there anything wrong with my arrays??? Here is part of my code for action performed:
    void addUserButton_actionPerformed(ActionEvent e) {
    newUserName = userNameTextField.getText();
    newUserAddress = userAdressTextField.getText();
    newUserID = Integer.parseInt ( userIDTextField.getText());
    User newUser = new User (newUserName, newUserAddress, newUserID);
    Users users = new Users();
    users.addUser(newUser);
    clearButton();
    void displayUsersButton_actionPerformed(ActionEvent e) {
    Users users = new Users();
    users.displayUsers();
    displayUsersTextArea.append (users.getUserInformation());
    void deleteUserButton_actionPerformed(ActionEvent e) {
    //Still incomplete
    Thanks for your help!

    First, PLEASE USE THE SPECIAL TOKENS FOUND AT
    http://forum.java.sun.com/faq.jsp#messageformat WHEN
    POSTING CODE!!!! Sorry about that, Iam new and I did'nt know about Special Tokens.
    As far as the problem, let me start out by asking if
    you've considered using a class that implements the
    List interface. Perhaps Vector or ArrayList would
    make a better choice since they already handle
    "growing" and "shrinking" for you.I tried using vector arrays but it got too complicated. It was very easy to add and remove objects from the vector but I never figured out how to display all the objects with all the data.
    public void displayUsers( ){
    for (int i = 0; i < userArraySize; i++) {
    usersInformation += "\n" +
    " + (userArray.getUserName());   //what is
    usersInformation?  Also, how does getUserName(),
    getUserID(), getUserAddress() know which user object
    to operate on if these are methods of userArray?
    usersInformation += "\t" +
    " + (userArray.getUserID());     //I'm guess you've
    only posted "some" of your code. 
    usersInformation += "\t" +
    " + (userArray.getUserAddress());//Try posting all
    that you have so far, and please use the special
    tokens to format your code.
    }I made a mistake while I was cutting & pasting my code. It should be for example:
    usersInformation += "\n" (userArray.getUserName());
    The comment about instanciating a new Users for each
    actionPerformed is on point. You are replacing your
    Usres with a new object each time.Yep this was the problem. I just changed the constructor, declared and
    created object of Users elsewhere.
    Thanks for your help!

Maybe you are looking for

  • Icon not showing up (and also some of my images periodically)

    Hello All; I'm having two graphical issues with my App: 1) The Icon does not show up despite being referenced correctly and showing up fine in the simulator. Does it have to be a png of exactly the dimensions 57 x 57? 2) I have a bunch of different b

  • Static Class Function vs. Instance Variables

    I'm making a Wheel class to spin the wheels on some toy trains as they move back and forth. Each wheel on the train is an instance of the Wheel class and there are several of them. I thought it would be great to just have a static class function to t

  • Newbie help finding JAXP JAR

    I know this is an incredibly simple question - but I have gone round and round on the download pages and cannot the the JAXP classes that are supposed to packaged with J2SE 5.0. I have downloaded the JDK 5.0 with Java EE as well as JDK 5.0 Update 16.

  • Spell Checking

    Is spell checking available in the Lightroom 5 Book Module?

  • Cannot Load JPG Files From Canon Powershot S2 IS

    Hi, I'm having a problem loading JPG files from my Canon Powershot S2 IS. When I plug the camera into the USB port, I get the Canon Camera/DV Twain Driver with a list of images to import. They are all JPEG images, which is my camera's native format.