semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
    public void render(IContentNode contentNode, Request req, Response resp, Application app, ServerInfo serverInfo) {
        Node fileNode = contentNode.getNode();
        try {
            Node res = fileNode.getNode("jcr:content");
            if (checkLastModified(res, req.getServletRequset(), resp.getServletResponse())) {
                return;
            }
            Property data = res.getProperty("jcr:data");
            InputStream is = data.getBinary().getStream();
            int contentLength = (int) data.getBinary().getSize();
            String mime;
            if (res.hasProperty("jcr:mimeType")) {
                mime = res.getProperty("jcr:mimeType").getString();
            } else {
                mime = serverInfo.getSerlvetContext().getMimeType(fileNode.getName());
            }
            if (mime != null && mime.startsWith("image")) {
                int w = req.getInt("w", 0);
                int h = req.getInt("h", 0);
                String fmt = req.get("fmt");
                if (w != 0 || h != 0 || fmt != null) {
                    Resource imgRes = ImageResource.create(is, mime.substring(6), w, h, req.getInt("cut", 0), fmt);
                    imgRes.process(serverInfo);
                    return;
                }
            }
            resp.getServletResponse().setContentType(mime);
            resp.getServletResponse().setContentLength(contentLength);
            OutputStream os = resp.getServletResponse().getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
            os.close();
        } catch (PathNotFoundException e) {
            e.printStackTrace();
        } catch (RepositoryException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
@Override
    public void configure() {
        initResouce();
        if (this.locale == null) {
            this.locale = Locale.getDefault();
        }
        InputStream[] ins = new InputStream[getResourceList().size()];
        try {
            int i = 0;
            for (URL url : getResourceList()) {
                ins[i++] = url.openStream();
            }
            this.resources = new ValidatorResources(ins);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (SAXException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
private HashSet<String> href(String urlstr) throws IOException {
        HashSet<String> hrefs = new HashSet<String>();
        URL url = new URL(urlstr);
        URLConnection con = url.openConnection();
        con.setRequestProperty("Cookie", "_session_id=" + _session_id);
        InputStreamReader r = new InputStreamReader(con.getInputStream());
        StringWriter b = new StringWriter();
        IOUtils.copyTo(r, b);
        r.close();
        try {
            Thread.sleep(WAIT_SECONDS * 1000);
        } catch (Exception err) {
        }
        String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]");
        for (String s1 : tokens) {
            if (!(s1.startsWith("a") && s1.contains("href"))) continue;
            String tokens2[] = s1.split("[\\\"\\\']");
            for (String s2 : tokens2) {
                if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue;
                hrefs.add(s2);
            }
        }
        return hrefs;
    }
private void createGraphicalViewer(Composite parent) {
        viewer = new ScrollingGraphicalViewer();
        viewer.createControl(parent);
        viewer.getControl().setBackground(parent.getBackground());
        viewer.setRootEditPart(new ScalableFreeformRootEditPart());
        viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer));
        registerEditPartViewer(viewer);
        configureEditPartViewer(viewer);
        viewer.setEditPartFactory(new GraphicalEditPartsFactory(getSite().getShell()));
        viewer.setContents(getContractEditor().getContract());
        ContextMenuProvider provider = new ContractContextMenuProvider(getGraphicalViewer(), getContractEditor().getActionRegistry());
        getGraphicalViewer().setContextMenu(provider);
        getSite().registerContextMenu(provider, getGraphicalViewer());
    }
public static void downloadFromUrl(String url1, String fileName) {
        try {
            URL url = new URL(url1);
            File file = new File(fileName);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
        } catch (IOException e) {
        }
    }
public static NotaFiscal insert(NotaFiscal objNF) {
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        int result;
        if (c == null) {
            return null;
        }
        if (objNF == null) {
            return null;
        }
        try {
            c.setAutoCommit(false);
            String sql = "";
            int idNotaFiscal;
            idNotaFiscal = NotaFiscalDAO.getLastCodigo();
            if (idNotaFiscal < 1) {
                return null;
            }
            sql = "INSERT INTO nota_fiscal " + "(id_nota_fiscal, id_fornecedor, total, data_emissao, data_cadastro, numero) " + "VALUES(?, ?, TRUNCATE(?,2), STR_TO_DATE(?,'%d/%m/%Y'), now(), ?) ";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idNotaFiscal);
            pst.setLong(2, objNF.getFornecedor().getCodigo());
            pst.setString(3, new DecimalFormat("#0.00").format(objNF.getValor()));
            pst.setString(4, objNF.getDataEmissaoFormatada());
            pst.setString(5, objNF.getNumero());
            result = pst.executeUpdate();
            pst = null;
            if (result > 0) {
                Iterator<ItemNotaFiscal> itINF = (objNF.getItemNotaFiscal()).iterator();
                while ((itINF != null) && (itINF.hasNext())) {
                    ItemNotaFiscal objINF = (ItemNotaFiscal) itINF.next();
                    sql = "";
                    sql = "INSERT INTO item_nota_fiscal " + "(id_nota_fiscal, id_produto, quantidade, subtotal) " + "VALUES(?, ?, ?, TRUNCATE(?,2))";
                    pst = c.prepareStatement(sql);
                    pst.setInt(1, idNotaFiscal);
                    pst.setInt(2, objINF.getProduto().getCodigo());
                    pst.setInt(3, objINF.getQuantidade());
                    pst.setString(4, new DecimalFormat("#0.00").format(objINF.getSubtotal()));
                    result = pst.executeUpdate();
                }
            }
            c.commit();
            objNF.setCodigo(idNotaFiscal);
        } catch (final Exception e) {
            try {
                c.rollback();
            } catch (final Exception e1) {
                System.out.println("[NotaFiscalDAO.insert.rollback] Erro ao inserir -> " + e1.getMessage());
            }
            System.out.println("[NotaFiscalDAO.insert] Erro ao inserir -> " + e.getMessage());
            objNF = null;
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        return objNF;
    }
public void init(String file) {
        URL url = SoundFactory.class.getResource(file);
        try {
            JAXBContext context = JAXBContext.newInstance("elf.xml.sounds");
            Unmarshaller unmarshaller = context.createUnmarshaller();
            SoundsBaseType root = null;
            Object tmpobj = unmarshaller.unmarshal(url.openConnection().getInputStream());
            if (tmpobj instanceof JAXBElement<?>) {
                if (((JAXBElement<?>) tmpobj).getValue() instanceof SoundsBaseType) {
                    root = (SoundsBaseType) ((JAXBElement<?>) tmpobj).getValue();
                    addMusic("MENUSONG", root.getMenumusic().getMusicpath());
                    List<SoundsMusicType> musiclist = root.getMusic();
                    Iterator<SoundsMusicType> it = musiclist.iterator();
                    while (it.hasNext()) {
                        SoundsMusicType smt = it.next();
                        addMusic(smt.getMusicname(), smt.getMusicpath());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
private Image2D resolvePNG(URI uri) {
        Image2D image2D = null;
        if (uri.getScheme() != null) {
            try {
                URL url = new URL(uri.toString());
                InputStream is = url.openStream();
                BufferedImage image = PNGDecoder.decode(is);
                int imageType = Image2D.RGB;
                if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA;
                image2D = new Image2D(imageType, image);
            } catch (IOException ex) {
            }
        } else {
            String path = uri.getPath();
            File file = new File(path);
            if (file.getAbsoluteFile().exists()) {
                try {
                    FileInputStream is = new FileInputStream(file);
                    BufferedImage image = PNGDecoder.decode(is);
                    int imageType = Image2D.RGB;
                    if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA;
                    image2D = new Image2D(imageType, image);
                } catch (FileNotFoundException ex) {
                } catch (IOException ex) {
                }
            }
        }
        return image2D;
    }
public void modifyApplicationMessage(String locale, String messageName, String messageValue) {
        Properties properties = new Properties();
        try {
            String i18nPath = ServerUtil.removelastResourceURL(ConfigurationServiceImpl.class.getResource("/es/ua/tranube/prototype/main/client/TranubeConstants_en.properties").getPath()).toString();
            File englishFile = new File(i18nPath + "TranubeConstants_en.properties");
            if (!englishFile.exists()) throw new Exception("English file not found");
            String propertiesFilePath = i18nPath + "TranubeConstants_" + locale + ".properties";
            File file = new File(propertiesFilePath);
            if (!file.exists()) {
                FileReader in = new FileReader(englishFile);
                FileWriter out = new FileWriter(file);
                int c;
                while ((c = in.read()) != -1) out.write(c);
                in.close();
                out.close();
            }
            InputStream is = ConfigurationServiceImpl.class.getResourceAsStream("/es/ua/tranube/prototype/main/client/TranubeConstants_" + locale + ".properties");
            BufferedReader breader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuilder strBuilder = new StringBuilder();
            boolean found = false;
            while ((line = breader.readLine()) != null) {
                if (line.startsWith("#")) strBuilder.append(line).append("\n"); else {
                    String[] pieces = line.split("=");
                    if (pieces.length == 2) {
                        if (pieces[0].trim().equals(messageName)) {
                            strBuilder.append(pieces[0].trim() + " = " + messageValue + "\n");
                            found = true;
                        } else strBuilder.append(line).append("\n");
                    } else strBuilder.append(line).append("\n");
                }
            }
            if (!found) strBuilder.append(messageName).append(" = ").append(messageValue).append("\n");
            breader.close();
            is.close();
            FileWriter writer = new FileWriter(file);
            writer.write(strBuilder.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public String getPloidy(String source) {
        StringBuilder ploidyHtml = new StringBuilder();
        String hyperdiploidyUrl = customParameters.getHyperdiploidyUrl();
        String urlString = hyperdiploidyUrl + "?source=" + source;
        URL url = null;
        try {
            url = new URL(urlString);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                ploidyHtml.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ploidyHtml.toString();
    }
public static String hashPassword(String password) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(password.getBytes());
            byte result[] = md5.digest("InTeRlOgY".getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String s = Integer.toHexString(result[i]);
                int length = s.length();
                if (length >= 2) {
                    sb.append(s.substring(length - 2, length));
                } else {
                    sb.append("0");
                    sb.append(s);
                }
            }
            return "{md5}" + sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return password;
        }
    }
public void patchFile(final File classFile) {
        if (!classFile.exists()) {
            myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind()));
            return;
        }
        FileInputStream fis;
        try {
            byte[] patchedData;
            fis = new FileInputStream(classFile);
            try {
                patchedData = patchClass(fis);
                if (patchedData == null) {
                    return;
                }
            } finally {
                fis.close();
            }
            FileOutputStream fos = new FileOutputStream(classFile);
            try {
                fos.write(patchedData);
            } finally {
                fos.close();
            }
        } catch (IOException e) {
            myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString()));
        }
    }
public static String encryptPassword(String password) {
        if (password == null) return null;
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            log.error("Algorithm not found", e);
            return null;
        }
        digest.reset();
        digest.update(password.getBytes());
        return hexValue(digest.digest());
    }
private synchronized void connect() throws IOException {
        long now = System.currentTimeMillis();
        if (lastConnect == 0 || lastConnect + 500 < now) {
            Log.logRB(Resource.CONNECTINGTO, new Object[] { getName() });
            String auth = setProxy();
            conn = url.openConnection();
            if (auth != null) conn.setRequestProperty("Proxy-Authorization", auth);
            conn.connect();
            lastModified = conn.getLastModified();
            lastConnect = System.currentTimeMillis();
        }
    }
public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(inputLocation);
            outputStream = new FileOutputStream(outputLocation);
            byte buffer[] = new byte[1024];
            while (inputStream.available() > 0) {
                int read = inputStream.read(buffer);
                outputStream.write(buffer, 0, read);
            }
            inputLocation.delete();
        } finally {
            IOUtil.closeAndIgnoreErrors(inputStream);
            IOUtil.closeAndIgnoreErrors(outputStream);
        }
    }
public void send(String payload, TransportReceiver receiver) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost();
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Cookie", cookie);
        post.setURI(uri);
        Throwable ex;
        try {
            post.setEntity(new StringEntity(payload, "UTF-8"));
            HttpResponse response = client.execute(post);
            if (200 == response.getStatusLine().getStatusCode()) {
                String contents = readStreamAsString(response.getEntity().getContent());
                receiver.onTransportSuccess(contents);
            } else {
                receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
            }
            return;
        } catch (UnsupportedEncodingException e) {
            ex = e;
        } catch (ClientProtocolException e) {
            ex = e;
        } catch (IOException e) {
            ex = e;
        }
        receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
    }
private void doIt() throws Throwable {
        int numCachedTiles = 0;
        try {
            List<MapTile> backTiles = new ArrayList<MapTile>();
            final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east));
            final String backMapGuid = "gst";
            final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid);
            dstDir.mkdir();
            for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) {
                final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z);
                final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z);
                for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) {
                    NASAMapTile tile = new NASAMapTile((int) x, (int) y, z);
                    XFile file = new XFile(dstDir, tile.toKeyString());
                    if (file.exists() && file.isFile()) continue;
                    backTiles.add(tile);
                }
            }
            logger.info(backTiles.size() + " tiles to cache");
            for (MapTile tile : backTiles) {
                InputStream in = null;
                OutputStream out = null;
                final URL url = new URL(tile.getPath());
                try {
                    int i = 4;
                    while (--i > 0) {
                        final XFile outFile = new XFile(dstDir, tile.toKeyString());
                        final URLConnection conn = url.openConnection();
                        if (conn == null || !conn.getContentType().startsWith("image")) {
                            logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'");
                            Thread.sleep(1000L * (long) Math.pow(2, 8 - i));
                            continue;
                        }
                        in = conn.getInputStream();
                        if (in != null) {
                            out = new XFileOutputStream(outFile);
                            IOUtils.copy(in, out);
                            break;
                        } else throw new IllegalStateException("opened stream is null");
                    }
                } finally {
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                    if (in != null) in.close();
                }
                if (++numCachedTiles % 10 == 0) {
                    logger.info(numCachedTiles + " tiles cached");
                    Thread.sleep(sleep);
                }
            }
        } catch (Throwable e) {
            logger.error("map tile caching has failed: ", e);
            throw e;
        }
    }
