Example usage for java.lang String split

List of usage examples for java.lang String split

Introduction

In this page you can find the example usage for java.lang String split.

Prototype

public String[] split(String regex) 

Source Link

Document

Splits this string around matches of the given regular expression.

Usage

From source file:com.web.server.WebServer.java

/**
 * This is the start of the all the services in web server
 * @param args/*from w ww  . j  a  v  a 2s.c o m*/
 * @throws IOException 
 * @throws SAXException 
 */
public static void main(String[] args) throws IOException, SAXException {

    Hashtable urlClassLoaderMap = new Hashtable();
    Hashtable executorServicesMap = new Hashtable();
    Hashtable ataMap = new Hashtable<String, ATAConfig>();
    Hashtable messagingClassMap = new Hashtable();
    ConcurrentHashMap servletMapping = new ConcurrentHashMap();
    DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    Digester serverdigester = serverdigesterLoader.newDigester();
    final ServerConfig serverconfig = (ServerConfig) serverdigester
            .parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));
    DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    Digester messagingdigester = messagingdigesterLoader.newDigester();
    MessagingElem messagingconfig = (MessagingElem) messagingdigester
            .parse(new InputSource(new FileInputStream("./config/messaging.xml")));
    //System.out.println(messagingconfig);
    ////System.out.println(serverconfig.getDeploydirectory());
    PropertyConfigurator.configure("log4j.properties");
    /*MemcachedClient cache=new MemcachedClient(
        new InetSocketAddress("localhost", 1000));*/

    // Store a value (async) for one hour
    //c.set("someKey", 36, new String("arun"));
    // Retrieve a value.        
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool();

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = null;
    try {
        name = new ObjectName("com.web.server:type=WarDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    WarDeployer warDeployer = new WarDeployer(serverconfig.getDeploydirectory(), serverconfig.getFarmWarDir(),
            serverconfig.getClustergroup(), urlClassLoaderMap, executorServicesMap, messagingClassMap,
            servletMapping, messagingconfig, sessionObjects);
    warDeployer.setPriority(MIN_PRIORITY);
    try {
        mbs.registerMBean(warDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //warDeployer.start();
    executor.execute(warDeployer);

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getPort())));

    serverSocketChannel.configureBlocking(false);

    final byte[] shutdownBt = new byte[50];
    WebServerRequestProcessor webserverRequestProcessor = new WebServer().new WebServerRequestProcessor(
            servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(),
            Integer.parseInt(serverconfig.getShutdownport()), 1);
    webserverRequestProcessor.setPriority(MIN_PRIORITY);
    try {
        name = new ObjectName("com.web.server:type=WebServerRequestProcessor");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(webserverRequestProcessor, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //webserverRequestProcessor.start();
    executor.execute(webserverRequestProcessor);

    for (int i = 0; i < 10; i++) {
        WebServerRequestProcessor webserverRequestProcessor1 = new WebServer().new WebServerRequestProcessor(
                servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(),
                Integer.parseInt(serverconfig.getShutdownport()), 2);
        webserverRequestProcessor1.setPriority(MIN_PRIORITY);
        try {
            name = new ObjectName("com.web.server:type=WebServerRequestProcessor" + (i + 1));
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(webserverRequestProcessor1, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        executor.execute(webserverRequestProcessor1);
    }

    ServerSocketChannel serverSocketChannelServices = ServerSocketChannel.open();

    serverSocketChannelServices
            .bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getServicesport())));

    serverSocketChannelServices.configureBlocking(false);

    ExecutorServiceThread executorService = new ExecutorServiceThread(serverSocketChannelServices,
            executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap, urlClassLoaderMap,
            serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(),
            serverconfig.getEarservicesdirectory(), serverconfig.getNodesport());

    try {
        name = new ObjectName("com.web.services:type=ExecutorServiceThread");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(executorService, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //executorService.start();
    executor.execute(executorService);

    for (int i = 0; i < 10; i++) {
        ExecutorServiceThread executorService1 = new ExecutorServiceThread(serverSocketChannelServices,
                executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap,
                urlClassLoaderMap, serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(),
                serverconfig.getEarservicesdirectory(), serverconfig.getNodesport());

        try {
            name = new ObjectName("com.web.services:type=ExecutorServiceThread" + (i + 1));
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(executorService1, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        executor.execute(executorService1);
    }

    WebServerHttpsRequestProcessor webserverHttpsRequestProcessor = new WebServer().new WebServerHttpsRequestProcessor(
            servletMapping, urlClassLoaderMap, Integer.parseInt(serverconfig.getHttpsport()),
            serverconfig.getDeploydirectory(), Integer.parseInt(serverconfig.getShutdownport()),
            serverconfig.getHttpscertificatepath(), serverconfig.getHttpscertificatepasscode(), 1);
    try {
        name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(webserverHttpsRequestProcessor, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    webserverHttpsRequestProcessor.setPriority(MAX_PRIORITY);
    //webserverRequestProcessor.start();
    executor.execute(webserverHttpsRequestProcessor);

    /* for(int i=0;i<2;i++){
        webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport())+(i+1),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1);
              
      try {
    name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor"+(i+1));
      } catch (MalformedObjectNameException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
      } 
              
      try {
    mbs.registerMBean(webserverHttpsRequestProcessor, name);
      } catch (InstanceAlreadyExistsException | MBeanRegistrationException
       | NotCompliantMBeanException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
      }
              
      executor.execute(webserverHttpsRequestProcessor);
    }*/

    /*ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap);
            
    try {
       name = new ObjectName("com.web.services:type=ATAServer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ataServer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
            
    ataServer.start();*/

    /*ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap);
            
    try {
       name = new ObjectName("com.web.services:type=ATAConfigClient");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ataClient, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    ataClient.start();*/

    MessagingServer messageServer = new MessagingServer(serverconfig.getMessageport(), messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=MessagingServer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(messageServer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //messageServer.start();
    executor.execute(messageServer);

    RandomQueueMessagePicker randomqueuemessagepicker = new RandomQueueMessagePicker(messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=RandomQueueMessagePicker");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(randomqueuemessagepicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //randomqueuemessagepicker.start();
    executor.execute(randomqueuemessagepicker);

    RoundRobinQueueMessagePicker roundrobinqueuemessagepicker = new RoundRobinQueueMessagePicker(
            messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=RoundRobinQueueMessagePicker");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(roundrobinqueuemessagepicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //roundrobinqueuemessagepicker.start();
    executor.execute(roundrobinqueuemessagepicker);

    TopicMessagePicker topicpicker = new TopicMessagePicker(messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=TopicMessagePicker");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(topicpicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //topicpicker.start();
    executor.execute(topicpicker);

    try {
        name = new ObjectName("com.web.server:type=SARDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    SARDeployer sarDeployer = SARDeployer.newInstance(serverconfig.getDeploydirectory());
    try {
        mbs.registerMBean(sarDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    executor.execute(sarDeployer);
    /*try {
       mbs.invoke(name, "startDeployer", null, null);
    } catch (InstanceNotFoundException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (ReflectionException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (MBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    */
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    System.setProperty(Context.PROVIDER_URL, "rmi://localhost:" + serverconfig.getServicesregistryport());
    ;
    Registry registry = LocateRegistry.createRegistry(Integer.parseInt(serverconfig.getServicesregistryport()));

    /*JarDeployer jarDeployer=new JarDeployer(registry,serverconfig.getServicesdirectory(), serverconfig.getServiceslibdirectory(),serverconfig.getCachedir(),executorServicesMap, urlClassLoaderMap);
    try {
       name = new ObjectName("com.web.server:type=JarDeployer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(jarDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //jarDeployer.start();
    executor.execute(jarDeployer);*/

    EARDeployer earDeployer = new EARDeployer(registry, serverconfig.getEarservicesdirectory(),
            serverconfig.getDeploydirectory(), executorServicesMap, urlClassLoaderMap,
            serverconfig.getCachedir(), warDeployer);
    try {
        name = new ObjectName("com.web.server:type=EARDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(earDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //earDeployer.start();
    executor.execute(earDeployer);

    JVMConsole jvmConsole = new JVMConsole(Integer.parseInt(serverconfig.getJvmConsolePort()));

    try {
        name = new ObjectName("com.web.server:type=JVMConsole");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(jvmConsole, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    executor.execute(jvmConsole);

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    XMLDeploymentScanner xmlDeploymentScanner = new XMLDeploymentScanner(serverconfig.getDeploydirectory(),
            serverconfig.getServiceslibdirectory());
    exec.scheduleAtFixedRate(xmlDeploymentScanner, 0, 1000, TimeUnit.MILLISECONDS);

    EmbeddedJMS embeddedJMS = null;
    try {
        embeddedJMS = new EmbeddedJMS();
        embeddedJMS.start();
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

    EJBDeployer ejbDeployer = new EJBDeployer(serverconfig.getServicesdirectory(), registry,
            Integer.parseInt(serverconfig.getServicesregistryport()), embeddedJMS);
    try {
        name = new ObjectName("com.web.server:type=EJBDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(ejbDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //jarDeployer.start();
    executor.execute(ejbDeployer);

    new Thread() {
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(Integer.parseInt(serverconfig.getShutdownport()));
                while (true) {
                    Socket sock = serverSocket.accept();
                    InputStream istream = sock.getInputStream();
                    istream.read(shutdownBt);
                    String shutdownStr = new String(shutdownBt);
                    String[] shutdownToken = shutdownStr.split("\r\n\r\n");
                    //System.out.println(shutdownStr);
                    if (shutdownToken[0].startsWith("shutdown WebServer")) {
                        synchronized (shutDownObject) {
                            shutDownObject.notifyAll();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            System.out.println("IN shutdown Hook");
            synchronized (shutDownObject) {
                shutDownObject.notifyAll();
            }
        }
    }));
    try {
        synchronized (shutDownObject) {
            shutDownObject.wait();
        }
        executor.shutdownNow();
        serverSocketChannel.close();
        serverSocketChannelServices.close();
        embeddedJMS.stop();

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    System.out.println("IN shutdown Hook1");
    /*try{
       Thread.sleep(10000);
    }
    catch(Exception ex){
               
    }*/

    //webserverRequestProcessor.stop();
    //webserverRequestProcessor1.stop();

    /*warDeployer.stop();
    executorService.stop();
    //ataServer.stop();
    //ataClient.stop();
    messageServer.stop();
    randomqueuemessagepicker.stop();
    roundrobinqueuemessagepicker.stop();
    topicpicker.stop();*/
    /*try {
       mbs.invoke(new ObjectName("com.web.server:type=SARDeployer"), "destroyDeployer", null, null);
    } catch (InstanceNotFoundException | MalformedObjectNameException
    | ReflectionException | MBeanException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/
    //earDeployer.stop();
    System.exit(0);
}

From source file:com.paul.linknet.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//  w  w w .j a  v a 2  s  .  co  m
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from www .  j a  v  a 2  s  .c  o m
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:ch.kostceco.tools.kostval.KOSTVal.java

/** Die Eingabe besteht aus 2 oder 3 Parameter: [0] Validierungstyp [1] Pfad zur Val-File [2]
 * option: Verbose//from   www .  j av a  2  s .  com
 * 
 * @param args
 * @throws IOException */

@SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");

    // Zeitstempel Start
    java.util.Date nowStart = new java.util.Date();
    java.text.SimpleDateFormat sdfStart = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    String ausgabeStart = sdfStart.format(nowStart);

    /* TODO: siehe Bemerkung im applicationContext-services.xml bezglich Injection in der
     * Superklasse aller Impl-Klassen ValidationModuleImpl validationModuleImpl =
     * (ValidationModuleImpl) context.getBean("validationmoduleimpl"); */

    KOSTVal kostval = (KOSTVal) context.getBean("kostval");
    File configFile = new File("configuration" + File.separator + "kostval.conf.xml");

    // Ueberprfung des Parameters (Log-Verzeichnis)
    String pathToLogfile = kostval.getConfigurationService().getPathToLogfile();

    File directoryOfLogfile = new File(pathToLogfile);

    if (!directoryOfLogfile.exists()) {
        directoryOfLogfile.mkdir();
    }

    // Im Logverzeichnis besteht kein Schreibrecht
    if (!directoryOfLogfile.canWrite()) {
        System.out.println(
                kostval.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE, directoryOfLogfile));
        System.exit(1);
    }

    if (!directoryOfLogfile.isDirectory()) {
        System.out.println(kostval.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY));
        System.exit(1);
    }

    // Ist die Anzahl Parameter (mind. 2) korrekt?
    if (args.length < 2) {
        System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
        System.exit(1);
    }

    File valDatei = new File(args[1]);
    File logDatei = null;
    logDatei = valDatei;

    // Informationen zum Arbeitsverzeichnis holen
    String pathToWorkDir = kostval.getConfigurationService().getPathToWorkDir();
    /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
     * entsprechenden Modul die property anzugeben: <property name="configurationService"
     * ref="configurationService" /> */

    // Informationen holen, welche Formate validiert werden sollen
    String pdfaValidation = kostval.getConfigurationService().pdfaValidation();
    String siardValidation = kostval.getConfigurationService().siardValidation();
    String tiffValidation = kostval.getConfigurationService().tiffValidation();
    String jp2Validation = kostval.getConfigurationService().jp2Validation();

    // Konfiguration des Loggings, ein File Logger wird zustzlich erstellt
    LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator");
    String logFileName = logConfigurator.configure(directoryOfLogfile.getAbsolutePath(), logDatei.getName());
    File logFile = new File(logFileName);
    // Ab hier kann ins log geschrieben werden...

    String formatValOn = "";
    // ermitteln welche Formate validiert werden knnen respektive eingeschaltet sind
    if (pdfaValidation.equals("yes")) {
        formatValOn = "PDF/A";
        if (tiffValidation.equals("yes")) {
            formatValOn = formatValOn + ", TIFF";
        }
        if (jp2Validation.equals("yes")) {
            formatValOn = formatValOn + ", JP2";
        }
        if (siardValidation.equals("yes")) {
            formatValOn = formatValOn + ", SIARD";
        }
    } else if (tiffValidation.equals("yes")) {
        formatValOn = "TIFF";
        if (jp2Validation.equals("yes")) {
            formatValOn = formatValOn + ", JP2";
        }
        if (siardValidation.equals("yes")) {
            formatValOn = formatValOn + ", SIARD";
        }
    } else if (jp2Validation.equals("yes")) {
        formatValOn = "JP2";
        if (siardValidation.equals("yes")) {
            formatValOn = formatValOn + ", SIARD";
        }
    } else if (siardValidation.equals("yes")) {
        formatValOn = "SIARD";
    }

    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_HEADER));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_END));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMATON, formatValOn));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_INFO));
    System.out.println("KOST-Val");
    System.out.println("");

    if (args[0].equals("--format") && formatValOn.equals("")) {
        // Formatvalidierung aber alle Formate ausgeschlossen
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_NOFILEENDINGS)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_NOFILEENDINGS));
        System.exit(1);
    }

    File xslOrig = new File("resources" + File.separator + "kost-val.xsl");
    File xslCopy = new File(directoryOfLogfile.getAbsolutePath() + File.separator + "kost-val.xsl");
    if (!xslCopy.exists()) {
        Util.copyFile(xslOrig, xslCopy);
    }

    File tmpDir = new File(pathToWorkDir);

    /* bestehendes Workverzeichnis Abbruch wenn nicht leer, da am Schluss das Workverzeichnis
     * gelscht wird und entsprechend bestehende Dateien gelscht werden knnen */
    if (tmpDir.exists()) {
        if (tmpDir.isDirectory()) {
            // Get list of file in the directory. When its length is not zero the folder is not empty.
            String[] files = tmpDir.list();
            if (files.length > 0) {
                LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                        kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)));
                System.out.println(
                        kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir));
                System.exit(1);
            }
        }
    }

    // Im Pfad keine Sonderzeichen xml-Validierung SIP 1d und SIARD C strzen ab

    String patternStr = "[^!#\\$%\\(\\)\\+,\\-_\\.=@\\[\\]\\{\\}\\~:\\\\a-zA-Z0-9 ]";
    Pattern pattern = Pattern.compile(patternStr);

    String name = tmpDir.getAbsolutePath();

    String[] pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];

        Matcher matcher = pattern.matcher(element);

        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                    kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    // die Anwendung muss mindestens unter Java 6 laufen
    String javaRuntimeVersion = System.getProperty("java.vm.version");
    if (javaRuntimeVersion.compareTo("1.6.0") < 0) {
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_WRONG_JRE)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_WRONG_JRE));
        System.exit(1);
    }

    // bestehendes Workverzeichnis wieder anlegen
    if (!tmpDir.exists()) {
        tmpDir.mkdir();
    }

    // Im workverzeichnis besteht kein Schreibrecht
    if (!tmpDir.canWrite()) {
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir));
        System.exit(1);
    }

    /* Vorberitung fr eine allfllige Festhaltung bei unterschiedlichen PDFA-Validierungsresultaten
     * in einer PDF_Diagnosedatei sowie Zhler der SIP-Dateiformate */
    String diaPath = kostval.getConfigurationService().getPathToDiagnose();

    // Im diaverzeichnis besteht kein Schreibrecht
    File diaDir = new File(diaPath);

    if (!diaDir.exists()) {
        diaDir.mkdir();
    }

    if (!diaDir.canWrite()) {
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_DIADIRECTORY_NOTWRITABLE, diaDir)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_DIADIRECTORY_NOTWRITABLE, diaDir));
        System.exit(1);
    }

    File xmlDiaOrig = new File("resources" + File.separator + "KaD-Diagnosedaten.kost-val.xml");
    File xmlDiaCopy = new File(diaPath + File.separator + "KaD-Diagnosedaten.kost-val.xml");
    if (!xmlDiaCopy.exists()) {
        Util.copyFile(xmlDiaOrig, xmlDiaCopy);
    }
    File xslDiaOrig = new File("resources" + File.separator + "kost-val_KaDdia.xsl");
    File xslDiaCopy = new File(diaPath + File.separator + "kost-val_KaDdia.xsl");
    if (!xslDiaCopy.exists()) {
        Util.copyFile(xslDiaOrig, xslDiaCopy);
    }

    /* Ueberprfung des optionalen Parameters (2 -v --> im Verbose-mode werden die originalen Logs
     * nicht gelscht (PDFTron, Jhove & Co.) */
    boolean verbose = false;
    if (args.length > 2) {
        if (!(args[2].equals("-v"))) {
            LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                    kostval.getTextResourceService().getText(ERROR_PARAMETER_OPTIONAL_1)));
            System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_OPTIONAL_1));
            System.exit(1);
        } else {
            verbose = true;
        }
    }

    /* Initialisierung TIFF-Modul B (JHove-Validierung) berprfen der Konfiguration: existiert die
     * jhove.conf am angebenen Ort? */
    String jhoveConf = kostval.getConfigurationService().getPathToJhoveConfiguration();
    File fJhoveConf = new File(jhoveConf);
    if (!fJhoveConf.exists() || !fJhoveConf.getName().equals("jhove.conf")) {

        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_JHOVECONF_MISSING)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_JHOVECONF_MISSING));
        System.exit(1);
    }

    // Im Pfad keine Sonderzeichen xml-Validierung SIP 1d und SIARD C strzen ab

    name = valDatei.getAbsolutePath();

    pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];

        Matcher matcher = pattern.matcher(element);

        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                    kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    // Ueberprfung des Parameters (Val-Datei): existiert die Datei?
    if (!valDatei.exists()) {
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_VALFILE_FILENOTEXISTING)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_VALFILE_FILENOTEXISTING));
        System.exit(1);
    }

    if (args[0].equals("--format")) {
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT1));
        Integer countNio = 0;
        Integer countSummaryNio = 0;
        Integer count = 0;
        Integer pdfaCountIo = 0;
        Integer pdfaCountNio = 0;
        Integer siardCountIo = 0;
        Integer siardCountNio = 0;
        Integer tiffCountIo = 0;
        Integer tiffCountNio = 0;
        Integer jp2CountIo = 0;
        Integer jp2CountNio = 0;

        // TODO: Formatvalidierung an einer Datei --> erledigt --> nur Marker
        if (!valDatei.isDirectory()) {

            boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }

            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            // Zeitstempel End
            java.util.Date nowEnd = new java.util.Date();
            java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            String ausgabeEnd = sdfEnd.format(nowEnd);
            ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
            Util.valEnd(ausgabeEnd, logFile);
            Util.amp(logFile);

            // Die Konfiguration hereinkopieren
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);

                factory.setExpandEntityReferences(false);

                Document docConfig = factory.newDocumentBuilder().parse(configFile);
                NodeList list = docConfig.getElementsByTagName("configuration");
                Element element = (Element) list.item(0);

                Document docLog = factory.newDocumentBuilder().parse(logFile);

                Node dup = docLog.importNode(element, true);

                docLog.getDocumentElement().appendChild(dup);
                FileWriter writer = new FileWriter(logFile);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ElementToStream(docLog.getDocumentElement(), baos);
                String stringDoc2 = new String(baos.toByteArray());
                writer.write(stringDoc2);
                writer.close();

                // Der Header wird dabei leider verschossen, wieder zurck ndern
                String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                Util.oldnewstring(oldstring, newstring, logFile);

            } catch (Exception e) {
                LOGGER.logError("<Error>"
                        + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                System.out.println("Exception: " + e.getMessage());
            }

            if (valFile) {
                // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                // Validierte Datei valide
                System.exit(0);
            } else {
                // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                // Fehler in Validierte Datei --> invalide
                System.exit(2);

            }
        } else {
            // TODO: Formatvalidierung ber ein Ordner --> erledigt --> nur Marker
            Map<String, File> fileMap = Util.getFileMap(valDatei, false);
            Set<String> fileMapKeys = fileMap.keySet();

            for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) {
                String entryName = iterator.next();
                File newFile = fileMap.get(entryName);
                if (!newFile.isDirectory()) {
                    valDatei = newFile;
                    count = count + 1;

                    // Ausgabe Dateizhler Ersichtlich das KOST-Val Dateien durchsucht
                    System.out.print(count + "   ");
                    System.out.print("\r");

                    if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2")))
                            && jp2Validation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            jp2CountIo = jp2CountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            jp2CountNio = jp2CountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }
                    } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".tiff")
                            || valDatei.getAbsolutePath().toLowerCase().endsWith(".tif")))
                            && tiffValidation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            tiffCountIo = tiffCountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            tiffCountNio = tiffCountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }
                    } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".siard"))
                            && siardValidation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            siardCountIo = siardCountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            siardCountNio = siardCountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }

                    } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf")
                            || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa")))
                            && pdfaValidation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            pdfaCountIo = pdfaCountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            pdfaCountNio = pdfaCountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }

                    } else {
                        countNio = countNio + 1;
                    }
                }
            }

            System.out.print("                   ");
            System.out.print("\r");

            if (countNio.equals(count)) {
                // keine Dateien Validiert
                LOGGER.logError(
                        kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
                System.out.println(
                        kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
            }

            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            // Zeitstempel End
            java.util.Date nowEnd = new java.util.Date();
            java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            String ausgabeEnd = sdfEnd.format(nowEnd);
            ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
            Util.valEnd(ausgabeEnd, logFile);
            Util.amp(logFile);

            // Die Konfiguration hereinkopieren
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);

                factory.setExpandEntityReferences(false);

                Document docConfig = factory.newDocumentBuilder().parse(configFile);
                NodeList list = docConfig.getElementsByTagName("configuration");
                Element element = (Element) list.item(0);

                Document docLog = factory.newDocumentBuilder().parse(logFile);

                Node dup = docLog.importNode(element, true);

                docLog.getDocumentElement().appendChild(dup);
                FileWriter writer = new FileWriter(logFile);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ElementToStream(docLog.getDocumentElement(), baos);
                String stringDoc2 = new String(baos.toByteArray());
                writer.write(stringDoc2);
                writer.close();

                // Der Header wird dabei leider verschossen, wieder zurck ndern
                String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                Util.oldnewstring(oldstring, newstring, logFile);

            } catch (Exception e) {
                LOGGER.logError("<Error>"
                        + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                System.out.println("Exception: " + e.getMessage());
            }

            countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio;

            if (countNio.equals(count)) {
                // keine Dateien Validiert bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                System.exit(1);
            } else if (countSummaryNio == 0) {
                // bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                // alle Validierten Dateien valide
                System.exit(0);
            } else {
                // bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                // Fehler in Validierten Dateien --> invalide
                System.exit(2);
            }
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
                tmpDir.deleteOnExit();
            }
        }
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

    } else if (args[0].equals("--sip")) {
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT1));

        // TODO: Sipvalidierung --> erledigt --> nur Marker
        boolean validFormat = false;
        File originalSipFile = valDatei;
        File unSipFile = valDatei;
        File outputFile3c = null;
        String fileName3c = null;
        File tmpDirZip = null;

        // zuerst eine Formatvalidierung ber den Content dies ist analog aufgebaut wie --format
        Integer countNio = 0;
        Integer countSummaryNio = 0;
        Integer countSummaryIo = 0;
        Integer count = 0;
        Integer pdfaCountIo = 0;
        Integer pdfaCountNio = 0;
        Integer siardCountIo = 0;
        Integer siardCountNio = 0;
        Integer tiffCountIo = 0;
        Integer tiffCountNio = 0;
        Integer jp2CountIo = 0;
        Integer jp2CountNio = 0;

        if (!valDatei.isDirectory()) {
            Boolean zip = false;
            // Eine ZIP Datei muss mit PK.. beginnen
            if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".zip")
                    || valDatei.getAbsolutePath().toLowerCase().endsWith(".zip64"))) {

                FileReader fr = null;

                try {
                    fr = new FileReader(valDatei);
                    BufferedReader read = new BufferedReader(fr);

                    // Hex 03 in Char umwandeln
                    String str3 = "03";
                    int i3 = Integer.parseInt(str3, 16);
                    char c3 = (char) i3;
                    // Hex 04 in Char umwandeln
                    String str4 = "04";
                    int i4 = Integer.parseInt(str4, 16);
                    char c4 = (char) i4;

                    // auslesen der ersten 4 Zeichen der Datei
                    int length;
                    int i;
                    char[] buffer = new char[4];
                    length = read.read(buffer);
                    for (i = 0; i != length; i++)
                        ;

                    // die beiden charArrays (soll und ist) mit einander vergleichen
                    char[] charArray1 = buffer;
                    char[] charArray2 = new char[] { 'P', 'K', c3, c4 };

                    if (Arrays.equals(charArray1, charArray2)) {
                        // hchstwahrscheinlich ein ZIP da es mit 504B0304 respektive PK.. beginnt
                        zip = true;
                    }
                } catch (Exception e) {
                    LOGGER.logError("<Error>"
                            + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    System.out.println("Exception: " + e.getMessage());
                }
            }

            // wenn die Datei kein Directory ist, muss sie mit zip oder zip64 enden
            if ((!(valDatei.getAbsolutePath().toLowerCase().endsWith(".zip")
                    || valDatei.getAbsolutePath().toLowerCase().endsWith(".zip64"))) || zip == false) {
                // Abbruch! D.h. Sip message beginnen, Meldung und Beenden ab hier bis System.exit( 1 );
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1));
                valDatei = originalSipFile;
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE,
                        kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE,
                        valDatei.getAbsolutePath()));
                System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION));
                System.out.println(valDatei.getAbsolutePath());

                // die eigentliche Fehlermeldung
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_MODUL_Aa_SIP)
                        + kostval.getTextResourceService().getText(ERROR_XML_AA_INCORRECTFILEENDING));
                System.out.println(kostval.getTextResourceService().getText(ERROR_XML_AA_INCORRECTFILEENDING));

                // Fehler im Validierten SIP --> invalide & Abbruch
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                System.out.println("Invalid");
                System.out.println("");
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));

                // Zeitstempel End
                java.util.Date nowEnd = new java.util.Date();
                java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
                String ausgabeEnd = sdfEnd.format(nowEnd);
                ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
                Util.valEnd(ausgabeEnd, logFile);
                Util.amp(logFile);

                // Die Konfiguration hereinkopieren
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setValidating(false);

                    factory.setExpandEntityReferences(false);

                    Document docConfig = factory.newDocumentBuilder().parse(configFile);
                    NodeList list = docConfig.getElementsByTagName("configuration");
                    Element element = (Element) list.item(0);

                    Document docLog = factory.newDocumentBuilder().parse(logFile);

                    Node dup = docLog.importNode(element, true);

                    docLog.getDocumentElement().appendChild(dup);
                    FileWriter writer = new FileWriter(logFile);

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ElementToStream(docLog.getDocumentElement(), baos);
                    String stringDoc2 = new String(baos.toByteArray());
                    writer.write(stringDoc2);
                    writer.close();

                    // Der Header wird dabei leider verschossen, wieder zurck ndern
                    String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                    String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                    Util.oldnewstring(oldstring, newstring, logFile);

                } catch (Exception e) {
                    LOGGER.logError("<Error>"
                            + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    System.out.println("Exception: " + e.getMessage());
                }

                // bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                System.exit(1);

            } else {
                // geziptes SIP --> in temp dir entzipen
                String toplevelDir = valDatei.getName();
                int lastDotIdx = toplevelDir.lastIndexOf(".");
                toplevelDir = toplevelDir.substring(0, lastDotIdx);
                tmpDirZip = new File(
                        tmpDir.getAbsolutePath() + File.separator + "ZIP" + File.separator + toplevelDir);
                try {
                    Zip64Archiver.unzip(valDatei.getAbsolutePath(), tmpDirZip.getAbsolutePath());
                } catch (Exception e) {
                    try {
                        Zip64Archiver.unzip64(valDatei, tmpDirZip);
                    } catch (Exception e1) {
                        // Abbruch! D.h. Sip message beginnen, Meldung und Beenden ab hier bis System.exit
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1));
                        valDatei = originalSipFile;
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE,
                                kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE,
                                valDatei.getAbsolutePath()));
                        System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION));
                        System.out.println(valDatei.getAbsolutePath());

                        // die eigentliche Fehlermeldung
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_MODUL_Aa_SIP)
                                + kostval.getTextResourceService().getText(ERROR_XML_AA_CANNOTEXTRACTZIP));
                        System.out.println(
                                kostval.getTextResourceService().getText(ERROR_XML_AA_CANNOTEXTRACTZIP));

                        // Fehler im Validierten SIP --> invalide & Abbruch
                        LOGGER.logError(
                                kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
                        LOGGER.logError(
                                kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                        System.out.println("Invalid");
                        System.out.println("");
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));

                        // Zeitstempel End
                        java.util.Date nowEnd = new java.util.Date();
                        java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat(
                                "dd.MM.yyyy HH:mm:ss");
                        String ausgabeEnd = sdfEnd.format(nowEnd);
                        ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
                        Util.valEnd(ausgabeEnd, logFile);
                        Util.amp(logFile);

                        // Die Konfiguration hereinkopieren
                        try {
                            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                            factory.setValidating(false);

                            factory.setExpandEntityReferences(false);

                            Document docConfig = factory.newDocumentBuilder().parse(configFile);
                            NodeList list = docConfig.getElementsByTagName("configuration");
                            Element element = (Element) list.item(0);

                            Document docLog = factory.newDocumentBuilder().parse(logFile);

                            Node dup = docLog.importNode(element, true);

                            docLog.getDocumentElement().appendChild(dup);
                            FileWriter writer = new FileWriter(logFile);

                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            ElementToStream(docLog.getDocumentElement(), baos);
                            String stringDoc2 = new String(baos.toByteArray());
                            writer.write(stringDoc2);
                            writer.close();

                            // Der Header wird dabei leider verschossen, wieder zurck ndern
                            String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                            Util.oldnewstring(oldstring, newstring, logFile);

                        } catch (Exception e2) {
                            LOGGER.logError("<Error>" + kostval.getTextResourceService()
                                    .getText(ERROR_XML_UNKNOWN, e2.getMessage()));
                            System.out.println("Exception: " + e2.getMessage());
                        }

                        // bestehendes Workverzeichnis ggf. lschen
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        System.exit(1);
                    }
                }
                valDatei = tmpDirZip;

                File toplevelfolder = new File(
                        valDatei.getAbsolutePath() + File.separator + valDatei.getName());
                if (toplevelfolder.exists()) {
                    valDatei = toplevelfolder;
                }
                unSipFile = valDatei;
            }
        } else {
            // SIP ist ein Ordner valDatei bleibt unverndert
        }

        // Vorgngige Formatvalidierung (Schritt 3c)
        Map<String, File> fileMap = Util.getFileMap(valDatei, false);
        Set<String> fileMapKeys = fileMap.keySet();

        int pdf = 0;
        int tiff = 0;
        int siard = 0;
        int txt = 0;
        int csv = 0;
        int xml = 0;
        int xsd = 0;
        int wave = 0;
        int mp3 = 0;
        int jp2 = 0;
        int jpx = 0;
        int jpeg = 0;
        int png = 0;
        int dng = 0;
        int svg = 0;
        int mpeg2 = 0;
        int mp4 = 0;
        int xls = 0;
        int odt = 0;
        int ods = 0;
        int odp = 0;
        int other = 0;

        for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) {
            String entryName = iterator.next();
            File newFile = fileMap.get(entryName);

            if (!newFile.isDirectory()
                    && newFile.getAbsolutePath().contains(File.separator + "content" + File.separator)) {
                valDatei = newFile;
                count = count + 1;

                // Ausgabe Dateizhler Ersichtlich das KOST-Val Dateien durchsucht
                System.out.print(count + "   ");
                System.out.print("\r");

                String extension = valDatei.getName();
                int lastIndexOf = extension.lastIndexOf(".");
                if (lastIndexOf == -1) {
                    // empty extension
                    extension = "other";
                } else {
                    extension = extension.substring(lastIndexOf);
                }

                if (extension.equalsIgnoreCase(".pdf") || extension.equalsIgnoreCase(".pdfa")) {
                    pdf = pdf + 1;
                } else if (extension.equalsIgnoreCase(".tiff") || extension.equalsIgnoreCase(".tif")) {
                    tiff = tiff + 1;
                } else if (extension.equalsIgnoreCase(".siard")) {
                    siard = siard + 1;
                } else if (extension.equalsIgnoreCase(".txt")) {
                    txt = txt + 1;
                } else if (extension.equalsIgnoreCase(".csv")) {
                    csv = csv + 1;
                } else if (extension.equalsIgnoreCase(".xml")) {
                    xml = xml + 1;
                } else if (extension.equalsIgnoreCase(".xsd")) {
                    xsd = xsd + 1;
                } else if (extension.equalsIgnoreCase(".wav")) {
                    wave = wave + 1;
                } else if (extension.equalsIgnoreCase(".mp3")) {
                    mp3 = mp3 + 1;
                } else if (extension.equalsIgnoreCase(".jp2")) {
                    jp2 = jp2 + 1;
                } else if (extension.equalsIgnoreCase(".jpx") || extension.equalsIgnoreCase(".jpf")) {
                    jpx = jpx + 1;
                } else if (extension.equalsIgnoreCase(".jpe") || extension.equalsIgnoreCase(".jpeg")
                        || extension.equalsIgnoreCase(".jpg")) {
                    jpeg = jpeg + 1;
                } else if (extension.equalsIgnoreCase(".png")) {
                    png = png + 1;
                } else if (extension.equalsIgnoreCase(".dng")) {
                    dng = dng + 1;
                } else if (extension.equalsIgnoreCase(".svg")) {
                    svg = svg + 1;
                } else if (extension.equalsIgnoreCase(".mpeg") || extension.equalsIgnoreCase(".mpg")) {
                    mpeg2 = mpeg2 + 1;
                } else if (extension.equalsIgnoreCase(".f4a") || extension.equalsIgnoreCase(".f4v")
                        || extension.equalsIgnoreCase(".m4a") || extension.equalsIgnoreCase(".m4v")
                        || extension.equalsIgnoreCase(".mp4")) {
                    mp4 = mp4 + 1;
                } else if (extension.equalsIgnoreCase(".xls") || extension.equalsIgnoreCase(".xlw")
                        || extension.equalsIgnoreCase(".xlsx")) {
                    xls = xls + 1;
                } else if (extension.equalsIgnoreCase(".odt") || extension.equalsIgnoreCase(".ott")) {
                    odt = odt + 1;
                } else if (extension.equalsIgnoreCase(".ods") || extension.equalsIgnoreCase(".ots")) {
                    ods = ods + 1;
                } else if (extension.equalsIgnoreCase(".odp") || extension.equalsIgnoreCase(".otp")) {
                    odp = odp + 1;
                } else {
                    other = other + 1;
                }

                if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2")))
                        && jp2Validation.equals("yes")) {

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        jp2CountIo = jp2CountIo + 1;
                    } else {
                        jp2CountNio = jp2CountNio + 1;
                    }

                } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".tiff")
                        || valDatei.getAbsolutePath().toLowerCase().endsWith(".tif")))
                        && tiffValidation.equals("yes")) {

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        tiffCountIo = tiffCountIo + 1;
                    } else {
                        tiffCountNio = tiffCountNio + 1;
                    }

                } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".siard"))
                        && siardValidation.equals("yes")) {

                    // Arbeitsverzeichnis zum Entpacken des Archivs erstellen
                    String pathToWorkDirSiard = kostval.getConfigurationService().getPathToWorkDir();
                    File tmpDirSiard = new File(pathToWorkDirSiard + File.separator + "SIARD");
                    if (tmpDirSiard.exists()) {
                        Util.deleteDir(tmpDirSiard);
                    }
                    if (!tmpDirSiard.exists()) {
                        tmpDirSiard.mkdir();
                    }

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        siardCountIo = siardCountIo + 1;
                    } else {
                        siardCountNio = siardCountNio + 1;
                    }

                } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf")
                        || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa")))
                        && pdfaValidation.equals("yes")) {

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        pdfaCountIo = pdfaCountIo + 1;
                    } else {
                        pdfaCountNio = pdfaCountNio + 1;
                    }

                } else {
                    countNio = countNio + 1;
                }
            }
        }

        countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio;
        countSummaryIo = pdfaCountIo + siardCountIo + tiffCountIo + jp2CountIo;
        int countSummaryIoP = 100 / count * countSummaryIo;
        int countSummaryNioP = 100 / count * countSummaryNio;
        int countNioP = 100 / count * countNio;
        String summary3c = kostval.getTextResourceService().getText(MESSAGE_XML_SUMMARY_3C, count,
                countSummaryIo, countSummaryNio, countNio, countSummaryIoP, countSummaryNioP, countNioP);

        if (countSummaryNio == 0) {
            // alle Validierten Dateien valide
            validFormat = true;
            fileName3c = "3c_Valide.txt";
        } else {
            // Fehler in Validierten Dateien --> invalide
            validFormat = false;
            fileName3c = "3c_Invalide.txt";
        }
        // outputFile3c = new File( directoryOfLogfile + fileName3c );
        outputFile3c = new File(pathToWorkDir + File.separator + fileName3c);
        try {
            outputFile3c.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (countNio == count) {
            // keine Dateien Validiert
            LOGGER.logError(kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
            System.out
                    .println(kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
        }

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

        // Start Normale SIP-Validierung mit auswertung Format-Val. im 3c

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1));
        valDatei = unSipFile;
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE,
                kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)));
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE,
                originalSipFile.getAbsolutePath()));
        System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION));
        System.out.println(originalSipFile.getAbsolutePath());

        Controllersip controller = (Controllersip) context.getBean("controllersip");
        boolean okMandatory = false;
        okMandatory = controller.executeMandatory(valDatei, directoryOfLogfile);
        boolean ok = false;

        /* die Validierungen 1a - 1d sind obligatorisch, wenn sie bestanden wurden, knnen die
         * restlichen Validierungen, welche nicht zum Abbruch der Applikation fhren, ausgefhrt
         * werden.
         * 
         * 1a wurde bereits getestet (vor der Formatvalidierung entsprechend fngt der Controller mit
         * 1b an */
        if (okMandatory) {
            ok = controller.executeOptional(valDatei, directoryOfLogfile);
        }
        // Formatvalidierung validFormat
        ok = (ok && okMandatory && validFormat);

        if (ok) {
            // Validiertes SIP valide
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_VALID));
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
            System.out.println("Valid");
            System.out.println("");
        } else {
            // Fehler im Validierten SIP --> invalide
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
            System.out.println("Invalid");
            System.out.println("");

        }

        // ggf. Fehlermeldung 3c ergnzen Util.val3c(summary3c, logFile );

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));
        // Zeitstempel End
        java.util.Date nowEnd = new java.util.Date();
        java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeEnd = sdfEnd.format(nowEnd);
        ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
        Util.valEnd(ausgabeEnd, logFile);
        Util.val3c(summary3c, logFile);
        Util.amp(logFile);

        // Die Konfiguration hereinkopieren
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);

            factory.setExpandEntityReferences(false);

            Document docConfig = factory.newDocumentBuilder().parse(configFile);
            NodeList list = docConfig.getElementsByTagName("configuration");
            Element element = (Element) list.item(0);

            Document docLog = factory.newDocumentBuilder().parse(logFile);

            Node dup = docLog.importNode(element, true);

            docLog.getDocumentElement().appendChild(dup);
            FileWriter writer = new FileWriter(logFile);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ElementToStream(docLog.getDocumentElement(), baos);
            String stringDoc2 = new String(baos.toByteArray());
            writer.write(stringDoc2);
            writer.close();

            // Der Header wird dabei leider verschossen, wieder zurck ndern
            String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
            Util.oldnewstring(oldstring, newstring, logFile);

        } catch (Exception e) {
            LOGGER.logError(
                    "<Error>" + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            System.out.println("Exception: " + e.getMessage());
        }

        // bestehendes Workverzeichnis ggf. lschen
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
        }
        StringBuffer command = new StringBuffer("rd " + tmpDir.getAbsolutePath() + " /s /q");

        try {
            // KaD-Diagnose-Datei mit den neusten Anzahl Dateien pro KaD-Format Updaten
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlDiaCopy);

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("KOSTVal_FFCounter");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;

                    if (pdf > 0) {
                        String pdfNodeString = eElement.getElementsByTagName("pdf").item(0).getTextContent();
                        int pdfNodeValue = Integer.parseInt(pdfNodeString);
                        pdf = pdf + pdfNodeValue;
                        Util.kadDia("<pdf>" + pdfNodeValue + "</pdf>", "<pdf>" + pdf + "</pdf>", xmlDiaCopy);
                    }
                    if (tiff > 0) {
                        String tiffNodeString = eElement.getElementsByTagName("tiff").item(0).getTextContent();
                        int tiffNodeValue = Integer.parseInt(tiffNodeString);
                        tiff = tiff + tiffNodeValue;
                        Util.kadDia("<tiff>" + tiffNodeValue + "</tiff>", "<tiff>" + tiff + "</tiff>",
                                xmlDiaCopy);
                    }
                    if (siard > 0) {
                        String siardNodeString = eElement.getElementsByTagName("siard").item(0)
                                .getTextContent();
                        int siardNodeValue = Integer.parseInt(siardNodeString);
                        siard = siard + siardNodeValue;
                        Util.kadDia("<siard>" + siardNodeValue + "</siard>", "<siard>" + siard + "</siard>",
                                xmlDiaCopy);
                    }
                    if (txt > 0) {
                        String txtNodeString = eElement.getElementsByTagName("txt").item(0).getTextContent();
                        int txtNodeValue = Integer.parseInt(txtNodeString);
                        txt = txt + txtNodeValue;
                        Util.kadDia("<txt>" + txtNodeValue + "</txt>", "<txt>" + txt + "</txt>", xmlDiaCopy);
                    }
                    if (csv > 0) {
                        String csvNodeString = eElement.getElementsByTagName("csv").item(0).getTextContent();
                        int csvNodeValue = Integer.parseInt(csvNodeString);
                        csv = csv + csvNodeValue;
                        Util.kadDia("<csv>" + csvNodeValue + "</csv>", "<csv>" + csv + "</csv>", xmlDiaCopy);
                    }
                    if (xml > 0) {
                        String xmlNodeString = eElement.getElementsByTagName("xml").item(0).getTextContent();
                        int xmlNodeValue = Integer.parseInt(xmlNodeString);
                        xml = xml + xmlNodeValue;
                        Util.kadDia("<xml>" + xmlNodeValue + "</xml>", "<xml>" + xml + "</xml>", xmlDiaCopy);
                    }
                    if (xsd > 0) {
                        String xsdNodeString = eElement.getElementsByTagName("xsd").item(0).getTextContent();
                        int xsdNodeValue = Integer.parseInt(xsdNodeString);
                        xsd = xsd + xsdNodeValue;
                        Util.kadDia("<xsd>" + xsdNodeValue + "</xsd>", "<xsd>" + xsd + "</xsd>", xmlDiaCopy);
                    }
                    if (wave > 0) {
                        String waveNodeString = eElement.getElementsByTagName("wave").item(0).getTextContent();
                        int waveNodeValue = Integer.parseInt(waveNodeString);
                        wave = wave + waveNodeValue;
                        Util.kadDia("<wave>" + waveNodeValue + "</wave>", "<wave>" + wave + "</wave>",
                                xmlDiaCopy);
                    }
                    if (mp3 > 0) {
                        String mp3NodeString = eElement.getElementsByTagName("mp3").item(0).getTextContent();
                        int mp3NodeValue = Integer.parseInt(mp3NodeString);
                        mp3 = mp3 + mp3NodeValue;
                        Util.kadDia("<mp3>" + mp3NodeValue + "</mp3>", "<mp3>" + mp3 + "</mp3>", xmlDiaCopy);
                    }
                    if (jp2 > 0) {
                        String jp2NodeString = eElement.getElementsByTagName("jp2").item(0).getTextContent();
                        int jp2NodeValue = Integer.parseInt(jp2NodeString);
                        jp2 = jp2 + jp2NodeValue;
                        Util.kadDia("<jp2>" + jp2NodeValue + "</jp2>", "<jp2>" + jp2 + "</jp2>", xmlDiaCopy);
                    }
                    if (jpx > 0) {
                        String jpxNodeString = eElement.getElementsByTagName("jpx").item(0).getTextContent();
                        int jpxNodeValue = Integer.parseInt(jpxNodeString);
                        jpx = jpx + jpxNodeValue;
                        Util.kadDia("<jpx>" + jpxNodeValue + "</jpx>", "<jpx>" + jpx + "</jpx>", xmlDiaCopy);
                    }
                    if (jpeg > 0) {
                        String jpegNodeString = eElement.getElementsByTagName("jpeg").item(0).getTextContent();
                        int jpegNodeValue = Integer.parseInt(jpegNodeString);
                        jpeg = jpeg + jpegNodeValue;
                        Util.kadDia("<jpeg>" + jpegNodeValue + "</jpeg>", "<jpeg>" + jpeg + "</jpeg>",
                                xmlDiaCopy);
                    }
                    if (png > 0) {
                        String pngNodeString = eElement.getElementsByTagName("png").item(0).getTextContent();
                        int pngNodeValue = Integer.parseInt(pngNodeString);
                        png = png + pngNodeValue;
                        Util.kadDia("<png>" + pngNodeValue + "</png>", "<png>" + png + "</png>", xmlDiaCopy);
                    }
                    if (dng > 0) {
                        String dngNodeString = eElement.getElementsByTagName("dng").item(0).getTextContent();
                        int dngNodeValue = Integer.parseInt(dngNodeString);
                        dng = dng + dngNodeValue;
                        Util.kadDia("<dng>" + dngNodeValue + "</dng>", "<dng>" + dng + "</dng>", xmlDiaCopy);
                    }
                    if (svg > 0) {
                        String svgNodeString = eElement.getElementsByTagName("svg").item(0).getTextContent();
                        int svgNodeValue = Integer.parseInt(svgNodeString);
                        svg = svg + svgNodeValue;
                        Util.kadDia("<svg>" + svgNodeValue + "</svg>", "<svg>" + svg + "</svg>", xmlDiaCopy);
                    }
                    if (mpeg2 > 0) {
                        String mpeg2NodeString = eElement.getElementsByTagName("mpeg2").item(0)
                                .getTextContent();
                        int mpeg2NodeValue = Integer.parseInt(mpeg2NodeString);
                        mpeg2 = mpeg2 + mpeg2NodeValue;
                        Util.kadDia("<mpeg2>" + mpeg2NodeValue + "</mpeg2>", "<mpeg2>" + mpeg2 + "</mpeg2>",
                                xmlDiaCopy);
                    }
                    if (mp4 > 0) {
                        String mp4NodeString = eElement.getElementsByTagName("mp4").item(0).getTextContent();
                        int mp4NodeValue = Integer.parseInt(mp4NodeString);
                        mp4 = mp4 + mp4NodeValue;
                        Util.kadDia("<mp4>" + mp4NodeValue + "</mp4>", "<mp4>" + mp4 + "</mp4>", xmlDiaCopy);
                    }
                    if (xls > 0) {
                        String xlsNodeString = eElement.getElementsByTagName("xls").item(0).getTextContent();
                        int xlsNodeValue = Integer.parseInt(xlsNodeString);
                        xls = xls + xlsNodeValue;
                        Util.kadDia("<xls>" + xlsNodeValue + "</xls>", "<xls>" + xls + "</xls>", xmlDiaCopy);
                    }
                    if (odt > 0) {
                        String odtNodeString = eElement.getElementsByTagName("odt").item(0).getTextContent();
                        int odtNodeValue = Integer.parseInt(odtNodeString);
                        odt = odt + odtNodeValue;
                        Util.kadDia("<odt>" + odtNodeValue + "</odt>", "<odt>" + odt + "</odt>", xmlDiaCopy);
                    }
                    if (ods > 0) {
                        String odsNodeString = eElement.getElementsByTagName("ods").item(0).getTextContent();
                        int odsNodeValue = Integer.parseInt(odsNodeString);
                        ods = ods + odsNodeValue;
                        Util.kadDia("<ods>" + odsNodeValue + "</ods>", "<ods>" + ods + "</ods>", xmlDiaCopy);
                    }
                    if (odp > 0) {
                        String odpNodeString = eElement.getElementsByTagName("odp").item(0).getTextContent();
                        int odpNodeValue = Integer.parseInt(odpNodeString);
                        odp = odp + odpNodeValue;
                        Util.kadDia("<odp>" + odpNodeValue + "</odp>", "<odp>" + odp + "</odp>", xmlDiaCopy);
                    }
                    if (other > 0) {
                        String otherNodeString = eElement.getElementsByTagName("other").item(0)
                                .getTextContent();
                        int otherNodeValue = Integer.parseInt(otherNodeString);
                        other = other + otherNodeValue;
                        Util.kadDia("<other>" + otherNodeValue + "</other>", "<other>" + other + "</other>",
                                xmlDiaCopy);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ok) {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            if (tmpDir.exists()) {
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(command.toString());
            }
            System.exit(0);
        } else {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            if (tmpDir.exists()) {
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(command.toString());
            }
            System.exit(2);
        }
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));

    } else {
        /* Ueberprfung des Parameters (Val-Typ): format / sip args[0] ist nicht "--format" oder
         * "--sip" --> INVALIDE */
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
            tmpDir.deleteOnExit();
        }
        System.exit(1);
    }
}

From source file:by.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;/*from ww w.j ava2 s  . c om*/
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            System.out.println(server + ":" + port);
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        System.out.println("???" + username + "," + password);
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:com.rabbitmq.perf.PerfTest.java

public static void main(String[] args) {
    Options options = getOptions();/*  w  w  w . j  a v a  2  s .  c o m*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }
        String testID = new SimpleDateFormat("HHmmss-SSS").format(Calendar.getInstance().getTime());
        testID = strArg(cmd, 'd', "test-" + testID);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        String queueNames = strArg(cmd, 'u', "");
        String routingKey = strArg(cmd, 'k', null);
        boolean randomRoutingKey = cmd.hasOption('K');
        int samplingInterval = intArg(cmd, 'i', 1);
        float producerRateLimit = floatArg(cmd, 'r', 0.0f);
        float consumerRateLimit = floatArg(cmd, 'R', 0.0f);
        int producerCount = intArg(cmd, 'x', 1);
        int consumerCount = intArg(cmd, 'y', 1);
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        long confirm = intArg(cmd, 'c', -1);
        boolean autoAck = cmd.hasOption('a');
        int multiAckEvery = intArg(cmd, 'A', 0);
        int channelPrefetch = intArg(cmd, 'Q', 0);
        int consumerPrefetch = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        int producerMsgCount = intArg(cmd, 'C', 0);
        int consumerMsgCount = intArg(cmd, 'D', 0);
        List<?> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);
        boolean predeclared = cmd.hasOption('p');

        String uri = strArg(cmd, 'h', "amqp://localhost");

        //setup
        PrintlnStats stats = new PrintlnStats(testID, 1000L * samplingInterval, producerCount > 0,
                consumerCount > 0, (flags.contains("mandatory") || flags.contains("immediate")), confirm != -1);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setShutdownTimeout(0); // So we still shut down even with slow consumers
        factory.setUri(uri);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        MulticastParams p = new MulticastParams();
        p.setAutoAck(autoAck);
        p.setAutoDelete(true);
        p.setConfirm(confirm);
        p.setConsumerCount(consumerCount);
        p.setConsumerMsgCount(consumerMsgCount);
        p.setConsumerRateLimit(consumerRateLimit);
        p.setConsumerTxSize(consumerTxSize);
        p.setExchangeName(exchangeName);
        p.setExchangeType(exchangeType);
        p.setFlags(flags);
        p.setMultiAckEvery(multiAckEvery);
        p.setMinMsgSize(minMsgSize);
        p.setPredeclared(predeclared);
        p.setConsumerPrefetch(consumerPrefetch);
        p.setChannelPrefetch(channelPrefetch);
        p.setProducerCount(producerCount);
        p.setProducerMsgCount(producerMsgCount);
        p.setProducerTxSize(producerTxSize);
        p.setQueueNames(Arrays.asList(queueNames.split(",")));
        p.setRoutingKey(routingKey);
        p.setRandomRoutingKey(randomRoutingKey);
        p.setProducerRateLimit(producerRateLimit);
        p.setTimeLimit(timeLimit);

        MulticastSet set = new MulticastSet(stats, factory, p, testID);
        set.run(true);

        stats.printFinal();
    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException, Exception {
    // MY CODE/*from   w  ww  . j a  v a2  s .c o  m*/
    if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) {
        return;
    }
    ;
    // MY CODE -- END

    boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false,
            hidden = false;
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        }
        // Always use binary transfer 
        //            else if (args[base].equals("-b")) {
        //                binaryTransfer = true;
        //            }
        else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);
            // MY CODE
            byte[] bytes = IOUtils.toByteArray(input);
            InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes));
            // MY CODE -- END
            ftp.storeFile(remote, encrypted);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            // MY CODE
            ByteArrayOutputStream remoteFile = new ByteArrayOutputStream();
            //InputStream byteIn = new ByteArrayInputStream(buf);
            ftp.retrieveFile(remote, remoteFile);
            remoteFile.flush();
            Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray());
            if (opt.isPresent()) {
                output.write(opt.get());
            }
            remoteFile.close();
            // MY CODE -- END
            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

/**
 * @param args// w  ww.ja va 2  s  . c o  m
 */
public static void main(String[] args) {
    boolean inplace = false;

    String workspace = "/Users/davidabad/workspaces/SIDE-Modules/";
    String frameworkmodulesPath = "/Volumes/Data/SVN/side/HEAD/S-IDE/FrameworksModules/trunk/";
    String classifier_base = "enterprise";
    String version_base = "3.4.6";
    String classifier_target = "enterprise";
    String version_target = "3.4.11";
    String frameworkmodulesInplace = "/Volumes/Data/SVN/projects/Ifremer/IfremerV5/src/modules/mavenProjects";

    Properties props = new Properties();
    try {
        InputStream resourceAsStream = PrepareSIDEModulesMigration.class
                .getResourceAsStream("config.properties");
        if (resourceAsStream != null) {
            props.load(resourceAsStream);

            inplace = Boolean.parseBoolean(props.getProperty("inplace", Boolean.toString(inplace)));
            workspace = props.getProperty("workspace", workspace);
            frameworkmodulesPath = props.getProperty("frameworkmodulesPath", frameworkmodulesPath);
            classifier_base = props.getProperty("classifier_base", classifier_base);
            version_base = props.getProperty("version_base", version_base);
            classifier_target = props.getProperty("classifier_target", classifier_target);
            version_target = props.getProperty("version_target", version_target);
            frameworkmodulesInplace = props.getProperty("frameworkmodulesInplace", frameworkmodulesInplace);
        } else {
            System.out.println("no configuration founded in classpath config.properties");
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    System.out.println("properties :");
    Enumeration<?> propertyNames = props.propertyNames();
    while (propertyNames.hasMoreElements()) {
        String nextElement = propertyNames.nextElement().toString();
        System.out.println("\t " + nextElement + " : " + props.getProperty(nextElement));
    }

    File workspaceFile = new File(workspace);

    File targetHome = new File(workspaceFile, MIGRATION_FOLDER);
    if (targetHome.exists()) {
        try {
            FileUtils.deleteDirectory(targetHome);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    final String versionInProjectName = getVersionInProjectName(classifier_base, version_base);
    String versionInProjectName2 = getVersionInProjectName(classifier_target, version_target);

    if (frameworkmodulesPath.contains(",")) {
        // this is a list of paths
        String[] split = frameworkmodulesPath.split(",");
        for (String string : split) {
            if (StringUtils.trimToNull(string) != null) {
                executeInpath(inplace, string, classifier_base, version_base, classifier_target, version_target,
                        frameworkmodulesInplace, workspaceFile, versionInProjectName, versionInProjectName2);
            }
        }
    } else {
        executeInpath(inplace, frameworkmodulesPath, classifier_base, version_base, classifier_target,
                version_target, frameworkmodulesInplace, workspaceFile, versionInProjectName,
                versionInProjectName2);
    }

    System.out.println("Job's done !");
    System.out.println("Please check " + MIGRATION_FOLDER);
    System.out.println(
            "If all is ok you can use commit.sh in a terminal do : cd " + MIGRATION_FOLDER + "; sh commit.sh");
    System.out.println(
            "This script will create new svn projet and commit resources, add 'target' to svn:ignore ...");

}

From source file:de.prozesskraft.pkraft.Createdoc.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    Createdoc tmp = new Createdoc();
    /*----------------------------
      get options from ini-file/*  w  w  w .  j ava2 s. co  m*/
    ----------------------------*/
    File installDir = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Createdoc.class) + "/..");

    File inifile = new java.io.File(installDir.getAbsolutePath() + "/etc/pkraft-createdoc.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option odefinition = OptionBuilder.withArgName("definition").hasArg()
            .withDescription("[mandatory] process definition file")
            //            .isRequired()
            .create("definition");

    Option oformat = OptionBuilder.withArgName("format").hasArg()
            .withDescription("[mandatory, default=pdf] output format (pdf|pptx) ").create("format");

    Option ooutput = OptionBuilder.withArgName("output").hasArg().withDescription(
            "[mandatory, default=out.<format>] output file with full documentation of process definition")
            //            .isRequired()
            .create("output");

    ////      Option property = OptionBuilder.withArgName( "property=value" )
    ////            .hasArgs(2)
    ////            .withValueSeparator()
    ////            .withDescription( "use value for given property" )
    ////            .create("D");
    //      
    //      /*----------------------------
    //        create options object
    //      ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(odefinition);
    options.addOption(oformat);
    options.addOption(ooutput);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    line = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("createdoc", options);
        System.exit(0);
    }

    if (line.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      die variablen festlegen
    ----------------------------*/
    int error = 0;
    String definition = null;
    String format = null;
    String output = null;

    // festlegen von definition
    if (line.hasOption("definition")) {
        definition = line.getOptionValue("definition");
        if (!(new java.io.File(definition).exists())) {
            System.err.println("file does not exist " + definition);
        }
    } else {
        System.err.println("parameter -definition is mandatory");
        error++;
    }

    // festlegen von format
    if (line.hasOption("format")) {
        if (line.getOptionValue("format").matches("pdf|pptx")) {
            format = line.getOptionValue("format");
        } else {
            System.err.println("for -format use only pdf|pptx");
            error++;
        }
    } else {
        format = "pdf";
    }

    // festlegen von output
    if (line.hasOption("output")) {
        output = line.getOptionValue("output");
    } else {
        output = "out." + format;
    }

    // feststellen ob output bereits existiert
    if (new java.io.File(output).exists()) {
        System.err.println("output already exists: " + output);
        error++;
    }

    // aussteigen, falls fehler aufgetaucht sind
    if (error > 0) {
        System.err.println("error(s) occured. try -help for help.");
        System.exit(1);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process process = new Process();
    Reporter report;

    process.setInfilexml(definition);

    System.out.println("info: reading process definition " + definition);

    try {
        process.readXml();
        process.setStepRanks();
    }

    catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //festlegen des temporaeren verzeichnisses fuer die Daten und Pfade erzeugen
    long jetztMillis = System.currentTimeMillis();
    String randomPathJasperFilled = "/tmp/" + jetztMillis + "_jasperFilled";
    String randomPathPng = "/tmp/" + jetztMillis + "_png";
    String randomPathPdf = "/tmp/" + jetztMillis + "_pdf";
    String randomPathPptx = "/tmp/" + jetztMillis + "_pptx";

    new File(randomPathJasperFilled).mkdirs();
    new File(randomPathPng).mkdirs();
    new File(randomPathPdf).mkdirs();
    new File(randomPathPptx).mkdirs();

    //////////////////////////////////////////

    // erstellen der Bilder

    // konfigurieren der processing ansicht
    //      PmodelViewPage page = new PmodelViewPage(process);
    PmodelViewPage page = new PmodelViewPage();
    page.einstellungen.getProcess().setStepRanks();
    page.einstellungen.setSize(100);
    page.einstellungen.setZoom(100);
    //      page.einstellungen.setZoom(8 * 100/process.getMaxLevel());
    page.einstellungen.setTextsize(0);
    page.einstellungen.setRanksize(7);
    page.einstellungen.setWidth(2500);
    page.einstellungen.setHeight(750);
    page.einstellungen.setGravx(10);
    page.einstellungen.setGravy(0);
    page.einstellungen.setRootpositionratiox((float) 0.05);
    page.einstellungen.setRootpositionratioy((float) 0.5);
    page.einstellungen.setProcess(process);

    createContents(page);

    // mit open kann die page angezeigt werden
    if (!(produktiv)) {
        open();
    }

    //      // warten
    //      System.out.println("stabilisierung ansicht: 5 sekunden warten gravitation = "+page.einstellungen.getGravx());
    //      long jetzt5 = System.currentTimeMillis();
    //      while (System.currentTimeMillis() < jetzt5 + 5000)
    //      {
    //         
    //      }
    //
    //      page.einstellungen.setGravx(10);
    //
    // warten
    int wartezeitSeconds = 1;
    if (produktiv) {
        wartezeitSeconds = page.einstellungen.getProcess().getStep().size() * 2;
    }
    System.out.println("stabilisierung ansicht: " + wartezeitSeconds + " sekunden warten gravitation = "
            + page.einstellungen.getGravx());
    long jetzt6 = System.currentTimeMillis();
    while (System.currentTimeMillis() < jetzt6 + (wartezeitSeconds * 1000)) {

    }

    page.einstellungen.setFix(true);

    // VORBEREITUNG) bild speichern
    processTopologyImagePath = randomPathPng + "/processTopology.png";
    page.savePic(processTopologyImagePath);
    // zuerst 1 sekunde warten, dann autocrop
    long jetzt = System.currentTimeMillis();
    while (System.currentTimeMillis() < jetzt + 1000) {

    }
    new AutoCropBorder(processTopologyImagePath);

    // VORBEREITUNG) fuer jeden step ein bild speichern
    for (Step actualStep : process.getStep()) {

        // root ueberspringen
        //         if (actualStep.isRoot());

        String stepImagePath = randomPathPng + "/step_" + actualStep.getName() + "_Topology.png";

        // Farbe des Steps auf finished (gruen) aendern
        page.einstellungen.getProcess().getRootStep().setStatusOverwrite("waiting");
        actualStep.setStatusOverwrite("finished");

        // etwas warten, bis die farbe bezeichnet wurde
        long jetzt4 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt4 + 500) {

        }

        page.savePic(stepImagePath);
        // zuerst 1 sekunde warten, dann autocrop
        long jetzt3 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt3 + 1000) {

        }
        new AutoCropBorder(stepImagePath);

        stepTopologyImagePath.put(actualStep.getName(), stepImagePath);

        // farbe wieder auf grau aendern
        actualStep.setStatusOverwrite(null);

        System.out.println("erstelle bild fuer step: " + actualStep.getName());

        long jetzt2 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt2 + 1000) {

        }
    }

    page.destroy();

    //////////////////////////////////////////
    report = new Reporter();

    // P03) erstellen des p03
    System.out.println("info: generating p03.");

    String pdfPathP03 = null;
    String pptxPathP03 = null;
    String jasperPathP03 = null;
    String jasperFilledPathP03 = null;

    // P03) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p03") != null) {
        pdfPathP03 = randomPathPdf + "/p03.pdf";
        pptxPathP03 = randomPathPptx + "/p03.pptx";
        jasperPathP03 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p03");
        jasperFilledPathP03 = (randomPathJasperFilled + "/p03.jasperFilled");

        pdfRankFiles.put("0.0.03", pdfPathP03);
        pptxRankFiles.put("0.0.03", pptxPathP03);
    } else {
        System.err.println("no entry 'p03' found in ini file");
        System.exit(1);
    }

    DateFormat dateFormat = new SimpleDateFormat("dd. MM. yyyy");
    Date date = new Date();

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processDatum", dateFormat.format(date));
    report.setParameter("processArchitectLogoImagePath",
            installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "logo"));
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    try {
        report.fillReportFileToFile(jasperPathP03, jasperFilledPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP03, pdfPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP03, pptxPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////
    report = new Reporter();

    // P05) erstellen des p05
    System.out.println("info: generating p05.");

    String pdfPathP05 = null;
    String pptxPathP05 = null;
    String jasperPathP05 = null;
    String jasperFilledPathP05 = null;

    // P05) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p05") != null) {
        pdfPathP05 = randomPathPdf + "/p05.pdf";
        pptxPathP05 = randomPathPptx + "/p05.pptx";
        jasperPathP05 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p05");
        jasperFilledPathP05 = (randomPathJasperFilled + "/p05.jasperFilled");

        pdfRankFiles.put("0.0.05", pdfPathP05);
        pptxRankFiles.put("0.0.05", pptxPathP05);
    }

    else {
        System.err.println("no entry 'p05' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    try {
        report.fillReportFileToFile(jasperPathP05, jasperFilledPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP05, pdfPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP05, pptxPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////
    report = new Reporter();

    // P08) erstellen des p08
    System.out.println("info: generating p08.");

    String pdfPathP08 = null;
    String pptxPathP08 = null;
    String jasperPathP08 = null;
    String jasperFilledPathP08 = null;

    // P08) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p08") != null) {
        pdfPathP08 = randomPathPdf + "/p08.pdf";
        pptxPathP08 = randomPathPptx + "/p08.pptx";
        jasperPathP08 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p08");
        jasperFilledPathP08 = (randomPathJasperFilled + "/p08.jasperFilled");

        pdfRankFiles.put("0.0.08", pdfPathP08);
        pptxRankFiles.put("0.0.08", pptxPathP08);
    } else {
        System.err.println("no entry 'p08' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());
    report.setParameter("processDescription", process.getDescription());

    try {
        report.fillReportFileToFile(jasperPathP08, jasperFilledPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP08, pdfPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP08, pptxPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////

    report = new Reporter();

    // P10) erstellen des p10
    System.out.println("info: generating p10.");

    String pdfPathP10 = null;
    String pptxPathP10 = null;
    String jasperPathP10 = null;
    String jasperFilledPathP10 = null;

    // P10) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p10") != null) {
        pdfPathP10 = randomPathPdf + "/p10.pdf";
        pptxPathP10 = randomPathPptx + "/p10.pptx";
        jasperPathP10 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p10");
        jasperFilledPathP10 = (randomPathJasperFilled + "/p10.jasperFilled");

        pdfRankFiles.put("0.0.10", pdfPathP10);
        pptxRankFiles.put("0.0.10", pptxPathP10);
    } else {
        System.err.println("no entry 'p10' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // rootstep holen
    Step rootStep = process.getStep(process.getRootstepname());

    // ueber alle commit iterieren
    for (Commit actualCommit : rootStep.getCommit()) {

        // ueber alle files iterieren
        for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {
            HashMap<String, Object> row = new HashMap<String, Object>();

            // Spalte 'origin'
            row.put("origin", "user/cb2");

            // Spalte 'objectType'
            row.put("objectType", "file");

            // Spalte 'minOccur'
            row.put("minOccur", "" + actualFile.getMinoccur());

            // Spalte 'maxOccur'
            row.put("maxOccur", "" + actualFile.getMaxoccur());

            // Spalte 'objectKey'
            row.put("objectKey", actualFile.getKey());

            // die steps herausfinden, die dieses file benoetigen
            ArrayList<Step> allStepsThatNeedThisFileFromRoot = process.getStepWhichNeedFromRoot("file",
                    actualFile.getKey());
            String stepnameListe = "";
            for (Step actStep : allStepsThatNeedThisFileFromRoot) {
                stepnameListe += "\n=> " + actStep.getName();
            }

            // Spalte 'objectDescription'
            row.put("objectDescription", actualFile.getDescription() + stepnameListe);

            // Datensatz dem report hinzufuegen
            report.addField(row);
        }

        // ueber alle variablen iterieren
        for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
            HashMap<String, Object> row = new HashMap<String, Object>();

            // Spalte 'origin'
            row.put("origin", "user/cb2");

            // Spalte 'objectType'
            row.put("objectType", "variable");

            // Spalte 'minOccur'
            row.put("minOccur", "" + actualVariable.getMinoccur());

            // Spalte 'maxOccur'
            row.put("maxOccur", "" + actualVariable.getMaxoccur());

            // Spalte 'objectKey'
            row.put("objectKey", actualVariable.getKey());

            // die steps herausfinden, die dieses file benoetigen
            ArrayList<Step> allStepsThatNeedThisObjectFromRoot = process.getStepWhichNeedFromRoot("variable",
                    actualVariable.getKey());
            String stepnameListe = "";
            for (Step actStep : allStepsThatNeedThisObjectFromRoot) {
                stepnameListe += "\n=> " + actStep.getName();
            }

            // Spalte 'objectDescription'
            row.put("objectDescription", actualVariable.getDescription() + stepnameListe);

            // Datensatz dem report hinzufuegen
            report.addField(row);
        }

    }

    try {
        report.fillReportFileToFile(jasperPathP10, jasperFilledPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP10, pdfPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP10, pptxPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    report = new Reporter();

    // P20) erstellen des p20
    System.out.println("info: generating p20.");

    String pdfPathP20 = null;
    String pptxPathP20 = null;
    String jasperPathP20 = null;
    String jasperFilledPathP20 = null;

    // P20) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p20") != null) {
        pdfPathP20 = randomPathPdf + "/p20.pdf";
        pptxPathP20 = randomPathPptx + "/p20.pptx";
        jasperPathP20 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p20");
        jasperFilledPathP20 = (randomPathJasperFilled + "/p20.jasperFilled");

        pdfRankFiles.put("0.0.20", pdfPathP20);
        pptxRankFiles.put("0.0.20", pptxPathP20);
    } else {
        System.err.println("no entry 'p20' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // ueber alle steps iterieren (ausser root)
    for (Step actualStep : (ArrayList<Step>) process.getStep()) {

        // ueberspringen wenn es sich um root handelt
        if (!(actualStep.getName().equals(process.getRootstepname()))) {
            // ueber alle commit iterieren
            for (Commit actualCommit : actualStep.getCommit()) {

                // nur die, die toroot=true ( und spaeter auch tosdm=true)
                if (actualCommit.isTorootPresent()) {
                    // ueber alle files iterieren
                    for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {

                        HashMap<String, Object> row = new HashMap<String, Object>();

                        // Spalte 'destination'
                        row.put("destination", "user/cb2");

                        // Spalte 'objectType'
                        row.put("objectType", "file");

                        // Spalte 'minOccur'
                        row.put("minOccur", "" + actualFile.getMinoccur());

                        // Spalte 'maxOccur'
                        row.put("maxOccur", "" + actualFile.getMaxoccur());

                        // Spalte 'objectKey'
                        row.put("objectKey", actualFile.getKey());

                        // Spalte 'objectDescription'
                        row.put("objectDescription",
                                actualFile.getDescription() + "\n<= " + actualStep.getName());

                        // Datensatz dem report hinzufuegen
                        report.addField(row);
                    }

                    // ueber alle variablen iterieren
                    for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
                        HashMap<String, Object> row = new HashMap<String, Object>();

                        // Spalte 'objectType'
                        row.put("destination", "user/cb2");

                        // Spalte 'objectType'
                        row.put("objectType", "variable");

                        // Spalte 'minOccur'
                        row.put("minOccur", "" + actualVariable.getMinoccur());

                        // Spalte 'maxOccur'
                        row.put("maxOccur", "" + actualVariable.getMaxoccur());

                        // Spalte 'objectKey'
                        row.put("objectKey", actualVariable.getKey());

                        // Spalte 'objectDescription'
                        row.put("objectDescription",
                                actualVariable.getDescription() + "\n<= " + actualStep.getName());

                        // Datensatz dem report hinzufuegen
                        report.addField(row);
                    }
                }
            }
        }

    }

    try {
        report.fillReportFileToFile(jasperPathP20, jasperFilledPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP20, pdfPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP20, pptxPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    report = new Reporter();

    // P30) erstellen des p30
    System.out.println("info: generating p30.");

    String pdfPathP30 = null;
    String pptxPathP30 = null;
    String jasperPathP30 = null;
    String jasperFilledPathP30 = null;

    // P30) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p30") != null) {
        pdfPathP30 = randomPathPdf + "/p30.pdf";
        pptxPathP30 = randomPathPptx + "/p30.pptx";
        jasperPathP30 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p30");
        jasperFilledPathP30 = (randomPathJasperFilled + "/p30.jasperFilled");

        pdfRankFiles.put("0.0.30", pdfPathP30);
        pptxRankFiles.put("0.0.30", pptxPathP30);
    } else {
        System.err.println("no entry 'p30' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // P1) bild an report melden
    report.setParameter("processTopologyImagePath", processTopologyImagePath);

    try {
        report.fillReportFileToFile(jasperPathP30, jasperFilledPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP30, pdfPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP30, pptxPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //      System.exit(0);
    //////////////////////////////////////////

    report = new Reporter();

    // P40) erstellen des p40
    System.out.println("info: generating p40.");

    String pdfPathP40 = null;
    String pptxPathP40 = null;
    String jasperPathP40 = null;
    String jasperFilledPathP40 = null;

    // P40) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p40") != null) {
        pdfPathP40 = randomPathPdf + "/p40.pdf";
        pptxPathP40 = randomPathPptx + "/p40.pptx";
        jasperPathP40 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p40");
        jasperFilledPathP40 = (randomPathJasperFilled + "/p40.jasperFilled");

        pdfRankFiles.put("0.0.40", pdfPathP40);
        pptxRankFiles.put("0.0.40", pptxPathP40);
    } else {
        System.err.println("no entry 'p40' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // P40) bild an report melden
    report.setParameter("processTopologyImagePath", processTopologyImagePath);

    // Tabelle erzeugen

    ArrayList<Step> steps = process.getStep();
    for (int x = 0; x < steps.size(); x++) {
        HashMap<String, Object> row = new HashMap<String, Object>();
        Step actualStep = steps.get(x);

        // erste Spalte ist 'rank'
        // um die korrekte sortierung zu erhalten soll der rank-string auf jeweils 2 Stellen erweitert werden
        String[] rankArray = actualStep.getRank().split("\\.");
        Integer[] rankArrayInt = new Integer[rankArray.length];
        for (int y = 0; y < rankArray.length; y++) {
            rankArrayInt[y] = Integer.parseInt(rankArray[y]);
        }
        String rankFormated = String.format("%02d.%02d", rankArrayInt);
        row.put("stepRank", rankFormated);

        // zweite Spalte ist 'stepname'
        row.put("stepName", actualStep.getName());
        //            System.out.println("stepName: "+actualStep.getName());

        // dritte Spalte ist 'Beschreibung'
        row.put("stepDescription", actualStep.getDescription());
        //            System.out.println("stepRank: "+actualStep.getDescription());

        // wenn nicht der root-step, dann row eintragen
        if (!(actualStep.getName().equals(process.getRootstepname()))) {
            report.addField(row);
        }
    }

    try {
        report.fillReportFileToFile(jasperPathP40, jasperFilledPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP40, pdfPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP40, pptxPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    // fuer jeden Step einen eigenen Input Report erzeugen

    for (Step actualStep : process.getStep()) {
        // root-step ueberspringen
        if (actualStep.getName().equals(process.getRootstepname())) {
            System.out.println("skipping step root");
        }

        // alle anderen auswerten
        else {

            report = new Reporter();

            // P51x) erstellen des p51
            System.out.println(
                    "info: generating p51 for step " + actualStep.getRank() + " => " + actualStep.getName());

            String stepRank = actualStep.getRank();

            String pdfPathP51 = null;
            String pptxPathP51 = null;
            String jasperPathP51 = null;
            String jasperFilledPathP51 = null;

            // P51x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
            if (ini.get("pkraft-createdoc", "p51") != null) {
                pdfPathP51 = randomPathPdf + "/p5." + stepRank + ".1.pdf";
                pptxPathP51 = randomPathPptx + "/p5." + stepRank + ".1.pptx";
                jasperPathP51 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p51");
                jasperFilledPathP51 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled";

                String[] rankArray = stepRank.split("\\.");
                Integer[] rankArrayInt = new Integer[rankArray.length];
                for (int x = 0; x < rankArray.length; x++) {
                    rankArrayInt[x] = Integer.parseInt(rankArray[x]);
                }
                String rankFormated = String.format("%03d.%03d", rankArrayInt);

                pdfRankFiles.put(rankFormated + ".1", pdfPathP51);
                pptxRankFiles.put(rankFormated + ".1", pptxPathP51);
            } else {
                System.err.println("no entry 'p51' found in ini file");
                System.exit(1);
            }

            report.setParameter("processName", process.getName());
            report.setParameter("processVersion", process.getVersion());
            report.setParameter("processArchitectCompany", process.getArchitectCompany());
            report.setParameter("processArchitectName", process.getArchitectName());
            report.setParameter("processArchitectMail", process.getArchitectMail());
            report.setParameter("processCustomerCompany", process.getCustomerCompany());
            report.setParameter("processCustomerName", process.getCustomerName());
            report.setParameter("processCustomerMail", process.getCustomerMail());

            report.setParameter("stepName", actualStep.getName());
            report.setParameter("stepRank", stepRank);
            report.setParameter("stepDescription", actualStep.getDescription());

            String aufruf = "";
            if (actualStep.getWork() != null) {
                // zusammensetzen des scriptaufrufs
                String interpreter = "";

                if (actualStep.getWork().getInterpreter() != null) {
                    interpreter = actualStep.getWork().getInterpreter();
                }

                aufruf = interpreter + " " + actualStep.getWork().getCommand();
                for (Callitem actualCallitem : actualStep.getWork().getCallitem()) {
                    aufruf += " " + actualCallitem.getPar();
                    if (!(actualCallitem.getDel() == null)) {
                        aufruf += actualCallitem.getDel();
                    }
                    if (!(actualCallitem.getVal() == null)) {
                        aufruf += actualCallitem.getVal();
                    }
                }
            } else if (actualStep.getSubprocess() != null) {
                aufruf = ini.get("apps", "pkraft-startinstance");
                aufruf += " --pdomain " + actualStep.getSubprocess().getDomain();
                aufruf += " --pname " + actualStep.getSubprocess().getName();
                aufruf += " --pversion " + actualStep.getSubprocess().getVersion();

                for (Commit actCommit : actualStep.getSubprocess().getStep().getCommit()) {
                    for (de.prozesskraft.pkraft.File actFile : actCommit.getFile()) {
                        aufruf += " --commitfile " + actFile.getGlob();
                    }
                    for (Variable actVariable : actCommit.getVariable()) {
                        aufruf += " --commitvariable " + actVariable.getKey() + "=" + actVariable.getValue();
                    }
                }
            }
            report.setParameter("stepWorkCall", aufruf);

            // P51x) bild an report melden
            report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName()));

            // ueber alle lists iterieren
            for (List actualList : actualStep.getList()) {
                HashMap<String, Object> row = new HashMap<String, Object>();

                // Spalte 'Woher?'
                row.put("origin", "-");

                // Spalte 'typ'
                row.put("objectType", "wert");

                // Spalte 'minOccur'
                row.put("minOccur", "-");

                // Spalte 'maxOccur'
                row.put("maxOccur", "-");

                // Spalte 'Label'
                row.put("objectKey", actualList.getName());

                // Spalte 'Label'
                String listString = actualList.getItem().toString();
                row.put("objectDescription", listString.substring(1, listString.length() - 1));

                report.addField(row);
            }

            // ueber alle inits iterieren
            for (Init actualInit : actualStep.getInit()) {
                HashMap<String, Object> row = new HashMap<String, Object>();

                // Spalte 'Woher?'
                if (actualInit.getFromstep().equals(process.getRootstepname())) {
                    row.put("origin", "user/cb2");
                } else {
                    row.put("origin", actualInit.getFromstep());
                }

                // Spalte 'typ'
                row.put("objectType", actualInit.getFromobjecttype());

                // Spalte 'minOccur'
                row.put("minOccur", "" + actualInit.getMinoccur());

                // Spalte 'maxOccur'
                row.put("maxOccur", "" + actualInit.getMaxoccur());

                // Spalte 'Label'
                row.put("objectKey", actualInit.getListname());

                // Spalte 'Label'
                row.put("objectDescription", "-");

                report.addField(row);
            }

            try {
                report.fillReportFileToFile(jasperPathP51, jasperFilledPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pdf
            try {
                report.convertFileToPdf(jasperFilledPathP51, pdfPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pptx
            try {
                report.convertFileToPptx(jasperFilledPathP51, pptxPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            report = null;
        }
    }

    //////////////////////////////////////////

    // fuer jeden Step einen eigenen Output Report erzeugen

    for (Step actualStep : process.getStep()) {
        // root-step ueberspringen
        if (actualStep.getName().equals(process.getRootstepname())) {
            System.out.println("skipping step root");
        }

        // alle anderen auswerten
        else {

            report = new Reporter();

            // P52x) erstellen des p52
            System.out.println(
                    "info: generating p52 for step " + actualStep.getRank() + " => " + actualStep.getName());

            String stepRank = actualStep.getRank();

            String pdfPathP52 = null;
            String pptxPathP52 = null;
            String jasperPathP52 = null;
            String jasperFilledPathP52 = null;

            // P52x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
            if (ini.get("pkraft-createdoc", "p52") != null) {
                pdfPathP52 = randomPathPdf + "/p5." + stepRank + ".2.pdf";
                pptxPathP52 = randomPathPptx + "/p5." + stepRank + ".2.pptx";
                jasperPathP52 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p52");
                jasperFilledPathP52 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled";

                String[] rankArray = stepRank.split("\\.");
                Integer[] rankArrayInt = new Integer[rankArray.length];
                for (int x = 0; x < rankArray.length; x++) {
                    rankArrayInt[x] = Integer.parseInt(rankArray[x]);
                }
                String rankFormated = String.format("%03d.%03d", rankArrayInt);

                pdfRankFiles.put(rankFormated + ".2", pdfPathP52);
                pptxRankFiles.put(rankFormated + ".2", pptxPathP52);
            } else {
                System.err.println("no entry 'p52' found in ini file");
                System.exit(1);
            }

            report.setParameter("processName", process.getName());
            report.setParameter("processVersion", process.getVersion());
            report.setParameter("processArchitectCompany", process.getArchitectCompany());
            report.setParameter("processArchitectName", process.getArchitectName());
            report.setParameter("processArchitectMail", process.getArchitectMail());
            report.setParameter("processCustomerCompany", process.getCustomerCompany());
            report.setParameter("processCustomerName", process.getCustomerName());
            report.setParameter("processCustomerMail", process.getCustomerMail());

            report.setParameter("stepName", actualStep.getName());
            report.setParameter("stepRank", stepRank);

            // logfile ermitteln
            String logfile = "-";
            if (actualStep.getWork() != null) {
                if (actualStep.getWork().getLogfile() == null || actualStep.getWork().getLogfile().equals("")) {
                    report.setParameter("stepWorkLogfile", actualStep.getWork().getLogfile());
                }
            } else if (actualStep.getSubprocess() != null) {
                logfile = ".log";
            }
            report.setParameter("stepWorkLogfile", logfile);

            // zusammensetzen der return/exitcode informationen
            String exitInfo = "exit 0 = kein fehler aufgetreten";
            exitInfo += "\nexit >0 = ein fehler ist aufgetreten.";
            if (actualStep.getWork() != null) {
                for (Exit actualExit : actualStep.getWork().getExit()) {
                    exitInfo += "\nexit " + actualExit.getValue() + " = " + actualExit.getMsg();
                }
            }
            report.setParameter("stepWorkExit", exitInfo);

            // P52x) bild an report melden
            report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName()));

            // ueber alle inits iterieren
            for (Commit actualCommit : actualStep.getCommit()) {

                // ueber alle files iterieren
                for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {

                    HashMap<String, Object> row = new HashMap<String, Object>();

                    // Spalte 'destination'
                    if (actualCommit.isTorootPresent()) {
                        row.put("destination", "user/cb2");
                    } else {
                        row.put("destination", "prozessintern");
                    }

                    // Spalte 'objectType'
                    row.put("objectType", "file");

                    // Spalte 'minOccur'
                    row.put("minOccur", "" + actualFile.getMinoccur());

                    // Spalte 'maxOccur'
                    row.put("maxOccur", "" + actualFile.getMaxoccur());

                    // Spalte 'objectKey'
                    row.put("objectKey", actualFile.getKey());

                    // Spalte 'objectDescription'
                    row.put("objectDescription", actualFile.getDescription());

                    // Datensatz dem report hinzufuegen
                    report.addField(row);
                }

                // ueber alle variablen iterieren
                for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
                    HashMap<String, Object> row = new HashMap<String, Object>();

                    // Spalte 'destination'
                    if (actualCommit.isTorootPresent()) {
                        row.put("destination", "user/cb2");
                    } else {
                        row.put("destination", "prozessintern");
                    }

                    // Spalte 'objectType'
                    row.put("objectType", "variable");

                    // Spalte 'minOccur'
                    row.put("minOccur", "" + actualVariable.getMinoccur());

                    // Spalte 'maxOccur'
                    row.put("maxOccur", "" + actualVariable.getMaxoccur());

                    // Spalte 'objectKey'
                    row.put("objectKey", actualVariable.getKey());

                    // Spalte 'objectDescription'
                    row.put("objectDescription", actualVariable.getDescription());

                    // Datensatz dem report hinzufuegen
                    report.addField(row);
                }

            }
            try {
                report.fillReportFileToFile(jasperPathP52, jasperFilledPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pdf
            try {
                report.convertFileToPdf(jasperFilledPathP52, pdfPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pptx
            try {
                report.convertFileToPptx(jasperFilledPathP52, pptxPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            report = null;
        }
    }

    // warten bis alles auf platte geschrieben ist
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    // merge and output
    if (format.equals("pdf")) {
        mergePdf(pdfRankFiles, output);
    } else if (format.equals("pptx")) {
        mergePptx(pptxRankFiles, output);
    }

    System.out.println("info: generating process documentation ready.");
    System.exit(0);
}

From source file:DIA_Umpire_Quant.DIA_Umpire_Quant.java

/**
 * @param args the command line arguments
 *///from ww w .  j a  va 2s .  com
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire quantitation with targeted re-extraction analysis (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx10G DIA_Umpire_Quant.jar diaumpire_quant.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_quant.log");
    } catch (Exception e) {
    }

    try {

        Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
        Logger.getRootLogger().info("Parameter file:" + args[0]);

        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        String line = "";
        String WorkFolder = "";
        int NoCPUs = 2;

        String UserMod = "";
        String Combined_Prot = "";
        String InternalLibID = "";
        String ExternalLibPath = "";
        String ExternalLibDecoyTag = "DECOY";
        boolean DefaultProtFiltering = true;
        boolean DataSetLevelPepFDR = false;
        float ProbThreshold = 0.99f;
        float ExtProbThreshold = 0.99f;
        float Freq = 0f;
        int TopNPep = 6;
        int TopNFrag = 6;
        float MinFragMz = 200f;
        String FilterWeight = "GW";
        float MinWeight = 0.9f;
        float RTWindow_Int = -1f;
        float RTWindow_Ext = -1f;

        TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        HashMap<String, File> AssignFiles = new HashMap<>();
        boolean InternalLibSearch = false;
        boolean ExternalLibSearch = false;

        boolean ExportSaint = false;
        boolean SAINT_MS1 = false;
        boolean SAINT_MS2 = true;

        HashMap<String, String[]> BaitList = new HashMap<>();
        HashMap<String, String> BaitName = new HashMap<>();
        HashMap<String, String[]> ControlList = new HashMap<>();
        HashMap<String, String> ControlName = new HashMap<>();

        //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            Logger.getRootLogger().info(line);
            if (!"".equals(line) && !line.startsWith("#")) {
                //System.out.println(line);
                if (line.equals("==File list begin")) {
                    do {
                        line = reader.readLine();
                        line = line.trim();
                        if (line.equals("==File list end")) {
                            continue;
                        } else if (!"".equals(line)) {
                            File newfile = new File(line);
                            if (newfile.exists()) {
                                AssignFiles.put(newfile.getAbsolutePath(), newfile);
                            } else {
                                Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                            }
                        }
                    } while (!line.equals("==File list end"));
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                String value = line.split("=")[1].trim();
                switch (type) {
                case "TargetedExtraction": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibSearch": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "ExternalLibSearch": {
                    ExternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }

                case "Path": {
                    WorkFolder = value;
                    break;
                }
                case "path": {
                    WorkFolder = value;
                    break;
                }
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                case "Fasta": {
                    tandemPara.FastaPath = value;
                    break;
                }
                case "Combined_Prot": {
                    Combined_Prot = value;
                    break;
                }
                case "DefaultProtFiltering": {
                    DefaultProtFiltering = Boolean.parseBoolean(value);
                    break;
                }
                case "DecoyPrefix": {
                    if (!"".equals(value)) {
                        tandemPara.DecoyPrefix = value;
                    }
                    break;
                }
                case "UserMod": {
                    UserMod = value;
                    break;
                }
                case "ProteinFDR": {
                    tandemPara.ProtFDR = Float.parseFloat(value);
                    break;
                }
                case "PeptideFDR": {
                    tandemPara.PepFDR = Float.parseFloat(value);
                    break;
                }
                case "DataSetLevelPepFDR": {
                    DataSetLevelPepFDR = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibID": {
                    InternalLibID = value;
                    break;
                }
                case "ExternalLibPath": {
                    ExternalLibPath = value;
                    break;
                }
                case "ExtProbThreshold": {
                    ExtProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Int": {
                    RTWindow_Int = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Ext": {
                    RTWindow_Ext = Float.parseFloat(value);
                    break;
                }
                case "ExternalLibDecoyTag": {
                    ExternalLibDecoyTag = value;
                    if (ExternalLibDecoyTag.endsWith("_")) {
                        ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0,
                                ExternalLibDecoyTag.length() - 1);
                    }
                    break;
                }
                case "ProbThreshold": {
                    ProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "ReSearchProb": {
                    //ReSearchProb = Float.parseFloat(value);
                    break;
                }
                case "FilterWeight": {
                    FilterWeight = value;
                    break;
                }
                case "MinWeight": {
                    MinWeight = Float.parseFloat(value);
                    break;
                }
                case "TopNFrag": {
                    TopNFrag = Integer.parseInt(value);
                    break;
                }
                case "TopNPep": {
                    TopNPep = Integer.parseInt(value);
                    break;
                }
                case "Freq": {
                    Freq = Float.parseFloat(value);
                    break;
                }
                case "MinFragMz": {
                    MinFragMz = Float.parseFloat(value);
                    break;
                }

                //<editor-fold defaultstate="collapsed" desc="SaintOutput">
                case "ExportSaintInput": {
                    ExportSaint = Boolean.parseBoolean(value);
                    break;
                }
                case "QuantitationType": {
                    switch (value) {
                    case "MS1": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = false;
                        break;
                    }
                    case "MS2": {
                        SAINT_MS1 = false;
                        SAINT_MS2 = true;
                        break;
                    }
                    case "BOTH": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = true;
                        break;
                    }
                    }
                    break;
                }
                //                    case "BaitInputFile": {
                //                        SaintBaitFile = value;
                //                        break;
                //                    }
                //                    case "PreyInputFile": {
                //                        SaintPreyFile = value;
                //                        break;
                //                    }
                //                    case "InterationInputFile": {
                //                        SaintInteractionFile = value;
                //                        break;
                //                    }
                default: {
                    if (type.startsWith("BaitName_")) {
                        BaitName.put(type.substring(9), value);
                    }
                    if (type.startsWith("BaitFile_")) {
                        BaitList.put(type.substring(9), value.split("\t"));
                    }
                    if (type.startsWith("ControlName_")) {
                        ControlName.put(type.substring(12), value);
                    }
                    if (type.startsWith("ControlFile_")) {
                        ControlList.put(type.substring(12), value.split("\t"));
                    }
                    break;
                }
                //</editor-fold>                    
                }
            }
        }
        //</editor-fold>

        //Initialize PTM manager using compomics library
        PTMManager.GetInstance();
        if (!UserMod.equals("")) {
            PTMManager.GetInstance().ImportUserMod(UserMod);
        }

        //Check if the fasta file can be found
        if (!new File(tandemPara.FastaPath).exists()) {
            Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                    + " cannot be found, the process will be terminated, please check.");
            System.exit(1);
        }

        //Check if the prot.xml file can be found
        if (!new File(Combined_Prot).exists()) {
            Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                    + " cannot be found, the export protein summary table will be empty.");
        }

        LCMSID protID = null;

        //Parse prot.xml and generate protein master list given an FDR 
        if (Combined_Prot != null && !Combined_Prot.equals("")) {
            protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
            if (!"".equals(Combined_Prot) && protID == null) {
                protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
                ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
                //Use DIA-Umpire default protein FDR calculation
                if (DefaultProtFiltering) {
                    protID.RemoveLowLocalPWProtein(0.8f);
                    protID.RemoveLowMaxIniProbProtein(0.9f);
                    protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                } //Get protein FDR calculation without other filtering
                else {
                    protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                }
                protID.LoadSequence();
                protID.WriteLCMSIDSerialization(Combined_Prot);
            }
            Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
        }
        HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

        //Generate DIA file list
        ArrayList<DIAPack> FileList = new ArrayList<>();

        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                FileList.add(DiaFile);
                HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
            }
        }

        LCMSID combinePepID = null;
        if (DataSetLevelPepFDR) {
            combinePepID = LCMSID.ReadLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            if (combinePepID == null) {
                FDR_DataSetLevel fdr = new FDR_DataSetLevel();
                fdr.GeneratePepIonList(FileList, tandemPara, WorkFolder + "combinePepID.SerFS");
                combinePepID = fdr.combineID;
                combinePepID.WriteLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            }
        }

        //process each DIA file for quantification based on untargeted identifications
        for (DIAPack DiaFile : FileList) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info("Loading identification results " + DiaFile.Filename + "....");

            //If the LCMSID serialization is found
            if (!DiaFile.ReadSerializedLCMSID()) {
                DiaFile.ParsePepXML(tandemPara, combinePepID);
                DiaFile.BuildStructure();
                if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                    Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                    System.exit(1);
                }
                DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
                DiaFile.GenerateClusterScanNomapping();
                //Doing quantification
                DiaFile.AssignQuant();
                DiaFile.ClearStructure();
            }
            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(DiaFile.Filename + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }

        //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library">            
        Logger.getRootLogger().info(
                "=================================================================================================");
        if (InternalLibSearch && FileList.size() > 1) {
            Logger.getRootLogger().info("Module C: Targeted extraction using internal library");

            FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    InternalLibID);
            if (libManager == null) {
                Logger.getRootLogger().info("Building internal spectral library");
                libManager = new FragmentLibManager(InternalLibID);
                ArrayList<LCMSID> LCMSIDList = new ArrayList<>();
                for (DIAPack dia : FileList) {
                    LCMSIDList.add(dia.IDsummary);
                }
                libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag);
                libManager.WriteFragmentLibSerialization(WorkFolder);
            }
            libManager.ReduceMemoryUsage();

            Logger.getRootLogger()
                    .info("Building retention time prediction model and generate candidate peptide list");
            for (int i = 0; i < FileList.size(); i++) {
                FileList.get(i).IDsummary.ClearMappedPep();
            }
            for (int i = 0; i < FileList.size(); i++) {
                for (int j = i + 1; j < FileList.size(); j++) {
                    RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder,
                            FileList.get(i).GetParameter(), FileList.get(i).IDsummary,
                            FileList.get(j).IDsummary);
                    alignment.GenerateModel();
                    alignment.GenerateMappedPepIon();
                }
                FileList.get(i).ExportID();
                FileList.get(i).IDsummary = null;
            }

            Logger.getRootLogger().info("Targeted matching........");
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) {
                    diafile.UseMappedIon = true;
                    diafile.FilterMappedIonByProb = false;
                    diafile.BuildStructure();
                    diafile.MS1FeatureMap.ReadPeakCluster();
                    diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                    diafile.GenerateMassCalibrationRTMap();
                    diafile.TargetedExtractionQuant(false, libManager, 1.1f, RTWindow_Int);
                    diafile.MS1FeatureMap.ClearAllPeaks();
                    diafile.IDsummary.ReduceMemoryUsage();
                    diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold);
                    diafile.ExportID();
                    Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                            + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
                    diafile.ClearStructure();
                }
                diafile.IDsummary = null;
                System.gc();
            }
            Logger.getRootLogger().info(
                    "=================================================================================================");
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library">
        //External library search
        if (ExternalLibSearch) {
            Logger.getRootLogger().info("Module C: Targeted extraction using external library");

            //Read exteranl library
            FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    FilenameUtils.getBaseName(ExternalLibPath));
            if (ExlibManager == null) {
                ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath));

                //Import traML file
                ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag);
                //Check if there are decoy spectra
                ExlibManager.CheckDecoys();
                //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath);
                ExlibManager.WriteFragmentLibSerialization(WorkFolder);
            }
            Logger.getRootLogger()
                    .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size());
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                //Generate RT mapping
                RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager,
                        diafile.GetParameter());
                RTmap.GenerateModel();
                RTmap.GenerateMappedPepIon();

                diafile.BuildStructure();
                diafile.MS1FeatureMap.ReadPeakCluster();
                diafile.GenerateMassCalibrationRTMap();
                //Perform targeted re-extraction
                diafile.TargetedExtractionQuant(false, ExlibManager, ProbThreshold, RTWindow_Ext);
                diafile.MS1FeatureMap.ClearAllPeaks();
                diafile.IDsummary.ReduceMemoryUsage();
                //Remove target IDs below the defined probability threshold
                diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold);
                diafile.ExportID();
                diafile.ClearStructure();
                Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                        + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
            }
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">
        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (diafile.IDsummary == null) {
                diafile.ReadSerializedLCMSID();
                diafile.IDsummary.ClearAssignPeakCluster();
                //diafile.IDsummary.ClearPSMs();                    
            }
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.MinFragMZ = MinFragMz;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}