Foreach loop in static block won't compile

When I try to compile this:public class TestEnum
  private static String[] numerals =
      {"einz", "zwei", "drei", "vier"};
  static
    for (String n : numerals)
      // doesn't matter what's in here
  public static void main(String[] args)
}I get this exception:An exception has occurred in the compiler (1.4.2-beta).
java.lang.NullPointerException
    at com.sun.tools.javac.comp.Lower.visitArrayForeachLoop(Lower.java:2269)
    at com.sun.tools.javac.comp.Lower.visitForeachLoop(Lower.java:2242)
    at com.sun.tools.javac.tree.Tree$ForeachLoop.accept(Tree.java:559)
    at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
    at com.sun.tools.javac.tree.TreeTranslator.translate(TreeTranslator.java:51)
    at com.sun.tools.javac.tree.TreeTranslator.visitBlock(TreeTranslator.java:131)
    at com.sun.tools.javac.tree.Tree$Block.accept(Tree.java:497)
    at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
    at com.sun.tools.javac.comp.Lower.visitClassDef(Lower.java:1645)
    at com.sun.tools.javac.tree.Tree$ClassDef.accept(Tree.java:409)
    at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
    at com.sun.tools.javac.comp.Lower.translate(Lower.java:1594)
    at com.sun.tools.javac.comp.Lower.translateTopLevelClass(Lower.java:2438)
    at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:408)
    at com.sun.tools.javac.main.Main.compile(Main.java:523)
    at com.sun.tools.javac.Main.compile(Main.java:41)
    at com.sun.tools.javac.Main.main(Main.java:32)The same thing happens if I use foreach with a Collection instead an array. If I use an old-style for loop or Iterator in the static block, it compiles fine. I can also put the foreach loop in the main method, and it works. Is this a known bug?

You guys rock. Thanks for finding this problem. I'll get it fixed.

