semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@SuppressWarnings("unchecked")
    protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException {
        Enumeration<String> attrNameEnum = request.getSession().getAttributeNames();
        String attrName;
        while (attrNameEnum.hasMoreElements()) {
            attrName = attrNameEnum.nextElement();
            if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) {
                variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName));
            }
        }
        variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI());
        Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        try {
            temp.process(variableMap, new OutputStreamWriter(outStream));
            response.setContentLength(outStream.size());
            IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            throw new Admin4jRuntimeException(e);
        }
    }
public static void copyExternalResource(File sourceFile, File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            closeQuietly(source);
            closeQuietly(destination);
        }
    }
public static void convert(URL url, PrintWriter writer, String server) {
        try {
            XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
            XPath xpe = xpf.newXPath();
            InputStream is = null;
            try {
                is = url.openStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Document doc = readFromStream(is);
            xpe.setNamespaceContext(new NamespaceContext() {

                public String getNamespaceURI(String s) {
                    if (s.equals("tns")) {
                        return "http://services.remote/";
                    } else if (s.equals("xsd")) {
                        return "http://www.w3.org/2001/XMLSchema";
                    } else if (s.equals("soap")) {
                        return "http://schemas.xmlsoap.org/wsdl/soap/";
                    } else if (s.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
                        return "http://schemas.xmlsoap.org/wsdl/";
                    } else {
                        return null;
                    }
                }

                public String getPrefix(String s) {
                    return null;
                }

                public Iterator getPrefixes(String s) {
                    return null;
                }
            });
            Element defs = (Element) xpe.compile("/*:definitions").evaluate(doc, XPathConstants.NODE);
            defs.setAttribute("xmlns", "http://schemas.xmlsoap.org/wsdl/");
            Node schemaLocation = (Node) xpe.compile("/*:definitions/*:types/xsd:schema/xsd:import/@schemaLocation").evaluate(doc, XPathConstants.NODE);
            String sl = schemaLocation.getNodeValue();
            for (int i = 0; i < 3; i++) sl = sl.substring(sl.indexOf('/') + 1);
            schemaLocation.setNodeValue(server + "/" + sl);
            Node location = (Node) xpe.compile("/*:definitions/*:service/*:port/soap:address/@location").evaluate(doc, XPathConstants.NODE);
            String l = location.getNodeValue();
            for (int i = 0; i < 3; i++) l = l.substring(l.indexOf('/') + 1);
            location.setNodeValue(server + "/" + l);
            write(doc, writer);
        } catch (XPathFactoryConfigurationException e) {
            e.printStackTrace();
            System.err.println("Error:" + e);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
            System.err.println("Error:" + e);
        }
    }
public void bspMain(BSP bsp, Serializable arg) throws AbortedException {
        if (!(arg instanceof String[])) {
            bsp.abort(new RuntimeException("String[] as arguments expected"));
        }
        String[] args = (String[]) arg;
        long t1 = 0L, t2;
        try {
            if (bsp != null) bsp.printStdOut(bsp.getHostname()); else System.out.println(InetAddress.getLocalHost().getCanonicalHostName());
        } catch (Exception e) {
            if (bsp != null) bsp.printStdOut("exception: " + e); else System.out.println("exception: " + e);
        }
        Formula formula = null;
        if (bsp == null || bsp.getProcessId() == 0) {
            try {
                InputStream src;
                String input;
                if (args.length > 0) input = args[0]; else input = "sat/uuf175-03.cnf";
                if (bsp != null) bsp.printStdOut("using formula definition: " + input); else System.out.println("using formula definition: " + input);
                if (bsp != null) {
                    bsp.printStdOut("trying to read formula from class file server of the job owner's peer");
                    src = bsp.getResourceAsStream(input);
                } else {
                    System.out.println("trying to read formula from http://www.upb.de/fachbereich/AG/agmadh/WWW/bono/" + input);
                    URL url = new URL("http", "www.upb.de", -1, "/fachbereich/AG/agmadh/WWW/bono/" + input, null);
                    src = url.openStream();
                }
                formula = new Formula(src, bsp);
            } catch (Exception e) {
                if (bsp != null) {
                    bsp.printStdOut("cannot load formula: " + e);
                    bsp.abort(e);
                } else {
                    System.out.println("cannot load formula: " + e);
                    System.exit(1);
                }
            }
            formula.print(bsp);
        }
        if (bsp != null) {
            bsp.sync();
            if (bsp.getProcessId() == 0) t1 = bsp.getTime();
            Formula.parallelSolve(formula, bsp);
            bsp.sync();
            if (bsp.getProcessId() == 0) {
                t2 = bsp.getTime();
                bsp.printStdOut("consumed time: " + ((t2 - t1) / 1000) + "s");
            }
        } else formula.solve(bsp);
        if (bsp == null || bsp.getProcessId() == 0) {
            if (formula.isSatisfiable()) {
                if (bsp != null) bsp.printStdOut("satisfiable"); else System.out.println("satisfiable");
            } else {
                if (bsp != null) bsp.printStdOut("not satisfiable"); else System.out.println("not satisfiable");
            }
            formula.printVariables(bsp);
        }
    }
private void connect() throws Exception {
        if (client != null) throw new IllegalStateException("Already connected.");
        try {
            _logger.debug("About to connect to ftp server " + server + " port " + port);
            client = new FTPClient();
            client.connect(server, port);
            if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
                throw new Exception("Unable to connect to FTP server " + server + " port " + port + " got error [" + client.getReplyString() + "]");
            }
            _logger.info("Connected to ftp server " + server + " port " + port);
            _logger.debug(client.getReplyString());
            _logger.debug("FTP server is [" + client.getSystemName() + "]");
            if (!client.login(username, password)) {
                throw new Exception("Invalid username / password combination for FTP server " + server + " port " + port);
            }
            _logger.debug("Log in successful.");
            if (passiveMode) {
                client.enterLocalPassiveMode();
                _logger.debug("Passive mode selected.");
            } else {
                client.enterLocalActiveMode();
                _logger.debug("Active mode selected.");
            }
            if (binaryMode) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                _logger.debug("BINARY mode selected.");
            } else {
                client.setFileType(FTP.ASCII_FILE_TYPE);
                _logger.debug("ASCII mode selected.");
            }
            if (client.changeWorkingDirectory(remoteRootDir)) {
                _logger.debug("Changed directory to " + remoteRootDir);
            } else {
                if (client.makeDirectory(remoteRootDir)) {
                    _logger.debug("Created directory " + remoteRootDir);
                    if (client.changeWorkingDirectory(remoteRootDir)) {
                        _logger.debug("Changed directory to " + remoteRootDir);
                    } else {
                        throw new Exception("Cannot change directory to [" + remoteRootDir + "] on FTP server " + server + " port " + port);
                    }
                } else {
                    throw new Exception("Cannot create directory [" + remoteRootDir + "] on FTP server " + server + " port " + port);
                }
            }
        } catch (Exception e) {
            disconnect();
            throw e;
        }
    }