public static int doPost(String urlString, String username, String password, Map<String, String> parameters) throws IOException {
        PrintWriter out = null;
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            if (username != null && password != null) {
                String encoding = base64Encode(username + ':' + password);
                connection.setRequestProperty("Authorization", "Basic " + encoding);
            }
            connection.setDoOutput(true);
            out = new PrintWriter(connection.getOutputStream());
            boolean first = true;
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    out.print('&');
                }
                out.print(entry.getKey());
                out.print('=');
                out.print(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            out.close();
            connection.connect();
            if (!(connection instanceof HttpURLConnection)) {
                throw new IOException();
            }
            return ((HttpURLConnection) connection).getResponseCode();
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
public InputStream getFileStream(String filePath) {
        if (this.inJar) {
            try {
                URL url = getClassResourceUrl(this.getClass(), filePath);
                if (url != null) {
                    return url.openStream();
                }
            } catch (IOException ioe) {
                Debug.signal(Debug.ERROR, this, ioe);
            }
        } else {
            try {
                return new FileInputStream(filePath);
            } catch (FileNotFoundException fe) {
                Debug.signal(Debug.ERROR, this, fe);
            }
        }
        return null;
    }
public static String MD5(String text) {
        byte[] md5hash = new byte[32];
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return convertToHex(md5hash);
    }
public static String MD5ToString(String md5) {
        String hashword = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(md5.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            hashword = hash.toString(16);
        } catch (NoSuchAlgorithmException nsae) {
        }
        return hashword;
    }
public static String MD5(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }