    private void addLocale(Locale locale) throws MissingResourceException {
        locale = stripVariant(locale);
        Map<String, String> props = localeToMap.get(locale);
        if (props == null) props = new HashMap<String, String>();
        String urlName = locale.toString() + LOCALE_FILE_URL_SUFFIX;
        URL url = ClassLoader.getSystemClassLoader().getResource(urlName);
        if (url == null) {
            url = Thread.currentThread().getContextClassLoader().getResource(urlName);
            if (url == null) {
                throw new MissingResourceException("Cannot locate hprops for " + "locale " + locale, "PropertiesLocalizer", "HProperties: for " + locale);
            }
        }
        BufferedReader input = null;
        try {
            input = new BufferedReader(new InputStreamReader((InputStream) url.openStream(), "UTF8"));
            String str;
            while ((str = input.readLine()) != null) {
                str = str.trim();
                if (!str.startsWith("#") && !str.startsWith("!")) {
                    int index = -1;
                    for (int i = 0; i < str.length(); i++) {
                        char c = str.charAt(i);
                        if (c == ':' || c == '=') {
                            index = i;
                            break;
                        }
                    }
                    if (index > 0) {
                        String key = str.substring(0, index).trim();
                        String value = str.substring(index + 1);
                        props.put(key, value);
                    }
                }
            }
        } catch (IOException ioe) {
            throw new MissingResourceException(ioe.getMessage(), "PropertiesLocalizer", "HProperties: for " + locale.toString());
        } finally {
            try {
                input.close();
            } catch (IOException ioe) {
            }
        }
        localeToMap.put(locale, props);
    }


    public void run() throws Exception {
        logger.debug("#run enter");
        PreparedStatement ps = null;
        try {
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(SQL_UPDATE_ITEM_MIN_QTTY);
            ps.setInt(1, deliveryId);
            ps.setInt(2, deliveryId);
            ps.executeUpdate();
            ps.close();
            logger.debug("#run update STORE.ITEM ok");
            ps = connection.prepareStatement(SQL_DELETE_DELIVERY_LINE);
            ps.setInt(1, deliveryId);
            ps.executeUpdate();
            ps.close();
            logger.debug("#run delete STORE.DELIVERY_LINE ok");
            ps = connection.prepareStatement(SQL_DELETE_DELIVERY);
            ps.setInt(1, deliveryId);
            ps.executeUpdate();
            ps.close();
            logger.debug("#run delete STORE.DELIVERY ok");
            connection.commit();
        } catch (Exception ex) {
            logger.error("#run Transaction roll back ", ex);
            connection.rollback();
            throw new Exception("#run Не удалось загрузить в БД информацию об обновлении склада. Ошибка : " + ex.getMessage());
        } finally {
            connection.setAutoCommit(true);
        }
        logger.debug("#run exit");
    }


    private void retrieveClasses(URL url, Map<String, T> cmds) {
        try {
            String resource = URLDecoder.decode(url.getPath(), "UTF-8");
            File directory = new File(resource);
            if (directory.exists()) {
                String[] files = directory.list();
                for (String file : files) {
                    if (file.endsWith(".class")) {
                        addInstanceIfCommand(pckgname + '.' + file.substring(0, file.length() - 6), cmds);
                    }
                }
            } else {
                JarURLConnection con = (JarURLConnection) url.openConnection();
                String starts = con.getEntryName();
                Enumeration<JarEntry> entriesEnum = con.getJarFile().entries();
                while (entriesEnum.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entriesEnum.nextElement();
                    String entryname = entry.getName();
                    if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) {
                        String classname = entryname.substring(0, entryname.length() - 6);
                        if (classname.startsWith("/")) {
                            classname = classname.substring(1);
                        }
                        classname = classname.replace('/', '.');
                        addInstanceIfCommand(classname, cmds);
                    }
                }
            }
        } catch (IOException ioe) {
            LOG.warning("couldn't retrieve classes of " + url + ". Reason: " + ioe);
        }
    }


    public String postEvent(EventDocument eventDoc, Map attachments) {
        if (eventDoc == null || eventDoc.getEvent() == null) return null;
        if (jmsTemplate == null) {
            sendEvent(eventDoc, attachments);
            return eventDoc.getEvent().getEventId();
        }
        if (attachments != null) {
            Iterator iter = attachments.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (entry.getValue() instanceof DataHandler) {
                    File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey());
                    try {
                        IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file));
                        entry.setValue(file);
                    } catch (IOException err) {
                        err.printStackTrace();
                    }
                }
            }
        }
        InternalEventObject eventObj = new InternalEventObject();
        eventObj.setEventDocument(eventDoc);
        eventObj.setAttachments(attachments);
        eventObj.setSessionContext(SessionContextUtil.getCurrentContext());
        eventDoc.getEvent().setEventId(GuidUtil.generate());
        if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj);
        return eventDoc.getEvent().getEventId();
    }


    public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(algorithm);
            md.update(plaintext.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException nsae) {
            throw nsae;
        } catch (UnsupportedEncodingException uee) {
            throw uee;
        }
        return (new BigInteger(1, md.digest())).toString(16);
    }


    public static String loadUrlContentAsString(URL url) throws IOException {
        char[] buf = new char[2048];
        StringBuffer ret = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        for (int chars = reader.read(buf); chars != -1; chars = reader.read(buf)) {
            ret.append(buf, 0, chars);
        }
        reader.close();
        return ret.toString();
    }


    public static boolean copyFile(File from, File to) {
        try {
            FileChannel fromChannel = new FileInputStream(from).getChannel();
            FileChannel toChannel = new FileOutputStream(to).getChannel();
            toChannel.transferFrom(fromChannel, 0, fromChannel.size());
            fromChannel.close();
            toChannel.close();
        } catch (IOException e) {
            log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e);
            return false;
        }
        return true;
    }


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        super.execute(context);
        debug("Start execute job " + this.getClass().getName());
        try {
            String name = "nixspam-ip.dump.gz";
            String f = this.path_app_root + "/" + this.properties.get("dir") + "/";
            try {
                org.apache.commons.io.FileUtils.forceMkdir(new File(f));
            } catch (IOException ex) {
                fatal("IOException", ex);
            }
            f += "/" + name;
            String url = "http://www.dnsbl.manitu.net/download/" + name;
            debug("(1) - start download: " + url);
            com.utils.HttpUtil.downloadData(url, f);
            com.utils.IOUtil.unzip(f, f.replace(".gz", ""));
            File file_to_read = new File(f.replaceAll(".gz", ""));
            BigFile lines = null;
            try {
                lines = new BigFile(file_to_read.toString());
            } catch (Exception e) {
                fatal("Excpetion", e);
                return;
            }
            try {
                Statement stat = conn_url.createStatement();
                stat.executeUpdate(properties.get("query_delete"));
                stat.close();
            } catch (SQLException e) {
                fatal("SQLException", e);
            }
            try {
                conn_url.setAutoCommit(false);
            } catch (SQLException e) {
                fatal("SQLException", e);
            }
            boolean ok = true;
            int i = 0;
            for (String line : lines) {
                if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) {
                    continue;
                }
                try {
                    line = line.substring(line.indexOf(" "));
                    line = line.trim();
                    if (getIPException(line)) {
                        continue;
                    }
                    Statement stat = this.conn_url.createStatement();
                    stat.executeUpdate("insert into blacklist(url) values('" + line + "')");
                    stat.close();
                    i++;
                } catch (SQLException e) {
                    fatal("SQLException", e);
                    try {
                        conn_url.rollback();
                    } catch (SQLException ex) {
                        fatal("SQLException", ex);
                    }
                    ok = false;
                    break;
                }
            }
            boolean del = file_to_read.delete();
            debug("File " + file_to_read + " del:" + del);
            name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv";
            f = this.path_app_root + "/" + this.properties.get("dir") + "/";
            org.apache.commons.io.FileUtils.forceMkdir(new File(f));
            f += "/" + name;
            url = "http://spam-ip.com/csv_dump/" + name;
            debug("(2) - start download: " + url);
            com.utils.HttpUtil.downloadData(url, f);
            file_to_read = new File(f);
            try {
                lines = new BigFile(file_to_read.toString());
            } catch (Exception e) {
                fatal("Exception", e);
                return;
            }
            try {
                conn_url.setAutoCommit(false);
            } catch (SQLException e) {
                fatal("SQLException", e);
            }
            ok = true;
            for (String line : lines) {
                if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) {
                    continue;
                }
                try {
                    line = line.split(",")[1];
                    line = line.trim();
                    if (getIPException(line)) {
                        continue;
                    }
                    Statement stat = this.conn_url.createStatement();
                    stat.executeUpdate("insert into blacklist(url) values('" + line + "')");
                    stat.close();
                    i++;
                } catch (SQLException e) {
                    fatal("SQLException", e);
                    try {
                        conn_url.rollback();
                    } catch (SQLException ex) {
                        fatal("SQLException", ex);
                    }
                    ok = false;
                    break;
                }
            }
            del = file_to_read.delete();
            debug("File " + file_to_read + " del:" + del);
            if (ok) {
                debug("Import della BlackList Concluso tot righe: " + i);
                try {
                    conn_url.commit();
                } catch (SQLException e) {
                    fatal("SQLException", e);
                }
            } else {
                fatal("Problemi con la Blacklist");
            }
            try {
                conn_url.setAutoCommit(true);
            } catch (SQLException e) {
                fatal("SQLException", e);
            }
            try {
                Statement stat = this.conn_url.createStatement();
                stat.executeUpdate("VACUUM");
                stat.close();
            } catch (SQLException e) {
                fatal("SQLException", e);
            }
        } catch (IOException ex) {
            fatal("IOException", ex);
        }
        debug("End execute job " + this.getClass().getName());
    }


    private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException {
        try {
            final MessageDigest hash = MessageDigest.getInstance("SHA1");
            hash.update(new String(password).getBytes());
            hash.update(GGUtils.intToByte(seed));
            return hash.digest();
        } catch (final NoSuchAlgorithmException e) {
            LOG.error("SHA1 algorithm not usable", e);
            throw new GGException("SHA1 algorithm not usable!", e);
        }
    }


    private void handleXInclude(final String localName, final Attributes atts) {
        if ("include".equals(localName)) {
            this.inXInclude++;
            String href = atts.getValue("href");
            if ((href == null) || "".equals(href.trim())) {
                href = null;
            }
            String parse = atts.getValue("parse");
            if ((parse == null) || "".equals(parse.trim())) {
                parse = "xml";
            }
            String xpointer = atts.getValue("xpointer");
            if ((xpointer == null) || "".equals(xpointer.trim())) {
                xpointer = null;
            }
            String encoding = atts.getValue("encoding");
            if ((encoding == null) || "".equals(encoding.trim())) {
                encoding = null;
            }
            String accept = atts.getValue("accept");
            if ((accept == null) || "".equals(accept.trim())) {
                accept = null;
            }
            String accept_language = atts.getValue("accept-language");
            if ((accept_language == null) || "".equals(accept_language.trim())) {
                accept_language = null;
            }
            if (href != null) {
                if (href.indexOf(":/") == -1) {
                    if (href.startsWith("/")) {
                        href = href.substring(1);
                    }
                    href = this.documentURI + href;
                }
                if (this.localParser.get() == null) {
                    this.localParser.set(new CShaniDomParser());
                }
                CShaniDomParser p = (CShaniDomParser) this.localParser.get();
                InputStream in = null;
                try {
                    URL url = new URL(href);
                    URLConnection connection = url.openConnection();
                    if (accept != null) {
                        connection.addRequestProperty("Accept", accept);
                    }
                    if (accept_language != null) {
                        connection.addRequestProperty("Accept-Language", accept_language);
                    }
                    in = connection.getInputStream();
                    ADocument doc = null;
                    if (encoding != null) {
                        doc = (ADocument) p.parse(new InputStreamReader(in, encoding));
                    } else {
                        doc = (ADocument) p.parse(in);
                    }
                    if (xpointer == null) {
                        CDOM2SAX converter = new CDOM2SAX(doc.getDocumentElement());
                        converter.setProperty("http://xml.org/sax/properties/lexical-handler", this.lHandler);
                        converter.setContentHandler(this.cHandler);
                        converter.setDocumentHandler(this.dHandler);
                        converter.setDTDHandler(this.dtdHandler);
                        converter.serialize();
                    } else {
                        XPath xpath = new DOMXPath(xpointer);
                        for (Iterator it = doc.getNamespaceList().iterator(); it.hasNext(); ) {
                            CNamespace ns = (CNamespace) it.next();
                            xpath.addNamespace(ns.getPrefix() == null ? "" : ns.getPrefix(), ns.getNamespaceURI());
                        }
                        List result = xpath.selectNodes(doc.getDocumentElement());
                        for (final Iterator it = result.iterator(); it.hasNext(); ) {
                            final Node node = (Node) it.next();
                            CDOM2SAX converter = new CDOM2SAX(node);
                            converter.setProperty("http://xml.org/sax/properties/lexical-handler", this.lHandler);
                            converter.setContentHandler(this.cHandler);
                            converter.setDocumentHandler(this.dHandler);
                            converter.setDTDHandler(this.dtdHandler);
                            converter.serialize();
                        }
                    }
                } catch (final Exception e) {
                    this.xiFallbackFlag++;
                } finally {
                    try {
                        in.close();
                        in = null;
                    } catch (final Exception ignore) {
                    }
                }
            }
        }
    }


    private void gzip(FileHolder fileHolder) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        if (fileHolder.selectedFileList.size() == 0) {
            return;
        }
        File destFile = new File(fileHolder.destFiles[0]);
        try {
            OutputStream outStream = new FileOutputStream(destFile);
            outStream = new GZIPOutputStream(outStream);
            File selectedFile = fileHolder.selectedFileList.get(0);
            super.currentObjBeingProcessed = selectedFile;
            this.inStream = new FileInputStream(selectedFile);
            while ((bytes_read = this.inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytes_read);
            }
            outStream.close();
            this.inStream.close();
        } catch (IOException e) {
            errEntry.setThrowable(e);
            errEntry.setAppContext("gzip()");
            errEntry.setAppMessage("Error gzip'ing: " + destFile);
            logger.logError(errEntry);
        }
    }


    private void zip(FileHolder fileHolder, int zipCompressionLevel) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        if (fileHolder.selectedFileList.size() == 0) {
            return;
        }
        File zipDestFile = new File(fileHolder.destFiles[0]);
        try {
            ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile));
            for (int i = 0; i < fileHolder.selectedFileList.size(); i++) {
                File selectedFile = fileHolder.selectedFileList.get(i);
                super.currentObjBeingProcessed = selectedFile;
                this.inStream = new FileInputStream(selectedFile);
                ZipEntry entry = new ZipEntry(selectedFile.getName());
                outStream.setLevel(zipCompressionLevel);
                outStream.putNextEntry(entry);
                while ((bytes_read = this.inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytes_read);
                }
                outStream.closeEntry();
                this.inStream.close();
            }
            outStream.close();
        } catch (IOException e) {
            errEntry.setThrowable(e);
            errEntry.setAppContext("gzip()");
            errEntry.setAppMessage("Error zipping: " + zipDestFile);
            logger.logError(errEntry);
        }
        return;
    }


    private void tar(FileHolder fileHolder, boolean gzipIt) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        if (fileHolder.selectedFileList.size() == 0) {
            return;
        }
        File tarDestFile = new File(fileHolder.destFiles[0]);
        try {
            OutputStream outStream = new FileOutputStream(tarDestFile);
            if (gzipIt) {
                outStream = new GZIPOutputStream(outStream);
            }
            TarOutputStream tarOutStream = new TarOutputStream(outStream);
            for (int i = 0; i < fileHolder.selectedFileList.size(); i++) {
                File selectedFile = fileHolder.selectedFileList.get(i);
                super.currentObjBeingProcessed = selectedFile;
                this.inStream = new FileInputStream(selectedFile);
                TarEntry tarEntry = null;
                try {
                    tarEntry = new TarEntry(selectedFile, selectedFile.getName());
                } catch (InvalidHeaderException e) {
                    errEntry.setThrowable(e);
                    errEntry.setAppContext("tar()");
                    errEntry.setAppMessage("Error tar'ing: " + selectedFile);
                    logger.logError(errEntry);
                }
                tarOutStream.putNextEntry(tarEntry);
                while ((bytes_read = inStream.read(buffer)) != -1) {
                    tarOutStream.write(buffer, 0, bytes_read);
                }
                tarOutStream.closeEntry();
                inStream.close();
                super.processorSyncFlag.restartWaitUntilFalse();
            }
            tarOutStream.close();
        } catch (Exception e) {
            errEntry.setThrowable(e);
            errEntry.setAppContext("tar()");
            errEntry.setAppMessage("Error tar'ing: " + tarDestFile);
            logger.logError(errEntry);
        }
    }


    List<String> options(String path) throws TwinException {
        try {
            BasicHttpRequest request = new BasicHttpRequest("OPTIONS", url + path);
            HttpClient client = getClient();
            HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
            Header hdr = response.getFirstHeader("Allow");
            if (hdr == null || hdr.getValue().isEmpty()) return Collections.emptyList();
            return Arrays.asList(hdr.getValue().split("\\s*,\\s*"));
        } catch (IOException e) {
            throw TwinError.UnknownError.create("IOException when accessing RC", e);
        }
    }


    @SuppressWarnings("unchecked")
    private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException {
        String uri = url + path;
        HttpRequest request;
        if (body == null) {
            BasicHttpRequest r = new BasicHttpRequest(method, uri);
            request = r;
        } else {
            BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri);
            StringEntity entity;
            try {
                entity = new StringEntity(JSON.encode(body), "utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            entity.setContentType("application/json; charset=utf-8");
            r.setEntity(entity);
            request = r;
        }
        HttpClient client = getClient();
        try {
            HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
            HttpEntity entity = response.getEntity();
            if (entity == null) return null;
            String contentType = entity.getContentType().getValue();
            boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;"));
            String result = null;
            InputStream in = entity.getContent();
            try {
                Reader r = new InputStreamReader(in, "UTF-8");
                StringBuilder sb = new StringBuilder();
                char[] buf = new char[256];
                int read;
                while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read);
                r.close();
                result = sb.toString();
            } finally {
                try {
                    in.close();
                } catch (Exception e) {
                }
            }
            int code = response.getStatusLine().getStatusCode();
            if (code >= 400) {
                if (isJson) {
                    try {
                        throw deserializeException((Map<String, Object>) JSON.decode(result));
                    } catch (IllegalArgumentException e) {
                        throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e);
                    }
                }
                if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result);
            }
            if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result);
            try {
                return (Map<String, Object>) JSON.decode(result, recognizers);
            } catch (Exception e) {
                throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e);
            }
        } catch (ClientProtocolException e) {
            throw new IOException(e);
        }
    }


    public static File copy(String fromFileName, String toFileName) throws IOException {
        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);
        System.out.println("AbsolutePath fromFile: " + fromFile.getAbsolutePath());
        System.out.println("AbsolutePath toFile: " + toFile.getAbsolutePath());
        if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
        if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
        if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);
        if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());
        if (toFile.exists()) {
            if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
        } else {
            String parent = toFile.getParent();
            if (parent == null) parent = System.getProperty("user.dir");
            File dir = new File(parent);
            if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
            if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
            if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
        return toFile;
    }


    private void saveCampaign() throws HeadlessException {
        try {
            dbConnection.setAutoCommit(false);
            dbConnection.setSavepoint();
            String sql = "UPDATE campaigns SET " + "queue = ? ," + "adjustRatioPeriod = ?, " + "asterisk = ?, " + "context = ?," + "extension = ?, " + "dialContext = ?, " + "dialPrefix = ?," + "dialTimeout = ?, " + "dialingMethod = ?," + "dialsPerFreeResourceRatio = ?, " + "maxIVRChannels = ?, " + "maxDialingThreads = ?," + "maxDialsPerFreeResourceRatio = ?," + "minDialsPerFreeResourceRatio = ?, " + "maxTries = ?, " + "firstRetryAfterMinutes = ?," + "secondRetryAfterMinutes = ?, " + "furtherRetryAfterMinutes = ?, " + "startDate = ?, " + "endDate = ?," + "popUpURL = ?, " + "contactBatchSize = ?, " + "retriesBatchPct = ?, " + "reschedulesBatchPct = ?, " + "allowReschedule = ?, " + "rescheduleToOnself = ?, " + "script = ?," + "agentsCanUpdateContacts = ?, " + "hideContactFields = ?, " + "afterCallWork = ?, " + "reserveAvailableAgents = ?, " + "useDNCList = ?, " + "enableAgentDNC = ?, " + "contactsFilter = ?, " + "DNCTo = ?," + "callRecordingPolicy = ?, " + "callRecordingPercent = ?, " + "callRecordingMaxAge = ?, " + "WHERE name = ?";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            int i = 1;
            statement.setString(i++, txtQueue.getText());
            statement.setInt(i++, Integer.valueOf(txtAdjustRatio.getText()));
            statement.setString(i++, "");
            statement.setString(i++, txtContext.getText());
            statement.setString(i++, txtExtension.getText());
            statement.setString(i++, txtDialContext.getText());
            statement.setString(i++, txtDialPrefix.getText());
            statement.setInt(i++, 30000);
            statement.setInt(i++, cboDialingMethod.getSelectedIndex());
            statement.setFloat(i++, Float.valueOf(txtInitialDialingRatio.getText()));
            statement.setInt(i++, Integer.valueOf(txtMaxIVRChannels.getText()));
            statement.setInt(i++, Integer.valueOf(txtDialLimit.getText()));
            statement.setFloat(i++, Float.valueOf(txtMaxDialingRatio.getText()));
            statement.setFloat(i++, Float.valueOf(txtMinDialingRatio.getText()));
            statement.setInt(i++, Integer.valueOf(txtMaxRetries.getText()));
            statement.setInt(i++, Integer.valueOf(txtFirstRetry.getText()));
            statement.setInt(i++, Integer.valueOf(txtSecondRetry.getText()));
            statement.setInt(i++, Integer.valueOf(txtFurtherRetries.getText()));
            statement.setDate(i++, Date.valueOf(txtStartDate.getText()));
            statement.setDate(i++, Date.valueOf(txtEndDate.getText()));
            statement.setString(i++, txtURL.getText());
            statement.setInt(i++, Integer.valueOf(txtContactBatchSize.getText()));
            statement.setInt(i++, Integer.valueOf(txtRetryBatchPct.getText()));
            statement.setInt(i++, Integer.valueOf(txtRescheduleBatchPct.getText()));
            statement.setInt(i++, chkAgentCanReschedule.isSelected() ? 1 : 0);
            statement.setInt(i++, chkAgentCanRescheduleSelf.isSelected() ? 1 : 0);
            statement.setString(i++, txtScript.getText());
            statement.setInt(i++, chkAgentCanUpdateContacts.isSelected() ? 1 : 0);
            statement.setString(i++, "");
            statement.setInt(i++, Integer.valueOf(txtACW.getText()));
            statement.setInt(i++, Integer.valueOf(txtReserveAgents.getText()));
            statement.setInt(i++, cboDNCListPreference.getSelectedIndex());
            statement.setInt(i++, 1);
            statement.setString(i++, "");
            statement.setInt(i++, 0);
            statement.setInt(i++, cboRecordingPolicy.getSelectedIndex());
            statement.setInt(i++, Integer.valueOf(txtRecordingPct.getText()));
            statement.setInt(i++, Integer.valueOf(txtRecordingMaxAge.getText()));
            statement.setString(i++, campaign);
            statement.executeUpdate();
            dbConnection.commit();
        } catch (SQLException ex) {
            try {
                dbConnection.rollback();
            } catch (SQLException ex1) {
                Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1);
            }
            JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex);
        }
    }


    static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException {
        try {
            method.getParams().setSoTimeout(timeout * 1000);
            int status = -1;
            JSONObject result = null;
            for (int i = 0; i < RETRY; i++) {
                System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")");
                status = httpClient.executeMethod(method);
                if (status == HttpStatus.SC_OK) {
                    InputStream inputStream = method.getResponseBodyAsStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(inputStream, baos);
                    String response = new String(baos.toByteArray(), "UTF-8");
                    System.out.println(response);
                    result = JSONObject.fromString(response);
                    if (result.has("status")) {
                        String lingrStatus = result.getString("status");
                        if ("ok".equals(lingrStatus)) {
                            break;
                        } else {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                } else {
                    throw new HttpRequestFailureException(status);
                }
            }
            return result;
        } catch (SocketTimeoutException e) {
            throw new HttpRequestTimeoutException(e);
        } finally {
            method.releaseConnection();
        }
    }


    private static synchronized void calcLocalFileHash() {
        long startTime = System.currentTimeMillis();
        if (currentFileHash != null) return;
        List fileList = getAllFiles("/", new AllFilesFilter());
        int len = 0;
        byte[] buf = new byte[1024];
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA");
            for (Iterator i = fileList.iterator(); i.hasNext(); ) {
                String path = (String) i.next();
                LocalFileResource lfr = new LocalFileResource(path);
                if (lfr.isDirectory()) {
                    digest.update(path.getBytes("UTF-8"));
                    continue;
                }
                InputStream stream = lfr.getFileAsInputStream();
                while ((len = stream.read(buf)) != -1) {
                    digest.update(buf, 0, len);
                }
                stream.close();
            }
            currentFileHash = new String(Hex.encodeHex(digest.digest()));
        } catch (Exception e) {
            log.error("No SHA found ...?", e);
            currentFileHash = "unknown" + System.currentTimeMillis();
        } finally {
            if (log.isDebugEnabled()) log.debug("Needed " + (System.currentTimeMillis() - startTime) + "ms for hash calculation");
        }
    }


    public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception {
        long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L);
        BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"');
        String contentType = binaryAttribute.getContentType();
        if (contentType != null) {
            if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) {
                response.setContentType("application/octet-stream");
            } else {
                response.setContentType(contentType);
            }
        } else {
            response.setContentType("application/octet-stream");
        }
        IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream());
        return null;
    }


    public boolean load() {
        if (getFilename() != null && getFilename().length() > 0) {
            try {
                File file = new File(PreferencesManager.loadDirectoryLocation("macros") + File.separator + getFilename());
                URL url = file.toURL();
                InputStreamReader isr = new InputStreamReader(url.openStream());
                BufferedReader br = new BufferedReader(isr);
                String line = br.readLine();
                String macro_text = "";
                while (line != null) {
                    macro_text = macro_text.concat(line);
                    line = br.readLine();
                    if (line != null) {
                        macro_text = macro_text.concat(System.getProperty("line.separator"));
                    }
                }
                code = macro_text;
            } catch (Exception e) {
                System.err.println("Exception at StoredMacro.load(): " + e.toString());
                return false;
            }
        }
        return true;
    }


    public String readReferenceText(final String ident) throws NoContentException {
        try {
            String name = getFilename(ident);
            URL url = new URL(FreqAnalysisPlugin.getDefault().getBundle().getEntry("/"), name);
            InputStream in = url.openStream();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            String line = br.readLine();
            while (null != line) {
                buffer.append(line + "\n");
                line = br.readLine();
            }
            return buffer.toString();
        } catch (MalformedURLException muEx) {
            logError(muEx);
        } catch (UnsupportedEncodingException ueEx) {
            logError(ueEx);
        } catch (IOException ioEx) {
            logError(ioEx);
        }
        throw new NoContentException("Unable to find or read reference text.");
    }


    public String getPassword(URI uri) {
        if (_getPassword(uri) != null) return _getPassword(uri);
        String result = null;
        try {
            String sUri = scrubURI(uri);
            URL url = new URL(TEMP_PASSWORD_SERVICE_URL + "?SID=" + sessionId + "&ruri=" + URLEncoder.encode(sUri, "UTF-8"));
            JSONObject jsonObject = null;
            URLConnection conn = url.openConnection();
            InputStream istream = conn.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(istream));
            if ((result = in.readLine()) != null) {
                jsonObject = new JSONObject(result);
            }
            if (jsonObject.has("success")) {
                if (jsonObject.get("success").toString().equals("false")) {
                    if (jsonObject.has("error")) {
                        logger.log("Returned error message from temporary password service is: " + jsonObject.get("error"));
                    }
                    return null;
                }
            }
            if (jsonObject.has("temppass")) {
                result = (String) jsonObject.get("temppass");
            }
        } catch (java.io.FileNotFoundException fe) {
            logger.log("Could not find temporary password service. " + fe);
            fe.printStackTrace();
        } catch (Exception e) {
            logger.log("Exception getting temporary password. " + e);
            e.printStackTrace();
        }
        if (result == null) return null;
        return result;
    }


    public static Debugger getDebugger(InetAddress host, int port, String password) throws IOException {
        try {
            Socket s = new Socket(host, port);
            try {
                ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(s.getInputStream());
                int protocolVersion = in.readInt();
                if (protocolVersion > 220) {
                    throw new IOException("Incompatible protocol version " + protocolVersion + ". At most 220 was expected.");
                }
                byte[] challenge = (byte[]) in.readObject();
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(password.getBytes("UTF-8"));
                md.update(challenge);
                out.writeObject(md.digest());
                return new LocalDebuggerProxy((Debugger) in.readObject());
            } finally {
                s.close();
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new UndeclaredThrowableException(e);
        }
    }


    public void testSavepoint4() throws Exception {
        Statement stmt = con.createStatement();
        stmt.execute("CREATE TABLE #savepoint4 (data int)");
        stmt.close();
        con.setAutoCommit(false);
        for (int i = 0; i < 3; i++) {
            System.out.println("iteration: " + i);
            PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)");
            pstmt.setInt(1, 1);
            assertTrue(pstmt.executeUpdate() == 1);
            Savepoint savepoint = con.setSavepoint();
            assertNotNull(savepoint);
            assertTrue(savepoint.getSavepointId() == 1);
            try {
                savepoint.getSavepointName();
                assertTrue(false);
            } catch (SQLException e) {
            }
            pstmt.setInt(1, 2);
            assertTrue(pstmt.executeUpdate() == 1);
            pstmt.close();
            pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4");
            ResultSet rs = pstmt.executeQuery();
            assertTrue(rs.next());
            assertTrue(rs.getInt(1) == 3);
            assertTrue(!rs.next());
            pstmt.close();
            rs.close();
            con.rollback(savepoint);
            pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4");
            rs = pstmt.executeQuery();
            assertTrue(rs.next());
            assertTrue(rs.getInt(1) == 1);
            assertTrue(!rs.next());
            pstmt.close();
            rs.close();
            con.rollback();
        }
        con.setAutoCommit(true);
    }


    public void testSavepoint9() throws Exception {
        Statement stmt = con.createStatement();
        stmt.execute("CREATE TABLE #savepoint9 (data int)");
        stmt.close();
        con.setAutoCommit(false);
        Savepoint sp = con.setSavepoint();
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint9 (data) VALUES (?)");
        pstmt.setInt(1, 1);
        assertTrue(pstmt.executeUpdate() == 1);
        pstmt.close();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint9");
        assertTrue(rs.next());
        assertTrue(rs.getInt(1) == 1);
        assertTrue(!rs.next());
        stmt.close();
        rs.close();
        con.commit();
        con.rollback();
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint9");
        assertTrue(rs.next());
        assertTrue("bug [2021839]", rs.getInt(1) == 1);
        assertTrue(!rs.next());
        stmt.close();
        rs.close();
        con.setAutoCommit(true);
    }


public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception {
        Vector<SearchKeyResult> outVec = new Vector<SearchKeyResult>();
        String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, "UTF-8");
        URL url = new URL(uri);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        Pattern regex = Pattern.compile("pub.*?\\s*(\\w+)\\s*.*?(\\d+-\\d+-\\d+).*?\\s*(.+?)\\s*", Pattern.CANON_EQ);
        String line;
        while ((line = input.readLine()) != null) {
            Matcher regexMatcher = regex.matcher(line);
            while (regexMatcher.find()) {
                String id = regexMatcher.group(2);
                String downUrl = iKeyServer + regexMatcher.group(1);
                String downDate = regexMatcher.group(3);
                String name = HTMLDecoder.decodeHTML(regexMatcher.group(4));
                outVec.add(new SearchKeyResult(id, name, downDate, downUrl));
            }
        }
        input.close();
        return outVec;
    }


    public static void copyFile(File fileIn, File fileOut) throws IOException {
        FileChannel chIn = new FileInputStream(fileIn).getChannel();
        FileChannel chOut = new FileOutputStream(fileOut).getChannel();
        try {
            chIn.transferTo(0, chIn.size(), chOut);
        } catch (IOException e) {
            throw e;
        } finally {
            if (chIn != null) chIn.close();
            if (chOut != null) chOut.close();
        }
    }


    public static String md5(String source) {
        MessageDigest md;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            byte[] digested = md.digest();
            for (int i = 0; i < digested.length; i++) {
                pw.printf("%02x", digested[i]);
            }
            pw.flush();
            return sw.getBuffer().toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    public void sorter() {
        String inputLine1, inputLine2;
        String epiNames[] = new String[1000];
        String epiEpisodes[] = new String[1000];
        int lineCounter = 0;
        try {
            String pluginDir = pluginInterface.getPluginDirectoryName();
            String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt";
            File episodeList = new File(eplist_file);
            if (!episodeList.isFile()) {
                episodeList.createNewFile();
            }
            final BufferedReader in = new BufferedReader(new FileReader(episodeList));
            while ((inputLine1 = in.readLine()) != null) {
                if ((inputLine2 = in.readLine()) != null) {
                    epiNames[lineCounter] = inputLine1;
                    epiEpisodes[lineCounter] = inputLine2;
                    lineCounter++;
                }
            }
            in.close();
            int epiLength = epiNames.length;
            for (int i = 0; i < (lineCounter); i++) {
                for (int j = 0; j < (lineCounter - 1); j++) {
                    if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) {
                        String temp = epiNames[j];
                        epiNames[j] = epiNames[j + 1];
                        epiNames[j + 1] = temp;
                        String temp2 = epiEpisodes[j];
                        epiEpisodes[j] = epiEpisodes[j + 1];
                        epiEpisodes[j + 1] = temp2;
                    }
                }
            }
            File episodeList2 = new File(eplist_file);
            BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2));
            for (int i = 0; i <= lineCounter; i++) {
                if (epiNames[i] == null) {
                    break;
                }
                bufWriter.write(epiNames[i] + "\n");
                bufWriter.write(epiEpisodes[i] + "\n");
            }
            bufWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static URLConnection createConnection(URL url) throws java.io.IOException {
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) urlConn;
            httpConn.setRequestMethod("POST");
        }
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setDefaultUseCaches(false);
        return urlConn;
    }


    public Document createDocument(String uri) throws IOException {
        ParsedURL purl = new ParsedURL(uri);
        InputStream is = purl.openStream(MimeTypeConstants.MIME_TYPES_SVG);
        InputSource isrc = new InputSource(is);
        String contentType = purl.getContentType();
        int cindex = -1;
        if (contentType != null) {
            contentType = contentType.toLowerCase();
            cindex = contentType.indexOf(HTTP_CHARSET);
        }
        if (cindex != -1) {
            int i = cindex + HTTP_CHARSET.length();
            int eqIdx = contentType.indexOf('=', i);
            if (eqIdx != -1) {
                eqIdx++;
                String charset;
                int idx = contentType.indexOf(',', eqIdx);
                int semiIdx = contentType.indexOf(';', eqIdx);
                if ((semiIdx != -1) && ((semiIdx < idx) || (idx == -1))) idx = semiIdx;
                if (idx != -1) charset = contentType.substring(eqIdx, idx); else charset = contentType.substring(eqIdx);
                isrc.setEncoding(charset.trim());
            }
        }
        isrc.setSystemId(uri);
        Document doc = super.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, isrc);
        try {
            ((SVGOMDocument) doc).setURLObject(new URL(purl.toString()));
        } catch (MalformedURLException mue) {
            throw new IOException("Malformed URL: " + uri);
        }
        return doc;
    }


    public Long addPortletName(PortletNameBean portletNameBean) {
        PreparedStatement ps = null;
        DatabaseAdapter dbDyn = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            CustomSequenceType seq = new CustomSequenceType();
            seq.setSequenceName("seq_WM_PORTAL_PORTLET_NAME");
            seq.setTableName("WM_PORTAL_PORTLET_NAME");
            seq.setColumnName("ID_SITE_CTX_TYPE");
            Long sequenceValue = dbDyn.getSequenceNextValue(seq);
            ps = dbDyn.prepareStatement("insert into WM_PORTAL_PORTLET_NAME " + "( ID_SITE_CTX_TYPE, TYPE ) " + "values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ?" + (dbDyn.getIsNeedUpdateBracket() ? ")" : ""));
            RsetTools.setLong(ps, 1, sequenceValue);
            ps.setString(2, portletNameBean.getPortletName());
            ps.executeUpdate();
            dbDyn.commit();
            return sequenceValue;
        } catch (Exception e) {
            try {
                if (dbDyn != null) dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error add new portlet name ";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }


    public void updatePortletName(PortletNameBean portletNameBean) {
        DatabaseAdapter dbDyn = null;
        PreparedStatement ps = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            String sql = "update WM_PORTAL_PORTLET_NAME " + "set    TYPE=? " + "where  ID_SITE_CTX_TYPE=?";
            ps = dbDyn.prepareStatement(sql);
            ps.setString(1, portletNameBean.getPortletName());
            RsetTools.setLong(ps, 2, portletNameBean.getPortletId());
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1);
            dbDyn.commit();
        } catch (Exception e) {
            try {
                dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error save portlet name";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }


    public void deletePortletName(PortletNameBean portletNameBean) {
        DatabaseAdapter dbDyn = null;
        PreparedStatement ps = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null");
            String sql = "delete from  WM_PORTAL_PORTLET_NAME " + "where  ID_SITE_CTX_TYPE=?";
            ps = dbDyn.prepareStatement(sql);
            RsetTools.setLong(ps, 1, portletNameBean.getPortletId());
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1);
            dbDyn.commit();
        } catch (Exception e) {
            try {
                dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error delete portlet name";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }


    protected void setTestContent(IDfDocument document, String testFileName) throws Exception {
        InputStream testFileIs = new BufferedInputStream(FileHelper.getFileAsStreamFromClassPath(testFileName));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(testFileIs, baos);
        String contentType = formatHelper.getFormatForExtension(FileHelper.getFileExtension(testFileName));
        document.setContentType(contentType);
        document.setContent(baos);
    }


    public void run() {
        if (getCommand() == null) throw new IllegalArgumentException("Given command is null!");
        if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!");
        if (getCommand() instanceof ListCommand) {
            try {
                setReply(ReplyWorker.readReply(getSocketProvider(), true));
                setStatus(ReplyWorker.FINISHED);
            } catch (IOException ioe) {
                setCaughtException(ioe);
                setStatus(ReplyWorker.ERROR_IO_EXCEPTION);
            }
            return;
        } else if (getCommand() instanceof RetrieveCommand) {
            RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand();
            if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) {
                try {
                    log.debug("Download file: " + retrieveCommand.getFromFile().toString());
                    FileOutputStream out = null;
                    FileChannel channel = null;
                    if (getDownloadMethod() == RetrieveCommand.FILE_BASED) {
                        out = new FileOutputStream(retrieveCommand.getToFile().getFile());
                        channel = out.getChannel();
                        if (retrieveCommand.getResumePosition() != -1) {
                            try {
                                channel.position(retrieveCommand.getResumePosition());
                            } catch (IOException ioe) {
                                setCaughtException(ioe);
                                setStatus(ReplyWorker.ERROR_IO_EXCEPTION);
                                try {
                                    channel.close();
                                } catch (IOException ioe2) {
                                }
                                return;
                            }
                        }
                    } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) {
                    }
                    int amount;
                    try {
                        while ((amount = getSocketProvider().read(buffer)) != -1) {
                            if (amount == 0) {
                                try {
                                    Thread.sleep(4);
                                } catch (InterruptedException e) {
                                }
                            }
                            buffer.flip();
                            while (buffer.hasRemaining()) {
                                if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) {
                                    int rem = buffer.remaining();
                                    byte[] buf = new byte[rem];
                                    buffer.get(buf, 0, rem);
                                    this.outputPipe.write(buf, 0, rem);
                                } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) {
                                } else {
                                    channel.write(buffer);
                                }
                            }
                            buffer.clear();
                        }
                        buffer.flip();
                        while (buffer.hasRemaining()) {
                            if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) {
                                int rem = buffer.remaining();
                                byte[] buf = new byte[rem];
                                buffer.get(buf, 0, rem);
                                this.outputPipe.write(buf, 0, rem);
                            } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) {
                            } else {
                                channel.write(buffer);
                            }
                        }
                        buffer.clear();
                        setStatus(ReplyWorker.FINISHED);
                        if (channel != null) channel.close();
                        if (this.outputPipe != null) this.outputPipe.close();
                        getSocketProvider().close();
                    } catch (IOException ioe) {
                        setCaughtException(ioe);
                        setStatus(ReplyWorker.ERROR_IO_EXCEPTION);
                    } finally {
                        try {
                            channel.close();
                            getSocketProvider().close();
                        } catch (Exception e) {
                        }
                    }
                } catch (FileNotFoundException fnfe) {
                    setCaughtException(fnfe);
                    setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND);
                }
            } else throw new IllegalArgumentException("Unknown file transfer type for download!");
            return;
        } else if (getCommand() instanceof StoreCommand) {
            StoreCommand storeCommand = (StoreCommand) getCommand();
            if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) {
                try {
                    log.debug("Upload file: " + storeCommand.getFromFile());
                    InputStream in = storeCommand.getStream();
                    int amount;
                    int socketWrite;
                    int socketAmount = 0;
                    if (in instanceof FileInputStream) {
                        FileChannel channel = ((FileInputStream) in).getChannel();
                        if (storeCommand.getResumePosition() != -1) {
                            try {
                                channel.position(storeCommand.getResumePosition());
                            } catch (IOException ioe) {
                                setCaughtException(ioe);
                                setStatus(ReplyWorker.ERROR_IO_EXCEPTION);
                                try {
                                    channel.close();
                                } catch (IOException ioe2) {
                                }
                                return;
                            }
                        }
                        try {
                            while ((amount = channel.read(buffer)) != -1) {
                                buffer.flip();
                                socketWrite = 0;
                                while ((socketWrite = getSocketProvider().write(buffer)) != -1) {
                                    socketAmount += socketWrite;
                                    if (amount <= socketAmount) {
                                        break;
                                    }
                                    if (socketWrite == 0) {
                                        try {
                                            Thread.sleep(4);
                                        } catch (InterruptedException e) {
                                        }
                                    }
                                }
                                if (socketWrite == -1) {
                                    break;
                                }
                                socketAmount = 0;
                                buffer.clear();
                            }
                            setStatus(ReplyWorker.FINISHED);
                            channel.close();
                            getSocketProvider().close();
                        } catch (IOException ioe) {
                            setCaughtException(ioe);
                            setStatus(ReplyWorker.ERROR_IO_EXCEPTION);
                        } finally {
                            try {
                                channel.close();
                                getSocketProvider().close();
                            } catch (Exception e) {
                            }
                        }
                    } else {
                        try {
                            while ((amount = in.read(buffer.array())) != -1) {
                                buffer.flip();
                                buffer.limit(amount);
                                socketWrite = 0;
                                while ((socketWrite = getSocketProvider().write(buffer)) != -1) {
                                    socketAmount = socketWrite;
                                    if (amount <= socketAmount) {
                                        break;
                                    }
                                    if (socketWrite == 0) {
                                        try {
                                            Thread.sleep(4);
                                        } catch (InterruptedException e) {
                                        }
                                    }
                                }
                                if (socketWrite == -1) {
                                    break;
                                }
                                socketAmount = 0;
                                buffer.clear();
                            }
                            setStatus(ReplyWorker.FINISHED);
                            in.close();
                            getSocketProvider().close();
                        } catch (IOException ioe) {
                            setCaughtException(ioe);
                            setStatus(ReplyWorker.ERROR_IO_EXCEPTION);
                        } finally {
                            try {
                                in.close();
                                getSocketProvider().close();
                            } catch (Exception e) {
                            }
                        }
                    }
                } catch (FileNotFoundException fnfe) {
                    setCaughtException(fnfe);
                    setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND);
                }
            } else throw new IllegalArgumentException("Unknown file transfer type for upload!");
        } else throw new IllegalArgumentException("Given command is not supported!");
    }