public void saveMapping() throws SQLException {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = (Connection) DriverManager.getConnection(this.jdbcURL);
            connection.setAutoCommit(false);
            String query = "INSERT INTO mapping(product_id, comp_id, count) VALUES(?,?,?)";
            ps = (PreparedStatement) connection.prepareStatement(query);
            ps.setInt(1, this.productId);
            ps.setInt(2, this.componentId);
            ps.setInt(3, 1);
            ps.executeUpdate();
        } catch (Exception ex) {
            connection.rollback();
        } finally {
            try {
                connection.close();
            } catch (Exception ex) {
            }
            try {
                ps.close();
            } catch (Exception ex) {
            }
        }
    }
public FileOutputStream transfer(File from, File to, long mark) throws IOException, InterruptedException {
        if (out != null) {
            close();
        }
        FileChannel fch = new FileInputStream(from).getChannel();
        FileChannel rollch = new FileOutputStream(to).getChannel();
        long size = mark;
        int count = 0;
        try {
            while ((count += rollch.transferFrom(fch, count, size - count)) < size) {
            }
        } finally {
            fch.close();
            rollch.close();
        }
        out = create(to);
        return out;
    }
@Test
    public void parse() throws Exception {
        URL url = new URL("http://www.oki.com");
        HtmlParser parser = new HtmlParser();
        byte[] bytes = FileUtilities.getContents(url.openStream(), Integer.MAX_VALUE).toByteArray();
        OutputStream parsed = parser.parse(new ByteArrayInputStream(bytes), new ByteArrayOutputStream());
        assertTrue(parsed.toString().indexOf("Oki") > -1);
    }
protected String connectPost(String urlString, String parameter) {
        String response = null;
        try {
            URL url = new URL(urlString);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            log.fine(connection.getURL().toString());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(parameter.getBytes());
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            response = in.readLine();
            in.close();
            log.finest(response);
        } catch (Exception e) {
            log.log(Level.SEVERE, urlString, e);
        }
        return response;
    }
public static String makeMD5(String pin) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(pin.getBytes());
            byte[] hash = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                hexString.append(Integer.toHexString(0xFF & hash[i]));
            }
            return hexString.toString();
        } catch (Exception e) {
            return null;
        }
    }
public boolean checkConnection() {
        int tries = 3;
        for (int i = 0; i < tries; i++) {
            try {
                final URL url = new URL(wsURL);
                final URLConnection conn = url.openConnection();
                conn.setReadTimeout(3000);
                conn.getContent();
                return true;
            } catch (IOException ex) {
                Logger.getLogger(ExternalSalesHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(OrdersSync.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return false;
    }
public void process() throws Exception {
        String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath()));
        Map<String, String> parametersMap = new HashMap<String, String>();
        parametersMap.put("searchXML", searchXML);
        String proxyHost = null;
        int proxyPort = -1;
        String serverUserName = null;
        String serverUserPassword = null;
        FileOutputStream fos = null;
        if (getUseProxy()) {
            serverUserName = getServerUserName();
            serverUserPassword = getServerUserPassword();
        }
        if (getUseProxy()) {
            proxyHost = getProxyHost();
            proxyPort = getProxyPort();
        }
        try {
            InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1);
            fos = new FileOutputStream(getSearchResponseRelativeFilePath());
            IOUtils.copyLarge(responseInputStream, fos);
        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }
    }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest)) {
            log.fatal("not a http request");
            return;
        }
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String uri = httpRequest.getRequestURI();
        int pathStartIdx = 0;
        String resourceName = null;
        pathStartIdx = uri.indexOf(path);
        if (pathStartIdx <= -1) {
            log.fatal("the url pattern must match: " + path + " found uri: " + uri);
            return;
        }
        resourceName = uri.substring(pathStartIdx + path.length());
        int suffixIdx = uri.lastIndexOf('.');
        if (suffixIdx <= -1) {
            log.fatal("no file suffix found for resource: " + uri);
            return;
        }
        String suffix = uri.substring(suffixIdx + 1).toLowerCase();
        String mimeType = (String) mimeTypes.get(suffix);
        if (mimeType == null) {
            log.fatal("no mimeType found for resource: " + uri);
            log.fatal("valid mimeTypes are: " + mimeTypes.keySet());
            return;
        }
        String themeName = getThemeName();
        if (themeName == null) {
            themeName = this.themeName;
        }
        if (!themeName.startsWith("/")) {
            themeName = "/" + themeName;
        }
        InputStream is = null;
        is = ResourceFilter.class.getResourceAsStream(themeName + resourceName);
        if (is != null) {
            IOUtils.copy(is, response.getOutputStream());
            response.setContentType(mimeType);
            response.flushBuffer();
            IOUtils.closeQuietly(response.getOutputStream());
            IOUtils.closeQuietly(is);
        } else {
            log.fatal("error loading resource: " + resourceName);
        }
    }
protected InputSource defaultResolveEntity(String publicId, String systemId) throws SAXException {
        if (systemId == null) return null;
        if (systemId.indexOf("file:/") >= 0) {
            try {
                final InputSource is = new InputSource(new URL(systemId).openStream());
                is.setSystemId(systemId);
                if (D.ON && log.finerable()) log.finer("Entity found " + systemId);
                return is;
            } catch (Exception ex) {
                if (D.ON && log.finerable()) log.finer("Unable to open " + systemId);
            }
        }
        final String PREFIX = "/metainfo/xml";
        final org.zkoss.util.resource.Locator loader = Locators.getDefault();
        URL url = null;
        int j = systemId.indexOf("://");
        if (j > 0) {
            final String resId = PREFIX + systemId.substring(j + 2);
            url = loader.getResource(resId);
        }
        if (url == null) {
            j = systemId.lastIndexOf('/');
            final String resId = j >= 0 ? PREFIX + systemId.substring(j) : PREFIX + '/' + systemId;
            url = loader.getResource(resId);
        }
        if (url != null) {
            if (D.ON && log.finerable()) log.finer("Entity resovled to " + url);
            try {
                final InputSource is = new InputSource(url.openStream());
                is.setSystemId(url.toExternalForm());
                return is;
            } catch (IOException ex) {
                throw new SAXException(ex);
            }
        }
        return null;
    }
private void runUpdate(String sql, boolean transactional) {
        log().info("Vacuumd executing statement: " + sql);
        Connection dbConn = null;
        boolean commitRequired = false;
        boolean autoCommitFlag = !transactional;
        try {
            dbConn = getDataSourceFactory().getConnection();
            dbConn.setAutoCommit(autoCommitFlag);
            PreparedStatement stmt = dbConn.prepareStatement(sql);
            int count = stmt.executeUpdate();
            stmt.close();
            if (log().isDebugEnabled()) {
                log().debug("Vacuumd: Ran update " + sql + ": this affected " + count + " rows");
            }
            commitRequired = transactional;
        } catch (SQLException ex) {
            log().error("Vacuumd:  Database error execuating statement  " + sql, ex);
        } finally {
            if (dbConn != null) {
                try {
                    if (commitRequired) {
                        dbConn.commit();
                    } else if (transactional) {
                        dbConn.rollback();
                    }
                } catch (SQLException ex) {
                } finally {
                    if (dbConn != null) {
                        try {
                            dbConn.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
    }
@SuppressWarnings(value = "RetentionPolicy.SOURCE")
    public static byte[] getHashMD5(String chave) {
        byte[] hashMd5 = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(chave.getBytes());
            hashMd5 = md.digest();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            Dialog.erro(ex.getMessage(), null);
        }
        return (hashMd5);
    }
private void backupOriginalFile(String myFile) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S");
        String datePortion = format.format(date);
        try {
            FileInputStream fis = new FileInputStream(myFile);
            FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html");
            FileChannel fcin = fis.getChannel();
            FileChannel fcout = fos.getChannel();
            fcin.transferTo(0, fcin.size(), fcout);
            fcin.close();
            fcout.close();
            fis.close();
            fos.close();
            System.out.println("**** Backup of file made.");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (text == null || text.length() < 1) {
            return null;
        }
        MessageDigest md = MessageDigest.getInstance(TYPE_SHA);
        md.update(text.getBytes(ENCODE), 0, text.length());
        byte[] sha1hash = new byte[40];
        sha1hash = md.digest();
        return convertToHexFormat(sha1hash);
    }
@Override
    protected ActionForward executeAction(ActionMapping mapping, ActionForm form, User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
        long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L);
        String attributeIdentifier = request.getParameter("identifier");
        if (resourceId != 0L && StringUtils.hasText(attributeIdentifier)) {
            try {
                BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, attributeIdentifier, user);
                response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"');
                String contentType = binaryAttribute.getContentType();
                if (contentType != null) {
                    if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) {
                        response.setContentType("application/octet-stream");
                    } else {
                        response.setContentType(contentType);
                    }
                } else {
                    response.setContentType("application/octet-stream");
                }
                IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream());
                return null;
            } catch (DataRetrievalFailureException e) {
                addGlobalError(request, "errors.notFound");
            } catch (Exception e) {
                addGlobalError(request, e);
            }
        }
        return mapping.getInputForward();
    }
public static String encrypt(String plaintext) throws EncryptionException {
        if (plaintext == null) {
            throw new EncryptionException();
        }
        try {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(plaintext.getBytes("UTF-8"));
            return Base64.encodeBytes(md.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new EncryptionException(e);
        } catch (UnsupportedEncodingException e) {
            throw new EncryptionException(e);
        }
    }