semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void format(File source, File target) {
        if (!source.exists()) {
            throw new IllegalArgumentException("Source '" + source + " doesn't exist");
        }
        if (!source.isFile()) {
            throw new IllegalArgumentException("Source '" + source + " is not a file");
        }
        target.mkdirs();
        String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1);
        String _target = source.getName().replace(fileExtension, "html");
        target = new File(target.getPath() + "/" + _target);
        try {
            Reader reader = new FileReader(source);
            Writer writer = new FileWriter(target);
            this.format(reader, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
@Override
        public Void doInBackground() {
            java.io.FileOutputStream fos = null;
            try {
                String localFile = "JavaPointNew.jar";
                java.io.BufferedInputStream in = null;
                try {
                    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                    contentLength = httpConn.getContentLength();
                    if (contentLength == -1) {
                        System.out.println("unknown content length");
                    } else {
                        System.out.println("content length: " + contentLength + " bytes");
                    }
                    in = new java.io.BufferedInputStream(httpConn.getInputStream());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                fos = new java.io.FileOutputStream(localFile);
                java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                int x = 0;
                int bytes = 0;
                while ((x = in.read(data, 0, 1024)) >= 0) {
                    bout.write(data, 0, x);
                    bytes += x;
                    setProgress((int) ((Math.min(bytes * 100 / contentLength, 100)) + .5));
                }
                bout.close();
                in.close();
                File jarFile = mainFrame.presentationFile;
                if (jarFile.exists()) {
                    final File temporaryJarFile = Utilities.createTemporaryFile("presentation", ".jar", false, null);
                    final JarFile updatedJarFile = new JarFile(localFile);
                    final JarOutputStream output = new JarOutputStream(new FileOutputStream(temporaryJarFile));
                    for (final JarEntry entry : Utilities.toList(updatedJarFile.entries())) {
                        if (!entry.getName().startsWith(Constants.JAR_ENTRY_PRESENTATION_PREFIX)) {
                            final InputStream entryStream = updatedJarFile.getInputStream(entry);
                            output.putNextEntry(entry);
                            Utilities.write(entryStream, output);
                        }
                    }
                    new SlidesWriter().write(mainFrame.getSlides(), output);
                    jarFile.delete();
                    new File(localFile).delete();
                    if (!temporaryJarFile.renameTo(jarFile)) {
                        throw new RuntimeException("Failed to update " + jarFile);
                    }
                } else {
                    new SlidesWriter().write(mainFrame.getSlides(), new JarOutputStream(new FileOutputStream(jarFile)));
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
private static void extract(final ZipFile zf, final ZipEntry zipEntry, final String desDir, final int... startDirLevel) throws IOException {
        File desf = new File(desDir);
        if (!desf.exists()) {
            desf.mkdirs();
        }
        int start = 1;
        if (null != startDirLevel && startDirLevel.length > 0) {
            start = startDirLevel[0];
            if (start < 1) {
                start = 1;
            }
        }
        String startDir = "";
        String zeName = zipEntry.getName();
        String folder = zeName;
        boolean isDir = zipEntry.isDirectory();
        if (null != folder) {
            String[] folders = folder.split("\\/");
            if (null != folders && folders.length > 0) {
                int len = folders.length;
                if (start == 1) {
                    startDir = zeName;
                } else {
                    if (start > len) {
                    } else {
                        for (int i = start - 1; i < len; i++) {
                            startDir += "/" + folders[i];
                        }
                        if (null != startDir) {
                            startDir = startDir.substring(1);
                        }
                    }
                }
            }
        }
        startDir = StringUtils.trim(startDir);
        if (StringUtils.isNotEmpty(startDir)) {
            StringBuilder desFileName = new StringBuilder(desDir);
            if (!desDir.endsWith("/") && !startDir.startsWith("/")) {
                desFileName.append("/");
            }
            desFileName.append(startDir);
            File destFile = new File(desFileName.toString());
            if (isDir) {
                if (!destFile.exists()) {
                    destFile.mkdirs();
                }
            } else {
                File parentDir = new File(destFile.getParentFile().getPath());
                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }
                InputStream is = zf.getInputStream(zipEntry);
                OutputStream os = new FileOutputStream(destFile);
                IOUtils.copy(is, os);
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            }
        }
    }
public void create(File target) {
        if ("dir".equals(type)) {
            File dir = new File(target, name);
            dir.mkdirs();
            for (Resource c : children) {
                c.create(dir);
            }
        } else if ("package".equals(type)) {
            String[] dirs = name.split("\\.");
            File parent = target;
            for (String d : dirs) {
                parent = new File(parent, d);
            }
            parent.mkdirs();
            for (Resource c : children) {
                c.create(parent);
            }
        } else if ("file".equals(type)) {
            InputStream is = getInputStream();
            File file = new File(target, name);
            try {
                if (is != null) {
                    FileOutputStream fos = new FileOutputStream(file);
                    IOUtils.copy(is, fos);
                    fos.flush();
                    fos.close();
                } else {
                    PrintStream ps = new PrintStream(file);
                    ps.print(content);
                    ps.flush();
                    ps.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if ("zip".equals(type)) {
            try {
                unzip(target);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new RuntimeException("unknown resource type: " + type);
        }
    }
private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException {
        final long mgr = Constants.MANAGER;
        Data data, response;
        try {
            response = sendAndWait(new Request(mgr)).get(0);
            MessageDigest md;
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("MD5 hash not supported.");
            }
            byte[] challenge = response.getBytes();
            md.update(challenge);
            md.update(password.getBytes(Data.STRING_ENCODING));
            data = Data.valueOf(md.digest());
            try {
                response = sendAndWait(new Request(mgr).add(0, data)).get(0);
            } catch (ExecutionException ex) {
                throw new IncorrectPasswordException();
            }
            setLoginMessage(response.getString());
            response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0);
            setID(response.getWord());
        } catch (InterruptedException ex) {
            throw new LoginFailedException(ex);
        } catch (ExecutionException ex) {
            throw new LoginFailedException(ex);
        } catch (IOException ex) {
            throw new LoginFailedException(ex);
        }
    }
public String readBaseLib() throws Exception {
        if (_BASE_LIB_JS == null) {
            StringBuffer js = new StringBuffer();
            try {
                URL url = AbstractRunner.class.getResource(_BASELIB_FILENAME);
                if (url != null) {
                    InputStream is = url.openStream();
                    InputStreamReader reader = new InputStreamReader(is);
                    BufferedReader bfReader = new BufferedReader(reader);
                    String tmp = null;
                    do {
                        tmp = bfReader.readLine();
                        if (tmp != null) {
                            js.append(tmp).append('\n');
                        }
                    } while (tmp != null);
                    bfReader.close();
                    reader.close();
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
            _BASE_LIB_JS = js.toString();
        }
        return _BASE_LIB_JS;
    }
public static InputStream download(String endereco, ProxyConfig proxy) {
        if (proxy != null) {
            System.getProperties().put("proxySet", "true");
            System.getProperties().put("proxyPort", proxy.getPorta());
            System.getProperties().put("proxyHost", proxy.getHost());
            Authenticator.setDefault(new ProxyAuthenticator(proxy.getUsuario(), proxy.getSenha()));
        }
        try {
            URL url = new URL(endereco);
            ;
            URLConnection connection = url.openConnection();
            InputStream bis = new BufferedInputStream(connection.getInputStream());
            return bis;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
private void validateODFDoc(String url, String ver, ValidationReport commentary) throws IOException, MalformedURLException {
        logger.debug("Beginning document validation ...");
        synchronized (ODFValidationSession.class) {
            PropertyMapBuilder builder = new PropertyMapBuilder();
            String[] segments = url.split("/");
            CommentatingErrorHandler h = new CommentatingErrorHandler(commentary, segments[segments.length - 1]);
            ValidateProperty.ERROR_HANDLER.put(builder, h);
            ValidationDriver driver = new ValidationDriver(builder.toPropertyMap());
            InputStream candidateStream = null;
            try {
                logger.debug("Loading schema version " + ver);
                byte[] schemaBytes = getSchemaForVersion(ver);
                driver.loadSchema(new InputSource(new ByteArrayInputStream(schemaBytes)));
                URLConnection conn = new URL(url).openConnection();
                candidateStream = conn.getInputStream();
                logger.debug("Calling validate()");
                commentary.incIndent();
                boolean isValid = driver.validate(new InputSource(candidateStream));
                logger.debug("Errors in instance:" + h.getInstanceErrCount());
                if (h.getInstanceErrCount() > CommentatingErrorHandler.THRESHOLD) {
                    commentary.addComment("(<i>" + (h.getInstanceErrCount() - CommentatingErrorHandler.THRESHOLD) + " error(s) omitted for the sake of brevity</i>)");
                }
                commentary.decIndent();
                if (isValid) {
                    commentary.addComment("The document is valid");
                } else {
                    commentary.addComment("ERROR", "The document is invalid");
                }
            } catch (SAXException e) {
                commentary.addComment("FATAL", "The resource is not conformant XML: " + e.getMessage());
                logger.error(e.getMessage());
            } finally {
                Utils.streamClose(candidateStream);
            }
        }
    }
public void testRead() throws ParserConfigurationException, SAXException, ParseException, IOException {
        InputStream in = getConfStream();
        LogDistiller ld = dOMConfigurator.read(in);
        in.close();
        checkLogDistiller(ld);
        File tmp = File.createTempFile("logdistiller", "test");
        tmp.delete();
        tmp.mkdir();
        URL url = WeblogicLogEvent.class.getResource("wldomain7.log");
        in = url.openStream();
        assertNotNull("load resource wldomain7.log", in);
        Reader reader = new InputStreamReader(in);
        ld.getOutput().setDirectory(tmp.getAbsolutePath());
        LogDistillation exec = new LogDistillation(ld);
        LogEvent.Factory factory = exec.getLogTypeDescription().newFactory(reader, url.toString());
        exec.begin();
        LogEvent le;
        while ((le = factory.nextEvent()) != null) {
            exec.processLogEvent(le);
        }
        exec.end();
        in.close();
        assertEquals("number of logevents processed", 21, exec.getEventCount());
        final int[] groupEventCount = { 6, 6, 1, 4, 9, 7 };
        for (int i = 0; i < 6; i++) {
            LogDistillation.Group g = exec.getGroups()[i];
            LogDistiller.Group def = g.getDefinition();
            assertEquals("number of logevents in group[id='" + def.getId() + "']", groupEventCount[i], g.getEventCount());
        }
    }
public static String read(ClassLoader classLoader, String name, boolean all) throws IOException {
        if (all) {
            StringMaker sm = new StringMaker();
            Enumeration enu = classLoader.getResources(name);
            while (enu.hasMoreElements()) {
                URL url = (URL) enu.nextElement();
                InputStream is = url.openStream();
                String s = read(is);
                if (s != null) {
                    sm.append(s);
                    sm.append(StringPool.NEW_LINE);
                }
                is.close();
            }
            return sm.toString().trim();
        } else {
            InputStream is = classLoader.getResourceAsStream(name);
            String s = read(is);
            is.close();
            return s;
        }
    }
private String getDocumentAsString(URL url) throws IOException {
        StringBuffer result = new StringBuffer();
        InputStream in = url.openStream();
        int c;
        while ((c = in.read()) != -1) result.append((char) c);
        return result.toString();
    }
@Override
    public Object getImage(String key) {
        if (key.indexOf("exhibition/") != -1) {
            InputStream inputStream = null;
            try {
                URL url = new URL(getBaseURL() + "icons/" + key + ".png");
                inputStream = url.openStream();
                return url;
            } catch (Exception e) {
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        ExceptionHandlingService.INSTANCE.handleException(e);
                    }
                }
            }
        }
        return super.getImage(key);
    }
protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException {
        InputStream is = servletConfig.getServletContext().getResourceAsStream(pathInfo);
        if (is == null) {
            throw new ServletException("Static resource " + pathInfo + " is not available");
        }
        try {
            int ind = pathInfo.lastIndexOf(".");
            if (ind != -1 && ind < pathInfo.length()) {
                String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1));
                if (type != null) {
                    response.setContentType(type);
                }
            }
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
        } catch (IOException ex) {
            throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream");
        }
    }
private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception {
        long lastModified = 0;
        Iterator paths = resourcePaths.iterator();
        while (paths.hasNext()) {
            String path = (String) paths.next();
            URL url = context.getServletContext().getResource(path);
            if (url == null) {
                log.debug("Null url " + path);
                break;
            }
            long lastM = url.openConnection().getLastModified();
            if (lastM > lastModified) lastModified = lastM;
            if (log.isDebugEnabled()) {
                log.debug("Last modified " + path + " " + lastM);
            }
        }
        if (jarPaths != null) {
            paths = jarPaths.values().iterator();
            while (paths.hasNext()) {
                File jarFile = (File) paths.next();
                long lastM = jarFile.lastModified();
                if (lastM > lastModified) lastModified = lastM;
                if (log.isDebugEnabled()) {
                    log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM);
                }
            }
        }
        return lastModified;
    }
public static boolean check(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(2000);
            urlConnection.getContent();
        } catch (Exception e) {
            logger.error("There is no internet connection", e);
            return false;
        }
        return true;
    }
public XMLTreeView(JFrame frame, Web3DService web3DService) {
        frame.getContentPane().setLayout(new BorderLayout());
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(file);
        saxTree = new SAXTreeBuilder(top);
        InputStream urlIn = null;
        try {
            SAXParser saxParser = new SAXParser();
            saxParser.setContentHandler(saxTree);
            String request = web3DService.getServiceEndPoint() + "?" + "SERVICE=" + web3DService.getService() + "&" + "REQUEST=GetCapabilities&" + "ACCEPTFORMATS=text/xml&" + "ACCEPTVERSIONS=";
            for (int i = 0; i < web3DService.getAcceptVersions().length; i++) {
                if (i > 0) request += ",";
                request += web3DService.getAcceptVersions()[i];
            }
            System.out.println(request);
            URL url = new URL(request);
            URLConnection urlc = url.openConnection();
            urlc.setReadTimeout(Navigator.TIME_OUT);
            if (web3DService.getEncoding() != null) {
                urlc.setRequestProperty("Authorization", "Basic " + web3DService.getEncoding());
            }
            urlIn = urlc.getInputStream();
            saxParser.parse(new InputSource(urlIn));
        } catch (Exception ex) {
            top.add(new DefaultMutableTreeNode(ex.getMessage()));
        }
        try {
            urlIn.close();
        } catch (Exception e) {
        }
        JTree tree = new JTree(saxTree.getTree());
        JScrollPane scrollPane = new JScrollPane(tree);
        frame.getContentPane().add("Center", scrollPane);
        frame.setVisible(true);
    }
public GEItem lookup(final int itemID) {
        try {
            URL url = new URL(GrandExchange.HOST + GrandExchange.GET + itemID);
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            String input;
            boolean exists = false;
            int i = 0;
            double[] values = new double[4];
            String name = "", examine = "";
            while ((input = br.readLine()) != null) {
                if (input.contains("<div class=\"brown_box main_ge_page") && !exists) {
                    if (!input.contains("vertically_spaced")) {
                        return null;
                    }
                    exists = true;
                    br.readLine();
                    br.readLine();
                    name = br.readLine();
                } else if (input.contains("<img id=\"item_image\" src=\"")) {
                    examine = br.readLine();
                } else if (input.matches("(?i).+ (price|days):</b> .+")) {
                    values[i] = parse(input);
                    i++;
                } else if (input.matches("<div id=\"legend\">")) break;
            }
            return new GEItem(name, examine, itemID, values);
        } catch (IOException ignore) {
        }
        return null;
    }
public GEItem lookup(final String itemName) {
        try {
            URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members=");
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            String input;
            while ((input = br.readLine()) != null) {
                if (input.contains("<div id=\"search_results_text\">")) {
                    input = br.readLine();
                    if (input.contains("Your search for")) {
                        return null;
                    }
                } else if (input.startsWith("<td><img src=")) {
                    Matcher matcher = GrandExchange.PATTERN.matcher(input);
                    if (matcher.find()) {
                        if (matcher.group(2).contains(itemName)) {
                            return lookup(Integer.parseInt(matcher.group(1)));
                        }
                    }
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }