    public Object sendObjectRequestToSpecifiedServer(java.lang.String serverName, java.lang.String servletName, java.lang.Object request) {
        Object reqxml = null;
        org.jdom.Document retdoc = null;
        String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", "");
        String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080");
        if (myport == null || myport.trim().equals("")) {
            myport = "80";
        }
        if (this.serverURL == null) {
            try {
                java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase();
                if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost";
            } catch (Exception exp) {
                exp.printStackTrace();
                serverURL = "localhost";
            }
            newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport);
            ipdig.show();
            serverURL = myurl = ipdig.getIPAddress();
            myport = ipdig.getPortNo();
            java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL);
            java.util.prefs.Preferences.systemRoot().put("portno", myport);
            System.out.println(serverURL);
        }
        try {
            java.net.URL url = new java.net.URL("http://" + serverName + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection();
            urlconn.setDoOutput(true);
            java.io.OutputStream os = urlconn.getOutputStream();
            java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32());
            java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos);
            java.io.ObjectOutputStream dos = new java.io.ObjectOutputStream(gop);
            dos.writeObject(request);
            dos.flush();
            dos.close();
            java.io.InputStream ios = urlconn.getInputStream();
            java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32());
            java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis);
            java.io.ObjectInputStream br = new java.io.ObjectInputStream(gip);
            reqxml = br.readObject();
        } catch (Exception exp) {
            exp.printStackTrace(System.out);
            System.out.println("Exception in Servlet Connector: " + exp);
        }
        return reqxml;
    }


public Object sendRequestObjectResponse(java.lang.String servletName, java.lang.String request) {
        String osRoot = OSRoot.getRoot();
        String fname = "";
        Object retobj = null;
        String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", "");
        String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080");
        if (myport == null || myport.trim().equals("")) {
            myport = "80";
        }
        if (this.serverURL == null) {
            try {
                java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase();
                if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost";
            } catch (Exception exp) {
                exp.printStackTrace();
                serverURL = "localhost";
            }
            newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport);
            ipdig.show();
            serverURL = myurl = ipdig.getIPAddress();
            myport = ipdig.getPortNo();
            java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL);
            java.util.prefs.Preferences.systemRoot().put("portno", myport);
            System.out.println(serverURL);
        }
        try {
            System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection();
            urlconn.setDoOutput(true);
            urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
            java.io.OutputStream os = urlconn.getOutputStream();
            String req1xml = request;
            java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32());
            java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos);
            java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8");
            System.out.println(req1xml);
            try {
                java.io.FileOutputStream pw = new java.io.FileOutputStream("log.txt");
                pw.write(req1xml.getBytes());
                pw.flush();
                pw.close();
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            dos.write(req1xml);
            dos.flush();
            dos.close();
            System.out.println("url conn: " + urlconn.getContentEncoding() + "  " + urlconn.getContentType());
            java.io.InputStream ios = urlconn.getInputStream();
            java.io.File f1 = new java.io.File(osRoot + "/localattachments/Reports");
            if (!f1.exists()) f1.mkdirs();
            java.io.File file = null;
            if (urlconn.getContentType() != null && urlconn.getContentType().trim().equals("application/vnd.oasis.opendocument.text")) {
                file = new java.io.File(osRoot + "/localattachments/Reports/" + System.currentTimeMillis() + ".odt");
            } else if (urlconn.getContentType() != null && urlconn.getContentType().trim().equals("text/html")) {
                file = new java.io.File(osRoot + "/localattachments/Reports/" + System.currentTimeMillis() + ".html");
            } else {
                file = new java.io.File(osRoot + "/localattachments/Reports/" + System.currentTimeMillis() + ".xls");
            }
            file = new java.io.File(file.getAbsolutePath());
            java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
            int c;
            while ((c = ios.read()) != -1) fos.write(c);
            fos.close();
            ios.close();
            fname = file.getAbsolutePath();
            System.out.println(fname);
            newgen.presentation.component.Utility.getInstance().showBrowser("file://" + fname);
        } catch (Exception exp) {
            exp.printStackTrace(System.out);
            javax.swing.JOptionPane.showMessageDialog(null, "Could not establish connection with the server,
Please verify server name/IP adress,
Also check if NewGenLib server is running", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE);
        }
        return fname;
    }


public String sendRequestHTTPTunelling(java.lang.String servletName, java.lang.String request) {
        String reqxml = "";
        org.jdom.Document retdoc = null;
        String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", "");
        String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080");
        if (myport == null || myport.trim().equals("")) {
            myport = "80";
        }
        if (this.serverURL == null) {
            try {
                java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase();
                if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost";
            } catch (Exception exp) {
                exp.printStackTrace();
                serverURL = "localhost";
            }
            newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport);
            ipdig.show();
            serverURL = myurl = ipdig.getIPAddress();
            myport = ipdig.getPortNo();
            java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL);
            java.util.prefs.Preferences.systemRoot().put("portno", myport);
            System.out.println(serverURL);
        }
        try {
            System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection();
            urlconn.setDoOutput(true);
            urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
            java.io.OutputStream os = urlconn.getOutputStream();
            String req1xml = request;
            java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32());
            java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos);
            java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8");
            System.out.println(req1xml);
            try {
                java.io.FileOutputStream pw = new java.io.FileOutputStream("log.txt");
                pw.write(req1xml.getBytes());
                pw.flush();
                pw.close();
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            dos.write(req1xml);
            dos.flush();
            dos.close();
            System.out.println("url conn: " + urlconn.getContentEncoding() + "  " + urlconn.getContentType());
            java.io.InputStream ios = urlconn.getInputStream();
            java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32());
            java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis);
            java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8");
            retdoc = (new org.jdom.input.SAXBuilder()).build(br);
            try {
                java.io.FileOutputStream pw = new java.io.FileOutputStream("log3.txt");
                pw.write(reqxml.getBytes());
                pw.flush();
                pw.close();
            } catch (Exception exp) {
                exp.printStackTrace();
            }
        } catch (Exception exp) {
            exp.printStackTrace(System.out);
            javax.swing.JOptionPane.showMessageDialog(null, "Could not establish connection with the server,
Please verify server name/IP adress,
Also check if NewGenLib server is running", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE);
        }
        System.out.println(reqxml);
        return (new org.jdom.output.XMLOutputter()).outputString(retdoc);
    }


public String sendRequestAndGetNormalStringOutPut(java.lang.String servletName, java.lang.String request) {
        String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", "");
        String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080");
        if (myport == null || myport.trim().equals("")) {
            myport = "80";
        }
        if (this.serverURL == null) {
            try {
                java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase();
                if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost";
            } catch (Exception exp) {
                exp.printStackTrace();
                serverURL = "localhost";
            }
            newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport);
            ipdig.show();
            serverURL = myurl = ipdig.getIPAddress();
            myport = ipdig.getPortNo();
            java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL);
            java.util.prefs.Preferences.systemRoot().put("portno", myport);
            System.out.println(serverURL);
        }
        String response = "";
        try {
            System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName);
            java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection();
            urlconn.setDoOutput(true);
            urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
            java.io.OutputStream os = urlconn.getOutputStream();
            String req1xml = request;
            java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32());
            java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos);
            java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8");
            System.out.println(req1xml);
            dos.write(req1xml);
            dos.flush();
            dos.close();
            System.out.println("url conn: " + urlconn.getContentEncoding() + "  " + urlconn.getContentType());
            java.io.InputStream ios = urlconn.getInputStream();
            java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32());
            java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis);
            java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8");
            int n = -1;
            while ((n = br.read()) != -1) response += (char) n;
        } catch (java.net.ConnectException conexp) {
            javax.swing.JOptionPane.showMessageDialog(null, "Could not establish connection with the NewGenLib server, " + "
These might be the possible reasons." + "

Check the network connectivity between this machine and the server." + "

Check whether NewGenLib server is running on the server machine." + "

NewGenLib server might not have initialized properly. In this case" + "
go to server machine, open NewGenLibDesktop Application," + "
 utility ->Send log to NewGenLib Customer Support", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE);
        } catch (Exception exp) {
            exp.printStackTrace(System.out);
            TroubleShootConnectivity troubleShoot = new TroubleShootConnectivity();
        }
        return response;
    }


    private void loadConfig(ServletContext ctx, String configFileName) {
        Digester digester = new Digester();
        digester.push(this);
        digester.addFactoryCreate("pagespy/server", new AbstractObjectCreationFactory() {

            public Object createObject(Attributes attrs) {
                String className = attrs.getValue("className");
                try {
                    return Class.forName(className).newInstance();
                } catch (Exception e) {
                    throw new ClassCastException("Error al instanciar " + className);
                }
            }
        });
        digester.addSetProperty("pagespy/server/param", "name", "value");
        digester.addSetNext("pagespy/server", "setServer", PageSpyServer.class.getName());
        digester.addCallMethod("pagespy/ignored-patterns", "setIgnorePattern", 1);
        digester.addCallParam("pagespy/ignored-patterns", 0);
        digester.addFactoryCreate("pagespy/property-setters/setter", new AbstractObjectCreationFactory() {

            public Object createObject(Attributes attrs) {
                String className = attrs.getValue("className");
                try {
                    return Class.forName(className).newInstance();
                } catch (Exception e) {
                    throw new ClassCastException("Error al instanciar " + className);
                }
            }
        });
        digester.addSetNext("pagespy/property-setters/setter", "addPropertySetter", PagePropertySetter.class.getName());
        digester.addFactoryCreate("pagespy/page-replacers/replacer", new AbstractObjectCreationFactory() {

            public Object createObject(Attributes attrs) {
                String className = attrs.getValue("className");
                try {
                    return Class.forName(className).newInstance();
                } catch (Exception e) {
                    throw new ClassCastException("Error al instanciar " + className);
                }
            }
        });
        digester.addSetNext("pagespy/page-replacers/replacer", "addPageReplacer", PageReplacer.class.getName());
        digester.addFactoryCreate("pagespy/properties-panel", new AbstractObjectCreationFactory() {

            public Object createObject(Attributes attrs) {
                String className = attrs.getValue("className");
                try {
                    return Class.forName(className).newInstance();
                } catch (Exception e) {
                    throw new ClassCastException("Error al instanciar " + className);
                }
            }
        });
        digester.addSetNext("pagespy/properties-panel", "setPropertiesPanel", PagePanel.class.getName());
        try {
            this.getLogger().info("Initializing " + configFileName);
            URL url = ctx.getResource(configFileName);
            if (url == null) {
                url = this.getClass().getResource(configFileName);
            }
            digester.parse(url.openStream());
        } catch (Exception e) {
            this.getLogger().error("Error parsing configuration file.", e);
            throw new RuntimeException(e);
        }
    }


    public static final String encryptMD5(String decrypted) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(decrypted.getBytes());
            byte hash[] = md5.digest();
            md5.reset();
            return hashToHex(hash);
        } catch (NoSuchAlgorithmException _ex) {
            return null;
        }
    }


    public static void copyFile(File source, File dest) {
        try {
            FileChannel in = new FileInputStream(source).getChannel();
            if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs();
            FileChannel out = new FileOutputStream(dest).getChannel();
            in.transferTo(0, in.size(), out);
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void fileUpload() throws Exception {
        NULogger.getLogger().info("now file upload code");
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://dl-web.dropbox.com/upload");
        httppost.setHeader("Referer", "https://www.dropbox.com/home/Public");
        httppost.setHeader("Cookie", DropBoxAccount.getForumjarcookie() + ";" + DropBoxAccount.getForumlidcookie() + ";" + DropBoxAccount.getTouchcookie());
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("t", new StringBody(token));
        mpEntity.addPart("plain", new StringBody("yes"));
        mpEntity.addPart("dest", new StringBody("/Public"));
        mpEntity.addPart("file", new MonitoredFileBody(file, uploadProgress));
        httppost.setEntity(mpEntity);
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into dropbox.com");
        status = UploadStatus.UPLOADING;
        HttpResponse response = httpclient.execute(httppost);
        status = UploadStatus.GETTINGLINK;
        HttpEntity resEntity = response.getEntity();
        NULogger.getLogger().info(response.getStatusLine().toString());
        if (resEntity != null) {
            uploadresponse = EntityUtils.toString(resEntity);
        }
        NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse);
        if (uploadresponse.contains("The resource was found at https://www.dropbox.com/home/Public")) {
            downloadlink = "http://dl.dropbox.com/u/" + uid + "/" + (URLEncoder.encode(file.getName(), "UTF-8").replace("+", "%20"));
            NULogger.getLogger().log(Level.INFO, "Downloadlink : {0}", downloadlink);
            downURL = downloadlink;
        } else {
            throw new Exception("Dropbox server problem or network problem.. Couldn't get proper response.");
        }
    }


        public void actionPerformed(ActionEvent ev) {
            if (fileChooser == null) {
                fileChooser = new JFileChooser();
                ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)");
                fileFilter.addExtension("jar");
                fileFilter.addExtension("zip");
                fileChooser.setFileFilter(fileFilter);
            }
            if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) {
                String manifestDeviceName = null;
                URL[] urls = new URL[1];
                ArrayList descriptorEntries = new ArrayList();
                JarFile jar = null;
                try {
                    jar = new JarFile(fileChooser.getSelectedFile());
                    Manifest manifest = jar.getManifest();
                    if (manifest != null) {
                        Attributes attrs = manifest.getMainAttributes();
                        manifestDeviceName = attrs.getValue("Device-Name");
                    }
                    for (Enumeration en = jar.entries(); en.hasMoreElements(); ) {
                        String entry = ((JarEntry) en.nextElement()).getName();
                        if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) {
                            descriptorEntries.add(entry);
                        }
                    }
                    urls[0] = fileChooser.getSelectedFile().toURL();
                } catch (IOException e) {
                    Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e);
                    return;
                } finally {
                    if (jar != null) {
                        try {
                            jar.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
                if (descriptorEntries.size() == 0) {
                    Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName());
                    return;
                }
                if (descriptorEntries.size() > 1) {
                    manifestDeviceName = null;
                }
                ClassLoader classLoader = Common.createExtensionsClassLoader(urls);
                HashMap devices = new HashMap();
                for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) {
                    String entryName = (String) it.next();
                    try {
                        devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class));
                    } catch (IOException e) {
                        Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e);
                        return;
                    }
                }
                for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) {
                    DeviceEntry entry = (DeviceEntry) en.nextElement();
                    if (devices.containsKey(entry.getDescriptorLocation())) {
                        devices.remove(entry.getDescriptorLocation());
                    }
                }
                if (devices.size() == 0) {
                    Message.info("Device profile already added");
                    return;
                }
                try {
                    File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName());
                    if (deviceFile.exists()) {
                        deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath());
                    }
                    IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile);
                    DeviceEntry entry = null;
                    for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) {
                        String descriptorLocation = (String) it.next();
                        Device device = (Device) devices.get(descriptorLocation);
                        if (manifestDeviceName != null) {
                            entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false);
                        } else {
                            entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false);
                        }
                        lsDevicesModel.addElement(entry);
                        Config.addDeviceEntry(entry);
                    }
                    lsDevices.setSelectedValue(entry, true);
                } catch (IOException e) {
                    Message.error("Error adding device profile, " + Message.getCauseMessage(e), e);
                    return;
                }
            }
        }


    public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException {
        MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null);
        File dotInput = null, dotOutput = outputLocation.toFile();
        ByteArrayOutputStream dotContents = new ByteArrayOutputStream();
        try {
            dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION);
            FileOutputStream tmpDotOutputStream = null;
            try {
                IOUtils.copy(input, dotContents);
                tmpDotOutputStream = new FileOutputStream(dotInput);
                IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream);
            } finally {
                IOUtils.closeQuietly(tmpDotOutputStream);
            }
            IStatus result = runDot(format, dimension, dotInput, dotOutput);
            if (dotOutput.isFile()) {
                if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status);
                return;
            }
        } catch (IOException e) {
            status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e));
        } finally {
            dotInput.delete();
            IOUtils.closeQuietly(input);
        }
        throw new CoreException(status);
    }


    public static Image load(final InputStream input, String format, Point dimension) throws CoreException {
        MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null);
        File dotInput = null, dotOutput = null;
        ByteArrayOutputStream dotContents = new ByteArrayOutputStream();
        try {
            dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION);
            dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format);
            dotOutput.delete();
            FileOutputStream tmpDotOutputStream = null;
            try {
                IOUtils.copy(input, dotContents);
                tmpDotOutputStream = new FileOutputStream(dotInput);
                IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream);
            } finally {
                IOUtils.closeQuietly(tmpDotOutputStream);
            }
            IStatus result = runDot(format, dimension, dotInput, dotOutput);
            status.add(result);
            status.add(logInput(dotContents));
            if (dotOutput.isFile()) {
                if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status);
                ImageLoader loader = new ImageLoader();
                ImageData[] imageData = loader.load(dotOutput.getAbsolutePath());
                return new Image(Display.getDefault(), imageData[0]);
            }
        } catch (SWTException e) {
            status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e));
        } catch (IOException e) {
            status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e));
        } finally {
            dotInput.delete();
            dotOutput.delete();
            IOUtils.closeQuietly(input);
        }
        throw new CoreException(status);
    }


    public void testAutoCommit() throws Exception {
        Connection con = getConnectionOverrideProperties(new Properties());
        try {
            Statement stmt = con.createStatement();
            assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)"));
            con.setAutoCommit(false);
            assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)"));
            con.setAutoCommit(false);
            con.rollback();
            assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)"));
            con.setAutoCommit(true);
            con.setAutoCommit(false);
            con.rollback();
            con.setAutoCommit(true);
            ResultSet rs = stmt.executeQuery("select i from #testAutoCommit");
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertFalse(rs.next());
            rs.close();
            stmt.close();
        } finally {
            con.close();
        }
    }


    private void unpackBundle() throws IOException {
        File useJarPath = null;
        if (DownloadManager.isWindowsVista()) {
            useJarPath = lowJarPath;
            File jarDir = useJarPath.getParentFile();
            if (jarDir != null) {
                jarDir.mkdirs();
            }
        } else {
            useJarPath = jarPath;
        }
        DownloadManager.log("Unpacking " + this + " to " + useJarPath);
        InputStream rawStream = new FileInputStream(localPath);
        JarInputStream in = new JarInputStream(rawStream) {

            public void close() throws IOException {
            }
        };
        try {
            File jarTmp = null;
            JarEntry entry;
            while ((entry = in.getNextJarEntry()) != null) {
                String entryName = entry.getName();
                if (entryName.equals("classes.pack")) {
                    File packTmp = new File(useJarPath + ".pack");
                    packTmp.getParentFile().mkdirs();
                    DownloadManager.log("Writing temporary .pack file " + packTmp);
                    OutputStream tmpOut = new FileOutputStream(packTmp);
                    try {
                        DownloadManager.send(in, tmpOut);
                    } finally {
                        tmpOut.close();
                    }
                    jarTmp = new File(useJarPath + ".tmp");
                    DownloadManager.log("Writing temporary .jar file " + jarTmp);
                    unpack(packTmp, jarTmp);
                    packTmp.delete();
                } else if (!entryName.startsWith("META-INF")) {
                    File dest;
                    if (DownloadManager.isWindowsVista()) {
                        dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar));
                    } else {
                        dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar));
                    }
                    if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath;
                    File destTmp = new File(dest + ".tmp");
                    boolean exists = dest.exists();
                    if (!exists) {
                        DownloadManager.log(dest + ".mkdirs()");
                        dest.getParentFile().mkdirs();
                    }
                    try {
                        DownloadManager.log("Using temporary file " + destTmp);
                        FileOutputStream out = new FileOutputStream(destTmp);
                        try {
                            byte[] buffer = new byte[2048];
                            int c;
                            while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c);
                        } finally {
                            out.close();
                        }
                        if (exists) dest.delete();
                        DownloadManager.log("Renaming from " + destTmp + " to " + dest);
                        if (!destTmp.renameTo(dest)) {
                            throw new IOException("unable to rename " + destTmp + " to " + dest);
                        }
                    } catch (IOException e) {
                        if (!exists) throw e;
                    }
                }
            }
            if (jarTmp != null) {
                if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) {
                    throw new IOException("unable to rename " + jarTmp + " to " + useJarPath);
                }
            }
            if (DownloadManager.isWindowsVista()) {
                DownloadManager.log("Using broker to move " + name);
                if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) {
                    throw new IOException("unable to create " + name);
                }
                DownloadManager.log("Broker finished " + name);
            }
            DownloadManager.log("Finished unpacking " + this);
        } finally {
            rawStream.close();
        }
        if (deleteOnInstall) {
            localPath.delete();
        }
    }


    public static void main(String[] args) {
        for (int i = 0; i < args.length - 2; i++) {
            if (!CommonArguments.parseArguments(args, i, u)) {
                u.usage();
                System.exit(1);
            }
            if (CommonParameters.startArg > (i + 1)) i = CommonParameters.startArg - 1;
        }
        if (args.length < CommonParameters.startArg + 2) {
            u.usage();
            System.exit(1);
        }
        try {
            int readsize = 1024;
            ContentName argName = ContentName.fromURI(args[CommonParameters.startArg]);
            CCNHandle handle = CCNHandle.open();
            File theFile = new File(args[CommonParameters.startArg + 1]);
            if (theFile.exists()) {
                System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]);
            }
            FileOutputStream output = new FileOutputStream(theFile);
            long starttime = System.currentTimeMillis();
            CCNInputStream input;
            if (CommonParameters.unversioned) input = new CCNInputStream(argName, handle); else input = new CCNFileInputStream(argName, handle);
            if (CommonParameters.timeout != null) {
                input.setTimeout(CommonParameters.timeout);
            }
            byte[] buffer = new byte[readsize];
            int readcount = 0;
            long readtotal = 0;
            while ((readcount = input.read(buffer)) != -1) {
                readtotal += readcount;
                output.write(buffer, 0, readcount);
                output.flush();
            }
            if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms");
            System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes.");
            System.exit(0);
        } catch (ConfigurationException e) {
            System.out.println("Configuration exception in ccngetfile: " + e.getMessage());
            e.printStackTrace();
        } catch (MalformedContentNameStringException e) {
            System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Cannot write file or read content. " + e.getMessage());
            e.printStackTrace();
        }
        System.exit(1);
    }


    private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha1hash = md.digest();
        return LoginHttpPostProcessor.ConvertToHex(sha1hash);
    }


    public void executeUpdateTransaction(List queries) throws SQLException {
        assert connection != null;
        boolean autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        try {
            Iterator iterator = queries.iterator();
            while (iterator.hasNext()) {
                String query = (String) iterator.next();
                Statement statement = connection.createStatement();
                statement.executeUpdate(query);
            }
            connection.commit();
            connection.setAutoCommit(autoCommit);
        } catch (SQLException e) {
            connection.rollback();
            throw new SQLException(e.getMessage());
        }
    }


    protected String readFileUsingFileUrl(String fileUrlName) {
        String response = "";
        try {
            URL url = new URL(fileUrlName);
            URLConnection connection = url.openConnection();
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader in = new BufferedReader(isr);
            String inputLine = "";
            while ((inputLine = in.readLine()) != null) {
                response += inputLine + "\n";
            }
            if (response.endsWith("\n")) {
                response = response.substring(0, response.length() - 1);
            }
            in.close();
        } catch (Exception x) {
            x.printStackTrace();
        }
        return response;
    }


    protected String readFileUsingHttp(String fileUrlName) {
        String response = "";
        try {
            URL url = new URL(fileUrlName);
            URLConnection connection = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) connection;
            httpConn.setRequestProperty("Content-Type", "text/html");
            httpConn.setRequestProperty("Content-Length", "0");
            httpConn.setRequestMethod("GET");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setAllowUserInteraction(false);
            InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
            BufferedReader in = new BufferedReader(isr);
            String inputLine = "";
            while ((inputLine = in.readLine()) != null) {
                response += inputLine + "\n";
            }
            if (response.endsWith("\n")) {
                response = response.substring(0, response.length() - 1);
            }
            in.close();
        } catch (Exception x) {
            x.printStackTrace();
        }
        return response;
    }


    public static List<ServerInfo> getStartedServers() {
        List<ServerInfo> infos = new ArrayList<ServerInfo>();
        try {
            StringBuilder request = new StringBuilder();
            request.append(url).append("/").append(displayServlet);
            request.append("?ingame=1");
            URL objUrl = new URL(request.toString());
            URLConnection urlConnect = objUrl.openConnection();
            InputStream in = urlConnect.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            while (reader.ready()) {
                String name = reader.readLine();
                String ip = reader.readLine();
                int port = Integer.valueOf(reader.readLine());
                ServerInfo server = new ServerInfo(name, ip, port);
                server.nbPlayers = Integer.valueOf(reader.readLine());
                infos.add(server);
            }
            in.close();
            return infos;
        } catch (Exception e) {
            return infos;
        }
    }


    private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) {
        final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer();
        viewer.createControl(parent);
        _root = new EditRootEditPart();
        viewer.setRootEditPart(_root);
        getEditDomain().addViewer(viewer);
        getSite().setSelectionProvider(viewer);
        viewer.setEditPartFactory(getEditPartFactory());
        final KeyHandler keyHandler = new GraphicalViewerKeyHandler(viewer) {

            @SuppressWarnings("unchecked")
            @Override
            public boolean keyPressed(final KeyEvent event) {
                if (event.stateMask == SWT.MOD1 && event.keyCode == SWT.DEL) {
                    final List<? extends EditorPart> objects = viewer.getSelectedEditParts();
                    if (objects == null || objects.isEmpty()) return true;
                    final GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE);
                    final CompoundCommand compoundCmd = new CompoundCommand("Delete");
                    for (int i = 0; i < objects.size(); i++) {
                        final EditPart object = (EditPart) objects.get(i);
                        deleteReq.setEditParts(object);
                        final Command cmd = object.getCommand(deleteReq);
                        if (cmd != null) compoundCmd.add(cmd);
                    }
                    getCommandStack().execute(compoundCmd);
                    return true;
                }
                if (event.stateMask == SWT.MOD3 && (event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.ARROW_LEFT || event.keyCode == SWT.ARROW_RIGHT || event.keyCode == SWT.ARROW_UP)) {
                    final List<? extends EditorPart> objects = viewer.getSelectedEditParts();
                    if (objects == null || objects.isEmpty()) return true;
                    final GroupRequest moveReq = new ChangeBoundsRequest(RequestConstants.REQ_MOVE);
                    final CompoundCommand compoundCmd = new CompoundCommand("Move");
                    for (int i = 0; i < objects.size(); i++) {
                        final EditPart object = (EditPart) objects.get(i);
                        moveReq.setEditParts(object);
                        final LocationCommand cmd = (LocationCommand) object.getCommand(moveReq);
                        if (cmd != null) {
                            cmd.setLocation(new Point(event.keyCode == SWT.ARROW_LEFT ? -1 : event.keyCode == SWT.ARROW_RIGHT ? 1 : 0, event.keyCode == SWT.ARROW_DOWN ? 1 : event.keyCode == SWT.ARROW_UP ? -1 : 0));
                            cmd.setRelative(true);
                            compoundCmd.add(cmd);
                        }
                    }
                    getCommandStack().execute(compoundCmd);
                    return true;
                }
                return super.keyPressed(event);
            }
        };
        keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), getActionRegistry().getAction(GEFActionConstants.DIRECT_EDIT));
        viewer.setKeyHandler(keyHandler);
        viewer.setContents(getEditorInput().getAdapter(NamedUuidEntity.class));
        viewer.addDropTargetListener(createTransferDropTargetListener(viewer));
        return viewer;
    }


    public int[] bubbleSort(int[] data) {
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data.length - i - 1; j++) {
                if (data[j] > data[j + 1]) {
                    int temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }
        return data;
    }


    private void findFile() throws SchedulerException {
        java.io.InputStream f = null;
        String furl = null;
        File file = new File(getFileName());
        if (!file.exists()) {
            URL url = classLoadHelper.getResource(getFileName());
            if (url != null) {
                try {
                    furl = URLDecoder.decode(url.getPath(), "UTF-8");
                    file = new File(furl);
                    f = url.openStream();
                } catch (java.io.UnsupportedEncodingException uee) {
                } catch (IOException ignor) {
                }
            }
        } else {
            try {
                f = new java.io.FileInputStream(file);
            } catch (FileNotFoundException e) {
            }
        }
        if (f == null && isFailOnFileNotFound()) {
            throw new SchedulerException("File named '" + getFileName() + "' does not exist. f == null && isFailOnFileNotFound()");
        } else if (f == null) {
            getLog().warn("File named '" + getFileName() + "' does not exist. f == null");
        } else {
            fileFound = true;
            try {
                if (furl != null) this.filePath = furl; else this.filePath = file.getAbsolutePath();
                f.close();
            } catch (IOException ioe) {
                getLog().warn("Error closing jobs file " + getFileName(), ioe);
            }
        }
    }


    @Override
    public String getPath() {
        InputStream in = null;
        OutputStream out = null;
        File file = null;
        try {
            file = File.createTempFile("java-storage_" + RandomStringUtils.randomAlphanumeric(32), ".tmp");
            file.deleteOnExit();
            out = new FileOutputStream(file);
            in = openStream();
            IOUtils.copy(in, out);
        } catch (IOException e) {
            throw new RuntimeException();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        if (file != null && file.exists()) {
            return file.getPath();
        }
        return null;
    }


    public static void copy(File file, File dir, boolean overwrite) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        File out = new File(dir, file.getName());
        if (out.exists() && !overwrite) {
            throw new IOException("File: " + out + " already exists.");
        }
        FileOutputStream fos = new FileOutputStream(out, false);
        byte[] block = new byte[4096];
        int read = bis.read(block);
        while (read != -1) {
            fos.write(block, 0, read);
            read = bis.read(block);
        }
    }


    public void createBankSignature() {
        byte b;
        try {
            _bankMessageDigest = MessageDigest.getInstance("MD5");
            _bankSig = Signature.getInstance("MD5/RSA/PKCS#1");
            _bankSig.initSign((PrivateKey) _bankPrivateKey);
            _bankMessageDigest.update(getBankString().getBytes());
            _bankMessageDigestBytes = _bankMessageDigest.digest();
            _bankSig.update(_bankMessageDigestBytes);
            _bankSignatureBytes = _bankSig.sign();
        } catch (Exception e) {
        }
        ;
    }


    public void createVendorSignature() {
        byte b;
        try {
            _vendorMessageDigest = MessageDigest.getInstance("MD5");
            _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1");
            _vendorSig.initSign((PrivateKey) _vendorPrivateKey);
            _vendorMessageDigest.update(getBankString().getBytes());
            _vendorMessageDigestBytes = _vendorMessageDigest.digest();
            _vendorSig.update(_vendorMessageDigestBytes);
            _vendorSignatureBytes = _vendorSig.sign();
        } catch (Exception e) {
        }
        ;
    }


    private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) {
        if ((organizationName == null) || (organizationName.equals(""))) {
            message = "invalid new_organization_name.";
            return false;
        }
        String tmpxml = TextUtil.xmlEscape(organizationName);
        String tmpdb = DBAccess.SQLEscape(organizationName);
        if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) {
            message = "invalid new_organization_name.";
            return false;
        }
        if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) {
            message = "invalid new_organization_name.";
            return false;
        }
        String[] orgnames = ServerConsoleServlet.getOrganizationNames();
        for (int i = 0; i < orgnames.length; i++) {
            if (orgnames.equals(organizationName)) {
                message = "already exists.";
                return false;
            }
        }
        message = "create new organization: " + organizationName;
        File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName);
        if (!newOrganizationDirectory.mkdir()) {
            message = "cannot create directory.";
            return false;
        }
        File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName"));
        cacheDir.mkdir();
        File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName"));
        confDir.mkdir();
        File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName"));
        rdfDir.mkdir();
        File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName"));
        resourceDir.mkdir();
        File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete");
        obsoleteDir.mkdir();
        File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName"));
        schemaDir.mkdir();
        String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate"));
        File templ = new File(organization_temp_dir);
        File[] confFiles = templ.listFiles();
        for (int i = 0; i < confFiles.length; i++) {
            try {
                FileReader fr = new FileReader(confFiles[i]);
                FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName());
                int c = -1;
                while ((c = fr.read()) != -1) fw.write(c);
                fw.flush();
                fw.close();
                fr.close();
            } catch (IOException e) {
            }
        }
        SchemaModelHolder.reloadSchemaModel(organizationName);
        ResourceModelHolder.reloadResourceModel(organizationName);
        UserLogServlet.initializeUserLogDB(organizationName);
        MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username);
        ResourceModelHolder.reloadResourceModel(organizationName);
        message = organizationName + " is created. Restart Tomcat to activate this organization.";
        return true;
    }


    public static URL getComponentXmlFileWith(String name) throws Exception {
        List<URL> all = getComponentXmlFiles();
        for (URL url : all) {
            InputStream stream = null;
            try {
                stream = url.openStream();
                Element root = XML.getRootElement(stream);
                for (Element elem : (List<Element>) root.elements()) {
                    String ns = elem.getNamespace().getURI();
                    if (name.equals(elem.attributeValue("name"))) {
                        return url;
                    }
                }
            } finally {
                Resources.closeStream(stream);
            }
        }
        return null;
    }


protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        String requestURI = req.getRequestURI();
        String resource = requestURI.substring(requestURI.indexOf(servletPath) + servletPath.length());
        URL url = ClassResource.get(resourceDirectory + resource);
        try {
            File file = null;
            JarEntry jarEntry = null;
            JarFile jarFile = null;
            if (!url.toExternalForm().startsWith("jar:")) {
                file = new File(url.toURI());
            } else {
                jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
                String[] jarURL = url.toExternalForm().split("!");
                jarEntry = jarFile.getJarEntry(jarURL[1].substring(1));
            }
            if (file != null && file.isDirectory()) {
                PrintWriter writer = resp.getWriter();
                resp.setContentType("text/html");
                DevelUtils.writePageBegin(writer);
                DevelUtils.writeTitleAndHeaderEnd(writer, "Makumba resources");
                if (SourceViewServlet.redirected(req, resp, servletPath)) {
                    return;
                }
                String relativeDirectory = file.getName();
                if (file.getAbsolutePath().indexOf(resourceDirectory) != -1) {
                    relativeDirectory = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(resourceDirectory));
                }
                SourceViewServlet.printDirlistingHeader(writer, file.getCanonicalPath(), relativeDirectory);
                if (!(relativeDirectory.equals(resourceDirectory))) {
                    writer.println("../ (up one level)");
                }
                SourceViewServlet.processDirectory(writer, file, null);
                String[] list = file.list();
                Arrays.sort(list);
                for (int i = 0; i < list.length; i++) {
                    String s = list[i];
                    File f = new File(file.getAbsolutePath() + File.separator + s);
                    if (f.isFile()) {
                        writer.println("" + s + "");
                    }
                }
                writer.println("
");
                DevelUtils.writePageEnd(writer);
                resp.setHeader("Last-Modified", dfLastModified.format(new Date()));
                return;
            } else if (jarEntry != null && jarEntry.isDirectory()) {
                Enumeration<JarEntry> entries = jarFile.entries();
                ArrayList<String> files = new ArrayList<String>();
                ArrayList<String> directories = new ArrayList<String>();
                PrintWriter writer = resp.getWriter();
                resp.setContentType("text/html");
                DevelUtils.writePageBegin(writer);
                DevelUtils.writeTitleAndHeaderEnd(writer, "Makumba resources");
                if (SourceViewServlet.redirected(req, resp, servletPath)) {
                    return;
                }
                String relativeDirectory = jarEntry.getName();
                SourceViewServlet.printDirlistingHeader(writer, url.toExternalForm(), relativeDirectory);
                if (!relativeDirectory.equals(resourceDirectory) && !relativeDirectory.equals(resourceDirectory + "/")) {
                    writer.println("../ (up one level)");
                }
                while (entries.hasMoreElements()) {
                    JarEntry entry = (JarEntry) entries.nextElement();
                    if (entry.getName().startsWith(relativeDirectory)) {
                        String s = entry.getName().substring(relativeDirectory.length());
                        while (s.length() > 0 && s.startsWith("/")) {
                            s = s.substring(1);
                        }
                        if (s.indexOf("/") == -1) {
                            if (s.length() > 0) {
                                files.add(s);
                            }
                        } else if (s.indexOf("/") == s.lastIndexOf("/") && s.endsWith("/")) {
                            if (s.endsWith("/")) {
                                s = s.substring(0, s.length() - 1);
                            }
                            if (s.length() > 0) {
                                directories.add(s);
                            }
                        }
                    }
                }
                for (String string : directories) {
                    writer.println("" + string + "/");
                }
                for (String string : files) {
                    writer.println("" + string + "");
                }
                writer.println("
");
                DevelUtils.writePageEnd(writer);
                resp.setHeader("Last-Modified", dfLastModified.format(new Date()));
                return;
            } else {
                final Date lastModified;
                if (url.toExternalForm().startsWith("jar:")) {
                    JarFile jf = ((JarURLConnection) url.openConnection()).getJarFile();
                    String[] jarURL = url.toExternalForm().split("!");
                    lastModified = new Date(jf.getJarEntry(jarURL[1].substring(1)).getTime());
                } else {
                    lastModified = new Date(new File(url.toURI()).lastModified());
                }
                resp.setHeader("Last-Modified", dfLastModified.format(lastModified));
                resp.setContentType(getContentType(url));
                Object cachedResource = NamedResources.getStaticCache(makumbaResources).getResource(resource);
                ServletOutputStream outputStream = resp.getOutputStream();
                if (isBinary(url)) {
                    for (int i = 0; i < ((byte[]) cachedResource).length; i++) {
                        outputStream.write(((byte[]) cachedResource)[i]);
                    }
                } else {
                    outputStream.print(cachedResource.toString());
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }


    public String loadURLString(java.net.URL url) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buf = new StringBuffer();
            String s = "";
            while (br.ready() && s != null) {
                s = br.readLine();
                if (s != null) {
                    buf.append(s);
                    buf.append("\n");
                }
            }
            return buf.toString();
        } catch (IOException ex) {
            return "";
        } catch (NullPointerException npe) {
            return "";
        }
    }


    public void removeResource(String resourceID, String sql, String[] keys) throws XregistryException {
        try {
            Connection connection = globalContext.createConnection();
            connection.setAutoCommit(false);
            PreparedStatement statement = null;
            try {
                statement = connection.prepareStatement(sql);
                for (int i = 0; i < keys.length; i++) {
                    statement.setString(i + 1, keys[i]);
                }
                statement.executeUpdate();
                statement = connection.prepareStatement(DELETE_RESOURCE_SQL);
                statement.setString(1, resourceID);
                statement.executeUpdate();
                log.info("Execuate SQL " + statement);
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw new XregistryException(e);
            } finally {
                try {
                    statement.close();
                    connection.setAutoCommit(true);
                    globalContext.closeConnection(connection);
                } catch (SQLException e) {
                    throw new XregistryException(e);
                }
            }
        } catch (SQLException e) {
            throw new XregistryException(e);
        }
    }


    public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException {
        ZipFile zip = new ZipFile(mapPackFile);
        try {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            MessageDigest md5Total = MessageDigest.getInstance("MD5");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (entry.isDirectory()) continue;
                String name = entry.getName();
                if (name.toUpperCase().startsWith("META-INF")) continue;
                md5.reset();
                InputStream in = zip.getInputStream(entry);
                byte[] data = Utilities.getInputBytes(in);
                in.close();
                byte[] digest = md5.digest(data);
                log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\"");
                md5Total.update(digest);
                md5Total.update(name.getBytes());
            }
            String md5sum = Hex.encodeHexString(md5Total.digest());
            log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum);
            return md5sum;
        } finally {
            zip.close();
        }
    }


    public static void main(String[] args) throws Exception {
        BufferedImage image = ImageIO.read(BitmapFont.class.getResource("Candara-38-Bold.png"));
        URL url = BitmapFontData.class.getResource("Candara-38-Bold.fnt");
        BitmapFontData bitmapFontData = new BitmapFontData(url.openStream(), true);
        BitmapFont font = new BitmapFont(bitmapFontData, true);
        font.drawMultiLine("Hello world\nthis is a\ntest!!!", 100, 100);
        VertexData vertexData = font.createVertexData();
        Display.setDisplayMode(new DisplayMode(640, 480));
        Display.create();
        RenderPass renderPass = new RenderPass();
        renderPass.setClearMask(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
        renderPass.setClearColor(new Color4f(0.3f, 0.4f, 0.5f, 1f));
        renderPass.setView(View.createOrtho(0, 640, 0, 480, -1000, 1000));
        ByteBuffer[][] pixels = { { TextureLoader.getImageData(image) } };
        Texture texture = new Texture(TextureType.TEXTURE_2D, 4, image.getWidth(), image.getHeight(), 0, Format.BGRA, pixels, false, false);
        Shape shape = new Shape(vertexData);
        shape.getState().setUnit(0, new Unit(texture));
        shape.getState().setBlendEnabled(true);
        shape.getState().setBlendSrcFunc(BlendSrcFunc.SRC_ALPHA);
        shape.getState().setBlendDstFunc(BlendDstFunc.ONE_MINUS_SRC_ALPHA);
        renderPass.getRootNode().addShape(shape);
        Renderer renderer = new Renderer(new SceneGraph(renderPass));
        while (!Display.isCloseRequested()) {
            renderer.render();
            Display.update();
        }
        Display.destroy();
    }


    public static void fileUpload() throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        file = new File("H:\\FileServeUploader.java");
        HttpPost httppost = new HttpPost(postURL);
        httppost.setHeader("Cookie", uprandcookie + ";" + autologincookie);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2097152000"));
        mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid));
        mpEntity.addPart("go", new StringBody("1"));
        mpEntity.addPart("files", cbFile);
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into depositfiles...........................");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            uploadresponse = EntityUtils.toString(resEntity);
            downloadlink = parseResponse(uploadresponse, "ud_download_url = '", "'");
            deletelink = parseResponse(uploadresponse, "ud_delete_url = '", "'");
            System.out.println("download link : " + downloadlink);
            System.out.println("delete link : " + deletelink);
        }
    }


    @Override
    public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException {
        LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath());
        LOGGER.debug("Output stream: " + out.toString());
        if (ServerConfiguration.isDynamicSEL()) {
            LOGGER.error("IS DINAMIC SEL????");
        } else {
        }
        if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(realFile);
                int bytes = IOUtils.copy(in, out);
                LOGGER.debug("System resource or Allowed Client wrote bytes:  " + bytes);
                out.flush();
            } catch (Exception e) {
                LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e);
            } finally {
                IOUtils.closeQuietly(in);
            }
        } else {
            FileInputStream in = null;
            try {
                in = new FileInputStream(realFile);
                int bytes = IOUtils.copy(in, out);
                LOGGER.debug("System resource or Allowed Client wrote bytes:  " + bytes);
                out.flush();
            } catch (Exception e) {
                LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e);
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }


    private void bokActionPerformed(java.awt.event.ActionEvent evt) {
        Vector vret = this.uniformtitlepanel.getEnteredValuesKeys();
        String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds();
        String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib);
        System.out.println(xmlreq);
        try {
            java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet");
            java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection();
            urlconn.setDoOutput(true);
            java.io.OutputStream dos = urlconn.getOutputStream();
            dos.write(xmlreq.getBytes());
            java.io.InputStream ios = urlconn.getInputStream();
            SAXBuilder saxb = new SAXBuilder();
            Document retdoc = saxb.build(ios);
            Element rootelement = retdoc.getRootElement();
            if (rootelement.getChild("Error") == null) {
                this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase"));
            } else {
                this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor"));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }


    public synchronized void readModels(Project p, URL url) throws IOException {
        _proj = p;
        Argo.log.info("=======================================");
        Argo.log.info("== READING MODEL " + url);
        try {
            XMIReader reader = new XMIReader();
            InputSource source = new InputSource(url.openStream());
            source.setSystemId(url.toString());
            _curModel = reader.parse(source);
            if (reader.getErrors()) {
                throw new IOException("XMI file " + url.toString() + " could not be parsed.");
            }
            _UUIDRefs = new HashMap(reader.getXMIUUIDToObjectMap());
        } catch (SAXException saxEx) {
            Exception ex = saxEx.getException();
            if (ex == null) {
                saxEx.printStackTrace();
            } else {
                ex.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Argo.log.info("=======================================");
        try {
            _proj.addModel((ru.novosoft.uml.foundation.core.MNamespace) _curModel);
        } catch (PropertyVetoException ex) {
            System.err.println("An error occurred adding the model to the project!");
            ex.printStackTrace();
        }
        Collection ownedElements = _curModel.getOwnedElements();
        Iterator oeIterator = ownedElements.iterator();
        while (oeIterator.hasNext()) {
            MModelElement me = (MModelElement) oeIterator.next();
            if (me instanceof MClass) {
                _proj.defineType((MClass) me);
            } else if (me instanceof MDataType) {
                _proj.defineType((MDataType) me);
            }
        }
    }


    public static String getMD5Hash(String in) {
        StringBuffer result = new StringBuffer(32);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(in.getBytes());
            Formatter f = new Formatter(result);
            for (byte b : md5.digest()) {
                f.format("%02x", b);
            }
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return result.toString();
    }


    private boolean load(URL url) {
        try {
            URLConnection connection = url.openConnection();
            parser = new PDFParser(connection.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private void forcedCopy(File sourceFile, File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }


    public static void copyFile(File source, File destination) throws IOException {
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(destination);
        FileChannel inCh = fis.getChannel();
        FileChannel outCh = fos.getChannel();
        inCh.transferTo(0, inCh.size(), outCh);
        inCh.close();
        fis.close();
        outCh.close();
        fos.flush();
        fos.close();
    }


    public static void main(String[] args) {
        try {
            {
                byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 };
                byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 };
                System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1));
                System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1));
                byte[] dbytes = decode(encodeBytes(bytes1));
                System.out.print(encodeBytes(bytes1) + " decoded: ");
                for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n"));
            }
            {
                java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64");
                Base64.InputStream b64is = new Base64.InputStream(fis, DECODE);
                byte[] bytes = new byte[0];
                int b = -1;
                while ((b = b64is.read()) >= 0) {
                    byte[] temp = new byte[bytes.length + 1];
                    System.arraycopy(bytes, 0, temp, 0, bytes.length);
                    temp[bytes.length] = (byte) b;
                    bytes = temp;
                }
                b64is.close();
                javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes);
                javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0);
                javax.swing.JFrame jframe = new javax.swing.JFrame();
                jframe.getContentPane().add(jlabel);
                jframe.pack();
                jframe.show();
                java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out");
                fos.write(bytes);
                fos.close();
                fis = new java.io.FileInputStream("test.gif_out");
                b64is = new Base64.InputStream(fis, ENCODE);
                byte[] ebytes = new byte[0];
                b = -1;
                while ((b = b64is.read()) >= 0) {
                    byte[] temp = new byte[ebytes.length + 1];
                    System.arraycopy(ebytes, 0, temp, 0, ebytes.length);
                    temp[ebytes.length] = (byte) b;
                    ebytes = temp;
                }
                b64is.close();
                String s = new String(ebytes);
                javax.swing.JTextArea jta = new javax.swing.JTextArea(s);
                javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta);
                jframe = new javax.swing.JFrame();
                jframe.setTitle("Read from test.gif_out");
                jframe.getContentPane().add(jsp);
                jframe.pack();
                jframe.show();
                fos = new java.io.FileOutputStream("test.gif.b64_out");
                fos.write(ebytes);
                fis = new java.io.FileInputStream("test.gif.b64_out");
                b64is = new Base64.InputStream(fis, DECODE);
                byte[] edbytes = new byte[0];
                b = -1;
                while ((b = b64is.read()) >= 0) {
                    byte[] temp = new byte[edbytes.length + 1];
                    System.arraycopy(edbytes, 0, temp, 0, edbytes.length);
                    temp[edbytes.length] = (byte) b;
                    edbytes = temp;
                }
                b64is.close();
                iicon = new javax.swing.ImageIcon(edbytes);
                jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0);
                jframe = new javax.swing.JFrame();
                jframe.getContentPane().add(jlabel);
                jframe.pack();
                jframe.show();
            }
            {
                java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out");
                byte[] rbytes = new byte[0];
                int b = -1;
                while ((b = fis.read()) >= 0) {
                    byte[] temp = new byte[rbytes.length + 1];
                    System.arraycopy(rbytes, 0, temp, 0, rbytes.length);
                    temp[rbytes.length] = (byte) b;
                    rbytes = temp;
                }
                fis.close();
                java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2");
                Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE);
                b64os.write(rbytes);
                b64os.close();
                fis = new java.io.FileInputStream("test.gif.b64_out2");
                byte[] rebytes = new byte[0];
                b = -1;
                while ((b = fis.read()) >= 0) {
                    byte[] temp = new byte[rebytes.length + 1];
                    System.arraycopy(rebytes, 0, temp, 0, rebytes.length);
                    temp[rebytes.length] = (byte) b;
                    rebytes = temp;
                }
                fis.close();
                String s = new String(rebytes);
                javax.swing.JTextArea jta = new javax.swing.JTextArea(s);
                javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta);
                javax.swing.JFrame jframe = new javax.swing.JFrame();
                jframe.setTitle("Read from test.gif.b64_out2");
                jframe.getContentPane().add(jsp);
                jframe.pack();
                jframe.show();
                fos = new java.io.FileOutputStream("test.gif_out2");
                b64os = new Base64.OutputStream(fos, DECODE);
                b64os.write(rebytes);
                b64os.close();
                javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2");
                javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0);
                jframe = new javax.swing.JFrame();
                jframe.getContentPane().add(jlabel);
                jframe.pack();
                jframe.show();
            }
            {
                java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt");
                Base64.InputStream b64is = new Base64.InputStream(fis, DECODE);
                java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip");
                int b;
                while ((b = b64is.read()) >= 0) fos.write(b);
                fos.close();
                b64is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }
        FileInputStream input = new FileInputStream(srcFile);
        try {
            FileOutputStream output = new FileOutputStream(destFile);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(input);
        }
        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }


    public static void copyURLToFile(URL source, File destination) throws IOException {
        InputStream input = source.openStream();
        try {
            FileOutputStream output = openOutputStream(destination);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(input);
        }
    }


    public static Checksum checksum(File file, Checksum checksum) throws IOException {
        if (file.isDirectory()) {
            throw new IllegalArgumentException("Checksums can't be computed on directories");
        }
        InputStream in = null;
        try {
            in = new CheckedInputStream(new FileInputStream(file), checksum);
            IOUtils.copy(in, new OutputStream() {

                @Override
                public void write(byte[] b, int off, int len) {
                }

                @Override
                public void write(int b) {
                }

                @Override
                public void write(byte[] b) throws IOException {
                }
            });
        } finally {
            IOUtils.closeQuietly(in);
        }
        return checksum;
    }


    public Node external_open_url(Node startAt) throws Exception {
        if (inUse) {
            throw new InterpreterException(StdErrors.extend(StdErrors.Already_used, "File already open"));
        }
        inUse = true;
        startAt.isGoodArgsLength(false, 2);
        ExtURL url = new ExtURL(startAt.getSubNode(1, Node.TYPE_STRING).getString());
        String protocol = url.getProtocol();
        String mode = null;
        Node props = null;
        Node datas = null;
        byte[] buffer = null;
        String old_c = null;
        String old_r = null;
        int max_i = startAt.size() - 1;
        if (startAt.elementAt(max_i).getSymbolicValue_undestructive().isVList()) {
            props = startAt.getSubNode(max_i--, Node.TYPE_LIST);
        }
        int i_ = 2;
        if (i_ <= max_i) {
            mode = startAt.getSubNode(i_++, Node.TYPE_STRING).getString().toUpperCase().trim();
            if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) {
                if (!(mode.equals("GET") || mode.equals("POST") || mode.equals("PUT"))) {
                    throw new InterpreterException(128010, "Unsupported request methode");
                }
            } else if (protocol.equalsIgnoreCase("ftp") || protocol.equalsIgnoreCase("file")) {
                if (!(mode.equalsIgnoreCase("r") || mode.equalsIgnoreCase("w"))) {
                    throw new InterpreterException(128015, "Unsupported access methode");
                }
            } else if (protocol.equalsIgnoreCase("jar") || protocol.equalsIgnoreCase("stdin")) {
                if (!(mode.equalsIgnoreCase("r"))) {
                    throw new InterpreterException(128015, "Unsupported access methode");
                }
            } else if (protocol.equalsIgnoreCase("tcp") || protocol.equalsIgnoreCase("ssl+tcp")) {
                if (!(mode.equalsIgnoreCase("rw"))) {
                    throw new InterpreterException(128015, "Unsupported access methode");
                }
            } else if (protocol.equalsIgnoreCase("stdout") || protocol.equalsIgnoreCase("stderr")) {
                if (!(mode.equalsIgnoreCase("w"))) {
                    throw new InterpreterException(128015, "Unsupported access methode");
                }
            } else {
                throw new InterpreterException(128011, "Unsupported protocol");
            }
        }
        if (i_ <= max_i) {
            if (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https")) {
                throw new InterpreterException(128016, "Unsupported request datas");
            }
            datas = startAt.getSubNode(i_++, Node.TYPE_STRING | Node.TYPE_OBJECT);
            if (datas.isVObject()) {
                Object obj = datas.getVObjectExternalInstance();
                if (External_Buffer.class.isInstance(obj)) {
                    Buffer bbuffer = ((External_Buffer) obj).getBuffer();
                    buffer = bbuffer.read_bytes();
                } else {
                    throw new InterpreterException(StdErrors.extend(StdErrors.Invalid_parameter, "Object (" + obj.getClass().getName() + ") required " + External_Buffer.class.getName()));
                }
            } else {
                buffer = datas.getString().getBytes();
            }
        }
        if (datas != null && mode != null && mode.equals("GET")) {
            throw new InterpreterException(128012, "GET request with data body");
        }
        if (props != null && (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https"))) {
            throw new InterpreterException(128013, "Cannot handle header properties in request");
        }
        try {
            if (protocol.equalsIgnoreCase("file") && mode != null && mode.equalsIgnoreCase("w")) {
                File f = new File(url.toURI());
                outputStream = new FileOutputStream(f);
                outputBuffer = new BufferedOutputStream(outputStream);
                output = new DataOutputStream(outputBuffer);
            } else if (protocol.equalsIgnoreCase("tcp")) {
                tcpHost = url.getHost();
                tcpPort = url.getPort();
                if (tcpPort < 0 || tcpPort > 65535) {
                    throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort));
                }
                socket = new Socket(tcpHost, tcpPort);
                if (readTimeOut > 0) {
                    socket.setSoTimeout(readTimeOut);
                }
                inputStream = socket.getInputStream();
                inputBuffer = new BufferedInputStream(inputStream);
                input = new DataInputStream(inputBuffer);
                outputStream = socket.getOutputStream();
                outputBuffer = new BufferedOutputStream(outputStream);
                output = new DataOutputStream(outputBuffer);
            } else if (protocol.equalsIgnoreCase("ssl+tcp")) {
                tcpHost = url.getHost();
                tcpPort = url.getPort();
                if (tcpPort < 0 || tcpPort > 65535) {
                    throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort));
                }
                SocketFactory socketFactory = SSLSocketFactory.getDefault();
                socket = socketFactory.createSocket(tcpHost, tcpPort);
                if (readTimeOut > 0) {
                    socket.setSoTimeout(readTimeOut);
                }
                inputStream = socket.getInputStream();
                inputBuffer = new BufferedInputStream(inputStream);
                input = new DataInputStream(inputBuffer);
                outputStream = socket.getOutputStream();
                outputBuffer = new BufferedOutputStream(outputStream);
                output = new DataOutputStream(outputBuffer);
            } else if (protocol.equalsIgnoreCase("stdout")) {
                setBufOut(System.out);
            } else if (protocol.equalsIgnoreCase("stderr")) {
                setBufOut(System.err);
            } else if (protocol.equalsIgnoreCase("stdin")) {
                setBufIn(System.in);
            } else {
                urlConnection = url.openConnection();
                if (connectTimeOut > 0) {
                    urlConnection.setConnectTimeout(connectTimeOut);
                }
                if (readTimeOut > 0) {
                    urlConnection.setReadTimeout(readTimeOut);
                }
                urlConnection.setUseCaches(false);
                urlConnection.setDoInput(true);
                if (urlConnection instanceof HttpURLConnection) {
                    HttpURLConnection httpCon = (HttpURLConnection) urlConnection;
                    if (props != null) {
                        for (int i = 0; i < props.size(); i++) {
                            Node pnode = props.getSubNode(i, Node.TYPE_DICO);
                            String header_s = Node.getPairKey(pnode);
                            String value_s = Node.node2VString(Node.getPairValue(pnode)).getString();
                            Interpreter.Log("   HTTP-Header: " + header_s + " : " + value_s);
                            httpCon.setRequestProperty(header_s, value_s);
                        }
                    }
                    if (mode != null && (mode.equals("POST") || mode.equals("PUT"))) {
                        if (mode.equals("PUT")) {
                            Interpreter.Log("   HTTP PUT: " + url.toString());
                        } else {
                            Interpreter.Log("   HTTP POST: " + url.toString());
                        }
                        urlConnection.setDoOutput(true);
                        httpCon.setRequestMethod(mode);
                        outputStream = urlConnection.getOutputStream();
                        outputBuffer = new BufferedOutputStream(outputStream);
                        output = new DataOutputStream(outputBuffer);
                        output.write(buffer);
                        output.flush();
                    }
                    inputStream = urlConnection.getInputStream();
                    inputBuffer = new BufferedInputStream(inputStream);
                    input = new DataInputStream(inputBuffer);
                } else {
                    if (mode == null || (mode != null && mode.equalsIgnoreCase("r"))) {
                        Interpreter.Log("   " + protocol + " read : " + url.toString());
                        inputStream = urlConnection.getInputStream();
                        inputBuffer = new BufferedInputStream(inputStream);
                        input = new DataInputStream(inputBuffer);
                    } else {
                        Interpreter.Log("   " + protocol + " write : " + url.toString());
                        outputStream = urlConnection.getOutputStream();
                        outputBuffer = new BufferedOutputStream(outputStream);
                        output = new DataOutputStream(outputBuffer);
                    }
                }
            }
        } catch (Exception e) {
            throw e;
        }
        bytePos = 0;
        putHook();
        return null;
    }


    public static int[] BubbleSortDEC(int[] values) {
        boolean change = true;
        int aux;
        int[] indexes = new int[values.length];
        for (int i = 0; i < values.length; i++) {
            indexes[i] = i;
        }
        while (change) {
            change = false;
            for (int i = 0; i < values.length - 1; i++) {
                if (values[i] < values[i + 1]) {
                    aux = values[i];
                    values[i] = values[i + 1];
                    values[i + 1] = aux;
                    aux = indexes[i];
                    indexes[i] = indexes[i + 1];
                    indexes[i + 1] = aux;
                    change = true;
                }
            }
        }
        return (indexes);
    }


    private void foundNewVersion() {
        updater = new UpdaterView();
        updater.setLabelText("Initiating Updater...");
        updater.setProgress(0);
        updater.setLocationRelativeTo(null);
        updater.setVisible(true);
        URL pathUrl = ClassLoader.getSystemResource("img/icon.png");
        String path = pathUrl.toString();
        path = path.substring(4, path.length() - 14);
        try {
            file = new File(new URI(path));
            updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar"));
            if (updaterFile.exists()) {
                updaterFile.delete();
            }
            updater.setProgress(25);
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    try {
                        FileChannel in = (new FileInputStream(file)).getChannel();
                        FileChannel out = (new FileOutputStream(updaterFile)).getChannel();
                        in.transferTo(0, file.length(), out);
                        updater.setProgress(50);
                        in.close();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    startUpdater();
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }


                public void run() {
                    try {
                        FileChannel in = (new FileInputStream(file)).getChannel();
                        FileChannel out = (new FileOutputStream(updaterFile)).getChannel();
                        in.transferTo(0, file.length(), out);
                        updater.setProgress(50);
                        in.close();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    startUpdater();
                }


    private static void doCopyFile(FileInputStream in, FileOutputStream out) {
        FileChannel inChannel = null, outChannel = null;
        try {
            inChannel = in.getChannel();
            outChannel = out.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw ManagedIOException.manage(e);
        } finally {
            if (inChannel != null) {
                close(inChannel);
            }
            if (outChannel != null) {
                close(outChannel);
            }
        }
    }


    public String[] getElements() throws IOException {
        Vector v = new Vector();
        PushbackInputStream in = null;
        try {
            URLConnection urlConn = dtdURL.openConnection();
            in = new PushbackInputStream(new BufferedInputStream(urlConn.getInputStream()));
            while (scanForLTBang(in)) {
                String elementType = getString(in);
                if (elementType.equals("ELEMENT")) {
                    skipWhiteSpace(in);
                    String elementName = getString(in);
                    v.addElement(elementName);
                }
            }
            in.close();
            String[] elements = new String[v.size()];
            v.copyInto(elements);
            return elements;
        } catch (Exception exc) {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ignore) {
                }
            }
            throw new IOException("Error reading DTD: " + exc.toString());
        }
    }


    private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) {
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(input, writer);
        } catch (IOException e) {
            throw new ComixException("Could not read the database script", e);
        }
        String multipleSql = writer.toString();
        String[] split = multipleSql.split("-- SCRIPT_SPLIT --");
        for (String sql : split) {
            if (!sql.trim().equals("")) {
                sqlDatabase.execSQL(sql);
            }
        }
    }


    protected void loadXmlFromUri(URI uri) {
        URLConnection urlc;
        try {
            urlc = uri.toURL().openConnection();
            InputStream is = urlc.getInputStream();
            Reader rd = new InputStreamReader(is);
            xmlSource = new StreamSource(rd);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }


    protected void loadXslFromUri(URI uri) {
        URLConnection urlc;
        try {
            urlc = uri.toURL().openConnection();
            InputStream is = urlc.getInputStream();
            Reader rd = new InputStreamReader(is);
            Source xslSource = new StreamSource(rd);
            try {
                xslTemplate = factory.newTemplates(xslSource);
            } catch (TransformerConfigurationException tce) {
                tce.printStackTrace();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }


    @Override
    public IMedium createMedium(String urlString, IMetadata optionalMetadata) throws MM4UCannotCreateMediumElementsException {
        Debug.println("createMedium(): URL: " + urlString);
        IAudio tempAudio = null;
        try {
            String cachedFileUri = null;
            try {
                URL url = new URL(urlString);
                InputStream is = url.openStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len;
                while ((len = is.read(buf)) > 0) out.write(buf, 0, len);
                MediaCache cache = new MediaCache();
                cachedFileUri = cache.addAudio(urlString, out).getURI().substring(5);
            } catch (MalformedURLException e) {
                cachedFileUri = urlString;
            }
            TAudioFileFormat fFormat = null;
            try {
                fFormat = (TAudioFileFormat) new MpegAudioFileReader().getAudioFileFormat(new File(cachedFileUri));
            } catch (Exception e) {
                System.err.println("getAudioFileFormat() failed: " + e);
            }
            int length = Constants.UNDEFINED_INTEGER;
            if (fFormat != null) {
                length = Math.round(Integer.valueOf(fFormat.properties().get("duration").toString()).intValue() / 1000);
            }
            String mimeType = Utilities.getMimetype(Utilities.getURISuffix(urlString));
            optionalMetadata.addIfNotNull(IMedium.MEDIUM_METADATA_MIMETYPE, mimeType);
            if (length != Constants.UNDEFINED_INTEGER) {
                tempAudio = new Audio(this, length, urlString, optionalMetadata);
            }
        } catch (Exception exc) {
            exc.printStackTrace();
            return null;
        }
        return tempAudio;
    }


    public void writeTo(OutputStream out) throws IOException {
        if (!closed) {
            throw new IOException("Stream not closed");
        }
        if (isInMemory()) {
            memoryOutputStream.writeTo(out);
        } else {
            FileInputStream fis = new FileInputStream(outputFile);
            try {
                IOUtils.copy(fis, out);
            } finally {
                IOUtils.close(fis);
            }
        }
    }