Similar Messages

  • Foreach Loop Container with a Data Flow Task looking for file from Connection Manager

    So I have a Data Flow Task within a Foreach Loop Container. The Foreach Loop Container has a Variable Mapping of User:FileName to pass to the Data Flow Task.
    The Data Flow Task has a Flat File Source since we're looking to process .csv Files. And the Flat File Source has a Flat File Connection Manager where I specified the File name when I created it. I thought you needed to do this even though it won't really
    use it since it should be getting its File name from the Foreach Loop Container. But when attempting to execute, it is blowing up because it seems to be looking for my test file name that I indicated in the Flat File Connection Manager rather than the file
    it should be trying to process in User:FileName from the Foreach Loop Container.
    What am I doing wrong here??? I thought you needed to indicate a File name within the Flat File Connection Manager even though it really won't be using it.
    Thanks for your review...I hope I've been clear...and am hopeful for a reply.
    PSULionRP

    The Flat File Connection manager's Connection String needs to be set to reference the variable used in the ForEach Loop:
    Arthur My Blog

  • ForEach Loop Container Mapping Variable From SSIS Package Not Working In SQL-Server StoredProcedure

    I have an SSIS package that uses a ForEach Loop Container to enumerate Excel Files in a dir. I also have a Task Flow that inserts data from those Excel files into SQL-Server.
    Im trying to insert the file names into a column into the same table in SQL-Server by using a mapping variable in my StoredProcedure.
    Im having trouble with my MappingVariable at the end of the script with red squigglies. The following is my StoredProcedure script.
    CREATE PROCEDURE [dbo].[Insert_F_STG_v2]
    -- Add the parameters for the stored procedure here
    @Hrs float,
    @Type nvarchar(100),
    @SN nvarchar(100),
    @Op nvarchar(100),
    @[USER::CurrentFileName]
    AS
    BEGIN
    SET NOCOUNT ON;
    INSERT INTO [CRM_RC].[dbo].[F_StgTbl]
    [Hrs],
    [Type],
    [SN],
    [Op],
    [Report_Date]
    VALUES
    @Hrs ,
    @Type,
    @SN,
    @Op,
    @[USER::CurrentFileName]
    END
    The last @[USER::CurrentFileName] in the Values block at the bottom of the script is the one giving me issues.
    The following is the error:
    Msg 102, Level 15, State 1, Procedure Insert_F_STG_v2, Line 95
    Incorrect syntax near 'USER::CurrentFileName'.

    This seems to be the solution, but get the following exception: 
    [Derived Column [2]] Error: The "Derived Column" failed because truncation occurred, and the truncation row disposition on "Derived Column.Outputs[Derived Column Output].Columns[Derived Column 1]" specifies failure on truncation. A truncation error occurred
    on the specified object of the specified component.
    AND:  [SSIS.Pipeline] Error: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Derived Column" (2) failed with error code 0xC020902A while processing input "Derived Column Input" (3). The identified component returned
    an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

  • Code won't compile - array

    This is my first in depth attempt to understand the code for enabling arrays. I THINK I have a fairly simple problem, but the code won't compile and NetBeans is telling me I'm missing a symbol &/or class, which I just don't get. Here is the code for the Inventory1 module as well as the main module - what am I not seeing?
    Inventory1 module
    import java.util.Scanner;
    import static java.lang.System.out;
    public class Inventory1
      //declare and initialize variables
      int[] itemNumber = new int [5];
      String[] productName = new String[5];
      int[] stockAmount = new int[5];
      double[] productCost = new double[5];
      double[] totalValue = new double[5];
      int i;
      //int i = 0;
      //initialize scanner
      Scanner sc = new Scanner(System.in);
      Inventory1 info = new Inventory1
    public void inventoryInput()
      while (int i = 0; i < 5; i++)
         out.println("Please enter item number: "); //prompt - item number
         info.itemNumber[i] = sc.nextInt(); // input
         out.println( "Enter product name/description: "); //prompt - product name
         info.productName[i] = sc.nextLine(); // input
         out.println("Quantity in stock: "); // prompt - quantity
         int temp = sc.nextInt(); // capture temp number to verify
         if( temp <=0 )
         { // ensure stock amount is positive number
             out.println( "Inventory numbers must be positive. Please" +
                 "enter a correct value." ); // prompt for correct #
             temp = sc.nextInt(); // exit if statement
         else info.stockAmount[i] = temp; // input
         out.println("What is the product cost for each unit? "); // prompt - cost
         double temp2 = sc.nextDouble();
         if( temp <=0 )
             out.println( "Product cost must be a positive dollar " +
                  "amount. Please enter correct product cost." );
             temp2 = sc.nextDouble();
         else info.productCost[i] = temp2;
      out.println( "We hope this inventory program was helpful. Thank you for " +
          "using our program." );
      } // end method inventoryInput   
    }main module
    public class Main {
      public static void main(String[] args) { //start main method
            Inventory1 currentInventory = new Inventory1(); //call Inventory class
            currentInventory.inventoryInput();
    }

    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\build\classes
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:28: '(' or '[' expected
    public void inventoryInput()
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: '.class' expected
    while (int i = 0; i < 5; i++)
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: illegal start of type
    while (int i = 0; i < 5; i++)
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: not a statement
    while (int i = 0; i < 5; i++)
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: ';' expected
    while (int i = 0; i < 5; i++)
    5 errors
    BUILD FAILED (total time: 0 seconds)

  • Error handling in static block

    Hello All,
    I have the following code
    static{
    abc();
    private static void abc() throws Exception{
    how do I throw error in static block because if I write
    static {
    abc() throws Exception;
    it gives error during compilation.
    How do I handle it.
    Sachin

    This is my code ...
    import java.io.FileInputStream;
    import java.io.*;
    import java.util.Properties;
    * @author sachin
    * This class is used setting the configurations
    public class Config{
         static String files_incoming;
         static String files_outgoing;
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
                   LoggerCitiUtil.debug("Error in static block");               
         public static void configurations() throws ICMSException{
              Properties prop = new Properties();
              try{
                   Properties property = System.getProperties();
                   String systemPath = property.getProperty("MAIN_BASE_PATH");
              prop.load(new FileInputStream( systemPath + "bin/scp.ini"));
              }catch(IOException e){                 
                   LoggerCitiUtil.debug("File not loaded in Config class");               
              try{
    files_incoming=prop.getProperty("files_incoming").trim();;
    files_outgoing=prop.getProperty("files_outgoing").trim();;                                   
              }catch(Exception e){
                   LoggerCitiUtil.debug("Error in Config class");
                   e.printStackTrace();
    In the static block I want to throw new ICMSException(e);
    When I write this :
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
    throw new ICMSException(e);
                   LoggerCitiUtil.debug("Error in static block");               
    But it gives unhandled Exception during compile time.
    Can anyone help me out ?.

  • Help with forEach loop

    I have a JSTL forEach loop similar to below:
    <c:forEach var="product" items="${sessionScope.products}">
         <tr><td>${product.description}</td></tr>
    </c:forEach>I would like to use a static class to format the description. Something like below, but I know I cannot do it this way. How can I accomplish this?
    <tr><td>${ProductFormatter.getHtmlDescription(product)}</td></tr>thanks

    The least change approach. If you have already have a static function to do this, then a function tag would be appropriate.
    The function tag basically lets you call a static function from EL.
    custom.tld
    <?xml version="1.0" encoding="UTF-8" ?>
    <taglib xsi:schemaLocation="http://java.sun.com/xml/ns/javaee web-
            jsptaglibrary_2_1.xsd" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1"
    >
         <tlib-version>1.0</tlib-version>
         <short-name>my</short-name>
         <uri>http://www.mytags.com/</uri>
         <function>
              <name>productFormatter</name>
              <function-class>com.mypackage.ProductFormatter</function-class>
              <function-signature>java.lang.String getHtmlDescription(com.mypackage.Product)</function-signature>
         </function>     
    </taglib>If you include that tld in your WEB-INF directory, then the following in a JSP should work:
    <%@ taglib uri="http://www.mytags.com/" prefix="my"%>
    <c:forEach var="product" items="${sessionScope.products}">
         <tr><td>${my:productFormatter(product)}</td></tr>
    </c:forEach>Rather than putting the code in a static function, you might be better off encoding the logic into a custom tag. It depends on what your formatting function is like.
    cheers,
    evnafets

  • Problem in static block execution

    Hi all
    i have a class which has a static block and a static method.For the first time i call the static method in the class its strange that its excuting a part of the static block and entering the method later and agian turning back to static block.
    but for the secon time when i call the static method in that class its fine that static block is not executed..
    here is the code of the class which contains static block and static method
    public class LogServices
    private static String propFilename="plas.properties";
    private static String file="vdvd";
    static
    System.out.println("Inside static block");
    try
    System.out.println("Inside static block of Plasma Log Services ");
              file=PropertyProvider.getProperty(propFilename,"Log4jprops"); // here i am calling another method in another class to get some string from properties
    System.out.println("\n File is ********************************** "+file);
    catch(Exception e)
    System.out.println("Exception encountered the following Exception ["+e.getMessage()+"]");
              System.out.println("Finished static block");
    public static Logger initLog()
    Logger logger=Logger.getLogger(PlasmaLogServices.class);
    System.out.println("File in method is:"+file);
    return logger;
    and in my main program i am calling this
    LogServices.initLog(); and the output i observed on the screen is
    Inside static block
    Inside static block of Plasma Log Services
    File in method is:vdvd
    File is ********************************** log.properties
    Finished static block
    if u look at the output after " Inside static block of Plasma Log Services" (part of static block) its enetering method where " File in method is:vdvd" is printed .
    After some debugging i came to know that if i remove the line
    file=PropertyProvider.getProperty(propFilename,"Log4jprops"); and replace it by file="log.properties";(mean hardcoded) then the static block executes and later that method executes.
    can any one pls help me in this regard???

    The first time you instantiate a class
    LogServices, it's static block is being
    executed.
    After you've instantiated the class, you call its
    static method.
    If you call the static method again, the
    LogServices have their static block already
    executed, so it won't be executed again.
    I think that the execution of static block and static
    method is not mixed, as you thought. I think it is
    rather a logging issue. Most loggers do not guarantee
    that logging-messages are output in correct order.
    Regards, TomHello sir
    tahnks for ur reply and i got that .the problem was in the propertyprovider class i had a static variable logger =PlasmaLogservices.initLog() ; and hence after that it was by passing to that static method and coming back again .
    thanks for looking in to this

  • Foreach loop

    Hello,
    I am trying to convert a normal for loop to the new foreach loop. I was able to do one function that prints every element, but can't seem to be able to modify the elements in the array.
    //This works ok
    public static void printjoy(int [][] array1)
    System.out.println();
    for (int x[] : array1)
    for (int y : x)
    System.out.print(y);
    System.out.println();
    System.out.println();
    //This causes no errors, but it doesn't do the "element plus 10". It just returns the same array unchanged.
    public static void adjArray(int [][] array2)
    for (int x[] : array2)
    for (int y : x)
    y = y +10;
    This is the array declaration and initialization:
    int [][] joy = {
    {66,4,73,4},
    {81,82,81,18},
    {20,22,69,76},
    {71,65,84,79}
    This is how I call the two functions:
    printjoy(joy); //original array
    adjArray(joy); //add ten to each element
    printjoy(joy); //print adjusted array
    Thanks in advance for any help.
    Message was edited by:
    mgkicker

    I am trying to convert a normal for loop to the new
    foreach loop. I was able to do one function that
    prints every element, but can't seem to be able to
    modify the elements in the array.Right, you can't do that.
    for (int ii : arr) {
      ii = 0; // just changes ii, not the array element it's a copy of
    is equivalent to
    for (int ix = 0; ix < arr.length; ix++) {
      int ii = arr[ix];
      ii = 0; // just changes ii, not the array element it's a copy of
    }With the foreach loop, you don't have access to the array, only to the element's value.

  • Static Blocks

    HI I am Mahesh
    How many static blocks can i have in a class?

    You can search the text in a java files.
    I believe these are all added together when the class is actaully compiled.
    There is one method called <cinit>

  • [solved] acerhk - won't compile anymore.

    On my 8y old Acer Travelmate i need acerhk to get wifi working.
    Since the latest kernels it won't compile anymore without errors.
    Anyone get some idea how to get arround with this?
    Output:
    make -C /lib/modules/3.8.4-1-ARCH/build SUBDIRS=/tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35 modules
    make[1]: Entering directory `/usr/src/linux-3.8.4-1-ARCH'
    CC [M] /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.o
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2933:23: Fehler: expected »=«, »,«, »;«, »asm« or »__attribute__« before »model_init«
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2958:22: Fehler: expected »=«, »,«, »;«, »asm« or »__attribute__« before »acerhk_remove«
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2960:22: Fehler: expected »=«, »,«, »;«, »asm« or »__attribute__« before »acerhk_probe«
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:3042:22: Fehler: expected »=«, »,«, »;«, »asm« or »__attribute__« before »acerhk_remove«
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:3068:12: Fehler: »acerhk_probe« ist hier nicht deklariert (nicht in einer Funktion)
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:3069:2: Fehler: Implizite Deklaration der Funktion »__devexit_p« [-Werror=implicit-function-declaration]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:3069:25: Fehler: »acerhk_remove« ist hier nicht deklariert (nicht in einer Funktion)
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:136:14: Warnung: »reg2« definiert, aber nicht verwendet [-Wunused-variable]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:386:13: Warnung: »enable_dritek_keyboard« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:392:13: Warnung: »disable_dritek_keyboard« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:764:12: Warnung: »get_cmos_index« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:876:29: Warnung: »find_hk_area« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:1317:20: Warnung: »setup_model_features« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:1980:20: Warnung: »probe_model« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2205:13: Warnung: »init_input« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2303:13: Warnung: »release_input« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2671:12: Warnung: »acerhk_proc_init« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2783:13: Warnung: »acerhk_proc_cleanup« definiert, aber nicht verwendet [-Wunused-function]
    /tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.c:2925:26: Warnung: »acerhk_misc_dev« definiert, aber nicht verwendet [-Wunused-variable]
    cc1: Einige Warnungen werden als Fehler behandelt
    make[2]: *** [/tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35/acerhk.o] Fehler 1
    make[1]: *** [_module_/tmp/yaourt-tmp-andreas/aur-acerhk/src/acerhk-0.5.35] Fehler 2
    make[1]: Leaving directory `/usr/src/linux-3.8.4-1-ARCH'
    make: *** [acerhk.ko] Fehler 2
    ==> FEHLER: Ein Fehler geschah in build().
    Last edited by lemondreas (2013-03-27 14:42:04)

    sure.
    Make sure to have linux-headers installed as the same version lie your kernel.
    The source for acerhk-0.5.35.tgz is unavailable so i downloaded it from here http://filesocial.com/3ex2d4 and put it in the same folder as PKBUILD
    My PKBUILD looks like this:
    # $Id: PKGBUILD 23215 2010-08-08 21:04:28Z cbrannon $
    # Maintainer: Corrado Primier <[email protected]>
    # Contributor: Marco Fister <[email protected]>
    pkgname=acerhk
    pkgver=0.5.35
    pkgrel=26
    pkgdesc="Acer hotkey driver"
    url="http://www.cakey.de/acerhk/"
    arch=('i686') # Unavailable for x86_64
    license=('GPL')
    depends=('linux>=3.0.0')
    makedepends=('linux-headers>=3.0.0')
    source=(acerhk-0.5.35.tgz acerhk.rc
    2.6.30.patch kernelversion.patch 5100.patch 2.6.36.patch)
    install=acerhk.install
    _kernver=`uname -r`
    build() {
    cd "${srcdir}/${pkgname}-${pkgver}"
    sed -i 's/CFLAGS/EXTRA_CFLAGS/' Makefile
    sed -i 's/__devinit//g; s/__devexit_p//g; s/__devexit//' acerhk.c
    patch -Np1 -i "${srcdir}/5100.patch" || return 1
    patch -Np1 -i "${srcdir}/2.6.30.patch" || return 1
    patch -Np0 -i "${srcdir}/2.6.36.patch" || return 1
    patch -N -p1 < "$srcdir/kernelversion.patch" || return 1
    sed -i 's@linux/config.h@linux/input.h@' "${srcdir}/${pkgname}-${pkgver}/acerhk.c"
    # Set KERNELSRC. The makefile tries to autodetect it with uname,
    # but that is unreliable.
    make CONFIG_FUNCTION_TRACER= KERNELSRC="/lib/modules/${_kernver}/build" acerhk.ko || return 1
    install -Dm644 "${srcdir}/${pkgname}-${pkgver}/acerhk.ko" \
    "${pkgdir}/lib/modules/${_kernver}/kernel/drivers/block/acerhk.ko" || return 1
    install -Dm755 "${srcdir}/acerhk.rc" "${pkgdir}/etc/rc.d/acerhk" || return 1
    # vim:set ts=2 sw=2 et:
    md5sums=('05255919f312cb76af473a760c284433'
    '935584b3e4bfbb3af8460558e5b98bb5'
    '2a0bc99e5b12e25096441df4d53d7df7'
    'fd2ef062ecbc9d670e1b42aa5866d32d'
    '8966a93e66200a535179cf9eb689fe4d'
    'd257a4e9223ebfde48b9608805df9c99')
    By the way:
    Is there any possible way to get acerhk work with systemd?
    Like activating the wifi-LED along the boot process and manually control ist with "sysctl start/stop acerhk"?
    Last edited by lemondreas (2013-03-28 18:15:23)

  • Static Block vs Static Method

    Hi,
    what is the diff. b/w declaring the variable inside the static block vs static method?
    Why static block is executed first before static method?
    Once the class has been loaded inside the memory the static block will automatically executed by the compiler & it will executed before any static methods. What is the reason behind this why? static block is executed before static method? Please do provide an answer for this..
    Thanks,
    JavaLover

    Um.
    A static method is like a regular method; it only gets called if its...called.
    public class Test
      static
         //this stuff executes after being loaded into memory
      public static void main(string args[])
        //this main method is executed by the VM when you execute "java Test"
        staticMethod(); // this makes the program call staticMethod();
      public static void staticMethod()
        //this code wouldn't be executed if main(string[]) hadn't called it.
    }Hope everything I've said here is correct.

  • ConcurrentModificationException while attempting a foreach loop

    I'm writing a bit of code using JGraphT (not necessarily important that you understand how to use it though), and I'm running into a ConcurrentModificationException.
    public static ArrayList<DirectedGraph<Long, DefaultEdge>> level2()
              Set<Long> vertices = graph.vertexSet();
              ArrayList<DirectedGraph<Long, DefaultEdge>> graphs = new ArrayList<DirectedGraph<Long, DefaultEdge>>();
              ArrayList<GraphSizeStorage> storage = new ArrayList<GraphSizeStorage>();
              int counter = 0;
              double foo = vertices.size()/10;
              System.out.print("\nCalculating the Level 2 graphs for all nodes: ");
              for(Long v : vertices)
                   if(counter % foo == 0 && counter >= foo) { System.out.print("."); }
                   DirectedGraph<Long, DefaultEdge> g = new DefaultDirectedGraph<Long, DefaultEdge>(DefaultEdge.class);
                   g.addVertex(v);
                   System.out.println("Adding Vertex: " + v);
                   Set<DefaultEdge> edges = graph.outgoingEdgesOf(v);
                   for(DefaultEdge e : edges)
                        g.addVertex(graph.getEdgeTarget(e));
                        System.out.println("Adding Vertex: " + graph.getEdgeTarget(e));
                        g.addEdge(v, graph.getEdgeTarget(e));
                        System.out.println("Adding Edge from " + v + " to " + graph.getEdgeTarget(e));
                   //At this point, level 1 should be complete.
                   //To get level 2, I'll get a set of g's vertices, and for all vertices that aren't v,
                   //I'll basically add a new edge, the same way I did above.
                   DirectedGraph<Long, DefaultEdge> gClone = g;
                   Set<Long> gVertices = gClone.vertexSet();
                   for(Long v2 : gVertices)
                   {At that foreach loop near the end, I get the exception. The two lines before it were recently modified (to no avail) in hopes of fixing it; instead of two lines, it used to be one line that said
    Set<Long> gVertices = g.vertexSet();
    My question is: Is there an easy way to get around this exception? Would it be possible to copy the variable g instead of making a reference to it? How about its vertexSet?
    Thanks for your help
    KFJ

    KungfuJoe wrote:
    Eh, forget about it. I modified the loops, they don't give me too much trouble anymore. Optimization is key I suppose.If "optimisation" mean don't modify the collection when iterating over it.

  • How can I load a .xlsx File into a SQL Server Table using a Foreach Loop Container in SSIS?

    I know I've REALLY struggled with this before. I just don't understand why this has to be soooooo difficult.
    I can very easily do a straight Data Pump of a .xlsX File into a SQL Server Table using a normal Excel Connection and a normal Excel Source...simply converting Unicode to DT_STR and then using an OLE DB Destination of the SQL Server Table.
    If I want to make the SSIS Package a little more flexible by allowing multiple .xlsX spreadsheets to be pumped in by using a Foreach Loop Container, the whole SSIS Package seems to go to hell in a hand basket. I simply do the following...
    Put the Data Flow Task within the Foreach Loop Container
    Add the Variable Mapping Variable User::FilePath that I defined as a Variable and a string within the FOreach Loop Container
    I change the Excel Connection and its Expression to be ExcelFilePath ==> @[User::FilePath]
    I then try and change the Excel Source and its Data Access Mode to Table Name or view name variable and provide the Variable Name User::FilePath
    And that's when I run into trouble...
    Exception from HRESULT: 0xC02020E8
    Error at Data Flow Task [Excel Source [56]]:SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occured. Error code: 0x80004005.
    Error at Data Flow Task [Excel Source [56]]: Opening a rowset for "...(the EXACT Path and .xlsx File Name)...". Check that the object exists in the database. (And I know it's there!!!)
    I don't understand by adding a Foreach Loop Container to try and make this as efficient as possible has caused such an error unless I'm overlooking something. I have even tried delaying my validations and that doesn't seem to help.
    I have looked hard in Google and even YouTube to try and find a solution for this but for the life of me I cannot seem to find anything on pumping a .xlsX file into SQL Server using a Foreach Loop Container.
    Can ANYONE please help me out here? I'm at the end of my rope trying to get this to work. I think the last time I was in this quandry, trying to pump a .xlsX File into a SQL Server Table using a Foreach Loop Container in SSIS, I actually wrote a C# Script
    to write the contents of the .xlsX File into a .csv File and then Actually used the .csv File to pump the data into a SQL Server Table.
    Thanks for your review and am hoping and praying for a reply and solution.

    Hi ITBobbyP,
    If I understand correctly, you want to load data from multiple sheets in an .xlsx file into a SQL Server table.
    If in this scenario, please refer to the following tips:
    The Foreach Loop container should be configured as shown below:
    Enumerator: Foreach ADO.NET Schema Rowset Enumerator
    Connection String: The OLE DB Connection String for the excel file.
    Schema: Tables.
    In the Variable Mapping, map the variable to Sheet_Name, and change the Index from 0 to 2.
    The connection string for Excel Connection Manager is the original one, we needn’t make any change.
    Change Table Name or View name to the variable Sheet_Name.
    If you want to load data from multiple sheets in multiple .xlsx files into a SQL Server table, please refer to following thread:
    http://stackoverflow.com/questions/7411741/how-to-loop-through-excel-files-and-load-them-into-a-database-using-ssis-package
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • SSIS BULK INSERT unsing UNC inside of ForEach Loop Container Failed could not be opened. Operating system error code 5(Access is denied.)

    Hi,
    I am trying to figure out how to fix my problem
    Error: Could not be opened. Operating system error code 5(Access is denied.)
    Process Description:
    Target Database Server Reside on different Server in the Network
    SSIS Package runs from a Remote Server
    SSIS Package use a ForEachLoop Container to loop into a directory to do Bulk Insert
    SSIS Package use variables to specified the share location of the files using UNC like this
    \\server\files
    Database Service accounts under the Database is runing it has full permission on the share drive were the files reside.
    In the Execution Results tab shows the prepare SQL statement for the BULK insert and I can run the same exact the bulk insert in SSMS without errors, from the Database Server and from the server were SSIS package is executed.
    I am on a dead end and I don’t want to re-write SSIS to use Data Flow Task because is not flexible to update when metadata of the table changed.
    Below post it has almost the same situation:
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8de13e74-709a-43a5-8be2-034b764ca44f/problem-with-bulk-insert-task-in-foreach-loop?forum=sqlintegrationservices

    Insteresting how I fixed the issue, Adding the Application Name into the SQL OLAP Connection String Fixed the issue. I am not sure why SQL Server wasn't able to open the file remotely without this.

  • [Forum FAQ] How to calculate the total count of insert rows within a Foreach Loop Container in SSIS?

    Introduction
    We need to loop through all the flat files that have the same structure in a folder and import all the data to a single SQL Server table. How can we obtain the total count of the rows inserted to the destination SQL Server table?
    Solution
    We can use Execute SQL Task or Script Task to aggregate the row count increment for each iteration of the Foreach Loop Container. The following steps are the preparations before we add the Execute SQL Task or Script Task:
    Create a String type variable FilePath, two Int32 type variables InsertRowCnt and TotalRowCnt.
    Drag a Foreach Loop Container to the Control Flow design surface, set the Enumerator to “Foreach File Enumerator”, specify the source folder and the files extension, and set the “Retrieve file name” option to “Fully qualified”.
    On the “Variable Mappings” tab of the container, map the variable FilePath to the collection value.
    Drag a Data Flow Task to the container, in the Data Flow Task, add a Flat File Source, a Row Count Transformation, and an OLE DB Destination, and join them. Create a Flat File Connection Manager to connect to one of the flat files, and then configure the
    Flat File Source as well as the OLE DB Destination adapter. Set the variable for the Row Count Transformation to “User::InsertRowCnt”.
    Open the Property Expressions Editor for the Flat File Connection Manager, and set the expression of “ConnectionString” property to
    “@[User::FilePath]”.
    (I) Execute SQL Task Method:
    In the Control Flow, drag an Execute SQL Task under the Data Flow Task and join them.
    Create one or using any one existing OLE DB Connection Manager for the Execute SQL Task, set the “ResultSet” option to “Single row”, and then set the “SQLStatement” property to:
    DECLARE @InsertRowCnt INT,
                   @TotalRowCnt INT
    SET @InsertRowCnt=?
    SET @TotalRowCnt=?
    SET @TotalRowCnt=@InsertRowCnt+@TotalRowCnt
    SELECT TotalRowCnt=@TotalRowCnt
    On to parameter 1. 
    On the “Result Set” tab of the Execute SQL Task, map result 0 to variable “User::TotalRowCnt”.
    (II) Script Task Method:
    In the Control Flow, drag a Script Task under the Data Flow Task and join them.
    In the Script Task, select variable InsertRowCnt for “ReadOnlyVariables” option, and select variable TotalRowCnt for “ReadWriteVariables”.
    Edit the Main method as follows (C#):
    public void Main()
    // TODO: Add your code here
    int InsertRowCnt = Convert.ToInt32(Dts.Variables["User::InsertRowCnt"].Value.ToString()
    int TotalRowCnt = Convert.ToInt32(Dts.Variables["User::TotalRowCnt"].Value.ToString());
    TotalRowCnt = TotalRowCnt + InsertRowCnt;
    Dts.Variables["User::InsertRowCnt"].Value = TotalRowCnt;
    Dts.TaskResult = (int)ScriptResults.Success;
              Or (VB)
              Public Sub Main()
            ' Add your code here
            Dim InsertRowCnt As Integer =        
            Convert.ToInt32(Dts.Variables("User::InsertRowCnt").Value.ToString())
            Dim TotalRowCnt As Integer =
            Convert.ToInt32(Dts.Variables("User::TotalRowCnt").Value.ToString())
            TotalRowCnt = TotalRowCnt + InsertRowCnt
            Dts.Variables("User::TotalRowCnt").Value = TotalRowCnt
            Dts.TaskResult = ScriptResults.Success
           End Sub
    Applies to
    Microsoft SQL Server 2005
    Microsoft SQL Server 2008
    Microsoft SQL Server 2008 R2
    Microsoft SQL Server 2012
    Microsoft SQL Server 2014
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Hi ITBobbyP,
    If I understand correctly, you want to load data from multiple sheets in an .xlsx file into a SQL Server table.
    If in this scenario, please refer to the following tips:
    The Foreach Loop container should be configured as shown below:
    Enumerator: Foreach ADO.NET Schema Rowset Enumerator
    Connection String: The OLE DB Connection String for the excel file.
    Schema: Tables.
    In the Variable Mapping, map the variable to Sheet_Name, and change the Index from 0 to 2.
    The connection string for Excel Connection Manager is the original one, we needn’t make any change.
    Change Table Name or View name to the variable Sheet_Name.
    If you want to load data from multiple sheets in multiple .xlsx files into a SQL Server table, please refer to following thread:
    http://stackoverflow.com/questions/7411741/how-to-loop-through-excel-files-and-load-them-into-a-database-using-ssis-package
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

Maybe you are looking for