semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static void retrieveAttachments(RemoteAttachment[] attachments, String id, String projectName, String key, SimpleDateFormat formatter, java.sql.Connection connect) {
        if (attachments.length != 0) {
            for (RemoteAttachment attachment : attachments) {
                attachmentAuthor = attachment.getAuthor();
                if (attachment.getCreated() != null) {
                    attachmentCreated = formatter.format(attachment.getCreated().getTime());
                }
                attachmentFileName = attachment.getFilename();
                attachmentFileSize = attachment.getFilesize();
                attachmentId = attachment.getId();
                attachmentMimeType = attachment.getMimetype();
                if (attachmentMimeType.startsWith("text")) {
                    URL attachmentUrl;
                    try {
                        attachmentUrl = new URL("https://issues.apache.org/jira/secure/attachment/" + attachmentId + "/" + attachmentFileName);
                        urlConnection = (HttpURLConnection) attachmentUrl.openConnection();
                        urlConnection.connect();
                        serverCode = urlConnection.getResponseCode();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (serverCode == 200) {
                        actual = new File("../attachments/" + projectName + "/" + key);
                        if (!actual.exists()) {
                            actual.mkdirs();
                        }
                        attachmentPath = "../attachments/" + projectName + "/" + key + "/" + attachmentFileName;
                        BufferedInputStream bis;
                        try {
                            bis = new BufferedInputStream(urlConnection.getInputStream());
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(attachmentPath));
                            byte[] b = new byte[1024];
                            int len = -1;
                            while ((len = bis.read(b)) != -1) {
                                if (len == 1024) {
                                    bos.write(b);
                                } else {
                                    bos.write(b, 0, len);
                                }
                            }
                            bos.close();
                            bis.close();
                            insertAttachment(connect, id);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
@Override
    public String readFixString(final int len) {
        if (len < 1) {
            return StringUtils.EMPTY;
        }
        final StringWriter sw = new StringWriter();
        try {
            IOUtils.copy(createLimitedInputStream(len), sw, null);
        } catch (IOException e) {
            throw createRuntimeException(e);
        }
        return sw.toString();
    }
public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:6557");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            int responseCode = conn.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String decodedString;
            while ((decodedString = in.readLine()) != null) {
                System.out.println(decodedString);
            }
            in.close();
            conn.disconnect();
        } catch (Exception ex) {
            Logger.getLogger(TestSSLConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
public String storeImage(InputStream inStream, String fileName, boolean resize) throws Exception {
        Calendar rightNow = Calendar.getInstance();
        String dayNamedFolderName = "" + rightNow.get(Calendar.YEAR) + StringUtil.getPaddedIntWithZeros(2, rightNow.get(Calendar.MONTH) + 1) + StringUtil.getPaddedIntWithZeros(2, rightNow.get(Calendar.DATE));
        String uploadDirRoot = props.getProperty("uploaded.files.root");
        File file = new File(uploadDirRoot + System.getProperty("file.separator") + dayNamedFolderName);
        if (!file.exists()) file.mkdirs();
        String extension = FilenameUtils.getExtension(fileName);
        String outFileName;
        if (Boolean.parseBoolean(props.getPropertiesInstance().getProperty(IFConsts.USEORIGINALFILENAME, "true"))) {
            outFileName = StringUtil.removeSpecChars(StringUtil.unaccent(FilenameUtils.getBaseName(fileName)));
        } else {
            outFileName = StringUtil.hash(fileName + Long.toString(System.currentTimeMillis()));
        }
        if (Boolean.parseBoolean(props.getPropertiesInstance().getProperty(IFConsts.USEEXTENSION, "true"))) {
            outFileName = outFileName + DOT + extension;
        }
        String outPathAndName = uploadDirRoot + System.getProperty("file.separator") + dayNamedFolderName + System.getProperty("file.separator") + props.getProperty("uploaded.files.prefix") + outFileName;
        File uploadedFile = new File(outPathAndName);
        _logger.info("uploadedFile.getAbsolutePath() = {}", uploadedFile.getAbsolutePath());
        uploadedFile.createNewFile();
        OutputStream outStream = new FileOutputStream(outPathAndName);
        IOUtils.copyLarge(inStream, outStream);
        IOUtils.closeQuietly(inStream);
        outStream.close();
        if (resize) {
            writeResizedImage(outPathAndName, extension, "imgSize_xs");
            writeResizedImage(outPathAndName, extension, "imgSize_s");
            writeResizedImage(outPathAndName, extension, "imgSize_m");
            writeResizedImage(outPathAndName, extension, "imgSize_l");
            writeResizedImage(outPathAndName, extension, "imgSize_xl");
        }
        String retVal = dayNamedFolderName + "/" + props.getProperty("uploaded.files.prefix") + outFileName;
        return retVal;
    }
protected void copyDependents() {
        for (File source : dependentFiles.keySet()) {
            try {
                if (!dependentFiles.get(source).exists()) {
                    if (dependentFiles.get(source).isDirectory()) dependentFiles.get(source).mkdirs(); else dependentFiles.get(source).getParentFile().mkdirs();
                }
                IOUtils.copyEverything(source, dependentFiles.get(source));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
public static boolean copy(File from, File to) {
        if (from.isDirectory()) {
            for (String name : Arrays.asList(from.list())) {
                if (!copy(from, to, name)) {
                    LogUtils.info("Failed to copy " + name + " from " + from + " to " + to, null);
                    return false;
                }
            }
        } else {
            try {
                FileInputStream is = new FileInputStream(from);
                FileChannel ifc = is.getChannel();
                FileOutputStream os = makeFile(to);
                if (USE_NIO) {
                    FileChannel ofc = os.getChannel();
                    ofc.transferFrom(ifc, 0, from.length());
                } else {
                    pipe(is, os, false);
                }
                is.close();
                os.close();
            } catch (IOException ex) {
                LogUtils.warning("Failed to copy " + from + " to " + to, ex);
                return false;
            }
        }
        long time = from.lastModified();
        setLastModified(to, time);
        long newtime = to.lastModified();
        if (newtime != time) {
            LogUtils.info("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime), null);
            to.setLastModified(time);
            long morenewtime = to.lastModified();
            return false;
        }
        return time == newtime;
    }
private static void loadUnits(URL url) throws Exception {
        try {
            SYSTEM = new UnitSystem();
            XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            reader.setFeature("http://xml.org/sax/features/namespaces", true);
            reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
            reader.setContentHandler(SYSTEM);
            reader.parse(new InputSource(url.openStream()));
        } catch (Throwable ex) {
            throw new Exception(url.toString() + ": " + ex.getMessage(), ex);
        }
    }
public static void main(String[] args) throws MalformedURLException, IOException {
        URL url = new URL("https://imo.im/");
        URLConnection con = url.openConnection();
        InputStream is = con.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while (((len = is.read(buffer)) >= 0)) {
            out.write(buffer, 0, len);
        }
        out.flush();
        System.out.println(out.toString());
    }
private void copy(File source, File destination) throws PackageException {
        try {
            FileInputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(destination);
            byte[] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) > 0) out.write(buff, 0, len);
            in.close();
            out.close();
        } catch (IOException e) {
            throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString());
        }
    }
public void processAction(DatabaseAdapter db_, DataDefinitionActionDataListType parameters) throws Exception {
        PreparedStatement ps = null;
        try {
            if (log.isDebugEnabled()) log.debug("db connect - " + db_.getClass().getName());
            String seqName = DefinitionService.getString(parameters, "sequence_name", null);
            if (seqName == null) {
                String errorString = "Name of sequnce not found";
                log.error(errorString);
                throw new Exception(errorString);
            }
            String tableName = DefinitionService.getString(parameters, "name_table", null);
            if (tableName == null) {
                String errorString = "Name of table not found";
                log.error(errorString);
                throw new Exception(errorString);
            }
            String columnName = DefinitionService.getString(parameters, "name_pk_field", null);
            if (columnName == null) {
                String errorString = "Name of column not found";
                log.error(errorString);
                throw new Exception(errorString);
            }
            CustomSequenceType seqSite = new CustomSequenceType();
            seqSite.setSequenceName(seqName);
            seqSite.setTableName(tableName);
            seqSite.setColumnName(columnName);
            long seqValue = db_.getSequenceNextValue(seqSite);
            String valueColumnName = DefinitionService.getString(parameters, "name_value_field", null);
            if (columnName == null) {
                String errorString = "Name of valueColumnName not found";
                log.error(errorString);
                throw new Exception(errorString);
            }
            String insertValue = DefinitionService.getString(parameters, "insert_value", null);
            if (columnName == null) {
                String errorString = "Name of insertValue not found";
                log.error(errorString);
                throw new Exception(errorString);
            }
            String sql = "insert into " + tableName + " " + "(" + columnName + "," + valueColumnName + ")" + "values" + "(?,?)";
            if (log.isDebugEnabled()) {
                log.debug(sql);
                log.debug("pk " + seqValue);
                log.debug("value " + insertValue);
            }
            ps = db_.prepareStatement(sql);
            ps.setLong(1, seqValue);
            ps.setString(2, insertValue);
            ps.executeUpdate();
            db_.commit();
        } catch (Exception e) {
            try {
                db_.rollback();
            } catch (Exception e1) {
            }
            log.error("Error insert value", e);
            throw e;
        } finally {
            org.riverock.generic.db.DatabaseManager.close(ps);
            ps = null;
        }
    }
public Object downloadObject() throws CommunicationException, FileNotFoundException, InvalidClassException, ClassNotFoundException {
        Object returnObject = null;
        String requestStr = new String();
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            for (java.util.Iterator i = parameters.entrySet().iterator(); i.hasNext(); ) {
                java.util.Map.Entry e = (java.util.Map.Entry) i.next();
                requestStr += URLEncoder.encode((String) e.getKey(), "UTF-8") + "=" + URLEncoder.encode((String) e.getValue(), "UTF-8") + "&";
            }
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.println(requestStr);
            out.close();
            System.out.println("HTTPCommunication.downloadObject() - Response:" + connection.getResponseCode() + " : " + connection.getResponseMessage());
            if (connection.getResponseCode() == connection.HTTP_OK) {
                GZIPInputStream gzipIn = new GZIPInputStream(connection.getInputStream());
                ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
                returnObject = objectIn.readObject();
                objectIn.close();
            } else if (connection.getResponseCode() == connection.HTTP_NOT_FOUND) {
                throw new FileNotFoundException(connection.getResponseMessage());
            } else {
                throw new CommunicationException(connection.getResponseMessage(), connection.getResponseCode());
            }
        } catch (java.net.ConnectException ce) {
            throw new CommunicationException("Cannot connect to " + urlString + ".\n" + "Server is not responding!", ce);
        } catch (java.net.MalformedURLException mfue) {
            throw new CommunicationException("Cannot connect to " + urlString + ".\n" + "Bad url string!", mfue);
        } catch (ClassNotFoundException cnfe) {
            throw cnfe;
        } catch (InvalidClassException ice) {
            throw ice;
        } catch (java.io.FileNotFoundException fnfe) {
            throw fnfe;
        } catch (java.io.InterruptedIOException iioe) {
            this.parentWorkflow.getMenuButtonEventHandler().stopAutomaticRefresh();
            throw new CommunicationException("Communication is timeouted", iioe);
        } catch (java.io.IOException ioe) {
            throw new CommunicationException("Error while trying to communicate the server: \n" + ioe.getMessage(), ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return returnObject;
    }
public static void writeFileToFile(File fin, File fout, boolean append) throws IOException {
        FileChannel inChannel = new FileInputStream(fin).getChannel();
        FileChannel outChannel = new FileOutputStream(fout, append).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null) try {
                inChannel.close();
            } catch (IOException ex) {
            }
            if (outChannel != null) try {
                outChannel.close();
            } catch (IOException ex) {
            }
        }
    }
public static int ToGSML(GeoSciML_Mapping mapping, String strTemplate, String strRequest, PrintWriter sortie, String requestedSRS) throws Exception {
        String level = "info.";
        if (ConnectorServlet.debug) level = "debug.";
        Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.Gml2Gsml");
        log.debug(strRequest);
        String tagFeature = "FIELDS";
        URL url2Request = new URL(strRequest);
        URLConnection conn = url2Request.openConnection();
        Date dDebut = new Date();
        BufferedReader buffin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String strLine = null;
        int nbFeatures = 0;
        Template template = VelocityCreator.createTemplate("/fr/brgm/exows/gml2gsml/templates/" + strTemplate);
        while ((strLine = buffin.readLine()) != null) {
            if (strLine.indexOf(tagFeature) != -1) {
                nbFeatures++;
                GSMLFeatureGeneric feature = createGSMLFeatureFromGMLFeatureString(mapping, strLine);
                VelocityContext context = new VelocityContext();
                context.put("feature", feature);
                String outputFeatureMember = VelocityCreator.createXMLbyContext(context, template);
                sortie.println(outputFeatureMember);
            }
        }
        buffin.close();
        Date dFin = new Date();
        String output = "GEOSCIML : " + nbFeatures + " features handled - time : " + (dFin.getTime() - dDebut.getTime()) / 1000 + " [" + dDebut + " // " + dFin + "]";
        log.trace(output);
        return nbFeatures;
    }
public static void ToHTML(GeoSciML_Mapping mapping, String strTemplate, String strRequest, String lang, PrintWriter sortie) throws Exception {
        String level = "info.";
        if (ConnectorServlet.debug) level = "debug.";
        Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.Gml2Gsml");
        String tagFeature = "FIELDS";
        URL url2Request = new URL(strRequest);
        URLConnection conn = url2Request.openConnection();
        Date dDebut = new Date();
        BufferedReader buffin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String strLine = null;
        int nbFeatures = 0;
        Template template = VelocityCreator.createTemplate("/fr/brgm/exows/gml2gsml/templates/" + strTemplate);
        while ((strLine = buffin.readLine()) != null) {
            if (strLine.indexOf(tagFeature) != -1) {
                nbFeatures++;
                GSMLFeatureGeneric feature = createGSMLFeatureFromGMLFeatureString(mapping, strLine);
                VelocityContext context = new VelocityContext();
                context.put("feature", feature);
                context.put("lang", lang);
                context.put("vocabularies", new Vocabularies());
                String outputFeatureMember = VelocityCreator.createXMLbyContext(context, template);
                sortie.println(outputFeatureMember);
            }
        }
        buffin.close();
        Date dFin = new Date();
        String output = "GEOSCIML : " + nbFeatures + " features handled - time : " + (dFin.getTime() - dDebut.getTime()) / 1000 + " [" + dDebut + " // " + dFin + "]";
        log.trace(output);
    }
public int executeUpdate(String query, QueryParameter params) throws DAOException {
        PreparedStatement ps = null;
        Query queryObj = getModel().getQuery(query);
        if (conditionalQueries != null && conditionalQueries.containsKey(query)) {
            queryObj = (Query) conditionalQueries.get(query);
        }
        String sql = queryObj.getStatement(params.getVariables());
        logger.debug(sql);
        try {
            if (con == null || con.isClosed()) {
                con = DataSource.getInstance().getConnection(getModel().getDataSource());
            }
            ps = con.prepareStatement(sql);
            setParameters(ps, queryObj, params);
            return ps.executeUpdate();
        } catch (SQLException e) {
            logger.error("DataBase Error :", e);
            if (transactionMode) rollback();
            transactionMode = false;
            throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage());
        } catch (Exception ex) {
            logger.error("Error :", ex);
            if (transactionMode) rollback();
            transactionMode = false;
            throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", ex.getMessage());
        } finally {
            try {
                if (!transactionMode) con.commit();
                if (ps != null) ps.close();
                if (!transactionMode && con != null) con.close();
            } catch (SQLException e) {
                throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage());
            }
        }
    }
private <T> T conectar(String className, String methodName, Class<?>[] parameterTypes, Object[] args, T t) throws Exception {
        try {
            HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
            conexao.setRequestMethod("POST");
            conexao.setDoOutput(true);
            conexao.setRequestProperty("className", className);
            conexao.setRequestProperty("methodName", methodName);
            ServiceObject serviceObject = new ServiceObject();
            serviceObject.write(new Object[] { parameterTypes, args }, conexao.getOutputStream());
            if (conexao.getResponseCode() != 200) {
                throw new ServiceException("Falha grave no servidor com url: " + url);
            }
            String typeResponse = conexao.getHeaderField("Service-Type-Response");
            Object object = serviceObject.read(conexao.getInputStream());
            return returns.get(typeResponse).tratarReturn(object, t);
        } catch (IOException e) {
            throw new ServiceException("Falha ao conectar no servidor com url: " + url, e);
        } catch (ClassNotFoundException e) {
            throw new ServiceException("Falha objeto espera nao e compatavel. Resposta do servidor com url: " + url, e);
        }
    }
public static String hexMD5(String value) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(value.getBytes("utf-8"));
            byte[] digest = messageDigest.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
    }
public static String hexSHA1(String value) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            md.update(value.getBytes("utf-8"));
            byte[] digest = md.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
    }