public void service(Request req, Response resp) {
        PrintStream out = null;
        try {
            out = resp.getPrintStream(8192);
            String env = req.getParameter("env");
            String regex = req.getParameter("regex");
            String deep = req.getParameter("deep");
            String term = req.getParameter("term");
            String index = req.getParameter("index");
            String refresh = req.getParameter("refresh");
            String searcher = req.getParameter("searcher");
            String grep = req.getParameter("grep");
            String fiServerDetails = req.getParameter("fi_server_details");
            String serverDetails = req.getParameter("server_details");
            String hostDetails = req.getParameter("host_details");
            String name = req.getParameter("name");
            String show = req.getParameter("show");
            String path = req.getPath().getPath();
            int page = req.getForm().getInteger("page");
            if (path.startsWith("/fs")) {
                String fsPath = path.replaceAll("^/fs", "");
                File realPath = new File("C:\\", fsPath.replace('/', File.separatorChar));
                if (realPath.isDirectory()) {
                    out.write(FileSystemDirectory.getContents(new File("c:\\"), fsPath, "/fs"));
                } else {
                    resp.set("Cache", "no-cache");
                    FileInputStream fin = new FileInputStream(realPath);
                    FileChannel channel = fin.getChannel();
                    WritableByteChannel channelOut = resp.getByteChannel();
                    channel.transferTo(0, realPath.length(), channelOut);
                    channel.close();
                    fin.close();
                    System.err.println("Serving " + path + " as " + realPath.getCanonicalPath());
                }
            } else if (path.startsWith("/files/")) {
                String[] segments = req.getPath().getSegments();
                boolean done = false;
                if (segments.length > 1) {
                    String realPath = req.getPath().getPath(1);
                    File file = context.getFile(realPath);
                    if (file.isFile()) {
                        resp.set("Content-Type", context.getContentType(realPath));
                        FileInputStream fin = new FileInputStream(file);
                        FileChannel channel = fin.getChannel();
                        WritableByteChannel channelOut = resp.getByteChannel();
                        long start = System.currentTimeMillis();
                        channel.transferTo(0, realPath.length(), channelOut);
                        channel.close();
                        fin.close();
                        System.err.println("Time take to write [" + realPath + "] was [" + (System.currentTimeMillis() - start) + "] of size [" + file.length() + "]");
                        done = true;
                    }
                }
                if (!done) {
                    resp.set("Content-Type", "text/plain");
                    out.println("Can not serve directory: path");
                }
            } else if (path.startsWith("/upload")) {
                FileItemFactory factory = new DiskFileItemFactory();
                FileUpload upload = new FileUpload(factory);
                RequestAdapter adapter = new RequestAdapter(req);
                List<FileItem> list = upload.parseRequest(adapter);
                Map<String, FileItem> map = new HashMap<String, FileItem>();
                for (FileItem entry : list) {
                    String fileName = entry.getFieldName();
                    map.put(fileName, entry);
                }
                resp.set("Content-Type", "text/html");
                out.println("");
                out.println("");
                for (int i = 0; i < 10; i++) {
                    Part file = req.getPart("datafile" + (i + 1));
                    if (file != null && file.isFile()) {
                        String partName = file.getName();
                        String partFileName = file.getFileName();
                        File partFile = new File(partFileName);
                        FileItem item = map.get(partName);
                        InputStream in = file.getInputStream();
                        String fileName = file.getFileName().replaceAll("\\\\", "_").replaceAll(":", "_");
                        File filePath = new File(fileName);
                        OutputStream fileOut = new FileOutputStream(filePath);
                        byte[] chunk = new byte[8192];
                        int count = 0;
                        while ((count = in.read(chunk)) != -1) {
                            fileOut.write(chunk, 0, count);
                        }
                        fileOut.close();
                        in.close();
                        out.println("
");
                        out.println("
File	");
                        out.println(filePath.getCanonicalPath());
                        out.println("
	");
                        out.println("
Size	");
                        out.println(filePath.length());
                        out.println("
	");
                        out.println("
MD5	");
                        out.println(Digest.getSignature(Digest.Algorithm.MD5, file.getInputStream()));
                        out.println("
");
                        out.println(Digest.getSignature(Digest.Algorithm.MD5, item.getInputStream()));
                        if (partFile.exists()) {
                            out.println("
");
                            out.println(Digest.getSignature(Digest.Algorithm.MD5, new FileInputStream(partFile)));
                        }
                        out.println("
	");
                        out.println("
SHA1	");
                        out.println(Digest.getSignature(Digest.Algorithm.SHA1, file.getInputStream()));
                        out.println("
");
                        out.println(Digest.getSignature(Digest.Algorithm.SHA1, item.getInputStream()));
                        if (partFile.exists()) {
                            out.println("
");
                            out.println(Digest.getSignature(Digest.Algorithm.SHA1, new FileInputStream(partFile)));
                        }
                        out.println("
	");
                        out.println("
Header
");
                        out.println(file.toString().trim());
                        out.println("

	");
                        if (partFileName.toLowerCase().endsWith(".xml")) {
                            String xml = file.getContent();
                            String formatted = format(xml);
                            String fileFormatName = fileName + ".formatted";
                            File fileFormatOut = new File(fileFormatName);
                            FileOutputStream formatOut = new FileOutputStream(fileFormatOut);
                            formatOut.write(formatted.getBytes("UTF-8"));
                            out.println("
Formatted XML
");
                            out.println("" + partFileName + "");
                            out.println("

	");
                            formatOut.close();
                        }
                        out.println("
");
                    }
                }
                out.println("");
                out.println("");
            } else if (path.startsWith("/sql/") && index != null && searcher != null) {
                String file = req.getPath().getPath(1);
                File root = searchEngine.index(searcher).getRoot();
                SearchEngine engine = searchEngine.index(searcher);
                File indexFile = getStoredProcIndexFile(engine.getRoot(), index);
                File search = new File(root, "cpsql");
                File source = new File(root, file.replace('/', File.separatorChar));
                FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(search, indexFile);
                FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(source.getName());
                resp.set("Content-Type", "text/html");
                out.println("");
                out.println("
");
                for (String procName : proc.getReferences()) {
                    FindStoredProcs.StoredProc theProc = storedProcProj.getStoredProc(procName);
                    if (theProc != null) {
                        String url = getRelativeURL(root, theProc.getFile());
                        out.println("" + theProc.getName() + "");
                    }
                }
                out.println("
");
                out.println("");
            } else if (show != null && index != null && searcher != null) {
                String authentication = req.getValue("Authorization");
                if (authentication == null) {
                    resp.setCode(401);
                    resp.setText("Authorization Required");
                    resp.set("Content-Type", "text/html");
                    resp.set("WWW-Authenticate", "Basic realm=\"DTS Subversion Repository\"");
                    out.println("");
                    out.println("");
                    out.println("401 Authorization Required");
                    out.println("");
                    out.println("");
                    out.println("
401 Authorization Required
");
                    out.println("");
                    out.println("");
                } else {
                    resp.set("Content-Type", "text/html");
                    Principal principal = new PrincipalParser(authentication);
                    String file = show;
                    SearchEngine engine = searchEngine.index(searcher);
                    File root = engine.getRoot();
                    File javaIndexFile = getJavaIndexFile(root, index);
                    File storedProcIndexFile = getStoredProcIndexFile(root, index);
                    File sql = new File(root, "cpsql");
                    File source = new File(root, file.replace('/', File.separatorChar));
                    File javaSource = new File(root, file.replace('/', File.separatorChar));
                    File canonical = source.getCanonicalFile();
                    Repository repository = Subversion.login(Scheme.HTTP, principal.getName(), principal.getPassword());
                    Info info = null;
                    try {
                        info = repository.info(canonical);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    List<Change> logMessages = new ArrayList<Change>();
                    try {
                        logMessages = repository.log(canonical);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    FileInputStream in = new FileInputStream(canonical);
                    List<String> lines = LineStripper.stripLines(in);
                    out.println("");
                    out.println("");
                    out.println("");
                    out.println("<link rel='stylesheet' type='text/css' href='style.css'>");
                    out.println("");
                    out.println("");
                    out.println("");
                    if (info != null) {
                        out.println("
");
                        out.printf("
<tt>Author</tt>	<tt>" + info.author + "</tt>
");
                        out.printf("
<tt>Version</tt>	<tt>" + info.version + "</tt>
");
                        out.printf("
<tt>URL</tt>	<tt>" + info.location + "</tt>
");
                        out.printf("
<tt>Path</tt>	<tt>" + canonical + "</tt>
");
                        out.println("
");
                    }
                    out.println("
");
                    out.println("
");
                    out.println("
");
                    FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(sql, storedProcIndexFile);
                    FindStoredProcs.StoredProc storedProc = null;
                    FindJavaSources.JavaProject project = null;
                    FindJavaSources.JavaClass javaClass = null;
                    List<FindJavaSources.JavaClass> importList = null;
                    if (file.endsWith(".sql")) {
                        storedProc = storedProcProj.getStoredProc(canonical.getName());
                    } else if (file.endsWith(".java")) {
                        project = FindJavaSources.getProject(root, javaIndexFile);
                        javaClass = project.getClass(source);
                        importList = project.getImports(javaSource);
                    }
                    for (int i = 0; i < lines.size(); i++) {
                        out.println(i);
                    }
                    out.println("
	");
                    out.print("
");
                    for (int i = 0; i < lines.size(); i++) {
                        String line = lines.get(i);
                        String escaped = escapeHtml(line);
                        if (project != null) {
                            for (FindJavaSources.JavaClass entry : importList) {
                                String className = entry.getClassName();
                                String fullyQualifiedName = entry.getFullyQualifiedName();
                                if (line.startsWith("import") && line.indexOf(fullyQualifiedName) > -1) {
                                    File classFile = entry.getSourceFile();
                                    String url = getRelativeURL(root, classFile);
                                    escaped = escaped.replaceAll(fullyQualifiedName + ";", "" + fullyQualifiedName + ";");
                                } else if (line.indexOf(className) > -1) {
                                    File classFile = entry.getSourceFile();
                                    String url = getRelativeURL(root, classFile);
                                    escaped = escaped.replaceAll("\\s" + className + ",", " " + className + ",");
                                    escaped = escaped.replaceAll("\\s" + className + "\\{", " " + className + "{");
                                    escaped = escaped.replaceAll("," + className + ",", "," + className + ",");
                                    escaped = escaped.replaceAll("," + className + "\\{", "," + className + "{");
                                    escaped = escaped.replaceAll("\\s" + className + "\\s", " " + className + " ");
                                    escaped = escaped.replaceAll("\\(" + className + "\\s", "(" + className + " ");
                                    escaped = escaped.replaceAll("\\s" + className + "\\.", " " + className + ".");
                                    escaped = escaped.replaceAll("\\(" + className + "\\.", "(" + className + ".");
                                    escaped = escaped.replaceAll("\\s" + className + "\\(", " " + className + "(");
                                    escaped = escaped.replaceAll("\\(" + className + "\\(", "(" + className + "(");
                                    escaped = escaped.replaceAll(">" + className + ",", ">" + className + ",");
                                    escaped = escaped.replaceAll(">" + className + "\\s", ">" + className + " ");
                                    escaped = escaped.replaceAll(">" + className + "<", ">" + className + "<");
                                    escaped = escaped.replaceAll("\\(" + className + "\\);", "(" + className + ")");
                                }
                            }
                        } else if (storedProc != null) {
                            Set<String> procSet = storedProc.getTopReferences();
                            List<String> sortedProcs = new ArrayList(procSet);
                            Collections.sort(sortedProcs, LONGEST_FIRST);
                            for (String procFound : sortedProcs) {
                                if (escaped.indexOf(procFound) != -1) {
                                    File nameFile = storedProcProj.getLocation(procFound);
                                    if (nameFile != null) {
                                        String url = getRelativeURL(root, nameFile);
                                        escaped = escaped.replaceAll("\\s" + procFound + "\\s", " " + procFound + " ");
                                        escaped = escaped.replaceAll("\\s" + procFound + ",", " " + procFound + ",");
                                        escaped = escaped.replaceAll("\\s" + procFound + ";", " " + procFound + ";");
                                        escaped = escaped.replaceAll("," + procFound + "\\s", "," + procFound + " ");
                                        escaped = escaped.replaceAll("," + procFound + ",", "," + procFound + ",");
                                        escaped = escaped.replaceAll("," + procFound + ";", "," + procFound + ";");
                                        escaped = escaped.replaceAll("=" + procFound + "\\s", "=" + procFound + " ");
                                        escaped = escaped.replaceAll("=" + procFound + ",", "=" + procFound + ",");
                                        escaped = escaped.replaceAll("=" + procFound + ";", "=" + procFound + ";");
                                        escaped = escaped.replaceAll("." + procFound + "\\s", "." + procFound + " ");
                                        escaped = escaped.replaceAll("." + procFound + ",", "." + procFound + ",");
                                        escaped = escaped.replaceAll("." + procFound + ";", "." + procFound + ";");
                                    } else {
                                        System.err.println("NOT FOUND: " + procFound);
                                    }
                                }
                            }
                        }
                        out.println(escaped);
                    }
                    out.println("
	");
                    out.println("
");
                    out.println("
");
                    out.println("
");
                    out.printf("
<tt>Revision</tt>	<tt>Date</tt>	<tt>Author</tt>	<tt>Comment</tt>
");
                    DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    for (Change message : logMessages) {
                        out.printf("
<tt>%s</tt>	<tt>%s</tt>	<tt>%s</tt>	<tt>%s</tt>
%n", message.version, format.format(message.date).replaceAll("\\s", " "), message.author, message.message);
                    }
                    out.println("
");
                    if (project != null) {
                        out.println("
");
                        for (FindJavaSources.JavaClass entry : importList) {
                            String url = getRelativeURL(root, entry.getSourceFile());
                            out.println("import " + entry.getFullyQualifiedName() + " as " + entry.getClassName());
                        }
                        out.println("
");
                    }
                    if (storedProc != null) {
                        out.println("
");
                        for (String procName : storedProc.getReferences()) {
                            FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(procName);
                            if (proc != null) {
                                String url = getRelativeURL(root, proc.getFile());
                                out.println("using " + proc.getName() + "");
                            }
                        }
                        out.println("
");
                    }
                    out.println("</form>");
                    out.println("");
                    out.println("");
                }
            } else if (path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".formatted")) {
                path = path.replace('/', File.separatorChar);
                if (path.endsWith(".formatted")) {
                    resp.set("Content-Type", "text/plain");
                } else if (path.endsWith(".js")) {
                    resp.set("Content-Type", "application/javascript");
                } else {
                    resp.set("Content-Type", "text/css");
                }
                resp.set("Cache", "no-cache");
                WritableByteChannel channelOut = resp.getByteChannel();
                File file = new File(".", path).getCanonicalFile();
                System.err.println("Serving " + path + " as " + file.getCanonicalPath());
                FileChannel sourceChannel = new FileInputStream(file).getChannel();
                sourceChannel.transferTo(0, file.length(), channelOut);
                sourceChannel.close();
                channelOut.close();
            } else if (env != null && regex != null) {
                ServerDetails details = config.getEnvironment(env).load(persister, serverDetails != null, fiServerDetails != null, hostDetails != null);
                List<String> tokens = new ArrayList<String>();
                List<Searchable> list = details.search(regex, deep != null, tokens);
                Collections.sort(tokens, LONGEST_FIRST);
                for (String token : tokens) {
                    System.out.println("TOKEN: " + token);
                }
                resp.set("Content-Type", "text/html");
                out.println("");
                out.println("");
                out.println("<link rel='stylesheet' type='text/css' href='style.css'>");
                out.println("");
                out.println("");
                out.println("");
                writeSearchBox(out, searcher, null, null, regex);
                out.println("
Found " + list.size() + " hits for " + regex + "");
                out.println("
");
                int countIndex = 1;
                for (Searchable value : list) {
                    out.println("
" + countIndex++ + " " + value.getSource() + "
");
                    out.println("

");
                    StringWriter buffer = new StringWriter();
                    persister.write(value, buffer);
                    String text = buffer.toString();
                    text = escapeHtml(text);
                    for (String token : tokens) {
                        text = text.replaceAll(token, "" + token + "");
                    }
                    out.println(text);
                    out.println("

");
                }
                out.println("
");
                out.println("</form>");
                out.println("");
                out.println("");
            } else if (index != null && term != null && term.length() > 0) {
                out.println("");
                out.println("");
                out.println("<link rel='stylesheet' type='text/css' href='style.css'>");
                out.println("");
                out.println("");
                out.println("");
                writeSearchBox(out, searcher, term, index, null);
                if (searcher == null) {
                    searcher = searchEngine.getDefaultSearcher();
                }
                if (refresh != null) {
                    SearchEngine engine = searchEngine.index(searcher);
                    File root = engine.getRoot();
                    File searchIndex = getJavaIndexFile(root, index);
                    FindJavaSources.deleteProject(root, searchIndex);
                }
                boolean isRefresh = refresh != null;
                boolean isGrep = grep != null;
                boolean isSearchNames = name != null;
                SearchQuery query = new SearchQuery(index, term, page, isRefresh, isGrep, isSearchNames);
                List<SearchResult> results = searchEngine.index(searcher).search(query);
                writeSearchResults(query, searcher, results, out);
                out.println("");
                out.println("");
            } else {
                out.println("");
                out.println("");
                writeSearchBox(out, searcher, null, null, null);
                out.println("");
                out.println("");
            }
            out.close();
        } catch (Exception e) {
            try {
                e.printStackTrace();
                resp.reset();
                resp.setCode(500);
                resp.setText("Internal Server Error");
                resp.set("Content-Type", "text/html");
                out.println("");
                out.println("
Internal Server Error

");
                e.printStackTrace(out);
                out.println("
");
                out.println("");
                out.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public String getData() throws ValueFormatException, RepositoryException, IOException {
        InputStream is = getStream();
        StringWriter sw = new StringWriter();
        IOUtils.copy(is, sw, "UTF-8");
        IOUtils.closeQuietly(is);
        return sw.toString();
    }


    public InputStream unZip(URL url) throws Exception {
        ZipInputStream zipped = new ZipInputStream(url.openStream());
        System.out.println("unzipping: " + url.getFile());
        ZipEntry zip = zipped.getNextEntry();
        byte[] b = new byte[4096];
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        for (int iRead = zipped.read(b); iRead != -1; iRead = zipped.read(b)) {
            bOut.write(b, 0, iRead);
        }
        zipped.close();
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        return (InputStream) bIn;
    }


    public byte[] getFile(final String file) throws IOException {
        if (this.files.contains(file)) {
            ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes));
            ZipEntry entry = input.getNextEntry();
            while (entry != null) {
                entry = input.getNextEntry();
                if ((entry.getName().equals(file)) && (!entry.isDirectory())) {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    IOUtils.copy(input, output);
                    output.close();
                    input.close();
                    return output.toByteArray();
                }
            }
            input.close();
        }
        return null;
    }


    public void unzip(final File outDir) throws IOException {
        ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes));
        ZipEntry entry = input.getNextEntry();
        while (entry != null) {
            entry = input.getNextEntry();
            if (entry != null) {
                File file = this.createFile(outDir, entry.getName());
                if (!entry.isDirectory()) {
                    FileOutputStream output = new FileOutputStream(file);
                    IOUtils.copy(input, output);
                    output.close();
                }
            }
        }
        input.close();
    }


    public static Pedido insert(Pedido objPedido) {
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        int result;
        if (c == null) {
            return null;
        }
        try {
            c.setAutoCommit(false);
            String sql = "";
            int idPedido;
            idPedido = PedidoDAO.getLastCodigo();
            if (idPedido < 1) {
                return null;
            }
            sql = "insert into pedido " + "(id_pedido, id_funcionario,data_pedido,valor) " + "values(?,?,now(),truncate(?,2))";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idPedido);
            pst.setInt(2, objPedido.getFuncionario().getCodigo());
            pst.setString(3, new DecimalFormat("#0.00").format(objPedido.getValor()));
            result = pst.executeUpdate();
            pst = null;
            if (result > 0) {
                Iterator<ItemPedido> itItemPedido = (objPedido.getItemPedido()).iterator();
                while ((itItemPedido != null) && (itItemPedido.hasNext())) {
                    ItemPedido objItemPedido = (ItemPedido) itItemPedido.next();
                    sql = "";
                    sql = "insert into item_pedido " + "(id_pedido,id_produto,quantidade,subtotal) " + "values (?,?,?,truncate(?,2))";
                    pst = c.prepareStatement(sql);
                    pst.setInt(1, idPedido);
                    pst.setInt(2, (objItemPedido.getProduto()).getCodigo());
                    pst.setInt(3, objItemPedido.getQuantidade());
                    pst.setString(4, new DecimalFormat("#0.00").format(objItemPedido.getSubtotal()));
                    result = pst.executeUpdate();
                }
            }
            pst = null;
            sql = "";
            sql = "insert into pedido_situacao " + "(id_pedido,id_situacao, em, observacao, id_funcionario) " + "values (?,?,now(), ?, ?)";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idPedido);
            pst.setInt(2, 1);
            pst.setString(3, "Inclus�o de pedido");
            pst.setInt(4, objPedido.getFuncionario().getCodigo());
            result = pst.executeUpdate();
            pst = null;
            sql = "";
            sql = "insert into tramitacao " + "(data_tramitacao, id_pedido, id_dep_origem, id_dep_destino) " + "values (now(),?,?, ?)";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idPedido);
            pst.setInt(2, 6);
            pst.setInt(3, 2);
            result = pst.executeUpdate();
            c.commit();
            objPedido.setCodigo(idPedido);
        } catch (final Exception e) {
            try {
                c.rollback();
            } catch (final Exception e1) {
                System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e1.getMessage());
            }
            System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        return objPedido;
    }


    public static String encodePassword(String password) {
        try {
            MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1");
            messageDiegest.update(password.getBytes("UTF-8"));
            return Base64.encodeToString(messageDiegest.digest(), false);
        } catch (NoSuchAlgorithmException e) {
            log.error("Exception while encoding password");
            throw new Error(e);
        } catch (UnsupportedEncodingException e) {
            log.error("Exception while encoding password");
            throw new Error(e);
        }
    }


    public Map load() throws IOException {
        rpdMap = new HashMap();
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xr = factory.newSAXParser().getXMLReader();
            ConfigHandler handler = new ConfigHandler();
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            InputStream is = url.openStream();
            xr.parse(new InputSource(is));
            is.close();
        } catch (SAXParseException e) {
            String msg = "Error while parsing line " + e.getLineNumber() + " of " + url + ": " + e.getMessage();
            throw new IOException(msg);
        } catch (SAXException e) {
            throw new IOException("Problem with XML: " + e);
        } catch (ParserConfigurationException e) {
            throw new IOException(e.getMessage());
        }
        return rpdMap;
    }


    private String urlConnectionTranslate(String word) {
        try {
            URL url = new URL("http://ajax.googleapis.com/ajax/services/" + "language/translate?v=1.0&q=" + word + "&langpair=is%7Cen");
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("Referer", "http://www.hi.is");
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            JSONObject json = new JSONObject(builder.toString());
            return json.getJSONObject("responseData").getString("translatedText");
        } catch (Exception e) {
            Log.e(TranslatorApplication.tag, e.toString());
        }
        return null;
    }


    protected boolean createFile(final IProject project, final IProgressMonitor monitor, final Template templ, final String sourceUrl, final String destFile, final boolean isBinary) throws IOException, CoreException {
        URL url;
        url = new URL(sourceUrl);
        final URLConnection con = url.openConnection();
        final IFile f = project.getFile(replaceVariables(templ.getVariables(), destFile));
        createParents(f, monitor);
        if (isBinary) {
            f.create(con.getInputStream(), true, monitor);
        } else {
            final StringWriter sw = new StringWriter();
            final InputStream in = con.getInputStream();
            for (; ; ) {
                final int c = in.read();
                if (-1 == c) {
                    break;
                }
                sw.write(c);
            }
            sw.close();
            final String fileText = replaceVariables(templ.getVariables(), sw.toString());
            f.create(new ByteArrayInputStream(fileText.getBytes()), true, monitor);
        }
        return true;
    }


    public void convert(File src, File dest) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(src));
        DcmParser p = pfact.newDcmParser(in);
        Dataset ds = fact.newDataset();
        p.setDcmHandler(ds.getDcmHandler());
        try {
            FileFormat format = p.detectFileFormat();
            if (format != FileFormat.ACRNEMA_STREAM) {
                System.out.println("\n" + src + ": not an ACRNEMA stream!");
                return;
            }
            p.parseDcmFile(format, Tags.PixelData);
            if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) {
                System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert");
                return;
            }
            boolean hasPixelData = p.getReadTag() == Tags.PixelData;
            boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12;
            int pxlen = p.getReadLength();
            if (hasPixelData) {
                if (inflate) {
                    ds.putUS(Tags.BitsAllocated, 16);
                    pxlen = pxlen * 4 / 3;
                }
                if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) {
                    System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert");
                    return;
                }
            }
            ds.putUI(Tags.StudyInstanceUID, uid(studyUID));
            ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID));
            ds.putUI(Tags.SOPInstanceUID, uid(instUID));
            ds.putUI(Tags.SOPClassUID, classUID);
            if (!ds.contains(Tags.NumberOfSamples)) {
                ds.putUS(Tags.NumberOfSamples, 1);
            }
            if (!ds.contains(Tags.PhotometricInterpretation)) {
                ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2");
            }
            if (fmi) {
                ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian));
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
            try {
            } finally {
                ds.writeFile(out, encodeParam());
                if (hasPixelData) {
                    if (!skipGroupLen) {
                        out.write(PXDATA_GROUPLEN);
                        int grlen = pxlen + 8;
                        out.write((byte) grlen);
                        out.write((byte) (grlen >> 8));
                        out.write((byte) (grlen >> 16));
                        out.write((byte) (grlen >> 24));
                    }
                    out.write(PXDATA_TAG);
                    out.write((byte) pxlen);
                    out.write((byte) (pxlen >> 8));
                    out.write((byte) (pxlen >> 16));
                    out.write((byte) (pxlen >> 24));
                }
                if (inflate) {
                    int b2, b3;
                    for (; pxlen > 0; pxlen -= 3) {
                        out.write(in.read());
                        b2 = in.read();
                        b3 = in.read();
                        out.write(b2 & 0x0f);
                        out.write(b2 >> 4 | ((b3 & 0x0f) << 4));
                        out.write(b3 >> 4);
                    }
                } else {
                    for (; pxlen > 0; --pxlen) {
                        out.write(in.read());
                    }
                }
                out.close();
            }
            System.out.print('.');
        } finally {
            in.close();
        }
    }


    int[] slowSort() {
        int[] values = getValues();
        int n = values.length;
        for (int pass = 1; pass < n; pass++) {
            for (int i = 0; i < n - pass; i++) {
                if (values[i] > values[i + 1]) {
                    int temp = values[i];
                    values[i] = values[i + 1];
                    values[i + 1] = temp;
                }
            }
        }
        return values;
    }


    public File unpackResource(String resourceName) throws IOException {
        File file = null;
        URL url = getURL("/" + resourceName);
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof JarURLConnection) {
            file = handleJarFile((JarURLConnection) urlConn, resourceName);
        } else if (urlConn instanceof BundleURLConnection) {
            file = handleBundleFile((BundleURLConnection) urlConn);
        } else {
            file = handleClassicFile(resourceName);
        }
        return file;
    }


    private static Properties load(URL url) {
        Properties props = new Properties();
        try {
            InputStream is = null;
            try {
                is = url.openStream();
                props.load(is);
            } finally {
                is.close();
            }
        } catch (IOException e) {
        }
        return props;
    }


    public static HttpsURLConnection createRequest(String feedUrl, String httpMethod, Map<String, String> headers) throws BuzzIOException {
        HttpsURLConnection con;
        try {
            URL url = new URL(feedUrl);
            con = (HttpsURLConnection) url.openConnection();
            con.setRequestMethod(httpMethod);
            if (headers != null && !headers.isEmpty()) {
                for (String key : headers.keySet()) {
                    con.setRequestProperty(key, headers.get(key));
                }
            }
        } catch (IOException e) {
            throw new BuzzIOException(e);
        }
        return con;
    }


    private void doDecrypt() {
        runningThread = new Thread() {

            @Override
            public void run() {
                Application.getController().notifyProgressStarted();
                Application.getController().notifyProgressUpdated(-1);
                for (int f = 0; f < fileList.size(); f++) {
                    File archive = fileList.get(f);
                    String arname = archive.getName();
                    String arsuf = arname.substring(arname.lastIndexOf('.'), arname.length());
                    Algorithm alg = null;
                    Algorithm algs[] = algFactory.getAlgorithms();
                    for (int i = 0; i < algs.length; i++) {
                        if (algs[i].getSuffix().equalsIgnoreCase(arsuf)) {
                            alg = algs[i];
                            break;
                        }
                    }
                    if (alg == null) {
                        Application.getController().displayError(bundle.getString("unknown_alg_title"), bundle.getString("unknown_alg_text"));
                        return;
                    }
                    currentAlgorithm = alg;
                    if (!alg.initDecrypt(password)) {
                        Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                        return;
                    }
                    try {
                        ZipArchiveInputStream zis = null;
                        InputStream is = null;
                        if (EncryptionMode.getBestEncryptionMode(alg.getEncryptionMode()) == EncryptionMode.MODE_STREAM) {
                            is = alg.getDecryptionStream(new FileInputStream(archive));
                            if (is == null) {
                                Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                                return;
                            }
                        } else if (EncryptionMode.getBestEncryptionMode(alg.getEncryptionMode()) == EncryptionMode.MODE_BLOCK) {
                            is = new BlockCipherInputStream(new FileInputStream(archive), alg);
                            if (is == null) {
                                Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                                return;
                            }
                        }
                        zis = new ZipArchiveInputStream(is);
                        if (zis == null) {
                            Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                            return;
                        }
                        File outputDir = getTargetDirectory();
                        if (outputDir == null) {
                            return;
                        }
                        if (!outputDir.exists()) {
                            if (!outputDir.mkdir()) {
                                Application.getController().displayError(bundle.getString("output_dir_fail_title"), outputDir.getAbsolutePath() + " " + bundle.getString("output_dir_fail_text"));
                                return;
                            }
                        }
                        ZipArchiveEntry zae = null;
                        boolean gotEntries = false;
                        while ((zae = zis.getNextZipEntry()) != null) {
                            gotEntries = true;
                            File out = new File(outputDir, zae.getName());
                            if (out.exists()) {
                                if (!mayOverwrite(out)) {
                                    continue;
                                }
                            }
                            Application.getController().displayVerbose("writing to file: " + out.getAbsolutePath());
                            if (!out.getParentFile().exists()) {
                                out.getParentFile().mkdirs();
                            }
                            if (zae.isDirectory()) {
                                out.mkdir();
                                continue;
                            }
                            FileOutputStream os = new FileOutputStream(out);
                            long length = zae.getCompressedSize(), counter = 0;
                            Application.getController().displayVerbose("Length of zip entry " + zae.getName() + " is " + length + "b");
                            byte[] buffer = new byte[16384];
                            MessageDigest md = MessageDigest.getInstance("SHA-1");
                            DigestInputStream in = new DigestInputStream(zis, md);
                            while ((counter = in.read(buffer)) > 0) {
                                if (Thread.currentThread().isInterrupted()) {
                                    os.close();
                                    zis.close();
                                    Application.getController().notifyProgressFinished();
                                    resetModel(true);
                                    return;
                                }
                                os.write(buffer, 0, (int) counter);
                            }
                            os.close();
                            if (zae.getComment() != null && zae.getComment().length() > 0) {
                                if (Arrays.equals(md.digest(), new Base64().decode(zae.getComment()))) {
                                    Application.getController().displayVerbose("Hash of " + zae.getName() + ": " + new Base64().encodeToString(md.digest()));
                                    Application.getController().displayError("Hash Error", "The stored hash of the original file and the hash of the decrypted data do not match. Normally, this means that your data has been manipulated/damaged, but it can also happen if your Java Runtime has a bug in his hash functions.\nIT IS VERY IMPORTANT TO CHECK THE INTEGRITY OF YOUR DECRYPTED DATA!");
                                } else {
                                    Application.getController().displayVerbose("the hash of " + zae.getName() + " was verified succesfully");
                                }
                            }
                        }
                        if (!gotEntries) {
                            Application.getController().displayError(bundle.getString("error_no_entries_title"), bundle.getString("error_no_entries_text"));
                            outputDir.delete();
                        }
                        zis.close();
                        resetModel(false);
                    } catch (FileNotFoundException ex) {
                        Application.getController().displayError(bundle.getString("error_file_not_exist"), ex.getLocalizedMessage());
                    } catch (IOException ex) {
                        Application.getController().displayError(bundle.getString("error_generic_io"), ex.getLocalizedMessage());
                    } catch (NoSuchAlgorithmException ex) {
                        Application.getController().displayError(bundle.getString("unknown_alg_text"), ex.getLocalizedMessage());
                    }
                }
                Application.getController().notifyProgressFinished();
                resetModel(true);
            }
        };
        runningThread.start();
    }


            @Override
            public void run() {
                Application.getController().notifyProgressStarted();
                Application.getController().notifyProgressUpdated(-1);
                for (int f = 0; f < fileList.size(); f++) {
                    File archive = fileList.get(f);
                    String arname = archive.getName();
                    String arsuf = arname.substring(arname.lastIndexOf('.'), arname.length());
                    Algorithm alg = null;
                    Algorithm algs[] = algFactory.getAlgorithms();
                    for (int i = 0; i < algs.length; i++) {
                        if (algs[i].getSuffix().equalsIgnoreCase(arsuf)) {
                            alg = algs[i];
                            break;
                        }
                    }
                    if (alg == null) {
                        Application.getController().displayError(bundle.getString("unknown_alg_title"), bundle.getString("unknown_alg_text"));
                        return;
                    }
                    currentAlgorithm = alg;
                    if (!alg.initDecrypt(password)) {
                        Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                        return;
                    }
                    try {
                        ZipArchiveInputStream zis = null;
                        InputStream is = null;
                        if (EncryptionMode.getBestEncryptionMode(alg.getEncryptionMode()) == EncryptionMode.MODE_STREAM) {
                            is = alg.getDecryptionStream(new FileInputStream(archive));
                            if (is == null) {
                                Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                                return;
                            }
                        } else if (EncryptionMode.getBestEncryptionMode(alg.getEncryptionMode()) == EncryptionMode.MODE_BLOCK) {
                            is = new BlockCipherInputStream(new FileInputStream(archive), alg);
                            if (is == null) {
                                Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                                return;
                            }
                        }
                        zis = new ZipArchiveInputStream(is);
                        if (zis == null) {
                            Application.getController().displayError(bundle.getString("dec_init_fail_title"), bundle.getString("dec_init_fail_text"));
                            return;
                        }
                        File outputDir = getTargetDirectory();
                        if (outputDir == null) {
                            return;
                        }
                        if (!outputDir.exists()) {
                            if (!outputDir.mkdir()) {
                                Application.getController().displayError(bundle.getString("output_dir_fail_title"), outputDir.getAbsolutePath() + " " + bundle.getString("output_dir_fail_text"));
                                return;
                            }
                        }
                        ZipArchiveEntry zae = null;
                        boolean gotEntries = false;
                        while ((zae = zis.getNextZipEntry()) != null) {
                            gotEntries = true;
                            File out = new File(outputDir, zae.getName());
                            if (out.exists()) {
                                if (!mayOverwrite(out)) {
                                    continue;
                                }
                            }
                            Application.getController().displayVerbose("writing to file: " + out.getAbsolutePath());
                            if (!out.getParentFile().exists()) {
                                out.getParentFile().mkdirs();
                            }
                            if (zae.isDirectory()) {
                                out.mkdir();
                                continue;
                            }
                            FileOutputStream os = new FileOutputStream(out);
                            long length = zae.getCompressedSize(), counter = 0;
                            Application.getController().displayVerbose("Length of zip entry " + zae.getName() + " is " + length + "b");
                            byte[] buffer = new byte[16384];
                            MessageDigest md = MessageDigest.getInstance("SHA-1");
                            DigestInputStream in = new DigestInputStream(zis, md);
                            while ((counter = in.read(buffer)) > 0) {
                                if (Thread.currentThread().isInterrupted()) {
                                    os.close();
                                    zis.close();
                                    Application.getController().notifyProgressFinished();
                                    resetModel(true);
                                    return;
                                }
                                os.write(buffer, 0, (int) counter);
                            }
                            os.close();
                            if (zae.getComment() != null && zae.getComment().length() > 0) {
                                if (Arrays.equals(md.digest(), new Base64().decode(zae.getComment()))) {
                                    Application.getController().displayVerbose("Hash of " + zae.getName() + ": " + new Base64().encodeToString(md.digest()));
                                    Application.getController().displayError("Hash Error", "The stored hash of the original file and the hash of the decrypted data do not match. Normally, this means that your data has been manipulated/damaged, but it can also happen if your Java Runtime has a bug in his hash functions.\nIT IS VERY IMPORTANT TO CHECK THE INTEGRITY OF YOUR DECRYPTED DATA!");
                                } else {
                                    Application.getController().displayVerbose("the hash of " + zae.getName() + " was verified succesfully");
                                }
                            }
                        }
                        if (!gotEntries) {
                            Application.getController().displayError(bundle.getString("error_no_entries_title"), bundle.getString("error_no_entries_text"));
                            outputDir.delete();
                        }
                        zis.close();
                        resetModel(false);
                    } catch (FileNotFoundException ex) {
                        Application.getController().displayError(bundle.getString("error_file_not_exist"), ex.getLocalizedMessage());
                    } catch (IOException ex) {
                        Application.getController().displayError(bundle.getString("error_generic_io"), ex.getLocalizedMessage());
                    } catch (NoSuchAlgorithmException ex) {
                        Application.getController().displayError(bundle.getString("unknown_alg_text"), ex.getLocalizedMessage());
                    }
                }
                Application.getController().notifyProgressFinished();
                resetModel(true);
            }


    public static boolean postData(URL url, String parameters) {
        HttpURLConnection hpcon = null;
        try {
            hpcon = (HttpURLConnection) url.openConnection();
            hpcon.setRequestMethod("POST");
            hpcon.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
            hpcon.setUseCaches(false);
            hpcon.setDoInput(true);
            hpcon.setDoOutput(true);
            DataOutputStream printout = new DataOutputStream(hpcon.getOutputStream());
            printout.writeBytes(parameters);
            printout.flush();
            printout.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(hpcon.getInputStream()));
            String input;
            boolean success = false;
            while ((input = in.readLine()) != null) {
                if (input.contains("OK")) success = true;
            }
            return success;
        } catch (Exception e) {
            try {
                if (hpcon != null) hpcon.disconnect();
            } catch (Exception e2) {
            }
            return false;
        }
    }


    public static String getAnalysisServletOutput(String inputXml) {
        java.io.BufferedWriter bWriter = null;
        URLConnection connection = null;
        String resultString = "";
        bWriter = null;
        connection = null;
        String target = ServletConstant.ANALYSIS_SERVLET;
        String message = "\nTHIS MESSAGE IS SENT FROM THE CLIENT APPLET   \n\r";
        try {
            URL url = new URL(target);
            connection = (HttpURLConnection) url.openConnection();
            ((HttpURLConnection) connection).setRequestMethod("POST");
            connection.setDoOutput(true);
            bWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(connection.getOutputStream()));
            bWriter.write(message);
            bWriter.flush();
            bWriter.close();
            java.io.BufferedReader bReader = null;
            bReader = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
            String line;
            StringBuffer sb = new StringBuffer();
            while ((line = bReader.readLine()) != null) {
                sb.append(line);
            }
            resultString = sb.toString();
            bReader.close();
            ((HttpURLConnection) connection).disconnect();
        } catch (java.io.IOException ex) {
            resultString += ex.toString();
        } finally {
            if (bWriter != null) {
                try {
                    bWriter.close();
                } catch (Exception ex) {
                    resultString += ex.toString();
                }
            }
            if (connection != null) {
                try {
                    ((HttpURLConnection) connection).disconnect();
                } catch (Exception ex) {
                    resultString += ex.toString();
                }
            }
        }
        return resultString;
    }


    private void download(String fileName) {
        String filePath = Activator.showSaveDialog(fileName, new String[] { ".xls" });
        if (filePath != null) {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = this.getClass().getResourceAsStream("/" + fileName);
                out = new FileOutputStream(filePath);
                IOUtils.copy(in, out);
            } catch (IOException ioe) {
                Activator.showExceptionDialog(ioe);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e1) {
                        Activator.showExceptionDialog(e1);
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e1) {
                        Activator.showExceptionDialog(e1);
                    }
                }
            }
        }
    }


    public static void main(String[] args) throws Exception {
        dataList = new ArrayList<String>();
        System.setProperty("http.agent", Phex.getFullPhexVendor());
        URL url = new URL(listUrl);
        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();
        readData(inputStream);
        System.out.println("Total data read: " + dataList.size());
        inputStream.close();
        writeToOutputFile();
    }


    public static boolean napiUserCheck(String user, String pass) throws TimeoutException, InterruptedException, IOException {
        URLConnection conn = null;
        InputStream in = null;
        URL url = new URL("http://www.napiprojekt.pl/users_check.php?nick=" + user + "&pswd=" + pass);
        conn = url.openConnection(Global.getProxy());
        in = Timeouts.getInputStream(conn);
        byte[] buffer = new byte[1024];
        in.read(buffer, 0, 1024);
        if (in != null) {
            in.close();
        }
        String response = new String(buffer);
        if (response.indexOf("ok") == 0) {
            return true;
        } else {
            return false;
        }
    }


    public static AddUserResponse napiUserAdd(String user, String pass, String email) throws TimeoutException, InterruptedException, IOException {
        if (user.matches("^[a-zA-Z0-9]{2,20}$") == false) {
            return AddUserResponse.NAPI_ADD_USER_BAD_LOGIN;
        }
        if (pass.equals("")) {
            return AddUserResponse.NAPI_ADD_USER_BAD_PASS;
        }
        if (email.matches("^[a-zA-Z0-9\\-\\_]{1,30}@[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)+$") == false) {
            return AddUserResponse.NAPI_ADD_USER_BAD_EMAIL;
        }
        URLConnection conn = null;
        ClientHttpRequest httpPost = null;
        InputStreamReader responseStream = null;
        URL url = new URL("http://www.napiprojekt.pl/users_add.php");
        conn = url.openConnection(Global.getProxy());
        httpPost = new ClientHttpRequest(conn);
        httpPost.setParameter("login", user);
        httpPost.setParameter("haslo", pass);
        httpPost.setParameter("mail", email);
        httpPost.setParameter("z_programu", "true");
        responseStream = new InputStreamReader(httpPost.post(), "Cp1250");
        BufferedReader responseReader = new BufferedReader(responseStream);
        String response = responseReader.readLine();
        if (response.indexOf("login już istnieje") != -1) {
            return AddUserResponse.NAPI_ADD_USER_LOGIN_EXISTS;
        }
        if (response.indexOf("na podany e-mail") != -1) {
            return AddUserResponse.NAPI_ADD_USER_EMAIL_EXISTS;
        }
        if (response.indexOf("NPc0") == 0) {
            return AddUserResponse.NAPI_ADD_USER_OK;
        }
        return AddUserResponse.NAPI_ADD_USER_BAD_UNKNOWN;
    }


    public static void fileCopy(String src, String dst) {
        try {
            FileInputStream fis = new FileInputStream(src);
            FileOutputStream fos = new FileOutputStream(dst);
            int read = -1;
            byte[] buf = new byte[8192];
            while ((read = fis.read(buf)) != -1) {
                fos.write(buf, 0, read);
            }
            fos.flush();
            fos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void findAllProviders() {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Enumeration<URL> resources = loader.getResources("META-INF/services/" + PersistenceProvider.class.getName());
            Set<String> names = new HashSet<String>();
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                InputStream is = url.openStream();
                try {
                    names.addAll(providerNamesFromReader(new BufferedReader(new InputStreamReader(is))));
                } finally {
                    is.close();
                }
            }
            for (String s : names) {
                Class providerClass = loader.loadClass(s);
                providers.add((PersistenceProvider) providerClass.newInstance());
            }
        } catch (IOException e) {
            throw new PersistenceException(e);
        } catch (InstantiationException e) {
            throw new PersistenceException(e);
        } catch (IllegalAccessException e) {
            throw new PersistenceException(e);
        } catch (ClassNotFoundException e) {
            throw new PersistenceException(e);
        }
    }


    protected String doIt() throws java.lang.Exception {
        StringBuffer sql = null;
        int no = 0;
        String clientCheck = getWhereClause();
        if (m_deleteOldImported) {
            sql = new StringBuffer("DELETE I_BPartner " + "WHERE I_IsImported='Y'").append(clientCheck);
            no = DB.executeUpdateEx(sql.toString(), get_TrxName());
            log.fine("Delete Old Impored =" + no);
        }
        sql = new StringBuffer("UPDATE I_BPartner " + "SET AD_Client_ID = COALESCE (AD_Client_ID, ").append(m_AD_Client_ID).append(")," + " AD_Org_ID = COALESCE (AD_Org_ID, 0)," + " IsActive = COALESCE (IsActive, 'Y')," + " Created = COALESCE (Created, SysDate)," + " CreatedBy = COALESCE (CreatedBy, 0)," + " Updated = COALESCE (Updated, SysDate)," + " UpdatedBy = COALESCE (UpdatedBy, 0)," + " I_ErrorMsg = ' '," + " I_IsImported = 'N' " + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Reset=" + no);
        ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_BEFORE_VALIDATE);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET GroupValue=(SELECT MAX(Value) FROM C_BP_Group g WHERE g.IsDefault='Y'" + " AND g.AD_Client_ID=i.AD_Client_ID) ");
        sql.append("WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Group Default=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BP_Group_ID=(SELECT C_BP_Group_ID FROM C_BP_Group g" + " WHERE i.GroupValue=g.Value AND g.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_BP_Group_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Group=" + no);
        sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Group, ' " + "WHERE C_BP_Group_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.config("Invalid Group=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c" + " WHERE i.CountryCode=c.CountryCode AND c.AD_Client_ID IN (0, i.AD_Client_ID)) " + "WHERE C_Country_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Country=" + no);
        sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Country, ' " + "WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.config("Invalid Country=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "Set RegionName=(SELECT MAX(Name) FROM C_Region r" + " WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID" + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) ");
        sql.append("WHERE RegionName IS NULL AND C_Region_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Region Default=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r" + " WHERE r.Name=i.RegionName AND r.C_Country_ID=i.C_Country_ID" + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) " + "WHERE C_Region_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Region=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Region, ' " + "WHERE C_Region_ID IS NULL " + " AND EXISTS (SELECT * FROM C_Country c" + " WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.config("Invalid Region=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_Greeting_ID=(SELECT C_Greeting_ID FROM C_Greeting g" + " WHERE i.BPContactGreeting=g.Name AND g.AD_Client_ID IN (0, i.AD_Client_ID)) " + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Greeting=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Greeting, ' " + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.config("Invalid Greeting=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET (C_BPartner_ID,AD_User_ID)=" + "(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u " + "WHERE i.EMail=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) " + "WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Found EMail User=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p" + " WHERE i.Value=p.Value AND p.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL" + " AND I_IsImported='N'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Found BPartner=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET AD_User_ID=(SELECT AD_User_ID FROM AD_User c" + " WHERE i.ContactName=c.Name AND i.C_BPartner_ID=c.C_BPartner_ID AND c.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_BPartner_ID IS NOT NULL AND AD_User_ID IS NULL AND ContactName IS NOT NULL" + " AND I_IsImported='N'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Found Contact=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID" + " FROM C_BPartner_Location bpl INNER JOIN C_Location l ON (bpl.C_Location_ID=l.C_Location_ID)" + " WHERE i.C_BPartner_ID=bpl.C_BPartner_ID AND bpl.AD_Client_ID=i.AD_Client_ID" + " AND (i.Address1=l.Address1 OR (i.Address1 IS NULL AND l.Address1 IS NULL))" + " AND (i.Address2=l.Address2 OR (i.Address2 IS NULL AND l.Address2 IS NULL))" + " AND (i.City=l.City OR (i.City IS NULL AND l.City IS NULL))" + " AND (i.Postal=l.Postal OR (i.Postal IS NULL AND l.Postal IS NULL))" + " AND (i.Postal_Add=l.Postal_Add OR (l.Postal_Add IS NULL AND l.Postal_Add IS NULL))" + " AND i.C_Region_ID=l.C_Region_ID AND i.C_Country_ID=l.C_Country_ID) " + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL" + " AND I_IsImported='N'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Found Location=" + no);
        sql = new StringBuffer("UPDATE I_BPartner i " + "SET R_InterestArea_ID=(SELECT R_InterestArea_ID FROM R_InterestArea ia " + "WHERE i.InterestAreaName=ia.Name AND ia.AD_Client_ID=i.AD_Client_ID) " + "WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL" + " AND I_IsImported='N'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Set Interest Area=" + no);
        sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value is mandatory, ' " + "WHERE Value IS NULL " + " AND I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.config("Value is mandatory=" + no);
        ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_AFTER_VALIDATE);
        commitEx();
        if (p_IsValidateOnly) {
            return "Validated";
        }
        int noInsert = 0;
        int noUpdate = 0;
        sql = new StringBuffer("SELECT * FROM I_BPartner " + "WHERE I_IsImported='N'").append(clientCheck);
        sql.append(" ORDER BY Value, I_BPartner_ID");
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
            rs = pstmt.executeQuery();
            String Old_BPValue = "";
            MBPartner bp = null;
            MBPartnerLocation bpl = null;
            while (rs.next()) {
                String New_BPValue = rs.getString("Value");
                X_I_BPartner impBP = new X_I_BPartner(getCtx(), rs, get_TrxName());
                log.fine("I_BPartner_ID=" + impBP.getI_BPartner_ID() + ", C_BPartner_ID=" + impBP.getC_BPartner_ID() + ", C_BPartner_Location_ID=" + impBP.getC_BPartner_Location_ID() + ", AD_User_ID=" + impBP.getAD_User_ID());
                if (!New_BPValue.equals(Old_BPValue)) {
                    bp = null;
                    if (impBP.getC_BPartner_ID() == 0) {
                        if (impBP.getName() == null || impBP.getName().length() == 0) {
                            sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Invalid Name, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                            DB.executeUpdate(sql.toString(), get_TrxName());
                            continue;
                        }
                        bp = new MBPartner(impBP);
                        if (!impBP.get_ValueAsString("AD_Language").equals("")) bp.set_ValueOfColumn("AD_Language", impBP.get_ValueAsString("AD_Language"));
                        if (!impBP.get_ValueAsString("lbr_BPTypeBR").equals("")) bp.set_ValueOfColumn("lbr_BPTypeBR", impBP.get_ValueAsString("lbr_BPTypeBR"));
                        if (!impBP.get_ValueAsString("lbr_CNPJ").equals("")) {
                            Boolean ok = org.adempierelbr.validator.ValidatorBPartner.validaCNPJ(impBP.get_ValueAsString("lbr_CNPJ"));
                            if (ok) bp.set_ValueOfColumn("lbr_CNPJ", impBP.get_ValueAsString("lbr_CNPJ")); else {
                                sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Invalid CNPJ, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                                DB.executeUpdate(sql.toString(), get_TrxName());
                                continue;
                            }
                        }
                        if (!impBP.get_ValueAsString("lbr_CPF").equals("")) {
                            Boolean ok = org.adempierelbr.validator.ValidatorBPartner.validaCPF(impBP.get_ValueAsString("lbr_CPF"));
                            if (ok) bp.set_ValueOfColumn("lbr_CPF", impBP.get_ValueAsString("lbr_CPF")); else {
                                sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Invalid CPF, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                                DB.executeUpdate(sql.toString(), get_TrxName());
                                continue;
                            }
                        }
                        if (!impBP.get_ValueAsString("lbr_IE").equals("")) {
                            bp.set_ValueOfColumn("lbr_IE", impBP.get_ValueAsString("lbr_IE"));
                            bp.set_ValueOfColumn("lbr_IsIEExempt", false);
                        }
                        if (!impBP.get_ValueAsString("lbr_CCM").equals("")) bp.set_ValueOfColumn("lbr_CCM", impBP.get_ValueAsString("lbr_CCM"));
                        if (!impBP.get_ValueAsString("lbr_RG").equals("")) bp.set_ValueOfColumn("lbr_RG", impBP.get_ValueAsString("lbr_RG"));
                        if (!impBP.get_ValueAsString("isVendor").equals("")) bp.set_ValueOfColumn("isVendor", impBP.get_ValueAsString("isVendor"));
                        if (!impBP.get_ValueAsString("isCustomer").equals("")) bp.set_ValueOfColumn("isCustomer", impBP.get_ValueAsString("isCustomer"));
                        if (!impBP.get_ValueAsString("isSalesRep").equals("")) bp.set_ValueOfColumn("isSalesRep", impBP.get_ValueAsString("isSalesRep"));
                        ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT);
                        setTypeOfBPartner(impBP, bp);
                        if (bp.save()) {
                            impBP.setC_BPartner_ID(bp.getC_BPartner_ID());
                            log.finest("Insert BPartner - " + bp.getC_BPartner_ID());
                            noInsert++;
                        } else {
                            sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("(CASE WHEN (SELECT COUNT(*) FROM C_BPartner WHERE lbr_CNPJ IS NOT NULL AND lbr_CNPJ='").append(impBP.get_ValueAsString("lbr_CNPJ")).append("') > 0 THEN 'CNPJ Duplicado, ' WHEN (SELECT COUNT(*) FROM C_BPartner WHERE lbr_CPF IS NOT NULL AND lbr_CPF='").append(impBP.get_ValueAsString("lbr_CPF")).append("') > 0 THEN 'CPF Duplicado, ' END) ||").append("'Cannot Insert BPartner, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                            DB.executeUpdateEx(sql.toString(), get_TrxName());
                            continue;
                        }
                    } else {
                        bp = new MBPartner(getCtx(), impBP.getC_BPartner_ID(), get_TrxName());
                        if (impBP.getName() != null) {
                            bp.setName(impBP.getName());
                            bp.setName2(impBP.getName2());
                        }
                        if (impBP.getDUNS() != null) bp.setDUNS(impBP.getDUNS());
                        if (impBP.getTaxID() != null) bp.setTaxID(impBP.getTaxID());
                        if (impBP.getNAICS() != null) bp.setNAICS(impBP.getNAICS());
                        if (impBP.getDescription() != null) bp.setDescription(impBP.getDescription());
                        if (impBP.getC_BP_Group_ID() != 0) bp.setC_BP_Group_ID(impBP.getC_BP_Group_ID());
                        ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT);
                        if (!impBP.get_ValueAsString("AD_Language").equals("")) bp.set_ValueOfColumn("AD_Language", impBP.get_ValueAsString("AD_Language"));
                        if (!impBP.get_ValueAsString("lbr_BPTypeBR").equals("")) bp.set_ValueOfColumn("lbr_BPTypeBR", impBP.get_ValueAsString("lbr_BPTypeBR"));
                        if (!impBP.get_ValueAsString("lbr_CNPJ").equals("")) {
                            Boolean ok = org.adempierelbr.validator.ValidatorBPartner.validaCNPJ(impBP.get_ValueAsString("lbr_CNPJ"));
                            if (ok) bp.set_ValueOfColumn("lbr_CNPJ", impBP.get_ValueAsString("lbr_CNPJ")); else {
                                sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Invalid CNPJ, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                                DB.executeUpdate(sql.toString(), get_TrxName());
                                continue;
                            }
                        }
                        if (!impBP.get_ValueAsString("lbr_CPF").equals("")) {
                            Boolean ok = org.adempierelbr.validator.ValidatorBPartner.validaCPF(impBP.get_ValueAsString("lbr_CPF"));
                            if (ok) bp.set_ValueOfColumn("lbr_CPF", impBP.get_ValueAsString("lbr_CPF")); else {
                                sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Invalid CPF, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                                DB.executeUpdate(sql.toString(), get_TrxName());
                                continue;
                            }
                        }
                        if (!impBP.get_ValueAsString("lbr_IE").equals("")) bp.set_ValueOfColumn("lbr_IE", impBP.get_ValueAsString("lbr_IE"));
                        if (!impBP.get_ValueAsString("lbr_CCM").equals("")) bp.set_ValueOfColumn("lbr_CCM", impBP.get_ValueAsString("lbr_CCM"));
                        if (!impBP.get_ValueAsString("lbr_RG").equals("")) bp.set_ValueOfColumn("lbr_RG", impBP.get_ValueAsString("lbr_RG"));
                        if (!impBP.get_ValueAsString("isVendor").equals("")) bp.set_ValueOfColumn("isVendor", impBP.get_ValueAsString("isVendor"));
                        if (!impBP.get_ValueAsString("isCustomer").equals("")) bp.set_ValueOfColumn("isCustomer", impBP.get_ValueAsString("isCustomer"));
                        if (!impBP.get_ValueAsString("isSalesRep").equals("")) bp.set_ValueOfColumn("isSalesRep", impBP.get_ValueAsString("isSalesRep"));
                        setTypeOfBPartner(impBP, bp);
                        if (bp.save()) {
                            log.finest("Update BPartner - " + bp.getC_BPartner_ID());
                            noUpdate++;
                        } else {
                            sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Update BPartner, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                            DB.executeUpdateEx(sql.toString(), get_TrxName());
                            continue;
                        }
                    }
                    bpl = null;
                    if (impBP.getC_BPartner_Location_ID() != 0) {
                        bpl = new MBPartnerLocation(getCtx(), impBP.getC_BPartner_Location_ID(), get_TrxName());
                        MLocation location = new MLocation(getCtx(), bpl.getC_Location_ID(), get_TrxName());
                        location.setC_Country_ID(impBP.getC_Country_ID());
                        location.setC_Region_ID(impBP.getC_Region_ID());
                        location.setCity(impBP.getCity());
                        location.setAddress1(impBP.getAddress1());
                        location.setAddress2(impBP.getAddress2());
                        location.setAddress3(impBP.get_ValueAsString("Address3"));
                        location.setAddress4(impBP.get_ValueAsString("Address4"));
                        location.setPostal(impBP.getPostal());
                        location.setPostal_Add(impBP.getPostal_Add());
                        if (!location.save()) log.warning("Location not updated"); else bpl.setC_Location_ID(location.getC_Location_ID());
                        if (impBP.getPhone() != null) bpl.setPhone(impBP.getPhone());
                        if (impBP.getPhone2() != null) bpl.setPhone2(impBP.getPhone2());
                        if (impBP.getFax() != null) bpl.setFax(impBP.getFax());
                        ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT);
                        bpl.save();
                    } else if (impBP.getC_Country_ID() != 0 && impBP.getAddress1() != null && impBP.getCity() != null) {
                        MLocation location = new MLocation(getCtx(), impBP.getC_Country_ID(), impBP.getC_Region_ID(), impBP.getCity(), get_TrxName());
                        location.setAddress1(impBP.getAddress1());
                        location.setAddress2(impBP.getAddress2());
                        location.setAddress3(impBP.get_ValueAsString("Address3"));
                        location.setAddress4(impBP.get_ValueAsString("Address4"));
                        location.setPostal(impBP.getPostal());
                        location.setPostal_Add(impBP.getPostal_Add());
                        if (location.save()) log.finest("Insert Location - " + location.getC_Location_ID()); else {
                            rollback();
                            noInsert--;
                            sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert Location, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                            DB.executeUpdateEx(sql.toString(), get_TrxName());
                            continue;
                        }
                        bpl = new MBPartnerLocation(bp);
                        bpl.setC_Location_ID(location.getC_Location_ID());
                        bpl.setPhone(impBP.getPhone());
                        bpl.setPhone2(impBP.getPhone2());
                        bpl.setFax(impBP.getFax());
                        ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT);
                        if (bpl.save()) {
                            log.finest("Insert BP Location - " + bpl.getC_BPartner_Location_ID());
                            impBP.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
                        } else {
                            rollback();
                            noInsert--;
                            sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert BPLocation, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                            DB.executeUpdateEx(sql.toString(), get_TrxName());
                            continue;
                        }
                    }
                }
                Old_BPValue = New_BPValue;
                MUser user = null;
                if (impBP.getAD_User_ID() != 0) {
                    user = new MUser(getCtx(), impBP.getAD_User_ID(), get_TrxName());
                    if (user.getC_BPartner_ID() == 0) user.setC_BPartner_ID(bp.getC_BPartner_ID()); else if (user.getC_BPartner_ID() != bp.getC_BPartner_ID()) {
                        rollback();
                        noInsert--;
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'BP of User <> BP, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                    if (impBP.getC_Greeting_ID() != 0) user.setC_Greeting_ID(impBP.getC_Greeting_ID());
                    String name = impBP.getContactName();
                    if (name == null || name.length() == 0) name = impBP.getEMail();
                    user.setName(name);
                    if (impBP.getTitle() != null) user.setTitle(impBP.getTitle());
                    if (impBP.getContactDescription() != null) user.setDescription(impBP.getContactDescription());
                    if (impBP.getComments() != null) user.setComments(impBP.getComments());
                    if (impBP.getPhone() != null) user.setPhone(impBP.getPhone());
                    if (impBP.getPhone2() != null) user.setPhone2(impBP.getPhone2());
                    if (impBP.getFax() != null) user.setFax(impBP.getFax());
                    if (impBP.getEMail() != null) user.setEMail(impBP.getEMail());
                    if (impBP.getBirthday() != null) user.setBirthday(impBP.getBirthday());
                    if (bpl != null) user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
                    ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT);
                    if (user.save()) {
                        log.finest("Update BP Contact - " + user.getAD_User_ID());
                    } else {
                        rollback();
                        noInsert--;
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Update BP Contact, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                } else if (impBP.getContactName() != null || impBP.getEMail() != null) {
                    user = new MUser(bp);
                    if (impBP.getC_Greeting_ID() != 0) user.setC_Greeting_ID(impBP.getC_Greeting_ID());
                    String name = impBP.getContactName();
                    if (name == null || name.length() == 0) name = impBP.getEMail();
                    user.setName(name);
                    user.setTitle(impBP.getTitle());
                    user.setDescription(impBP.getContactDescription());
                    user.setComments(impBP.getComments());
                    user.setPhone(impBP.getPhone());
                    user.setPhone2(impBP.getPhone2());
                    user.setFax(impBP.getFax());
                    user.setEMail(impBP.getEMail());
                    user.setBirthday(impBP.getBirthday());
                    if (bpl != null) user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
                    ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT);
                    if (user.save()) {
                        log.finest("Insert BP Contact - " + user.getAD_User_ID());
                        impBP.setAD_User_ID(user.getAD_User_ID());
                    } else {
                        rollback();
                        noInsert--;
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert BPContact, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                }
                if (impBP.getR_InterestArea_ID() != 0 && user != null) {
                    MContactInterest ci = MContactInterest.get(getCtx(), impBP.getR_InterestArea_ID(), user.getAD_User_ID(), true, get_TrxName());
                    ci.save();
                }
                impBP.setI_IsImported(true);
                impBP.setProcessed(true);
                impBP.setProcessing(false);
                impBP.saveEx();
                commitEx();
            }
            DB.close(rs, pstmt);
        } catch (SQLException e) {
            rollback();
            throw new DBException(e, sql.toString());
        } finally {
            DB.close(rs, pstmt);
            rs = null;
            pstmt = null;
            sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='N', Updated=SysDate " + "WHERE I_IsImported<>'Y'").append(clientCheck);
            no = DB.executeUpdateEx(sql.toString(), get_TrxName());
            addLog(0, null, new BigDecimal(no), "@Errors@");
            addLog(0, null, new BigDecimal(noInsert), "@C_BPartner_ID@: @Inserted@");
            addLog(0, null, new BigDecimal(noUpdate), "@C_BPartner_ID@: @Updated@");
        }
        return "";
    }


    public static int proxy(java.net.URI uri, HttpServletRequest req, HttpServletResponse res) throws IOException {
        final HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setHost(uri.getHost());
        HttpMethodBase httpMethod = null;
        if (HttpRpcServer.METHOD_GET.equalsIgnoreCase(req.getMethod())) {
            httpMethod = new GetMethod(uri.toString());
            httpMethod.setFollowRedirects(true);
        } else if (HttpRpcServer.METHOD_POST.equalsIgnoreCase(req.getMethod())) {
            httpMethod = new PostMethod(uri.toString());
            final Enumeration parameterNames = req.getParameterNames();
            if (parameterNames != null) while (parameterNames.hasMoreElements()) {
                final String parameterName = (String) parameterNames.nextElement();
                for (String parameterValue : req.getParameterValues(parameterName)) ((PostMethod) httpMethod).addParameter(parameterName, parameterValue);
            }
            ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        }
        if (httpMethod == null) throw new IllegalArgumentException("Unsupported http request method");
        final int responseCode;
        final Enumeration headers = req.getHeaderNames();
        if (headers != null) while (headers.hasMoreElements()) {
            final String headerName = (String) headers.nextElement();
            final Enumeration headerValues = req.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                httpMethod.setRequestHeader(headerName, (String) headerValues.nextElement());
            }
        }
        final HttpState httpState = new HttpState();
        if (req.getCookies() != null) for (Cookie cookie : req.getCookies()) {
            String host = req.getHeader("Host");
            if (StringUtils.isEmpty(cookie.getDomain())) cookie.setDomain(StringUtils.isEmpty(host) ? req.getServerName() + ":" + req.getServerPort() : host);
            if (StringUtils.isEmpty(cookie.getPath())) cookie.setPath("/");
            httpState.addCookie(new org.apache.commons.httpclient.Cookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure()));
        }
        httpMethod.setQueryString(req.getQueryString());
        responseCode = (new HttpClient()).executeMethod(hostConfig, httpMethod, httpState);
        if (responseCode < 0) {
            httpMethod.releaseConnection();
            return responseCode;
        }
        if (httpMethod.getResponseHeaders() != null) for (Header header : httpMethod.getResponseHeaders()) res.setHeader(header.getName(), header.getValue());
        final InputStream in = httpMethod.getResponseBodyAsStream();
        final OutputStream out = res.getOutputStream();
        IOUtils.copy(in, out);
        out.flush();
        out.close();
        in.close();
        httpMethod.releaseConnection();
        return responseCode;
    }


    protected URLConnection openConnection(URL url) throws IOException {
        if (url == null) return null;
        if (!url.getProtocol().equals("nntp")) return null;
        if (m_connection != null) {
            if (m_connection.getURL().getHost().equals(url.getHost()) && (m_connection.getURL().getPort() == url.getPort()) && (m_connection.getURL().getUserInfo().equals(url.getUserInfo()))) {
                return m_connection;
            }
        }
        m_connection = new NNTPConnection(url);
        return m_connection;
    }


    private static boolean copyFile(File src, File dest) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fis != null) try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (fos != null) try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException {
        int k_blockSize = 1024;
        int byteCount;
        char[] buf = new char[k_blockSize];
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile));
        zos.setMethod(ZipOutputStream.DEFLATED);
        OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1");
        BufferedWriter bw = new BufferedWriter(osw);
        ZipEntry zot;
        ZipInputStream zis = new ZipInputStream(new FileInputStream(infile));
        InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1");
        BufferedReader br = new BufferedReader(isr);
        ZipEntry zit;
        while ((zit = zis.getNextEntry()) != null) {
            if (zit.getName().equals("content.xml")) {
                continue;
            }
            zot = new ZipEntry(zit.getName());
            zos.putNextEntry(zot);
            while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount);
            bw.flush();
            zos.closeEntry();
        }
        zos.putNextEntry(new ZipEntry("content.xml"));
        bw.flush();
        return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
    }


    @Override
    public AC3DModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {
        boolean baseURLWasNull = setBaseURLFromModelURL(url);
        AC3DModel model = loadModel(url.openStream(), skin);
        if (baseURLWasNull) {
            popBaseURL();
        }
        return (model);
    }


    public WordEntry[] getVariants(String word) throws MatchPackException {
        String upperWord = word.toUpperCase();
        if (variantsDictionary == null) {
            try {
                long start = System.currentTimeMillis();
                URL url = this.getClass().getResource("varlex.dic");
                ObjectInputStream si = new ObjectInputStream(url.openStream());
                variantsDictionary = (Map) si.readObject();
                long end = System.currentTimeMillis();
                System.out.println("loaded " + (end - start) + "ms");
                si.close();
            } catch (Exception e) {
                throw new MatchPackException("cannot load: varlex.dic " + e.getMessage());
            }
        }
        List l = (List) variantsDictionary.get(upperWord);
        if (l == null) {
            return new WordEntry[0];
        }
        return (WordEntry[]) l.toArray(new WordEntry[0]);
    }


    public void generateHtmlPage(String real_filename, String url_filename) {
        String str_content = "";
        URL m_url = null;
        URLConnection m_urlcon = null;
        try {
            m_url = new URL(url_filename);
            m_urlcon = m_url.openConnection();
            InputStream in_stream = m_urlcon.getInputStream();
            byte[] bytes = new byte[1];
            Vector v_bytes = new Vector();
            while (in_stream.read(bytes) != -1) {
                v_bytes.add(bytes);
                bytes = new byte[1];
            }
            byte[] all_bytes = new byte[v_bytes.size()];
            for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0];
            str_content = new String(all_bytes, "GBK");
        } catch (Exception urle) {
        }
        try {
            oaFileOperation file_control = new oaFileOperation();
            file_control.writeFile(str_content, real_filename, true);
            String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1);
            String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1);
            if (strUrlFileName.indexOf(".jsp") > 0) {
                strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp";
                m_url = new URL(strPath + strUrlFileName);
                m_url.openConnection();
            }
            intWriteFileCount++;
            intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount;
        } catch (Exception e) {
        }
        m_urlcon = null;
    }