    public void testSimpleHttpPostsHTTP10() throws Exception {
        int reqNo = 20;
        Random rnd = new Random();
        List testData = new ArrayList(reqNo);
        for (int i = 0; i < reqNo; i++) {
            int size = rnd.nextInt(5000);
            byte[] data = new byte[size];
            rnd.nextBytes(data);
            testData.add(data);
        }
        this.server.registerHandler("*", new HttpRequestHandler() {

            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
                if (request instanceof HttpEntityEnclosingRequest) {
                    HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
                    byte[] data = EntityUtils.toByteArray(incoming);
                    ByteArrayEntity outgoing = new ByteArrayEntity(data);
                    outgoing.setChunked(false);
                    response.setEntity(outgoing);
                } else {
                    StringEntity outgoing = new StringEntity("No content");
                    response.setEntity(outgoing);
                }
            }
        });
        this.server.start();
        this.client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        HttpHost host = new HttpHost("localhost", this.server.getPort());
        try {
            for (int r = 0; r < reqNo; r++) {
                if (!conn.isOpen()) {
                    Socket socket = new Socket(host.getHostName(), host.getPort());
                    conn.bind(socket, this.client.getParams());
                }
                BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
                byte[] data = (byte[]) testData.get(r);
                ByteArrayEntity outgoing = new ByteArrayEntity(data);
                post.setEntity(outgoing);
                HttpResponse response = this.client.execute(post, host, conn);
                assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion());
                byte[] received = EntityUtils.toByteArray(response.getEntity());
                byte[] expected = (byte[]) testData.get(r);
                assertEquals(expected.length, received.length);
                for (int i = 0; i < expected.length; i++) {
                    assertEquals(expected[i], received[i]);
                }
                if (!this.client.keepAlive(response)) {
                    conn.close();
                }
            }
            HttpConnectionMetrics cm = conn.getMetrics();
            assertEquals(reqNo, cm.getRequestCount());
            assertEquals(reqNo, cm.getResponseCount());
        } finally {
            conn.close();
            this.server.shutdown();
        }
    }


    public void testHttpPostsWithExpectContinue() throws Exception {
        int reqNo = 20;
        Random rnd = new Random();
        List testData = new ArrayList(reqNo);
        for (int i = 0; i < reqNo; i++) {
            int size = rnd.nextInt(5000);
            byte[] data = new byte[size];
            rnd.nextBytes(data);
            testData.add(data);
        }
        this.server.registerHandler("*", new HttpRequestHandler() {

            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
                if (request instanceof HttpEntityEnclosingRequest) {
                    HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
                    byte[] data = EntityUtils.toByteArray(incoming);
                    ByteArrayEntity outgoing = new ByteArrayEntity(data);
                    outgoing.setChunked(true);
                    response.setEntity(outgoing);
                } else {
                    StringEntity outgoing = new StringEntity("No content");
                    response.setEntity(outgoing);
                }
            }
        });
        this.server.start();
        this.client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        HttpHost host = new HttpHost("localhost", this.server.getPort());
        try {
            for (int r = 0; r < reqNo; r++) {
                if (!conn.isOpen()) {
                    Socket socket = new Socket(host.getHostName(), host.getPort());
                    conn.bind(socket, this.client.getParams());
                }
                BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
                byte[] data = (byte[]) testData.get(r);
                ByteArrayEntity outgoing = new ByteArrayEntity(data);
                outgoing.setChunked(true);
                post.setEntity(outgoing);
                HttpResponse response = this.client.execute(post, host, conn);
                byte[] received = EntityUtils.toByteArray(response.getEntity());
                byte[] expected = (byte[]) testData.get(r);
                assertEquals(expected.length, received.length);
                for (int i = 0; i < expected.length; i++) {
                    assertEquals(expected[i], received[i]);
                }
                if (!this.client.keepAlive(response)) {
                    conn.close();
                }
            }
            HttpConnectionMetrics cm = conn.getMetrics();
            assertEquals(reqNo, cm.getRequestCount());
            assertEquals(reqNo, cm.getResponseCount());
        } finally {
            conn.close();
            this.server.shutdown();
        }
    }


    public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException {
        String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID");
        String tempUploadDir = MewitProperties.getTemporaryUploadDirectory();
        if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) {
            tempUploadDir += "\\";
        }
        String fileName = null;
        int position = file.getOriginalFilename().lastIndexOf(".");
        if (position <= 0) {
            fileName = java.util.UUID.randomUUID().toString();
        } else {
            fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position);
        }
        File outputFile = new File(tempUploadDir, fileName);
        log(INFO, "writing the content of uploaded file to: " + outputFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        IOUtils.copy(file.getInputStream(), fos);
        file.getInputStream().close();
        fos.close();
        return doUploadFile(sessionId, outputFile, file.getOriginalFilename());
    }


    private String doUploadFile(String sessionId, File file, String originalFileName) throws UnsupportedEncodingException, IOException {
        log(INFO, sessionId);
        log(INFO, file.getPath());
        DefaultHttpClient httpclient = new DefaultHttpClient();
        UploadFileRequest request = new UploadFileRequest();
        request.setSessionId(sessionId);
        request.setDirectory(UUID.randomUUID().toString());
        request.setFileName(originalFileName);
        URL url = file.toURI().toURL();
        URLConnection urlCon = url.openConnection();
        XStream writer = new XStream();
        writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
        writer.alias("UploadFileRequest", UploadFileRequest.class);
        XStream reader = new XStream();
        reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
        reader.alias("UploadFileResponse", UploadFileResponse.class);
        String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8");
        HttpPost httppost = new HttpPost(MewitProperties.getMewitUrl() + "/resources/uploadFile?REQUEST=" + strRequest);
        FileEntity fileEntity = new FileEntity(file, urlCon.getContentType());
        httppost.setEntity(fileEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8");
            log(INFO, result);
            UploadFileResponse oResponse = (UploadFileResponse) reader.fromXML(result);
            return oResponse.getFile();
        }
        return null;
    }


public void readPage(String search) {
        InputStream is = null;
        try {
            URL url = new URL("http://www.english-german-dictionary.com/index.php?search=" + search.trim());
            is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is, "ISO-8859-15");
            Scanner scan = new Scanner(isr);
            String str = new String();
            String translate = new String();
            String temp;
            while (scan.hasNextLine()) {
                temp = (scan.nextLine());
                if (temp.contains("")) {
                    int anfang = temp.indexOf("-->") + 3;
                    temp = temp.substring(anfang);
                    temp = temp.substring(0, temp.indexOf("


    private void album(String albumTitle, String albumNbSong, URL url) {
        try {
            if (color == SWT.COLOR_WHITE) {
                color = SWT.COLOR_GRAY;
            } else {
                color = SWT.COLOR_WHITE;
            }
            url.openConnection();
            InputStream is = url.openStream();
            Image coverPicture = new Image(this.getDisplay(), is);
            Composite albumComposite = new Composite(main, SWT.NONE);
            albumComposite.setLayout(new FormLayout());
            FormData data = new FormData();
            data.left = new FormAttachment(0, 5);
            data.right = new FormAttachment(100, -5);
            if (prevCompo == null) {
                data.top = new FormAttachment(0, 0);
            } else {
                data.top = new FormAttachment(prevCompo, 0, SWT.BOTTOM);
            }
            albumComposite.setLayoutData(data);
            albumComposite.setBackground(Display.getDefault().getSystemColor(color));
            Label cover = new Label(albumComposite, SWT.LEFT);
            cover.setText("cover");
            cover.setImage(coverPicture);
            data = new FormData(75, 75);
            cover.setLayoutData(data);
            Label title = new Label(albumComposite, SWT.CENTER);
            title.setFont(new Font(this.getDisplay(), "Arial", 10, SWT.BOLD));
            title.setText(albumTitle);
            data = new FormData();
            data.bottom = new FormAttachment(50, -5);
            data.left = new FormAttachment(cover, 5);
            title.setBackground(Display.getDefault().getSystemColor(color));
            title.setLayoutData(data);
            Label nbSong = new Label(albumComposite, SWT.LEFT | SWT.BOLD);
            nbSong.setFont(new Font(this.getDisplay(), "Arial", 8, SWT.ITALIC));
            nbSong.setText("Release date : " + albumNbSong);
            data = new FormData();
            data.top = new FormAttachment(50, 5);
            data.left = new FormAttachment(cover, 5);
            nbSong.setBackground(Display.getDefault().getSystemColor(color));
            nbSong.setLayoutData(data);
            prevCompo = albumComposite;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public HttpResponse execute() throws IOException {
        URL _url = getUrl();
        if (_url == null) throw new IOException("url not set");
        Proxy _proxy = getProxy();
        URLConnection urlConn = _proxy == null ? _url.openConnection() : _url.openConnection(_proxy);
        HttpURLConnection httpUrlConn = urlConn instanceof HttpURLConnection ? (HttpURLConnection) urlConn : null;
        HttpsURLConnection httpsUrlConn = urlConn instanceof HttpsURLConnection ? (HttpsURLConnection) urlConn : null;
        if (httpUrlConn != null) {
            String reqMethod = getRequestMethod();
            httpUrlConn.setRequestMethod(reqMethod);
        }
        if (httpsUrlConn != null) {
            SSLSocketFactory sslF = getSSLSocketFactory();
            if (sslF != null) httpsUrlConn.setSSLSocketFactory(sslF);
        }
        setRequestHeader(urlConn);
        String contType = getContentType();
        int len = getContentLength();
        InputStream postDataStream = getContentInputStream();
        if (contType != null && postDataStream != null) urlConn.setRequestProperty(HttpHeaders.contentType, contType);
        if (len >= 0 && postDataStream != null) urlConn.setRequestProperty(HttpHeaders.contentLength, "" + len);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(postDataStream != null);
        urlConn.setUseCaches(isUseCaches());
        urlConn.setConnectTimeout(getConnectTimeout());
        urlConn.setReadTimeout(getReadTimeout());
        if (getInstanceFollowRedirects() != null && httpUrlConn != null) {
            httpUrlConn.setInstanceFollowRedirects(getInstanceFollowRedirects());
        }
        if (getIfModifiedSince() != null && httpUrlConn != null) {
            httpUrlConn.setIfModifiedSince(getIfModifiedSince());
        }
        urlConn.connect();
        if (postDataStream != null) {
            OutputStream output = urlConn.getOutputStream();
            FileUtil.copyAllData(postDataStream, output);
            output.flush();
            output.close();
            postDataStream.close();
        }
        HttpResponse response = createResponse(urlConn);
        if (isDisconnect() && httpUrlConn != null) {
            httpUrlConn.disconnect();
        }
        return response;
    }


    private static StringBuffer downloadHTTPPage(URL url) throws Exception {
        URLConnection con = url.openConnection();
        con.setReadTimeout(0);
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        while (null != (line = br.readLine())) {
            sb.append(line);
        }
        br.close();
        return sb;
    }


    private String fetch(String urlstring) {
        String content = "";
        try {
            URL url = new URL(urlstring);
            InputStream is = url.openStream();
            BufferedReader d = new BufferedReader(new InputStreamReader(is));
            String s;
            while (null != (s = d.readLine())) {
                content = content + s + "\n";
            }
            is.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return content;
    }


    public static String[] getURLListFromResource(String resourceName, String regExFilter, boolean firstNoEmptyMatched) {
        String[] urlArray;
        Vector<String> urlVector = new Vector<String>();
        try {
            ClassLoader classLoader = MqatMain.class.getClassLoader();
            URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
            Enumeration e = urlClassLoader.findResources(resourceName);
            for (; e.hasMoreElements(); ) {
                URL url = (URL) e.nextElement();
                if ("file".equals(url.getProtocol())) {
                    File file = new File(url.getPath());
                    File[] fileList = file.listFiles();
                    if (fileList != null) {
                        for (int i = 0; i < fileList.length; i++) {
                            String urlStr = fileList[i].toURL().toString();
                            if (urlStr.matches(regExFilter)) {
                                urlVector.add(urlStr);
                            }
                        }
                    }
                } else if ("jar".equals(url.getProtocol())) {
                    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
                    JarFile jarFile = jarConnection.getJarFile();
                    Enumeration jarEntries = jarFile.entries();
                    for (; jarEntries.hasMoreElements(); ) {
                        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
                        if (!jarEntry.isDirectory()) {
                            String urlStr = url.toString().substring(0, url.toString().lastIndexOf('!') + 1);
                            urlStr += "/" + jarEntry;
                            if (urlStr.matches(regExFilter)) {
                                urlVector.add(urlStr);
                            }
                        }
                    }
                }
                if (!urlVector.isEmpty() && firstNoEmptyMatched) {
                    break;
                }
            }
        } catch (Exception ex) {
            ExceptionHandler.handle(ex, ExceptionHandler.NO_VISUAL);
        }
        urlArray = urlVector.toArray(new String[urlVector.size()]);
        return urlArray;
    }


    private String copyTutorial() throws IOException {
        File inputFile = new File(getFilenameForOriginalTutorial());
        File outputFile = new File(getFilenameForCopiedTutorial());
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
        return getFilenameForCopiedTutorial();
    }


    public static String crypt(String senha) {
        String md5 = null;
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(CRYPT_ALGORITHM);
            md.update(senha.getBytes());
            Hex hex = new Hex();
            md5 = new String(hex.encode(md.digest()));
        } catch (NoSuchAlgorithmException e) {
            logger.error(ResourceUtil.getLOGMessage("_nls.mensagem.geral.log.crypt.no.such.algorithm", CRYPT_ALGORITHM));
        }
        return md5;
    }


    public static void copy(File src, File dst) throws IOException {
        FileInputStream fIn = null;
        FileOutputStream fOut = null;
        FileChannel sIn = null;
        FileChannel sOut = null;
        try {
            fIn = new FileInputStream(src);
            try {
                fOut = new FileOutputStream(dst);
                try {
                    sIn = fIn.getChannel();
                    sOut = fOut.getChannel();
                    sOut.transferFrom(sIn, 0, sIn.size());
                } finally {
                    if (sIn != null) {
                        sIn.close();
                    }
                    if (sOut != null) {
                        sOut.close();
                    }
                }
            } finally {
                if (fOut != null) {
                    fOut.close();
                }
            }
        } finally {
            if (fIn != null) {
                fIn.close();
            }
        }
    }


    private static ArrayList<String> YahooSearch(String query) {
        ArrayList<String> yahooSearchResults = new ArrayList<String>();
        try {
            String request = "http://boss.yahooapis.com/ysearch/web/v1/" + URLEncoder.encode("Java example for " + query, "UTF-8") + "?appid=zfau5aPV34ETbq9mWU0ui5e04y0rIewg1zwvzHb1tGoBFK2nSCU1SKS2D4zphh2rd3Wf" + "&format=xml&count=30&type=-msoffice,-pdf";
            URL url = new URL(request);
            System.out.println("Host : " + url.getHost());
            url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            String finalContents = "";
            while ((inputLine = reader.readLine()) != null) {
                finalContents += "\n" + inputLine;
            }
            Document doc = Jsoup.parse(finalContents);
            Elements eles = doc.getElementsByTag("url");
            for (Element ele : eles) {
                yahooSearchResults.add(ele.text());
                System.out.println("YahooResult: " + ele.text());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return yahooSearchResults;
    }


    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();
        }
    }


    private String getAuthUrlString(String account, String password) throws IOException, NoSuchAlgorithmException {
        Map<String, String> dict = retrieveLoginPage();
        if (dict == null) {
            return null;
        }
        StringBuilder url = new StringBuilder("/config/login?login=");
        url.append(account);
        url.append("&passwd=");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(password.getBytes(), 0, password.length());
        byte[] result = md5.digest();
        for (int i = 0; i < 16; i++) {
            url.append(StringUtil.toHex2(result[i]));
        }
        String md5chal = dict.get(".challenge");
        md5 = MessageDigest.getInstance("MD5");
        md5.update(md5chal.getBytes(), 0, md5chal.length());
        result = md5.digest();
        for (int i = 0; i < 16; i++) {
            url.append(StringUtil.toHex2(result[i]));
        }
        Iterator<String> j = dict.keySet().iterator();
        while (j.hasNext()) {
            String key = j.next();
            String value = dict.get(key);
            if (!key.equals("passwd")) {
                if (key.equals(".save") || key.equals(".js")) {
                    url.append("&" + key + "=1");
                } else if (key.equals(".challenge")) {
                    url.append("&" + key + "=" + value);
                } else {
                    String u = URLEncoder.encode(value, "UTF-8");
                    url.append("&" + key + "=" + u);
                }
            }
        }
        url.append("&");
        url.append(".hash=1");
        url.append("&");
        url.append(".md5=1");
        return url.toString();
    }


    public static boolean isCodebaseDownloadable(Properties p) {
        class CodebaseData {

            String file;

            boolean success = true;
        }
        String codebase = p.getProperty("java.rmi.server.codebase", null);
        if (null == codebase) {
            if (logger.isDebugEnabled()) logger.debug("java.rmi.server.codebase = null (return false)");
            return false;
        }
        try {
            URL cbUrl = new URL(codebase);
            String protocol = cbUrl.getProtocol();
            String filename = cbUrl.getFile();
            if (logger.isDebugEnabled()) {
                logger.debug("Verifying java.rmi.server.codebase setting(s)...");
                logger.debug("Codebase = " + cbUrl.toString());
            }
            if (protocol.equals("http")) {
                if (filename.indexOf("http") == -1) {
                    try {
                        int size = cbUrl.openConnection().getContentLength();
                        if (logger.isDebugEnabled()) logger.debug("Checking " + cbUrl + " : OK");
                        return true;
                    } catch (IOException e) {
                        if (logger.isDebugEnabled()) logger.debug("Checking " + cbUrl + " : FAIL");
                        return false;
                    } finally {
                        if (logger.isDebugEnabled()) logger.debug("Verifying java.rmi.server.codebase setting(s)... Done!");
                    }
                } else {
                    ArrayList files = new ArrayList();
                    StringTokenizer st = new StringTokenizer(codebase);
                    URL url = null;
                    String part = null;
                    CodebaseData data = null;
                    while (st.hasMoreTokens()) {
                        part = st.nextToken();
                        url = new URL(part);
                        data = new CodebaseData();
                        try {
                            int len = url.openConnection().getContentLength();
                            if (len == -1) {
                                data.success = false;
                                data.file = part;
                            } else {
                                data.file = part;
                            }
                        } catch (IOException e) {
                            data.success = false;
                        }
                        files.add(data);
                    }
                    String wrong = null;
                    CodebaseData codebaseData = null;
                    boolean allOK = true;
                    int errorFiles = 0;
                    for (int i = 0; i < files.size(); i++) {
                        codebaseData = (CodebaseData) files.get(i);
                        if (!codebaseData.success) {
                            wrong += " " + codebaseData.file;
                            ++errorFiles;
                            allOK = false;
                        }
                        if (logger.isDebugEnabled()) logger.debug((i + 1) + ". Checking " + codebaseData.file + " : " + (codebaseData.success ? "OK" : "FAIL"));
                    }
                    if (errorFiles == 0) {
                        if (logger.isDebugEnabled()) logger.debug("All entries can be downloaded successfully!");
                    } else {
                        logger.error(errorFiles + " of " + files.size() + " entries can *not* be downloaded successfully!");
                    }
                    if (logger.isDebugEnabled()) logger.debug("Verifying java.rmi.server.codebase setting(s)... Done!");
                    if (allOK) {
                        return true;
                    } else {
                        return false;
                    }
                }
            } else if (protocol.equalsIgnoreCase("file")) {
                if (logger.isDebugEnabled()) logger.debug("'file' protocol not supported for JSF");
            }
        } catch (MalformedURLException e) {
            logger.debug(e.getMessage());
            return false;
        }
        return false;
    }


    static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) {
        List<String> list = new ArrayList<String>();
        ZipFile zipFile = readZipFile(zipFileLocation);
        FileOutputStream output = null;
        InputStream inputStream = null;
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
        try {
            while (entries.hasMoreElements()) {
                java.util.zip.ZipEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (entryName != null && entryName.toLowerCase().endsWith(fileType)) {
                    inputStream = zipFile.getInputStream(entry);
                    String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/"));
                    File file = new File(fileName);
                    output = new FileOutputStream(file);
                    IOUtils.copy(inputStream, output);
                    list.add(fileName);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (output != null) output.close();
                if (inputStream != null) inputStream.close();
                if (zipFile != null) zipFile.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return list;
    }


    public boolean setTraceUrl(String s) {
        try {
            url = new URL(s);
            istream = url.openConnection();
            last_contentLenght = 0;
            reader = new BufferedReader(new InputStreamReader(istream.getInputStream()));
        } catch (MalformedURLException malformedurlexception) {
            System.out.println("Trace2Png: MalformedURLException: " + s);
            return false;
        } catch (IOException ioexception) {
            System.out.println("Trace2Png: IOException: " + s);
            return false;
        }
        trace = t2pNewTrace();
        return true;
    }


    public int readLines() {
        int i = 0;
        if (istream == null) return 0;
        try {
            String s1;
            if ((new String("http")).compareTo(url.getProtocol()) == 0) {
                istream = url.openConnection();
                if (last_contentLenght != istream.getContentLength()) {
                    last_contentLenght = istream.getContentLength();
                    istream = url.openConnection();
                    istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-");
                    System.out.println("Trace2Png: ContentLength: " + Integer.toString(istream.getContentLength()));
                    reader = new BufferedReader(new InputStreamReader(istream.getInputStream()));
                    String s;
                    while ((s = reader.readLine()) != null) {
                        bytes_read = bytes_read + s.length() + 1;
                        t2pProcessLine(trace, s);
                        i++;
                    }
                }
            } else {
                while ((s1 = reader.readLine()) != null) {
                    bytes_read = bytes_read + s1.length() + 1;
                    t2pProcessLine(trace, s1);
                    i++;
                }
            }
            t2pHandleEventPairs(trace);
            t2pSort(trace, sortby);
        } catch (IOException ioexception) {
            System.out.println("Trace2Png: IOException !!!");
        }
        return i;
    }


    private void publish() {
        if (uploadPrototypeBox.isSelected()) {
            try {
                URL url = new URL(prototypeURLField.getText());
                prototypeURLField.recordText();
                PrintStream ps;
                HttpURLConnection huc = null;
                if (url.getProtocol().equals("file")) {
                    ps = new PrintStream(new FileOutputStream(url.getFile()));
                } else {
                    URLConnection urlc = url.openConnection();
                    urlc.setDoOutput(true);
                    if (urlc instanceof HttpURLConnection) {
                        huc = ((HttpURLConnection) urlc);
                        huc.setRequestMethod("PUT");
                    }
                    ps = new PrintStream(urlc.getOutputStream());
                }
                target.writePrototype(ps);
                if (huc != null) {
                    huc.getResponseCode();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e, "Error Uploading Prototype", JOptionPane.ERROR_MESSAGE);
            }
        }
        if (postMetadataBox.isSelected()) {
            try {
                Hashtable env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, directoryURLField.getText());
                env.put(Context.SECURITY_PRINCIPAL, directoryPrincipalField.getText());
                env.put(Context.SECURITY_CREDENTIALS, directoryCredentialsField.getText());
                InitialDirContext dirContext = new InitialDirContext(env);
                Preferences prefs = Preferences.userNodeForPackage(getClass());
                prefs.put("directoryURL", directoryURLField.getText());
                prefs.put("directoryPrincipal", directoryPrincipalField.getText());
                prefs.put("directoryCredentials", directoryCredentialsField.getText());
                BasicAttributes attr = new BasicAttributes();
                attr.put(OBJECT_CLASS, RDS_RESOURCE);
                attr.put(CONTENT_TYPE, PROTOTYPE_TYPE);
                if (uploadPrototypeBox.isSelected()) {
                    attr.put(IMPLEMENTATION_URL, prototypeURLField.getText());
                }
                DefaultTableModel dtm = (DefaultTableModel) attributesTable.getModel();
                Preferences attrPrefs = prefs.node("attributes");
                for (int i = 0; i < dtm.getRowCount(); i++) {
                    attr.put((String) dtm.getValueAt(i, 0), (String) dtm.getValueAt(i, 1));
                    attrPrefs.put((String) dtm.getValueAt(i, 0), (String) dtm.getValueAt(i, 1));
                }
                NameParser np = dirContext.getNameParser("");
                Enumeration comps = new ResourceName(prototypeNameField.getText()).getAll();
                prototypeNameField.recordText();
                Name resourcedn = np.parse("");
                while (comps.hasMoreElements()) {
                    resourcedn.add(RC + "=" + (String) comps.nextElement());
                    try {
                        dirContext.createSubcontext(resourcedn);
                    } catch (NameAlreadyBoundException nabe) {
                    }
                }
                dirContext.modifyAttributes(resourcedn, DirContext.REPLACE_ATTRIBUTE, attr);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e, "Error Posting Metadata", JOptionPane.ERROR_MESSAGE);
            }
        }
    }


    public static void copyFile(File src, File dst) throws IOException {
        LOGGER.info("Copying file '" + src.getAbsolutePath() + "' to '" + dst.getAbsolutePath() + "'");
        FileChannel in = null;
        FileChannel out = null;
        try {
            FileInputStream fis = new FileInputStream(src);
            in = fis.getChannel();
            FileOutputStream fos = new FileOutputStream(dst);
            out = fos.getChannel();
            out.transferFrom(in, 0, in.size());
        } finally {
            try {
                if (in != null) in.close();
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, e.getMessage(), e);
                }
            }
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String theString = new String("");
        try {
            HttpResponse response = httpClient.execute(request);
            HttpEntity responseEntity = response.getEntity();
            InputStream stream = responseEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            Vector<String> vectorOfStrings = new Vector<String>();
            String tempString = new String();
            String tempStringAgent = new String();
            String tempStringClient = new String();
            String tempStringRoute = new String();
            String tempStringZone = new String();
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            stream.close();
            theString = builder.toString();
            JSONObject json = new JSONObject(theString);
            Log.i("_GetClient_", "<jsonobject> \n " + json.toString() + " \n </jsonobject>");
            this.dm = new DataManipulator(this);
            JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult");
            for (int i = 0; i < nameArray.length(); i++) {
                tempStringAgent = nameArray.getJSONObject(i).getString("Agent");
                tempStringClient = nameArray.getJSONObject(i).getString("Client");
                tempStringRoute = nameArray.getJSONObject(i).getString("Route");
                tempStringZone = nameArray.getJSONObject(i).getString("Zone");
                Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n");
                Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n");
                Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n");
                Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n");
                this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone);
                tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone");
                vectorOfStrings.add(new String(tempString));
            }
            int orderCount = vectorOfStrings.size();
            String[] orderTimeStamps = new String[orderCount];
            vectorOfStrings.copyInto(orderTimeStamps);
            setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void nuovoAcquisto(int quantita, Date d, double price, int id) throws SQLException {
        MyDBConnection c = new MyDBConnection();
        c.init();
        Connection conn = c.getMyConnection();
        PreparedStatement ps = conn.prepareStatement(insertAcquisto);
        ps.setInt(1, quantita);
        ps.setDate(2, d);
        ps.setDouble(3, price);
        ps.setInt(4, id);
        ps.executeUpdate();
        double newPrice = price;
        int newQ = quantita;
        ResultSet rs = MyDBConnection.executeQuery(queryPrezzo.replace("?", "" + id), conn);
        if (rs.next()) {
            int oldQ = rs.getInt(1);
            double oldPrice = rs.getDouble(2);
            newQ = quantita + oldQ;
            newPrice = (oldPrice * oldQ + price * quantita) / newQ;
            updatePortafoglio(conn, newPrice, newQ, id);
        } else insertPortafoglio(conn, id, newPrice, newQ);
        try {
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw new SQLException("Effettuato rollback dopo " + e.getMessage());
        } finally {
            c.close();
        }
    }


    public static boolean update(String user, String pass, String channelString, String globalIP) {
        FTPClient ftp = new FTPClient();
        int reply;
        try {
            ftp.connect("witna.co.uk", 21);
            ftp.login(user, pass);
            reply = ftp.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                updateChannelList(ftp, channelString);
                if (!ipUpdated) {
                    ipUpdated = updateMasterChannelIP(ftp, globalIP);
                }
                ftp.disconnect();
                return true;
            } else {
                ftp.disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException {
        StringBuffer encrypted = new StringBuffer();
        java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(plaintext.getBytes());
        byte[] digestArray = digest.digest();
        for (int i = 0; i < digestArray.length; i++) {
            encrypted.append(byte2hex(digestArray[i]));
        }
        setEncryptedPassword(encrypted.toString());
    }


    public static List importDate(Report report, TradingDate date) throws ImportExportException {
        List quotes = new ArrayList();
        String urlString = constructURL(date);
        EODQuoteFilter filter = new MetaStockQuoteFilter();
        PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings();
        try {
            URL url = new URL(urlString);
            InputStreamReader input = new InputStreamReader(url.openStream());
            BufferedReader bufferedInput = new BufferedReader(input);
            String line = null;
            do {
                line = bufferedInput.readLine();
                if (line != null) {
                    try {
                        EODQuote quote = filter.toEODQuote(line);
                        quotes.add(quote);
                        verify(report, quote);
                    } catch (QuoteFormatException e) {
                        report.addError(Locale.getString("DFLOAT_DISPLAY_URL") + ":" + date + ":" + Locale.getString("ERROR") + ": " + e.getMessage());
                    }
                }
            } while (line != null);
            bufferedInput.close();
        } catch (BindException e) {
            throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage()));
        } catch (ConnectException e) {
            throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage()));
        } catch (UnknownHostException e) {
            throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage()));
        } catch (NoRouteToHostException e) {
            throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage()));
        } catch (MalformedURLException e) {
            throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port));
        } catch (FileNotFoundException e) {
            report.addError(Locale.getString("FLOAT_DISPLAY_URL") + ":" + date + ":" + Locale.getString("ERROR") + ": " + Locale.getString("NO_QUOTES_FOUND"));
        } catch (IOException e) {
            throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES"));
        }
        return quotes;
    }


    public void register(MinecraftSession session, String username, String verificationKey) {
        if (Configuration.getConfiguration().isVerifyingNames()) {
            long salt = HeartbeatManager.getHeartbeatManager().getSalt();
            String hash = new StringBuilder().append(String.valueOf(salt)).append(username).toString();
            MessageDigest digest;
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("No MD5 algorithm!");
            }
            digest.update(hash.getBytes());
            if (!verificationKey.equals(new BigInteger(1, digest.digest()).toString(16))) {
                session.getActionSender().sendLoginFailure("Illegal name.");
                return;
            }
        }
        char[] nameChars = username.toCharArray();
        for (char nameChar : nameChars) {
            if (nameChar < ' ' || nameChar > '\177') {
                session.getActionSender().sendLoginFailure("Invalid name!");
                return;
            }
        }
        for (Player p : playerList.getPlayers()) {
            if (p.getName().equalsIgnoreCase(username)) {
                p.getSession().getActionSender().sendLoginFailure("Logged in from another computer.");
                break;
            }
        }
        final Player player = new Player(session, username);
        if (!playerList.add(player)) {
            player.getSession().getActionSender().sendLoginFailure("Too many players online!");
            return;
        }
        session.setPlayer(player);
        final Configuration c = Configuration.getConfiguration();
        session.getActionSender().sendLoginResponse(Constants.PROTOCOL_VERSION, c.getName(), c.getMessage(), false);
        LevelGzipper.getLevelGzipper().gzipLevel(session);
    }


    public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException {
        File d = new File(dir);
        if (!d.isDirectory()) throw new IllegalArgumentException("Not a directory:  " + dir);
        String[] entries = d.list();
        byte[] buffer = new byte[4096];
        int bytesRead;
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        for (int i = 0; i < entries.length; i++) {
            File f = new File(d, entries[i]);
            if (f.isDirectory()) continue;
            FileInputStream in = new FileInputStream(f);
            ZipEntry entry = new ZipEntry(f.getPath());
            out.putNextEntry(entry);
            while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();
    }


    private RemoteObject createRemoteObject(final VideoEntry videoEntry, final RemoteContainer container) throws RemoteException {
        MessageDigest instance;
        try {
            instance = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RemoteException(StatusCreator.newStatus("Error creating MD5", e));
        }
        StringWriter sw = new StringWriter();
        YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
        if (mediaGroup != null) {
            if (mediaGroup.getDescription() != null) {
                sw.append(mediaGroup.getDescription().getPlainTextContent());
            }
            List<MediaCategory> keywordsGroup = mediaGroup.getCategories();
            StringBuilder sb = new StringBuilder();
            if (keywordsGroup != null) {
                for (MediaCategory mediaCategory : keywordsGroup) {
                    sb.append(mediaCategory.getContent());
                }
            }
        }
        instance.update(sw.toString().getBytes());
        RemoteObject remoteVideo = InfomngmntFactory.eINSTANCE.createRemoteObject();
        remoteVideo.setHash(asHex(instance.digest()));
        remoteVideo.setId(SiteInspector.getId(videoEntry.getHtmlLink().getHref()));
        remoteVideo.setName(videoEntry.getTitle().getPlainText());
        remoteVideo.setRepositoryTypeObjectId(KEY_VIDEO);
        remoteVideo.setWrappedObject(videoEntry);
        setInternalUrl(remoteVideo, container);
        return remoteVideo;
    }


    public void createPdf(final String eventURI) throws IOException, DocumentException {
        createSections(eventURI);
        even = false;
        final Document document = new Document(Dimensions.getDimension(even, Dimension.MEDIABOX));
        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(MyProperties.getOutput()));
        writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnRight);
        writer.setCropBoxSize(Dimensions.getDimension(even, Dimension.CROPBOX));
        writer.setBoxSize("trim", Dimensions.getDimension(even, Dimension.TRIMBOX));
        writer.setBoxSize("bleed", Dimensions.getDimension(even, Dimension.BLEEDBOX));
        final EventBackgroundAndPageNumbers event = new EventBackgroundAndPageNumbers();
        writer.setPageEvent(event);
        document.open();
        final PdfContentByte content = writer.getDirectContent();
        event.setTabs(Index.INFO.getTab());
        importPages(document, content, new PdfReader(Index.INFO.getOutput()), Index.INFO.getTitle());
        importPages(document, content, MyProperties.getBefore(), event);
        addAdPage(document, content);
        PdfReader reader = new PdfReader(Presentations.INFO.getOutput());
        String[] titles = { "", "" };
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            titles = index.getSubtitle(titles, i);
            event.setTabs(titles[0].toLowerCase());
            addTitleLeft(content, Dimensions.getTitleArea(even), titles[0], MyFonts.TITLE);
            addTitleRight(content, Dimensions.getTitleArea(even), titles[1], MyFonts.DATE);
            content.addTemplate(writer.getImportedPage(reader, i), Dimensions.getOffsetX(even), Dimensions.getOffsetY(even));
            document.newPage();
            even = !even;
        }
        addAdPage(document, content);
        importPages(document, content, MyProperties.getAfter(), event);
        int total = writer.getPageNumber() - 1;
        event.setNoMorePageNumbers();
        event.setTabs(Schedules.INFO.getTab());
        reader = new PdfReader(Schedules.INFO.getOutput());
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            addTitleLeft(content, Dimensions.getTitleArea(even), Schedules.INFO.getTitle(), MyFonts.TITLE);
            content.addTemplate(writer.getImportedPage(reader, i), Dimensions.getOffsetX(even), Dimensions.getOffsetY(even));
            document.newPage();
            even = !even;
        }
        document.close();
        final File file = new File(MyProperties.getOutput());
        final byte[] original = new byte[(int) file.length()];
        final FileInputStream f = new FileInputStream(file);
        f.read(original);
        reader = new PdfReader(original);
        final List<Integer> ranges = new ArrayList<Integer>();
        for (int i = 1; i <= total; i++) {
            ranges.add(i);
            if (i == total / 2) {
                for (int j = total + 1; j <= reader.getNumberOfPages(); j++) {
                    ranges.add(j);
                }
            }
        }
        reader.selectPages(ranges);
        final PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(MyProperties.getOutput()));
        stamper.close();
    }


    public static boolean copyTextFile(File src, File dst) {
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dst));
            byte[] buf = new byte[1024];
            int readsize = 0;
            while ((readsize = bis.read(buf)) != -1) {
                bos.write(buf, 0, readsize);
            }
            bos.flush();
            bos.close();
            bis.close();
        } catch (IOException e) {
            ServerConsoleServlet.printSystemLog(e.toString() + " " + e.getMessage(), ServerConsoleServlet.LOG_ERROR);
            return false;
        }
        return true;
    }


    public void openJadFile(URL url) {
        try {
            setStatusBar("Loading...");
            jad.clear();
            jad.load(url.openStream());
            loadFromJad(url);
        } catch (FileNotFoundException ex) {
            System.err.println("Cannot found " + url.getPath());
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            System.err.println("Cannot open jad " + url.getPath());
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
            System.err.println("Cannot open jad " + url.getPath());
        } catch (IOException ex) {
            ex.printStackTrace();
            System.err.println("Cannot open jad " + url.getPath());
        }
    }


    public static String fromHtml(URL url, String defaultEncoding, boolean overrideEncoding) throws IOException, BadDocumentException {
        URLConnection conn = url.openConnection();
        String contentType = conn.getContentType();
        String encoding = conn.getContentEncoding();
        if (encoding == null) {
            int i = contentType.indexOf("charset");
            if (i >= 0) {
                String s = contentType.substring(i);
                i = s.indexOf('=');
                if (i >= 0) {
                    s = contentType.substring(i + 1).trim();
                    encoding = s.replace("\'", "").replace("\"", "").trim();
                    if (encoding.equals("")) {
                        encoding = defaultEncoding;
                    }
                }
            } else {
                encoding = defaultEncoding;
            }
        }
        String expected = "text/html";
        if (contentType == null) {
            DefaultXMLNoteErrorHandler.warning(null, 90190, "Returned content type for url.openConnection() is null");
            contentType = expected;
        }
        int index = contentType.indexOf(';');
        if (index >= 0) {
            contentType = contentType.substring(0, index).trim();
        }
        if (!contentType.equals(expected)) {
            String msg = translator.translate("The content type of url '%s' is not '%s', it is '%s'");
            throw new BadDocumentException(String.format(msg, url.toString(), expected, contentType));
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
        return fromHtml(in, encoding);
    }


    private MapProperties readProperties(URL url) {
        @SuppressWarnings("unchecked") MapProperties properties = new MapProperties(new LinkedHashMap());
        InputStream is = null;
        try {
            is = url.openStream();
            properties.load(is);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            StreamUtils.close(is);
        }
        return properties;
    }


    private String processFileUploadOperation(boolean isH264File) {
        String fileType = this.uploadFileFileName.substring(this.uploadFileFileName.lastIndexOf('.'));
        int uniqueHashCode = UUID.randomUUID().toString().hashCode();
        if (uniqueHashCode < 0) {
            uniqueHashCode *= -1;
        }
        String randomFileName = uniqueHashCode + fileType;
        String fileName = (isH264File) ? getproperty("videoDraftPath") : getproperty("videoDraftPathForNonH264") + randomFileName;
        File targetVideoPath = new File(fileName + randomFileName);
        System.out.println("Path: " + targetVideoPath.getAbsolutePath());
        try {
            targetVideoPath.createNewFile();
            FileChannel outStreamChannel = new FileOutputStream(targetVideoPath).getChannel();
            FileChannel inStreamChannel = new FileInputStream(this.uploadFile).getChannel();
            inStreamChannel.transferTo(0, inStreamChannel.size(), outStreamChannel);
            outStreamChannel.close();
            inStreamChannel.close();
            return randomFileName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private String hash(String message) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError("Can't find the SHA1 algorithm in the java.security package");
        }
        String saltString = String.valueOf(12345);
        md.update(saltString.getBytes());
        md.update(message.getBytes());
        byte[] digestBytes = md.digest();
        StringBuffer digestSB = new StringBuffer();
        for (int i = 0; i < digestBytes.length; i++) {
            int lowNibble = digestBytes[i] & 0x0f;
            int highNibble = (digestBytes[i] >> 4) & 0x0f;
            digestSB.append(Integer.toHexString(highNibble));
            digestSB.append(Integer.toHexString(lowNibble));
        }
        String digestStr = digestSB.toString().trim();
        return digestStr;
    }


    protected URL[][] getImageLinks(final URL url) {
        Lexer lexer;
        URL[][] ret;
        if (null != url) {
            try {
                lexer = new Lexer(url.openConnection());
                ret = extractImageLinks(lexer, url);
            } catch (Throwable t) {
                System.out.println(t.getMessage());
                ret = NONE;
            }
        } else ret = NONE;
        return (ret);
    }


    @Test
    public void testLoadSource() throws IOException {
        ArticleMetadata metadata = new ArticleMetadata();
        metadata.setId("http://arxiv.org/abs/math/0205003v1");
        InputStream inputStream = arxivDAOFacade.loadSource(metadata);
        Assert.assertNotNull(inputStream);
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, "utf8");
        String contents = writer.toString();
        Assert.assertTrue(contents.contains("A strengthening of the Nyman"));
        inputStream.close();
    }


    @Override
    protected void initializeGraphicalViewer() {
        super.initializeGraphicalViewer();
        getGraphicalViewer().setEditPartFactory(fact);
        ITypeRoot tr = sourceEditor.getInputElement();
        try {
            getGraphicalViewer().setContents(tr);
            ((DesignTimeComponent) fact.getTopPart().getModelChildren().get(0)).addListener(new DesignTimeListener() {

                public void handleUpdate(DesignTimeComponent comp) {
                    updateSourceWithComponent(comp.getTopLevel());
                }
            });
        } catch (Throwable e) {
            e.printStackTrace();
        }
        getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() {

            public void selectionChanged(SelectionChangedEvent arg0) {
                if (getSelectedComponent() == null) {
                    return;
                }
                PropertySheetPage propertySheet = ((PropertySheetPage) getAdapter(IPropertySheetPage.class));
                propertySheet.selectionChanged(getSite().getPart(), new StructuredSelection(getSelectedComponent()));
                try {
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
        getGraphicalViewer().setContextMenu(contextMenu);
        contextMenu.addMenuListener(this);
    }


    public static String generateToken(ClientInfo clientInfo) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            Random rand = new Random();
            String random = clientInfo.getIpAddress() + ":" + clientInfo.getPort() + ":" + rand.nextInt();
            md5.update(random.getBytes());
            String token = toHexString(md5.digest((new Date()).toString().getBytes()));
            clientInfo.setToken(token);
            return token;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    private ByteArrayInputStream fetchUrl(String urlString, Exception[] outException) {
        URL url;
        try {
            url = new URL(urlString);
            InputStream is = null;
            int inc = 65536;
            int curr = 0;
            byte[] result = new byte[inc];
            try {
                is = url.openStream();
                int n;
                while ((n = is.read(result, curr, result.length - curr)) != -1) {
                    curr += n;
                    if (curr == result.length) {
                        byte[] temp = new byte[curr + inc];
                        System.arraycopy(result, 0, temp, 0, curr);
                        result = temp;
                    }
                }
                return new ByteArrayInputStream(result, 0, curr);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        } catch (Exception e) {
            outException[0] = e;
        }
        return null;
    }


    @SuppressWarnings("unchecked")
    private List<String> getWordList() {
        IConfiguration config = Configurator.getDefaultConfigurator().getConfig(CONFIG_ID);
        List<String> wList = (List<String>) config.getObject("word_list");
        if (wList == null) {
            wList = new ArrayList<String>();
            InputStream resrc = null;
            try {
                resrc = new URL(list_url).openStream();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (resrc != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(resrc));
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        line = line.trim();
                        if (line.length() != 0) {
                            wList.add(line);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        }
        return wList;
    }


    public InputStream getResource(FCValue name) throws FCException {
        Element el = _factory.getElementWithID(name.getAsString());
        if (el == null) {
            throw new FCException("Could not find resource \"" + name + "\"");
        }
        String urlString = el.getTextTrim();
        if (!urlString.startsWith("http")) {
            try {
                log.debug("Get resource: " + urlString);
                URL url;
                if (urlString.startsWith("file:")) {
                    url = new URL(urlString);
                } else {
                    url = getClass().getResource(urlString);
                }
                return url.openStream();
            } catch (Exception e) {
                throw new FCException("Failed to load resource.", e);
            }
        } else {
            try {
                FCService http = getRuntime().getServiceFor(FCService.HTTP_DOWNLOAD);
                return http.perform(new FCValue[] { name }).getAsInputStream();
            } catch (Exception e) {
                throw new FCException("Failed to load resource.", e);
            }
        }
    }


    public static void copyFile(File source, File destination) throws IOException {
        destination.getParentFile().mkdirs();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination));
        byte[] buffer = new byte[4096];
        int read = -1;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
        in.close();
    }


    public boolean downloadFTP(String ipFTP, String loginFTP, String senhaFTP, String diretorioFTP, String diretorioAndroid, String arquivoFTP) throws SocketException, IOException {
        boolean retorno = false;
        FileOutputStream arqReceber = null;
        try {
            ftp.connect(ipFTP);
            Log.i("DownloadFTP", "Connected: " + ipFTP);
            ftp.login(loginFTP, senhaFTP);
            Log.i("DownloadFTP", "Logged on");
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            arqReceber = new FileOutputStream(file.toString());
            ftp.retrieveFile("/tablet_ftp/Novo/socialAlimenta.xml", arqReceber);
            retorno = true;
            ftp.disconnect();
            Log.i("DownloadFTP", "retorno:" + retorno);
        } catch (Exception e) {
            ftp.disconnect();
            Log.e("DownloadFTP", "Erro:" + e.getMessage());
        } finally {
            Log.e("DownloadFTP", "Finally");
        }
        return retorno;
    }


    public boolean uploadFTP(String ipFTP, String loginFTP, String senhaFTP, String diretorioFTP, String diretorioAndroid, String arquivoFTP) {
        try {
            dialogHandler.sendEmptyMessage(0);
            File file = new File(diretorioAndroid);
            File file2 = new File(diretorioAndroid + arquivoFTP);
            Log.v("uploadFTP", "Atribuidas as vari�veis");
            String status = "";
            if (file.isDirectory()) {
                Log.v("uploadFTP", "� diret�rio");
                if (file.list().length > 0) {
                    Log.v("uploadFTP", "file.list().length > 0");
                    ftp.connect(ipFTP);
                    ftp.login(loginFTP, senhaFTP);
                    ftp.enterLocalPassiveMode();
                    ftp.setFileTransferMode(FTPClient.ASCII_FILE_TYPE);
                    ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
                    ftp.changeWorkingDirectory(diretorioFTP);
                    FileInputStream arqEnviar = new FileInputStream(diretorioAndroid + arquivoFTP);
                    Log.v("uploadFTP", "FileInputStream declarado");
                    if (ftp.storeFile(arquivoFTP, arqEnviar)) {
                        Log.v("uploadFTP", "ftp.storeFile(arquivoFTP, arqEnviar)");
                        status = ftp.getStatus().toString();
                        Log.v("uploadFTP", "getStatus(): " + status);
                        if (file2.delete()) {
                            Log.i("uploadFTP", "Arquivo " + arquivoFTP + " exclu�do com sucesso");
                            retorno = true;
                        } else {
                            Log.e("uploadFTP", "Erro ao excluir o arquivo " + arquivoFTP);
                            retorno = false;
                        }
                    } else {
                        Log.e("uploadFTP", "ERRO: arquivo " + arquivoFTP + "n�o foi enviado!");
                        retorno = false;
                    }
                } else {
                    Log.e("uploadFTP", "N�o existe o arquivo " + arquivoFTP + "neste diret�rio!");
                    retorno = false;
                }
            } else {
                Log.e("uploadFTP", "N�o � diret�rio");
                retorno = false;
            }
            if (ftp.isConnected()) {
                Log.v("uploadFTP", "isConnected ");
                ftp.abort();
                status = ftp.getStatus().toString();
                Log.v("uploadFTP", "quit " + retorno);
            }
            return retorno;
        } catch (IOException e) {
            Log.e("uploadFTP", "ERRO FTP: " + e);
            retorno = false;
            return retorno;
        } finally {
            handler.sendEmptyMessage(0);
            Log.v("uploadFTP", "finally executado");
        }
    }


    public static String sha1(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(input.getBytes("UTF-8"), 0, input.length());
        sha1hash = md.digest();
        return convertToHex(sha1hash);
    }


    private void uploadConfiguration(URL url, IUser iUser) throws IOException, ContributionServiceException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append(System.getProperty("line.separator"));
        }
        SYSTEM_SETTINGS_SVC.setElementMetadata(sb.toString(), iUser);
        GetSystemScriptServlet.resetScript();
    }


    public static File getClassLoaderFile(String filename) throws IOException {
        Resource resource = new ClassPathResource(filename);
        try {
            return resource.getFile();
        } catch (IOException e) {
        }
        InputStream is = null;
        FileOutputStream os = null;
        try {
            String tempFilename = RandomStringUtils.randomAlphanumeric(20);
            File file = File.createTempFile(tempFilename, null);
            is = resource.getInputStream();
            os = new FileOutputStream(file);
            IOUtils.copy(is, os);
            return file;
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }


    public static boolean encodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


    public static boolean decodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


    protected void discoverFactories() {
        DataSourceRegistry registry = this;
        try {
            ClassLoader loader = DataSetURI.class.getClassLoader();
            Enumeration<URL> urls;
            if (loader == null) {
                urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory");
            } else {
                urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory");
            }
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String s = reader.readLine();
                while (s != null) {
                    if (s.trim().length() > 0) {
                        List<String> extensions = null;
                        List<String> mimeTypes = null;
                        String factoryClassName = s;
                        try {
                            Class c = Class.forName(factoryClassName);
                            DataSourceFactory f = (DataSourceFactory) c.newInstance();
                            try {
                                Method m = c.getMethod("extensions", new Class[0]);
                                extensions = (List<String>) m.invoke(f, new Object[0]);
                            } catch (NoSuchMethodException ex) {
                            } catch (InvocationTargetException ex) {
                                ex.printStackTrace();
                            }
                            try {
                                Method m = c.getMethod("mimeTypes", new Class[0]);
                                mimeTypes = (List<String>) m.invoke(f, new Object[0]);
                            } catch (NoSuchMethodException ex) {
                            } catch (InvocationTargetException ex) {
                                ex.printStackTrace();
                            }
                        } catch (ClassNotFoundException ex) {
                            ex.printStackTrace();
                        } catch (InstantiationException ex) {
                            ex.printStackTrace();
                        } catch (IllegalAccessException ex) {
                            ex.printStackTrace();
                        }
                        if (extensions != null) {
                            for (String e : extensions) {
                                registry.registerExtension(factoryClassName, e, null);
                            }
                        }
                        if (mimeTypes != null) {
                            for (String m : mimeTypes) {
                                registry.registerMimeType(factoryClassName, m);
                            }
                        }
                    }
                    s = reader.readLine();
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private Map<String, String> readStuff(Iterator<URL> urls) throws IOException {
        Map<String, String> result = new LinkedHashMap();
        while (urls.hasNext()) {
            URL url = urls.next();
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = reader.readLine();
            while (s != null) {
                s = s.trim();
                if (s.length() > 0) {
                    String[] ss = s.split("\\s");
                    for (int i = 1; i < ss.length; i++) {
                        result.put(ss[i], ss[0]);
                    }
                }
                s = reader.readLine();
            }
            reader.close();
        }
        return result;
    }


    protected void discoverRegistryEntries() {
        DataSourceRegistry registry = this;
        try {
            ClassLoader loader = DataSetURI.class.getClassLoader();
            Enumeration<URL> urls;
            if (loader == null) {
                urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions");
            } else {
                urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions");
            }
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String s = reader.readLine();
                while (s != null) {
                    s = s.trim();
                    if (s.length() > 0) {
                        String[] ss = s.split("\\s");
                        for (int i = 1; i < ss.length; i++) {
                            if (ss[i].contains(".")) {
                                System.err.println("META-INF/org.virbo.datasource.DataSourceFactory.extensions contains extension that contains period: ");
                                System.err.println(ss[0] + " " + ss[i] + " in " + url);
                                System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line");
                                System.err.println("");
                                throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url);
                            }
                            registry.registerExtension(ss[0], ss[i], null);
                        }
                    }
                    s = reader.readLine();
                }
                reader.close();
            }
            if (loader == null) {
                urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes");
            } else {
                urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes");
            }
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String s = reader.readLine();
                while (s != null) {
                    s = s.trim();
                    if (s.length() > 0) {
                        String[] ss = s.split("\\s");
                        for (int i = 1; i < ss.length; i++) {
                            registry.registerMimeType(ss[0], ss[i]);
                        }
                    }
                    s = reader.readLine();
                }
                reader.close();
            }
            if (loader == null) {
                urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions");
            } else {
                urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions");
            }
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String s = reader.readLine();
                while (s != null) {
                    s = s.trim();
                    if (s.length() > 0) {
                        String[] ss = s.split("\\s");
                        for (int i = 1; i < ss.length; i++) {
                            if (ss[i].contains(".")) {
                                System.err.println("META-INF/org.virbo.datasource.DataSourceFormat.extensions contains extension that contains period: ");
                                System.err.println(ss[0] + " " + ss[i] + " in " + url);
                                System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line");
                                System.err.println("");
                                throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url);
                            }
                            registry.registerFormatter(ss[0], ss[i]);
                        }
                    }
                    s = reader.readLine();
                }
                reader.close();
            }
            if (loader == null) {
                urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions");
            } else {
                urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions");
            }
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String s = reader.readLine();
                while (s != null) {
                    s = s.trim();
                    if (s.length() > 0) {
                        String[] ss = s.split("\\s");
                        for (int i = 1; i < ss.length; i++) {
                            if (ss[i].contains(".")) {
                                System.err.println("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions contains extension that contains period: ");
                                System.err.println(ss[0] + " " + ss[i] + " in " + url);
                                System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line");
                                System.err.println("");
                                throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url);
                            }
                            registry.registerEditor(ss[0], ss[i]);
                        }
                    }
                    s = reader.readLine();
                }
                reader.close();
            }
            if (loader == null) {
                urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions");
            } else {
                urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions");
            }
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String s = reader.readLine();
                while (s != null) {
                    s = s.trim();
                    if (s.length() > 0) {
                        String[] ss = s.split("\\s");
                        for (int i = 1; i < ss.length; i++) {
                            if (ss[i].contains(".")) {
                                System.err.println("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions contains extension that contains period: ");
                                System.err.println(ss[0] + " " + ss[i] + " in " + url);
                                System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line");
                                System.err.println("");
                                throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url);
                            }
                            registry.registerFormatEditor(ss[0], ss[i]);
                        }
                    }
                    s = reader.readLine();
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getMD5Hash(String input) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(input.getBytes());
            byte[] result = md5.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String byteStr = Integer.toHexString(result[i]);
                String swap = null;
                switch(byteStr.length()) {
                    case 1:
                        swap = "0" + Integer.toHexString(result[i]);
                        break;
                    case 2:
                        swap = Integer.toHexString(result[i]);
                        break;
                    case 8:
                        swap = (Integer.toHexString(result[i])).substring(6, 8);
                        break;
                }
                hexString.append(swap);
            }
            return hexString.toString();
        } catch (Exception ex) {
            System.out.println("Fehler beim Ermitteln eines Hashs (" + ex.getMessage() + ")");
        }
        return null;
    }


    public static void copyFile(File in, File out) throws Exception {
        Permissions before = getFilePermissons(in);
        FileChannel inFile = new FileInputStream(in).getChannel();
        FileChannel outFile = new FileOutputStream(out).getChannel();
        inFile.transferTo(0, inFile.size(), outFile);
        inFile.close();
        outFile.close();
        setFilePermissions(out, before);
    }


    public static void unzip(String zipfile, String outputDirectory) {
        try {
            byte[] buf = new byte[1024];
            ZipInputStream zipinputstream = null;
            ZipEntry zipentry;
            zipinputstream = new ZipInputStream(new FileInputStream(zipfile));
            zipentry = zipinputstream.getNextEntry();
            while (zipentry != null) {
                String entryName = zipentry.getName();
                System.out.println("entryname " + entryName);
                int n;
                FileOutputStream fileoutputstream;
                File newFile = new File(entryName);
                String directory = newFile.getParent();
                if (directory == null) {
                    if (newFile.isDirectory()) break;
                }
                fileoutputstream = new FileOutputStream(outputDirectory + entryName);
                while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n);
                fileoutputstream.close();
                zipinputstream.closeEntry();
                zipentry = zipinputstream.getNextEntry();
            }
            zipinputstream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String hashString(String password) {
        String hashword = null;
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA");
            sha.update(password.getBytes("UTF-8"));
            BigInteger hash = new BigInteger(1, sha.digest());
            hashword = hash.toString(16);
        } catch (NoSuchAlgorithmException nsae) {
            log.error(nsae);
        } catch (UnsupportedEncodingException e) {
            log.error(e);
        }
        return pad(hashword, 32, '0');
    }


    private static void copy(String from_name, String to_name) throws IOException {
        File from_file = new File(from_name);
        File to_file = new File(to_name);
        if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file);
        if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file);
        if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file);
        if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName());
        if (to_file.exists()) {
            if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file);
            System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):");
            System.out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String response = in.readLine();
            if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������");
        } else {
            String parent = to_file.getParent();
            if (parent == null) parent = System.getProperty("user.dir");
            File dir = new File(parent);
            if (!dir.exists()) abort("������� ���������� �� ���������" + parent);
            if (!dir.isFile()) abort("�� �������� ���������" + parent);
            if (!dir.canWrite()) abort("������ �� ������" + parent);
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(from_file);
            to = new FileOutputStream(to_file);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
    }


    public boolean createProject(String projectName, String export) {
        IProgressMonitor progressMonitor = new NullProgressMonitor();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IProject project = root.getProject(projectName);
        try {
            if (!project.exists()) {
                project.create(progressMonitor);
            }
            project.open(progressMonitor);
            IProjectDescription description = project.getDescription();
            description.setNatureIds(new String[] { JavaCore.NATURE_ID });
            project.setDescription(description, progressMonitor);
            IJavaProject javaProject = JavaCore.create(project);
            IFolder binFolder = project.getFolder("bin");
            IFolder outputFolder = project.getFolder(export);
            if (!binFolder.exists()) {
                binFolder.create(false, true, null);
            }
            javaProject.setOutputLocation(outputFolder.getFullPath(), progressMonitor);
            List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
            IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
            LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
            for (LibraryLocation element : locations) {
                entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
            }
            javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
            IFolder sourceFolder = project.getFolder("src");
            if (!sourceFolder.exists()) {
                sourceFolder.create(false, true, null);
            }
            IPackageFragmentRoot rootfolder = javaProject.getPackageFragmentRoot(sourceFolder);
            IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
            newEntries[oldEntries.length] = JavaCore.newSourceEntry(rootfolder.getPath());
            javaProject.setRawClasspath(newEntries, null);
            IPackageFragment pack;
            if (rootfolder.getPackageFragment("") == null) {
                pack = rootfolder.createPackageFragment("", true, progressMonitor);
            } else {
                pack = rootfolder.getPackageFragment("");
            }
            StringBuffer buffer = new StringBuffer();
            buffer.append("\n");
            buffer.append(source);
            ICompilationUnit cu = pack.createCompilationUnit("ProcessingApplet.java", buffer.toString(), false, null);
            return true;
        } catch (CoreException e) {
            e.printStackTrace();
        }
        return false;
    }


    protected InputStream makeRequestAndGetJSONData(String url) throws URISyntaxException, ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        uri = new URI(url);
        HttpGet method = new HttpGet(uri);
        HttpResponse response = httpClient.execute(method);
        data = response.getEntity().getContent();
        return data;
    }


    protected InputStream makeSignedRequestAndGetJSONData(String url) {
        try {
            if (consumer == null) loginOAuth();
        } catch (Exception e) {
            consumer = null;
            e.printStackTrace();
        }
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri);
            consumer.sign(method);
            HttpResponse response = httpClient.execute(method);
            data = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }


    public void loginOAuth() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, IllegalStateException, SAXException, ParserConfigurationException, FactoryConfigurationError, AndroidException {
        String url = getAuthentificationURL();
        HttpGet reqLogin = new HttpGet(url);
        consumer = new CommonsHttpOAuthConsumer(getConsumerKey(), getConsumerSecret());
        consumer.sign(reqLogin);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse resLogin = httpClient.execute(reqLogin);
        if (resLogin.getEntity() == null) {
            throw new AuthRemoteException();
        }
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(resLogin.getEntity().getContent());
        Element eOAuthToken = (Element) document.getElementsByTagName("oauth_token").item(0);
        if (eOAuthToken == null) {
            throw new AuthRemoteException();
        }
        Node e = eOAuthToken.getFirstChild();
        String sOAuthToken = e.getNodeValue();
        System.out.println("token: " + sOAuthToken);
        Element eOAuthTokenSecret = (Element) document.getElementsByTagName("oauth_token_secret").item(0);
        if (eOAuthTokenSecret == null) {
            throw new AuthRemoteException();
        }
        e = eOAuthTokenSecret.getFirstChild();
        String sOAuthTokenSecret = e.getNodeValue();
        System.out.println("Secret: " + sOAuthTokenSecret);
        consumer.setTokenWithSecret(sOAuthToken, sOAuthTokenSecret);
    }


    @Override
    public void init() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Throwable e) {
        }
        try {
            PopupFactory.setSharedInstance(new PopupFactory());
        } catch (Throwable e) {
        }
        Container c = getContentPane();
        c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
        String[] labels = getAppletInfo().split("\n");
        for (int i = 0; i < labels.length; i++) {
            c.add(new JLabel((labels[i].length() == 0) ? " " : labels[i]));
        }
        new Worker<Drawing>() {

            @Override
            protected Drawing construct() throws IOException {
                Drawing result;
                System.out.println("getParameter.datafile:" + getParameter("datafile"));
                if (getParameter("data") != null) {
                    NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data")));
                    result = (Drawing) domi.readObject(0);
                } else if (getParameter("datafile") != null) {
                    URL url = new URL(getDocumentBase(), getParameter("datafile"));
                    InputStream in = url.openConnection().getInputStream();
                    try {
                        NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in);
                        result = (Drawing) domi.readObject(0);
                    } finally {
                        in.close();
                    }
                } else {
                    result = null;
                }
                return result;
            }

            @Override
            protected void done(Drawing result) {
                Container c = getContentPane();
                c.setLayout(new BorderLayout());
                c.removeAll();
                c.add(drawingPanel = new NetPanel());
                if (result != null) {
                    Drawing drawing = (Drawing) result;
                    setDrawing(drawing);
                }
            }

            @Override
            protected void failed(Throwable value) {
                Container c = getContentPane();
                c.setLayout(new BorderLayout());
                c.removeAll();
                c.add(drawingPanel = new NetPanel());
                value.printStackTrace();
                getDrawing().add(new TextFigure(value.toString()));
                value.printStackTrace();
            }

            @Override
            protected void finished() {
                Container c = getContentPane();
                initDrawing(getDrawing());
                c.validate();
            }
        }.start();
    }