private String createHTML(PAGE_TYPE requestPage) {
        String result = "";
        URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css");
        InputStreamReader ins;
        try {
            ins = new InputStreamReader(url.openStream());
            BufferedReader bufferedReader = new BufferedReader(ins);
            String cssLine;
            while ((cssLine = bufferedReader.readLine()) != null) result += cssLine + "\n";
        } catch (IOException e1) {
            log.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
        }
        switch(requestPage) {
            case PAGE_LOGO:
                result += "" + "

" + "" + "		" + "

" + "";
                break;
            case PAGE_HOME:
                result += "
\n";
                queryZoom = null;
                queryZoom = new ArrayList<MQuery>();
                String appendToHome = null;
                String sql = " SELECT x.AD_CLIENT_ID, x.NAME, x.DESCRIPTION, x.AD_WINDOW_ID, x.PA_GOAL_ID, x.LINE, x.HTML, m.AD_MENU_ID" + " FROM PA_DASHBOARDCONTENT x" + " LEFT OUTER JOIN AD_MENU m ON x.ad_window_id=m.ad_window_id" + " WHERE (x.AD_Client_ID=0 OR x.AD_Client_ID=?) AND x.IsActive='Y'" + " ORDER BY LINE";
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                try {
                    pstmt = DB.prepareStatement(sql, null);
                    pstmt.setInt(1, Env.getAD_Client_ID(Env.getCtx()));
                    rs = pstmt.executeQuery();
                    while (rs.next()) {
                        appendToHome = rs.getString("HTML");
                        if (appendToHome != null) {
                            if (rs.getString("DESCRIPTION") != null) result += "
" + rs.getString("DESCRIPTION") + "
\n";
                            result += stripHtml(appendToHome, false) + "
\n";
                        }
                        if (rs.getInt("AD_MENU_ID") > 0) {
                            result += "" + rs.getString("DESCRIPTION") + "
\n");
                        }
                        result += "
\n";
                        if (rs.getInt("PA_GOAL_ID") > 0) result += goalsDetail(rs.getInt("PA_GOAL_ID"));
                    }
                } catch (SQLException e) {
                    log.log(Level.SEVERE, sql, e);
                } finally {
                    DB.close(rs, pstmt);
                    rs = null;
                    pstmt = null;
                }
                result += "

\n" + "
\n\n\n";
                break;
            default:
                log.warning("Unknown option - " + requestPage);
        }
        return result;
    }


    private void loadProperties() {
        if (properties == null) {
            properties = new Properties();
            try {
                URL url = getClass().getResource(propsFile);
                properties.load(url.openStream());
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }


    public synchronized long nextValue(final Session session) {
        if (sequence < seqLimit) {
            return ++sequence;
        } else {
            final MetaDatabase db = MetaTable.DATABASE.of(table);
            Connection connection = null;
            ResultSet res = null;
            String sql = null;
            PreparedStatement statement = null;
            StringBuilder out = new StringBuilder(64);
            try {
                connection = session.getSeqConnection(db);
                String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString();
                out.setLength(0);
                out.setLength(0);
                sql = db.getDialect().printSequenceNextValue(this, out).toString();
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.log(Level.INFO, sql + "; [" + tableName + ']');
                }
                statement = connection.prepareStatement(sql);
                statement.setString(1, tableName);
                int i = statement.executeUpdate();
                if (i == 0) {
                    out.setLength(0);
                    sql = db.getDialect().printSequenceInit(this, out).toString();
                    if (LOGGER.isLoggable(Level.INFO)) {
                        LOGGER.log(Level.INFO, sql + "; [" + tableName + ']');
                    }
                    statement = connection.prepareStatement(sql);
                    statement.setString(1, tableName);
                    statement.executeUpdate();
                }
                out.setLength(0);
                sql = db.getDialect().printSequenceCurrentValue(this, out).toString();
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.log(Level.INFO, sql + "; [" + tableName + ']');
                }
                statement = connection.prepareStatement(sql);
                statement.setString(1, tableName);
                res = statement.executeQuery();
                res.next();
                seqLimit = res.getLong(1);
                int step = res.getInt(2);
                maxValue = res.getLong(3);
                sequence = (seqLimit - step) + 1;
                if (maxValue != 0L) {
                    if (seqLimit > maxValue) {
                        seqLimit = maxValue;
                        if (sequence > maxValue) {
                            String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue;
                            throw new IllegalStateException(msg);
                        }
                        statement.close();
                        sql = db.getDialect().printSetMaxSequence(this, out).toString();
                        if (LOGGER.isLoggable(Level.INFO)) {
                            LOGGER.log(Level.INFO, sql + "; [" + tableName + ']');
                        }
                        statement = connection.prepareStatement(sql);
                        statement.setString(1, tableName);
                        statement.execute();
                    }
                    if (maxValue > Long.MAX_VALUE - step) {
                        String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)";
                        LOGGER.log(Level.WARNING, msg);
                    }
                }
                connection.commit();
            } catch (Throwable e) {
                if (connection != null) try {
                    connection.rollback();
                } catch (SQLException ex) {
                    LOGGER.log(Level.WARNING, "Rollback fails");
                }
                IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e);
                throw exception;
            } finally {
                MetaDatabase.close(null, statement, res, true);
            }
            return sequence;
        }
    }


    public static String sendGetRequest(String urlStr) {
        String result = null;
        try {
            URL url = new URL(urlStr);
            System.out.println(urlStr);
            URLConnection conn = url.openConnection();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line = "";
            System.out.println("aa" + line);
            while ((line = rd.readLine()) != null) {
                System.out.println("aa" + line);
                sb.append(line);
            }
            rd.close();
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static ByteBuffer readURL(URL url) throws IOException, MalformedURLException {
        URLConnection connection = null;
        try {
            connection = url.openConnection();
            return readInputStream(new BufferedInputStream(connection.getInputStream()));
        } catch (IOException e) {
            throw e;
        }
    }


    public static final String getUniqueKey() {
        String digest = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            String timeVal = "" + (System.currentTimeMillis() + 1);
            String localHost = "";
            ;
            try {
                localHost = InetAddress.getLocalHost().toString();
            } catch (UnknownHostException e) {
                println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage());
            }
            String randVal = "" + new Random().nextInt();
            String val = timeVal + localHost + randVal;
            md.reset();
            md.update(val.getBytes());
            digest = toHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            println("Warn: getUniqueKey() " + e);
        }
        return digest;
    }


    public static void main(String[] args) {
        FTPClient client = new FTPClient();
        try {
            client.connect("ftp.domain.com");
            client.login("admin", "secret");
            String filename = "/testing/data.txt";
            boolean deleted = client.deleteFile(filename);
            if (deleted) {
                System.out.println("File deleted...");
            }
            client.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public String readCustomTemplate(String spaceKey) throws LocalizedException {
        final URL url = this.findTemplate(spaceKey);
        if (url == null) {
            return spaceKey == null ? this.readDefaultTemplate() : this.readCustomTemplate(null);
        } else try {
            return read(url.openStream());
        } catch (IOException exception) {
            throw new LocalizedException(this, "reading.custom", spaceKey, exception);
        }
    }


    public static String getMD5(String text) {
        if (text == null) {
            return null;
        }
        String result = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance(ALG_MD5);
            md5.update(text.getBytes(ENCODING));
            result = "" + new BigInteger(1, md5.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] a) {
        ArrayList<String> allFilesToBeCopied = new ArrayList<String>();
        new File(outputDir).mkdirs();
        try {
            FileReader fis = new FileReader(completeFileWithDirToCathFileList);
            BufferedReader bis = new BufferedReader(fis);
            String line = "";
            String currentCombo = "";
            while ((line = bis.readLine()) != null) {
                String[] allEntries = line.split("\\s+");
                String fileName = allEntries[0];
                String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4];
                if (currentCombo.equals(thisCombo)) {
                } else {
                    System.out.println("merke: " + fileName);
                    allFilesToBeCopied.add(fileName);
                    currentCombo = thisCombo;
                }
            }
            System.out.println(allFilesToBeCopied.size());
            for (String file : allFilesToBeCopied) {
                try {
                    FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel();
                    FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void doStatementQueryAndUpdate(Connection conn, String id) throws SQLException {
        try {
            int key = getNextKey();
            Statement s1 = conn.createStatement();
            String bValue = "doStatementQueryAndUpdate:" + id + testId;
            if (key >= MAX_KEY_VALUE) {
                key = key % MAX_KEY_VALUE;
                s1.executeUpdate("delete from many_threads where a = " + key);
            }
            int count = s1.executeUpdate("insert into many_threads values (" + key + ", '" + bValue + "', 0)");
            assertEquals(1, count);
            assertEquals(key, executeQuery(s1, "select a from many_threads where a = " + key));
            s1.executeUpdate("update many_threads set value =  a * a, b = b || '&" + bValue + "' where a = " + (key + 1));
            s1.close();
            if (!conn.getAutoCommit()) {
                conn.commit();
            }
        } catch (SQLException e) {
            if (!conn.getAutoCommit()) {
                try {
                    conn.rollback();
                } catch (SQLException e2) {
                }
            }
        }
    }


    public void doPreparedStatementQueryAndUpdate(Connection conn, String id) throws SQLException {
        try {
            int key = getNextKey();
            String bValue = "doPreparedStatementQueryAndUpdate:" + id + ":" + testId;
            PreparedStatement s1;
            if (key >= MAX_KEY_VALUE) {
                key = key % MAX_KEY_VALUE;
                s1 = conn.prepareStatement("delete from many_threads where a = ?");
                s1.setInt(1, key);
                s1.executeUpdate();
                s1.close();
            }
            s1 = conn.prepareStatement("insert into many_threads values (?, ?, 0)");
            s1.setInt(1, key);
            s1.setString(2, bValue);
            assertEquals(1, s1.executeUpdate());
            s1.close();
            s1 = conn.prepareStatement("select a from many_threads where a = ?");
            s1.setInt(1, key);
            assertEquals(key, executeQuery(s1));
            s1.close();
            s1 = conn.prepareStatement("update many_threads set value = a * a, b = b || ? where a = ?");
            s1.setString(1, "&" + bValue);
            s1.setInt(2, key + 1);
            s1.executeUpdate();
            s1.close();
            if (!conn.getAutoCommit()) {
                conn.commit();
            }
        } catch (SQLException e) {
            if (!conn.getAutoCommit()) {
                try {
                    conn.rollback();
                } catch (SQLException e2) {
                }
            }
        }
    }


    public void run() {
        long time = System.currentTimeMillis();
        logger.info("Version: " + version);
        String hostname = properties.getProperty("mercuriushost");
        String protocol = properties.getProperty("mercuriusprotocol");
        String port = properties.getProperty("mercuriusport");
        String path = properties.getProperty("mercuriuspath");
        String action = properties.getProperty("mercuriusaction");
        logger.info("Getting Timex Data --- " + getTimeDifferent(time));
        String xml = timexfrmk.getUnsynchedSessionsXMLFormat();
        logger.info("Done getting Timex Data --- " + getTimeDifferent(time));
        if (timexfrmk.getSessionCount() > 0) {
            try {
                logger.info("Sending Timex Data to Mercurius --- " + getTimeDifferent(time));
                String data = URLEncoder.encode("action", "UTF-8") + "=" + URLEncoder.encode(action, "UTF-8");
                data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + URLEncoder.encode(xml, "UTF-8");
                if (isAdminFeedKeySet()) {
                    data += "&" + URLEncoder.encode("adminfeedkey", "UTF-8") + "=" + URLEncoder.encode(adminfeedkey, "UTF-8");
                    logger.debug("Using adminfeedkey to authenticate");
                } else {
                    Authenticator.setDefault(new CustomAuthenticator(user, password));
                    logger.debug("Using user/pwd to authenticate");
                }
                String u = protocol + "://" + hostname + ":" + port + path;
                logger.debug("Posting xml data to: " + u);
                URL url = new URL(u);
                URLConnection conn = url.openConnection();
                conn.setRequestProperty("User-Agent", "TimexMercurius/" + version);
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                StringBuffer s = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    s.append(line);
                }
                if (s.length() > 0) {
                    logger.debug(s.toString());
                    if (s.toString().indexOf("Result:") != -1) {
                        logger.info(s.toString().substring(s.toString().indexOf("Result:")));
                        if (s.toString().indexOf("Result: Successful") != -1) {
                            timexfrmk.updateSessionsStatus();
                        }
                    } else {
                        logger.error(s.toString());
                    }
                } else {
                    logger.info("No data returned");
                }
                wr.close();
                rd.close();
            } catch (MalformedURLException e) {
                logger.error(e);
                logger.trace(e, e);
            } catch (IOException e) {
                logger.error(e);
                logger.trace(e, e);
            } catch (Exception e) {
                logger.error(e);
                logger.trace(e, e);
            }
        } else {
            logger.info("There is nothing to send.  Everything has already been synchronized");
        }
        timexfrmk.close();
        logger.info("Done!!! Total Time: " + getTimeDifferent(time));
    }


    public static String hashString(String sPassword) {
        if (sPassword == null || sPassword.equals("")) {
            return "empty:";
        } else {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                md.update(sPassword.getBytes("UTF-8"));
                byte[] res = md.digest();
                return "sha1:" + StringUtils.byte2hex(res);
            } catch (NoSuchAlgorithmException e) {
                return "plain:" + sPassword;
            } catch (UnsupportedEncodingException e) {
                return "plain:" + sPassword;
            }
        }
    }


    public static String md5Encode16(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(s.getBytes("utf-8"));
            byte b[] = md.digest();
            int i;
            StringBuilder buf = new StringBuilder("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }


    public static void main(String[] args) {
        String inFile = "test_data/blobs.png";
        String outFile = "ReadWriteTest.png";
        itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New();
        itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New();
        reader.SetFileName(inFile);
        writer.SetFileName(outFile);
        writer.SetInput(reader.GetOutput());
        writer.Update();
    }


    public APIResponse create(Item item) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/item/create").openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setUseCaches(false);
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        marshaller.marshal(item, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8")));
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine()));
            response.setDone(true);
            response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration()))));
            connection.getInputStream().close();
        } else {
            response.setDone(false);
            response.setMessage("Create Item Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }


    public APIResponse delete(String id) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/item/delete/" + id).openConnection();
        connection.setRequestMethod("DELETE");
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.setDone(true);
            response.setMessage("Item Deleted!");
        } else {
            response.setDone(false);
            response.setMessage("Delete Item Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }


    public APIResponse update(Item item) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/item/update").openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setUseCaches(false);
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        marshaller.marshal(item, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8")));
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine()));
            response.setDone(true);
            response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration()))));
            connection.getInputStream().close();
        } else {
            response.setDone(false);
            response.setMessage("Update Item Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }


    public void addPropertyColumns(WCAChannel destination, Set<Property> properties) throws SQLException {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Connection con = session.connection();
        try {
            createPropertyTable(destination);
            extendPropertyList(destination, properties);
            Statement statement = con.createStatement();
            for (Property property : properties) {
                String propertyName = removeBadChars(property.getName());
                statement.executeUpdate(alterTable.format(new Object[] { getTableName(destination), propertyName, property.getDBColumnType() }));
            }
            con.commit();
            con.close();
            session.close();
        } catch (SQLException e) {
            con.rollback();
            session.close();
            throw e;
        }
    }


    public static File copyFile(File file, String dirName) {
        File destDir = new File(dirName);
        if (!destDir.exists() || !destDir.isDirectory()) {
            destDir.mkdirs();
        }
        File src = file;
        File dest = new File(dirName, src.getName());
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileChannel source = new FileInputStream(src).getChannel();
            FileChannel destination = new FileOutputStream(dest).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dest;
    }


    public static File copyFile(File file) {
        File src = file;
        File dest = new File(src.getName());
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileChannel source = new FileInputStream(src).getChannel();
            FileChannel destination = new FileOutputStream(dest).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dest;
    }


    public static File copyFile(String path) {
        File src = new File(path);
        File dest = new File(src.getName());
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileChannel source = new FileInputStream(src).getChannel();
            FileChannel destination = new FileOutputStream(dest).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dest;
    }


    public static File copyFileAs(String path, String newName) {
        File src = new File(path);
        File dest = new File(newName);
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileChannel source = new FileInputStream(src).getChannel();
            FileChannel destination = new FileOutputStream(dest).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dest;
    }


    protected void readURL(URL url) {
        InputStream istream = null;
        InputStreamReader isr = null;
        BufferedReader in = null;
        try {
            istream = url.openStream();
            isr = new InputStreamReader(istream);
            in = new BufferedReader(isr);
            String line = in.readLine();
            while (null != line) {
                System.out.println(line);
                line = in.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtilities.close(in);
            IOUtilities.close(isr);
            IOUtilities.close(istream);
        }
    }


    private static LaunchablePlugin[] findLaunchablePlugins(LoggerChannelListener listener) {
        List res = new ArrayList();
        File app_dir = getApplicationFile("plugins");
        if (!(app_dir.exists()) && app_dir.isDirectory()) {
            listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' not found");
            return (new LaunchablePlugin[0]);
        }
        File[] plugins = app_dir.listFiles();
        if (plugins == null || plugins.length == 0) {
            listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' empty");
            return (new LaunchablePlugin[0]);
        }
        for (int i = 0; i < plugins.length; i++) {
            File plugin_dir = plugins[i];
            if (!plugin_dir.isDirectory()) {
                continue;
            }
            try {
                ClassLoader classLoader = PluginLauncherImpl.class.getClassLoader();
                ClassLoader root_cl = classLoader;
                File[] contents = plugin_dir.listFiles();
                if (contents == null || contents.length == 0) {
                    continue;
                }
                String[] plugin_version = { null };
                String[] plugin_id = { null };
                contents = getHighestJarVersions(contents, plugin_version, plugin_id, true);
                for (int j = 0; j < contents.length; j++) {
                    classLoader = addFileToClassPath(root_cl, classLoader, contents[j]);
                }
                Properties props = new Properties();
                File properties_file = new File(plugin_dir, "plugin.properties");
                if (properties_file.exists()) {
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(properties_file);
                        props.load(fis);
                    } finally {
                        if (fis != null) {
                            fis.close();
                        }
                    }
                } else {
                    if (classLoader instanceof URLClassLoader) {
                        URLClassLoader current = (URLClassLoader) classLoader;
                        URL url = current.findResource("plugin.properties");
                        if (url != null) {
                            props.load(url.openStream());
                        }
                    }
                }
                String plugin_class = (String) props.get("plugin.class");
                if (plugin_class == null || plugin_class.indexOf(';') != -1) {
                    continue;
                }
                Class c = classLoader.loadClass(plugin_class);
                Plugin plugin = (Plugin) c.newInstance();
                if (plugin instanceof LaunchablePlugin) {
                    preloaded_plugins.put(plugin_class, plugin);
                    res.add(plugin);
                }
            } catch (Throwable e) {
                listener.messageLogged("Load of plugin in '" + plugin_dir + "' fails", e);
            }
        }
        LaunchablePlugin[] x = new LaunchablePlugin[res.size()];
        res.toArray(x);
        return (x);
    }


    public static String SHA1(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 convertToHex(sha1hash);
    }


    private static void includePodDependencies(Curnit curnit, JarOutputStream jarout) throws IOException {
        Properties props = new Properties();
        Collection<Pod> pods = curnit.getReferencedPods();
        for (Pod pod : pods) {
            PodUuid podId = pod.getPodId();
            URL weburl = PodArchiveResolver.getSystemResolver().getUrl(podId);
            String urlString = "";
            if (weburl != null) {
                String uriPath = weburl.getPath();
                String zipPath = CurnitFile.WITHINCURNIT_BASEPATH + uriPath;
                jarout.putNextEntry(new JarEntry(zipPath));
                IOUtils.copy(weburl.openStream(), jarout);
                jarout.closeEntry();
                urlString = CurnitFile.WITHINCURNIT_PROTOCOL + uriPath;
            }
            props.put(podId.toString(), urlString);
        }
        jarout.putNextEntry(new JarEntry(CurnitFile.PODSREFERENCED_NAME));
        props.store(jarout, "pod dependencies");
        jarout.closeEntry();
    }


    public Vector decode(final URL url) throws IOException {
        LineNumberReader reader;
        if (owner != null) {
            reader = new LineNumberReader(new InputStreamReader(new ProgressMonitorInputStream(owner, "Loading " + url, url.openStream())));
        } else {
            reader = new LineNumberReader(new InputStreamReader(url.openStream()));
        }
        Vector v = new Vector();
        String line;
        Vector events;
        try {
            while ((line = reader.readLine()) != null) {
                StringBuffer buffer = new StringBuffer(line);
                for (int i = 0; i < 1000; i++) {
                    buffer.append(reader.readLine()).append("\n");
                }
                events = decodeEvents(buffer.toString());
                if (events != null) {
                    v.addAll(events);
                }
            }
        } finally {
            partialEvent = null;
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return v;
    }